console.rs

   1use super::{
   2    stack_frame_list::{StackFrameList, StackFrameListEvent},
   3    variable_list::VariableList,
   4};
   5use alacritty_terminal::vte::ansi;
   6use anyhow::Result;
   7use collections::HashMap;
   8use dap::{CompletionItem, CompletionItemType, OutputEvent};
   9use editor::{
  10    Bias, CompletionProvider, Editor, EditorElement, EditorMode, EditorStyle, ExcerptId,
  11    MultiBufferOffset, SizingBehavior,
  12};
  13use fuzzy::StringMatchCandidate;
  14use gpui::{
  15    Action as _, AppContext, Context, Corner, Entity, FocusHandle, Focusable, HighlightStyle, Hsla,
  16    Render, Subscription, Task, TextStyle, WeakEntity, actions,
  17};
  18use language::{Anchor, Buffer, CharScopeContext, CodeLabel, TextBufferSnapshot, ToOffset};
  19use menu::{Confirm, SelectNext, SelectPrevious};
  20use project::{
  21    Completion, CompletionDisplayOptions, CompletionResponse,
  22    debugger::session::{CompletionsQuery, OutputToken, Session},
  23    lsp_store::CompletionDocumentation,
  24    search_history::{SearchHistory, SearchHistoryCursor},
  25};
  26use settings::Settings;
  27use std::fmt::Write;
  28use std::{cell::RefCell, ops::Range, rc::Rc, usize};
  29use theme::{Theme, ThemeSettings};
  30use ui::{ContextMenu, Divider, PopoverMenu, SplitButton, Tooltip, prelude::*};
  31use util::ResultExt;
  32
  33actions!(
  34    console,
  35    [
  36        /// Adds an expression to the watch list.
  37        WatchExpression
  38    ]
  39);
  40
  41pub struct Console {
  42    console: Entity<Editor>,
  43    query_bar: Entity<Editor>,
  44    session: Entity<Session>,
  45    _subscriptions: Vec<Subscription>,
  46    variable_list: Entity<VariableList>,
  47    stack_frame_list: Entity<StackFrameList>,
  48    last_token: OutputToken,
  49    update_output_task: Option<Task<()>>,
  50    focus_handle: FocusHandle,
  51    history: SearchHistory,
  52    cursor: SearchHistoryCursor,
  53}
  54
  55impl Console {
  56    pub fn new(
  57        session: Entity<Session>,
  58        stack_frame_list: Entity<StackFrameList>,
  59        variable_list: Entity<VariableList>,
  60        window: &mut Window,
  61        cx: &mut Context<Self>,
  62    ) -> Self {
  63        let console = cx.new(|cx| {
  64            let mut editor = Editor::multi_line(window, cx);
  65            editor.set_mode(EditorMode::Full {
  66                scale_ui_elements_with_buffer_font_size: true,
  67                show_active_line_background: true,
  68                sizing_behavior: SizingBehavior::ExcludeOverscrollMargin,
  69            });
  70            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
  71            editor.set_read_only(true);
  72            editor.disable_scrollbars_and_minimap(window, cx);
  73            editor.set_show_gutter(false, cx);
  74            editor.set_show_runnables(false, cx);
  75            editor.set_show_breakpoints(false, cx);
  76            editor.set_show_code_actions(false, cx);
  77            editor.set_show_line_numbers(false, cx);
  78            editor.set_show_git_diff_gutter(false, cx);
  79            editor.set_autoindent(false);
  80            editor.set_input_enabled(false);
  81            editor.set_use_autoclose(false);
  82            editor.set_show_wrap_guides(false, cx);
  83            editor.set_show_indent_guides(false, cx);
  84            editor.set_show_edit_predictions(Some(false), window, cx);
  85            editor.set_use_modal_editing(false);
  86            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
  87            editor
  88        });
  89        let focus_handle = cx.focus_handle();
  90
  91        let this = cx.weak_entity();
  92        let query_bar = cx.new(|cx| {
  93            let mut editor = Editor::single_line(window, cx);
  94            editor.set_placeholder_text("Evaluate an expression", window, cx);
  95            editor.set_use_autoclose(false);
  96            editor.set_show_gutter(false, cx);
  97            editor.set_show_wrap_guides(false, cx);
  98            editor.set_show_indent_guides(false, cx);
  99            editor.set_completion_provider(Some(Rc::new(ConsoleQueryBarCompletionProvider(this))));
 100
 101            editor
 102        });
 103
 104        let _subscriptions = vec![
 105            cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events),
 106            cx.on_focus(&focus_handle, window, |console, window, cx| {
 107                if console.is_running(cx) {
 108                    console.query_bar.focus_handle(cx).focus(window);
 109                }
 110            }),
 111        ];
 112
 113        Self {
 114            session,
 115            console,
 116            query_bar,
 117            variable_list,
 118            _subscriptions,
 119            stack_frame_list,
 120            update_output_task: None,
 121            last_token: OutputToken(0),
 122            focus_handle,
 123            history: SearchHistory::new(
 124                None,
 125                project::search_history::QueryInsertionBehavior::ReplacePreviousIfContains,
 126            ),
 127            cursor: Default::default(),
 128        }
 129    }
 130
 131    #[cfg(test)]
 132    pub(crate) fn editor(&self) -> &Entity<Editor> {
 133        &self.console
 134    }
 135
 136    fn is_running(&self, cx: &Context<Self>) -> bool {
 137        self.session.read(cx).is_started()
 138    }
 139
 140    fn handle_stack_frame_list_events(
 141        &mut self,
 142        _: Entity<StackFrameList>,
 143        event: &StackFrameListEvent,
 144        cx: &mut Context<Self>,
 145    ) {
 146        match event {
 147            StackFrameListEvent::SelectedStackFrameChanged(_) => cx.notify(),
 148            StackFrameListEvent::BuiltEntries => {}
 149        }
 150    }
 151
 152    pub(crate) fn show_indicator(&self, cx: &App) -> bool {
 153        self.session.read(cx).has_new_output(self.last_token)
 154    }
 155
 156    fn add_messages(
 157        &mut self,
 158        events: Vec<OutputEvent>,
 159        window: &mut Window,
 160        cx: &mut App,
 161    ) -> Task<Result<()>> {
 162        self.console.update(cx, |_, cx| {
 163            cx.spawn_in(window, async move |console, cx| {
 164                let mut len = console
 165                    .update(cx, |this, cx| this.buffer().read(cx).len(cx))?
 166                    .0;
 167                let (output, spans, background_spans) = cx
 168                    .background_spawn(async move {
 169                        let mut all_spans = Vec::new();
 170                        let mut all_background_spans = Vec::new();
 171                        let mut to_insert = String::new();
 172                        let mut scratch = String::new();
 173
 174                        for event in &events {
 175                            scratch.clear();
 176                            let mut ansi_handler = ConsoleHandler::default();
 177                            let mut ansi_processor =
 178                                ansi::Processor::<ansi::StdSyncHandler>::default();
 179
 180                            let trimmed_output = event.output.trim_end();
 181                            let _ = writeln!(&mut scratch, "{trimmed_output}");
 182                            ansi_processor.advance(&mut ansi_handler, scratch.as_bytes());
 183                            let output = std::mem::take(&mut ansi_handler.output);
 184                            to_insert.extend(output.chars());
 185                            let mut spans = std::mem::take(&mut ansi_handler.spans);
 186                            let mut background_spans =
 187                                std::mem::take(&mut ansi_handler.background_spans);
 188                            if ansi_handler.current_range_start < output.len() {
 189                                spans.push((
 190                                    ansi_handler.current_range_start..output.len(),
 191                                    ansi_handler.current_color,
 192                                ));
 193                            }
 194                            if ansi_handler.current_background_range_start < output.len() {
 195                                background_spans.push((
 196                                    ansi_handler.current_background_range_start..output.len(),
 197                                    ansi_handler.current_background_color,
 198                                ));
 199                            }
 200
 201                            for (range, _) in spans.iter_mut() {
 202                                let start_offset = len + range.start;
 203                                *range = start_offset..len + range.end;
 204                            }
 205
 206                            for (range, _) in background_spans.iter_mut() {
 207                                let start_offset = len + range.start;
 208                                *range = start_offset..len + range.end;
 209                            }
 210
 211                            len += output.len();
 212
 213                            all_spans.extend(spans);
 214                            all_background_spans.extend(background_spans);
 215                        }
 216                        (to_insert, all_spans, all_background_spans)
 217                    })
 218                    .await;
 219                console.update_in(cx, |console, window, cx| {
 220                    console.set_read_only(false);
 221                    console.move_to_end(&editor::actions::MoveToEnd, window, cx);
 222                    console.insert(&output, window, cx);
 223                    console.set_read_only(true);
 224
 225                    struct ConsoleAnsiHighlight;
 226
 227                    let buffer = console.buffer().read(cx).snapshot(cx);
 228
 229                    for (range, color) in spans {
 230                        let Some(color) = color else { continue };
 231                        let start_offset = range.start;
 232                        let range = buffer.anchor_after(MultiBufferOffset(range.start))
 233                            ..buffer.anchor_before(MultiBufferOffset(range.end));
 234                        let style = HighlightStyle {
 235                            color: Some(terminal_view::terminal_element::convert_color(
 236                                &color,
 237                                cx.theme(),
 238                            )),
 239                            ..Default::default()
 240                        };
 241                        console.highlight_text_key::<ConsoleAnsiHighlight>(
 242                            start_offset,
 243                            vec![range],
 244                            style,
 245                            cx,
 246                        );
 247                    }
 248
 249                    for (range, color) in background_spans {
 250                        let Some(color) = color else { continue };
 251                        let start_offset = range.start;
 252                        let range = buffer.anchor_after(MultiBufferOffset(range.start))
 253                            ..buffer.anchor_before(MultiBufferOffset(range.end));
 254                        console.highlight_background_key::<ConsoleAnsiHighlight>(
 255                            start_offset,
 256                            &[range],
 257                            color_fetcher(color),
 258                            cx,
 259                        );
 260                    }
 261
 262                    cx.notify();
 263                })?;
 264
 265                Ok(())
 266            })
 267        })
 268    }
 269
 270    pub fn watch_expression(
 271        &mut self,
 272        _: &WatchExpression,
 273        window: &mut Window,
 274        cx: &mut Context<Self>,
 275    ) {
 276        let expression = self.query_bar.update(cx, |editor, cx| {
 277            let expression = editor.text(cx);
 278            cx.defer_in(window, |editor, window, cx| {
 279                editor.clear(window, cx);
 280            });
 281
 282            expression
 283        });
 284        self.history.add(&mut self.cursor, expression.clone());
 285        self.cursor.reset();
 286        self.session.update(cx, |session, cx| {
 287            session
 288                .evaluate(
 289                    expression.clone(),
 290                    Some(dap::EvaluateArgumentsContext::Repl),
 291                    self.stack_frame_list.read(cx).opened_stack_frame_id(),
 292                    None,
 293                    cx,
 294                )
 295                .detach();
 296
 297            if let Some(stack_frame_id) = self.stack_frame_list.read(cx).opened_stack_frame_id() {
 298                session
 299                    .add_watcher(expression.into(), stack_frame_id, cx)
 300                    .detach();
 301            }
 302        });
 303    }
 304
 305    fn previous_query(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
 306        let prev = self.history.previous(&mut self.cursor);
 307        if let Some(prev) = prev {
 308            self.query_bar.update(cx, |editor, cx| {
 309                editor.set_text(prev, window, cx);
 310            });
 311        }
 312    }
 313
 314    fn next_query(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 315        let next = self.history.next(&mut self.cursor);
 316        let query = next.unwrap_or_else(|| {
 317            self.cursor.reset();
 318            ""
 319        });
 320
 321        self.query_bar.update(cx, |editor, cx| {
 322            editor.set_text(query, window, cx);
 323        });
 324    }
 325
 326    fn evaluate(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
 327        let expression = self.query_bar.update(cx, |editor, cx| {
 328            let expression = editor.text(cx);
 329            cx.defer_in(window, |editor, window, cx| {
 330                editor.clear(window, cx);
 331            });
 332
 333            expression
 334        });
 335
 336        self.history.add(&mut self.cursor, expression.clone());
 337        self.cursor.reset();
 338        self.session.update(cx, |session, cx| {
 339            session
 340                .evaluate(
 341                    expression,
 342                    Some(dap::EvaluateArgumentsContext::Repl),
 343                    self.stack_frame_list.read(cx).opened_stack_frame_id(),
 344                    None,
 345                    cx,
 346                )
 347                .detach();
 348        });
 349    }
 350
 351    fn render_submit_menu(
 352        &self,
 353        id: impl Into<ElementId>,
 354        keybinding_target: Option<FocusHandle>,
 355        cx: &App,
 356    ) -> impl IntoElement {
 357        PopoverMenu::new(id.into())
 358            .trigger(
 359                ui::ButtonLike::new_rounded_right("console-confirm-split-button-right")
 360                    .layer(ui::ElevationIndex::ModalSurface)
 361                    .size(ui::ButtonSize::None)
 362                    .child(
 363                        div()
 364                            .px_1()
 365                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
 366                    ),
 367            )
 368            .when(
 369                self.stack_frame_list
 370                    .read(cx)
 371                    .opened_stack_frame_id()
 372                    .is_some(),
 373                |this| {
 374                    this.menu(move |window, cx| {
 375                        Some(ContextMenu::build(window, cx, |context_menu, _, _| {
 376                            context_menu
 377                                .when_some(keybinding_target.clone(), |el, keybinding_target| {
 378                                    el.context(keybinding_target)
 379                                })
 380                                .action("Watch Expression", WatchExpression.boxed_clone())
 381                        }))
 382                    })
 383                },
 384            )
 385            .anchor(Corner::TopRight)
 386    }
 387
 388    fn render_console(&self, cx: &Context<Self>) -> impl IntoElement {
 389        EditorElement::new(&self.console, Self::editor_style(&self.console, cx))
 390    }
 391
 392    fn editor_style(editor: &Entity<Editor>, cx: &Context<Self>) -> EditorStyle {
 393        let is_read_only = editor.read(cx).read_only(cx);
 394        let settings = ThemeSettings::get_global(cx);
 395        let theme = cx.theme();
 396        let text_style = TextStyle {
 397            color: if is_read_only {
 398                theme.colors().text_muted
 399            } else {
 400                theme.colors().text
 401            },
 402            font_family: settings.buffer_font.family.clone(),
 403            font_features: settings.buffer_font.features.clone(),
 404            font_size: settings.buffer_font_size(cx).into(),
 405            font_weight: settings.buffer_font.weight,
 406            line_height: relative(settings.buffer_line_height.value()),
 407            ..Default::default()
 408        };
 409        EditorStyle {
 410            background: theme.colors().editor_background,
 411            local_player: theme.players().local(),
 412            text: text_style,
 413            ..Default::default()
 414        }
 415    }
 416
 417    fn render_query_bar(&self, cx: &Context<Self>) -> impl IntoElement {
 418        EditorElement::new(&self.query_bar, Self::editor_style(&self.query_bar, cx))
 419    }
 420
 421    pub(crate) fn update_output(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 422        if self.update_output_task.is_some() {
 423            return;
 424        }
 425        let session = self.session.clone();
 426        let token = self.last_token;
 427        self.update_output_task = Some(cx.spawn_in(window, async move |this, cx| {
 428            let Some((last_processed_token, task)) = session
 429                .update_in(cx, |session, window, cx| {
 430                    let (output, last_processed_token) = session.output(token);
 431
 432                    this.update(cx, |this, cx| {
 433                        if last_processed_token == this.last_token {
 434                            return None;
 435                        }
 436                        Some((
 437                            last_processed_token,
 438                            this.add_messages(output.cloned().collect(), window, cx),
 439                        ))
 440                    })
 441                    .ok()
 442                    .flatten()
 443                })
 444                .ok()
 445                .flatten()
 446            else {
 447                _ = this.update(cx, |this, _| {
 448                    this.update_output_task.take();
 449                });
 450                return;
 451            };
 452            _ = task.await.log_err();
 453            _ = this.update(cx, |this, _| {
 454                this.last_token = last_processed_token;
 455                this.update_output_task.take();
 456            });
 457        }));
 458    }
 459}
 460
 461impl Render for Console {
 462    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 463        let query_focus_handle = self.query_bar.focus_handle(cx);
 464        self.update_output(window, cx);
 465
 466        v_flex()
 467            .track_focus(&self.focus_handle)
 468            .key_context("DebugConsole")
 469            .on_action(cx.listener(Self::evaluate))
 470            .on_action(cx.listener(Self::watch_expression))
 471            .size_full()
 472            .border_2()
 473            .bg(cx.theme().colors().editor_background)
 474            .child(self.render_console(cx))
 475            .when(self.is_running(cx), |this| {
 476                this.child(Divider::horizontal()).child(
 477                    h_flex()
 478                        .on_action(cx.listener(Self::previous_query))
 479                        .on_action(cx.listener(Self::next_query))
 480                        .p_1()
 481                        .gap_1()
 482                        .bg(cx.theme().colors().editor_background)
 483                        .child(self.render_query_bar(cx))
 484                        .child(SplitButton::new(
 485                            ui::ButtonLike::new_rounded_all(ElementId::Name(
 486                                "split-button-left-confirm-button".into(),
 487                            ))
 488                            .on_click(move |_, window, cx| {
 489                                window.dispatch_action(Box::new(Confirm), cx)
 490                            })
 491                            .layer(ui::ElevationIndex::ModalSurface)
 492                            .size(ui::ButtonSize::Compact)
 493                            .child(Label::new("Evaluate"))
 494                            .tooltip({
 495                                let query_focus_handle = query_focus_handle.clone();
 496
 497                                move |_window, cx| {
 498                                    Tooltip::for_action_in(
 499                                        "Evaluate",
 500                                        &Confirm,
 501                                        &query_focus_handle,
 502                                        cx,
 503                                    )
 504                                }
 505                            }),
 506                            self.render_submit_menu(
 507                                ElementId::Name("split-button-right-confirm-button".into()),
 508                                Some(query_focus_handle.clone()),
 509                                cx,
 510                            )
 511                            .into_any_element(),
 512                        )),
 513                )
 514            })
 515    }
 516}
 517
 518impl Focusable for Console {
 519    fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
 520        self.focus_handle.clone()
 521    }
 522}
 523
 524struct ConsoleQueryBarCompletionProvider(WeakEntity<Console>);
 525
 526impl CompletionProvider for ConsoleQueryBarCompletionProvider {
 527    fn completions(
 528        &self,
 529        _excerpt_id: ExcerptId,
 530        buffer: &Entity<Buffer>,
 531        buffer_position: language::Anchor,
 532        _trigger: editor::CompletionContext,
 533        _window: &mut Window,
 534        cx: &mut Context<Editor>,
 535    ) -> Task<Result<Vec<CompletionResponse>>> {
 536        let Some(console) = self.0.upgrade() else {
 537            return Task::ready(Ok(Vec::new()));
 538        };
 539
 540        let support_completions = console
 541            .read(cx)
 542            .session
 543            .read(cx)
 544            .capabilities()
 545            .supports_completions_request
 546            .unwrap_or_default();
 547
 548        if support_completions {
 549            self.client_completions(&console, buffer, buffer_position, cx)
 550        } else {
 551            self.variable_list_completions(&console, buffer, buffer_position, cx)
 552        }
 553    }
 554
 555    fn apply_additional_edits_for_completion(
 556        &self,
 557        _buffer: Entity<Buffer>,
 558        _completions: Rc<RefCell<Box<[Completion]>>>,
 559        _completion_index: usize,
 560        _push_to_history: bool,
 561        _cx: &mut Context<Editor>,
 562    ) -> gpui::Task<anyhow::Result<Option<language::Transaction>>> {
 563        Task::ready(Ok(None))
 564    }
 565
 566    fn is_completion_trigger(
 567        &self,
 568        buffer: &Entity<Buffer>,
 569        position: language::Anchor,
 570        text: &str,
 571        trigger_in_words: bool,
 572        menu_is_open: bool,
 573        cx: &mut Context<Editor>,
 574    ) -> bool {
 575        let mut chars = text.chars();
 576        let char = if let Some(char) = chars.next() {
 577            char
 578        } else {
 579            return false;
 580        };
 581
 582        let snapshot = buffer.read(cx).snapshot();
 583        if !menu_is_open && !snapshot.settings_at(position, cx).show_completions_on_input {
 584            return false;
 585        }
 586
 587        let classifier = snapshot
 588            .char_classifier_at(position)
 589            .scope_context(Some(CharScopeContext::Completion));
 590        if trigger_in_words && classifier.is_word(char) {
 591            return true;
 592        }
 593
 594        self.0
 595            .read_with(cx, |console, cx| {
 596                console
 597                    .session
 598                    .read(cx)
 599                    .capabilities()
 600                    .completion_trigger_characters
 601                    .as_ref()
 602                    .map(|triggers| triggers.contains(&text.to_string()))
 603            })
 604            .ok()
 605            .flatten()
 606            .unwrap_or(true)
 607    }
 608}
 609
 610impl ConsoleQueryBarCompletionProvider {
 611    fn variable_list_completions(
 612        &self,
 613        console: &Entity<Console>,
 614        buffer: &Entity<Buffer>,
 615        buffer_position: language::Anchor,
 616        cx: &mut Context<Editor>,
 617    ) -> Task<Result<Vec<CompletionResponse>>> {
 618        let (variables, string_matches) = console.update(cx, |console, cx| {
 619            let mut variables = HashMap::default();
 620            let mut string_matches = Vec::default();
 621
 622            for variable in console.variable_list.update(cx, |variable_list, cx| {
 623                variable_list.completion_variables(cx)
 624            }) {
 625                if let Some(evaluate_name) = &variable.evaluate_name
 626                    && variables
 627                        .insert(evaluate_name.clone(), variable.value.clone())
 628                        .is_none()
 629                {
 630                    string_matches.push(StringMatchCandidate {
 631                        id: 0,
 632                        string: evaluate_name.clone(),
 633                        char_bag: evaluate_name.chars().collect(),
 634                    });
 635                }
 636
 637                if variables
 638                    .insert(variable.name.clone(), variable.value.clone())
 639                    .is_none()
 640                {
 641                    string_matches.push(StringMatchCandidate {
 642                        id: 0,
 643                        string: variable.name.clone(),
 644                        char_bag: variable.name.chars().collect(),
 645                    });
 646                }
 647            }
 648
 649            (variables, string_matches)
 650        });
 651
 652        let snapshot = buffer.read(cx).text_snapshot();
 653        let buffer_text = snapshot.text();
 654
 655        cx.spawn(async move |_, cx| {
 656            const LIMIT: usize = 10;
 657            let matches = fuzzy::match_strings(
 658                &string_matches,
 659                &buffer_text,
 660                true,
 661                true,
 662                LIMIT,
 663                &Default::default(),
 664                cx.background_executor().clone(),
 665            )
 666            .await;
 667
 668            let completions = matches
 669                .iter()
 670                .filter_map(|string_match| {
 671                    let variable_value = variables.get(&string_match.string)?;
 672
 673                    Some(project::Completion {
 674                        replace_range: Self::replace_range_for_completion(
 675                            &buffer_text,
 676                            buffer_position,
 677                            string_match.string.as_bytes(),
 678                            &snapshot,
 679                        ),
 680                        new_text: string_match.string.clone(),
 681                        label: CodeLabel::plain(string_match.string.clone(), None),
 682                        match_start: None,
 683                        snippet_deduplication_key: None,
 684                        icon_path: None,
 685                        documentation: Some(CompletionDocumentation::MultiLineMarkdown(
 686                            variable_value.into(),
 687                        )),
 688                        confirm: None,
 689                        source: project::CompletionSource::Custom,
 690                        insert_text_mode: None,
 691                    })
 692                })
 693                .collect::<Vec<_>>();
 694
 695            Ok(vec![project::CompletionResponse {
 696                is_incomplete: completions.len() >= LIMIT,
 697                display_options: CompletionDisplayOptions::default(),
 698                completions,
 699            }])
 700        })
 701    }
 702
 703    fn replace_range_for_completion(
 704        buffer_text: &String,
 705        buffer_position: Anchor,
 706        new_bytes: &[u8],
 707        snapshot: &TextBufferSnapshot,
 708    ) -> Range<Anchor> {
 709        let buffer_offset = buffer_position.to_offset(snapshot);
 710        let buffer_bytes = &buffer_text.as_bytes()[0..buffer_offset];
 711
 712        let mut prefix_len = 0;
 713        for i in (0..new_bytes.len()).rev() {
 714            if buffer_bytes.ends_with(&new_bytes[0..i]) {
 715                prefix_len = i;
 716                break;
 717            }
 718        }
 719
 720        let start = snapshot.clip_offset(buffer_offset - prefix_len, Bias::Left);
 721
 722        snapshot.anchor_before(start)..buffer_position
 723    }
 724
 725    const fn completion_type_score(completion_type: CompletionItemType) -> usize {
 726        match completion_type {
 727            CompletionItemType::Field | CompletionItemType::Property => 0,
 728            CompletionItemType::Variable | CompletionItemType::Value => 1,
 729            CompletionItemType::Method
 730            | CompletionItemType::Function
 731            | CompletionItemType::Constructor => 2,
 732            CompletionItemType::Class
 733            | CompletionItemType::Interface
 734            | CompletionItemType::Module => 3,
 735            _ => 4,
 736        }
 737    }
 738
 739    fn completion_item_sort_text(completion_item: &CompletionItem) -> String {
 740        completion_item.sort_text.clone().unwrap_or_else(|| {
 741            format!(
 742                "{:03}_{}",
 743                Self::completion_type_score(
 744                    completion_item.type_.unwrap_or(CompletionItemType::Text)
 745                ),
 746                completion_item.label.to_ascii_lowercase()
 747            )
 748        })
 749    }
 750
 751    fn client_completions(
 752        &self,
 753        console: &Entity<Console>,
 754        buffer: &Entity<Buffer>,
 755        buffer_position: language::Anchor,
 756        cx: &mut Context<Editor>,
 757    ) -> Task<Result<Vec<CompletionResponse>>> {
 758        let completion_task = console.update(cx, |console, cx| {
 759            console.session.update(cx, |state, cx| {
 760                let frame_id = console.stack_frame_list.read(cx).opened_stack_frame_id();
 761
 762                state.completions(
 763                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
 764                    cx,
 765                )
 766            })
 767        });
 768        let snapshot = buffer.read(cx).text_snapshot();
 769        cx.background_executor().spawn(async move {
 770            let completions = completion_task.await?;
 771
 772            let buffer_text = snapshot.text();
 773
 774            let completions = completions
 775                .into_iter()
 776                .map(|completion| {
 777                    let sort_text = Self::completion_item_sort_text(&completion);
 778                    let new_text = completion
 779                        .text
 780                        .as_ref()
 781                        .unwrap_or(&completion.label)
 782                        .to_owned();
 783
 784                    project::Completion {
 785                        replace_range: Self::replace_range_for_completion(
 786                            &buffer_text,
 787                            buffer_position,
 788                            new_text.as_bytes(),
 789                            &snapshot,
 790                        ),
 791                        new_text,
 792                        label: CodeLabel::plain(completion.label, None),
 793                        icon_path: None,
 794                        documentation: completion.detail.map(|detail| {
 795                            CompletionDocumentation::MultiLineMarkdown(detail.into())
 796                        }),
 797                        match_start: None,
 798                        snippet_deduplication_key: None,
 799                        confirm: None,
 800                        source: project::CompletionSource::Dap { sort_text },
 801                        insert_text_mode: None,
 802                    }
 803                })
 804                .collect();
 805
 806            Ok(vec![project::CompletionResponse {
 807                completions,
 808                display_options: CompletionDisplayOptions::default(),
 809                is_incomplete: false,
 810            }])
 811        })
 812    }
 813}
 814
 815#[derive(Default)]
 816struct ConsoleHandler {
 817    output: String,
 818    spans: Vec<(Range<usize>, Option<ansi::Color>)>,
 819    background_spans: Vec<(Range<usize>, Option<ansi::Color>)>,
 820    current_range_start: usize,
 821    current_background_range_start: usize,
 822    current_color: Option<ansi::Color>,
 823    current_background_color: Option<ansi::Color>,
 824    pos: usize,
 825}
 826
 827impl ConsoleHandler {
 828    fn break_span(&mut self, color: Option<ansi::Color>) {
 829        self.spans.push((
 830            self.current_range_start..self.output.len(),
 831            self.current_color,
 832        ));
 833        self.current_color = color;
 834        self.current_range_start = self.pos;
 835    }
 836
 837    fn break_background_span(&mut self, color: Option<ansi::Color>) {
 838        self.background_spans.push((
 839            self.current_background_range_start..self.output.len(),
 840            self.current_background_color,
 841        ));
 842        self.current_background_color = color;
 843        self.current_background_range_start = self.pos;
 844    }
 845}
 846
 847impl ansi::Handler for ConsoleHandler {
 848    fn input(&mut self, c: char) {
 849        self.output.push(c);
 850        self.pos += c.len_utf8();
 851    }
 852
 853    fn linefeed(&mut self) {
 854        self.output.push('\n');
 855        self.pos += 1;
 856    }
 857
 858    fn put_tab(&mut self, count: u16) {
 859        self.output
 860            .extend(std::iter::repeat('\t').take(count as usize));
 861        self.pos += count as usize;
 862    }
 863
 864    fn terminal_attribute(&mut self, attr: ansi::Attr) {
 865        match attr {
 866            ansi::Attr::Foreground(color) => {
 867                self.break_span(Some(color));
 868            }
 869            ansi::Attr::Background(color) => {
 870                self.break_background_span(Some(color));
 871            }
 872            ansi::Attr::Reset => {
 873                self.break_span(None);
 874                self.break_background_span(None);
 875            }
 876            _ => {}
 877        }
 878    }
 879}
 880
 881fn color_fetcher(color: ansi::Color) -> fn(&Theme) -> Hsla {
 882    let color_fetcher: fn(&Theme) -> Hsla = match color {
 883        // Named and theme defined colors
 884        ansi::Color::Named(n) => match n {
 885            ansi::NamedColor::Black => |theme| theme.colors().terminal_ansi_black,
 886            ansi::NamedColor::Red => |theme| theme.colors().terminal_ansi_red,
 887            ansi::NamedColor::Green => |theme| theme.colors().terminal_ansi_green,
 888            ansi::NamedColor::Yellow => |theme| theme.colors().terminal_ansi_yellow,
 889            ansi::NamedColor::Blue => |theme| theme.colors().terminal_ansi_blue,
 890            ansi::NamedColor::Magenta => |theme| theme.colors().terminal_ansi_magenta,
 891            ansi::NamedColor::Cyan => |theme| theme.colors().terminal_ansi_cyan,
 892            ansi::NamedColor::White => |theme| theme.colors().terminal_ansi_white,
 893            ansi::NamedColor::BrightBlack => |theme| theme.colors().terminal_ansi_bright_black,
 894            ansi::NamedColor::BrightRed => |theme| theme.colors().terminal_ansi_bright_red,
 895            ansi::NamedColor::BrightGreen => |theme| theme.colors().terminal_ansi_bright_green,
 896            ansi::NamedColor::BrightYellow => |theme| theme.colors().terminal_ansi_bright_yellow,
 897            ansi::NamedColor::BrightBlue => |theme| theme.colors().terminal_ansi_bright_blue,
 898            ansi::NamedColor::BrightMagenta => |theme| theme.colors().terminal_ansi_bright_magenta,
 899            ansi::NamedColor::BrightCyan => |theme| theme.colors().terminal_ansi_bright_cyan,
 900            ansi::NamedColor::BrightWhite => |theme| theme.colors().terminal_ansi_bright_white,
 901            ansi::NamedColor::Foreground => |theme| theme.colors().terminal_foreground,
 902            ansi::NamedColor::Background => |theme| theme.colors().terminal_background,
 903            ansi::NamedColor::Cursor => |theme| theme.players().local().cursor,
 904            ansi::NamedColor::DimBlack => |theme| theme.colors().terminal_ansi_dim_black,
 905            ansi::NamedColor::DimRed => |theme| theme.colors().terminal_ansi_dim_red,
 906            ansi::NamedColor::DimGreen => |theme| theme.colors().terminal_ansi_dim_green,
 907            ansi::NamedColor::DimYellow => |theme| theme.colors().terminal_ansi_dim_yellow,
 908            ansi::NamedColor::DimBlue => |theme| theme.colors().terminal_ansi_dim_blue,
 909            ansi::NamedColor::DimMagenta => |theme| theme.colors().terminal_ansi_dim_magenta,
 910            ansi::NamedColor::DimCyan => |theme| theme.colors().terminal_ansi_dim_cyan,
 911            ansi::NamedColor::DimWhite => |theme| theme.colors().terminal_ansi_dim_white,
 912            ansi::NamedColor::BrightForeground => |theme| theme.colors().terminal_bright_foreground,
 913            ansi::NamedColor::DimForeground => |theme| theme.colors().terminal_dim_foreground,
 914        },
 915        // 'True' colors
 916        ansi::Color::Spec(_) => |theme| theme.colors().editor_background,
 917        // 8 bit, indexed colors
 918        ansi::Color::Indexed(i) => {
 919            match i {
 920                // 0-15 are the same as the named colors above
 921                0 => |theme| theme.colors().terminal_ansi_black,
 922                1 => |theme| theme.colors().terminal_ansi_red,
 923                2 => |theme| theme.colors().terminal_ansi_green,
 924                3 => |theme| theme.colors().terminal_ansi_yellow,
 925                4 => |theme| theme.colors().terminal_ansi_blue,
 926                5 => |theme| theme.colors().terminal_ansi_magenta,
 927                6 => |theme| theme.colors().terminal_ansi_cyan,
 928                7 => |theme| theme.colors().terminal_ansi_white,
 929                8 => |theme| theme.colors().terminal_ansi_bright_black,
 930                9 => |theme| theme.colors().terminal_ansi_bright_red,
 931                10 => |theme| theme.colors().terminal_ansi_bright_green,
 932                11 => |theme| theme.colors().terminal_ansi_bright_yellow,
 933                12 => |theme| theme.colors().terminal_ansi_bright_blue,
 934                13 => |theme| theme.colors().terminal_ansi_bright_magenta,
 935                14 => |theme| theme.colors().terminal_ansi_bright_cyan,
 936                15 => |theme| theme.colors().terminal_ansi_bright_white,
 937                // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
 938                // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
 939                // 16..=231 => {
 940                //     let (r, g, b) = rgb_for_index(index as u8);
 941                //     rgba_color(
 942                //         if r == 0 { 0 } else { r * 40 + 55 },
 943                //         if g == 0 { 0 } else { g * 40 + 55 },
 944                //         if b == 0 { 0 } else { b * 40 + 55 },
 945                //     )
 946                // }
 947                // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
 948                // 232..=255 => {
 949                //     let i = index as u8 - 232; // Align index to 0..24
 950                //     let value = i * 10 + 8;
 951                //     rgba_color(value, value, value)
 952                // }
 953                // For compatibility with the alacritty::Colors interface
 954                // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
 955                _ => |_| gpui::black(),
 956            }
 957        }
 958    };
 959    color_fetcher
 960}
 961
 962#[cfg(test)]
 963mod tests {
 964    use super::*;
 965    use crate::tests::init_test;
 966    use editor::{MultiBufferOffset, test::editor_test_context::EditorTestContext};
 967    use gpui::TestAppContext;
 968    use language::Point;
 969
 970    #[track_caller]
 971    fn assert_completion_range(
 972        input: &str,
 973        expect: &str,
 974        replacement: &str,
 975        cx: &mut EditorTestContext,
 976    ) {
 977        cx.set_state(input);
 978
 979        let buffer_position = cx.editor(|editor, _, cx| {
 980            editor
 981                .selections
 982                .newest::<Point>(&editor.display_snapshot(cx))
 983                .start
 984        });
 985
 986        let snapshot = &cx.buffer_snapshot();
 987
 988        let replace_range = ConsoleQueryBarCompletionProvider::replace_range_for_completion(
 989            &cx.buffer_text(),
 990            snapshot.anchor_before(buffer_position),
 991            replacement.as_bytes(),
 992            snapshot,
 993        );
 994
 995        cx.update_editor(|editor, _, cx| {
 996            editor.edit(
 997                vec![(
 998                    MultiBufferOffset(snapshot.offset_for_anchor(&replace_range.start))
 999                        ..MultiBufferOffset(snapshot.offset_for_anchor(&replace_range.end)),
1000                    replacement,
1001                )],
1002                cx,
1003            );
1004        });
1005
1006        pretty_assertions::assert_eq!(expect, cx.display_text());
1007    }
1008
1009    #[gpui::test]
1010    async fn test_determine_completion_replace_range(cx: &mut TestAppContext) {
1011        init_test(cx);
1012
1013        let mut cx = EditorTestContext::new(cx).await;
1014
1015        assert_completion_range("resˇ", "result", "result", &mut cx);
1016        assert_completion_range("print(resˇ)", "print(result)", "result", &mut cx);
1017        assert_completion_range("$author->nˇ", "$author->name", "$author->name", &mut cx);
1018        assert_completion_range(
1019            "$author->books[ˇ",
1020            "$author->books[0]",
1021            "$author->books[0]",
1022            &mut cx,
1023        );
1024    }
1025}