Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LSP Completion preselect and preview doc #2705

Closed
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions book/src/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,18 @@ hidden = false
| `auto-format` | Enable automatic formatting on save. | `true` |
| `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. Used for autocompletion, set to 0 for instant. | `400` |
| `completion-trigger-len` | The min-length of word under cursor to trigger autocompletion | `2` |
| `completion-doc-preview` | Show the documentation of the first item in the completion menu | `false` |
| `auto-info` | Whether to display infoboxes | `true` |
| `true-color` | Set to `true` to override automatic detection of terminal truecolor support in the event of a false negative. | `false` |
| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file. | `[]` |
| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` |

### `[editor.lsp]` Section

| Key | Description | Default |
| --- | ----------- | ------- |
| `display-messages` | Display LSP progress messages below statusline[^1] | `false` |
| Key | Description | Default |
| --- | ----------- | ------- |
| `display-messages` | Display LSP progress messages below statusline[^1] | `false` |
| `preselect` | Show the LSP server's preselected suggestions first | `true` |

[^1]: A progress spinner is always shown in the statusline beside the file path.

Expand Down
51 changes: 29 additions & 22 deletions helix-term/src/commands/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,34 +449,41 @@ pub fn code_action(cx: &mut Context) {
return;
}

let mut picker = ui::Menu::new(actions, (), move |editor, code_action, event| {
if event != PromptEvent::Validate {
return;
}
let mut picker = ui::Menu::new(
actions,
(),
ui::menu::SortStrategy::Text,
false,
move |editor, code_action, event| {
if event != PromptEvent::Validate {
return;
}

// always present here
let code_action = code_action.unwrap();
// always present here
let code_action = code_action.unwrap();

match code_action {
lsp::CodeActionOrCommand::Command(command) => {
log::debug!("code action command: {:?}", command);
execute_lsp_command(editor, command.clone());
}
lsp::CodeActionOrCommand::CodeAction(code_action) => {
log::debug!("code action: {:?}", code_action);
if let Some(ref workspace_edit) = code_action.edit {
log::debug!("edit: {:?}", workspace_edit);
apply_workspace_edit(editor, offset_encoding, workspace_edit);
match code_action {
lsp::CodeActionOrCommand::Command(command) => {
log::debug!("code action command: {:?}", command);
execute_lsp_command(editor, command.clone());
}

// if code action provides both edit and command first the edit
// should be applied and then the command
if let Some(command) = &code_action.command {
execute_lsp_command(editor, command.clone());
lsp::CodeActionOrCommand::CodeAction(code_action) => {
log::debug!("code action: {:?}", code_action);
if let Some(ref workspace_edit) = code_action.edit {
log::debug!("edit: {:?}", workspace_edit);
apply_workspace_edit(editor, offset_encoding, workspace_edit);
}

// if code action provides both edit and command first the edit
// should be applied and then the command
if let Some(command) = &code_action.command {
execute_lsp_command(editor, command.clone());
}
}
}
}
});
},
);
picker.move_down(); // pre-select the first item

let popup =
Expand Down
254 changes: 138 additions & 116 deletions helix-term/src/ui/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ impl menu::Item for CompletionItem {
// .as_str(),
])
}

fn preselected(&self) -> bool {
self.preselect.unwrap_or(false)
}
}

/// Wraps a Menu.
Expand All @@ -92,128 +96,137 @@ impl Completion {
start_offset: usize,
trigger_offset: usize,
) -> Self {
let menu = Menu::new(items, (), move |editor: &mut Editor, item, event| {
fn item_to_transaction(
doc: &Document,
item: &CompletionItem,
offset_encoding: helix_lsp::OffsetEncoding,
start_offset: usize,
trigger_offset: usize,
) -> Transaction {
let transaction = if let Some(edit) = &item.text_edit {
let edit = match edit {
lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
lsp::CompletionTextEdit::InsertAndReplace(item) => {
unimplemented!("completion: insert_and_replace {:?}", item)
}
let menu = Menu::new(
items,
(),
menu::SortStrategy::Score,
editor.config().lsp.preselect.unwrap_or(false),
move |editor: &mut Editor, item, event| {
fn item_to_transaction(
doc: &Document,
item: &CompletionItem,
offset_encoding: helix_lsp::OffsetEncoding,
start_offset: usize,
trigger_offset: usize,
) -> Transaction {
let transaction = if let Some(edit) = &item.text_edit {
let edit = match edit {
lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
lsp::CompletionTextEdit::InsertAndReplace(item) => {
unimplemented!("completion: insert_and_replace {:?}", item)
}
};

util::generate_transaction_from_edits(
doc.text(),
vec![edit],
offset_encoding, // TODO: should probably transcode in Client
)
} else {
let text = item.insert_text.as_ref().unwrap_or(&item.label);
// Some LSPs just give you an insertText with no offset ¯\_(ツ)_/¯
// in these cases we need to check for a common prefix and remove it
let prefix = Cow::from(doc.text().slice(start_offset..trigger_offset));
let text = text.trim_start_matches::<&str>(&prefix);
Transaction::change(
doc.text(),
vec![(trigger_offset, trigger_offset, Some(text.into()))].into_iter(),
)
};

util::generate_transaction_from_edits(
doc.text(),
vec![edit],
offset_encoding, // TODO: should probably transcode in Client
)
} else {
let text = item.insert_text.as_ref().unwrap_or(&item.label);
// Some LSPs just give you an insertText with no offset ¯\_(ツ)_/¯
// in these cases we need to check for a common prefix and remove it
let prefix = Cow::from(doc.text().slice(start_offset..trigger_offset));
let text = text.trim_start_matches::<&str>(&prefix);
Transaction::change(
doc.text(),
vec![(trigger_offset, trigger_offset, Some(text.into()))].into_iter(),
)
};

transaction
}

fn completion_changes(transaction: &Transaction, trigger_offset: usize) -> Vec<Change> {
transaction
.changes_iter()
.filter(|(start, end, _)| (*start..=*end).contains(&trigger_offset))
.collect()
}
transaction
}

let (view, doc) = current!(editor);
fn completion_changes(
transaction: &Transaction,
trigger_offset: usize,
) -> Vec<Change> {
transaction
.changes_iter()
.filter(|(start, end, _)| (*start..=*end).contains(&trigger_offset))
.collect()
}

// if more text was entered, remove it
doc.restore(view.id);
let (view, doc) = current!(editor);

match event {
PromptEvent::Abort => {
doc.restore(view.id);
editor.last_completion = None;
}
PromptEvent::Update => {
// always present here
let item = item.unwrap();

let transaction = item_to_transaction(
doc,
item,
offset_encoding,
start_offset,
trigger_offset,
);

// initialize a savepoint
doc.savepoint();
doc.apply(&transaction, view.id);

editor.last_completion = Some(CompleteAction {
trigger_offset,
changes: completion_changes(&transaction, trigger_offset),
});
}
PromptEvent::Validate => {
// always present here
let item = item.unwrap();

let transaction = item_to_transaction(
doc,
item,
offset_encoding,
start_offset,
trigger_offset,
);

doc.apply(&transaction, view.id);

editor.last_completion = Some(CompleteAction {
trigger_offset,
changes: completion_changes(&transaction, trigger_offset),
});

// apply additional edits, mostly used to auto import unqualified types
let resolved_item = if item
.additional_text_edits
.as_ref()
.map(|edits| !edits.is_empty())
.unwrap_or(false)
{
None
} else {
Self::resolve_completion_item(doc, item.clone())
};
// if more text was entered, remove it
doc.restore(view.id);

if let Some(additional_edits) = resolved_item
.as_ref()
.and_then(|item| item.additional_text_edits.as_ref())
.or(item.additional_text_edits.as_ref())
{
if !additional_edits.is_empty() {
let transaction = util::generate_transaction_from_edits(
doc.text(),
additional_edits.clone(),
offset_encoding, // TODO: should probably transcode in Client
);
doc.apply(&transaction, view.id);
match event {
PromptEvent::Abort => {
doc.restore(view.id);
editor.last_completion = None;
}
PromptEvent::Update => {
// always present here
let item = item.unwrap();

let transaction = item_to_transaction(
doc,
item,
offset_encoding,
start_offset,
trigger_offset,
);

// initialize a savepoint
doc.savepoint();
doc.apply(&transaction, view.id);

editor.last_completion = Some(CompleteAction {
trigger_offset,
changes: completion_changes(&transaction, trigger_offset),
});
}
PromptEvent::Validate => {
// always present here
let item = item.unwrap();

let transaction = item_to_transaction(
doc,
item,
offset_encoding,
start_offset,
trigger_offset,
);

doc.apply(&transaction, view.id);

editor.last_completion = Some(CompleteAction {
trigger_offset,
changes: completion_changes(&transaction, trigger_offset),
});

// apply additional edits, mostly used to auto import unqualified types
let resolved_item = if item
.additional_text_edits
.as_ref()
.map(|edits| !edits.is_empty())
.unwrap_or(false)
{
None
} else {
Self::resolve_completion_item(doc, item.clone())
};

if let Some(additional_edits) = resolved_item
.as_ref()
.and_then(|item| item.additional_text_edits.as_ref())
.or(item.additional_text_edits.as_ref())
{
if !additional_edits.is_empty() {
let transaction = util::generate_transaction_from_edits(
doc.text(),
additional_edits.clone(),
offset_encoding, // TODO: should probably transcode in Client
);
doc.apply(&transaction, view.id);
}
}
}
}
};
});
};
},
);
let popup = Popup::new("completion", menu);
let mut completion = Self {
popup,
Expand Down Expand Up @@ -311,8 +324,17 @@ impl Component for Completion {
fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
self.popup.render(area, surface, cx);

// if we have a selection, render a markdown popup on top/below with info
if let Some(option) = self.popup.contents().selection() {
// If we have a selection or a doc preview, render a markdown popup on top/below with info
let mut option = self.popup.contents().selection();
if option.is_none()
&& cx.editor.config().completion_doc_preview
&& !self.popup.contents().is_empty()
{
// The doc preview will show the doc for the first completion item even when not selected
option = self.popup.contents().get_match(0);
}

if let Some(option) = option {
// need to render:
// option.detail
// ---
Expand Down
Loading