1use anyhow::{Context as _, Result};
2use channel::{ChannelChat, ChannelStore, MessageParams};
3use client::{UserId, UserStore};
4use collections::HashSet;
5use editor::{AnchorRangeExt, CompletionProvider, Editor, EditorElement, EditorStyle, ExcerptId};
6use fuzzy::{StringMatch, StringMatchCandidate};
7use gpui::{
8 AsyncApp, AsyncWindowContext, Context, Entity, Focusable, FontStyle, FontWeight,
9 HighlightStyle, IntoElement, Render, Task, TextStyle, WeakEntity, Window,
10};
11use language::{
12 Anchor, Buffer, BufferSnapshot, CodeLabel, LanguageRegistry, ToOffset,
13 language_settings::SoftWrap,
14};
15use project::{Completion, CompletionSource, search::SearchQuery};
16use settings::Settings;
17use std::{
18 cell::RefCell,
19 ops::Range,
20 rc::Rc,
21 sync::{Arc, LazyLock},
22 time::Duration,
23};
24use theme::ThemeSettings;
25use ui::{TextSize, prelude::*};
26
27use crate::panel_settings::MessageEditorSettings;
28
29const MENTIONS_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(50);
30
31static MENTIONS_SEARCH: LazyLock<SearchQuery> = LazyLock::new(|| {
32 SearchQuery::regex(
33 "@[-_\\w]+",
34 false,
35 false,
36 false,
37 false,
38 Default::default(),
39 Default::default(),
40 None,
41 )
42 .unwrap()
43});
44
45pub struct MessageEditor {
46 pub editor: Entity<Editor>,
47 user_store: Entity<UserStore>,
48 channel_chat: Option<Entity<ChannelChat>>,
49 mentions: Vec<UserId>,
50 mentions_task: Option<Task<()>>,
51 reply_to_message_id: Option<u64>,
52 edit_message_id: Option<u64>,
53}
54
55struct MessageEditorCompletionProvider(WeakEntity<MessageEditor>);
56
57impl CompletionProvider for MessageEditorCompletionProvider {
58 fn completions(
59 &self,
60 _excerpt_id: ExcerptId,
61 buffer: &Entity<Buffer>,
62 buffer_position: language::Anchor,
63 _: editor::CompletionContext,
64 _window: &mut Window,
65 cx: &mut Context<Editor>,
66 ) -> Task<Result<Option<Vec<Completion>>>> {
67 let Some(handle) = self.0.upgrade() else {
68 return Task::ready(Ok(None));
69 };
70 handle.update(cx, |message_editor, cx| {
71 message_editor.completions(buffer, buffer_position, cx)
72 })
73 }
74
75 fn resolve_completions(
76 &self,
77 _buffer: Entity<Buffer>,
78 _completion_indices: Vec<usize>,
79 _completions: Rc<RefCell<Box<[Completion]>>>,
80 _cx: &mut Context<Editor>,
81 ) -> Task<anyhow::Result<bool>> {
82 Task::ready(Ok(false))
83 }
84
85 fn is_completion_trigger(
86 &self,
87 _buffer: &Entity<Buffer>,
88 _position: language::Anchor,
89 text: &str,
90 _trigger_in_words: bool,
91 _cx: &mut Context<Editor>,
92 ) -> bool {
93 text == "@"
94 }
95}
96
97impl MessageEditor {
98 pub fn new(
99 language_registry: Arc<LanguageRegistry>,
100 user_store: Entity<UserStore>,
101 channel_chat: Option<Entity<ChannelChat>>,
102 editor: Entity<Editor>,
103 window: &mut Window,
104 cx: &mut Context<Self>,
105 ) -> Self {
106 let this = cx.entity().downgrade();
107 editor.update(cx, |editor, cx| {
108 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
109 editor.set_use_autoclose(false);
110 editor.set_show_gutter(false, cx);
111 editor.set_show_wrap_guides(false, cx);
112 editor.set_show_indent_guides(false, cx);
113 editor.set_completion_provider(Some(Box::new(MessageEditorCompletionProvider(this))));
114 editor.set_auto_replace_emoji_shortcode(
115 MessageEditorSettings::get_global(cx)
116 .auto_replace_emoji_shortcode
117 .unwrap_or_default(),
118 );
119 });
120
121 let buffer = editor
122 .read(cx)
123 .buffer()
124 .read(cx)
125 .as_singleton()
126 .expect("message editor must be singleton");
127
128 cx.subscribe_in(&buffer, window, Self::on_buffer_event)
129 .detach();
130 cx.observe_global::<settings::SettingsStore>(|this, cx| {
131 this.editor.update(cx, |editor, cx| {
132 editor.set_auto_replace_emoji_shortcode(
133 MessageEditorSettings::get_global(cx)
134 .auto_replace_emoji_shortcode
135 .unwrap_or_default(),
136 )
137 })
138 })
139 .detach();
140
141 let markdown = language_registry.language_for_name("Markdown");
142 cx.spawn_in(window, async move |_, cx| {
143 let markdown = markdown.await.context("failed to load Markdown language")?;
144 buffer.update(cx, |buffer, cx| buffer.set_language(Some(markdown), cx))
145 })
146 .detach_and_log_err(cx);
147
148 Self {
149 editor,
150 user_store,
151 channel_chat,
152 mentions: Vec::new(),
153 mentions_task: None,
154 reply_to_message_id: None,
155 edit_message_id: None,
156 }
157 }
158
159 pub fn reply_to_message_id(&self) -> Option<u64> {
160 self.reply_to_message_id
161 }
162
163 pub fn set_reply_to_message_id(&mut self, reply_to_message_id: u64) {
164 self.reply_to_message_id = Some(reply_to_message_id);
165 }
166
167 pub fn clear_reply_to_message_id(&mut self) {
168 self.reply_to_message_id = None;
169 }
170
171 pub fn edit_message_id(&self) -> Option<u64> {
172 self.edit_message_id
173 }
174
175 pub fn set_edit_message_id(&mut self, edit_message_id: u64) {
176 self.edit_message_id = Some(edit_message_id);
177 }
178
179 pub fn clear_edit_message_id(&mut self) {
180 self.edit_message_id = None;
181 }
182
183 pub fn set_channel_chat(&mut self, chat: Entity<ChannelChat>, cx: &mut Context<Self>) {
184 let channel_id = chat.read(cx).channel_id;
185 self.channel_chat = Some(chat);
186 let channel_name = ChannelStore::global(cx)
187 .read(cx)
188 .channel_for_id(channel_id)
189 .map(|channel| channel.name.clone());
190 self.editor.update(cx, |editor, cx| {
191 if let Some(channel_name) = channel_name {
192 editor.set_placeholder_text(format!("Message #{channel_name}"), cx);
193 } else {
194 editor.set_placeholder_text("Message Channel", cx);
195 }
196 });
197 }
198
199 pub fn take_message(&mut self, window: &mut Window, cx: &mut Context<Self>) -> MessageParams {
200 self.editor.update(cx, |editor, cx| {
201 let highlights = editor.text_highlights::<Self>(cx);
202 let text = editor.text(cx);
203 let snapshot = editor.buffer().read(cx).snapshot(cx);
204 let mentions = if let Some((_, ranges)) = highlights {
205 ranges
206 .iter()
207 .map(|range| range.to_offset(&snapshot))
208 .zip(self.mentions.iter().copied())
209 .collect()
210 } else {
211 Vec::new()
212 };
213
214 editor.clear(window, cx);
215 self.mentions.clear();
216 let reply_to_message_id = std::mem::take(&mut self.reply_to_message_id);
217
218 MessageParams {
219 text,
220 mentions,
221 reply_to_message_id,
222 }
223 })
224 }
225
226 fn on_buffer_event(
227 &mut self,
228 buffer: &Entity<Buffer>,
229 event: &language::BufferEvent,
230 window: &mut Window,
231 cx: &mut Context<Self>,
232 ) {
233 if let language::BufferEvent::Reparsed | language::BufferEvent::Edited = event {
234 let buffer = buffer.read(cx).snapshot();
235 self.mentions_task = Some(cx.spawn_in(window, async move |this, cx| {
236 cx.background_executor()
237 .timer(MENTIONS_DEBOUNCE_INTERVAL)
238 .await;
239 Self::find_mentions(this, buffer, cx).await;
240 }));
241 }
242 }
243
244 fn completions(
245 &mut self,
246 buffer: &Entity<Buffer>,
247 end_anchor: Anchor,
248 cx: &mut Context<Self>,
249 ) -> Task<Result<Option<Vec<Completion>>>> {
250 if let Some((start_anchor, query, candidates)) =
251 self.collect_mention_candidates(buffer, end_anchor, cx)
252 {
253 if !candidates.is_empty() {
254 return cx.spawn(async move |_, cx| {
255 Ok(Some(
256 Self::resolve_completions_for_candidates(
257 &cx,
258 query.as_str(),
259 &candidates,
260 start_anchor..end_anchor,
261 Self::completion_for_mention,
262 )
263 .await,
264 ))
265 });
266 }
267 }
268
269 if let Some((start_anchor, query, candidates)) =
270 self.collect_emoji_candidates(buffer, end_anchor, cx)
271 {
272 if !candidates.is_empty() {
273 return cx.spawn(async move |_, cx| {
274 Ok(Some(
275 Self::resolve_completions_for_candidates(
276 &cx,
277 query.as_str(),
278 candidates,
279 start_anchor..end_anchor,
280 Self::completion_for_emoji,
281 )
282 .await,
283 ))
284 });
285 }
286 }
287
288 Task::ready(Ok(Some(Vec::new())))
289 }
290
291 async fn resolve_completions_for_candidates(
292 cx: &AsyncApp,
293 query: &str,
294 candidates: &[StringMatchCandidate],
295 range: Range<Anchor>,
296 completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
297 ) -> Vec<Completion> {
298 let matches = fuzzy::match_strings(
299 candidates,
300 query,
301 true,
302 10,
303 &Default::default(),
304 cx.background_executor().clone(),
305 )
306 .await;
307
308 matches
309 .into_iter()
310 .map(|mat| {
311 let (new_text, label) = completion_fn(&mat);
312 Completion {
313 replace_range: range.clone(),
314 new_text,
315 label,
316 icon_path: None,
317 confirm: None,
318 documentation: None,
319 insert_text_mode: None,
320 source: CompletionSource::Custom,
321 }
322 })
323 .collect()
324 }
325
326 fn completion_for_mention(mat: &StringMatch) -> (String, CodeLabel) {
327 let label = CodeLabel {
328 filter_range: 1..mat.string.len() + 1,
329 text: format!("@{}", mat.string),
330 runs: Vec::new(),
331 };
332 (mat.string.clone(), label)
333 }
334
335 fn completion_for_emoji(mat: &StringMatch) -> (String, CodeLabel) {
336 let emoji = emojis::get_by_shortcode(&mat.string).unwrap();
337 let label = CodeLabel {
338 filter_range: 1..mat.string.len() + 1,
339 text: format!(":{}: {}", mat.string, emoji),
340 runs: Vec::new(),
341 };
342 (emoji.to_string(), label)
343 }
344
345 fn collect_mention_candidates(
346 &mut self,
347 buffer: &Entity<Buffer>,
348 end_anchor: Anchor,
349 cx: &mut Context<Self>,
350 ) -> Option<(Anchor, String, Vec<StringMatchCandidate>)> {
351 let end_offset = end_anchor.to_offset(buffer.read(cx));
352
353 let query = buffer.update(cx, |buffer, _| {
354 let mut query = String::new();
355 for ch in buffer.reversed_chars_at(end_offset).take(100) {
356 if ch == '@' {
357 return Some(query.chars().rev().collect::<String>());
358 }
359 if ch.is_whitespace() || !ch.is_ascii() {
360 break;
361 }
362 query.push(ch);
363 }
364 None
365 })?;
366
367 let start_offset = end_offset - query.len();
368 let start_anchor = buffer.read(cx).anchor_before(start_offset);
369
370 let mut names = HashSet::default();
371 if let Some(chat) = self.channel_chat.as_ref() {
372 let chat = chat.read(cx);
373 for participant in ChannelStore::global(cx)
374 .read(cx)
375 .channel_participants(chat.channel_id)
376 {
377 names.insert(participant.github_login.clone());
378 }
379 for message in chat
380 .messages_in_range(chat.message_count().saturating_sub(100)..chat.message_count())
381 {
382 names.insert(message.sender.github_login.clone());
383 }
384 }
385
386 let candidates = names
387 .into_iter()
388 .map(|user| StringMatchCandidate::new(0, &user))
389 .collect::<Vec<_>>();
390
391 Some((start_anchor, query, candidates))
392 }
393
394 fn collect_emoji_candidates(
395 &mut self,
396 buffer: &Entity<Buffer>,
397 end_anchor: Anchor,
398 cx: &mut Context<Self>,
399 ) -> Option<(Anchor, String, &'static [StringMatchCandidate])> {
400 static EMOJI_FUZZY_MATCH_CANDIDATES: LazyLock<Vec<StringMatchCandidate>> =
401 LazyLock::new(|| {
402 let emojis = emojis::iter()
403 .flat_map(|s| s.shortcodes())
404 .map(|emoji| StringMatchCandidate::new(0, emoji))
405 .collect::<Vec<_>>();
406 emojis
407 });
408
409 let end_offset = end_anchor.to_offset(buffer.read(cx));
410
411 let query = buffer.update(cx, |buffer, _| {
412 let mut query = String::new();
413 for ch in buffer.reversed_chars_at(end_offset).take(100) {
414 if ch == ':' {
415 let next_char = buffer
416 .reversed_chars_at(end_offset - query.len() - 1)
417 .next();
418 // Ensure we are at the start of the message or that the previous character is a whitespace
419 if next_char.is_none() || next_char.unwrap().is_whitespace() {
420 return Some(query.chars().rev().collect::<String>());
421 }
422
423 // If the previous character is not a whitespace, we are in the middle of a word
424 // and we only want to complete the shortcode if the word is made up of other emojis
425 let mut containing_word = String::new();
426 for ch in buffer
427 .reversed_chars_at(end_offset - query.len() - 1)
428 .take(100)
429 {
430 if ch.is_whitespace() {
431 break;
432 }
433 containing_word.push(ch);
434 }
435 let containing_word = containing_word.chars().rev().collect::<String>();
436 if util::word_consists_of_emojis(containing_word.as_str()) {
437 return Some(query.chars().rev().collect::<String>());
438 }
439 break;
440 }
441 if ch.is_whitespace() || !ch.is_ascii() {
442 break;
443 }
444 query.push(ch);
445 }
446 None
447 })?;
448
449 let start_offset = end_offset - query.len() - 1;
450 let start_anchor = buffer.read(cx).anchor_before(start_offset);
451
452 Some((start_anchor, query, &EMOJI_FUZZY_MATCH_CANDIDATES))
453 }
454
455 async fn find_mentions(
456 this: WeakEntity<MessageEditor>,
457 buffer: BufferSnapshot,
458 cx: &mut AsyncWindowContext,
459 ) {
460 let (buffer, ranges) = cx
461 .background_spawn(async move {
462 let ranges = MENTIONS_SEARCH.search(&buffer, None).await;
463 (buffer, ranges)
464 })
465 .await;
466
467 this.update(cx, |this, cx| {
468 let mut anchor_ranges = Vec::new();
469 let mut mentioned_user_ids = Vec::new();
470 let mut text = String::new();
471
472 this.editor.update(cx, |editor, cx| {
473 let multi_buffer = editor.buffer().read(cx).snapshot(cx);
474 for range in ranges {
475 text.clear();
476 text.extend(buffer.text_for_range(range.clone()));
477 if let Some(username) = text.strip_prefix('@') {
478 if let Some(user) = this
479 .user_store
480 .read(cx)
481 .cached_user_by_github_login(username)
482 {
483 let start = multi_buffer.anchor_after(range.start);
484 let end = multi_buffer.anchor_after(range.end);
485
486 mentioned_user_ids.push(user.id);
487 anchor_ranges.push(start..end);
488 }
489 }
490 }
491
492 editor.clear_highlights::<Self>(cx);
493 editor.highlight_text::<Self>(
494 anchor_ranges,
495 HighlightStyle {
496 font_weight: Some(FontWeight::BOLD),
497 ..Default::default()
498 },
499 cx,
500 )
501 });
502
503 this.mentions = mentioned_user_ids;
504 this.mentions_task.take();
505 })
506 .ok();
507 }
508
509 pub(crate) fn focus_handle(&self, cx: &gpui::App) -> gpui::FocusHandle {
510 self.editor.read(cx).focus_handle(cx)
511 }
512}
513
514impl Render for MessageEditor {
515 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
516 let settings = ThemeSettings::get_global(cx);
517 let text_style = TextStyle {
518 color: if self.editor.read(cx).read_only(cx) {
519 cx.theme().colors().text_disabled
520 } else {
521 cx.theme().colors().text
522 },
523 font_family: settings.ui_font.family.clone(),
524 font_features: settings.ui_font.features.clone(),
525 font_fallbacks: settings.ui_font.fallbacks.clone(),
526 font_size: TextSize::Small.rems(cx).into(),
527 font_weight: settings.ui_font.weight,
528 font_style: FontStyle::Normal,
529 line_height: relative(1.3),
530 ..Default::default()
531 };
532
533 div()
534 .w_full()
535 .px_2()
536 .py_1()
537 .bg(cx.theme().colors().editor_background)
538 .rounded_sm()
539 .child(EditorElement::new(
540 &self.editor,
541 EditorStyle {
542 local_player: cx.theme().players().local(),
543 text: text_style,
544 ..Default::default()
545 },
546 ))
547 }
548}