Visual Studio Code, rebuilt in Rust
Rust
feat(inlineCompletions): show the inline suggestion toolbar in the hover
rokartur3c3ba21b2555
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rsindex cdd9419a1be..37ed75c75ed 100644--- a/native/crates/app/src/menus.rs+++ b/native/crates/app/src/menus.rs@@ -72,6 +72,10 @@ pub enum MenuId {StickyScrollContext,/// `MenuId.ModalEditorEditorTitle`: the modal editor part's editor actions.ModalEditorEditorTitle,+ /// `MenuId.InlineSuggestionToolbar`: the inline suggestion hover's toolbar, `primary*` groups as buttons.+ InlineSuggestionToolbar,+ /// `MenuId.InlineCompletionsActions`: the inline suggestion hover toolbar's extra `...` items.+ InlineCompletionsActions,/// `MenuId.TitleBar`: the title bar's global toolbar.TitleBar,TitleBarContext,@@ -755,6 +759,10 @@ const WORKBENCH_MENUS: &[Row] = &[(MenuId::NotebookToolbar, None, "workbench.notebook.layout.configure", "Customize Notebook Layout", "notebookLayout", 1., Some("config.notebook.globalToolbar == true"), None),// mergeEditor commands.ts `ResetToBaseAndAutoMergeCommand`.(MenuId::MergeInputResultToolbar, None, "mergeEditor.resetResultToBaseAndAutoMerge", "Reset Result", "primary", 0., None, Some("isMergeEditor")),+ // inlineCompletions/browser/controller/commands.ts: EditorAction menu items take the precondition as their `when`.+ (MenuId::InlineSuggestionToolbar, None, "editor.action.inlineSuggest.commit", "Accept", "primary", 2., Some("inlineSuggestionVisible || inlineEditIsVisible"), Some("inlineSuggestionVisible || inlineEditIsVisible")),+ (MenuId::InlineSuggestionToolbar, None, "editor.action.inlineSuggest.acceptNextWord", "Accept Word", "primary", 2., Some("!editorReadonly && inlineSuggestionVisible"), Some("!editorReadonly && inlineSuggestionVisible")),+ (MenuId::InlineSuggestionToolbar, None, "editor.action.inlineSuggest.acceptNextLine", "Accept Line", "secondary", 2., Some("!editorReadonly && inlineSuggestionVisible"), Some("!editorReadonly && inlineSuggestionVisible")),// notificationsCommands.ts: the title bar bell.(MenuId::TitleBar, None, "notifications.toggleList", "Toggle Notifications", "navigation", 10000., Some("config.workbench.notifications.position == 'top-right' && config.workbench.notifications.showInTitleBar == true"), None),];@@ -816,6 +824,7 @@ const THEMES_SUBMENU: [(&str, &str, f64); 3] = [("workbench.action.selectTheme",/// `when`. Notifications and Integrated Browser toggle parts the port has not; Editor Actions is `EDITOR_ACTIONS_TOGGLE`./// titlebarActions.ts `ToggleEditorActions`.pub const EDITOR_ACTIONS_TOGGLE: &str = "toggle.workbench.editor.editorActionsLocation";+pub const ALWAYS_SHOW_INLINE_TOOLBAR: &str = "editor.action.inlineSuggest.toggleAlwaysShowToolbar";pub const TITLE_BAR_TOGGLES: [(&str, &str, f64, &str); 3] = [("window.commandCenter", "Command Center", 1., "!isCompactTitleBar"),("workbench.navigationControl.enabled", "Navigation Controls", 2., "!isCompactTitleBar && config.window.commandCenter"),@@ -865,6 +874,10 @@ pub fn workbench_menus() -> Vec<MenuItem> {let entry = Entry::Command { id: id.into(), precondition: None, toggled: Toggled::when(Some(Expr::has(toggled))), alt: None };items.push(MenuItem { menu, entry, title: title.into(), group: group.into(), order, when: Expr::deserialize(when) });}+ // inlineCompletions/browser/controller/commands.ts ToggleAlwaysShowInlineSuggestionToolbar.+ let toggled = Toggled::when(Expr::deserialize("config.editor.inlineSuggest.showToolbar == 'always'"));+ let entry = Entry::Command { id: ALWAYS_SHOW_INLINE_TOOLBAR.into(), precondition: None, toggled, alt: None };+ items.push(MenuItem { menu: MenuId::InlineSuggestionToolbar, entry, title: "Always Show Toolbar".into(), group: "secondary".into(), order: 10., when: None });// editor.contribution.ts: Diff View's modes, checked by the diff settings; Automatic names the mode it renders.let side_by_side = "config.diffEditor.renderSideBySide == true";let diff_modes = [@@ -1040,6 +1053,7 @@ const API_MENUS: &[(&str, MenuId)] = &[("mergeEditor/result/title", MenuId::MergeInputResultToolbar),("titleBar", MenuId::TitleBar),("modalEditor/editorTitle", MenuId::ModalEditorEditorTitle),+ ("editor/inlineCompletions/actions", MenuId::InlineCompletionsActions),("terminal/context", MenuId::TerminalInstanceContext),("terminal/title/context", MenuId::TerminalTabContext),];@@ -1148,6 +1162,7 @@ pub fn extension_menus(extensions: &[ScannedExtension]) -> Vec<MenuItem> {"comments/commentThread/title/context" | "comments/commentThread/comment/context" => Some("contribCommentPeekContext"),"mergeEditor/result/title" => Some("contribMergeEditorMenus"),"titleBar" => Some("contribTitleBar"),+ "editor/inlineCompletions/actions" => Some("inlineCompletionsAdditions"),"scm/historyItemRef/context" => Some("contribSourceControlHistoryItemMenu"),"viewContainer/title" => Some("contribViewContainerTitle"),_ => None,diff --git a/native/crates/app/src/workbench/accessible_view.rs b/native/crates/app/src/workbench/accessible_view.rsindex 292e852520f..5ba36b34f05 100644--- a/native/crates/app/src/workbench/accessible_view.rs+++ b/native/crates/app/src/workbench/accessible_view.rs@@ -407,6 +407,7 @@ impl Workbench {PartContent::Marker(marker) => super::content_hover_view::marker_accessible_content(marker),PartContent::Markdown(contents) => contents.iter().filter(|content| !crate::markdown::is_empty(content)).map(|content| plain_text(&parse(&MarkdownString::from_value(content)))).collect::<Vec<_>>().join("\n"),PartContent::ColorPicker => "There is a color picker here.".to_owned(),+ PartContent::InlineCompletions => "There are inline completions here".to_owned(),});}if let Some(PartContent::Marker(marker)) = parts.iter().map(|part| &part.content).find(|content| matches!(content, PartContent::Marker(_))) {diff --git a/native/crates/app/src/workbench/code_actions.rs b/native/crates/app/src/workbench/code_actions.rsindex 2a8799dcdcd..7144cb50a68 100644--- a/native/crates/app/src/workbench/code_actions.rs+++ b/native/crates/app/src/workbench/code_actions.rs@@ -824,7 +824,7 @@ impl Workbench {parts.sort_by_key(|part| (part.participant, part.ordinal));parts.into_iter().find_map(|part| match &part.content {super::content_hover::PartContent::Marker(marker) => Some(marker.clone()),- super::content_hover::PartContent::Markdown(_) | super::content_hover::PartContent::ColorPicker => None,+ super::content_hover::PartContent::Markdown(_) | super::content_hover::PartContent::ColorPicker | super::content_hover::PartContent::InlineCompletions => None,})});let fixes = &mut self.code_actions.marker_fixes;diff --git a/native/crates/app/src/workbench/content_hover.rs b/native/crates/app/src/workbench/content_hover.rsindex bc6c086435c..7456e855d3f 100644--- a/native/crates/app/src/workbench/content_hover.rs+++ b/native/crates/app/src/workbench/content_hover.rs@@ -143,6 +143,7 @@ pub(super) enum Participant {Marker,ColorPicker,Markdown,+ InlineCompletions,Unicode,}@@ -179,6 +180,8 @@ pub(super) enum PartContent {Markdown(Vec<Value>),/// The color picker of `ColorDetector.picker`.ColorPicker,+ /// hintsWidget/hoverParticipant.ts: the inline suggestion's toolbar.+ InlineCompletions,}/// `ContentHoverResult` as shown, with the widget's `_visibleData` for `isMouseGettingCloser`.@@ -566,7 +569,7 @@ impl Workbench {}stops.extend((0..marker.related_information.as_array().map_or(0, Vec::len)).map(PartStop::MarkerRelated));}- PartContent::ColorPicker => return stops,+ PartContent::ColorPicker | PartContent::InlineCompletions => return stops,}stops.push(PartStop::Copy);stops@@ -899,10 +902,15 @@ impl Workbench {parts.extend(self.definition_link_hover_parts(editor, anchor));parts.extend(self.keybinding_mark_hover_parts(editor, anchor));parts.extend(self.debug_inline_value_hover_parts(editor, anchor));+ parts.extend(self.inline_completions_hover_parts(editor, anchor));parts}None => Vec::new(),};+ // hoverParticipant.ts `renderHoverParts`: the toolbar asks for every item, for its count.+ if parts.iter().any(|part| part.participant == Participant::InlineCompletions) {+ self.trigger_inline_completions_explicitly(cx);+ }let operation = self.operation(serial).expect("checked above");operation.parts.extend(parts);operation.state = if operation.pending_providers == 0 { State::Idle } else { State::WaitingForAsync };@@ -1027,7 +1035,7 @@ pub(super) fn markdown_link_targets(contents: &[Value]) -> Vec<String> {fn part_marker(content: &PartContent) -> Option<&Arc<Marker>> {match content {PartContent::Marker(marker) => Some(marker),- PartContent::Markdown(_) | PartContent::ColorPicker => None,+ PartContent::Markdown(_) | PartContent::ColorPicker | PartContent::InlineCompletions => None,}}diff --git a/native/crates/app/src/workbench/content_hover_view.rs b/native/crates/app/src/workbench/content_hover_view.rsindex c8f90847261..915428d2381 100644--- a/native/crates/app/src/workbench/content_hover_view.rs+++ b/native/crates/app/src/workbench/content_hover_view.rs@@ -208,12 +208,16 @@ impl Workbench {rows.push(div().child(self.color_picker_row(cx)));continue;}+ PartContent::InlineCompletions => {+ rows.push(self.inline_completions_hover_toolbar(window, cx));+ continue;+ }};rows.push(self.hover_row_with_copy(row, index, copy_text, focused_part == Some(index), stop == Some(PartStop::Copy), cx));}let first_marker = parts.iter().find_map(|part| match &part.content {PartContent::Marker(marker) => Some(marker.clone()),- PartContent::Markdown(_) | PartContent::ColorPicker => None,+ PartContent::Markdown(_) | PartContent::ColorPicker | PartContent::InlineCompletions => None,});if let Some(marker) = first_marker {rows.push(self.marker_hover_status_bar(marker, stop_in(rows.len()), window, cx));diff --git a/native/crates/app/src/workbench/inline_completions.rs b/native/crates/app/src/workbench/inline_completions.rsindex d246360df1d..b01b29696e2 100644--- a/native/crates/app/src/workbench/inline_completions.rs+++ b/native/crates/app/src/workbench/inline_completions.rs@@ -4,12 +4,16 @@// 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::collections::HashMap;use std::time::Duration;-use gpui::{AnyElement, Context, Task, div, prelude::*, px};+use gpui::{AnyElement, ClickEvent, Context, Div, MouseButton, Stateful, Task, Window, div, prelude::*, px};use serde_json::{Value, json};use super::Workbench;+use super::content_hover::{Anchor, Part, PartContent, Participant};+use super::hover::{HoverContent, HoverOptions};+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};@@ -25,6 +29,9 @@ const DEBOUNCE: Duration = Duration::from_millis(50);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 {@@ -103,6 +110,8 @@ pub(super) struct Item {/// 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)>,@@ -158,6 +167,18 @@ impl Workbench {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" }));+ 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`,@@ -372,13 +393,14 @@ impl Workbench {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, ..item });+ items.push(Item { forward_stable, suppress_suggestions, list_commands: list_commands.clone(), ..item });}}}@@ -811,6 +833,126 @@ impl Workbench {}elements}++ /// hoverParticipant.ts `computeSync` with inlineCompletionsController.ts `shouldShowHoverAt`: one part while+ /// `editor.inlineSuggest.showToolbar` is `onHover` and the anchor starts at a part of the primary ghost text.+ // shortcut: the char after a mid-line ghost text anchors the hover too (upstream: only the injected text), upgrade+ // when the mouse target tells injected text apart.+ 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| part.column == anchor.start) {+ 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 }]+ }++ /// 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()+ .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.)).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_dropdown_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)+ }++ /// `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().mx(px(2.)).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().ml(px(4.)).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)]@@ -888,7 +1030,7 @@ fn completion_item(lines: &[String], default_range: (Position, Position), indentlet (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(), snippet, additional_edits })+ 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)]diff --git a/native/crates/app/src/workbench/inline_completions/tests.rs b/native/crates/app/src/workbench/inline_completions/tests.rsindex 6038a43dfce..2f0c49fe618 100644--- a/native/crates/app/src/workbench/inline_completions/tests.rs+++ b/native/crates/app/src/workbench/inline_completions/tests.rs@@ -799,3 +799,46 @@ fn an_item_for_another_line_is_not_reused(cx: &mut TestAppContext) {assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "helloworld", "range": range(2, 1, 2, 6), "idx": 0 }]), cx)), [(2, 6, 0)]);assert_eq!(view(&workbench, cx), "hello\nhello[world]");}++/// hintsWidget/hoverParticipant.ts: a hover over the ghost text asks for every item and shows the toolbar of+/// inlineCompletionsHintsWidget.ts: Previous, the count and Next, `MenuId.InlineSuggestionToolbar`'s primary items,+/// then behind "..." its secondary items, a separator, the list's commands and `MenuId.InlineCompletionsActions`.+#[gpui::test]+fn the_hover_over_the_ghost_text_shows_the_inline_suggestion_toolbar(cx: &mut TestAppContext) {+ use crate::menus::{Entry, MenuAction, MenuId, MenuItem};+ use crate::workbench::content_hover::{HoverSource, Participant};+ let (workbench, cx, receiver) = open_with_provider(cx, "inline-hover-toolbar", "foo");+ workbench.update(cx, |workbench, _| {+ let entry = Entry::Command { id: "port.inlineAction".into(), precondition: None, toggled: None, alt: None };+ workbench.menus.push(MenuItem { menu: MenuId::InlineCompletionsActions, entry, title: "Port Inline Action".into(), group: String::new(), order: 0., when: None });+ });+ type_text(&workbench, cx, "b");+ let list = json!({ "items": [{ "insertText": "foobar", "range": range(1, 1, 1, 5), "idx": 0 }, { "insertText": "foobaz", "range": range(1, 1, 1, 5), "idx": 1 }], "commands": [{ "command": { "id": "port.listCommand", "title": "Port List Command" } }] });+ provide_list(&receiver, list.clone(), cx);+ assert_eq!(view(&workbench, cx), "foob[ar]");+ workbench.update(cx, |workbench, cx| workbench.show_content_hover_at(Position::new(0, 4), HoverSource::Keyboard, false, cx));+ assert_eq!(asked(&provide_list(&receiver, list, cx)), [(1, 5, 1)], "the hover asks explicitly");+ for _ in 0..3 {+ cx.update(|window, _| window.refresh());+ cx.run_until_parked();+ }+ workbench.read_with(cx, |workbench, _| {+ let shown = workbench.content_hover.shown.as_ref().expect("the hover shows");+ assert!(shown.parts.iter().any(|part| part.participant == Participant::InlineCompletions));+ });+ for selector in ["inline-suggestion-editor.action.inlineSuggest.showPrevious", "inline-suggestion-count", "inline-suggestion-editor.action.inlineSuggest.showNext", "inline-suggestion-editor.action.inlineSuggest.commit", "inline-suggestion-editor.action.inlineSuggest.acceptNextWord"] {+ assert!(cx.debug_bounds(selector).is_some(), "{selector} is drawn");+ }+ assert!(cx.debug_bounds("inline-suggestion-editor.action.inlineSuggest.acceptNextLine").is_none(), "Accept Line is secondary");+ let more = cx.debug_bounds("inline-suggestion-more").expect("the toolbar has a ...");+ cx.simulate_mouse_down(more.center(), gpui::MouseButton::Left, gpui::Modifiers::default());+ cx.run_until_parked();+ let titles = workbench.read_with(cx, |workbench, _| {+ let menu = workbench.context_menu.as_ref().expect("the ... menu shows");+ menu.levels[0].actions.iter().map(|action| match action {+ MenuAction::Command { title, .. } => title.clone(),+ _ => "-".into(),+ }).collect::<Vec<_>>()+ });+ assert_eq!(titles, ["Accept Line", "Always Show Toolbar", "-", "Port List Command", "Port Inline Action"]);+}diff --git a/port/fixtures/extensions/menus/extension.js b/port/fixtures/extensions/menus/extension.jsnew file mode 100644index 00000000000..392378957a0--- /dev/null+++ b/port/fixtures/extensions/menus/extension.js@@ -0,0 +1,18 @@+const vscode = require('vscode');++const COMPLETIONS = ['port inline one', 'port inline two'];++exports.activate = function (context) {+ context.subscriptions.push(vscode.commands.registerCommand('port.menus.inlineAction', () => {}));+ context.subscriptions.push(vscode.languages.registerInlineCompletionItemProvider({ language: 'plaintext' }, {+ provideInlineCompletionItems(document, position) {+ const typed = document.lineAt(position.line).text.slice(0, position.character);+ if (typed.length === 0) {+ return [];+ }+ const range = new vscode.Range(position.line, 0, position.line, position.character);+ const items = COMPLETIONS.filter(text => text.startsWith(typed)).map(text => new vscode.InlineCompletionItem(text, range));+ return { items, commands: [{ command: 'port.menus.inlineAction', title: 'Port List Command' }] };+ },+ }));+};diff --git a/port/fixtures/extensions/menus/package.json b/port/fixtures/extensions/menus/package.jsonindex e1b4fe6387d..67635fd3926 100644--- a/port/fixtures/extensions/menus/package.json+++ b/port/fixtures/extensions/menus/package.json@@ -2,14 +2,19 @@"name": "menus","publisher": "port","version": "0.0.1",- "description": "Contributions to the contributes.menus ids of menusExtensionPoint.ts, for port/tools/ui-pair (port/fixtures/ui-pair/menus).",+ "description": "Contributions to the contributes.menus ids of menusExtensionPoint.ts, for port/tools/ui-pair (port/fixtures/ui-pair/menus), and an inline completions provider for plain text.",+ "main": "./extension.js",+ "activationEvents": [+ "onLanguage:plaintext"+ ],"engines": {"vscode": "^1.100.0"},"enabledApiProposals": ["contribViewContainerTitle","contribMergeEditorMenus",- "contribTitleBar"+ "contribTitleBar",+ "inlineCompletionsAdditions"],"contributes": {"commands": [@@ -63,6 +68,10 @@{"command": "port.menus.titleMore","title": "Port Title Action"+ },+ {+ "command": "port.menus.inlineAction",+ "title": "Port Inline Action"}],"menus": {@@ -109,6 +118,11 @@"group": "1_port"}],+ "editor/inlineCompletions/actions": [+ {+ "command": "port.menus.inlineAction"+ }+ ],"modalEditor/editorTitle": [{"command": "port.menus.titleNav",diff --git a/port/fixtures/ui-pair/menus/inline-completions-toolbar.json b/port/fixtures/ui-pair/menus/inline-completions-toolbar.jsonnew file mode 100644index 00000000000..d7ded6d64e4--- /dev/null+++ b/port/fixtures/ui-pair/menus/inline-completions-toolbar.json@@ -0,0 +1,13 @@+[+ {"wait": 8000},+ {"click": [700, 116]},+ {"type": "port"},+ {"wait": 2500},+ {"shot": "ghost"},+ {"hover": [430, 117]},+ {"wait": 2000},+ {"shot": "hover"},+ {"click": [695, 89]},+ {"wait": 1000},+ {"shot": "more"}+]diff --git a/port/ledger.md b/port/ledger.mdindex 3cdc2033dc2..902bbb929ad 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -316,7 +316,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| editor/contrib/inPlaceReplace | src/vs/editor/contrib | M8 | verified | | Replace with Previous/Next Value (Shift+Cmd+, and ., palette): number step and value sets of `navigateValueSet`, 350 ms outline in light themes; cargo test -p app editor::in_place_replace (upstream has no test); ui-pair light theme `x = true; y = 41; z = 1.5` from the palette || editor/contrib/indentation | src/vs/editor/contrib | M8 | verified | [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | indentation.ts actions (indent using spaces/tabs, tab display size, detect, convert to spaces/tabs) and trimTrailingWhitespaceCommand.ts with their upstream tests, auto-indent on Enter and on type (`editor.autoIndent`), Reindent Lines and Reindent Selected Lines: cargo test -p app indentation editor_status editor::auto_indent (cursor.test.ts indent cases, Auto Indent On Type - TypeScript/JavaScript, shiftCommand.test.ts doc block cases); auto-indent on paste (`editor.autoIndentOnPaste`, `autoIndentOnPasteWithinString`, `AutoIndentOnPaste.trigger`) and the Ruby, PHP and Visual Basic suites of indentation.test.ts pass; the cases upstream skips (`test.skip`: paste 5, Ruby, Go, CPP 3, HTML, Latex, Lua) are `#[ignore]` and fail as upstream (cargo test -p app auto_indent, 115 passed, 13 ignored); indentation.ts actions (indent using spaces/tabs, tab display size, detect, convert to spaces/tabs) and trimTrailingWhitespaceCommand.ts with their upstream tests, auto-indent on Enter and on type (`editor.autoIndent`), Reindent Lines and Reindent Selected Lines: cargo test -p app indentation editor_status editor::auto_indent (cursor.test.ts indent cases, Auto Indent On Type - TypeScript/JavaScript, shiftCommand.test.ts doc block cases); no auto-indent on paste (`editor.autoIndentOnPaste`, default off), not the Ruby, PHP, Go, CPP, HTML, Visual Basic, Latex and Lua suites || editor/contrib/inlayHints | src/vs/editor/contrib | M13 | ported | [3 S] inlay_hints.rs:136: a scroll asks the providers while `editor.inlayHints.enabled` is `off` (inlayHintsController.ts:184 returns before its scroll listener) | workbench/inlay_hints.rs over editor/injected_text.rs (the 'InlayHint' debounce: inlay_hints::tests::the_delay_follows_the_providers_answer_time; off a word a hint attaches after its token's start, `_getRangeAtPosition`: inlay_hints::tests::a_hint_off_a_word_attaches_after_the_start_of_its_token; inlayHintsController.ts: cache, fixed lengths while typing, label parts, links, tooltip resolve, double click edits, `editor.inlayHints.*`, `_executeInlayHintProvider`): cargo test -p app injected_text inlay_hints; ui-pair port/fixtures/language-features/steps-color.json (port/results/inlay-hints.md) |-| editor/contrib/inlineCompletions | src/vs/editor/contrib | M13 | ported | [3 M] inline_completions.rs: no inlineCompletionsHintsWidget.ts toolbar (previous/next, the count, `editor/inlineCompletions/actions` at :213) | workbench/inline_completions.rs, ghost_text.rs (computeGhostText.ts over diff::lcs_diff), the suggest widget adaptor in workbench/suggest_controller.rs and workbench/suggest_widget.rs: cargo test -p app ghost_text inline_completions (computeGhostText.test.ts cases, getSecondaryEdits.test.ts, inlineCompletions.test.ts: the "Inline Completions" suite with its Forward Stability tests, the Multi Cursor Support suite and both "Change hint" tests; suggestWidgetModel.test.ts "Ghost Text" and "offWhenInlineCompletions", the augmentation over the suggest widget's own list (only_the_answer_with_the_suggest_item_augments_it), the inline preselect of the suggest widget, Shift previewing the replace edit and handleSuggestAccepted), cargo test -p diff lcs_diff (diff.test.ts and upstream outputs); ui-pair port/fixtures/language-features/steps-ghost.json (port/results/inlay-hints.md). Not ported by design: "Emits empty response telemetry after instantiation service disposal" (the port has no telemetry), suggestWidgetModel.test.ts "Active" (test.skip upstream, microsoft/vscode#166023), ghostTextView/layout/scrollToReveal tests (DOM, the ui-pair check stands in). Inline edits, next edit suggestions and their tests (inlineEdits, editKind, longDistanceWidgetPlacement, renameSymbolProcessor, graph) are AI: removed. Items dedupe and select by `semanticId`: cargo test -p app items_with_the_same_trimmed_edit_cycle_as_one. `getDefaultRange` from the word start to the line end: cargo test -p app an_item_without_a_range_replaces_up_to_the_line_end. |+| editor/contrib/inlineCompletions | src/vs/editor/contrib | M13 | ported | [3 S] inline_completions.rs: `editor.inlineSuggest.showToolbar: always` shows no InlineCompletionsHintsWidget above the ghost text (only the hover's toolbar); [3 S] inline_completions.rs: the hover's toolbar is ~11pt narrower and ~2pt shorter than the reference's, its "..." menu opens right-aligned to the button (reference: left-aligned); [3 S] inline_completions.rs: the char after a mid-line ghost text also anchors the toolbar hover (upstream: only the injected text) | workbench/inline_completions.rs, ghost_text.rs (computeGhostText.ts over diff::lcs_diff), the suggest widget adaptor in workbench/suggest_controller.rs and workbench/suggest_widget.rs: cargo test -p app ghost_text inline_completions (computeGhostText.test.ts cases, getSecondaryEdits.test.ts, inlineCompletions.test.ts: the "Inline Completions" suite with its Forward Stability tests, the Multi Cursor Support suite and both "Change hint" tests; suggestWidgetModel.test.ts "Ghost Text" and "offWhenInlineCompletions", the augmentation over the suggest widget's own list (only_the_answer_with_the_suggest_item_augments_it), the inline preselect of the suggest widget, Shift previewing the replace edit and handleSuggestAccepted), cargo test -p diff lcs_diff (diff.test.ts and upstream outputs); ui-pair port/fixtures/language-features/steps-ghost.json (port/results/inlay-hints.md). Not ported by design: "Emits empty response telemetry after instantiation service disposal" (the port has no telemetry), suggestWidgetModel.test.ts "Active" (test.skip upstream, microsoft/vscode#166023), ghostTextView/layout/scrollToReveal tests (DOM, the ui-pair check stands in). Inline edits, next edit suggestions and their tests (inlineEdits, editKind, longDistanceWidgetPlacement, renameSymbolProcessor, graph) are AI: removed. Items dedupe and select by `semanticId`: cargo test -p app items_with_the_same_trimmed_edit_cycle_as_one. `getDefaultRange` from the word start to the line end: cargo test -p app an_item_without_a_range_replaces_up_to_the_line_end. The hover's toolbar (hintsWidget/hoverParticipant.ts, `MenuId.InlineSuggestionToolbar`, the list's commands and `editor/inlineCompletions/actions`): cargo test -p app the_hover_over_the_ghost_text_shows_the_inline_suggestion_toolbar; ui-pair port/fixtures/ui-pair/menus/inline-completions-toolbar.json with `ARGS=--extensionDevelopmentPath=port/fixtures/extensions/menus`. || editor/contrib/inlineProgress | src/vs/editor/contrib | M13 | verified | | workbench/inline_progress.rs (inlineProgress.ts): the spinner after 500 ms at the paste or drop position with 1em of room as injected text, its hover, click cancels; the paste falls back to the default paste: cargo test -p app paste_edits (the_paste_progress_makes_room_for_its_spinner); ui-pair d.md paste (no spinner once the provider answers, as in the reference) || editor/contrib/insertFinalNewLine | src/vs/editor/contrib | M8 | verified | | `OpenEditor::insert_final_new_line` in `editor/indentation.rs`, `editor.action.insertFinalNewLine` (writable): cargo test -p app insert_final_new_line; ui-pair notes.txt through the Command Palette || editor/contrib/lineSelection | src/vs/editor/contrib | M8 | verified | | Expand Line Selection (Cmd+L, palette): cargo test -p app expand_line_selection (lineSelection.test.ts); ui-pair notes.txt Cmd+L twice and on the last line |