src/completions.rs
483 lines · 13230 bytes
34 symbols in this file
Completionshook_allBufferShortNamesCompletioncreatecallbackServersCompletioncreatecallbackUsersCompletioncreatecallbackRoomMembersCompletioncreatecallbackNicksCompletioncreatecallbacknick_completion_candidatesMediaCompletioncreatecallbackextract_mxc_urisbuffer_completion_candidatestestsextracts_valid_mxc_urisignores_invalid_mxc_urisextracts_uris_followed_by_sentence_punctuationextracts_uris_wrapped_in_delimitersextracts_multiple_uris_from_a_single_linedrops_uris_without_a_media_idcompletes_only_resolvable_matrix_short_namesthread_buffers_contribute_sorted_room_member_nicksthread_buffers_without_a_room_contribute_nothingnon_thread_buffers_keep_the_builtin_nicklist_completion
1use std::{borrow::Cow, collections::BTreeSet};
2
3use matrix_sdk::ruma::MxcUri;
4
5use weechat::{
6 buffer::Buffer,
7 hooks::{
8 Completion, CompletionCallback, CompletionHook, CompletionPosition,
9 },
10 Weechat,
11};
12
13use crate::commands::is_buffer_target;
14use crate::commands::whois::{
15 matrix_member_completion_candidates, matrix_member_profiles,
16};
17use crate::Servers;
18
19#[allow(dead_code)]
20pub struct Completions {
21 buffer_short_names: CompletionHook,
22 servers: CompletionHook,
23 users: CompletionHook,
24 room_members: CompletionHook,
25 media: CompletionHook,
26 nicks: CompletionHook,
27}
28
29impl Completions {
30 pub fn hook_all(servers: Servers) -> Result<Self, ()> {
31 Ok(Self {
32 buffer_short_names: BufferShortNamesCompletion::create(
33 servers.clone(),
34 )?,
35 servers: ServersCompletion::create(servers.clone())?,
36 users: UsersCompletion::create(servers.clone())?,
37 room_members: RoomMembersCompletion::create()?,
38 media: MediaCompletion::create(servers.clone())?,
39 nicks: NicksCompletion::create(servers)?,
40 })
41 }
42}
43
44struct BufferShortNamesCompletion {
45 servers: Servers,
46}
47
48impl BufferShortNamesCompletion {
49 fn create(servers: Servers) -> Result<CompletionHook, ()> {
50 let comp = BufferShortNamesCompletion { servers };
51
52 // WeeChat's /buffer completion uses this item after adding its regular
53 // buffer names. Adding Matrix short names here keeps those core
54 // candidates intact while making the command-run hook reachable.
55 CompletionHook::new(
56 "buffers_names",
57 "Completion for Matrix buffer short names",
58 comp,
59 )
60 }
61}
62
63impl CompletionCallback for BufferShortNamesCompletion {
64 fn callback(
65 &mut self,
66 _: &Weechat,
67 _: &Buffer,
68 _: Cow<str>,
69 completion: &Completion,
70 ) -> Result<(), ()> {
71 for short_name in buffer_completion_candidates(
72 self.servers
73 .borrow()
74 .values()
75 .flat_map(|server| server.rooms())
76 .flat_map(|room| room.buffer_short_names()),
77 ) {
78 completion.add_with_options(
79 &short_name,
80 false,
81 CompletionPosition::Sorted,
82 );
83 }
84
85 Ok(())
86 }
87}
88
89struct ServersCompletion {
90 servers: Servers,
91}
92
93impl ServersCompletion {
94 fn create(servers: Servers) -> Result<CompletionHook, ()> {
95 let comp = ServersCompletion { servers };
96
97 CompletionHook::new(
98 "matrix_servers",
99 "Completion for the list of added Matrix servers",
100 comp,
101 )
102 }
103}
104
105impl CompletionCallback for ServersCompletion {
106 fn callback(
107 &mut self,
108 _weechat: &Weechat,
109 _buffer: &Buffer,
110 _completion_name: Cow<str>,
111 completion: &Completion,
112 ) -> Result<(), ()> {
113 for server_name in self.servers.borrow().keys() {
114 completion.add_with_options(
115 server_name,
116 false,
117 CompletionPosition::Sorted,
118 );
119 }
120 Ok(())
121 }
122}
123
124struct UsersCompletion {
125 servers: Servers,
126}
127
128impl UsersCompletion {
129 fn create(servers: Servers) -> Result<CompletionHook, ()> {
130 let comp = UsersCompletion { servers };
131
132 CompletionHook::new(
133 "matrix-users",
134 "Completion for the list of Matrix users",
135 comp,
136 )
137 }
138}
139
140impl CompletionCallback for UsersCompletion {
141 fn callback(
142 &mut self,
143 _: &Weechat,
144 buffer: &Buffer,
145 _: Cow<str>,
146 completion: &Completion,
147 ) -> Result<(), ()> {
148 if let Some(server) = self.servers.find_server(buffer) {
149 if let Some(connection) = server.connection() {
150 let tracked_users = self
151 .servers
152 .runtime()
153 .block_on(connection.client().encryption().tracked_users())
154 .unwrap_or_else(|e| {
155 tracing::warn!("Error getting tracked users: {e}");
156 Default::default()
157 });
158
159 for user in tracked_users.into_iter() {
160 completion.add_with_options(
161 user.as_str(),
162 true,
163 CompletionPosition::Sorted,
164 )
165 }
166 }
167 }
168
169 Ok(())
170 }
171}
172
173struct RoomMembersCompletion;
174
175impl RoomMembersCompletion {
176 fn create() -> Result<CompletionHook, ()> {
177 CompletionHook::new(
178 "matrix-room-members",
179 "Completion for Matrix room members in the current buffer",
180 RoomMembersCompletion,
181 )
182 }
183}
184
185impl CompletionCallback for RoomMembersCompletion {
186 fn callback(
187 &mut self,
188 _: &Weechat,
189 buffer: &Buffer,
190 _: Cow<str>,
191 completion: &Completion,
192 ) -> Result<(), ()> {
193 for candidate in
194 matrix_member_completion_candidates(&matrix_member_profiles(buffer))
195 {
196 completion.add_with_options(
197 &candidate,
198 true,
199 CompletionPosition::Sorted,
200 )
201 }
202
203 Ok(())
204 }
205}
206
207/// Feed room member nicks into WeeChat's built-in "nicks" completion.
208///
209/// Thread buffers keep an empty nicklist, so the built-in fallback of
210/// completing from the current buffer's nicklist finds no candidates
211/// there. Adding the parent room's members here makes nick completion
212/// work in thread buffers, while room buffers keep using the built-in
213/// nicklist completion (this hook adds nothing for them, so WeeChat
214/// falls back to it).
215struct NicksCompletion {
216 servers: Servers,
217}
218
219impl NicksCompletion {
220 fn create(servers: Servers) -> Result<CompletionHook, ()> {
221 let comp = NicksCompletion { servers };
222
223 CompletionHook::new(
224 "nick",
225 "Completion for Matrix room member nicks",
226 comp,
227 )
228 }
229}
230
231impl CompletionCallback for NicksCompletion {
232 fn callback(
233 &mut self,
234 _: &Weechat,
235 buffer: &Buffer,
236 _: Cow<str>,
237 completion: &Completion,
238 ) -> Result<(), ()> {
239 let room_names = self
240 .servers
241 .find_room(buffer)
242 .map(|room| room.names())
243 .unwrap_or_default();
244
245 for nick in nick_completion_candidates(
246 buffer.get_localvar("thread_root").is_some(),
247 room_names,
248 ) {
249 completion.add_with_options(&nick, true, CompletionPosition::Sorted)
250 }
251
252 Ok(())
253 }
254}
255
256/// Nick completion candidates for the given matrix buffer context.
257///
258/// Only thread buffers contribute candidates (the parent room's members);
259/// every other buffer contributes nothing so WeeChat keeps using its
260/// built-in nicklist-based completion there.
261fn nick_completion_candidates(
262 is_thread_buffer: bool,
263 room_names: Vec<String>,
264) -> Vec<String> {
265 if !is_thread_buffer {
266 return Vec::new();
267 }
268 let mut names = room_names;
269 names.sort_unstable();
270 names
271}
272
273struct MediaCompletion {
274 servers: Servers,
275}
276
277impl MediaCompletion {
278 fn create(servers: Servers) -> Result<CompletionHook, ()> {
279 let comp = MediaCompletion { servers };
280
281 CompletionHook::new(
282 "matrix-media",
283 "Completion for Matrix media URIs in the current buffer",
284 comp,
285 )
286 }
287}
288
289impl CompletionCallback for MediaCompletion {
290 fn callback(
291 &mut self,
292 _: &Weechat,
293 buffer: &Buffer,
294 _: Cow<str>,
295 completion: &Completion,
296 ) -> Result<(), ()> {
297 if self.servers.find_server(buffer).is_none() {
298 return Ok(());
299 }
300
301 let mut media = BTreeSet::new();
302
303 for line in buffer.lines().rev().take(200) {
304 let message = Weechat::remove_color(&line.message());
305 media.extend(extract_mxc_uris(&message));
306 }
307
308 for uri in media {
309 completion.add_with_options(
310 &uri,
311 false,
312 CompletionPosition::Sorted,
313 );
314 }
315
316 Ok(())
317 }
318}
319
320fn extract_mxc_uris(message: &str) -> Vec<String> {
321 message
322 .match_indices("mxc://")
323 .filter_map(|(start, _)| {
324 let uri = message[start..]
325 .split(|c: char| {
326 c.is_whitespace()
327 || matches!(
328 c,
329 '<' | '>' | '[' | ']' | '(' | ')' | '"' | '\''
330 )
331 })
332 .next()
333 .unwrap_or_default();
334 let uri = uri.trim_end_matches(|c: char| {
335 !(c.is_ascii_alphanumeric() || c == '-' || c == '_')
336 });
337 let uri = <&MxcUri>::from(uri);
338
339 if uri.is_valid() && uri.media_id().is_ok_and(|id| !id.is_empty()) {
340 Some(uri.as_str().to_owned())
341 } else {
342 None
343 }
344 })
345 .collect()
346}
347
348fn buffer_completion_candidates<I>(short_names: I) -> BTreeSet<String>
349where
350 I: IntoIterator<Item = String>,
351{
352 short_names
353 .into_iter()
354 .filter(|short_name| is_buffer_target(short_name))
355 .collect()
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn extracts_valid_mxc_uris() {
364 assert_eq!(
365 vec!["mxc://matrix.org/some-media-id".to_owned()],
366 extract_mxc_uris(
367 "authenticated download: /matrix media download \
368 mxc://matrix.org/some-media-id [file]"
369 )
370 );
371 }
372
373 #[test]
374 fn ignores_invalid_mxc_uris() {
375 assert!(extract_mxc_uris("download mxc://").is_empty());
376 }
377
378 #[test]
379 fn extracts_uris_followed_by_sentence_punctuation() {
380 assert_eq!(
381 vec!["mxc://matrix.org/some-media-id".to_owned()],
382 extract_mxc_uris("look at mxc://matrix.org/some-media-id."),
383 );
384 assert_eq!(
385 vec!["mxc://matrix.org/some-media-id".to_owned()],
386 extract_mxc_uris("see mxc://matrix.org/some-media-id, then reply"),
387 );
388 assert_eq!(
389 vec!["mxc://matrix.org/some-media-id".to_owned()],
390 extract_mxc_uris("is it mxc://matrix.org/some-media-id?"),
391 );
392 }
393
394 #[test]
395 fn extracts_uris_wrapped_in_delimiters() {
396 assert_eq!(
397 vec!["mxc://matrix.org/some-media-id".to_owned()],
398 extract_mxc_uris("(mxc://matrix.org/some-media-id)"),
399 );
400 assert_eq!(
401 vec!["mxc://matrix.org/some-media-id".to_owned()],
402 extract_mxc_uris("[mxc://matrix.org/some-media-id]"),
403 );
404 assert_eq!(
405 vec!["mxc://matrix.org/some-media-id".to_owned()],
406 extract_mxc_uris("\"mxc://matrix.org/some-media-id\""),
407 );
408 assert_eq!(
409 vec!["mxc://matrix.org/some-media-id".to_owned()],
410 extract_mxc_uris("<mxc://matrix.org/some-media-id>"),
411 );
412 }
413
414 #[test]
415 fn extracts_multiple_uris_from_a_single_line() {
416 assert_eq!(
417 vec![
418 "mxc://a.example.org/one".to_owned(),
419 "mxc://b.example.org/two".to_owned(),
420 ],
421 extract_mxc_uris(
422 "first mxc://a.example.org/one, then mxc://b.example.org/two."
423 ),
424 );
425 }
426
427 #[test]
428 fn drops_uris_without_a_media_id() {
429 assert!(extract_mxc_uris("download mxc://matrix.org/").is_empty());
430 }
431
432 #[test]
433 fn completes_only_resolvable_matrix_short_names() {
434 assert_eq!(
435 buffer_completion_candidates([
436 "#matrix:example.org".to_owned(),
437 "#matrix:example.org".to_owned(),
438 "".to_owned(),
439 "matrix room".to_owned(),
440 "list".to_owned(),
441 ]),
442 BTreeSet::from(["#matrix:example.org".to_owned()]),
443 );
444 }
445
446 #[test]
447 fn thread_buffers_contribute_sorted_room_member_nicks() {
448 assert_eq!(
449 nick_completion_candidates(
450 true,
451 vec![
452 "Bob".to_owned(),
453 "Alice".to_owned(),
454 "Ada (ada@example.org)".to_owned(),
455 ],
456 ),
457 vec![
458 "Ada (ada@example.org)".to_owned(),
459 "Alice".to_owned(),
460 "Bob".to_owned(),
461 ],
462 );
463 }
464
465 #[test]
466 fn thread_buffers_without_a_room_contribute_nothing() {
467 assert_eq!(
468 nick_completion_candidates(true, vec![]),
469 Vec::<String>::new()
470 );
471 }
472
473 #[test]
474 fn non_thread_buffers_keep_the_builtin_nicklist_completion() {
475 assert_eq!(
476 nick_completion_candidates(
477 false,
478 vec!["Alice".to_owned(), "Bob".to_owned(),],
479 ),
480 Vec::<String>::new(),
481 );
482 }
483}