Skip to content

feat: Stylua LSP server #970

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
87 changes: 73 additions & 14 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ thiserror = "1.0.49"
threadpool = "1.8.1"
toml = "0.8.1"

lsp-server = "0.7"
lsp-types = "0.97"
lsp-textdocument = "0.4.2"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { version = "0.2.81", optional = true }

Expand Down
108 changes: 108 additions & 0 deletions src/cli/lsp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use lsp_server::{Connection, Message, RequestId, Response};
use lsp_textdocument::TextDocuments;
use lsp_types::{
request::{Formatting, RangeFormatting, Request},
DocumentFormattingParams, OneOf, Position, Range, ServerCapabilities,
TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit,
};

use crate::{config::ConfigResolver, opt};

pub fn run(opt: opt::Opt) -> anyhow::Result<()> {
// Load the configuration
let opt_for_config_resolver = opt.clone();
let mut config_resolver = ConfigResolver::new(&opt_for_config_resolver)?;

let (connection, io_threads) = Connection::stdio();

let capabilities = ServerCapabilities {
document_formatting_provider: Some(OneOf::Left(true)),
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::INCREMENTAL,
)),
..Default::default()
};

connection.initialize(serde_json::to_value(capabilities)?)?;

let mut documents = TextDocuments::new();

for msg in &connection.receiver {
match msg {
Message::Request(req) => {
if connection.handle_shutdown(&req)? {
break;
}

match req.method.as_str() {
Formatting::METHOD => {
let result =
match serde_json::from_value::<DocumentFormattingParams>(req.params) {
Ok(params) => {
let res = handle_formatting(
req.id.clone(),
params,
&mut config_resolver,
&documents,
);

res.unwrap_or(Response::new_ok(req.id, serde_json::Value::Null))
}
Err(err) => Response::new_err(req.id, 1, err.to_string()),
};

connection.sender.send(Message::Response(result))?;
}
RangeFormatting::METHOD => {
// TODO: Would be cool to support this in the future
}
_ => {}
}
}
Message::Response(_) => {}
Message::Notification(notification) => {
documents.listen(notification.method.as_str(), &notification.params);
}
}
}

io_threads.join()?;

Ok(())
}

fn handle_formatting(
id: RequestId,
params: DocumentFormattingParams,
config_resolver: &mut ConfigResolver,
documents: &TextDocuments,
) -> Option<Response> {
let uri = params.text_document.uri;
let path = uri.path().as_str();

let src = documents.get_document_content(&uri, None)?;

let config = config_resolver
.load_configuration(path.as_ref())
.unwrap_or_default();

let new_text =
stylua_lib::format_code(src, config, None, stylua_lib::OutputVerification::None).ok()?;

if new_text == src {
return None;
}

// TODO: We can be smarter about this in the future, and update only the parts that changed
let edit = TextEdit {
range: Range {
start: Position::new(0, 0),
end: Position::new(u32::MAX, 0),
},
new_text,
};

let edits: Vec<TextEdit> = vec![edit];

Some(Response::new_ok(id, edits))
}
6 changes: 6 additions & 0 deletions src/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use stylua_lib::{format_code, Config, OutputVerification, Range};
use crate::config::find_ignore_file_path;

mod config;
mod lsp;
mod opt;
mod output_diff;

Expand Down Expand Up @@ -255,6 +256,11 @@ fn path_is_stylua_ignored(path: &Path, search_parent_directories: bool) -> Resul
fn format(opt: opt::Opt) -> Result<i32> {
debug!("resolved options: {:#?}", opt);

if opt.lsp {
lsp::run(opt)?;
return Ok(0);
}

if opt.files.is_empty() {
bail!("no files provided");
}
Expand Down
4 changes: 4 additions & 0 deletions src/cli/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ pub struct Opt {
/// Respect .styluaignore and glob matching for file paths provided directly to the tool
#[structopt(long)]
pub respect_ignores: bool,

/// Run Stylua LSP server
#[structopt(long)]
pub lsp: bool,
}

#[derive(ArgEnum, Clone, Copy, Debug, PartialEq, Eq)]
Expand Down
Loading