Skip to content

Commit 4618af1

Browse files
fix(completions): sort items by relevance on client (#362)
1 parent b2f8f0c commit 4618af1

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

crates/pgt_completions/src/builder.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ impl<'a> CompletionBuilder<'a> {
5050

5151
let should_preselect_first_item = should_preselect_first_item(&items);
5252

53+
/*
54+
* LSP Clients themselves sort the completion items.
55+
* They'll use the `sort_text` property if present (or fallback to the `label`).
56+
* Since our items are already sorted, we're 'hijacking' the sort_text.
57+
* We're simply adding the index of the item, padded by zeroes to the max length.
58+
*/
59+
let max_padding = items.len().to_string().len();
60+
5361
items
5462
.into_iter()
5563
.enumerate()
@@ -61,7 +69,9 @@ impl<'a> CompletionBuilder<'a> {
6169
kind: item.kind,
6270
label: item.label,
6371
preselected,
64-
score: item.score.get_score(),
72+
73+
// wonderous Rust syntax ftw
74+
sort_text: format!("{:0>padding$}", idx, padding = max_padding),
6575
}
6676
})
6777
.collect()

crates/pgt_completions/src/item.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::fmt::Display;
2+
13
use serde::{Deserialize, Serialize};
24

35
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -10,12 +12,26 @@ pub enum CompletionItemKind {
1012
Schema,
1113
}
1214

15+
impl Display for CompletionItemKind {
16+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17+
let txt = match self {
18+
CompletionItemKind::Table => "Table",
19+
CompletionItemKind::Function => "Function",
20+
CompletionItemKind::Column => "Column",
21+
CompletionItemKind::Schema => "Schema",
22+
};
23+
24+
write!(f, "{txt}")
25+
}
26+
}
27+
1328
#[derive(Debug, Serialize, Deserialize)]
1429
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1530
pub struct CompletionItem {
1631
pub label: String,
17-
pub(crate) score: i32,
1832
pub description: String,
1933
pub preselected: bool,
2034
pub kind: CompletionItemKind,
35+
/// String used for sorting by LSP clients.
36+
pub sort_text: String,
2137
}

crates/pgt_lsp/src/handlers/completions.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@ pub fn get_completions(
3232
label: i.label,
3333
label_details: Some(CompletionItemLabelDetails {
3434
description: Some(i.description),
35-
detail: None,
35+
detail: Some(format!(" {}", i.kind)),
3636
}),
3737
preselect: Some(i.preselected),
38+
sort_text: Some(i.sort_text),
3839
kind: Some(to_lsp_types_completion_item_kind(i.kind)),
3940
..CompletionItem::default()
4041
})

0 commit comments

Comments
 (0)