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