Visual Studio Code, rebuilt in Rust
Rust
use super::*;
#[test]
fn next_word_takes_a_word_or_what_comes_before_it() {
assert_eq!(next_word(" foo bar"), " ");
assert_eq!(next_word("foo bar"), "foo");
assert_eq!(next_word("(x)"), "(");
assert_eq!(next_word("\" + \"world\""), "\" ");
assert_eq!(next_word("bar"), "bar");
assert_eq!(next_word(");"), ");");
}
#[test]
fn a_completion_without_range_replaces_the_default_range() {
let lines = vec!["let co".to_owned()];
let indentation = crate::editor::Indentation { tab_size: 4, indent_size: None, insert_spaces: true };
let item = completion_item(&lines, (Position::new(0, 4), Position::new(0, 6)), indentation, 1, 2, &json!({ "insertText": "console", "idx": 3 })).unwrap();
assert_eq!((item.edit.start, item.edit.end, item.idx), (Position::new(0, 4), Position::new(0, 6), 3));
let ranged = completion_item(&lines, (Position::new(0, 4), Position::new(0, 6)), indentation, 1, 2, &json!({ "insertText": { "snippet": "co${1:nsole}" }, "range": { "startLineNumber": 1, "startColumn": 5, "endLineNumber": 1, "endColumn": 7 } })).unwrap();
assert_eq!((ranged.edit.text.as_str(), ranged.snippet.as_deref()), ("console", Some("co${1:nsole}")));
let reversed = completion_item(&lines, (Position::new(0, 4), Position::new(0, 6)), indentation, 1, 2, &json!({ "insertText": "console", "range": { "startLineNumber": 1, "startColumn": 7, "endLineNumber": 1, "endColumn": 5 } })).unwrap();
assert_eq!((reversed.edit.start, reversed.edit.end), (Position::new(0, 4), Position::new(0, 6)));
}
/// The `providerId` schema lists each provider as `extensionId:groupId` and `extensionId:*`, once.
#[gpui::test]
fn the_provider_id_schema_lists_each_provider_matcher(cx: &mut gpui::TestAppContext) {
let (workbench, cx, _, _) = crate::workbench::goto_symbol::tests::open(cx, "inline-provider-ids", "one\n");
let matchers = workbench.update(cx, |workbench, cx| {
let provider = |handle: u64, group: Value| vec![json!(handle), json!("*"), json!(false), json!("pub.ext"), json!("1.0.0"), group];
workbench.language_features.register(REGISTER, provider(1, json!("ghost")));
workbench.language_features.register(REGISTER, provider(2, Value::Null));
workbench.language_providers_changed(REGISTER, cx);
workbench.settings.lock().unwrap().registry.inline_completion_providers.clone()
});
assert_eq!(matchers, ["pub.ext:ghost", "pub.ext:*", "pub.ext"]);
}
use std::sync::mpsc::Receiver;
use exthost::session::ForwardedRequest;
use gpui::{TestAppContext, VisualTestContext};
use crate::host_sync::HostMessage;
use crate::workbench::goto_symbol::tests::{open, run};
const PROVIDER: u64 = 9;
/// `a.txt` holding `text` with the cursor at its end, and one inline completions provider (MockInlineCompletionsProvider).
fn open_with_provider<'a>(cx: &'a mut TestAppContext, name: &str, text: &str) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>) {
let (workbench, cx, receiver, _) = open(cx, name, text);
workbench.update(cx, |workbench, _| {
workbench.language_features.register(REGISTER, vec![json!(PROVIDER), json!("*"), json!(false), json!("pub.ext"), json!("1.0.0"), Value::Null]);
// inlineCompletions.test.ts has no suggest model: no quick suggest waits on the answers, nor stops them at 750 ms.
workbench.update_setting("editor.quickSuggestions", json!(false));
});
run(&workbench, cx, "cursorBottom");
run(&workbench, cx, "cursorEnd");
(workbench, cx, receiver)
}
/// Waits out the debounce and answers every `$provideInlineCompletions` call with `items`; returns the calls'
/// position and context.
fn provide(receiver: &Receiver<HostMessage>, items: Value, cx: &mut VisualTestContext) -> Vec<(Value, Value)> {
provide_list(receiver, json!({ "items": items }), cx)
}
/// `provide` with a whole list, each answer under a new pid.
fn provide_list(receiver: &Receiver<HostMessage>, list: Value, cx: &mut VisualTestContext) -> Vec<(Value, Value)> {
wait(cx, 1000);
answer(receiver, list, cx)
}
fn wait(cx: &mut VisualTestContext, ms: u64) {
cx.executor().advance_clock(Duration::from_millis(ms));
cx.run_until_parked();
}
/// Answers the `$provideInlineCompletions` calls made so far with `list`, without waiting.
fn answer(receiver: &Receiver<HostMessage>, list: Value, cx: &mut VisualTestContext) -> Vec<(Value, Value)> {
static PID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let mut calls = Vec::new();
for message in receiver.try_iter().filter(|message| message.method == "$provideInlineCompletions") {
calls.push((message.args[2].clone(), message.args[3].clone()));
let mut list = list.clone();
list["pid"] = json!(PID.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let _ = message.reply.expect("a call").send(Ok(list));
}
cx.run_until_parked();
calls
}
/// The calls' (line, column, triggerKind), as `getAndClearCallHistory` lists them.
fn asked(calls: &[(Value, Value)]) -> Vec<(u64, u64, u64)> {
calls.iter().map(|(position, context)| (position["lineNumber"].as_u64().unwrap(), position["column"].as_u64().unwrap(), context["triggerKind"].as_u64().unwrap())).collect()
}
/// `getAndClearViewStates`' view: the text with each ghost text's parts in brackets where they show.
fn view(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> String {
workbench.read_with(cx, |workbench, _| {
let mut lines = workbench.editors.active().unwrap().document().lines.clone();
for ghost in &workbench.inline_completions.ghosts {
let mut line: Vec<char> = lines[ghost.line].chars().collect();
for part in ghost.parts.iter().rev() {
line.splice(part.column..part.column, format!("[{}]", part.text).chars());
}
lines[ghost.line] = line.into_iter().collect();
}
lines.join("\n")
})
}
fn type_text(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, text: &str) {
workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("type", vec![json!({ "text": text })], window, cx));
cx.run_until_parked();
}
fn range(start_line: u64, start_column: u64, end_line: u64, end_column: u64) -> Value {
json!({ "startLineNumber": start_line, "startColumn": start_column, "endLineNumber": end_line, "endColumn": end_column })
}
fn text(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> String {
workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().lines.join("\n"))
}
fn ghost_text(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Option<String> {
workbench.read_with(cx, |workbench, _| workbench.inline_completions.ghosts.first().map(|ghost| ghost.parts[0].text.clone()))
}
/// inlineCompletions.test.ts "Additional Text Edits".
#[gpui::test]
fn accepting_applies_the_additional_text_edits(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-additional-edits", "buzz\nbaz");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
let items = json!([{ "insertText": "bazz", "range": range(2, 1, 2, 4), "additionalTextEdits": [{ "range": range(1, 1, 1, 5), "text": "bla" }], "idx": 0 }]);
let calls = provide(&receiver, items, cx);
assert_eq!(calls.iter().map(|(position, context)| (position.clone(), context["triggerKind"].clone())).collect::<Vec<_>>(), [(json!({ "lineNumber": 2, "column": 4 }), json!(1))]);
assert_eq!(ghost_text(&workbench, cx).as_deref(), Some("z"));
run(&workbench, cx, "editor.action.inlineSuggest.commit");
assert_eq!(text(&workbench, cx), "bla\nbazz");
}
/// inlineCompletions.test.ts "Change hint is passed from onDidChange to provideInlineCompletions" and "Change hint is
/// undefined when onDidChange fires without hint": the provider alone is asked again, at the moved cursor.
#[gpui::test]
fn a_provider_change_asks_it_again_with_its_change_hint(cx: &mut TestAppContext) {
let hint = json!({ "data": { "reason": "modelUpdated", "version": 42 } });
for (name, hint, expected) in [("inline-change-hint", hint.clone(), Some(hint)), ("inline-no-change-hint", Value::Null, None)] {
let (workbench, cx, receiver) = open_with_provider(cx, name, "foo");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
let items = json!([{ "insertText": "foobar", "range": range(1, 1, 1, 4), "idx": 0 }]);
let first = provide(&receiver, items.clone(), cx);
assert_eq!(first.len(), 1);
assert!(first[0].1.get("changeHint").is_none(), "{:?}", first[0].1);
run(&workbench, cx, "cursorLeft");
workbench.update_in(cx, |workbench, window, cx| {
let request = ForwardedRequest { req: 1, proxy: "MainThreadLanguageFeatures", method: "$emitInlineCompletionsChange".into(), args: vec![json!(PROVIDER), hint] };
_ = workbench.handle_host_request(request, window, cx);
});
let calls = provide(&receiver, items, cx);
assert_eq!(calls.len(), 1);
assert_eq!((calls[0].0.clone(), calls[0].1["triggerKind"].clone(), calls[0].1.get("changeHint").cloned()), (json!({ "lineNumber": 1, "column": 3 }), json!(0), expected));
}
}
/// inlineCompletions.test.ts "Forward Stability: Typing agrees": typing what the ghost text shows keeps it before
/// the provider answers again.
#[gpui::test]
fn typing_what_the_ghost_text_shows_keeps_it(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-typing-agrees", "");
let items = json!([{ "insertText": "foobar", "idx": 0 }]);
type_text(&workbench, cx, "foo");
assert_eq!(asked(&provide(&receiver, items.clone(), cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
type_text(&workbench, cx, "b");
assert_eq!(view(&workbench, cx), "foob[ar]");
assert_eq!(asked(&provide(&receiver, items.clone(), cx)), [(1, 5, 0)]);
assert_eq!(view(&workbench, cx), "foob[ar]");
type_text(&workbench, cx, "a");
assert_eq!(view(&workbench, cx), "fooba[r]");
assert_eq!(asked(&provide(&receiver, items, cx)), [(1, 6, 0)]);
assert_eq!(view(&workbench, cx), "fooba[r]");
}
/// The forward stability tests' `setupScenario`: "f" typed, an explicit request shows "foo bar", then the provider
/// answers "foo baz".
fn setup_scenario<'a>(cx: &'a mut TestAppContext, name: &str) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>, Value) {
let (workbench, cx, receiver) = open_with_provider(cx, name, "");
assert_eq!(view(&workbench, cx), "");
type_text(&workbench, cx, "f");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foo bar", "idx": 0 }]), cx)), [(1, 2, 1)]);
assert_eq!(view(&workbench, cx), "f[oo bar]");
(workbench, cx, receiver, json!([{ "insertText": "foo baz", "idx": 0 }]))
}
/// "Support forward instability": typing keeps the ghost text until the provider answers another one.
#[gpui::test]
fn a_new_answer_replaces_the_item_typing_agreed_with(cx: &mut TestAppContext) {
let (workbench, cx, receiver, baz) = setup_scenario(cx, "inline-forward-instability");
type_text(&workbench, cx, "o");
assert_eq!(view(&workbench, cx), "fo[o bar]");
assert_eq!(asked(&provide(&receiver, baz, cx)), [(1, 3, 0)]);
assert_eq!(view(&workbench, cx), "fo[o baz]");
}
/// "when accepting word by word": the partly accepted item stays first, also for an explicit request.
#[gpui::test]
fn accepting_a_word_keeps_the_item_over_a_new_answer(cx: &mut TestAppContext) {
let (workbench, cx, receiver, baz) = setup_scenario(cx, "inline-accept-word");
run(&workbench, cx, "editor.action.inlineSuggest.acceptNextWord");
assert_eq!(view(&workbench, cx), "foo[ bar]");
assert_eq!(asked(&provide(&receiver, baz.clone(), cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[ bar]");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
provide(&receiver, baz, cx);
assert_eq!(view(&workbench, cx), "foo[ bar]");
}
/// "when accepting undo": undo and redo of a partial accept move the item back and forth and keep it first.
#[gpui::test]
fn undo_and_redo_of_an_accepted_word_keep_the_item(cx: &mut TestAppContext) {
let (workbench, cx, receiver, baz) = setup_scenario(cx, "inline-accept-undo");
run(&workbench, cx, "editor.action.inlineSuggest.acceptNextWord");
assert_eq!(view(&workbench, cx), "foo[ bar]");
assert_eq!(asked(&provide(&receiver, baz.clone(), cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[ bar]");
run(&workbench, cx, "undo");
assert_eq!(asked(&provide(&receiver, baz.clone(), cx)), [(1, 2, 0)]);
assert_eq!(view(&workbench, cx), "f[oo bar]");
run(&workbench, cx, "redo");
assert_eq!(asked(&provide(&receiver, baz, cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[ bar]");
}
/// "Support backward instability": a deleted char goes back into the ghost text until the provider answers.
#[gpui::test]
fn deleting_moves_the_char_back_into_the_ghost_text(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-backward-instability", "");
type_text(&workbench, cx, "fooba");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foobar", "range": range(1, 1, 1, 6), "idx": 0 }]), cx)), [(1, 6, 1)]);
assert_eq!(view(&workbench, cx), "fooba[r]");
run(&workbench, cx, "deleteLeft");
assert_eq!(view(&workbench, cx), "foob[ar]");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foobaz", "range": range(1, 1, 1, 5), "idx": 0 }]), cx)), [(1, 5, 0)]);
assert_eq!(view(&workbench, cx), "foob[az]");
}
/// "Push item to preserve to front": a forward stable provider's shown item stays first in its new answer.
#[gpui::test]
fn the_shown_item_of_a_forward_stable_provider_stays_first(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-preserve-front", "");
let item = |text: &str, idx: u64| json!({ "insertText": text, "range": range(1, 1, 1, 4), "idx": idx });
type_text(&workbench, cx, "foo");
assert_eq!(asked(&provide_list(&receiver, json!({ "enableForwardStability": true, "items": [item("foobar", 0)] }), cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
assert_eq!(asked(&provide_list(&receiver, json!({ "enableForwardStability": true, "items": [item("foobar1", 0), item("foobar", 1)] }), cx)), [(1, 4, 1)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
}
/// A forward stable provider's shown item stays first when typing asks again; another provider's answer wins.
#[gpui::test]
fn typing_keeps_only_a_forward_stable_providers_item_first(cx: &mut TestAppContext) {
for (stable, expected) in [(true, "foob[ar]"), (false, "foob[ar1]")] {
let (workbench, cx, receiver) = open_with_provider(cx, &format!("inline-forward-stable-{stable}"), "");
let item = |text: &str, idx: u64| json!({ "insertText": text, "range": range(1, 1, 1, 4), "idx": idx });
type_text(&workbench, cx, "foo");
provide_list(&receiver, json!({ "enableForwardStability": stable, "items": [item("foobar", 0)] }), cx);
type_text(&workbench, cx, "b");
let answer = json!([{ "insertText": "foobar1", "range": range(1, 1, 1, 5), "idx": 0 }, { "insertText": "foobar", "range": range(1, 1, 1, 5), "idx": 1 }]);
assert_eq!(asked(&provide_list(&receiver, json!({ "enableForwardStability": stable, "items": answer }), cx)), [(1, 5, 0)]);
assert_eq!(view(&workbench, cx), expected);
}
}
/// `editor.setSelections` with a caret at each (line, column), the first one primary.
fn set_carets(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, carets: &[(usize, usize)]) {
let selections = carets.iter().map(|&(line, column)| crate::editor::Selection::caret(Position::new(line, column))).collect();
workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().set_selections(selections));
}
/// "Multi Cursor Support" `acceptNextWord`: an explicit request answered with `items`, then the next word, `times` times.
fn accept_next_word(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, receiver: &Receiver<HostMessage>, items: &Value, times: usize) {
for _ in 0..times {
run(workbench, cx, "editor.action.inlineSuggest.trigger");
provide(receiver, items.clone(), cx);
run(workbench, cx, "editor.action.inlineSuggest.acceptNextWord");
}
}
/// inlineCompletions.test.ts "Multi Cursor Support": "Basic", "Multi Part" and "Multi Part and Different Cursor
/// Columns": the edit repeats at a cursor only where the text around it is the same as around the primary one.
#[gpui::test]
fn accepting_repeats_the_edit_at_the_other_cursors(cx: &mut TestAppContext) {
let cases = [
("console\nconsole\n", [(0, 7), (1, 7)], "console[.log(\"hello\");]\nconsole[.log(\"hello\");]\n", "console.log(\"hello\");\nconsole.log(\"hello\");\n"),
("console.log()\nconsole.log\n", [(0, 11), (1, 11)], "console.log([\"hello\"])[;]\nconsole.log\n", "console.log(\"hello\");\nconsole.log\n"),
("console.log()\nconsole.warn\n", [(0, 11), (1, 12)], "console.log([\"hello\"])[;]\nconsole.warn\n", "console.log(\"hello\");\nconsole.warn\n"),
];
for (index, (document, carets, shown, accepted)) in cases.into_iter().enumerate() {
let (workbench, cx, receiver) = open_with_provider(cx, &format!("inline-multi-cursor-{index}"), document);
set_carets(&workbench, cx, &carets);
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
provide(&receiver, json!([{ "insertText": "console.log(\"hello\");", "range": range(1, 1, 1, 1000), "idx": 0 }]), cx);
assert_eq!(view(&workbench, cx), shown);
run(&workbench, cx, "editor.action.inlineSuggest.commit");
assert_eq!(text(&workbench, cx), accepted);
}
}
/// "Basic Partial Completion", "Partial Multi-Part Completion" and "Partial Mutli-Part and Different Cursor Columns
/// Completion": each accepted word repeats at the cursors whose text around them matches.
#[gpui::test]
fn accepting_a_word_repeats_it_at_the_other_cursors(cx: &mut TestAppContext) {
let cases = [
("let\nlet\n", [(0, 3), (1, 3)], "let a = 'some word'; ", 2, "let a\nlet a\n"),
("for ()\nfor \n", [(0, 4), (1, 4)], "for (let i = 0; i < 10; i++) {", 3, "for (let i)\nfor \n"),
("console.log()\nconsole.warnnnn\n", [(0, 11), (1, 15)], "console.log(\"hello\" + \" \" + \"world\");", 4, "console.log(\"hello\" + )\nconsole.warnnnn\n"),
];
for (index, (document, carets, insert_text, times, accepted)) in cases.into_iter().enumerate() {
let (workbench, cx, receiver) = open_with_provider(cx, &format!("inline-multi-cursor-word-{index}"), document);
set_carets(&workbench, cx, &carets);
let items = json!([{ "insertText": insert_text, "range": range(1, 1, 1, 1000), "idx": 0 }]);
accept_next_word(&workbench, cx, &receiver, &items, times);
assert_eq!(text(&workbench, cx), accepted);
}
}
/// `acceptNextLine` takes the line break with the line.
#[gpui::test]
fn accepting_a_line_takes_its_line_break(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-accept-line", "foo");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
provide(&receiver, json!([{ "insertText": "foobar\nbaz", "range": range(1, 1, 1, 4), "idx": 0 }]), cx);
run(&workbench, cx, "editor.action.inlineSuggest.acceptNextLine");
assert_eq!(view(&workbench, cx), "foobar\n[baz]");
}
const COMPLETIONS: u64 = 11;
/// suggestWidgetModel.test.ts `provider`: suggests "hello" over the word at the cursor, `.` triggers and commits it.
fn open_with_suggest<'a>(cx: &'a mut TestAppContext, name: &str, text: &str, settings: &[(&str, Value)]) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>) {
let (workbench, cx, receiver) = open_with_provider(cx, name, text);
workbench.update(cx, |workbench, _| {
workbench.language_features.register("$registerCompletionsProvider", vec![json!(COMPLETIONS), json!("*"), json!(["."]), json!(false)]);
for (key, value) in settings {
workbench.update_setting(key, value.clone());
}
});
(workbench, cx, receiver)
}
/// Waits out the delays and answers the completion requests with `hello` and the inline ones with `inline_items`,
/// until none comes; returns the inline requests' contexts.
fn answer_suggest(workbench: &gpui::Entity<Workbench>, receiver: &Receiver<HostMessage>, inline_items: &Value, cx: &mut VisualTestContext) -> Vec<Value> {
answer_suggest_with(workbench, receiver, &[json!({ "a": "hello" })], inline_items, cx)
}
/// `answer_suggest` with `suggestions`, each over the word at the cursor unless it has its range (`j`).
fn answer_suggest_with(workbench: &gpui::Entity<Workbench>, receiver: &Receiver<HostMessage>, suggestions: &[Value], inline_items: &Value, cx: &mut VisualTestContext) -> Vec<Value> {
let mut contexts = Vec::new();
loop {
cx.executor().advance_clock(Duration::from_millis(1000));
cx.run_until_parked();
let messages: Vec<HostMessage> = receiver.try_iter().filter(|message| message.method == "$provideCompletionItems" || message.method == "$provideInlineCompletions").collect();
if messages.is_empty() {
return contexts;
}
for message in messages {
let answer = match message.method {
"$provideInlineCompletions" => {
contexts.push(message.args[3].clone());
json!({ "items": inline_items, "pid": contexts.len() })
}
_ => completion_list(workbench, suggestions, cx),
};
let _ = message.reply.expect("a call").send(Ok(answer));
}
cx.run_until_parked();
}
}
fn completion_list(workbench: &gpui::Entity<Workbench>, suggestions: &[Value], cx: &mut VisualTestContext) -> Value {
let (head, word) = workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.active().unwrap();
let head = editor.selection().head.column;
(head, editor.document().word_at(&workbench.languages, 0, head).unwrap_or(head..head))
});
let word_range = range(1, word.start as u64 + 1, 1, word.end as u64 + 1);
let mut items = Vec::new();
for suggestion in suggestions {
let mut item = json!({ "b": crate::suggest::KIND_TEXT, "h": suggestion["a"], "k": ".", "j": word_range });
item.as_object_mut().unwrap().extend(suggestion.as_object().unwrap().clone());
items.push(item);
}
json!({ "a": range(1, head as u64 + 1, 1, head as u64 + 1), "b": items })
}
/// suggestWidgetModel.test.ts "Active" stays unported: upstream skips it, its fix causes microsoft/vscode#166023.
/// "Ghost Text": with `editor.suggest.preview` the focused suggest item shows as ghost text.
#[gpui::test]
fn the_focused_suggest_item_previews_as_ghost_text(cx: &mut TestAppContext) {
let quick = json!({ "other": "on", "comments": "off", "strings": "off" });
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-preview", "", &[("editor.suggest.preview", json!(true)), ("editor.quickSuggestions", quick)]);
type_text(&workbench, cx, "h");
run(&workbench, cx, "editor.action.triggerSuggest");
answer_suggest(&workbench, &receiver, &json!([]), cx);
assert_eq!(view(&workbench, cx), "h[ello]");
type_text(&workbench, cx, ".");
answer_suggest(&workbench, &receiver, &json!([]), cx);
assert_eq!(view(&workbench, cx), "hello.[hello]");
run(&workbench, cx, "hideSuggestWidget");
assert_eq!(view(&workbench, cx), "hello.");
}
/// "offWhenInlineCompletions: conflicting inline completion does not render over the suggest widget".
#[gpui::test]
fn an_inline_completion_that_conflicts_with_the_suggest_item_does_not_show(cx: &mut TestAppContext) {
let quick = json!({ "other": "offWhenInlineCompletions", "comments": "off", "strings": "off" });
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-conflict", "", &[("editor.quickSuggestions", quick)]);
type_text(&workbench, cx, "h");
run(&workbench, cx, "editor.action.triggerSuggest");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
answer_suggest(&workbench, &receiver, &json!([{ "insertText": "hi there", "range": range(1, 1, 1, 2), "idx": 0 }]), cx);
assert!(workbench.read_with(cx, |workbench, _| workbench.inline_completions.suggest_item.is_some()));
assert_eq!(view(&workbench, cx), "h");
}
/// `_computeAugmentation`: the providers hear the suggest item, and an inline completion that continues it shows
/// with it, the rest as preview.
#[gpui::test]
fn an_inline_completion_that_continues_the_suggest_item_shows_with_it(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-augment", "", &[]);
type_text(&workbench, cx, "h");
run(&workbench, cx, "editor.action.triggerSuggest");
let contexts = answer_suggest(&workbench, &receiver, &json!([{ "insertText": "hello world", "range": range(1, 1, 1, 2), "idx": 0 }]), cx);
assert_eq!(contexts.last().unwrap()["selectedSuggestionInfo"], json!({ "range": range(1, 1, 1, 2), "text": "hello", "completionKind": crate::suggest::KIND_TEXT, "isSnippetText": false }));
assert_eq!(view(&workbench, cx), "h[ello][ world]");
let preview: Vec<bool> = workbench.read_with(cx, |workbench, _| workbench.inline_completions.ghosts[0].parts.iter().map(|part| part.preview).collect());
assert_eq!(preview, [false, true]);
// `handleSuggestAccepted`: accepting the suggest item reports the part of the inline completion it took.
run(&workbench, cx, "acceptSelectedSuggestion");
let accepted: Vec<Value> = receiver.try_iter().filter(|message| message.method == "$handleInlineCompletionPartialAccept").map(|message| json!([message.args[0], message.args[3], message.args[4]])).collect();
assert_eq!(accepted, [json!([PROVIDER, 4, { "kind": 2, "acceptedLength": 5 }])]);
}
/// `_selectors`: the suggest widget focuses the item the shown inline completion continues, over the first one.
#[gpui::test]
fn the_suggest_widget_focuses_the_item_the_inline_completion_continues(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-preselect", "", &[]);
type_text(&workbench, cx, "h");
provide(&receiver, json!([{ "insertText": "hello world", "range": range(1, 1, 1, 2), "idx": 0 }]), cx);
assert_eq!(view(&workbench, cx), "h[ello world]");
run(&workbench, cx, "editor.action.triggerSuggest");
answer_suggest_with(&workbench, &receiver, &[json!({ "a": "hallo" }), json!({ "a": "hello" })], &json!([{ "insertText": "hello world", "range": range(1, 1, 1, 2), "idx": 0 }]), cx);
assert_eq!(view(&workbench, cx), "h[ello][ world]");
}
/// `InlineCompletionsSource`'s two lists: the shown inline completion does not augment the suggest item; only the
/// answer to the request with the suggest item does, and closing the widget seeds the ghost text with it.
#[gpui::test]
fn only_the_answer_with_the_suggest_item_augments_it(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-two-lists", "", &[]);
type_text(&workbench, cx, "h");
provide(&receiver, json!([{ "insertText": "hello world", "range": range(1, 1, 1, 2), "idx": 0 }]), cx);
assert_eq!(view(&workbench, cx), "h[ello world]");
run(&workbench, cx, "editor.action.triggerSuggest");
let mut held = Vec::new();
for _ in 0..3 {
wait(cx, 1000);
for message in receiver.try_iter() {
match message.method {
"$provideCompletionItems" => _ = message.reply.expect("a call").send(Ok(completion_list(&workbench, &[json!({ "a": "hello" })], cx))),
"$provideInlineCompletions" => held.push(message),
_ => {}
}
}
}
assert!(!held.is_empty() && held.iter().all(|message| !message.args[3]["selectedSuggestionInfo"].is_null()));
assert_eq!(view(&workbench, cx), "h");
for message in held {
_ = message.reply.expect("a call").send(Ok(json!({ "items": [{ "insertText": "hello there", "range": range(1, 1, 1, 2), "idx": 0 }], "pid": 90 })));
}
cx.run_until_parked();
assert_eq!(view(&workbench, cx), "h[ello][ there]");
run(&workbench, cx, "hideSuggestWidget");
assert_eq!(view(&workbench, cx), "h[ello there]");
}
/// `isShiftKeyPressed`: holding Shift previews the suggest item's replace edit instead of its insert edit.
#[gpui::test]
fn shift_previews_the_other_of_insert_and_replace(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_suggest(cx, "suggest-shift", "", &[("editor.suggest.preview", json!(true)), ("editor.quickSuggestions", json!(false))]);
type_text(&workbench, cx, "hlo");
run(&workbench, cx, "cursorLeft");
run(&workbench, cx, "cursorLeft");
run(&workbench, cx, "editor.action.triggerSuggest");
answer_suggest_with(&workbench, &receiver, &[json!({ "a": "hello", "j": { "insert": range(1, 1, 1, 2), "replace": range(1, 1, 1, 4) } })], &json!([]), cx);
assert_eq!(view(&workbench, cx), "h[ello]lo");
workbench.update(cx, |workbench, cx| workbench.inline_completions_modifiers_changed(true, cx));
assert_eq!(view(&workbench, cx), "h[el]lo");
}
/// suggestModel.test.ts "SuggestModel - offWhenInlineCompletions": `abc` with the cursor at its end, `other` kinds
/// waiting for the inline completions, and `settings` over that.
fn open_quick_suggest<'a>(cx: &'a mut TestAppContext, name: &str, settings: &[(&str, Value)]) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>) {
let mut all = vec![("editor.quickSuggestions", json!({ "comments": "off", "strings": "off", "other": "offWhenInlineCompletions" }))];
all.extend_from_slice(settings);
open_with_suggest(cx, name, "abc", &all)
}
/// Runs the clock `ms` and answers the inline requests with `inline_list`, or holds them in `held` when `None`;
/// returns whether quick suggest asked the completion providers (`onDidSuggest`).
fn quick_suggest_step(receiver: &Receiver<HostMessage>, inline_list: Option<&Value>, held: &mut Vec<HostMessage>, ms: u64, cx: &mut VisualTestContext) -> bool {
wait(cx, ms);
let mut suggested = false;
loop {
let messages: Vec<HostMessage> = receiver.try_iter().collect();
if messages.is_empty() {
return suggested;
}
for message in messages {
match (message.method, inline_list) {
("$provideCompletionItems", _) => suggested = true,
("$provideInlineCompletions", Some(list)) => _ = message.reply.expect("a call").send(Ok(list.clone())),
("$provideInlineCompletions", None) => held.push(message),
_ => {}
}
}
cx.run_until_parked();
}
}
/// "suppresses quick suggest when inline completions are showing ghost text".
#[gpui::test]
fn quick_suggest_waits_and_stays_off_when_inline_completions_show(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-inline-shows", &[]);
type_text(&workbench, cx, "d");
let list = json!({ "items": [{ "insertText": "abcdSuffix", "range": range(1, 1, 1, 5), "idx": 0 }], "pid": 1 });
assert!(!quick_suggest_step(&receiver, Some(&list), &mut Vec::new(), 200, cx));
assert_eq!(view(&workbench, cx), "abcd[Suffix]");
assert!(!quick_suggest_step(&receiver, None, &mut Vec::new(), 1000, cx));
}
/// "allows quick suggest when inline completions resolve with no results", and the string shorthand.
#[gpui::test]
fn quick_suggest_shows_when_inline_completions_answer_nothing(cx: &mut TestAppContext) {
for (name, quick) in [("quick-inline-empty", None), ("quick-inline-shorthand", Some(json!("offWhenInlineCompletions")))] {
let settings: Vec<(&str, Value)> = quick.into_iter().map(|quick| ("editor.quickSuggestions", quick)).collect();
let (workbench, cx, receiver) = open_quick_suggest(cx, name, &settings);
type_text(&workbench, cx, "d");
let mut held = Vec::new();
assert!(!quick_suggest_step(&receiver, None, &mut held, 100, cx));
assert!(!held.is_empty());
for message in held {
_ = message.reply.expect("a call").send(Ok(json!({ "items": [], "pid": 1 })));
}
assert!(quick_suggest_step(&receiver, None, &mut Vec::new(), 0, cx));
}
}
/// "allows quick suggest when inlineSuggest is disabled even with provider" and "allows quick suggest when no inline
/// provider exists": nothing to wait for.
#[gpui::test]
fn quick_suggest_does_not_wait_without_inline_completions(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-inline-disabled", &[("editor.inlineSuggest.enabled", json!(false))]);
type_text(&workbench, cx, "d");
assert!(quick_suggest_step(&receiver, None, &mut Vec::new(), 20, cx));
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-inline-none", &[]);
workbench.update(cx, |workbench, _| _ = workbench.language_features.unregister(PROVIDER));
type_text(&workbench, cx, "d");
assert!(quick_suggest_step(&receiver, None, &mut Vec::new(), 20, cx));
}
/// `disposableTimeout(750)`: inline completions that do not answer let quick suggest show and stop.
#[gpui::test]
fn quick_suggest_shows_after_the_wait_times_out(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-inline-timeout", &[]);
type_text(&workbench, cx, "d");
let mut held = Vec::new();
assert!(!quick_suggest_step(&receiver, None, &mut held, 700, cx));
assert!(quick_suggest_step(&receiver, None, &mut held, 100, cx));
assert!(workbench.read_with(cx, |workbench, _| workbench.inline_completions.request.is_none()));
}
/// "does not trigger after the inline model is disposed mid-wait (e.g., readonly toggled)".
#[gpui::test]
fn quick_suggest_does_not_show_after_the_editor_turns_read_only(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-inline-readonly", &[]);
type_text(&workbench, cx, "d");
let mut held = Vec::new();
assert!(!quick_suggest_step(&receiver, None, &mut held, 50, cx));
run(&workbench, cx, "workbench.action.files.setActiveEditorReadonlyInSession");
assert!(!quick_suggest_step(&receiver, None, &mut held, 1000, cx));
}
/// SuggestModel "string shorthand - \"off\" disables quick suggestions for all token types".
#[gpui::test]
fn the_off_shorthand_turns_quick_suggest_off(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-off", &[("editor.quickSuggestions", json!("off"))]);
type_text(&workbench, cx, "d");
assert!(!quick_suggest_step(&receiver, Some(&json!({ "items": [] })), &mut Vec::new(), 200, cx));
}
/// `canShowQuickSuggest` and `canShowSuggestOnTriggerCharacters`: a shown inline suggestion whose list sets
/// `suppressSuggestions` keeps the suggest widget from opening by itself.
#[gpui::test]
fn a_suppressing_inline_suggestion_keeps_the_widget_closed(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_quick_suggest(cx, "quick-suppress", &[("editor.quickSuggestions", json!("on"))]);
type_text(&workbench, cx, "d");
let list = json!({ "items": [{ "insertText": "abcdS.x", "idx": 0 }], "suppressSuggestions": true, "pid": 1 });
quick_suggest_step(&receiver, Some(&list), &mut Vec::new(), 200, cx);
run(&workbench, cx, "hideSuggestWidget");
assert_eq!(view(&workbench, cx), "abcd[S.x]");
type_text(&workbench, cx, "S");
assert!(!quick_suggest_step(&receiver, Some(&list), &mut Vec::new(), 200, cx));
type_text(&workbench, cx, ".");
assert_eq!(view(&workbench, cx), "abcdS.[x]");
assert!(!quick_suggest_step(&receiver, None, &mut Vec::new(), 200, cx));
}
/// inlineCompletions.test.ts "Emits empty response telemetry after instantiation service disposal" stays unported:
/// the port has no telemetry. "Does not trigger automatically if disabled".
#[gpui::test]
fn a_disabled_feature_does_not_ask_while_typing(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-disabled", "");
workbench.update(cx, |workbench, _| workbench.update_setting("editor.inlineSuggest.enabled", json!(false)));
type_text(&workbench, cx, "foo");
assert!(provide(&receiver, json!([{ "insertText": "foobar", "idx": 0 }]), cx).is_empty());
assert_eq!(view(&workbench, cx), "foo");
}
/// "Ghost text is shown after trigger".
#[gpui::test]
fn ghost_text_shows_after_a_trigger(cx: &mut TestAppContext) {
let items = json!([{ "insertText": "foobar", "range": range(1, 1, 1, 4), "idx": 0 }]);
let (workbench, cx, receiver) = open_with_provider(cx, "inline-shown-after-trigger", "foo");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
assert_eq!(asked(&provide(&receiver, items.clone(), cx)), [(1, 4, 1)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
}
/// `getDefaultRange` (provideInlineCompletions.ts): an item without a range replaces from the word start to the line end.
#[gpui::test]
fn an_item_without_a_range_replaces_up_to_the_line_end(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-default-range", "foo)");
set_carets(&workbench, cx, &[(0, 3)]);
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
provide(&receiver, json!([{ "insertText": "foobar)", "idx": 0 }]), cx);
assert_eq!(view(&workbench, cx), "foo[bar])");
}
/// "Ghost text is shown automatically when configured".
#[gpui::test]
fn ghost_text_shows_while_typing(cx: &mut TestAppContext) {
let items = json!([{ "insertText": "foobar", "range": range(1, 1, 1, 4), "idx": 0 }]);
let (workbench, cx, receiver) = open_with_provider(cx, "inline-shown-automatically", "");
type_text(&workbench, cx, "foo");
assert_eq!(asked(&provide(&receiver, items, cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
}
/// "Ghost text is updated automatically".
#[gpui::test]
fn ghost_text_follows_typing_and_the_next_answer(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-updated", "");
type_text(&workbench, cx, "foo");
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foobar", "range": range(1, 1, 1, 4), "idx": 0 }]), cx)), [(1, 4, 1)]);
assert_eq!(view(&workbench, cx), "foo[bar]");
type_text(&workbench, cx, "b");
assert_eq!(view(&workbench, cx), "foob[ar]");
type_text(&workbench, cx, "i");
assert_eq!(view(&workbench, cx), "foobi");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foobizz", "range": range(1, 1, 1, 6), "idx": 0 }]), cx)), [(1, 6, 0)]);
assert_eq!(view(&workbench, cx), "foobi[zz]");
}
/// "Unindent whitespace", "Unindent tab" and "No unindent after indentation": an item replacing indentation shows
/// after it and accepting replaces it; after other text it does not show.
#[gpui::test]
fn an_item_over_indentation_unindents_it(cx: &mut TestAppContext) {
for (name, typed, edit_column, shown, accepted) in [("inline-unindent", " ", 2, Some(" [foo]"), " foo"), ("inline-unindent-tab", "\t\t", 2, Some("\t\t[foo]"), "\tfoo"), ("inline-no-unindent", "buzz ", 6, None, "buzz ")] {
let (workbench, cx, receiver) = open_with_provider(cx, name, "");
type_text(&workbench, cx, typed);
provide(&receiver, json!([]), cx);
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
let column = typed.len() as u64 + 1;
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foo", "range": range(1, edit_column, 1, edit_column + 1), "idx": 0 }]), cx)), [(1, column, 1)]);
assert_eq!(view(&workbench, cx), shown.unwrap_or(typed), "{name}");
run(&workbench, cx, "editor.action.inlineSuggest.commit");
assert_eq!(text(&workbench, cx), accepted, "{name}");
}
}
/// "Next/previous": showing the next item asks explicitly once, then cycles through the items both ways.
#[gpui::test]
fn next_and_previous_cycle_through_the_items(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-next-previous", "");
type_text(&workbench, cx, "foo");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "foobar1", "range": range(1, 1, 1, 4), "idx": 0 }]), cx)), [(1, 4, 0)]);
assert_eq!(view(&workbench, cx), "foo[bar1]");
let items = json!(["foobar1", "foobizz2", "foobuzz3"].iter().enumerate().map(|(idx, text)| json!({ "insertText": text, "range": range(1, 1, 1, 4), "idx": idx })).collect::<Vec<_>>());
run(&workbench, cx, "editor.action.inlineSuggest.showNext");
assert_eq!(asked(&provide(&receiver, items.clone(), cx)), [(1, 4, 1)]);
let mut views = vec![view(&workbench, cx)];
for command in ["showNext", "showNext", "showPrevious", "showPrevious", "showPrevious"] {
run(&workbench, cx, &format!("editor.action.inlineSuggest.{command}"));
assert!(provide(&receiver, items.clone(), cx).is_empty());
views.push(view(&workbench, cx));
}
assert_eq!(views, ["foo[bizz2]", "foo[buzz3]", "foo[bar1]", "foo[buzz3]", "foo[bizz2]", "foo[bar1]"]);
}
/// inlineCompletionsSource.ts `distinctByKey(updatedItems, i => i.semanticId)`: two ranges around the same change,
/// trimmed of their common prefix and suffix, are one item when cycling.
#[gpui::test]
fn items_with_the_same_trimmed_edit_cycle_as_one(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-semantic-id", "");
type_text(&workbench, cx, "foo");
let items = json!([
{ "insertText": "foobar1", "range": range(1, 1, 1, 4), "idx": 0 },
{ "insertText": "bar1", "range": range(1, 4, 1, 4), "idx": 1 },
{ "insertText": "foobizz2", "range": range(1, 1, 1, 4), "idx": 2 },
]);
provide(&receiver, items.clone(), cx);
let mut views = vec![view(&workbench, cx)];
for _ in 0..3 {
run(&workbench, cx, "editor.action.inlineSuggest.showNext");
provide(&receiver, items.clone(), cx);
views.push(view(&workbench, cx));
}
assert_eq!(views, ["foo[bar1]", "foo[bizz2]", "foo[bar1]", "foo[bizz2]"]);
}
/// "Calling the provider is debounced" and "Backspace is debounced": keys 40ms apart, or backspaces 5ms apart,
/// ask once, 50ms after the last.
#[gpui::test]
fn typing_and_deleting_ask_once_after_the_debounce(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-debounce", "");
for typed in ["f", "o", "o"] {
type_text(&workbench, cx, typed);
wait(cx, 40);
}
assert!(answer(&receiver, json!({ "items": [] }), cx).is_empty());
wait(cx, 400);
assert_eq!(asked(&answer(&receiver, json!({ "items": [{ "insertText": "foobar", "range": range(1, 1, 1, 4), "idx": 0 }] }), cx)), [(1, 4, 0)]);
for _ in 0..2 {
for _ in 0..3 {
run(&workbench, cx, "deleteLeft");
wait(cx, 5);
}
type_text(&workbench, cx, "bar");
}
assert!(answer(&receiver, json!({ "items": [] }), cx).is_empty());
wait(cx, 400);
assert_eq!(asked(&answer(&receiver, json!({ "items": [] }), cx)), [(1, 4, 0)]);
}
/// "No race conditions": an answer to a request typing outdated does not show.
#[gpui::test]
fn an_answer_for_older_text_does_not_show(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-race", "");
type_text(&workbench, cx, "h");
provide(&receiver, json!([]), cx);
run(&workbench, cx, "editor.action.inlineSuggest.trigger");
wait(cx, 1000);
let outdated: Vec<HostMessage> = receiver.try_iter().filter(|message| message.method == "$provideInlineCompletions").collect();
assert_eq!(outdated.len(), 1);
type_text(&workbench, cx, "ello");
for message in outdated {
let _ = message.reply.expect("a call").send(Ok(json!({ "items": [{ "insertText": "helloworld", "range": range(1, 1, 1, 2), "idx": 0 }], "pid": 1 })));
}
cx.run_until_parked();
assert_eq!(view(&workbench, cx), "hello");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "helloworld", "range": range(1, 1, 1, 6), "idx": 0 }]), cx)), [(1, 6, 0)]);
assert_eq!(view(&workbench, cx), "hello[world]");
}
/// "Do not reuse cache from previous session (#132516)": an item for the line above does not show on the next one.
#[gpui::test]
fn an_item_for_another_line_is_not_reused(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-no-cache-reuse", "");
type_text(&workbench, cx, "hello\n");
run(&workbench, cx, "cursorLeft");
type_text(&workbench, cx, "x");
run(&workbench, cx, "deleteLeft");
assert_eq!(asked(&provide(&receiver, json!([{ "insertText": "helloworld", "range": range(1, 1, 1, 6), "idx": 0 }]), cx)), [(1, 6, 0)]);
assert_eq!(view(&workbench, cx), "hello[world]\n");
run(&workbench, cx, "cursorDown");
type_text(&workbench, cx, "hello");
wait(cx, 40);
assert!(answer(&receiver, json!({ "items": [] }), cx).is_empty());
assert_eq!(view(&workbench, cx), "hello\nhello");
type_text(&workbench, cx, "w");
run(&workbench, cx, "deleteLeft");
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]");
}
/// inlineCompletionsHintsWidget.ts with `showToolbar: always`: the toolbar shows above the ghost text and asks for
/// every item explicitly.
#[gpui::test]
fn the_always_shown_toolbar_sits_above_the_ghost_text(cx: &mut TestAppContext) {
let (workbench, cx, receiver) = open_with_provider(cx, "inline-hints-always", "x\nfoo");
workbench.update(cx, |workbench, _| workbench.update_setting("editor.inlineSuggest.showToolbar", json!("always")));
type_text(&workbench, cx, "b");
let items = json!([{ "insertText": "foobar", "range": range(2, 1, 2, 5), "idx": 0 }]);
assert_eq!(asked(&provide(&receiver, items.clone(), cx)), [(2, 5, 0)]);
assert_eq!(asked(&answer(&receiver, json!({ "items": items }), cx)), [(2, 5, 1)], "the toolbar asks explicitly");
for _ in 0..3 {
cx.update(|window, _| window.refresh());
cx.run_until_parked();
}
let hints = cx.debug_bounds("inline-suggestion-hints").expect("the toolbar shows");
let line_top = workbench.read_with(cx, |workbench, _| workbench.text_area_bounds.get().origin.y + workbench.editors.viewport.line_height);
assert_eq!(hints.bottom(), px(line_top + 2.), "the reference's box ends 2px into line 2");
assert_eq!(hints.size.height, px(1. + 4. + 25.5 + 4. + 1.), "the labels without keybindings inside the 4px padding and the border");
}
/// 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");
// The reference's DOM: the count's 19.5px line inside its label's 3px padding.
assert_eq!(cx.debug_bounds("inline-suggestion-count").unwrap().size.height, px(25.5));
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, left) = workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("the ... menu shows");
let titles = menu.levels[0].actions.iter().map(|action| match action {
MenuAction::Command { title, .. } => title.clone(),
_ => "-".into(),
}).collect::<Vec<_>>();
(titles, menu.levels[0].origin.x)
});
assert_eq!(titles, ["Accept Line", "Always Show Toolbar", "-", "Port List Command", "Port Inline Action"]);
assert_eq!(left, more.left(), "the dropdown's default `AnchorAlignment.LEFT`");
}
#[gpui::test]
fn the_chars_around_the_ghost_text_and_the_empty_area_after_it_anchor_the_hover(cx: &mut TestAppContext) {
use crate::workbench::content_hover::Anchor;
let (workbench, cx, receiver) = open_with_provider(cx, "inline-hover-anchors", "foo");
type_text(&workbench, cx, "b");
provide_list(&receiver, json!({ "items": [{ "insertText": "foobar", "range": range(1, 1, 1, 5) }] }), cx);
assert_eq!(view(&workbench, cx), "foob[ar]");
workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.active().unwrap();
let parts_at = |start, end| workbench.inline_completions_hover_parts(editor, Anchor { model_id: editor.model_id, line: 0, start, end }).len();
// inlineCompletionsController.ts `shouldShowHoverAt`: `Range.containsPosition` takes both ends.
assert_eq!(parts_at(3, 4), 1, "the char before the ghost text");
assert_eq!(parts_at(4, 4), 1, "the ghost text");
assert_eq!(parts_at(2, 3), 0, "a char off it");
assert_eq!(workbench.inline_completions_empty_area_anchor(editor, 0), Some(Anchor { model_id: editor.model_id, line: 0, start: 4, end: 4 }));
assert_eq!(workbench.inline_completions_empty_area_anchor(editor, 1), None);
});
}