Visual Studio Code, rebuilt in Rust
Rust
//! inlineCompletionsController.ts, inlineCompletionsModel.ts, inlineCompletionsSource.ts, provideInlineCompletions.ts,
//! ghostTextView.ts and controller/commands.ts for the providers extensions register: the completions at the cursor
//! are asked after typing (or explicitly), the selected one shows as ghost text, Tab accepts it.
// The AI parts (inline edits, next edit suggestions, the chat agent's completions) are removed by decision; a list
// item with `isInlineEdit` is dropped.
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
use gpui::{AnyElement, BoxShadow, ClickEvent, Context, Div, MouseButton, Size, Stateful, Task, Window, canvas, deferred, div, point, prelude::*, px, rgba};
use serde_json::{Value, json};
use super::Workbench;
use super::content_hover::{Anchor, Part, PartContent, Participant};
use super::content_hover_view::RADIUS;
use super::editor_message::layout_in_page;
use super::peek_view::UI_FONT;
use super::hover::{HoverContent, HoverOptions};
use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::menus::{ALWAYS_SHOW_INLINE_TOOLBAR, MenuAction, MenuId, menu_actions, menu_group_actions};
use super::editor_view::EDITOR_FONT;
use crate::commands::Outcome;
use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};
use crate::editor::{ContentChanged, EditReason, OpenEditor, Position, char_column, utf16_column};
use crate::ghost_text::{GhostText, GhostTextMode, Replacement, compute_ghost_text, end_positions_after_applying, inline_completion_is_visible, remove_common_prefix, remove_common_prefix_and_suffix, secondary_edits};
use crate::language_features::Candidate;
use crate::suggest::{CompletionItem, INSERT_AS_SNIPPET};
pub(super) const REGISTER: &str = "$registerInlineCompletionsSupport";
/// `InlineCompletionsDebounce` of the feature debounce service (`min: 50, max: 50`).
const DEBOUNCE: Duration = Duration::from_millis(50);
/// `InlineCompletionEndOfLifeReasonKind`.
const ACCEPTED: u64 = 0;
const REJECTED: u64 = 1;
const IGNORED: u64 = 2;
const SHOW_TOOLBAR: &str = "editor.inlineSuggest.showToolbar";
/// The ids the hover toolbar's "..." runs the list's commands by, followed by the command's index.
const LIST_COMMAND: &str = "inlineSuggestionHints.listCommand.";
#[derive(Default)]
pub(super) struct InlineCompletions {
model_id: Option<u32>,
/// `_isActive`: a trigger started the session; a stop ends it.
active: bool,
/// `inlineCompletions`: the items of the last answer without a suggest item.
items: Vec<Item>,
/// `suggestWidgetInlineCompletions`: the items of the last answer with one, the candidates that augment it.
suggest_widget_items: Vec<Item>,
/// The (handle, pid) of the lists the items came from, freed when replaced (`$freeInlineCompletionsList`).
lists: Vec<(u64, u64)>,
/// `_selectedInlineCompletionId`: the `semanticId` Alt+] and Alt+[ moved to; the first visible item otherwise.
selected: Option<Replacement>,
/// The model version both lists' edits are in; `createStateWithAppliedEdit` moves them through each edit since.
version: u32,
/// The item whose show the provider heard (`handleItemDidShow`).
shown: Option<(u64, u64, u64)>,
pub(super) request: Option<Task<()>>,
/// The `UpdateRequest` of the request in flight or answered last; a request it `satisfies` is not sent.
fetched: Option<Fetch>,
/// The Alt+] and Alt+[ steps waiting for the explicit request `_deltaSelectedInlineCompletionIndex` awaits.
cycle: isize,
/// The view zones of the ghost texts' additional lines and the lines each shows.
zones: Vec<(u32, Vec<String>)>,
/// `state`: the ghost text at each cursor, the primary one first; the injection ids number their parts in order.
ghosts: Vec<GhostText>,
/// `state.edits`: the edit behind each ghost text, applied together on accept.
edits: Vec<Replacement>,
/// `state.inlineSuggestion`: the item the ghost text shows; none for a suggest item's preview alone.
pub(super) ghost_item: Option<Item>,
/// `SuggestWidgetAdaptor.selectedItem`: the focused item of the visible suggest widget.
suggest_item: Option<SuggestItem>,
/// `isShiftKeyPressed`: the suggest item previews the other of insert and replace.
shift: bool,
/// `InlineCompletionsHintsWidget.position`: the primary ghost text's first column, the leftmost one while it
/// stays on its line.
hints_position: Option<Position>,
hints_size: Rc<Cell<Option<Size<f32>>>>,
}
#[derive(PartialEq)]
struct Fetch {
model_id: u32,
version: u32,
head: Position,
explicit: bool,
providers: Vec<u64>,
suggest: Option<SuggestItem>,
}
impl Fetch {
/// `UpdateRequest.satisfies`: an explicit request answers an automatic one too.
fn satisfies(&self, other: &Fetch) -> bool {
(self.model_id, self.version, self.head, &self.suggest) == (other.model_id, other.version, other.head, &other.suggest)
&& (!other.explicit || self.explicit)
&& other.providers.iter().all(|handle| self.providers.contains(handle))
}
}
/// `SuggestItemInfo`: the edit a suggest item makes at the cursor.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct SuggestItem {
edit: Replacement,
kind: u64,
is_snippet: bool,
list_incomplete: bool,
}
#[derive(Clone, Debug)]
pub(super) struct Item {
handle: u64,
pid: u64,
idx: u64,
edit: Replacement,
/// `_originalRange`: the range the provider gave, before the edits since moved it.
original: (Position, Position),
/// `forwardStable`: the list's `enableForwardStability`; its shown item stays first when it is asked again.
forward_stable: bool,
/// The list's `suppressSuggestions`: while it shows, the suggest widget does not open by itself.
suppress_suggestions: bool,
command: Value,
/// The list's `commands` (`activeCommands` of the selected item): `{ command, icon? }`.
list_commands: Vec<Value>,
/// `insertText.snippet`: the template the snippet controller inserts; `edit.text` is its plain text.
snippet: Option<String>,
additional_edits: Vec<(Position, Position, String)>,
}
impl Workbench {
/// `InlineCompletionSchemaContribution`: the `providerId` enum of the keybindings schema, each provider's
/// `extensionId:groupId` and `extensionId:*` (`inlineCompletionProviderGetMatcher`).
pub(super) fn inline_completion_providers_changed(&mut self) {
let mut matchers = Vec::new();
for registration in self.language_features.all(REGISTER) {
let extension = ®istration.extension_id;
let exact = match ®istration.group_id {
Some(group) => format!("{extension}:{group}"),
None => extension.to_owned(),
};
for matcher in [exact, format!("{extension}:*")] {
if !matchers.contains(&matcher) {
matchers.push(matcher);
}
}
}
self.settings.lock().unwrap().registry.inline_completion_providers = matchers;
}
pub(super) fn register_inline_completions(&mut self) {
self.commands.register("editor.action.inlineSuggest.trigger", |workbench, _, _, cx| {
workbench.inline_completions.active = true;
workbench.trigger_inline_completions(true, false, None, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.commit", |workbench, _, window, cx| {
workbench.accept_inline_completion(window, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.hide", |workbench, _, _, cx| {
workbench.stop_inline_completions(true, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.showNext", |workbench, _, _, cx| {
workbench.cycle_inline_completions(1, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.showPrevious", |workbench, _, _, cx| {
workbench.cycle_inline_completions(-1, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.acceptNextWord", |workbench, _, window, cx| {
workbench.accept_inline_completion_part(PartialKind::Word, window, cx);
Outcome::done()
});
self.commands.register("editor.action.inlineSuggest.acceptNextLine", |workbench, _, window, cx| {
workbench.accept_inline_completion_part(PartialKind::Line, window, cx);
Outcome::done()
});
self.commands.register(ALWAYS_SHOW_INLINE_TOOLBAR, |workbench, _, _, cx| {
let always = workbench.setting(SHOW_TOOLBAR) == "always";
workbench.update_setting(SHOW_TOOLBAR, json!(if always { "onHover" } else { "always" }));
workbench.ask_explicitly_for_the_hints(cx);
cx.notify();
Outcome::done()
});
}
/// `triggerExplicitly`.
pub(super) fn trigger_inline_completions_explicitly(&mut self, cx: &mut Context<Self>) {
self.inline_completions.active = true;
self.trigger_inline_completions(true, false, None, cx);
}
/// `inlineSuggestionVisible`, `inlineSuggestionHasIndentation`, `inlineSuggestionHasIndentationLessThanTabSize`,
/// `editor.hasSelection` and `cursorBeforeGhostText`.
pub(super) fn inline_completions_context(&self, context: &mut std::collections::HashMap<String, Value>) {
let ghost = self.inline_completions.ghosts.first().filter(|ghost| !ghost.is_empty());
context.insert("inlineSuggestionVisible".into(), json!(ghost.is_some()));
let Some(editor) = self.editors.active() else { return };
context.insert("editor.hasSelection".into(), json!(editor.selections.iter().any(|selection| !selection.is_empty())));
// `cursorBeforeGhostText`: the cursor sits where the first ghost text part starts.
let head = editor.selection().head;
context.insert("cursorBeforeGhostText".into(), json!(ghost.is_some_and(|ghost| ghost.line == head.line && ghost.parts[0].column == head.column)));
// `getIndentationInfo`: the ghost text starts in the line's indentation, and how its indentation compares
// to the tab size.
let (starts_with_indentation, less_than_tab_size) = ghost.map_or((false, true), |ghost| {
let line = &editor.document().lines[ghost.line];
let first = line.chars().position(|c| c != ' ' && c != '\t').unwrap_or(line.chars().count());
let part = &ghost.parts[0];
let in_indentation = part.column <= first;
let text: String = line.chars().take(part.column).collect::<String>() + &part.text;
let indentation = text.chars().take_while(|c| *c == ' ' || *c == '\t').fold(0, |visible, c| if c == '\t' { visible + editor.document().indentation.tab_size - visible % editor.document().indentation.tab_size } else { visible + 1 });
(in_indentation, !in_indentation || indentation < editor.document().indentation.tab_size || first < part.column)
});
context.insert("inlineSuggestionHasIndentation".into(), json!(starts_with_indentation));
context.insert("inlineSuggestionHasIndentationLessThanTabSize".into(), json!(less_than_tab_size));
}
pub(super) fn inline_completion_handles(&self, editor: &OpenEditor) -> Vec<(u64, Option<u64>)> {
let uri = editor.document().uri();
let language = editor.document().language_id.clone();
let candidate = Candidate { uri: &uri, language: &language };
self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| (registration.handle, registration.debounce_delay_ms)).collect()
}
/// `createStateWithAppliedEdit`, then the refetch of a text change: typing (`onDidType`) and the edits of the
/// controller's `triggerCommands` start a session or ask again, any other edit asks again while a session runs.
pub(super) fn inline_completions_edited(&mut self, change: &ContentChanged, source: &str, cx: &mut Context<Self>) {
self.rebase_inline_completions();
self.update_ghost_text(cx);
let Some(editor) = self.editors.active() else { return };
let triggers = matches!(source, "keyboard" | "tab" | "deleteLeft" | "deleteRight" | "editor.action.insertLineAfter" | "editor.action.insertLineBefore");
let starts = match triggers {
true => self.suggest_setting(editor, "editor.inlineSuggest.enabled") != json!(false),
false => self.inline_completions.active,
};
if !starts {
return;
}
// `_preserveCurrentCompletionReasons`: undo, redo and a partial accept keep the shown item first.
let preserve_current = change.is_undoing || change.is_redoing || source == "inlineSuggestion.accept";
self.inline_completions.active = true;
self.trigger_inline_completions(false, preserve_current, None, cx);
}
/// Moves the items' edits through the model's edits since `version`; without the log of them the items go.
fn rebase_inline_completions(&mut self) {
let Some(editor) = self.editors.active() else { return };
let model = editor.text_model();
let seen = self.inline_completions.version;
if model.version_id == seen {
return;
}
if !model.edits.first().is_some_and(|(version, ..)| *version <= seen) {
self.inline_completions.items.clear();
self.inline_completions.suggest_widget_items.clear();
}
for &(_, start, end, new_end, _) in model.edits.iter().filter(|(version, ..)| *version >= seen) {
for item in self.inline_completions.items.iter_mut().chain(&mut self.inline_completions.suggest_widget_items) {
item.edit = rebased(&item.edit, start, end, new_end);
}
}
self.inline_completions.version = model.version_id;
}
/// `onDidChangeInlineCompletions` of a provider (`$emitInlineCompletionsChange`): it alone is asked again with its
/// change hint, unless the ghost text shows another provider's completion.
pub(crate) fn inline_completions_provider_changed(&mut self, handle: u64, change_hint: Value, cx: &mut Context<Self>) {
let Some(editor) = self.editors.active() else { return };
if self.suggest_setting(editor, "editor.inlineSuggest.enabled") == json!(false) {
return;
}
if !self.inline_completions.ghosts.is_empty() && self.selected_item().is_some_and(|item| item.handle != handle) {
return;
}
self.inline_completions.active = true;
self.trigger_inline_completions(false, false, Some((handle, change_hint)), cx);
}
/// `onDidChangeCursorPosition` by the user or the API without an edit: a shown ghost text stops.
pub(super) fn inline_completions_cursor_moved(&mut self, cx: &mut Context<Self>) {
if !self.inline_completions.active {
return;
}
if !self.inline_completions.ghosts.is_empty() {
self.stop_inline_completions(false, cx);
} else {
self.update_ghost_text(cx);
}
}
/// Another model: the session stops.
pub(super) fn inline_completions_model_changed(&mut self, cx: &mut Context<Self>) {
let model_id = self.editors.active().map(|editor| editor.model_id);
if model_id != self.inline_completions.model_id {
self.stop_inline_completions(false, cx);
self.inline_completions.model_id = model_id;
}
}
/// `trigger` and `_fetchInlineCompletionsPromise`: after the debounce (none for an explicit request) every
/// provider is asked at the cursor, or only the `provider` that changed, with its change hint. The selected item
/// is preserved for the answer when `preserve_current`, explicit or forward stable (`itemToPreserve`).
fn trigger_inline_completions(&mut self, explicit: bool, preserve_current: bool, provider: Option<(u64, Value)>, cx: &mut Context<Self>) {
let Some(editor) = self.editors.active() else { return };
let suggest = self.inline_completions.suggest_item.clone().filter(|_| !self.show_on_suggest_conflict(editor));
// `seedInlineCompletionsWithSuggestWidget`: an answer to one list empties the other, so these are the newer.
if suggest.is_none() && !self.inline_completions.suggest_widget_items.is_empty() {
self.inline_completions.items = std::mem::take(&mut self.inline_completions.suggest_widget_items);
}
let preserve = self.selected_item().filter(|item| explicit || preserve_current || item.forward_stable).map(|item| (item.handle, item.pid, item.idx));
let Some(editor) = self.editors.active() else { return };
let mut providers = self.inline_completion_handles(editor);
let mut change_hint = Value::Null;
if let Some((handle, hint)) = provider {
providers.retain(|(provider, _)| *provider == handle);
change_hint = hint;
}
self.inline_completions.model_id = Some(editor.model_id);
if providers.is_empty() {
return;
}
let model_id = editor.model_id;
let version = editor.text_model().version_id;
let for_suggest_widget = suggest.is_some();
let fetch = Fetch { model_id, version, head: editor.selection().head, explicit, providers: providers.iter().map(|(handle, _)| *handle).collect(), suggest };
if self.inline_completions.fetched.as_ref().is_some_and(|fetched| fetched.satisfies(&fetch)) {
return;
}
self.inline_completions.fetched = Some(fetch);
// `debounceDelayMs` of the providers, the feature's otherwise.
let delay = match explicit {
true => Duration::ZERO,
false => providers.iter().filter_map(|(_, debounce)| *debounce).max().map_or(DEBOUNCE, Duration::from_millis),
};
self.inline_completions.request = Some(cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(delay).await;
let Ok(calls) = workbench.update(cx, |workbench, _| workbench.request_inline_completions(model_id, explicit, &change_hint, &providers)) else { return };
let mut lists = Vec::new();
for (handle, call) in calls {
if let Ok(Ok(list)) = call.await
&& !list.is_null()
{
lists.push((handle, list));
}
}
let _ = workbench.update(cx, |workbench, cx| {
workbench.inline_completions.request = None;
let current = workbench.editors.active().is_some_and(|editor| editor.model_id == model_id && editor.text_model().version_id == version);
if !current || !(workbench.inline_completions.active || workbench.inline_completions.suggest_item.is_some()) {
for (handle, list) in &lists {
workbench.free_inline_completion_list(*handle, list["pid"].as_u64().unwrap_or_default(), "lostRace");
}
workbench.inline_completions.cycle = 0;
workbench.quick_suggest_inline_completions_changed(cx);
return;
}
workbench.set_inline_completion_lists(lists, for_suggest_widget, preserve, cx);
workbench.select_cycled_inline_completion(cx);
});
}));
}
fn request_inline_completions(&self, model_id: u32, explicit: bool, change_hint: &Value, providers: &[(u64, Option<u64>)]) -> Vec<(u64, futures::channel::oneshot::Receiver<Result<Value, Value>>)> {
let Some(editor) = self.editors.active().filter(|editor| editor.model_id == model_id) else { return Vec::new() };
let uri = editor.document().uri();
let head = editor.selection().head;
let position = json!({ "lineNumber": head.line + 1, "column": utf16_column(&editor.document().lines[head.line], head.column) + 1 });
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |time| time.as_millis() as u64);
let min_show_delay = self.suggest_setting(editor, "editor.inlineSuggest.minShowDelay").as_u64().unwrap_or(0);
let mut context = json!({
"triggerKind": if explicit { 1 } else { 0 },
"includeInlineCompletions": true,
"includeInlineEdits": false,
"requestIssuedDateTime": now,
"earliestShownDateTime": now + if explicit { 0 } else { min_show_delay },
"requestUuid": format!("icr-{now}"),
});
if !change_hint.is_null() {
context["changeHint"] = change_hint.clone();
}
if let Some(item) = self.inline_completions.suggest_item.as_ref().filter(|_| !self.show_on_suggest_conflict(editor)) {
let lines = &editor.document().lines;
let column = |position: Position| utf16_column(&lines[position.line], position.column) + 1;
let range = json!({ "startLineNumber": item.edit.start.line + 1, "startColumn": column(item.edit.start), "endLineNumber": item.edit.end.line + 1, "endColumn": column(item.edit.end) });
context["selectedSuggestionInfo"] = json!({ "range": range, "text": item.edit.text, "completionKind": item.kind, "isSnippetText": item.is_snippet });
}
providers.iter().map(|(handle, _)| (*handle, self.host.call_cancellable("ExtHostLanguageFeatures", "$provideInlineCompletions", vec![json!(handle), uri.clone(), position.clone(), context.clone()]))).collect()
}
/// `createStateWithAppliedResults`: the items of the new lists, the item to preserve first while it can be reused
/// at the cursor, replace the list the request was for and empty the other; the old lists are freed, but the
/// preserved item's.
fn set_inline_completion_lists(&mut self, lists: Vec<(u64, Value)>, for_suggest_widget: bool, preserve: Option<(u64, u64, u64)>, cx: &mut Context<Self>) {
let Some(editor) = self.editors.active() else { return };
let lines = editor.document().lines.clone();
let head = editor.selection().head;
// `getDefaultRange`: from the word's start to the line end.
let word_start = editor.document().word_at(&self.languages, head.line, head.column).map_or(head.column, |word| word.start);
let default_range = (Position::new(head.line, word_start), Position::new(head.line, lines[head.line].chars().count()));
let mut items = Vec::new();
let mut list_ids = Vec::new();
for (handle, list) in &lists {
let pid = list["pid"].as_u64().unwrap_or_default();
let forward_stable = list["enableForwardStability"] == json!(true);
let suppress_suggestions = list["suppressSuggestions"] == json!(true);
let list_commands = list["commands"].as_array().cloned().unwrap_or_default();
list_ids.push((*handle, pid));
for completion in list["items"].as_array().into_iter().flatten() {
if completion["isInlineEdit"] == json!(true) {
continue;
}
if let Some(item) = completion_item(&lines, default_range, editor.document().indentation, *handle, pid, completion) {
items.push(Item { forward_stable, suppress_suggestions, list_commands: list_commands.clone(), ..item });
}
}
}
let version = editor.text_model().version_id;
let target = match for_suggest_widget {
true => &self.inline_completions.suggest_widget_items,
false => &self.inline_completions.items,
};
let preserved = preserve.and_then(|id| target.iter().find(|item| (item.handle, item.pid, item.idx) == id)).filter(|item| can_be_reused(item, &lines, head)).cloned();
if let Some(preserved) = preserved {
match items.iter().position(|item| item.edit == preserved.edit) {
Some(index) => items[..=index].rotate_right(1),
None => {
list_ids.push((preserved.handle, preserved.pid));
items.insert(0, preserved);
}
}
}
let old = std::mem::replace(&mut self.inline_completions.lists, list_ids);
let (target, other) = match for_suggest_widget {
true => (&mut self.inline_completions.suggest_widget_items, &mut self.inline_completions.items),
false => (&mut self.inline_completions.items, &mut self.inline_completions.suggest_widget_items),
};
*target = items;
other.clear();
self.inline_completions.version = version;
for (handle, pid) in old {
if !self.inline_completions.lists.contains(&(handle, pid)) {
self.free_inline_completion_list(handle, pid, "tokenCancellation");
}
}
self.update_ghost_text(cx);
}
fn free_inline_completion_list(&self, handle: u64, pid: u64, reason: &str) {
self.host.send("ExtHostLanguageFeatures", "$freeInlineCompletionsList", vec![json!(handle), json!(pid), json!({ "kind": reason })]);
}
/// The items whose edit shows at the cursor (`inlineCompletionIsVisible`) with their `semanticId`, the edit without
/// its common prefix and suffix; one item per `semanticId` (inlineCompletionsSource.ts `distinctByKey`).
fn visible_items(&self) -> Vec<(Replacement, &Item)> {
let Some(editor) = self.editors.active() else { return Vec::new() };
let lines = &editor.document().lines;
let head = editor.selection().head;
let mut visible: Vec<(Replacement, &Item)> = Vec::new();
for item in &self.inline_completions.items {
let semantic_id = remove_common_prefix_and_suffix(&item.edit, lines);
if inline_completion_is_visible(&item.edit, Some(item.original.0), lines, head) && !visible.iter().any(|(other, _)| *other == semantic_id) {
visible.push((semantic_id, item));
}
}
visible
}
fn selected_item(&self) -> Option<Item> {
let visible = self.visible_items();
let selected = visible.iter().find(|(id, _)| Some(id) == self.inline_completions.selected.as_ref());
selected.or(visible.first()).map(|(_, item)| (*item).clone())
}
/// `state`: the selected item's ghost text in `editor.inlineSuggest` mode (`subwordSmart`) at each cursor its edit
/// repeats at, drawn as injected text on its line and a view zone for its other lines.
fn update_ghost_text(&mut self, cx: &mut Context<Self>) {
// `selectedInlineCompletionIndex`: a selection no visible item has resets, so it does not jump back later.
if let Some(selected) = &self.inline_completions.selected
&& !self.visible_items().iter().any(|(id, _)| id == selected)
{
self.inline_completions.selected = None;
}
let (edits, ghosts, item) = self.current_ghost_texts();
self.inline_completions.edits = edits;
self.inline_completions.ghost_item = item;
if ghosts == self.inline_completions.ghosts {
self.quick_suggest_inline_completions_changed(cx);
return;
}
let first = ghosts.first().filter(|ghost| !ghost.parts.is_empty()).map(|ghost| Position::new(ghost.line, ghost.parts[0].column));
self.inline_completions.hints_position = match (first, self.inline_completions.hints_position) {
(Some(first), Some(session)) if session.line == first.line => Some(Position::new(first.line, first.column.min(session.column))),
(first, _) => first,
};
self.inline_completions.ghosts = ghosts.clone();
let line_height = self.editors.viewport.line_height;
let Some(editor) = self.editors.active_mut() else { return };
for (zone, _) in std::mem::take(&mut self.inline_completions.zones) {
editor.remove_view_zone(zone);
}
let mut injections = Vec::new();
for ghost in &ghosts {
let mut extra_lines: Vec<String> = Vec::new();
for part in &ghost.parts {
let mut part_lines = part.text.split('\n');
let first = part_lines.next().unwrap_or_default();
injections.push(InjectedText { position: Position::new(ghost.line, part.column), columns: first.chars().count() as f32, content: first.into(), wrap: WrapWidth::Chars, owner: InjectionOwner::GhostText, id: injections.len(), at_range_start: false });
extra_lines.extend(part_lines.map(String::from));
}
// `additionalLinesOriginalSuffix`: the rest of the line after a multi-line ghost text moves to its last line.
if !extra_lines.is_empty() {
let line_end = editor.document().lines[ghost.line].chars().count();
let zone = editor.add_view_zone(Some(Position::new(ghost.line, line_end)), extra_lines.len() as f32 * line_height);
self.inline_completions.zones.push((zone, extra_lines));
}
}
editor.set_injected_text(InjectionOwner::GhostText, injections);
if let Some(item) = self.inline_completions.ghost_item.clone() {
let key = (item.handle, item.pid, item.idx);
if self.inline_completions.shown != Some(key) {
self.inline_completions.shown = Some(key);
// `handleItemDidShow` with the text the ghost text shows.
self.host.send("ExtHostLanguageFeatures", "$handleInlineCompletionDidShow", vec![json!(item.handle), json!(item.pid), json!(item.idx), json!(item.edit.text)]);
}
}
cx.notify();
self.quick_suggest_inline_completions_changed(cx);
self.ask_explicitly_for_the_hints(cx);
}
/// inlineCompletionsHintsWidget.ts "request explicit": the always shown toolbar's count needs every item.
fn ask_explicitly_for_the_hints(&mut self, cx: &mut Context<Self>) {
let Some(editor) = self.editors.active() else { return };
let shown = self.inline_completions.hints_position.is_some() && self.suggest_setting(editor, SHOW_TOOLBAR) == "always";
if shown && !self.inline_completions.fetched.as_ref().is_some_and(|fetched| fetched.explicit) {
self.trigger_inline_completions_explicitly(cx);
}
}
/// `canShowQuickSuggest`: a visible inline suggestion (`inlineSuggestionVisible`) lets the suggest widget open by
/// itself unless its list sets `suppressSuggestions`.
pub(super) fn can_show_quick_suggest(&self) -> bool {
self.inline_completions.ghost_item.as_ref().is_none_or(|item| !item.suppress_suggestions)
}
/// The edits, ghost texts and item of `state`: the suggest item's edit, previewed with `editor.suggest.preview` or
/// carried on by the item that augments it, else the selected item's edit; each with its `getSecondaryEdits` at
/// the other cursors and kept where its ghost text shows; nothing when the primary one does not.
fn current_ghost_texts(&self) -> (Vec<Replacement>, Vec<GhostText>, Option<Item>) {
let Some(editor) = self.editors.active() else { return Default::default() };
if self.suggest_setting(editor, "editor.inlineSuggest.suppressInSnippetMode") != json!(false) && editor.snippet_session.is_some() {
return Default::default();
}
let lines = &editor.document().lines;
let ghost_mode = |key: &str| match self.suggest_setting(editor, key).as_str() {
Some("prefix") => GhostTextMode::Prefix,
Some("subword") => GhostTextMode::Subword,
_ => GhostTextMode::SubwordSmart,
};
let (edit, item, mode, preview_length) = match self.inline_completions.suggest_item.as_ref().filter(|_| !self.show_on_suggest_conflict(editor)) {
Some(suggest) => {
let suggest_edit = remove_common_prefix(&suggest.edit, lines);
let augmentation = self.augmentation(&suggest_edit, lines);
if self.suggest_setting(editor, "editor.suggest.preview") != json!(true) && augmentation.is_none() {
return Default::default();
}
let preview_length = augmentation.as_ref().map_or(0, |(_, edit)| edit.text.chars().count() - suggest_edit.text.chars().count());
let (item, edit) = augmentation.map_or((None, suggest_edit), |(item, edit)| (Some(item), edit));
(edit, item, ghost_mode("editor.suggest.previewMode"), preview_length)
}
None => {
let Some(item) = self.selected_item().filter(|_| self.inline_completions.active) else { return Default::default() };
(item.edit.clone(), Some(item), ghost_mode("editor.inlineSuggest.mode"), 0)
}
};
let positions: Vec<Position> = editor.selections.iter().map(|selection| selection.end()).collect();
let mut all_edits = vec![edit.clone()];
all_edits.extend(secondary_edits(lines, &positions, &edit));
let (mut edits, mut ghosts) = (Vec::new(), Vec::new());
// Upstream pairs the filtered secondary edits with `positions[idx]` too.
for (edit, position) in all_edits.into_iter().zip(&positions) {
if let Some(ghost) = compute_ghost_text(&edit, lines, mode, Some(*position), preview_length) {
edits.push(edit);
ghosts.push(ghost);
}
}
if ghosts.first().is_none_or(|ghost| ghost.parts.is_empty()) {
return Default::default();
}
(edits, ghosts, item)
}
/// `_computeAugmentation`: the first item whose edit, less the prefix it shares with the text up to the suggest
/// edit's end, starts where the suggest edit does, covers it and continues its text.
fn augmentation(&self, suggest_edit: &Replacement, lines: &[String]) -> Option<(Item, Replacement)> {
for item in &self.inline_completions.suggest_widget_items {
if suggest_edit.end < item.edit.start {
continue;
}
let clipped = Replacement { start: item.edit.start, end: item.edit.end.min(suggest_edit.end), text: item.edit.text.clone() };
let trimmed = remove_common_prefix(&clipped, lines);
let edit = Replacement { start: trimmed.start, end: item.edit.end, text: trimmed.text };
// `singleTextEditAugments`
if edit.text.starts_with(&suggest_edit.text) && edit.start == suggest_edit.start && suggest_edit.end <= edit.end {
return Some((item.clone(), edit));
}
}
None
}
/// `_shouldShowOnSuggestConflict` of `editor.inlineSuggest.experimental.showOnSuggestConflict`: an inline
/// completion shows over the suggest widget.
fn show_on_suggest_conflict(&self, editor: &OpenEditor) -> bool {
let Some(suggest) = self.inline_completions.suggest_item.as_ref().filter(|_| self.selected_item().is_some()) else { return false };
match self.suggest_setting(editor, "editor.inlineSuggest.experimental.showOnSuggestConflict").as_str() {
Some("always") => true,
Some("whenSuggestListIsIncomplete") => suggest.list_incomplete,
_ => false,
}
}
/// `SuggestWidgetAdaptor.update`: another focused suggest item asks the providers with it, while inline
/// suggestions are enabled or a session runs, and its preview shows.
pub(super) fn inline_completions_suggest_changed(&mut self, cx: &mut Context<Self>) {
let item = self.focused_suggestion().filter(|_| self.suggest_widget_visible()).map(|item| self.suggest_item_info(item, self.inline_completions.shift));
if item == self.inline_completions.suggest_item {
return;
}
self.inline_completions.suggest_item = item;
let Some(editor) = self.editors.active() else { return };
let enabled = self.suggest_setting(editor, "editor.inlineSuggest.enabled") != json!(false);
match (enabled && self.inline_completions.suggest_item.is_some()) || self.inline_completions.active {
true => self.trigger_inline_completions(false, false, None, cx),
false => self.inline_completions.request = None,
}
self.update_ghost_text(cx);
}
/// The editor's keydown and keyup of Shift while the suggest widget shows.
pub(super) fn inline_completions_modifiers_changed(&mut self, shift: bool, cx: &mut Context<Self>) {
if shift != self.inline_completions.shift {
self.inline_completions.shift = shift;
self.inline_completions_suggest_changed(cx);
}
}
/// `SuggestItemInfo.fromSuggestion`: a snippet's text with the line's indentation, over the chars `getOverwriteInfo`
/// gives around the cursor.
pub(super) fn suggest_item_info(&self, item: &CompletionItem, toggle_mode: bool) -> SuggestItem {
let editor = self.editors.active().expect("the suggest widget shows in the active editor");
let head = editor.selection().head;
let line = &editor.document().lines[head.line];
let is_snippet = item.insert_text_rules & INSERT_AS_SNIPPET != 0;
let text = match is_snippet {
true => {
let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
crate::editor::expand_snippet(&item.insert_text, &indent, true, editor.document().indentation, |_| None).text
}
false => item.insert_text.clone(),
};
let (before, after) = self.suggest_overwrite(item, toggle_mode);
let length = line.chars().count() as isize;
let column = |column: isize| Position::new(head.line, column.clamp(0, length) as usize);
let edit = Replacement { start: column(head.column as isize - before), end: column(head.column as isize + after.max(0)), text };
SuggestItem { edit, kind: item.kind, is_snippet, list_incomplete: item.incomplete }
}
/// The suggest controller's preselector: the suggest item with the longest text that the selected item's edit
/// augments.
pub(super) fn inline_completion_preselect(&self, items: &[CompletionItem]) -> Option<usize> {
let editor = self.editors.active()?;
let lines = &editor.document().lines;
let selected = remove_common_prefix(&self.selected_item()?.edit, lines);
let mut best: Option<(usize, usize)> = None;
for (index, item) in items.iter().enumerate() {
let edit = remove_common_prefix(&self.suggest_item_info(item, self.inline_completions.shift).edit, lines);
let length = edit.text.encode_utf16().count();
let augments = selected.text.starts_with(&edit.text) && edit.start == selected.start && edit.end <= selected.end;
if augments && length > 0 && best.is_none_or(|(_, best)| length > best) {
best = Some((index, length));
}
}
best.map(|(index, _)| index)
}
/// `handleSuggestAccepted`: the item the accepted suggest item's edit augments hears it as a partial accept.
pub(super) fn inline_completions_suggest_accepted(&self, item: &CompletionItem) {
let Some(editor) = self.editors.active() else { return };
let lines = &editor.document().lines;
let edit = remove_common_prefix(&self.suggest_item_info(item, self.inline_completions.shift).edit, lines);
let Some((completion, _)) = self.augmentation(&edit, lines) else { return };
let characters = edit.text.encode_utf16().count();
let already_accepted = crate::editor::text_between(lines, completion.edit.start, completion.edit.end).encode_utf16().count();
let info = json!({ "kind": 2, "acceptedLength": already_accepted + characters });
self.host.send("ExtHostLanguageFeatures", "$handleInlineCompletionPartialAccept", vec![json!(completion.handle), json!(completion.pid), json!(completion.idx), json!(characters), info]);
}
/// `stop`: the ghost text goes; an explicit cancel tells the provider the item was rejected.
pub(super) fn stop_inline_completions(&mut self, explicit: bool, cx: &mut Context<Self>) {
if let Some(item) = &self.inline_completions.ghost_item {
self.end_of_lifetime(item, if explicit { REJECTED } else { IGNORED });
}
self.inline_completions.active = false;
self.inline_completions.request = None;
self.inline_completions.fetched = None;
self.inline_completions.cycle = 0;
self.inline_completions.items.clear();
self.inline_completions.suggest_widget_items.clear();
self.inline_completions.shown = None;
for (handle, pid) in std::mem::take(&mut self.inline_completions.lists) {
self.free_inline_completion_list(handle, pid, "empty");
}
self.update_ghost_text(cx);
}
fn end_of_lifetime(&self, item: &Item, kind: u64) {
self.host.send("ExtHostLanguageFeatures", "$handleInlineCompletionEndOfLifetime", vec![json!(item.handle), json!(item.pid), json!(item.idx), json!({ "kind": kind })]);
}
/// `next`/`previous`: the selection wraps around the visible items; an explicit request asks first when the
/// session has only the automatic ones.
fn cycle_inline_completions(&mut self, delta: isize, cx: &mut Context<Self>) {
self.inline_completions.cycle += delta;
self.inline_completions.active = true;
self.trigger_inline_completions(true, false, None, cx);
if self.inline_completions.request.is_none() {
self.select_cycled_inline_completion(cx);
}
}
fn select_cycled_inline_completion(&mut self, cx: &mut Context<Self>) {
let delta = std::mem::take(&mut self.inline_completions.cycle);
if delta == 0 {
return;
}
let visible = self.visible_items();
if visible.is_empty() {
return;
}
let index = visible.iter().position(|(id, _)| Some(id) == self.inline_completions.selected.as_ref()).unwrap_or(0);
let next = (index as isize + delta).rem_euclid(visible.len() as isize) as usize;
self.inline_completions.selected = Some(visible[next].0.clone());
self.update_ghost_text(cx);
}
/// `accept`: the item's edit at every cursor it shows at (through the snippet controller for a snippet) and its
/// command; then a new request without delay.
fn accept_inline_completion(&mut self, window: &mut gpui::Window, cx: &mut Context<Self>) {
let Some(item) = self.inline_completions.ghost_item.clone() else { return };
let state_edits = self.inline_completions.edits.clone();
let additional_edits = item.additional_edits.iter().map(|(start, end, text)| Replacement { start: *start, end: *end, text: text.clone() });
let all_edits: Vec<Replacement> = state_edits.iter().cloned().chain(additional_edits).collect();
// `TextEdit.fromParallelReplacementsUnsorted` throws on overlapping edits, before anything is accepted.
if item.snippet.is_none() && end_positions_after_applying(&all_edits).is_none() {
return;
}
self.end_of_lifetime(&item, ACCEPTED);
self.inline_completions.shown = None;
self.inline_completions.items.clear();
self.inline_completions.suggest_widget_items.clear();
self.update_ghost_text(cx);
match &item.snippet {
// The edit's range is deleted with the additional edits, then the snippet goes in at its start.
Some(template) => {
let Some(editor) = self.editors.active_mut() else { return };
editor.push_undo_stop();
let mut edits = vec![(item.edit.start, item.edit.end, String::new(), false)];
edits.extend(item.additional_edits.iter().map(|(start, end, text)| (*start, *end, text.clone(), false)));
let change = editor.execute_edits(edits, Some(vec![crate::editor::Selection::caret(item.edit.start)]), EditReason::Unknown("inlineSuggestion.accept"));
self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);
let snippets = [(item.edit.start, item.edit.start, template.as_str(), false)];
self.insert_snippets(super::snippet_controller::SnippetInsert { snippets: &snippets, clipboard: None, undo_stop_before: false, undo_stop_after: true, reason: "inlineSuggestion.accept" }, cx);
}
None => {
let Some(editor) = self.editors.active_mut() else { return };
editor.push_undo_stop();
// The cursors go to the ends of the edits less their common suffix with the text they replace.
let minimal_edits: Vec<Replacement> = state_edits.iter().map(|edit| remove_common_prefix_and_suffix(edit, &editor.document().lines)).collect();
let selections = end_positions_after_applying(&minimal_edits).expect("parts of edits that do not overlap").into_iter().map(crate::editor::Selection::caret).collect();
let mut edits: Vec<_> = state_edits.into_iter().map(|edit| (edit.start, edit.end, edit.text, false)).collect();
edits.extend(item.additional_edits.iter().map(|(start, end, text)| (*start, *end, text.clone(), false)));
let change = editor.execute_edits(edits, Some(selections), EditReason::Unknown("inlineSuggestion.accept"));
editor.push_undo_stop();
self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);
}
}
if let Some(id) = item.command["id"].as_str().filter(|id| !id.is_empty()) {
let args = item.command["arguments"].as_array().cloned().unwrap_or_default();
self.execute_command(id, args, window, cx);
}
self.inline_completions.active = true;
self.trigger_inline_completions(false, false, None, cx);
}
/// `acceptNextWord`/`acceptNextLine` (`_acceptNext`): the primary ghost text's first word (or line) goes in at
/// every cursor `getSecondaryEdits` repeats it at, and the session goes on; all of a one-part ghost text accepts.
fn accept_inline_completion_part(&mut self, kind: PartialKind, window: &mut gpui::Window, cx: &mut Context<Self>) {
let (Some(item), Some(ghost)) = (self.inline_completions.ghost_item.clone(), self.inline_completions.ghosts.first().cloned()) else { return };
if ghost.is_empty() {
return;
}
let part = &ghost.parts[0];
let text = match kind {
PartialKind::Word => next_word(&part.text),
PartialKind::Line => part.text.split_inclusive('\n').next().unwrap_or_default().to_owned(),
};
// A snippet's partial commit might change it, so it is accepted whole.
if item.snippet.is_some() || (text == part.text && ghost.parts.len() == 1) {
self.accept_inline_completion(window, cx);
return;
}
let ghost_position = Position::new(ghost.line, part.column);
let Some(editor) = self.editors.active_mut() else { return };
let positions: Vec<Position> = editor.selections.iter().map(|selection| selection.end()).collect();
let (start, end) = (positions[0].min(ghost_position), positions[0].max(ghost_position));
let primary = Replacement { start, end, text: crate::editor::text_between(&editor.document().lines, start, end) + &text };
let mut replacements = vec![primary.clone()];
replacements.extend(secondary_edits(&editor.document().lines, &positions, &primary));
let Some(ends) = end_positions_after_applying(&replacements) else { return };
let selections = ends.into_iter().map(crate::editor::Selection::caret).collect();
editor.push_undo_stop();
let edits = replacements.into_iter().map(|edit| (edit.start, edit.end, edit.text, false)).collect();
let change = editor.execute_edits(edits, Some(selections), EditReason::Unknown("inlineSuggestion.accept"));
self.host.send("ExtHostLanguageFeatures", "$handleInlineCompletionPartialAccept", vec![json!(item.handle), json!(item.pid), json!(item.idx), json!(text.encode_utf16().count()), json!({ "kind": if kind == PartialKind::Word { 0 } else { 1 }, "acceptedLength": text.encode_utf16().count() })]);
self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);
}
/// ghostTextView.ts: a ghost text part drawn in the gap of its injected text in `editorGhostText.foreground`, italic
/// but for a preview part (`ghost-text-decoration-preview`).
pub(super) fn ghost_text_element(&self, id: usize, left: f32, line_height: f32) -> Option<AnyElement> {
let part = self.inline_completions.ghosts.iter().flat_map(|ghost| &ghost.parts).nth(id)?;
let text: String = part.text.split('\n').next().unwrap_or_default().to_owned();
Some(self.ghost_text_row(text, !part.preview).absolute().left(px(left)).top_0().h(px(line_height)).into_any_element())
}
fn ghost_text_row(&self, text: String, italic: bool) -> gpui::Div {
let mut row = div().flex().items_center().whitespace_nowrap().when(italic, |row| row.italic()).font_family(EDITOR_FONT).text_color(self.foreground_or("editorGhostText.foreground"));
if let Some(background) = self.theme.color("editorGhostText.background") {
row = row.bg(background);
}
if let Some(border) = self.theme.color("editorGhostText.border") {
row = row.border_1().border_color(border);
}
row.child(text)
}
/// `AdditionalLinesWidget`: each ghost text's other lines in the view zone below its line.
pub(super) fn ghost_text_lines(&self, editor: &OpenEditor, content_left: f32) -> Vec<AnyElement> {
let line_height = self.editors.viewport.line_height;
let mut elements = Vec::new();
for (zone, lines) in &self.inline_completions.zones {
let Some(top) = editor.view_zone_top(*zone, self.editors.viewport) else { continue };
let mut column = div().absolute().left(px(content_left - editor.scroll.left)).top(px(top - editor.scroll.top)).flex().flex_col();
for line in lines {
column = column.child(self.ghost_text_row(crate::editor::expand_tabs(line, editor.document().indentation.tab_size), true).h(px(line_height)));
}
elements.push(column.into_any_element());
}
elements
}
/// hoverParticipant.ts `computeSync` with inlineCompletionsController.ts `shouldShowHoverAt`: one part while
/// `editor.inlineSuggest.showToolbar` is `onHover` and the anchor's range contains a part of the primary ghost text:
/// the injected text, the char before it and the char after it.
pub(super) fn inline_completions_hover_parts(&self, editor: &OpenEditor, anchor: Anchor) -> Vec<Part> {
if self.suggest_setting(editor, SHOW_TOOLBAR) != "onHover" || self.inline_completions.model_id != Some(editor.model_id) {
return Vec::new();
}
let Some(ghost) = self.inline_completions.ghosts.first() else { return Vec::new() };
if ghost.line != anchor.line || !ghost.parts.iter().any(|part| (anchor.start..=anchor.end).contains(&part.column)) {
return Vec::new();
}
let (start, end) = (Position::new(anchor.line, anchor.start), Position::new(anchor.line, anchor.end));
vec![Part { participant: Participant::InlineCompletions, ordinal: 0, start, end, content: PartContent::InlineCompletions, source: None }]
}
/// hoverParticipant.ts `suggestHoverAnchor` for `CONTENT_EMPTY`: the empty area after line `line` anchors at
/// its end while a part of the primary ghost text is there.
pub(super) fn inline_completions_empty_area_anchor(&self, editor: &OpenEditor, line: usize) -> Option<Anchor> {
let end = editor.document().lines.get(line)?.chars().count();
let ghost = self.inline_completions.ghosts.first().filter(|_| self.inline_completions.model_id == Some(editor.model_id))?;
(ghost.line == line && ghost.parts.iter().any(|part| part.column == end)).then_some(Anchor { model_id: editor.model_id, line, start: end, end })
}
/// inlineCompletionsHintsWidget.ts `InlineSuggestionHintsContentWidget` without its border: Previous, the
/// `n/count` label and Next, then `MenuId.InlineSuggestionToolbar`'s `primary*` groups with their keybindings;
/// its other groups, the list's commands and `MenuId.InlineCompletionsActions` behind "...".
pub(super) fn inline_completions_hover_toolbar(&self, window: &Window, cx: &mut Context<Self>) -> Div {
let mut context = self.key_context(window);
context.insert(format!("config.{SHOW_TOOLBAR}"), self.setting(SHOW_TOOLBAR));
let foreground = self.color("icon.foreground");
// `inlineCompletionsCount`: known once an explicit request answered.
let visible = self.visible_items();
let count = self.inline_completions.fetched.as_ref().filter(|fetched| fetched.explicit).map(|_| visible.len());
let selected = visible.iter().position(|(id, _)| Some(id) == self.inline_completions.selected.as_ref()).unwrap_or(0);
let cycles = count.is_some_and(|count| count > 1);
let mut toolbar = div()
.p(px(4.))
.flex()
.items_center()
// actionbar.css: the labels' 11px under the hover's 19.5px line height.
.text_size(px(11.))
.line_height(px(19.5))
.text_color(self.color("editorHoverWidget.foreground"))
.child(self.inline_hint_button("editor.action.inlineSuggest.showPrevious", "Previous", "chevron-left", cycles, &context, cx))
.child(div().id("inline-suggestion-count").debug_selector(|| "inline-suggestion-count".into()).min_w(px(19. + 2. * 3.)).p(px(3.)).flex().justify_center().children(count.map(|count| format!("{}/{count}", selected + 1))))
.child(self.inline_hint_button("editor.action.inlineSuggest.showNext", "Next", "chevron-right", cycles, &context, cx));
for action in menu_group_actions(&self.menus, MenuId::InlineSuggestionToolbar, &context, |group| group.starts_with("primary")) {
let MenuAction::Command { id, title, enabled, .. } = action else { continue };
toolbar = toolbar.child(self.inline_status_bar_item(id, title, enabled, &context, cx));
}
let list_commands = self.selected_item().map(|item| item.list_commands).unwrap_or_default();
let mut extra = Vec::new();
for (index, command) in list_commands.iter().enumerate() {
let title = command["command"]["title"].as_str().unwrap_or_default().to_owned();
extra.push(MenuAction::Command { id: format!("{LIST_COMMAND}{index}"), title, enabled: true, checked: false, alt: None });
}
extra.extend(menu_actions(&self.menus, MenuId::InlineCompletionsActions, &context).into_iter().filter(|action| matches!(action, MenuAction::Command { .. })));
let mut secondary = menu_group_actions(&self.menus, MenuId::InlineSuggestionToolbar, &context, |group| !group.starts_with("primary"));
if !extra.is_empty() {
secondary.push(MenuAction::Separator);
secondary.extend(extra);
}
if secondary.is_empty() {
return toolbar;
}
let bounds = std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::default()));
let measured = bounds.clone();
let more = self
.icon("toolbar-more", 22., 16., foreground)
.id("inline-suggestion-more")
.debug_selector(|| "inline-suggestion-more".into())
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.child(self.hover_target("inline-suggestion-more-hover", HoverContent::Text("More Actions...".into()), HoverOptions::action_item()))
.on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &gpui::MouseDownEvent, window, cx| {
cx.stop_propagation();
// The list's commands carry their own arguments: each runs as a command of its own.
for (index, command) in list_commands.iter().enumerate() {
let id = command["command"]["id"].as_str().unwrap_or_default().to_owned();
let args = command["command"]["arguments"].as_array().cloned().unwrap_or_default();
workbench.commands.register(format!("{LIST_COMMAND}{index}"), move |workbench, _, window, cx| workbench.execute_command(&id, args.clone(), window, cx));
}
workbench.show_context_menu_actions(secondary.clone(), &context, bounds.get(), Vec::new(), window, cx);
}))
.child(gpui::canvas(move |element_bounds, _, _| measured.set(element_bounds), |_, _, _, _| {}).absolute().size_full());
toolbar.child(more)
}
/// `InlineSuggestionHintsContentWidget` with its border while `editor.inlineSuggest.showToolbar` is `always`:
/// ABOVE the hints position, else BELOW (`allowEditorOverflow`), left of the ghost text there.
pub(super) fn inline_completions_hints_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let position = self.inline_completions.hints_position.filter(|_| self.inline_completions.model_id == Some(editor.model_id))?;
if self.suggest_setting(editor, SHOW_TOOLBAR) != "always" || editor.folding.is_hidden(position.line) {
return None;
}
let view_line = editor.position_view_line(position, false);
let anchor_left = editor.segment_pixel_left(editor.segment(view_line), position.column, char_width);
let anchor_top = editor.line_top(view_line, self.editors.viewport) - editor.scroll.top;
let measured = self.inline_completions.hints_size.get();
let size = measured.unwrap_or(Size { width: 0., height: 0. });
let layout = layout_in_page(anchor_left - editor.scroll.left + content_left, anchor_top, self.editors.viewport.line_height, size, self.text_area_bounds.get(), window.viewport_size().map(f32::from));
let hints_size = self.inline_completions.hints_size.clone();
let measure = canvas(
move |bounds, window, cx| {
// Size inside the border: the reference box ends 2px into the line (bottom 70, line top 68), its cached height 2px short.
let size = bounds.size.map(f32::from);
if hints_size.get() != Some(size) {
super::part_view::redraw_after_frame(window, cx);
}
hints_size.set(Some(size));
},
|_, _, _, _| (),
)
.absolute()
.inset_0();
let high_contrast = self.theme.kind.is_high_contrast();
let widget = div()
.id("inline-suggestion-hints")
.debug_selector(|| "inline-suggestion-hints".into())
.absolute()
.left(px(layout.left))
.top(px(layout.top))
.border_1()
.border_color(self.color("editorHoverWidget.border"))
.rounded(px(RADIUS))
.font_family(UI_FONT)
.cursor_default()
.occlude()
.when(measured.is_none(), |widget| widget.invisible())
.when(high_contrast, |widget| widget.bg(self.color("editorHoverWidget.background")))
.when(!high_contrast, |widget| {
// --vscode-shadow-lg under frostedGlass.css's `.monaco-hover`.
widget.child(self.frosted_glass("editorHoverWidget.background", RADIUS)).shadow(vec![BoxShadow { color: rgba(0x00000024).into(), offset: point(px(0.), px(0.)), blur_radius: px(12.), spread_radius: px(0.), inset: false }])
})
.child(self.inline_completions_hover_toolbar(window, cx))
.child(measure);
Some(deferred(widget).with_priority(1).into_any_element())
}
/// `createCommandAction`: an icon button whose tooltip appends its keybinding; actionbar.css dims it disabled.
fn inline_hint_button(&self, command: &'static str, label: &str, icon: &str, enabled: bool, context: &HashMap<String, Value>, cx: &mut Context<Self>) -> Stateful<Div> {
let tooltip = self.keybindings.resolver.append_keybinding(label, command, context);
let button = self.icon(icon, 22., 16., self.color("icon.foreground")).id(format!("inline-suggestion-{command}")).debug_selector(move || format!("inline-suggestion-{command}")).rounded(px(4.));
if !enabled {
return button.opacity(0.4);
}
button
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.child(self.hover_target(format!("inline-suggestion-hover-{command}"), HoverContent::Text(tooltip), HoverOptions::action_item()))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx))))
}
/// `StatusBarViewItem`: the item's short title and its keybinding's keys at 60% (inlineCompletionsHintsWidget.css).
fn inline_status_bar_item(&self, id: String, title: String, enabled: bool, context: &HashMap<String, Value>, cx: &mut Context<Self>) -> Stateful<Div> {
let keys = self.keybindings.resolver.lookup_primary_keybinding(&id, context).map(|item| item.keybinding.iter().flat_map(|chord| chord.key_caps()).collect::<Vec<_>>()).unwrap_or_default();
// `unthemedKeybindingLabelOptions`: the key borders take the text's color.
let border = self.color("editorHoverWidget.foreground");
let key = |key: String| div().min_w(px(12. + 2. * 3. + 2.)).flex().justify_center().px(px(3.)).py(px(2.)).border_1().border_color(border).rounded(px(3.)).text_size(px(8.)).line_height(px(10.)).child(key);
let selector = format!("inline-suggestion-{id}");
let item = div()
.id(selector.clone())
.debug_selector(move || selector)
.flex()
.items_center()
.p(px(3.))
.mr(px(2.))
.rounded(px(4.))
.child(title)
.when(!keys.is_empty(), |item| item.child(div().flex().items_center().gap(px(4.)).ml(px(4.)).p(px(3.)).opacity(0.6).children(keys.into_iter().map(key))));
if !enabled {
return item.opacity(0.4);
}
item.cursor_pointer()
.hover(|item| item.bg(self.color("toolbar.hoverBackground")))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| drop(workbench.execute_command(&id, Vec::new(), window, cx))))
}
}
#[derive(Clone, Copy, PartialEq)]
enum PartialKind {
Word,
Line,
}
/// stringEdit.ts `applyEditsToRanges` for one range and one edit (`start..end` now ending at `new_end`): a range the
/// edit touches grows over its new text.
fn rebased(edit: &Replacement, start: Position, end: Position, new_end: Position) -> Replacement {
let moved = |position: Position| match position.line == end.line {
true => Position::new(new_end.line, new_end.column + position.column - end.column),
false => Position::new(position.line + new_end.line - end.line, position.column),
};
let range = if edit.end < start {
(edit.start, edit.end)
} else if edit.start > end {
(moved(edit.start), moved(edit.end))
} else {
(edit.start.min(start), if edit.end <= end { new_end } else { moved(edit.end) })
};
Replacement { start: range.0, end: range.1, text: edit.text.clone() }
}
/// `canBeReused`: the item's edit holds the cursor, shows, and is not shorter than the provider's range.
fn can_be_reused(item: &Item, lines: &[String], head: Position) -> bool {
let length = |start: Position, end: Position| (end.line - start.line, if end.line == start.line { end.column - start.column } else { end.column });
item.edit.start <= head && head <= item.edit.end && inline_completion_is_visible(&item.edit, Some(item.original.0), lines, head) && length(item.edit.start, item.edit.end) >= length(item.original.0, item.original.1)
}
/// `acceptNextWord`'s text: the first word when the text starts with one, else what comes before it; cut after the
/// first whitespace run when that ends earlier.
fn next_word(text: &str) -> String {
let word_start = text.find(crate::editor::is_word_char);
let mut until = match word_start {
Some(0) => text.find(|c: char| !crate::editor::is_word_char(c)).unwrap_or(text.len()),
Some(start) => start,
None => text.len(),
};
if let Some(start) = text.find(char::is_whitespace) {
let end = text[start..].find(|c: char| !c.is_whitespace()).map_or(text.len(), |length| start + length);
until = until.min(end);
}
text[..until].to_owned()
}
/// One `InlineCompletion` DTO: its range (or the request's `defaultReplaceRange`) and insert text.
fn completion_item(lines: &[String], default_range: (Position, Position), indentation: crate::editor::Indentation, handle: u64, pid: u64, completion: &Value) -> Option<Item> {
let (text, snippet) = match &completion["insertText"] {
Value::String(text) => (text.clone(), None),
// `snippet.toString()`: the placeholders' text, unresolved variables empty.
Value::Object(object) => {
let template = object.get("snippet")?.as_str()?.to_owned();
(crate::editor::expand_snippet(&template, "", false, indentation, |_| None).text, Some(template))
}
_ => return None,
};
let position = |line: &Value, column: &Value| {
let line = (line.as_u64().unwrap_or(1).max(1) as usize - 1).min(lines.len() - 1);
Position::new(line, char_column(&lines[line], column.as_u64().unwrap_or(1).max(1) as usize - 1))
};
// `Range` orders its ends, so a provider's reversed range is the same range.
let positions = |range: &Value| {
let (start, end) = (position(&range["startLineNumber"], &range["startColumn"]), position(&range["endLineNumber"], &range["endColumn"]));
(start.min(end), start.max(end))
};
let range = &completion["range"];
let (start, end) = match range.is_object() {
true => positions(range),
false => default_range,
};
let mut additional_edits = Vec::new();
for edit in completion["additionalTextEdits"].as_array().into_iter().flatten() {
let (start, end) = positions(&edit["range"]);
additional_edits.push((start, end, edit["text"].as_str().unwrap_or_default().to_owned()));
}
Some(Item { handle, pid, idx: completion["idx"].as_u64().unwrap_or_default(), edit: Replacement { start, end, text }, original: (start, end), forward_stable: false, suppress_suggestions: false, command: completion["command"].clone(), list_commands: Vec::new(), snippet, additional_edits })
}
#[cfg(test)]
mod tests;