1use anyhow::Result;
2use client::UserStore;
3use copilot::{Copilot, Status};
4use editor::{
5 Editor,
6 actions::{ShowEditPrediction, ToggleEditPrediction},
7 scroll::Autoscroll,
8};
9use feature_flags::{FeatureFlagAppExt, PredictEditsRateCompletionsFeatureFlag};
10use fs::Fs;
11use gpui::{
12 Action, Animation, AnimationExt, App, AsyncWindowContext, Corner, Entity, FocusHandle,
13 Focusable, IntoElement, ParentElement, Render, Subscription, WeakEntity, actions, div,
14 pulsating_between,
15};
16use indoc::indoc;
17use language::{
18 EditPredictionsMode, File, Language,
19 language_settings::{self, AllLanguageSettings, EditPredictionProvider, all_language_settings},
20};
21use regex::Regex;
22use settings::{Settings, SettingsStore, update_settings_file};
23use std::{
24 sync::{Arc, LazyLock},
25 time::Duration,
26};
27use supermaven::{AccountStatus, Supermaven};
28use ui::{
29 Clickable, ContextMenu, ContextMenuEntry, IconButton, IconButtonShape, Indicator, PopoverMenu,
30 PopoverMenuHandle, Tooltip, prelude::*,
31};
32use workspace::{
33 StatusItemView, Toast, Workspace, create_and_open_local_file, item::ItemHandle,
34 notifications::NotificationId,
35};
36use zed_actions::OpenBrowser;
37use zeta::RateCompletions;
38
39actions!(edit_prediction, [ToggleMenu]);
40
41const COPILOT_SETTINGS_URL: &str = "https://github.com/settings/copilot";
42
43struct CopilotErrorToast;
44
45pub struct InlineCompletionButton {
46 editor_subscription: Option<(Subscription, usize)>,
47 editor_enabled: Option<bool>,
48 editor_show_predictions: bool,
49 editor_focus_handle: Option<FocusHandle>,
50 language: Option<Arc<Language>>,
51 file: Option<Arc<dyn File>>,
52 edit_prediction_provider: Option<Arc<dyn inline_completion::InlineCompletionProviderHandle>>,
53 fs: Arc<dyn Fs>,
54 user_store: Entity<UserStore>,
55 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
56}
57
58enum SupermavenButtonStatus {
59 Ready,
60 Errored(String),
61 NeedsActivation(String),
62 Initializing,
63}
64
65impl Render for InlineCompletionButton {
66 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
67 let all_language_settings = all_language_settings(None, cx);
68
69 match all_language_settings.edit_predictions.provider {
70 EditPredictionProvider::None => div(),
71
72 EditPredictionProvider::Copilot => {
73 let Some(copilot) = Copilot::global(cx) else {
74 return div();
75 };
76 let status = copilot.read(cx).status();
77
78 let enabled = self.editor_enabled.unwrap_or(false);
79
80 let icon = match status {
81 Status::Error(_) => IconName::CopilotError,
82 Status::Authorized => {
83 if enabled {
84 IconName::Copilot
85 } else {
86 IconName::CopilotDisabled
87 }
88 }
89 _ => IconName::CopilotInit,
90 };
91
92 if let Status::Error(e) = status {
93 return div().child(
94 IconButton::new("copilot-error", icon)
95 .icon_size(IconSize::Small)
96 .on_click(cx.listener(move |_, _, window, cx| {
97 if let Some(workspace) = window.root::<Workspace>().flatten() {
98 workspace.update(cx, |workspace, cx| {
99 workspace.show_toast(
100 Toast::new(
101 NotificationId::unique::<CopilotErrorToast>(),
102 format!("Copilot can't be started: {}", e),
103 )
104 .on_click(
105 "Reinstall Copilot",
106 |_, cx| {
107 if let Some(copilot) = Copilot::global(cx) {
108 copilot
109 .update(cx, |copilot, cx| {
110 copilot.reinstall(cx)
111 })
112 .detach();
113 }
114 },
115 ),
116 cx,
117 );
118 });
119 }
120 }))
121 .tooltip(|window, cx| {
122 Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
123 }),
124 );
125 }
126 let this = cx.entity().clone();
127
128 div().child(
129 PopoverMenu::new("copilot")
130 .menu(move |window, cx| {
131 Some(match status {
132 Status::Authorized => this.update(cx, |this, cx| {
133 this.build_copilot_context_menu(window, cx)
134 }),
135 _ => this.update(cx, |this, cx| {
136 this.build_copilot_start_menu(window, cx)
137 }),
138 })
139 })
140 .anchor(Corner::BottomRight)
141 .trigger_with_tooltip(
142 IconButton::new("copilot-icon", icon),
143 |window, cx| {
144 Tooltip::for_action("GitHub Copilot", &ToggleMenu, window, cx)
145 },
146 )
147 .with_handle(self.popover_menu_handle.clone()),
148 )
149 }
150
151 EditPredictionProvider::Supermaven => {
152 let Some(supermaven) = Supermaven::global(cx) else {
153 return div();
154 };
155
156 let supermaven = supermaven.read(cx);
157
158 let status = match supermaven {
159 Supermaven::Starting => SupermavenButtonStatus::Initializing,
160 Supermaven::FailedDownload { error } => {
161 SupermavenButtonStatus::Errored(error.to_string())
162 }
163 Supermaven::Spawned(agent) => {
164 let account_status = agent.account_status.clone();
165 match account_status {
166 AccountStatus::NeedsActivation { activate_url } => {
167 SupermavenButtonStatus::NeedsActivation(activate_url.clone())
168 }
169 AccountStatus::Unknown => SupermavenButtonStatus::Initializing,
170 AccountStatus::Ready => SupermavenButtonStatus::Ready,
171 }
172 }
173 Supermaven::Error { error } => {
174 SupermavenButtonStatus::Errored(error.to_string())
175 }
176 };
177
178 let icon = status.to_icon();
179 let tooltip_text = status.to_tooltip();
180 let has_menu = status.has_menu();
181 let this = cx.entity().clone();
182 let fs = self.fs.clone();
183
184 return div().child(
185 PopoverMenu::new("supermaven")
186 .menu(move |window, cx| match &status {
187 SupermavenButtonStatus::NeedsActivation(activate_url) => {
188 Some(ContextMenu::build(window, cx, |menu, _, _| {
189 let fs = fs.clone();
190 let activate_url = activate_url.clone();
191 menu.entry("Sign In", None, move |_, cx| {
192 cx.open_url(activate_url.as_str())
193 })
194 .entry(
195 "Use Copilot",
196 None,
197 move |_, cx| {
198 set_completion_provider(
199 fs.clone(),
200 cx,
201 EditPredictionProvider::Copilot,
202 )
203 },
204 )
205 }))
206 }
207 SupermavenButtonStatus::Ready => Some(this.update(cx, |this, cx| {
208 this.build_supermaven_context_menu(window, cx)
209 })),
210 _ => None,
211 })
212 .anchor(Corner::BottomRight)
213 .trigger_with_tooltip(
214 IconButton::new("supermaven-icon", icon),
215 move |window, cx| {
216 if has_menu {
217 Tooltip::for_action(
218 tooltip_text.clone(),
219 &ToggleMenu,
220 window,
221 cx,
222 )
223 } else {
224 Tooltip::text(tooltip_text.clone())(window, cx)
225 }
226 },
227 )
228 .with_handle(self.popover_menu_handle.clone()),
229 );
230 }
231
232 EditPredictionProvider::Zed => {
233 let enabled = self.editor_enabled.unwrap_or(true);
234
235 let zeta_icon = if enabled {
236 IconName::ZedPredict
237 } else {
238 IconName::ZedPredictDisabled
239 };
240
241 let current_user_terms_accepted =
242 self.user_store.read(cx).current_user_has_accepted_terms();
243
244 if !current_user_terms_accepted.unwrap_or(false) {
245 let signed_in = current_user_terms_accepted.is_some();
246 let tooltip_meta = if signed_in {
247 "Read Terms of Service"
248 } else {
249 "Sign in to use"
250 };
251
252 return div().child(
253 IconButton::new("zed-predict-pending-button", zeta_icon)
254 .shape(IconButtonShape::Square)
255 .indicator(Indicator::dot().color(Color::Muted))
256 .indicator_border_color(Some(cx.theme().colors().status_bar_background))
257 .tooltip(move |window, cx| {
258 Tooltip::with_meta(
259 "Edit Predictions",
260 None,
261 tooltip_meta,
262 window,
263 cx,
264 )
265 })
266 .on_click(cx.listener(move |_, _, window, cx| {
267 telemetry::event!(
268 "Pending ToS Clicked",
269 source = "Edit Prediction Status Button"
270 );
271 window.dispatch_action(
272 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
273 cx,
274 );
275 })),
276 );
277 }
278
279 let show_editor_predictions = self.editor_show_predictions;
280
281 let icon_button = IconButton::new("zed-predict-pending-button", zeta_icon)
282 .shape(IconButtonShape::Square)
283 .when(enabled && !show_editor_predictions, |this| {
284 this.indicator(Indicator::dot().color(Color::Muted))
285 .indicator_border_color(Some(cx.theme().colors().status_bar_background))
286 })
287 .when(!self.popover_menu_handle.is_deployed(), |element| {
288 element.tooltip(move |window, cx| {
289 if enabled {
290 if show_editor_predictions {
291 Tooltip::for_action("Edit Prediction", &ToggleMenu, window, cx)
292 } else {
293 Tooltip::with_meta(
294 "Edit Prediction",
295 Some(&ToggleMenu),
296 "Hidden For This File",
297 window,
298 cx,
299 )
300 }
301 } else {
302 Tooltip::with_meta(
303 "Edit Prediction",
304 Some(&ToggleMenu),
305 "Disabled For This File",
306 window,
307 cx,
308 )
309 }
310 })
311 });
312
313 let this = cx.entity().clone();
314
315 let mut popover_menu = PopoverMenu::new("zeta")
316 .menu(move |window, cx| {
317 Some(this.update(cx, |this, cx| this.build_zeta_context_menu(window, cx)))
318 })
319 .anchor(Corner::BottomRight)
320 .with_handle(self.popover_menu_handle.clone());
321
322 let is_refreshing = self
323 .edit_prediction_provider
324 .as_ref()
325 .map_or(false, |provider| provider.is_refreshing(cx));
326
327 if is_refreshing {
328 popover_menu = popover_menu.trigger(
329 icon_button.with_animation(
330 "pulsating-label",
331 Animation::new(Duration::from_secs(2))
332 .repeat()
333 .with_easing(pulsating_between(0.2, 1.0)),
334 |icon_button, delta| icon_button.alpha(delta),
335 ),
336 );
337 } else {
338 popover_menu = popover_menu.trigger(icon_button);
339 }
340
341 div().child(popover_menu.into_any_element())
342 }
343 }
344 }
345}
346
347impl InlineCompletionButton {
348 pub fn new(
349 fs: Arc<dyn Fs>,
350 user_store: Entity<UserStore>,
351 popover_menu_handle: PopoverMenuHandle<ContextMenu>,
352 cx: &mut Context<Self>,
353 ) -> Self {
354 if let Some(copilot) = Copilot::global(cx) {
355 cx.observe(&copilot, |_, _, cx| cx.notify()).detach()
356 }
357
358 cx.observe_global::<SettingsStore>(move |_, cx| cx.notify())
359 .detach();
360
361 Self {
362 editor_subscription: None,
363 editor_enabled: None,
364 editor_show_predictions: true,
365 editor_focus_handle: None,
366 language: None,
367 file: None,
368 edit_prediction_provider: None,
369 popover_menu_handle,
370 fs,
371 user_store,
372 }
373 }
374
375 pub fn build_copilot_start_menu(
376 &mut self,
377 window: &mut Window,
378 cx: &mut Context<Self>,
379 ) -> Entity<ContextMenu> {
380 let fs = self.fs.clone();
381 ContextMenu::build(window, cx, |menu, _, _| {
382 menu.entry("Sign In", None, copilot::initiate_sign_in)
383 .entry("Disable Copilot", None, {
384 let fs = fs.clone();
385 move |_window, cx| hide_copilot(fs.clone(), cx)
386 })
387 .entry("Use Supermaven", None, {
388 let fs = fs.clone();
389 move |_window, cx| {
390 set_completion_provider(fs.clone(), cx, EditPredictionProvider::Supermaven)
391 }
392 })
393 })
394 }
395
396 pub fn build_language_settings_menu(
397 &self,
398 mut menu: ContextMenu,
399 window: &Window,
400 cx: &mut App,
401 ) -> ContextMenu {
402 let fs = self.fs.clone();
403 let line_height = window.line_height();
404
405 menu = menu.header("Show Edit Predictions For");
406
407 let language_state = self.language.as_ref().map(|language| {
408 (
409 language.clone(),
410 language_settings::language_settings(Some(language.name()), None, cx)
411 .show_edit_predictions,
412 )
413 });
414
415 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
416 let entry = ContextMenuEntry::new("This Buffer")
417 .toggleable(IconPosition::Start, self.editor_show_predictions)
418 .action(Box::new(ToggleEditPrediction))
419 .handler(move |window, cx| {
420 editor_focus_handle.dispatch_action(&ToggleEditPrediction, window, cx);
421 });
422
423 match language_state.clone() {
424 Some((language, false)) => {
425 menu = menu.item(
426 entry
427 .disabled(true)
428 .documentation_aside(move |_cx| {
429 Label::new(format!("Edit predictions cannot be toggled for this buffer because they are disabled for {}", language.name()))
430 .into_any_element()
431 })
432 );
433 }
434 Some(_) | None => menu = menu.item(entry),
435 }
436 }
437
438 if let Some((language, language_enabled)) = language_state {
439 let fs = fs.clone();
440
441 menu = menu.toggleable_entry(
442 language.name(),
443 language_enabled,
444 IconPosition::Start,
445 None,
446 move |_, cx| {
447 toggle_show_inline_completions_for_language(language.clone(), fs.clone(), cx)
448 },
449 );
450 }
451
452 let settings = AllLanguageSettings::get_global(cx);
453
454 let globally_enabled = settings.show_edit_predictions(None, cx);
455 menu = menu.toggleable_entry("All Files", globally_enabled, IconPosition::Start, None, {
456 let fs = fs.clone();
457 move |_, cx| toggle_inline_completions_globally(fs.clone(), cx)
458 });
459
460 let provider = settings.edit_predictions.provider;
461 let current_mode = settings.edit_predictions_mode();
462 let subtle_mode = matches!(current_mode, EditPredictionsMode::Subtle);
463 let eager_mode = matches!(current_mode, EditPredictionsMode::Eager);
464
465 if matches!(provider, EditPredictionProvider::Zed) {
466 menu = menu
467 .separator()
468 .header("Display Modes")
469 .item(
470 ContextMenuEntry::new("Eager")
471 .toggleable(IconPosition::Start, eager_mode)
472 .documentation_aside(move |_| {
473 Label::new("Display predictions inline when there are no language server completions available.").into_any_element()
474 })
475 .handler({
476 let fs = fs.clone();
477 move |_, cx| {
478 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Eager, cx)
479 }
480 }),
481 )
482 .item(
483 ContextMenuEntry::new("Subtle")
484 .toggleable(IconPosition::Start, subtle_mode)
485 .documentation_aside(move |_| {
486 Label::new("Display predictions inline only when holding a modifier key (alt by default).").into_any_element()
487 })
488 .handler({
489 let fs = fs.clone();
490 move |_, cx| {
491 toggle_edit_prediction_mode(fs.clone(), EditPredictionsMode::Subtle, cx)
492 }
493 }),
494 );
495 }
496
497 menu = menu.separator().header("Privacy Settings");
498 if let Some(provider) = &self.edit_prediction_provider {
499 let data_collection = provider.data_collection_state(cx);
500 if data_collection.is_supported() {
501 let provider = provider.clone();
502 let enabled = data_collection.is_enabled();
503 let is_open_source = data_collection.is_project_open_source();
504 let is_collecting = data_collection.is_enabled();
505 let (icon_name, icon_color) = if is_open_source && is_collecting {
506 (IconName::Check, Color::Success)
507 } else {
508 (IconName::Check, Color::Accent)
509 };
510
511 menu = menu.item(
512 ContextMenuEntry::new("Training Data Collection")
513 .toggleable(IconPosition::Start, data_collection.is_enabled())
514 .icon(icon_name)
515 .icon_color(icon_color)
516 .documentation_aside(move |cx| {
517 let (msg, label_color, icon_name, icon_color) = match (is_open_source, is_collecting) {
518 (true, true) => (
519 "Project identified as open source, and you're sharing data.",
520 Color::Default,
521 IconName::Check,
522 Color::Success,
523 ),
524 (true, false) => (
525 "Project identified as open source, but you're not sharing data.",
526 Color::Muted,
527 IconName::Close,
528 Color::Muted,
529 ),
530 (false, true) => (
531 "Project not identified as open source. No data captured.",
532 Color::Muted,
533 IconName::Close,
534 Color::Muted,
535 ),
536 (false, false) => (
537 "Project not identified as open source, and setting turned off.",
538 Color::Muted,
539 IconName::Close,
540 Color::Muted,
541 ),
542 };
543 v_flex()
544 .gap_2()
545 .child(
546 Label::new(indoc!{
547 "Help us improve our open dataset model by sharing data from open source repositories. \
548 Zed must detect a license file in your repo for this setting to take effect."
549 })
550 )
551 .child(
552 h_flex()
553 .items_start()
554 .pt_2()
555 .flex_1()
556 .gap_1p5()
557 .border_t_1()
558 .border_color(cx.theme().colors().border_variant)
559 .child(h_flex().flex_shrink_0().h(line_height).child(Icon::new(icon_name).size(IconSize::XSmall).color(icon_color)))
560 .child(div().child(msg).w_full().text_sm().text_color(label_color.color(cx)))
561 )
562 .into_any_element()
563 })
564 .handler(move |_, cx| {
565 provider.toggle_data_collection(cx);
566
567 if !enabled {
568 telemetry::event!(
569 "Data Collection Enabled",
570 source = "Edit Prediction Status Menu"
571 );
572 } else {
573 telemetry::event!(
574 "Data Collection Disabled",
575 source = "Edit Prediction Status Menu"
576 );
577 }
578 })
579 );
580
581 if is_collecting && !is_open_source {
582 menu = menu.item(
583 ContextMenuEntry::new("No data captured.")
584 .disabled(true)
585 .icon(IconName::Close)
586 .icon_color(Color::Error)
587 .icon_size(IconSize::Small),
588 );
589 }
590 }
591 }
592
593 menu = menu.item(
594 ContextMenuEntry::new("Configure Excluded Files")
595 .icon(IconName::LockOutlined)
596 .icon_color(Color::Muted)
597 .documentation_aside(|_| {
598 Label::new(indoc!{"
599 Open your settings to add sensitive paths for which Zed will never predict edits."}).into_any_element()
600 })
601 .handler(move |window, cx| {
602 if let Some(workspace) = window.root().flatten() {
603 let workspace = workspace.downgrade();
604 window
605 .spawn(cx, async |cx| {
606 open_disabled_globs_setting_in_editor(
607 workspace,
608 cx,
609 ).await
610 })
611 .detach_and_log_err(cx);
612 }
613 }),
614 );
615
616 if !self.editor_enabled.unwrap_or(true) {
617 menu = menu.item(
618 ContextMenuEntry::new("This file is excluded.")
619 .disabled(true)
620 .icon(IconName::ZedPredictDisabled)
621 .icon_size(IconSize::Small),
622 );
623 }
624
625 if let Some(editor_focus_handle) = self.editor_focus_handle.clone() {
626 menu = menu
627 .separator()
628 .entry(
629 "Predict Edit at Cursor",
630 Some(Box::new(ShowEditPrediction)),
631 {
632 let editor_focus_handle = editor_focus_handle.clone();
633 move |window, cx| {
634 editor_focus_handle.dispatch_action(&ShowEditPrediction, window, cx);
635 }
636 },
637 )
638 .context(editor_focus_handle);
639 }
640
641 menu
642 }
643
644 fn build_copilot_context_menu(
645 &self,
646 window: &mut Window,
647 cx: &mut Context<Self>,
648 ) -> Entity<ContextMenu> {
649 ContextMenu::build(window, cx, |menu, window, cx| {
650 self.build_language_settings_menu(menu, window, cx)
651 .separator()
652 .link(
653 "Go to Copilot Settings",
654 OpenBrowser {
655 url: COPILOT_SETTINGS_URL.to_string(),
656 }
657 .boxed_clone(),
658 )
659 .action("Sign Out", copilot::SignOut.boxed_clone())
660 })
661 }
662
663 fn build_supermaven_context_menu(
664 &self,
665 window: &mut Window,
666 cx: &mut Context<Self>,
667 ) -> Entity<ContextMenu> {
668 ContextMenu::build(window, cx, |menu, window, cx| {
669 self.build_language_settings_menu(menu, window, cx)
670 .separator()
671 .action("Sign Out", supermaven::SignOut.boxed_clone())
672 })
673 }
674
675 fn build_zeta_context_menu(
676 &self,
677 window: &mut Window,
678 cx: &mut Context<Self>,
679 ) -> Entity<ContextMenu> {
680 ContextMenu::build(window, cx, |menu, window, cx| {
681 self.build_language_settings_menu(menu, window, cx).when(
682 cx.has_flag::<PredictEditsRateCompletionsFeatureFlag>(),
683 |this| this.action("Rate Completions", RateCompletions.boxed_clone()),
684 )
685 })
686 }
687
688 pub fn update_enabled(&mut self, editor: Entity<Editor>, cx: &mut Context<Self>) {
689 let editor = editor.read(cx);
690 let snapshot = editor.buffer().read(cx).snapshot(cx);
691 let suggestion_anchor = editor.selections.newest_anchor().start;
692 let language = snapshot.language_at(suggestion_anchor);
693 let file = snapshot.file_at(suggestion_anchor).cloned();
694 self.editor_enabled = {
695 let file = file.as_ref();
696 Some(
697 file.map(|file| {
698 all_language_settings(Some(file), cx)
699 .edit_predictions_enabled_for_file(file, cx)
700 })
701 .unwrap_or(true),
702 )
703 };
704 self.editor_show_predictions = editor.edit_predictions_enabled();
705 self.edit_prediction_provider = editor.edit_prediction_provider();
706 self.language = language.cloned();
707 self.file = file;
708 self.editor_focus_handle = Some(editor.focus_handle(cx));
709
710 cx.notify();
711 }
712
713 pub fn toggle_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
714 self.popover_menu_handle.toggle(window, cx);
715 }
716}
717
718impl StatusItemView for InlineCompletionButton {
719 fn set_active_pane_item(
720 &mut self,
721 item: Option<&dyn ItemHandle>,
722 _: &mut Window,
723 cx: &mut Context<Self>,
724 ) {
725 if let Some(editor) = item.and_then(|item| item.act_as::<Editor>(cx)) {
726 self.editor_subscription = Some((
727 cx.observe(&editor, Self::update_enabled),
728 editor.entity_id().as_u64() as usize,
729 ));
730 self.update_enabled(editor, cx);
731 } else {
732 self.language = None;
733 self.editor_subscription = None;
734 self.editor_enabled = None;
735 }
736 cx.notify();
737 }
738}
739
740impl SupermavenButtonStatus {
741 fn to_icon(&self) -> IconName {
742 match self {
743 SupermavenButtonStatus::Ready => IconName::Supermaven,
744 SupermavenButtonStatus::Errored(_) => IconName::SupermavenError,
745 SupermavenButtonStatus::NeedsActivation(_) => IconName::SupermavenInit,
746 SupermavenButtonStatus::Initializing => IconName::SupermavenInit,
747 }
748 }
749
750 fn to_tooltip(&self) -> String {
751 match self {
752 SupermavenButtonStatus::Ready => "Supermaven is ready".to_string(),
753 SupermavenButtonStatus::Errored(error) => format!("Supermaven error: {}", error),
754 SupermavenButtonStatus::NeedsActivation(_) => "Supermaven needs activation".to_string(),
755 SupermavenButtonStatus::Initializing => "Supermaven initializing".to_string(),
756 }
757 }
758
759 fn has_menu(&self) -> bool {
760 match self {
761 SupermavenButtonStatus::Ready | SupermavenButtonStatus::NeedsActivation(_) => true,
762 SupermavenButtonStatus::Errored(_) | SupermavenButtonStatus::Initializing => false,
763 }
764 }
765}
766
767async fn open_disabled_globs_setting_in_editor(
768 workspace: WeakEntity<Workspace>,
769 cx: &mut AsyncWindowContext,
770) -> Result<()> {
771 let settings_editor = workspace
772 .update_in(cx, |_, window, cx| {
773 create_and_open_local_file(paths::settings_file(), window, cx, || {
774 settings::initial_user_settings_content().as_ref().into()
775 })
776 })?
777 .await?
778 .downcast::<Editor>()
779 .unwrap();
780
781 settings_editor
782 .downgrade()
783 .update_in(cx, |item, window, cx| {
784 let text = item.buffer().read(cx).snapshot(cx).text();
785
786 let settings = cx.global::<SettingsStore>();
787
788 // Ensure that we always have "inline_completions { "disabled_globs": [] }"
789 let edits = settings.edits_for_update::<AllLanguageSettings>(&text, |file| {
790 file.edit_predictions
791 .get_or_insert_with(Default::default)
792 .disabled_globs
793 .get_or_insert_with(Vec::new);
794 });
795
796 if !edits.is_empty() {
797 item.edit(edits.iter().cloned(), cx);
798 }
799
800 let text = item.buffer().read(cx).snapshot(cx).text();
801
802 static DISABLED_GLOBS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
803 Regex::new(r#""disabled_globs":\s*\[\s*(?P<content>(?:.|\n)*?)\s*\]"#).unwrap()
804 });
805 // Only capture [...]
806 let range = DISABLED_GLOBS_REGEX.captures(&text).and_then(|captures| {
807 captures
808 .name("content")
809 .map(|inner_match| inner_match.start()..inner_match.end())
810 });
811 if let Some(range) = range {
812 item.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
813 selections.select_ranges(vec![range]);
814 });
815 }
816 })?;
817
818 anyhow::Ok(())
819}
820
821fn toggle_inline_completions_globally(fs: Arc<dyn Fs>, cx: &mut App) {
822 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
823 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
824 file.defaults.show_edit_predictions = Some(!show_edit_predictions)
825 });
826}
827
828fn set_completion_provider(fs: Arc<dyn Fs>, cx: &mut App, provider: EditPredictionProvider) {
829 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
830 file.features
831 .get_or_insert(Default::default())
832 .edit_prediction_provider = Some(provider);
833 });
834}
835
836fn toggle_show_inline_completions_for_language(
837 language: Arc<Language>,
838 fs: Arc<dyn Fs>,
839 cx: &mut App,
840) {
841 let show_edit_predictions =
842 all_language_settings(None, cx).show_edit_predictions(Some(&language), cx);
843 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
844 file.languages
845 .entry(language.name())
846 .or_default()
847 .show_edit_predictions = Some(!show_edit_predictions);
848 });
849}
850
851fn hide_copilot(fs: Arc<dyn Fs>, cx: &mut App) {
852 update_settings_file::<AllLanguageSettings>(fs, cx, move |file, _| {
853 file.features
854 .get_or_insert(Default::default())
855 .edit_prediction_provider = Some(EditPredictionProvider::None);
856 });
857}
858
859fn toggle_edit_prediction_mode(fs: Arc<dyn Fs>, mode: EditPredictionsMode, cx: &mut App) {
860 let settings = AllLanguageSettings::get_global(cx);
861 let current_mode = settings.edit_predictions_mode();
862
863 if current_mode != mode {
864 update_settings_file::<AllLanguageSettings>(fs, cx, move |settings, _cx| {
865 if let Some(edit_predictions) = settings.edit_predictions.as_mut() {
866 edit_predictions.mode = mode;
867 } else {
868 settings.edit_predictions =
869 Some(language_settings::EditPredictionSettingsContent {
870 mode,
871 ..Default::default()
872 });
873 }
874 });
875 }
876}