From 85a310b75c4fe3fbec536b3d0e0d69b6a0cab90e Mon Sep 17 00:00:00 2001 From: He1pa <18012015693@163.com> Date: Wed, 23 Aug 2023 14:36:53 +0800 Subject: [PATCH] feat: integrate kcl fmt tools to lsp. Suport formmat single file --- kclvm/tools/src/LSP/src/capabilities.rs | 1 + kclvm/tools/src/LSP/src/request.rs | 31 ++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/kclvm/tools/src/LSP/src/capabilities.rs b/kclvm/tools/src/LSP/src/capabilities.rs index 9938bcbed..dfd3c417b 100644 --- a/kclvm/tools/src/LSP/src/capabilities.rs +++ b/kclvm/tools/src/LSP/src/capabilities.rs @@ -36,6 +36,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti }) }), ), + document_formatting_provider: Some(OneOf::Left(true)), ..Default::default() } } diff --git a/kclvm/tools/src/LSP/src/request.rs b/kclvm/tools/src/LSP/src/request.rs index 69836f88d..192d271f8 100644 --- a/kclvm/tools/src/LSP/src/request.rs +++ b/kclvm/tools/src/LSP/src/request.rs @@ -1,8 +1,7 @@ use std::{collections::HashMap, time::Instant}; - -use anyhow::Ok; use crossbeam_channel::Sender; -use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, TextEdit}; +use kclvm_tools::format::{format_source, FormatOptions}; +use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Range, TextEdit}; use ra_ap_vfs::VfsPath; use crate::{ @@ -47,6 +46,7 @@ impl LanguageServerState { .on::(handle_hover)? .on::(handle_document_symbol)? .on::(handle_code_action)? + .on::(handle_formatting)? .finish(); Ok(()) @@ -67,6 +67,31 @@ impl LanguageServerSnapshot { } } +pub(crate) fn handle_formatting( + _snap: LanguageServerSnapshot, + params: lsp_types::DocumentFormattingParams, + sender: Sender, +) -> anyhow::Result>> { + let file = file_path_from_url(¶ms.text_document.uri)?; + let src = std::fs::read_to_string(file.clone())?; + match format_source(&file, &src, &FormatOptions::default()) { + Ok((source, is_formatted)) => { + if is_formatted { + Ok(Some(vec![TextEdit { + range: Range::new(Position::new(0, 0), Position::new(u32::MAX, u32::MAX)), + new_text: source, + }])) + } else { + Ok(None) + } + } + Err(err) => { + log_message(format!("Format failed: {err}"), &sender)?; + Ok(None) + } + } +} + /// Called when a `GotoDefinition` request was received. pub(crate) fn handle_code_action( _snap: LanguageServerSnapshot,