[Bug] LSP hover shows raw Markdown when the server answers with a MarkedString

Abierto Apto para principiantes
#2,373 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
85/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
rust

Línea de trabajo

Empieza en rust/crates/lsp-client/src/client/results.rs en hover_contents, al que se llega desde parse_hover. El diff del reportante y las cuatro pruebas unitarias muestran las formas esperadas (cadena simple, {language, value}, MarkupContent, array). Ejecuta cargo test -p lsp-client en rust/ antes y después del cambio, y luego confirma con gleam lsp en Lithe Desktop que el popup muestra un bloque Gleam resaltado en lugar de fences visibles. Está terminado cuando esas pruebas unitarias pasan y el Markdown del hover en desktop/internal/workbench/pluginsemantics_hover.go ya no tiene doble fence.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug issue-form:bug review: no-score
Platform / 平台

macOS

Area / 模块

Language support / 语言服务

Lithe version / Lithe 版本

0.8.15 (desktop-v0.8.15, Core 4880022); Core main 529be33 has the same code

Priority / 优先级

P2 / 后续考虑:目前不着急,可安排到后续版本

OS and architecture / 操作系统与架构

macOS, arm64

Environment / 环境信息

Gleam 1.19.1 (gleam lsp) through a declarative language-server plugin

Steps to reproduce / 复现步骤
  1. Use a language server that answers textDocument/hover with a bare string, for example
    gleam lsp. Its answer for a documented function is:

    {"contents": "```gleam\nfn(Int, Int) -> Int\n```\n Adds two numbers and says so.\n",
     "range": {"start": {"line": 6, "character": 2}, "end": {"line": 6, "character": 5}}}
    
  2. Hover over a call of that function in Lithe Desktop.

Expected behavior / 预期行为

The popup renders Markdown: the signature as a highlighted Gleam code block, the documentation
as text below it. The LSP specification defines MarkedString as Markdown when it is a string,
and as a code block in language when it is {language, value}
(https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#markedString).

Actual behavior / 实际行为

The popup shows the source text, fences included (```gleam is visible), unhighlighted
and wrapped mid-word.

Cause: hover_contents in rust/crates/lsp-client/src/client/results.rs returns
isMarkdown: false for Value::String, so the desktop's hoverMarkdown
(desktop/internal/workbench/pluginsemantics_hover.go) wraps the Markdown in a plain fence. A
{language, value} object takes the kind branch, also gets false, and loses its language.

Suggested fix (tested locally on desktop-v0.8.15 with Core 4880022; the lsp-client tests
pass, and the hover renders correctly with gleam lsp):

 fn hover_contents(value: &Value) -> Option<(String, bool)> {
     match value {
-        Value::String(text) => Some((text.clone(), false)),
+        Value::String(text) => Some((text.clone(), true)),
         Value::Object(object) => {
             if let Some(value) = object.get("value").and_then(Value::as_str) {
+                if let Some(language) = object.get("language").and_then(Value::as_str) {
+                    let longest = value
+                        .split(|c| c != '`')
+                        .map(str::len)
+                        .max()
+                        .unwrap_or(0);
+                    let fence = "`".repeat(longest.max(2) + 1);
+                    return Some((
+                        format!("{fence}{language}\n{}\n{fence}", value.trim_end_matches('\n')),
+                        true,
+                    ));
+                }
                 let is_markdown = object

Unit tests for the four shapes (bare string, {language, value}, MarkupContent plaintext and
markdown, array) are in the patch below.

diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs
index 63ecf22..1ef44f4 100644
--- a/rust/crates/lsp-client/src/client/results.rs
+++ b/rust/crates/lsp-client/src/client/results.rs
@@ -180,11 +180,26 @@ fn parse_hover(result: &Value) -> Option<Value> {
     }))
 }
 
+// A bare string is a MarkedString, which the LSP specification defines as Markdown; an object
+// with a language is a MarkedString code block, rendered as a fence in that language; an object
+// with a kind is MarkupContent, Markdown only when its kind says so.
 fn hover_contents(value: &Value) -> Option<(String, bool)> {
     match value {
-        Value::String(text) => Some((text.clone(), false)),
+        Value::String(text) => Some((text.clone(), true)),
         Value::Object(object) => {
             if let Some(value) = object.get("value").and_then(Value::as_str) {
+                if let Some(language) = object.get("language").and_then(Value::as_str) {
+                    let longest = value
+                        .split(|c| c != '`')
+                        .map(str::len)
+                        .max()
+                        .unwrap_or(0);
+                    let fence = "`".repeat(longest.max(2) + 1);
+                    return Some((
+                        format!("{fence}{language}\n{}\n{fence}", value.trim_end_matches('\n')),
+                        true,
+                    ));
+                }
                 let is_markdown = object
                     .get("kind")
                     .and_then(Value::as_str)
@@ -1014,3 +1029,44 @@ fn parse_lsp_position_value(value: &Value) -> Option<Value> {
             .unwrap_or(0)
     }))
 }
+
+#[cfg(test)]
+mod hover_contents_tests {
+    use super::*;
+
+    #[test]
+    fn bare_string_is_markdown() {
+        let text = "```gleam\nfn(Int) -> Int\n```\n Adds.\n";
+        assert_eq!(hover_contents(&json!(text)), Some((text.to_string(), true)));
+    }
+
+    #[test]
+    fn marked_string_code_block_becomes_a_fence() {
+        let value = json!({ "language": "erlang", "value": "add(A, B) -> A + B.\n" });
+        assert_eq!(
+            hover_contents(&value),
+            Some(("```erlang\nadd(A, B) -> A + B.\n```".to_string(), true))
+        );
+    }
+
+    #[test]
+    fn markup_content_follows_its_kind() {
+        assert_eq!(
+            hover_contents(&json!({ "kind": "plaintext", "value": "a *b*" })),
+            Some(("a *b*".to_string(), false))
+        );
+        assert_eq!(
+            hover_contents(&json!({ "kind": "markdown", "value": "a *b*" })),
+            Some(("a *b*".to_string(), true))
+        );
+    }
+
+    #[test]
+    fn array_joins_its_parts_as_markdown() {
+        let value = json!([{ "language": "gleam", "value": "fn() -> Nil" }, "Docs."]);
+        assert_eq!(
+            hover_contents(&value),
+            Some(("```gleam\nfn() -> Nil\n```\n\nDocs.".to_string(), true))
+        );
+    }
+}
```

### Logs or diagnostic output / 日志或诊断输出

```shell
none needed; the cause is in the code above.
```

### Screenshots or recordings / 截图或录屏

before:
<img width="652" height="403" alt="image" src="https://github.com/user-attachments/assets/99cc2e1f-53fd-45d4-9997-afa5280fd63c" />


after: 
<img width="572" height="330" alt="image" src="https://github.com/user-attachments/assets/0a8efa8a-d944-450a-8634-b471e3fb4909" />

### Checklist / 提交前检查

- [x] I searched existing issues for duplicates. / 我已搜索现有 Issue,确认没有重复报告。
- [x] I removed secrets and personal data from the report. / 我已从报告中移除敏感信息和个人数据。
Lenguaje dominante
TypeScript
Estrellas
1.8k
Forks
151
Merge medio
4 h 4 min
PR fusionados (30 d)
558

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de 1lck/Lithe-IDEA

Todos los issues de 1lck/Lithe-IDEA

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.