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