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

Tailwind autocomplete #2920

Merged
merged 28 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7a67ec5
Add support for querying multiple language servers for completions
ForLoveOfCats Aug 15, 2023
40ce099
Use originating language server to resolve additional completion edits
ForLoveOfCats Aug 15, 2023
8839b07
Add broken Tailwind language server
ForLoveOfCats Aug 16, 2023
e54f16f
Register initial request handlers before launching server
ForLoveOfCats Aug 17, 2023
4f0fa21
Provide more data to tailwind langserver
SomeoneToIgnore Aug 17, 2023
a979e32
Utilize LSP completion `itemDefaults` a bit
ForLoveOfCats Aug 18, 2023
c842e87
Use updated lsp-types fork branch
ForLoveOfCats Aug 18, 2023
007d1b0
Z 2819 (#2872)
osiewicz Aug 22, 2023
a35b3f3
Expand word characters for html and css
SomeoneToIgnore Aug 22, 2023
814896d
Reenable html, remove emmet due to the lack of the code
SomeoneToIgnore Aug 22, 2023
affb73d
Only generate workspace/configuration for relevant adapter
ForLoveOfCats Aug 23, 2023
68408f3
Add VSCode CSS language server & add Tailwind to .css files
ForLoveOfCats Aug 23, 2023
a394aaa
Add Tailwind server to JS/TS
ForLoveOfCats Aug 23, 2023
fc457d4
Add `word_characters` to language overrides & use for more things
ForLoveOfCats Aug 25, 2023
ded6dec
Initial unstyled language server short name in completions
ForLoveOfCats Aug 28, 2023
35b7787
Add Tailwind server to TSX
ForLoveOfCats Aug 28, 2023
15628af
Style language server name in completion menu
ForLoveOfCats Aug 29, 2023
0e6c918
Woooooops, don't notify the language server until initialized
ForLoveOfCats Aug 29, 2023
e3a0252
Make multi-server completion requests not serial
ForLoveOfCats Aug 30, 2023
7e5735c
Reap overly long LSP requests with a 2m timeout
SomeoneToIgnore Aug 30, 2023
529adb9
Scope Tailwind in JS/TS to within string
ForLoveOfCats Aug 31, 2023
ff3865a
Merge branch 'main' into multi-server-completions-tailwind
ForLoveOfCats Aug 31, 2023
9e12df4
Post-rebase fixes
SomeoneToIgnore Aug 31, 2023
fff385a
Fix project tests
SomeoneToIgnore Aug 31, 2023
292af55
Ensure all client LSP queries are forwarded via collab
SomeoneToIgnore Aug 31, 2023
5bc5831
Fix wrong assertion in the test
SomeoneToIgnore Aug 31, 2023
e682db7
Route completion requests through remote protocol, if needed
SomeoneToIgnore Aug 31, 2023
5731ef5
Fix plugin LSP adapter intefrace
SomeoneToIgnore Aug 31, 2023
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
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 125 additions & 27 deletions crates/editor/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use gpui::{
elements::*,
executor,
fonts::{self, HighlightStyle, TextStyle},
geometry::vector::Vector2F,
geometry::vector::{vec2f, Vector2F},
impl_actions,
keymap_matcher::KeymapContext,
platform::{CursorStyle, MouseButton},
Expand Down Expand Up @@ -820,6 +820,7 @@ struct CompletionsMenu {
id: CompletionId,
initial_position: Anchor,
buffer: ModelHandle<Buffer>,
project: Option<ModelHandle<Project>>,
completions: Arc<[Completion]>,
match_candidates: Vec<StringMatchCandidate>,
matches: Arc<[StringMatch]>,
Expand Down Expand Up @@ -863,6 +864,48 @@ impl CompletionsMenu {
fn render(&self, style: EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
enum CompletionTag {}

let language_servers = self.project.as_ref().map(|project| {
project
.read(cx)
.language_servers_for_buffer(self.buffer.read(cx), cx)
.filter(|(_, server)| server.capabilities().completion_provider.is_some())
.map(|(adapter, server)| (server.server_id(), adapter.short_name))
.collect::<Vec<_>>()
});
let needs_server_name = language_servers
.as_ref()
.map_or(false, |servers| servers.len() > 1);

let get_server_name =
move |lookup_server_id: lsp::LanguageServerId| -> Option<&'static str> {
language_servers
.iter()
.flatten()
.find_map(|(server_id, server_name)| {
if *server_id == lookup_server_id {
Some(*server_name)
} else {
None
}
})
};

let widest_completion_ix = self
.matches
.iter()
.enumerate()
.max_by_key(|(_, mat)| {
let completion = &self.completions[mat.candidate_id];
let mut len = completion.label.text.chars().count();

if let Some(server_name) = get_server_name(completion.server_id) {
len += server_name.chars().count();
}

len
})
.map(|(ix, _)| ix);

let completions = self.completions.clone();
let matches = self.matches.clone();
let selected_item = self.selected_item;
Expand All @@ -889,19 +932,83 @@ impl CompletionsMenu {
style.autocomplete.item
};

Text::new(completion.label.text.clone(), style.text.clone())
.with_soft_wrap(false)
.with_highlights(combine_syntax_and_fuzzy_match_highlights(
&completion.label.text,
style.text.color.into(),
styled_runs_for_code_label(
&completion.label,
&style.syntax,
),
&mat.positions,
))
.contained()
.with_style(item_style)
let completion_label =
Text::new(completion.label.text.clone(), style.text.clone())
.with_soft_wrap(false)
.with_highlights(
combine_syntax_and_fuzzy_match_highlights(
&completion.label.text,
style.text.color.into(),
styled_runs_for_code_label(
&completion.label,
&style.syntax,
),
&mat.positions,
),
);

if let Some(server_name) = get_server_name(completion.server_id) {
Flex::row()
.with_child(completion_label)
.with_children((|| {
if !needs_server_name {
return None;
}

let text_style = TextStyle {
color: style.autocomplete.server_name_color,
font_size: style.text.font_size
* style.autocomplete.server_name_size_percent,
..style.text.clone()
};

let label = Text::new(server_name, text_style)
.aligned()
.constrained()
.dynamically(move |constraint, _, _| {
gpui::SizeConstraint {
min: constraint.min,
max: vec2f(
constraint.max.x(),
constraint.min.y(),
),
}
});

if Some(item_ix) == widest_completion_ix {
Some(
label
.contained()
.with_style(
style
.autocomplete
.server_name_container,
)
.into_any(),
)
} else {
Some(label.flex_float().into_any())
}
})())
.into_any()
} else {
completion_label.into_any()
}
.contained()
.with_style(item_style)
.constrained()
.dynamically(
move |constraint, _, _| {
if Some(item_ix) == widest_completion_ix {
constraint
} else {
gpui::SizeConstraint {
min: constraint.min,
max: constraint.min,
}
}
},
)
},
)
.with_cursor_style(CursorStyle::PointingHand)
Expand All @@ -918,19 +1025,7 @@ impl CompletionsMenu {
}
},
)
.with_width_from_item(
self.matches
.iter()
.enumerate()
.max_by_key(|(_, mat)| {
self.completions[mat.candidate_id]
.label
.text
.chars()
.count()
})
.map(|(ix, _)| ix),
)
.with_width_from_item(widest_completion_ix)
.contained()
.with_style(container_style)
.into_any()
Expand Down Expand Up @@ -2983,6 +3078,7 @@ impl Editor {
});

let id = post_inc(&mut self.next_completion_id);
let project = self.project.clone();
let task = cx.spawn(|this, mut cx| {
async move {
let menu = if let Some(completions) = completions.await.log_err() {
Expand All @@ -3001,6 +3097,7 @@ impl Editor {
})
.collect(),
buffer,
project,
completions: completions.into(),
matches: Vec::new().into(),
selected_item: 0,
Expand Down Expand Up @@ -9186,6 +9283,7 @@ pub fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str
None
})
.flat_map(|word| word.split_inclusive('_'))
.flat_map(|word| word.split_inclusive('-'))
}

trait RangeToAnchorExt {
Expand Down
102 changes: 101 additions & 1 deletion crates/editor/src/editor_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use gpui::{
use indoc::indoc;
use language::{
language_settings::{AllLanguageSettings, AllLanguageSettingsContent, LanguageSettingsContent},
BracketPairConfig, FakeLspAdapter, LanguageConfig, LanguageRegistry, Point,
BracketPairConfig, FakeLspAdapter, LanguageConfig, LanguageConfigOverride, LanguageRegistry,
Override, Point,
};
use parking_lot::Mutex;
use project::project_settings::{LspSettings, ProjectSettings};
Expand Down Expand Up @@ -7688,6 +7689,105 @@ async fn test_completions_with_additional_edits(cx: &mut gpui::TestAppContext) {
cx.assert_editor_state(indoc! {"fn main() { let a = Some(2)ˇ; }"});
}

#[gpui::test]
async fn test_completions_in_languages_with_extra_word_characters(cx: &mut gpui::TestAppContext) {
init_test(cx, |_| {});

let mut cx = EditorLspTestContext::new(
Language::new(
LanguageConfig {
path_suffixes: vec!["jsx".into()],
overrides: [(
"element".into(),
LanguageConfigOverride {
word_characters: Override::Set(['-'].into_iter().collect()),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
},
Some(tree_sitter_typescript::language_tsx()),
)
.with_override_query("(jsx_self_closing_element) @element")
.unwrap(),
lsp::ServerCapabilities {
completion_provider: Some(lsp::CompletionOptions {
trigger_characters: Some(vec![":".to_string()]),
..Default::default()
}),
..Default::default()
},
cx,
)
.await;

cx.lsp
.handle_request::<lsp::request::Completion, _, _>(move |_, _| async move {
Ok(Some(lsp::CompletionResponse::Array(vec![
lsp::CompletionItem {
label: "bg-blue".into(),
..Default::default()
},
lsp::CompletionItem {
label: "bg-red".into(),
..Default::default()
},
lsp::CompletionItem {
label: "bg-yellow".into(),
..Default::default()
},
])))
});

cx.set_state(r#"<p class="bgˇ" />"#);

// Trigger completion when typing a dash, because the dash is an extra
// word character in the 'element' scope, which contains the cursor.
cx.simulate_keystroke("-");
cx.foreground().run_until_parked();
cx.update_editor(|editor, _| {
if let Some(ContextMenu::Completions(menu)) = &editor.context_menu {
assert_eq!(
menu.matches.iter().map(|m| &m.string).collect::<Vec<_>>(),
&["bg-red", "bg-blue", "bg-yellow"]
);
} else {
panic!("expected completion menu to be open");
}
});

cx.simulate_keystroke("l");
cx.foreground().run_until_parked();
cx.update_editor(|editor, _| {
if let Some(ContextMenu::Completions(menu)) = &editor.context_menu {
assert_eq!(
menu.matches.iter().map(|m| &m.string).collect::<Vec<_>>(),
&["bg-blue", "bg-yellow"]
);
} else {
panic!("expected completion menu to be open");
}
});

// When filtering completions, consider the character after the '-' to
// be the start of a subword.
cx.set_state(r#"<p class="yelˇ" />"#);
cx.simulate_keystroke("l");
cx.foreground().run_until_parked();
cx.update_editor(|editor, _| {
if let Some(ContextMenu::Completions(menu)) = &editor.context_menu {
assert_eq!(
menu.matches.iter().map(|m| &m.string).collect::<Vec<_>>(),
&["bg-yellow"]
);
} else {
panic!("expected completion menu to be open");
}
});
}

fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
let point = DisplayPoint::new(row as u32, column as u32);
point..point
Expand Down
Loading