fix(editor): match WebStorm's JS/TS inlay hint defaults and cut long hints (#7338)

JS/TS inlay hints default as in WebStorm: inferred types for variables and fields, enum values, and parameter names for literal and anonymous-function arguments. The Editor toggle now reaches the typescript-language-server fallback too. Long hints are cut with the full label in the tooltip, which also refreshes when the server changes it.

Closes #7326

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-02 14:32:27 +08:00
1 джерело f853ccf544
коміт 2f799aede9
21 files changed
+513 -53

No files matched your search

+16
Переглянути файл
@@ -401,6 +401,8 @@ impl Default for CodeEditingSettings {
#[serde(default, rename_all = "camelCase")]
pub struct InlayHintsSettings {
pub types: bool,
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
pub js_ts_types: bool,
pub parameters: bool,
/// Hints of other kinds (chaining, closing labels…).
pub other: bool,
@@ -436,6 +438,7 @@ impl Default for InlayHintsSettings {
fn default() -> Self {
Self {
types: true,
js_ts_types: true,
parameters: true,
other: true,
closing_labels: true,
@@ -710,6 +713,19 @@ mod folding_tests {
}
}
#[cfg(test)]
mod inlay_hints_tests {
use super::InlayHintsSettings;
#[test]
fn existing_settings_enable_js_ts_type_hints_by_default() {
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
assert!(settings.types);
assert!(settings.js_ts_types);
assert!(!settings.parameters);
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
+2
Переглянути файл
@@ -514,6 +514,8 @@ pub fn set_settings(
let code_style = key == "editor"
|| key == "editor.codeStyle"
|| key.starts_with("editor.codeStyle.")
|| key == "editor.inlay"
|| key.starts_with("editor.inlay.")
|| key == "inspections"
|| key.starts_with("inspections.")
|| key == "files"
+1
Переглянути файл
@@ -251,6 +251,7 @@ impl Host {
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
crate::ts_code_style::configure(cfg, server_root, &effective);
crate::ts_code_style::configure_inlay_hints(cfg, &effective);
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
+97
Переглянути файл
@@ -2,6 +2,7 @@
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
//! quick fixes, auto-imports, refactorings and organize imports.
//! Editor › Inlay Hints › JavaScript and TypeScript types as their variable and field type hint preferences.
use ide_core::editor_settings::LanguageCodeStyle;
use ide_core::settings::Settings;
@@ -57,6 +58,27 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
cfg.settings = Some(merged);
}
/// The servers' inferred variable and field type hints, on while Editor › Inlay Hints shows types
/// and JavaScript and TypeScript types (both on by default, as in WebStorm). Sent either way, so a
/// change reaches a running server; the server's own settings win.
pub fn configure_inlay_hints(cfg: &mut LanguageServerConfig, settings: &Settings) {
let inlay = &settings.editor.inlay;
let on = inlay.types && inlay.js_ts_types;
// vtsls reads VS Code's names, typescript-language-server tsserver's.
let hints = match cfg.name.as_str() {
"vtsls" => json!({ "variableTypes": { "enabled": on }, "propertyDeclarationTypes": { "enabled": on } }),
"typescript-language-server" => {
json!({ "includeInlayVariableTypeHints": on, "includeInlayPropertyDeclarationTypeHints": on })
}
_ => return,
};
let mut merged = json!({ "typescript": { "inlayHints": hints }, "javascript": { "inlayHints": hints } });
if let Some(own) = cfg.settings.take() {
ide_sdk::apply::merge(&mut merged, own);
}
cfg.settings = Some(merged);
}
/// The `format` and `preferences` of one language's section.
fn section(
language: &str,
@@ -215,6 +237,81 @@ mod tests {
);
}
#[test]
fn variable_type_hints_follow_the_inlay_settings() {
let hints = |name: &str, types: bool, js_ts_types: bool, own: Option<Value>| {
let mut settings = Settings::default();
settings.editor.inlay.types = types;
settings.editor.inlay.js_ts_types = js_ts_types;
let mut cfg = server(name);
cfg.settings = own;
configure_inlay_hints(&mut cfg, &settings);
cfg.settings
};
let vtsls =
|on: bool| json!({ "variableTypes": { "enabled": on }, "propertyDeclarationTypes": { "enabled": on } });
// On by default, as in WebStorm.
assert!(Settings::default().editor.inlay.js_ts_types);
assert_eq!(
hints("vtsls", true, true, None),
Some(json!({ "typescript": { "inlayHints": vtsls(true) }, "javascript": { "inlayHints": vtsls(true) } }))
);
// Sent when off too, so that a running server turns them off.
assert_eq!(
hints("vtsls", true, false, None),
Some(json!({ "typescript": { "inlayHints": vtsls(false) }, "javascript": { "inlayHints": vtsls(false) } }))
);
// Type hints off as a whole: none asked for.
assert_eq!(hints("vtsls", false, true, None).unwrap()["typescript"]["inlayHints"], vtsls(false));
let tls = hints("typescript-language-server", true, true, None).unwrap();
assert_eq!(
tls["javascript"]["inlayHints"],
json!({ "includeInlayVariableTypeHints": true, "includeInlayPropertyDeclarationTypeHints": true })
);
// The server's own settings win, and keep their other keys.
let own = json!({ "typescript": { "inlayHints": { "variableTypes": { "enabled": true }, "x": 1 } } });
let s = hints("vtsls", true, false, Some(own)).unwrap();
assert_eq!(
s["typescript"]["inlayHints"],
json!({ "variableTypes": { "enabled": true }, "propertyDeclarationTypes": { "enabled": false }, "x": 1 })
);
assert_eq!(s["javascript"]["inlayHints"], vtsls(false));
// Other servers (Rust, Kotlin, ESLint…) keep their own defaults.
assert_eq!(hints("rust-analyzer", true, false, None), None);
assert_eq!(hints("eslint", true, false, None), None);
}
/// The bundled language definitions leave the switch's keys to it: a value there would win.
#[test]
fn bundled_settings_leave_type_hints_to_the_switch() {
let reg = ide_language::LanguageRegistry::load(None).unwrap();
for language in ["typescript", "javascript", "typescriptreact", "javascriptreact", "vue"] {
let lang = reg.get(&ide_core::LanguageId::new(language)).unwrap();
let vtsls = lang.language_servers.iter().find(|s| s.name == "vtsls").unwrap();
let options = serde_json::to_value(&vtsls.initialization_options).unwrap();
for section in ["typescript", "javascript"] {
assert_eq!(options[section]["inlayHints"]["enumMemberValues"]["enabled"], true, "{language}");
}
if language == "vue" {
continue;
}
let fallback = lang.language_servers.iter().find(|s| s.name == "typescript-language-server").unwrap();
for enabled in [true, false] {
let mut settings = Settings::default();
settings.editor.inlay.js_ts_types = enabled;
let mut cfg = fallback.clone();
configure_inlay_hints(&mut cfg, &settings);
let s = cfg.settings.unwrap();
for section in ["typescript", "javascript"] {
let hints = &s[section]["inlayHints"];
assert_eq!(hints["includeInlayVariableTypeHints"], enabled, "{language} / {section}");
assert_eq!(hints["includeInlayPropertyDeclarationTypeHints"], enabled, "{language} / {section}");
assert_eq!(hints["includeInlayEnumMemberValueHints"], true, "{language} / {section}");
}
}
}
}
#[test]
fn editorconfig_comes_first() {
let dir = tempfile::tempdir().unwrap();
+13 -1
Переглянути файл
@@ -41,6 +41,7 @@ mod switch_source_header;
mod tcp;
mod text;
mod ts_file_moves;
mod ts_parameter_hints;
mod tsserver_bridge;
pub mod types;
mod uri;
@@ -3574,9 +3575,20 @@ impl LspManager {
match r {
Ok(hints) => {
let conv = self.conv(t.enc());
let tsserver = t.server.config.tsserver_project;
let text = snap.text.as_str();
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(
hints.unwrap_or_default().into_iter().map(|h| convert::inlay_hint(&conv, &snap.path, h)),
hints
.unwrap_or_default()
.into_iter()
.map(|h| convert::inlay_hint(&conv, &snap.path, h))
// The TypeScript servers send all parameter names: keep WebStorm's.
.filter(|h| {
!tsserver
|| h.kind != InlayKind::Parameter
|| ts_parameter_hints::shown_at(&text[snap.text.byte_offset(h.position)..])
}),
);
}
Err(e) => out.fail(e),
+157
Переглянути файл
@@ -0,0 +1,157 @@
//! WebStorm's parameter name hints for JavaScript and TypeScript: at literal arguments and at
//! function expressions (`run(function () {}, 2)` shows `task:` and `count:`), not at variables.
//! tsserver offers only "literals" (no functions) or "all", so the servers are asked for all of
//! them and the hints at other arguments are dropped here.
/// Whether the argument starting `rest` gets a parameter name hint.
pub(crate) fn shown_at(rest: &str) -> bool {
literal(rest) || function(rest)
}
fn ident_char(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// `rest` starts with the keyword `word` (not a longer identifier).
fn keyword<'a>(rest: &'a str, word: &str) -> Option<&'a str> {
rest.strip_prefix(word).filter(|after| !after.starts_with(ident_char))
}
/// tsserver's hintable literals: strings, templates, numbers (signed too), booleans, `null`, `undefined`.
fn literal(rest: &str) -> bool {
let unsigned = rest.strip_prefix(['-', '+']).map_or(rest, str::trim_start);
let mut chars = unsigned.chars();
match chars.next() {
Some('"' | '\'' | '`') => true,
Some(c) if c.is_ascii_digit() => true,
Some('.') => chars.next().is_some_and(|c| c.is_ascii_digit()),
_ => ["true", "false", "null", "undefined"].iter().any(|w| keyword(rest, w).is_some()),
}
}
/// `function` expressions and arrow functions, `async` or not.
fn function(rest: &str) -> bool {
let rest = keyword(rest, "async").map_or(rest, str::trim_start);
if keyword(rest, "function").is_some() {
return true;
}
// `x => …`
let ident_len = rest.find(|c: char| !ident_char(c)).unwrap_or(rest.len());
if ident_len > 0 && !rest.starts_with(|c: char| c.is_ascii_digit()) {
return rest[ident_len..].trim_start().starts_with("=>");
}
// `(a, b) => …`, `(): void => …`
rest.starts_with('(') && arrow_after_parameters(rest)
}
/// `rest` (from `(`) is an arrow function: its parameter list, an optional return type, then `=>`.
fn arrow_after_parameters(rest: &str) -> bool {
let mut depth = 0usize;
let mut quote = None;
let mut chars = rest.char_indices().peekable();
while let Some((i, c)) = chars.next() {
if let Some(q) = quote {
if c == '\\' {
chars.next();
} else if c == q {
quote = None;
}
continue;
}
match c {
'"' | '\'' | '`' => quote = Some(c),
'(' | '[' | '{' | '<' => depth += 1,
')' | ']' | '}' | '>' if depth > 0 => {
// `=>` inside a type (`(f: () => void)`) is not the arrow's.
if c == '>' && rest[..i].ends_with('=') {
depth += 1;
}
depth -= 1;
if depth == 0 && c == ')' {
let after = rest[i + 1..].trim_start();
return after.starts_with("=>") || (after.starts_with(':') && return_type_then_arrow(&after[1..]));
}
}
_ => {}
}
}
false
}
/// After a return type's `:`: `=>` before the argument ends (`,` or `)` outside brackets).
fn return_type_then_arrow(rest: &str) -> bool {
let mut depth = 0usize;
let mut prev = ' ';
for c in rest.chars() {
match c {
'(' | '[' | '{' | '<' => depth += 1,
'>' if prev == '=' && depth == 0 => return true,
')' | ']' | '}' | '>' if depth > 0 => depth -= 1,
',' | ')' | ';' if depth == 0 => return false,
_ => {}
}
prev = c;
}
false
}
#[cfg(test)]
mod tests {
use super::shown_at;
#[test]
fn literals_and_functions_get_hints_other_arguments_do_not() {
let shown = [
"2)",
"-1, 2)",
"+ 1.5)",
".5)",
"0x1f)",
"'a')",
"\"a\")",
"`a${b}`)",
"true)",
"false)",
"null)",
"undefined)",
"function () {}, 2)",
"async function named() {})",
"() => {})",
"async () => 1)",
"x => x * 2)",
"async x => x)",
"(a, b) => a + b)",
"(a: number, { b }: Opts) => a)",
"(f: () => void) => f())",
"(): void => {})",
"(): Promise<Map<string, number>> => load())",
"(\n a,\n b,\n) => a)",
];
for arg in shown {
assert!(shown_at(arg), "{arg:?} should get a hint");
}
let hidden = [
"start, withTime)",
"withTime)",
"trueish)",
"nullable)",
"functionName)",
"asyncTask)",
"(a))",
"(1 + 2))",
"(a, b), c)",
"-x)",
"{ a: 1 })",
"[1, 2])",
"new Date())",
"foo(1))",
"a.b)",
"...rest)",
")",
"",
];
for arg in hidden {
assert!(!shown_at(arg), "{arg:?} should not get a hint");
}
}
}
+23
Переглянути файл
@@ -1654,6 +1654,29 @@ async fn property_editor_has_nothing_without_a_dart_server() {
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn tsserver_parameter_hints_keep_literals_and_callbacks_at_utf16_positions() {
let h = harness_configured("typescript", "ts", &[("mock", incremental_caps())], |cfg| {
cfg.tsserver_project = true;
});
let (doc, _) = h.open("a.ts", r#"run("😀", function () {}, 2, count);"#);
h.wait_status("mock", ServerStatus::Ready).await;
h.launcher.state("mock").respond(
"textDocument/inlayHint",
json!([
{"position": {"line": 0, "character": 4}, "kind": 2, "label": "label:"},
{"position": {"line": 0, "character": 10}, "kind": 2, "label": "task:"},
{"position": {"line": 0, "character": 26}, "kind": 2, "label": "count:"},
{"position": {"line": 0, "character": 29}, "kind": 2, "label": "value:"},
]),
);
let hints = h.mgr.inlay_hints(doc, rng(0, 0, 0, 36)).await.unwrap();
assert_eq!(
hints.iter().map(|hint| (hint.position.col, hint.label.as_str())).collect::<Vec<_>>(),
[(4, "label:"), (10, "task:"), (26, "count:")]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
let h = harness(&[("mock", incremental_caps())]);
+42
Переглянути файл
@@ -972,6 +972,48 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// JavaScript and TypeScript inlay hints with the bundled vtsls settings (#7326), as in WebStorm:
/// parameter names at literal and function arguments only, and inferred variable types. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
async fn vtsls_parameter_hints_follow_webstorm() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
let text = "function run(task: () => void, count: number, label?: string) {}\n\
const n = 2;\n\
run(function () {}, 2);\n\
run(() => {}, n, 'x');\n\
const total = n * 2;\n";
std::fs::write(root.join("main.ts"), text).unwrap();
let bundled = LanguageRegistry::load(None).unwrap();
let bundled = bundled.get(&LanguageId::new("typescript")).unwrap().language_servers;
let bundled = bundled.iter().find(|s| s.name == "vtsls").unwrap();
let mut server = npm_server(&tools, "vtsls", "vtsls", None);
server.initialization_options = bundled.initialization_options.clone();
server.tsserver_project = true;
let (mgr, _events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
let doc = DocId::next();
mgr.did_open(doc, &root.join("main.ts"), &LanguageId::new("typescript"), 1, text);
let range = Range::new(Pos::new(0, 0), Pos::new(5, 0));
let hints = retry("inlay hints", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.inlay_hints(doc, range).await.ok().filter(|h| !h.is_empty()) }
})
.await;
let mut labels: Vec<_> = hints.iter().map(|h| (h.position.line, h.label.trim().to_owned())).collect();
labels.sort();
// `run(function () {}, 2)`: both; `run(() => {}, n, 'x')`: not `count:` before the variable.
assert_eq!(
labels,
[(2, "count:".into()), (2, "task:".into()), (3, "label:".into()), (3, "task:".into()), (4, ": number".into()),],
"{hints:?}"
);
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
+5 -4
Переглянути файл
@@ -72,15 +72,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
+9 -9
Переглянути файл
@@ -32,15 +32,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
@@ -58,18 +59,17 @@ install-hint = "npm i -g typescript@6 typescript-language-server"
[language-servers.initialization-options.preferences]
providePrefixAndSuffixTextForRename = false
# Inlay hints, as for vtsls above.
# Inlay hints, as for vtsls above. Variable and field types come from the Editor switch, which
# the settings here would override.
[language-servers.settings.typescript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
[language-servers.settings.javascript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
+9 -9
Переглянути файл
@@ -35,15 +35,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
@@ -61,18 +62,17 @@ install-hint = "npm i -g typescript@6 typescript-language-server"
[language-servers.initialization-options.preferences]
providePrefixAndSuffixTextForRename = false
# Inlay hints, as for vtsls above.
# Inlay hints, as for vtsls above. Variable and field types come from the Editor switch, which
# the settings here would override.
[language-servers.settings.typescript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
[language-servers.settings.javascript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
+9 -9
Переглянути файл
@@ -39,15 +39,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
@@ -65,18 +66,17 @@ install-hint = "npm i -g typescript@6 typescript-language-server"
[language-servers.initialization-options.preferences]
providePrefixAndSuffixTextForRename = false
# Inlay hints, as for vtsls above.
# Inlay hints, as for vtsls above. Variable and field types come from the Editor switch, which
# the settings here would override.
[language-servers.settings.typescript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
[language-servers.settings.javascript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
+9 -9
Переглянути файл
@@ -36,15 +36,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
@@ -62,18 +63,17 @@ install-hint = "npm i -g typescript@6 typescript-language-server"
[language-servers.initialization-options.preferences]
providePrefixAndSuffixTextForRename = false
# Inlay hints, as for vtsls above.
# Inlay hints, as for vtsls above. Variable and field types come from the Editor switch, which
# the settings here would override.
[language-servers.settings.typescript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
[language-servers.settings.javascript.inlayHints]
includeInlayParameterNameHints = "literals"
includeInlayParameterNameHints = "all"
includeInlayParameterNameHintsWhenArgumentMatchesName = false
includeInlayVariableTypeHints = true
includeInlayVariableTypeHintsWhenTypeMatchesName = false
includeInlayEnumMemberValueHints = true
+5 -4
Переглянути файл
@@ -43,15 +43,16 @@ enabled = "never"
[language-servers.initialization-options.javascript.updateImportsOnFileMove]
enabled = "never"
# Inlay hints (off in vtsls by default): parameter names at literal arguments, inferred
# variable types and enum member values. Editor › Inlay Hints decides which are shown.
# Inlay hints (off in vtsls by default), as in WebStorm: parameter names at literal and function
# arguments (the server sends all of them; the IDE keeps those), inferred variable and field types
# (Editor › Inlay Hints › JavaScript and TypeScript types) and enum member values.
[language-servers.initialization-options.typescript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
[language-servers.initialization-options.javascript.inlayHints]
parameterNames = { enabled = "literals", suppressWhenArgumentMatchesName = true }
parameterNames = { enabled = "all", suppressWhenArgumentMatchesName = true }
variableTypes = { enabled = true, suppressWhenTypeMatchesName = true }
enumMemberValues = { enabled = true }
+2
Переглянути файл
@@ -10788,6 +10788,8 @@ export type InlayHint = {
/** Editor › Inlay Hints. */
export type InlayHintsSettings = {
types?: boolean,
/** Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm). */
jsTsTypes?: boolean,
parameters?: boolean,
/** Hints of other kinds (chaining, closing labels…). */
other?: boolean,
+63 -1
Переглянути файл
@@ -19,7 +19,7 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const { inlayDecorations, inlayExtension, inlayMenuItems } = await import("./inlay");
const { inlayDecorations, inlayExtension, inlayMenuItems, truncateParts, MAX_LABEL_LENGTH } = await import("./inlay");
const { lspDoc } = await import("./lsp");
const { usePlatform } = await import("@/platform/platformInfo");
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
@@ -86,6 +86,29 @@ describe("background inlay hints", () => {
expect(shown(view)).toBe(1);
});
it("updates hint and part tooltips while keeping the full truncated label", async () => {
const label = ": " + "InferredType".repeat(5);
const withTooltips = (tooltip: string, partTooltip: string) => ({
...hint,
label,
tooltip,
parts: [{ value: label, tooltip: partTooltip, location: null }],
});
ipc.lspInlayHints.mockResolvedValue(ok([withTooltips("Old hint", "Old part")]));
const view = editor();
await afterPass();
const widget = () => view.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!;
expect(widget().title).toBe(`${label}\n\nOld hint`);
expect(widget().querySelector("span")!.title).toBe(`${label}\n\nOld part`);
ipc.lspInlayHints.mockResolvedValue(ok([withTooltips("New hint", "New part")]));
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
await afterPass();
expect(widget().textContent).toHaveLength(MAX_LABEL_LENGTH);
expect(widget().title).toBe(`${label}\n\nNew hint`);
expect(widget().querySelector("span")!.title).toBe(`${label}\n\nNew part`);
});
it("keeps the shown hints while the server is busy answering empty, and clears once it settles", async () => {
ipc.lspInlayHints.mockResolvedValue(ok([hint]));
const view = editor();
@@ -185,6 +208,45 @@ describe("inlay hints", () => {
expect(openFile).toHaveBeenCalledWith("/p/foo.rs", { selection: { line: 4, col: 7 }, focus: true });
});
it("cuts a long label to the maximum length, with the full text on hover", () => {
// vtsls' type of an optional-chained object: `{ id: number; title: string; … }`.
const long = `: { ${Array.from({ length: 12 }, (_, i) => `field${i}: string;`).join(" ")} }`;
const view = editorWith([{ ...hint, label: long, parts: [] }]);
const el = view.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!;
expect(el.textContent).toHaveLength(MAX_LABEL_LENGTH);
expect(el.textContent).toBe(`${long.slice(0, MAX_LABEL_LENGTH - 1)}…`);
expect(el.title).toBe(long);
// The server's tooltip stays, below the full label.
const withTooltip = editorWith([{ ...hint, label: long, parts: [], tooltip: "Inferred type" }]);
expect(withTooltip.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!.title).toBe(`${long}\n\nInferred type`);
// A short label is shown whole, with no hover text of its own.
const short = editorWith([{ ...hint, label: ": number", parts: [] }]).dom.querySelector<HTMLElement>(
".cm-lsp-inlay",
)!;
expect(short.textContent).toBe(": number");
expect(short.title).toBe("");
});
it("cuts long label parts, keeping the navigable parts before the cut", () => {
const tail = "x".repeat(80);
const parts = [...hint.parts, { value: tail, tooltip: null, location: null }];
const view = editorWith([{ ...hint, label: parts.map((p) => p.value).join(""), parts }]);
const el = view.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!;
expect(el.textContent).toHaveLength(MAX_LABEL_LENGTH);
expect(el.querySelector(".cm-lsp-inlay-part")!.textContent).toBe("Foo");
expect(el.title).toBe(`: Foo${tail}`);
// The navigable part keeps its tooltip, below the full label.
expect(el.querySelector<HTMLElement>(".cm-lsp-inlay-part")!.title).toBe(`: Foo${tail}\n\nstruct Foo`);
});
it("truncates across parts at exactly the maximum length", () => {
expect(truncateParts(["abc", "def"], 6)).toEqual(["abc", "def"]);
expect(truncateParts(["abc", "def"], 5)).toEqual(["abc", "d…"]);
expect(truncateParts(["abcd", "ef"], 5)).toEqual(["abcd…"]);
expect(truncateParts(["abcdef"], 3)).toEqual(["ab…"]);
expect(truncateParts([], 3)).toEqual([]);
});
it("offers to disable hints of the clicked kind", () => {
const view = editorWith([hint]);
view.dom
+37 -6
Переглянути файл
@@ -60,6 +60,25 @@ export function inlayMenuItems(kind: InlayHint["kind"]): MenuItem[] {
];
}
/** The longest label shown in full; longer ones end in "…" with the full text on hover, as in IDEA. */
export const MAX_LABEL_LENGTH = 50;
/** `values` cut to `max` characters in all, the last one kept ending in "…"; parts past it dropped. */
export function truncateParts(values: readonly string[], max = MAX_LABEL_LENGTH): string[] {
if (values.reduce((n, v) => n + v.length, 0) <= max) return [...values];
const out: string[] = [];
let left = max - 1;
for (const value of values) {
if (value.length >= left) {
out.push(`${value.slice(0, left)}…`);
break;
}
out.push(value);
left -= value.length;
}
return out;
}
class InlayWidget extends WidgetType {
constructor(readonly hint: InlayHint) {
super();
@@ -70,10 +89,16 @@ class InlayWidget extends WidgetType {
return (
a.label === b.label &&
a.kind === b.kind &&
a.tooltip === b.tooltip &&
a.paddingLeft === b.paddingLeft &&
a.paddingRight === b.paddingRight &&
(a.parts?.length ?? 0) === (b.parts?.length ?? 0) &&
(a.parts ?? []).every((p, i) => p.location?.path === b.parts[i]?.location?.path && p.value === b.parts[i]?.value)
(a.parts ?? []).every(
(p, i) =>
p.location?.path === b.parts[i]?.location?.path &&
p.value === b.parts[i]?.value &&
p.tooltip === b.parts[i]?.tooltip,
)
);
}
toDOM(view: EditorView) {
@@ -82,11 +107,15 @@ class InlayWidget extends WidgetType {
if (this.hint.paddingLeft) el.classList.add("cm-lsp-inlay-pl");
if (this.hint.paddingRight) el.classList.add("cm-lsp-inlay-pr");
const parts = this.hint.parts ?? [];
const cut = this.hint.label.length > MAX_LABEL_LENGTH;
if (parts.some((p) => p.location || p.tooltip)) {
for (const part of parts) {
const shown = truncateParts(parts.map((p) => p.value));
for (const [i, value] of shown.entries()) {
const part = parts[i]!;
const span = document.createElement("span");
span.textContent = part.value;
if (part.tooltip) span.title = part.tooltip;
span.textContent = value;
// A part's own tooltip hides the hint's: put the full label above it when the label is cut.
if (part.tooltip) span.title = cut ? `${this.hint.label}\n\n${part.tooltip}` : part.tooltip;
if (part.location) {
span.className = "cm-lsp-inlay-part";
const loc = part.location;
@@ -100,7 +129,7 @@ class InlayWidget extends WidgetType {
}
el.appendChild(span);
}
} else el.textContent = this.hint.label;
} else el.textContent = truncateParts([this.hint.label])[0] ?? "";
// A plain type hint (basedpyright's `: Series`) names no location: ⌘-click opens the preceding identifier's type.
if (
this.hint.kind === "type" &&
@@ -117,7 +146,9 @@ class InlayWidget extends WidgetType {
void gotoTargets(view, "typeDefinition", offset);
});
}
if (this.hint.tooltip) el.title = this.hint.tooltip;
// A cut label shows in full on hover, above the server's own tooltip.
const title = [cut ? this.hint.label : "", this.hint.tooltip ?? ""].filter(Boolean).join("\n\n");
if (title) el.title = title;
el.setAttribute("aria-hidden", "true");
el.addEventListener("contextmenu", (e) => {
e.preventDefault();
+11 -1
Переглянути файл
@@ -15,6 +15,13 @@ const EXAMPLES = [
file: "total.rs",
parts: ["fn checkout() {\n let total", { annotation: ": f64" }, ' = 42.0 * 1.05;\n println!("{total}");\n}'],
},
{
id: "jsTsTypes",
label: "JavaScript and TypeScript types",
language: "typescript",
file: "total.ts",
parts: ["const total", { annotation: ": number" }, " = 42 * 1.05;\nconsole.log(total);"],
},
{
id: "parameters",
label: "Parameter names",
@@ -56,12 +63,15 @@ export function InlayHintsPanel() {
const example = EXAMPLES[index]!;
const [enabled] = useSetting<boolean>("editor.inlayHints");
const [shown, setShown] = useSetting<boolean>(`editor.inlay.${example.id}`);
const [types] = useSetting<boolean>("editor.inlay.types");
const [disabledLanguages] = useSetting<string[]>("editor.inlay.disabledLanguages");
const [family] = useSetting<string>("editor.fontFamily");
const [fallback] = useSetting<string>("editor.fallbackFont");
const [size] = useSetting<number>("editor.fontSize");
const [lineHeight] = useSetting<number>("editor.lineHeight");
const showHint = enabled && shown && !disabledLanguages.includes(example.language);
// JavaScript and TypeScript types are type hints: the Types switch has to be on too.
const showHint =
enabled && shown && (example.id !== "jsTsTypes" || types) && !disabledLanguages.includes(example.language);
return (
<div className={styles.split}>
+1
Переглянути файл
@@ -248,6 +248,7 @@ export const EDITOR_EXTRA_DEFAULTS = {
},
inlay: {
types: true,
jsTsTypes: true,
parameters: true,
other: true,
closingLabels: true,
+1
Переглянути файл
@@ -4303,6 +4303,7 @@
"Copy Image": "Copy Image",
"Couldn't copy the image": "Couldn't copy the image",
"Closing labels": "Closing labels",
"JavaScript and TypeScript types": "JavaScript and TypeScript types",
"Roll Back to Here": "Roll Back to Here",
"Couldn't roll back": "Couldn't roll back",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.",
+1
Переглянути файл
@@ -10883,6 +10883,7 @@
"Copy Image": "复制图片",
"Couldn't copy the image": "无法复制图片",
"Closing labels": "结束标签",
"JavaScript and TypeScript types": "JavaScript 和 TypeScript 类型",
"Roll Back to Here": "回滚到这里",
"Couldn't roll back": "无法回滚",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "这条消息及之后的消息会被移除,Agent 在此之后改动的文件会恢复到这条消息发送前的状态。消息会放回输入框。",