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    HighlightKey, 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    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::{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, cx);
 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                    let buffer = console.buffer().read(cx).snapshot(cx);
 226
 227                    for (range, color) in spans {
 228                        let Some(color) = color else { continue };
 229                        let start_offset = range.start;
 230                        let range = buffer.anchor_after(MultiBufferOffset(range.start))
 231                            ..buffer.anchor_before(MultiBufferOffset(range.end));
 232                        let style = HighlightStyle {
 233                            color: Some(terminal_view::terminal_element::convert_color(
 234                                &color,
 235                                cx.theme(),
 236                            )),
 237                            ..Default::default()
 238                        };
 239                        console.highlight_text_key(
 240                            HighlightKey::ConsoleAnsiHighlight(start_offset),
 241                            vec![range],
 242                            style,
 243                            false,
 244                            cx,
 245                        );
 246                    }
 247
 248                    for (range, color) in background_spans {
 249                        let Some(color) = color else { continue };
 250                        let start_offset = range.start;
 251                        let range = buffer.anchor_after(MultiBufferOffset(range.start))
 252                            ..buffer.anchor_before(MultiBufferOffset(range.end));
 253                        let color_fn = color_fetcher(color);
 254                        console.highlight_background(
 255                            HighlightKey::ConsoleAnsiHighlight(start_offset),
 256                            &[range],
 257                            move |_, theme| color_fn(theme),
 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 is_completion_trigger(
 556        &self,
 557        buffer: &Entity<Buffer>,
 558        position: language::Anchor,
 559        text: &str,
 560        trigger_in_words: bool,
 561        cx: &mut Context<Editor>,
 562    ) -> bool {
 563        let mut chars = text.chars();
 564        let char = if let Some(char) = chars.next() {
 565            char
 566        } else {
 567            return false;
 568        };
 569
 570        let snapshot = buffer.read(cx).snapshot();
 571
 572        let classifier = snapshot
 573            .char_classifier_at(position)
 574            .scope_context(Some(CharScopeContext::Completion));
 575        if trigger_in_words && classifier.is_word(char) {
 576            return true;
 577        }
 578
 579        self.0
 580            .read_with(cx, |console, cx| {
 581                console
 582                    .session
 583                    .read(cx)
 584                    .capabilities()
 585                    .completion_trigger_characters
 586                    .as_ref()
 587                    .map(|triggers| triggers.contains(&text.to_string()))
 588            })
 589            .ok()
 590            .flatten()
 591            .unwrap_or(true)
 592    }
 593}
 594
 595impl ConsoleQueryBarCompletionProvider {
 596    fn variable_list_completions(
 597        &self,
 598        console: &Entity<Console>,
 599        buffer: &Entity<Buffer>,
 600        buffer_position: language::Anchor,
 601        cx: &mut Context<Editor>,
 602    ) -> Task<Result<Vec<CompletionResponse>>> {
 603        let (variables, string_matches) = console.update(cx, |console, cx| {
 604            let mut variables = HashMap::default();
 605            let mut string_matches = Vec::default();
 606
 607            for variable in console.variable_list.update(cx, |variable_list, cx| {
 608                variable_list.completion_variables(cx)
 609            }) {
 610                if let Some(evaluate_name) = &variable.evaluate_name
 611                    && variables
 612                        .insert(evaluate_name.clone(), variable.value.clone())
 613                        .is_none()
 614                {
 615                    string_matches.push(StringMatchCandidate {
 616                        id: 0,
 617                        string: evaluate_name.clone(),
 618                        char_bag: evaluate_name.chars().collect(),
 619                    });
 620                }
 621
 622                if variables
 623                    .insert(variable.name.clone(), variable.value.clone())
 624                    .is_none()
 625                {
 626                    string_matches.push(StringMatchCandidate {
 627                        id: 0,
 628                        string: variable.name.clone(),
 629                        char_bag: variable.name.chars().collect(),
 630                    });
 631                }
 632            }
 633
 634            (variables, string_matches)
 635        });
 636
 637        let snapshot = buffer.read(cx).text_snapshot();
 638        let buffer_text = snapshot.text();
 639
 640        cx.spawn(async move |_, cx| {
 641            const LIMIT: usize = 10;
 642            let matches = fuzzy::match_strings(
 643                &string_matches,
 644                &buffer_text,
 645                true,
 646                true,
 647                LIMIT,
 648                &Default::default(),
 649                cx.background_executor().clone(),
 650            )
 651            .await;
 652
 653            let completions = matches
 654                .iter()
 655                .filter_map(|string_match| {
 656                    let variable_value = variables.get(&string_match.string)?;
 657
 658                    Some(project::Completion {
 659                        replace_range: Self::replace_range_for_completion(
 660                            &buffer_text,
 661                            buffer_position,
 662                            string_match.string.as_bytes(),
 663                            &snapshot,
 664                        ),
 665                        new_text: string_match.string.clone(),
 666                        label: CodeLabel::plain(string_match.string.clone(), None),
 667                        match_start: None,
 668                        snippet_deduplication_key: None,
 669                        icon_path: None,
 670                        documentation: Some(CompletionDocumentation::MultiLineMarkdown(
 671                            variable_value.into(),
 672                        )),
 673                        confirm: None,
 674                        source: project::CompletionSource::Custom,
 675                        insert_text_mode: None,
 676                    })
 677                })
 678                .collect::<Vec<_>>();
 679
 680            Ok(vec![project::CompletionResponse {
 681                is_incomplete: completions.len() >= LIMIT,
 682                display_options: CompletionDisplayOptions::default(),
 683                completions,
 684            }])
 685        })
 686    }
 687
 688    fn replace_range_for_completion(
 689        buffer_text: &String,
 690        buffer_position: Anchor,
 691        new_bytes: &[u8],
 692        snapshot: &TextBufferSnapshot,
 693    ) -> Range<Anchor> {
 694        let buffer_offset = buffer_position.to_offset(snapshot);
 695        let buffer_bytes = &buffer_text.as_bytes()[0..buffer_offset];
 696
 697        let mut prefix_len = 0;
 698        for i in (0..new_bytes.len()).rev() {
 699            if buffer_bytes.ends_with(&new_bytes[0..i]) {
 700                prefix_len = i;
 701                break;
 702            }
 703        }
 704
 705        let start = snapshot.clip_offset(buffer_offset - prefix_len, Bias::Left);
 706
 707        snapshot.anchor_before(start)..buffer_position
 708    }
 709
 710    const fn completion_type_score(completion_type: CompletionItemType) -> usize {
 711        match completion_type {
 712            CompletionItemType::Field | CompletionItemType::Property => 0,
 713            CompletionItemType::Variable | CompletionItemType::Value => 1,
 714            CompletionItemType::Method
 715            | CompletionItemType::Function
 716            | CompletionItemType::Constructor => 2,
 717            CompletionItemType::Class
 718            | CompletionItemType::Interface
 719            | CompletionItemType::Module => 3,
 720            _ => 4,
 721        }
 722    }
 723
 724    fn completion_item_sort_text(completion_item: &CompletionItem) -> String {
 725        completion_item.sort_text.clone().unwrap_or_else(|| {
 726            format!(
 727                "{:03}_{}",
 728                Self::completion_type_score(
 729                    completion_item.type_.unwrap_or(CompletionItemType::Text)
 730                ),
 731                completion_item.label.to_ascii_lowercase()
 732            )
 733        })
 734    }
 735
 736    fn client_completions(
 737        &self,
 738        console: &Entity<Console>,
 739        buffer: &Entity<Buffer>,
 740        buffer_position: language::Anchor,
 741        cx: &mut Context<Editor>,
 742    ) -> Task<Result<Vec<CompletionResponse>>> {
 743        let completion_task = console.update(cx, |console, cx| {
 744            console.session.update(cx, |state, cx| {
 745                let frame_id = console.stack_frame_list.read(cx).opened_stack_frame_id();
 746
 747                state.completions(
 748                    CompletionsQuery::new(buffer.read(cx), buffer_position, frame_id),
 749                    cx,
 750                )
 751            })
 752        });
 753        let snapshot = buffer.read(cx).text_snapshot();
 754        cx.background_executor().spawn(async move {
 755            let completions = completion_task.await?;
 756
 757            let buffer_text = snapshot.text();
 758
 759            let completions = completions
 760                .into_iter()
 761                .map(|completion| {
 762                    let sort_text = Self::completion_item_sort_text(&completion);
 763                    let new_text = completion
 764                        .text
 765                        .as_ref()
 766                        .unwrap_or(&completion.label)
 767                        .to_owned();
 768
 769                    project::Completion {
 770                        replace_range: Self::replace_range_for_completion(
 771                            &buffer_text,
 772                            buffer_position,
 773                            new_text.as_bytes(),
 774                            &snapshot,
 775                        ),
 776                        new_text,
 777                        label: CodeLabel::plain(completion.label, None),
 778                        icon_path: None,
 779                        documentation: completion.detail.map(|detail| {
 780                            CompletionDocumentation::MultiLineMarkdown(detail.into())
 781                        }),
 782                        match_start: None,
 783                        snippet_deduplication_key: None,
 784                        confirm: None,
 785                        source: project::CompletionSource::Dap { sort_text },
 786                        insert_text_mode: None,
 787                    }
 788                })
 789                .collect();
 790
 791            Ok(vec![project::CompletionResponse {
 792                completions,
 793                display_options: CompletionDisplayOptions::default(),
 794                is_incomplete: false,
 795            }])
 796        })
 797    }
 798}
 799
 800#[derive(Default)]
 801struct ConsoleHandler {
 802    output: String,
 803    spans: Vec<(Range<usize>, Option<ansi::Color>)>,
 804    background_spans: Vec<(Range<usize>, Option<ansi::Color>)>,
 805    current_range_start: usize,
 806    current_background_range_start: usize,
 807    current_color: Option<ansi::Color>,
 808    current_background_color: Option<ansi::Color>,
 809    pos: usize,
 810}
 811
 812impl ConsoleHandler {
 813    fn break_span(&mut self, color: Option<ansi::Color>) {
 814        self.spans.push((
 815            self.current_range_start..self.output.len(),
 816            self.current_color,
 817        ));
 818        self.current_color = color;
 819        self.current_range_start = self.pos;
 820    }
 821
 822    fn break_background_span(&mut self, color: Option<ansi::Color>) {
 823        self.background_spans.push((
 824            self.current_background_range_start..self.output.len(),
 825            self.current_background_color,
 826        ));
 827        self.current_background_color = color;
 828        self.current_background_range_start = self.pos;
 829    }
 830}
 831
 832impl ansi::Handler for ConsoleHandler {
 833    fn input(&mut self, c: char) {
 834        self.output.push(c);
 835        self.pos += c.len_utf8();
 836    }
 837
 838    fn linefeed(&mut self) {
 839        self.output.push('\n');
 840        self.pos += 1;
 841    }
 842
 843    fn put_tab(&mut self, count: u16) {
 844        self.output
 845            .extend(std::iter::repeat('\t').take(count as usize));
 846        self.pos += count as usize;
 847    }
 848
 849    fn terminal_attribute(&mut self, attr: ansi::Attr) {
 850        match attr {
 851            ansi::Attr::Foreground(color) => {
 852                self.break_span(Some(color));
 853            }
 854            ansi::Attr::Background(color) => {
 855                self.break_background_span(Some(color));
 856            }
 857            ansi::Attr::Reset => {
 858                self.break_span(None);
 859                self.break_background_span(None);
 860            }
 861            _ => {}
 862        }
 863    }
 864}
 865
 866fn color_fetcher(color: ansi::Color) -> fn(&Theme) -> Hsla {
 867    let color_fetcher: fn(&Theme) -> Hsla = match color {
 868        // Named and theme defined colors
 869        ansi::Color::Named(n) => match n {
 870            ansi::NamedColor::Black => |theme| theme.colors().terminal_ansi_black,
 871            ansi::NamedColor::Red => |theme| theme.colors().terminal_ansi_red,
 872            ansi::NamedColor::Green => |theme| theme.colors().terminal_ansi_green,
 873            ansi::NamedColor::Yellow => |theme| theme.colors().terminal_ansi_yellow,
 874            ansi::NamedColor::Blue => |theme| theme.colors().terminal_ansi_blue,
 875            ansi::NamedColor::Magenta => |theme| theme.colors().terminal_ansi_magenta,
 876            ansi::NamedColor::Cyan => |theme| theme.colors().terminal_ansi_cyan,
 877            ansi::NamedColor::White => |theme| theme.colors().terminal_ansi_white,
 878            ansi::NamedColor::BrightBlack => |theme| theme.colors().terminal_ansi_bright_black,
 879            ansi::NamedColor::BrightRed => |theme| theme.colors().terminal_ansi_bright_red,
 880            ansi::NamedColor::BrightGreen => |theme| theme.colors().terminal_ansi_bright_green,
 881            ansi::NamedColor::BrightYellow => |theme| theme.colors().terminal_ansi_bright_yellow,
 882            ansi::NamedColor::BrightBlue => |theme| theme.colors().terminal_ansi_bright_blue,
 883            ansi::NamedColor::BrightMagenta => |theme| theme.colors().terminal_ansi_bright_magenta,
 884            ansi::NamedColor::BrightCyan => |theme| theme.colors().terminal_ansi_bright_cyan,
 885            ansi::NamedColor::BrightWhite => |theme| theme.colors().terminal_ansi_bright_white,
 886            ansi::NamedColor::Foreground => |theme| theme.colors().terminal_foreground,
 887            ansi::NamedColor::Background => |theme| theme.colors().terminal_background,
 888            ansi::NamedColor::Cursor => |theme| theme.players().local().cursor,
 889            ansi::NamedColor::DimBlack => |theme| theme.colors().terminal_ansi_dim_black,
 890            ansi::NamedColor::DimRed => |theme| theme.colors().terminal_ansi_dim_red,
 891            ansi::NamedColor::DimGreen => |theme| theme.colors().terminal_ansi_dim_green,
 892            ansi::NamedColor::DimYellow => |theme| theme.colors().terminal_ansi_dim_yellow,
 893            ansi::NamedColor::DimBlue => |theme| theme.colors().terminal_ansi_dim_blue,
 894            ansi::NamedColor::DimMagenta => |theme| theme.colors().terminal_ansi_dim_magenta,
 895            ansi::NamedColor::DimCyan => |theme| theme.colors().terminal_ansi_dim_cyan,
 896            ansi::NamedColor::DimWhite => |theme| theme.colors().terminal_ansi_dim_white,
 897            ansi::NamedColor::BrightForeground => |theme| theme.colors().terminal_bright_foreground,
 898            ansi::NamedColor::DimForeground => |theme| theme.colors().terminal_dim_foreground,
 899        },
 900        // 'True' colors
 901        ansi::Color::Spec(_) => |theme| theme.colors().editor_background,
 902        // 8 bit, indexed colors
 903        ansi::Color::Indexed(i) => {
 904            match i {
 905                // 0-15 are the same as the named colors above
 906                0 => |theme| theme.colors().terminal_ansi_black,
 907                1 => |theme| theme.colors().terminal_ansi_red,
 908                2 => |theme| theme.colors().terminal_ansi_green,
 909                3 => |theme| theme.colors().terminal_ansi_yellow,
 910                4 => |theme| theme.colors().terminal_ansi_blue,
 911                5 => |theme| theme.colors().terminal_ansi_magenta,
 912                6 => |theme| theme.colors().terminal_ansi_cyan,
 913                7 => |theme| theme.colors().terminal_ansi_white,
 914                8 => |theme| theme.colors().terminal_ansi_bright_black,
 915                9 => |theme| theme.colors().terminal_ansi_bright_red,
 916                10 => |theme| theme.colors().terminal_ansi_bright_green,
 917                11 => |theme| theme.colors().terminal_ansi_bright_yellow,
 918                12 => |theme| theme.colors().terminal_ansi_bright_blue,
 919                13 => |theme| theme.colors().terminal_ansi_bright_magenta,
 920                14 => |theme| theme.colors().terminal_ansi_bright_cyan,
 921                15 => |theme| theme.colors().terminal_ansi_bright_white,
 922                // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
 923                // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
 924                // 16..=231 => {
 925                //     let (r, g, b) = rgb_for_index(index as u8);
 926                //     rgba_color(
 927                //         if r == 0 { 0 } else { r * 40 + 55 },
 928                //         if g == 0 { 0 } else { g * 40 + 55 },
 929                //         if b == 0 { 0 } else { b * 40 + 55 },
 930                //     )
 931                // }
 932                // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
 933                // 232..=255 => {
 934                //     let i = index as u8 - 232; // Align index to 0..24
 935                //     let value = i * 10 + 8;
 936                //     rgba_color(value, value, value)
 937                // }
 938                // For compatibility with the alacritty::Colors interface
 939                // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
 940                _ => |_| gpui::black(),
 941            }
 942        }
 943    };
 944    color_fetcher
 945}
 946
 947#[cfg(test)]
 948mod tests {
 949    use super::*;
 950    use crate::tests::init_test;
 951    use editor::{MultiBufferOffset, test::editor_test_context::EditorTestContext};
 952    use gpui::TestAppContext;
 953    use language::Point;
 954
 955    #[track_caller]
 956    fn assert_completion_range(
 957        input: &str,
 958        expect: &str,
 959        replacement: &str,
 960        cx: &mut EditorTestContext,
 961    ) {
 962        cx.set_state(input);
 963
 964        let buffer_position = cx.editor(|editor, _, cx| {
 965            editor
 966                .selections
 967                .newest::<Point>(&editor.display_snapshot(cx))
 968                .start
 969        });
 970
 971        let snapshot = &cx.buffer_snapshot();
 972
 973        let replace_range = ConsoleQueryBarCompletionProvider::replace_range_for_completion(
 974            &cx.buffer_text(),
 975            snapshot.anchor_before(buffer_position),
 976            replacement.as_bytes(),
 977            snapshot,
 978        );
 979
 980        cx.update_editor(|editor, _, cx| {
 981            editor.edit(
 982                vec![(
 983                    MultiBufferOffset(snapshot.offset_for_anchor(&replace_range.start))
 984                        ..MultiBufferOffset(snapshot.offset_for_anchor(&replace_range.end)),
 985                    replacement,
 986                )],
 987                cx,
 988            );
 989        });
 990
 991        pretty_assertions::assert_eq!(expect, cx.display_text());
 992    }
 993
 994    #[gpui::test]
 995    async fn test_determine_completion_replace_range(cx: &mut TestAppContext) {
 996        init_test(cx);
 997
 998        let mut cx = EditorTestContext::new(cx).await;
 999
1000        assert_completion_range("resˇ", "result", "result", &mut cx);
1001        assert_completion_range("print(resˇ)", "print(result)", "result", &mut cx);
1002        assert_completion_range("$author->nˇ", "$author->name", "$author->name", &mut cx);
1003        assert_completion_range(
1004            "$author->books[ˇ",
1005            "$author->books[0]",
1006            "$author->books[0]",
1007            &mut cx,
1008        );
1009    }
1010}