Skip to content

Commit

Permalink
feat: integrate kcl fmt tools to lsp. Suport formmat single file
Browse files Browse the repository at this point in the history
  • Loading branch information
He1pa committed Aug 23, 2023
1 parent 09cb631 commit e01b62d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
1 change: 1 addition & 0 deletions kclvm/tools/src/LSP/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti
})
}),
),
document_formatting_provider: Some(OneOf::Left(true)),
..Default::default()
}
}
33 changes: 29 additions & 4 deletions kclvm/tools/src/LSP/src/request.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
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 std::{collections::HashMap, time::Instant};

use crate::{
completion::completion,
Expand Down Expand Up @@ -47,6 +46,7 @@ impl LanguageServerState {
.on::<lsp_types::request::HoverRequest>(handle_hover)?
.on::<lsp_types::request::DocumentSymbolRequest>(handle_document_symbol)?
.on::<lsp_types::request::CodeActionRequest>(handle_code_action)?
.on::<lsp_types::request::Formatting>(handle_formatting)?
.finish();

Ok(())
Expand All @@ -67,6 +67,31 @@ impl LanguageServerSnapshot {
}
}

pub(crate) fn handle_formatting(
_snap: LanguageServerSnapshot,
params: lsp_types::DocumentFormattingParams,
sender: Sender<Task>,
) -> anyhow::Result<Option<Vec<TextEdit>>> {
let file = file_path_from_url(&params.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,
Expand Down

0 comments on commit e01b62d

Please sign in to comment.