├── .cargo └── config.toml ├── images ├── eldoc.png ├── completion.png ├── references.png ├── architecture.jpg └── Architecture_of_LSPCE.png ├── Cargo.toml ├── docs ├── Design.org ├── TODO.org └── SelfTalking.org ├── .gitignore ├── CHANGELOG.org ├── src ├── error.rs ├── socket.rs ├── logger.rs ├── connection.rs ├── stdio.rs ├── msg.rs └── lib.rs ├── rust-api.md ├── lspce-snippet.el ├── lspce-calltree.el ├── lspce-util.el ├── lspce-langs.el ├── Cargo.lock ├── README.org ├── LICENSE └── lspce-core.el /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["-Ctarget-cpu=native"] 3 | -------------------------------------------------------------------------------- /images/eldoc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zbelial/lspce/HEAD/images/eldoc.png -------------------------------------------------------------------------------- /images/completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zbelial/lspce/HEAD/images/completion.png -------------------------------------------------------------------------------- /images/references.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zbelial/lspce/HEAD/images/references.png -------------------------------------------------------------------------------- /images/architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zbelial/lspce/HEAD/images/architecture.jpg -------------------------------------------------------------------------------- /images/Architecture_of_LSPCE.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zbelial/lspce/HEAD/images/Architecture_of_LSPCE.png -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lspce-module" 3 | version = "1.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["cdylib"] 8 | 9 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 10 | 11 | [dependencies] 12 | lsp-types = "0.95.0" 13 | crossbeam-channel = "0.5.4" 14 | chrono = "0.4" 15 | emacs = "0.18.0" 16 | serde = { version = "1.0", features = ["derive"] } 17 | serde_json = "1.0" 18 | bytes = "1.0" 19 | lazy_static = "1.4.0" 20 | 21 | [profile.dev] 22 | debug = 0 23 | 24 | [profile.release] 25 | lto = true 26 | codegen-units = 1 27 | -------------------------------------------------------------------------------- /docs/Design.org: -------------------------------------------------------------------------------- 1 | 2 | * Roadmap 3 | ** Version 0.1 4 | - Transports: support using stdio as a transport. 5 | - Initialize and Shutdown 6 | - Goto Definition: provides goto definition support for a symbol selected in a text document. 7 | - Find References: finds all project-wide references for a symbol selected in a text document. 8 | - Code Complete: provides code complete lists. 9 | ** Version 0.2 10 | - Document synchronization: incremental and full text document synchronization. 11 | - File events: synchronization of file events to the server. 12 | - Diagnostic: show diagnostic problems. 13 | - Code Actions: provide actions to fix diagnostic problems. 14 | - Rename refactoring: provides renaming symbols. 15 | ** Version 0.3 16 | - Server Request: handle server request. 17 | ** Version xxx 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # These are some examples of commonly ignored file patterns. 2 | # You should customize this list as applicable to your project. 3 | # Learn more about .gitignore: 4 | # https://www.atlassian.com/git/tutorials/saving-changes/gitignore 5 | 6 | # Node artifact files 7 | node_modules/ 8 | dist/ 9 | 10 | # Compiled Java class files 11 | *.class 12 | 13 | # Compiled Python bytecode 14 | *.py[cod] 15 | 16 | # Log files 17 | *.log 18 | 19 | # Package files 20 | *.jar 21 | 22 | # Maven 23 | target/ 24 | dist/ 25 | 26 | # JetBrains IDE 27 | .idea/ 28 | 29 | # Unit test reports 30 | TEST*.xml 31 | 32 | # Generated by MacOS 33 | .DS_Store 34 | 35 | # Generated by Windows 36 | Thumbs.db 37 | 38 | # Applications 39 | *.app 40 | *.exe 41 | *.war 42 | 43 | # Large media files 44 | *.mp4 45 | *.tiff 46 | *.avi 47 | *.flv 48 | *.mov 49 | *.wmv 50 | 51 | lspce-module.so 52 | lspce-module.so.* 53 | 54 | .aider* -------------------------------------------------------------------------------- /docs/TODO.org: -------------------------------------------------------------------------------- 1 | #+STARTUP: overview 2 | #+STARTUP: hidestars 3 | #+STARTUP: hideblocks 4 | 5 | 6 | * DONE initializationOptions 7 | 8 | - State "DONE" from [2022-05-27 五 23:21] 9 | * DONE modeline 10 | 11 | - State "DONE" from [2022-05-27 五 23:40] 12 | * DONE 诊断 13 | - State "DONE" from [2022-05-29 日 00:12] 14 | 使用flymake。 15 | 16 | * PROCESS 完善补全 17 | - State "PROCESS" from "DONE" [2022-05-29 日 13:12] 18 | - State "DONE" from "PROCESS" [2022-05-29 日 13:01] 19 | * DONE 补全支持snippet 20 | - State "DONE" from [2022-05-29 日 13:01] 21 | * DONE signatureHelp 22 | - State "DONE" from [2022-06-11 六 23:14] 23 | 支持eldoc。 24 | * codeAction 25 | * workspace/configuration 26 | * server启动进度 27 | 28 | * PROCESS java支持 29 | * DONE hover 30 | 31 | - State "DONE" from [2022-05-26 四 16:43] 32 | * autoImport 33 | * rename 34 | * xref查找引用导致发送didOpen的问题 35 | 36 | -------------------------------------------------------------------------------- /CHANGELOG.org: -------------------------------------------------------------------------------- 1 | * Next 2 | ** enhancement - add =lspce-incoming-calls= and =lspce-outgoing-calls=. 3 | ** enhancement - add =lspce-imenu-create=, which creates imenu with textDocument/documentSymbol. Thanks @theFool32. 4 | ** enhancement - support =workspace/didChangeConfiguration=. 5 | ** enhancement - add lspce--lsp-type-map where you can specify lsp-type for file extensions. 6 | ** enhancement - support specifing how many completion items jdtls can return at the most. 7 | ** enhancement - support specifing which environment variables should be passed to rust code to start lsp servers. 8 | ** enhancement - add initializationOptions for deno/pylsp/jedi-language-server, delete things about pyright. 9 | ** README - mention how to support python virtual environments for pylsp and jedi-language-server. 10 | * 1.1.0 (2024-07-12) 11 | ** enhancement - add =xref-find-type-definition= 12 | ** enhancement - support =xref-find-declaration= 13 | ** enhancement - support =deprecatedSupport= in completion 14 | ** enhancement - support =inlayHint= 15 | ** enhancement - support =xref-backend-apropos= 16 | ** enhancement - support passing exec-path to then environment when spawning a LSP server 17 | ** enhancement - support writing LSP server's stderr to the log file 18 | ** enhancement - support fetching implementations when fetching definitions in =xref-find-declaration= (useful for languages like go/rust/java etc.) 19 | ** bugfix - fix no argument snippets for rust code 20 | ** bugfix - stop writing "stderr reach EOF" repeatedly to log 21 | ** other enhancements and bugfixes 22 | * 1.0.0 (2023-06-21) 23 | Hard to say. 24 | -------------------------------------------------------------------------------- /docs/SelfTalking.org: -------------------------------------------------------------------------------- 1 | #+STARTUP: overview 2 | #+STARTUP: hidestars 3 | #+STARTUP: hideblocks 4 | 5 | * subprocess and stdin/stdout 6 | 启动LSP Server进程后,要能够通过stdin输入、从stdout获取输出。 7 | #+BEGIN_SRC rust 8 | use std::process::{Command, Stdio}; 9 | use std::io::Write; 10 | 11 | let mut child = Command::new("/bin/cat") 12 | .stdin(Stdio::piped()) 13 | .stdout(Stdio::piped()) 14 | .spawn() 15 | .expect("failed to execute child"); 16 | 17 | // If the child process fills its stdout buffer, it may end up 18 | // waiting until the parent reads the stdout, and not be able to 19 | // read stdin in the meantime, causing a deadlock. 20 | // Writing from another thread ensures that stdout is being read 21 | // at the same time, avoiding the problem. 22 | let mut stdin = child.stdin.take().expect("failed to get stdin"); 23 | std::thread::spawn(move || { 24 | stdin.write_all(b"test").expect("failed to write to stdin"); 25 | }); 26 | 27 | let output = child 28 | .wait_with_output() 29 | .expect("failed to wait on child"); 30 | 31 | assert_eq!(b"test", output.stdout.as_slice()); 32 | #+END_SRC 33 | 34 | * LSP and its lifetime 35 | ** 请求 36 | 每个请求都必须要有响应。 37 | ** 通知 38 | 通知一定不能有响应。 39 | ** initialize 请求 40 | Client发送到Server的 _第一个_ 请求。在Server返回InitializeResult之前,client不能发送任何请求/通知给server。 41 | Server处理initialize请求期间,只能发送通知 ~window/showMessage~, ~window/logMessage~, ~telemetry/event~ 或者请求 ~window/showMessageRequest~ 给client。 42 | ** initialized 通知 43 | Client收到server的InitializeResult响应之后,发送其它任何请求/通知给server之前,发送给server的。 44 | ** shutdown 请求 45 | Client发送给server,要求server =shut down=, 但不要 =exit=. 否则这个请求的响应就没法发送给client了。 46 | 此后,client就只能发送 ~exit~ 通知给server了,而且要在收到shutdown响应之后。 47 | ** exit 通知 48 | 请求server结束其进程。 49 | 50 | * Emacs如何跟LSP Server进程通信 51 | 52 | * jsonrpc 53 | 不使用三方库。 54 | * TODO 支持TCP/HTTP 55 | * Emacs completion table 56 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fmt::{self, Display, Formatter}; 3 | use std::io::Error as IoError; 4 | use std::num::ParseIntError; 5 | use std::result::Result as RustResult; 6 | use std::str::Utf8Error; 7 | 8 | use crate::msg::{Notification, Request}; 9 | 10 | #[derive(Debug, Clone)] 11 | pub struct ProtocolError(pub(crate) String); 12 | 13 | #[derive(Debug, Clone)] 14 | pub struct LspceError(pub(crate) String); 15 | 16 | impl std::error::Error for ProtocolError {} 17 | impl std::error::Error for LspceError {} 18 | 19 | impl fmt::Display for ProtocolError { 20 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 21 | fmt::Display::fmt(&self.0, f) 22 | } 23 | } 24 | 25 | impl fmt::Display for LspceError { 26 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 27 | fmt::Display::fmt(&self.0, f) 28 | } 29 | } 30 | 31 | #[derive(Debug)] 32 | pub enum ExtractError { 33 | /// The extracted message was of a different method than expected. 34 | MethodMismatch(T), 35 | /// Failed to deserialize the message. 36 | JsonError { 37 | method: String, 38 | error: serde_json::Error, 39 | }, 40 | } 41 | 42 | impl std::error::Error for ExtractError {} 43 | impl fmt::Display for ExtractError { 44 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 45 | match self { 46 | ExtractError::MethodMismatch(req) => { 47 | write!(f, "Method mismatch for request '{}'", req.method) 48 | } 49 | ExtractError::JsonError { method, error } => { 50 | write!(f, "Invalid request\nMethod: {method}\n error: {error}",) 51 | } 52 | } 53 | } 54 | } 55 | 56 | impl std::error::Error for ExtractError {} 57 | impl fmt::Display for ExtractError { 58 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 59 | match self { 60 | ExtractError::MethodMismatch(req) => { 61 | write!(f, "Method mismatch for notification '{}'", req.method) 62 | } 63 | ExtractError::JsonError { method, error } => { 64 | write!(f, "Invalid notification\nMethod: {method}\n error: {error}") 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /rust-api.md: -------------------------------------------------------------------------------- 1 | # LSPCE Rust API Documentation 2 | 3 | This document describes the Emacs API functions exposed by the LSPCE Rust module. 4 | 5 | ## Logging Functions 6 | 7 | ### `change_max_diagnostics_count(count: i32) -> String` 8 | Changes the maximum number of diagnostics to cache. Returns a success message. 9 | 10 | ### `read_max_diagnostics_count() -> i32` 11 | Returns the current maximum number of diagnostics being cached. 12 | 13 | ### `disable_logging() -> String` 14 | Disables logging to /tmp/lspce.log. Returns a success message. 15 | 16 | ### `enable_logging() -> String` 17 | Enables logging to /tmp/lspce.log. Returns a success message. 18 | 19 | ### `set_log_level(level: u8) -> String` 20 | Sets the logging level. Returns a success message. 21 | 22 | ### `get_log_level() -> u8` 23 | Returns the current logging level. 24 | 25 | ### `set_log_file(file: String) -> String` 26 | Sets the logging file path. Returns a success message. 27 | 28 | ## Server Management Functions 29 | 30 | ### `connect(root_uri: String, lsp_type: String, cmd: String, cmd_args: String, initialize_req: String, timeout: i32, emacs_envs: String) -> Option` 31 | Connects to an LSP server or creates a new server process. Returns server info as JSON string if successful. 32 | 33 | ### `shutdown(root_uri: String, file_type: String, req: String) -> Option` 34 | Shuts down an LSP server. Returns None. 35 | 36 | ### `server(root_uri: String, file_type: String) -> Option` 37 | Returns server info as JSON string if server exists. 38 | 39 | ## Request/Response Functions 40 | 41 | ### `request_async(root_uri: String, file_type: String, req: String) -> Option` 42 | Sends an async request to the LSP server. Returns true if successful. 43 | 44 | ### `notify(root_uri: String, file_type: String, req: String) -> Option` 45 | Sends a notification to the LSP server. Returns true if successful. 46 | 47 | ### `read_response_exact(root_uri: String, file_type: String, id: String, method: String) -> Option` 48 | Reads a specific response by request ID. Returns response content as JSON string. 49 | 50 | ### `read_notification(root_uri: String, file_type: String) -> Option` 51 | Reads the next notification from the server. Returns notification content as JSON string. 52 | 53 | ## Diagnostic Functions 54 | 55 | ### `read_file_diagnostics(root_uri: String, file_type: String, uri: String) -> Option` 56 | Reads diagnostics for a specific file URI. Returns diagnostics as JSON string. 57 | 58 | ### `read_latest_response_id(root_uri: String, file_type: String) -> Option` 59 | Returns the ID of the latest response received. 60 | 61 | ### `read_latest_response_tick(root_uri: String, file_type: String) -> Option` 62 | Returns the tick value of the latest response received. 63 | -------------------------------------------------------------------------------- /src/socket.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::VecDeque, 3 | io::{self, BufReader}, 4 | net::TcpStream, 5 | sync::{Arc, Mutex}, 6 | thread, 7 | }; 8 | 9 | use crossbeam_channel::{bounded, Receiver, Sender}; 10 | 11 | use crate::{ 12 | connection::{NOTIFICATION_MAX, REQUEST_MAX}, 13 | logger::Logger, 14 | msg::Message, 15 | stdio::{make_io_threads, IoThreads}, 16 | }; 17 | 18 | pub(crate) fn socket_transport( 19 | stream: TcpStream, 20 | exit: Arc>, 21 | ) -> (Sender, Receiver, IoThreads) { 22 | let exit_reader = Arc::clone(&exit); 23 | let (reader_receiver, reader) = make_reader(stream.try_clone().unwrap(), exit_reader); 24 | 25 | let exit_writer = Arc::clone(&exit); 26 | let (writer_sender, writer) = make_writer(stream.try_clone().unwrap(), exit_writer); 27 | 28 | let io_threads = make_io_threads(reader, writer); 29 | (writer_sender, reader_receiver, io_threads) 30 | } 31 | 32 | fn make_reader( 33 | stream: TcpStream, 34 | exit: Arc>, 35 | ) -> (Receiver, thread::JoinHandle>) { 36 | let (sender_to_client, receiver_for_client) = bounded::(0); 37 | let reader_thread = thread::spawn(move || { 38 | let mut buf_read = BufReader::new(stream); 39 | while let Some(msg) = Message::read(&mut buf_read).unwrap() { 40 | Logger::debug(&format!("socket read {:#?}", &msg)); 41 | 42 | match sender_to_client.send(msg) { 43 | Ok(_) => {} 44 | Err(e) => { 45 | Logger::error(&format!("send to client error {}", e)); 46 | } 47 | } 48 | 49 | let exit = exit.lock().unwrap(); 50 | if *exit { 51 | Logger::info("socket write finished."); 52 | return Ok(()); 53 | } 54 | } 55 | Ok(()) 56 | }); 57 | (receiver_for_client, reader_thread) 58 | } 59 | 60 | fn make_writer( 61 | mut stream: TcpStream, 62 | exit_writer: Arc>, 63 | ) -> (Sender, thread::JoinHandle>) { 64 | let (sender_for_client, receiver_from_client) = bounded::(0); 65 | let writer_thread = thread::spawn(move || { 66 | receiver_from_client 67 | .into_iter() 68 | .try_for_each(|it| { 69 | let exit = exit_writer.lock().unwrap(); 70 | if *exit { 71 | Logger::info("stdio write finished."); 72 | return Ok(()); 73 | } 74 | 75 | Logger::debug(&format!("stdio write {:#?}", &it)); 76 | 77 | it.write(&mut stream) 78 | }) 79 | .unwrap(); 80 | Ok(()) 81 | }); 82 | (sender_for_client, writer_thread) 83 | } 84 | -------------------------------------------------------------------------------- /lspce-snippet.el: -------------------------------------------------------------------------------- 1 | ;;; lspce-snippet.el --- LSP Client for Emacs -*- lexical-binding: t; -*- 2 | 3 | ;; A simplified snippet expanding implementation. 4 | (defun lspce--expand-snippet (snippet &optional expand-env) 5 | "Expand SNIPPET at current point. 6 | 7 | EXPAND-ENV is a list of (SYM VALUE) let-style dynamic 8 | bindings considered when expanding the snippet. If omitted, use 9 | SNIPPET's expand-env field. 10 | 11 | SNIPPET is just a snippet body (which is a string 12 | for normal snippets)." 13 | ;; If not a snippet, no need to invoke the expensive snippet expanding. 14 | (if (not (string-search "$" snippet)) 15 | (insert snippet) 16 | (cl-assert (and yas-minor-mode 17 | (memq 'yas--post-command-handler post-command-hook)) 18 | nil 19 | "[yas] `yas-expand-snippet' needs properly setup `yas-minor-mode'") 20 | 21 | (let* ((start (point)) 22 | (end (point))) 23 | (goto-char start) 24 | (setq yas--indent-original-column (current-column)) 25 | 26 | (let ((content snippet)) 27 | (setq yas--start-column (current-column)) 28 | ;; Stacked expansion: also shoosh the overlay modification hooks. 29 | (let ((yas--inhibit-overlay-hooks t)) 30 | (setq snippet 31 | (yas--snippet-create content expand-env start (point)))) 32 | 33 | ;; Stacked-expansion: This checks for stacked expansion, save the 34 | ;; `yas--previous-active-field' and advance its boundary. 35 | (let ((existing-field (and yas--active-field-overlay 36 | (overlay-buffer yas--active-field-overlay) 37 | (overlay-get yas--active-field-overlay 'yas--field)))) 38 | (when existing-field 39 | (setf (yas--snippet-previous-active-field snippet) existing-field) 40 | (yas--advance-end-maybe-previous-fields 41 | existing-field (overlay-end yas--active-field-overlay) 42 | (cdr yas--active-snippets)))) 43 | 44 | ;; Exit the snippet immediately if no fields. 45 | (unless (yas--snippet-fields snippet) 46 | (yas-exit-snippet snippet)) 47 | 48 | ;; Now, schedule a move to the first field. 49 | (let ((first-field (car (yas--snippet-fields snippet)))) 50 | (when first-field 51 | (sit-for 0) ;; fix issue 125 52 | (yas--letenv (yas--snippet-expand-env snippet) 53 | (yas--move-to-field snippet first-field)) 54 | (when (and (eq (yas--field-number first-field) 0) 55 | (> (length (yas--field-text-for-display 56 | first-field)) 57 | 0)) 58 | ;; Keep region for ${0:exit text}. 59 | (setq deactivate-mark nil)))) 60 | (yas--message 4 "snippet %d expanded." (yas--snippet-id snippet)) 61 | t)))) 62 | 63 | (provide 'lspce-snippet) 64 | -------------------------------------------------------------------------------- /src/logger.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | fs::File, 4 | io::{self, BufRead, Error, Read, Write}, 5 | mem::MaybeUninit, 6 | path::Path, 7 | sync::{ 8 | atomic::{AtomicU8, Ordering}, 9 | Arc, Mutex, Once, 10 | }, 11 | }; 12 | 13 | use chrono::Local; 14 | use lazy_static::lazy_static; 15 | 16 | pub const LOG_DISABLED: u8 = 0; 17 | pub const LOG_ERROR: u8 = 1; 18 | pub const LOG_INFO: u8 = 2; 19 | pub const LOG_TRACE: u8 = 3; 20 | pub const LOG_DEBUG: u8 = 4; 21 | 22 | pub static LOG_LEVEL: AtomicU8 = AtomicU8::new(LOG_INFO); 23 | 24 | lazy_static! { 25 | pub static ref LOG_FILE_NAME: Mutex = Mutex::new(String::new()); 26 | } 27 | 28 | pub fn log_enabled(level: u8) -> bool { 29 | LOG_LEVEL.load(Ordering::Relaxed) >= level 30 | } 31 | 32 | pub fn log_file_name() -> String { 33 | LOG_FILE_NAME.lock().unwrap().clone() 34 | } 35 | 36 | pub struct Logger {} 37 | 38 | impl Logger { 39 | fn log(buf: &str) { 40 | let mut logger = logger().lock().unwrap(); 41 | logger.write_all( 42 | Local::now() 43 | .format("%Y-%m-%d %H:%M:%S%.3f - ") 44 | .to_string() 45 | .as_bytes(), 46 | ); 47 | logger.write_all(buf.as_bytes()); 48 | logger.write_all("\n".as_bytes()); 49 | } 50 | pub fn error(buf: &str) { 51 | let log_level = LOG_LEVEL.load(Ordering::Relaxed); 52 | if log_level >= LOG_ERROR { 53 | Logger::log(buf); 54 | } 55 | } 56 | pub fn info(buf: &str) { 57 | let log_level = LOG_LEVEL.load(Ordering::Relaxed); 58 | if log_level >= LOG_INFO { 59 | Logger::log(buf); 60 | } 61 | } 62 | pub fn trace(buf: &str) { 63 | let log_level = LOG_LEVEL.load(Ordering::Relaxed); 64 | if log_level >= LOG_TRACE { 65 | Logger::log(buf); 66 | } 67 | } 68 | pub fn debug(buf: &str) { 69 | let log_level = LOG_LEVEL.load(Ordering::Relaxed); 70 | if log_level >= LOG_DEBUG { 71 | Logger::log(buf); 72 | } 73 | } 74 | } 75 | 76 | struct FakeFile {} 77 | 78 | impl Write for FakeFile { 79 | fn write(&mut self, buf: &[u8]) -> Result { 80 | Ok(buf.len()) 81 | } 82 | fn flush(&mut self) -> Result<(), Error> { 83 | Ok(()) 84 | } 85 | } 86 | 87 | fn logger() -> &'static Arc> { 88 | static mut LOGGER: MaybeUninit>> = MaybeUninit::uninit(); 89 | static ONCE: Once = Once::new(); 90 | 91 | ONCE.call_once(|| unsafe { 92 | let file_name = log_file_name(); 93 | if !file_name.is_empty() { 94 | if let Ok(f) = File::options().create(true).append(true).open(file_name) { 95 | LOGGER.as_mut_ptr().write(Arc::new(Mutex::new(f))) 96 | } else { 97 | LOGGER.as_mut_ptr().write(Arc::new(Mutex::new(FakeFile {}))) 98 | } 99 | } else { 100 | LOGGER.as_mut_ptr().write(Arc::new(Mutex::new(FakeFile {}))) 101 | } 102 | }); 103 | 104 | unsafe { &*LOGGER.as_mut_ptr() } 105 | } 106 | -------------------------------------------------------------------------------- /src/connection.rs: -------------------------------------------------------------------------------- 1 | //! steal from https://docs.rs/lsp-server/latest/lsp_server/ 2 | //! A language server scaffold, exposing a synchronous crossbeam-channel based API. 3 | //! This crate handles protocol handshaking and parsing messages, while you 4 | //! control the message dispatch loop yourself. 5 | //! 6 | //! Run with `RUST_LOG=lsp_server=debug` to see all the messages. 7 | 8 | use std::{ 9 | collections::VecDeque, 10 | io, 11 | net::{TcpListener, TcpStream, ToSocketAddrs}, 12 | process::{ChildStderr, ChildStdin, ChildStdout}, 13 | sync::{Arc, Mutex}, 14 | }; 15 | 16 | use crossbeam_channel::{Receiver, SendError, Sender}; 17 | 18 | use crate::{ 19 | logger::Logger, 20 | msg::{Message, Notification, Request}, 21 | stdio::IoThreads, 22 | }; 23 | use crate::{socket, stdio}; 24 | 25 | pub const NOTIFICATION_MAX: usize = 10; 26 | pub const REQUEST_MAX: usize = 10; 27 | 28 | /// Connection is just a pair of channels of LSP messages. 29 | pub struct Connection { 30 | sender: Sender, 31 | receiver: Receiver, 32 | exit: Arc>, 33 | } 34 | 35 | impl Connection { 36 | pub fn write(&self, req: Message) -> Result<(), SendError> { 37 | self.sender.send(req) 38 | } 39 | 40 | pub fn read(&self) -> Option { 41 | match self 42 | .receiver 43 | .recv_timeout(std::time::Duration::from_millis(1)) 44 | { 45 | Ok(q) => Some(q), 46 | Err(e) => { 47 | // Logger::error(&format!("Connection read error {}", e)); 48 | None 49 | } 50 | } 51 | } 52 | 53 | pub fn to_exit(&self) { 54 | match self.exit.lock() { 55 | Ok(mut e) => { 56 | *e = true; 57 | } 58 | Err(e) => { 59 | Logger::error(&format!("Connection to_exit error {}", e)); 60 | } 61 | } 62 | Logger::info("after exit in Connection."); 63 | } 64 | 65 | /// Create connection over standard in/standard out. 66 | /// 67 | /// Use this to create a real language server. 68 | pub fn stdio(mut stdin: ChildStdin, mut stdout: ChildStdout, mut stderr: ChildStderr) -> (Connection, IoThreads) { 69 | let exit = Arc::new(Mutex::new(false)); 70 | 71 | let exit2 = Arc::clone(&exit); 72 | let (sender, receiver, io_threads) = stdio::stdio_transport(stdin, stdout, stderr, exit2); 73 | ( 74 | Connection { 75 | sender, 76 | receiver, 77 | exit, 78 | }, 79 | io_threads, 80 | ) 81 | } 82 | 83 | /// Open a connection over tcp. 84 | /// This call blocks until a connection is established. 85 | /// 86 | /// Use this to create a real language server. 87 | pub fn connect(addr: A) -> io::Result<(Connection, IoThreads)> { 88 | let exit = Arc::new(Mutex::new(false)); 89 | 90 | let exit2 = Arc::clone(&exit); 91 | 92 | let stream = TcpStream::connect(addr)?; 93 | let (sender, receiver, io_threads) = socket::socket_transport(stream, exit2); 94 | Ok(( 95 | Connection { 96 | sender, 97 | receiver, 98 | exit, 99 | }, 100 | io_threads, 101 | )) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /lspce-calltree.el: -------------------------------------------------------------------------------- 1 | ;;; lspce.el --- LSP Client for Emacs -*- lexical-binding: t; -*- 2 | 3 | (require 'lspce-core) 4 | (require 'lspce-util) 5 | (require 'seq) 6 | (require 'hierarchy) 7 | (require 'button) 8 | (require 'compile) ;; compilation-info-face, compilation-line-face 9 | 10 | (defcustom lspce-call-hierarchy-call-site nil 11 | "If t, jump to the first call site instead of the start 12 | of the surrounding function when clicking." 13 | :type 'boolean) 14 | 15 | (defcustom lspce-call-hierarchy-show-position nil 16 | "If t, show where the incoming or outgoing call comes from." 17 | :type 'boolean) 18 | 19 | (defvar lspce--incoming-call-buffer-name "*Lspce incoming call*") 20 | (defvar lspce--outgoing-call-buffer-name "*Lspce outgoing call*") 21 | 22 | (defun lspce--prepare-call-hierarchy () 23 | (if (lspce--server-capable-chain "callHierarchyProvider") 24 | (lspce--request "textDocument/prepareCallHierarchy" (lspce--make-textDocumentPositionParams)) 25 | (lspce--warn "Server does not support call hierarchy.") 26 | nil)) 27 | 28 | (define-button-type 'lspce-call-hierarchy-button 29 | 'follow-link t ; Click via mouse 30 | 'face 'default) 31 | 32 | (defun lspce--call-hierarchy-open-file (file) 33 | (select-window (get-mru-window (selected-frame) nil :not-selected)) 34 | (find-file file)) 35 | 36 | (defun lspce--call-hierarchy-next-line () 37 | (interactive) 38 | (when (= (forward-line 1) 1) 39 | (goto-char (point-min))) 40 | (goto-char (line-beginning-position)) 41 | (skip-chars-forward "^a-zA-Z_")) 42 | 43 | (defun lspce--call-hierarchy-previous-line () 44 | (interactive) 45 | (when (= (forward-line -1) -1) 46 | (goto-char (point-max))) 47 | (goto-char (line-beginning-position)) 48 | (skip-chars-forward "^a-zA-Z_")) 49 | 50 | ;; learn some skills from https://github.com/dolmens/eglot-hierarchy 51 | (defun lspce--hierarchy-calls (direction) 52 | "Fetch incoming calls to current symbol. 53 | DIRECTION should be 'incoming or 'outgoing." 54 | (let* ((root (lspce--prepare-call-hierarchy)) 55 | (root-nodes (seq-map (lambda (node) `(:item ,node)) root)) 56 | (tree (hierarchy-new)) 57 | (root-uri lspce--root-uri) 58 | (lsp-type lspce--lsp-type) 59 | (method (if (eq direction 'incoming) 60 | "callHierarchy/incomingCalls" 61 | "callHierarchy/outgoingCalls")) 62 | (tag (if (eq direction 'incoming) 63 | "from" 64 | "to")) 65 | (buffer-name (if (eq direction 'incoming) 66 | lspce--incoming-call-buffer-name 67 | lspce--outgoing-call-buffer-name))) 68 | (if (length> root 0) 69 | (progn 70 | (hierarchy-add-trees 71 | tree 72 | root-nodes 73 | nil 74 | (lambda (node) 75 | (let* ((item (plist-get node :item))) 76 | (condition-case err 77 | (let* ((response (lspce--request method (list :item item) nil root-uri lsp-type)) 78 | children) 79 | (setq children (seq-map (lambda (item) 80 | `(:item ,(gethash tag item) 81 | :fromRanges ,(gethash "fromRanges" item))) 82 | response)) 83 | children) 84 | ((error user-error) 85 | (lspce--error "Failed to invoke %s, %s" method err))))) 86 | nil 87 | t) 88 | (pop-to-buffer 89 | (hierarchy-tree-display 90 | tree 91 | (lambda (node _) 92 | (let* ((item (plist-get node :item)) 93 | (fromRanges (plist-get node :fromRanges)) 94 | (label "") 95 | name range filename selectionRange) 96 | (setq name (gethash "name" item) 97 | filename (lspce--uri-to-path (gethash "uri" item)) 98 | range (gethash "range" item) 99 | selectionRange (gethash "selectionRange" item)) 100 | (if lspce-call-hierarchy-show-position 101 | (let ((rname filename) 102 | (line (when-let* ((start (gethash "start" selectionRange))) 103 | (or (gethash "line" start) 0)))) 104 | (when (string-prefix-p (lspce--uri-to-path root-uri) rname) 105 | (setq rname (string-replace (lspce--uri-to-path root-uri) "" rname)) 106 | (when (string-prefix-p "/" rname) 107 | (setq rname (substring-no-properties rname 1)))) 108 | (setq rname (propertize rname 'face compilation-info-face)) 109 | (setq line (propertize (format "%s" line) 'face compilation-line-face)) 110 | (setq label (format "%s %s:%s" name rname line))) 111 | (setq label name)) 112 | (insert-text-button label 113 | :type 'lspce-call-hierarchy-button 114 | 'action (lambda (btn) 115 | ;; FIXME select-window may fail 116 | (let ((w (get-buffer-window (marker-buffer btn)))) 117 | (when w 118 | (select-window w))) 119 | (lspce--call-hierarchy-open-file filename) 120 | (let (jump-range) 121 | (if (and lspce-call-hierarchy-call-site) 122 | (setq jump-range selectionRange) 123 | (setq jump-range range)) 124 | (goto-char (lspce--lsp-position-to-point 125 | (gethash "start" jump-range)))))))) 126 | (get-buffer-create buffer-name))) 127 | (with-current-buffer buffer-name 128 | (keymap-local-set (kbd "h") #'backward-char) 129 | (keymap-local-set (kbd "l") #'forward-char) 130 | (keymap-local-set (kbd "b") #'backward-char) 131 | (keymap-local-set (kbd "f") #'forward-char) 132 | (keymap-local-set (kbd "n") #'lspce--call-hierarchy-next-line) 133 | (keymap-local-set (kbd "p") #'lspce--call-hierarchy-previous-line) 134 | (keymap-local-set (kbd "j") #'lspce--call-hierarchy-next-line) 135 | (keymap-local-set (kbd "k") #'lspce--call-hierarchy-previous-line) 136 | (goto-char (point-min)) 137 | (widget-button-press (point)))) 138 | (lspce--warn "No incoming call hierachy under point.")))) 139 | 140 | ;;;###autoload 141 | (defun lspce-incoming-calls () 142 | "Fetch incoming calls to current symbol." 143 | (interactive) 144 | (lspce--hierarchy-calls 'incoming)) 145 | 146 | ;;;###autoload 147 | (defun lspce-outgoing-calls () 148 | "Fetch outgoing calls from current symbol." 149 | (interactive) 150 | (lspce--hierarchy-calls 'outgoing)) 151 | 152 | (provide 'lspce-calltree) 153 | -------------------------------------------------------------------------------- /src/stdio.rs: -------------------------------------------------------------------------------- 1 | use std::io::{BufRead, Read}; 2 | use std::time::Instant; 3 | use std::{ 4 | collections::VecDeque, 5 | io::{self, stdin, stdout}, 6 | ops::ControlFlow, 7 | process::{ChildStderr, ChildStdin, ChildStdout}, 8 | sync::{Arc, Mutex}, 9 | thread, 10 | }; 11 | 12 | use bytes::BytesMut; 13 | use crossbeam_channel::{bounded, Receiver, Sender}; 14 | 15 | use crate::logger::{log_enabled, LOG_DEBUG}; 16 | use crate::msg::{ErrorCode, Message, RequestId, Response}; 17 | use crate::{ 18 | connection::{NOTIFICATION_MAX, REQUEST_MAX}, 19 | logger::Logger, 20 | }; 21 | 22 | /// Creates an LSP connection via stdio. 23 | pub(crate) fn stdio_transport( 24 | mut child_stdin: ChildStdin, 25 | mut child_stdout: ChildStdout, 26 | mut child_stderr: ChildStderr, 27 | exit: Arc>, 28 | ) -> (Sender, Receiver, IoThreads) { 29 | let exit_writer = Arc::clone(&exit); 30 | let (sender_for_client, receiver_from_client) = bounded::(10); 31 | let writer_thread = thread::spawn(move || { 32 | let mut stdin = child_stdin; 33 | loop { 34 | { 35 | match exit_writer.lock() { 36 | Ok(exit) => { 37 | if *exit { 38 | Logger::info("stdio writer_thread exited normally."); 39 | break; 40 | } 41 | } 42 | Err(e) => { 43 | Logger::error(&format!("stdio writer_thread exit error {}", e)); 44 | } 45 | } 46 | } 47 | let recv_value = receiver_from_client.recv_timeout(std::time::Duration::from_millis(1)); 48 | match recv_value { 49 | Ok(r) => { 50 | Logger::debug(&format!( 51 | "stdio write {}", 52 | serde_json::to_string_pretty(&r).unwrap_or("invalid json".to_string()) 53 | )); 54 | 55 | r.write(&mut stdin) 56 | } 57 | Err(t) => Ok(()), 58 | }; 59 | } 60 | Ok(()) 61 | }); 62 | 63 | let exit_reader = Arc::clone(&exit); 64 | let (sender_to_client, receiver_for_client) = bounded::(10); 65 | let reader_thread = thread::spawn(move || { 66 | let mut stdout = child_stdout; 67 | let mut reader = std::io::BufReader::new(stdout); 68 | 69 | loop { 70 | { 71 | match exit_reader.lock() { 72 | Ok(exit) => { 73 | if *exit { 74 | Logger::info("stdio reader_thread exited normally."); 75 | break; 76 | } 77 | } 78 | Err(e) => { 79 | Logger::error(&format!("stdio reader_thread exit error {}", e)); 80 | } 81 | } 82 | } 83 | match Message::read(&mut reader) { 84 | Ok(m) => { 85 | if let Some(msg) = m { 86 | if log_enabled(LOG_DEBUG) { 87 | let msg_log = msg.clone(); 88 | match msg_log { 89 | Message::Request(r) => Logger::debug(&format!( 90 | "stdio read request {}", 91 | serde_json::to_string_pretty(&r).unwrap_or(r.content) 92 | )), 93 | Message::Response(r) => Logger::debug(&format!( 94 | "stdio read response {}", 95 | serde_json::to_string_pretty(&r).unwrap_or(r.content) 96 | )), 97 | Message::Notification(r) => Logger::debug(&format!( 98 | "stdio read notification {}", 99 | serde_json::to_string_pretty(&r).unwrap_or(r.content) 100 | )), 101 | } 102 | } 103 | let r = sender_to_client.send(msg); 104 | if r.is_err() { 105 | Logger::error(&format!("stdio read error {}", r.err().unwrap())); 106 | } 107 | } else { 108 | thread::sleep(std::time::Duration::from_millis(1)); 109 | } 110 | } 111 | Err(e) => { 112 | Logger::error(&format!("stdio read error {}", e)); 113 | 114 | let msg = Response::new_err(RequestId::from(1), -32603, format!("{}", e)); 115 | sender_to_client.send(Message::Response(msg)); 116 | } 117 | } 118 | } 119 | 120 | Ok(()) 121 | }); 122 | 123 | let exit_stderr = Arc::clone(&exit); 124 | let stderr_thread = thread::spawn(move || { 125 | let mut stderr = child_stderr; 126 | let mut reader = std::io::BufReader::new(stderr); 127 | let mut buffer = String::new(); 128 | loop { 129 | { 130 | match exit_stderr.lock() { 131 | Ok(exit) => { 132 | if *exit { 133 | Logger::info(&format!("stdio stderr_thread exited normally.")); 134 | break; 135 | } 136 | } 137 | Err(e) => { 138 | Logger::error(&format!("stdio stderr_thread error {}", e)); 139 | } 140 | } 141 | } 142 | 143 | buffer.clear(); 144 | match reader.read_line(&mut buffer) { 145 | Ok(0) => { 146 | // Logger::error(&format!("stderr reach EOF")); 147 | }, 148 | Ok(n) => { 149 | Logger::error(&format!("[stderr] {}", &buffer)); 150 | }, 151 | Err(e) => { 152 | Logger::error(&format!("stderr read error {}", e)); 153 | }, 154 | } 155 | } 156 | }); 157 | 158 | let threads = IoThreads { 159 | reader: reader_thread, 160 | writer: writer_thread, 161 | }; 162 | (sender_for_client, receiver_for_client, threads) 163 | } 164 | 165 | // Creates an IoThreads 166 | pub(crate) fn make_io_threads( 167 | reader: thread::JoinHandle>, 168 | writer: thread::JoinHandle>, 169 | ) -> IoThreads { 170 | IoThreads { reader, writer } 171 | } 172 | 173 | pub struct IoThreads { 174 | reader: thread::JoinHandle>, 175 | writer: thread::JoinHandle>, 176 | } 177 | 178 | impl IoThreads { 179 | pub fn join(self) -> io::Result<()> { 180 | Logger::info("IoThreads join"); 181 | 182 | match self.reader.join() { 183 | Ok(r) => r?, 184 | Err(err) => { 185 | println!("reader panicked!"); 186 | std::panic::panic_any(err) 187 | } 188 | }; 189 | match self.writer.join() { 190 | Ok(r) => r, 191 | Err(err) => { 192 | println!("writer panicked!"); 193 | std::panic::panic_any(err); 194 | } 195 | }; 196 | Logger::info("IoThreads join finished."); 197 | 198 | Ok(()) 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /lspce-util.el: -------------------------------------------------------------------------------- 1 | ;;; lspce.el --- LSP Client for Emacs -*- lexical-binding: t; -*- 2 | 3 | (eval-when-compile 4 | (require 'cl-macs)) 5 | (require 'url-util) 6 | (require 'yasnippet) 7 | 8 | (defconst LSPCE-VERSION "1.1.0") 9 | (defconst LSPCE-NAME "lspce") 10 | 11 | (defconst LSPCE-LOG-ERROR 4) 12 | (defconst LSPCE-LOG-WARN 3) 13 | (defconst LSPCE-LOG-INFO 2) 14 | (defconst LSPCE-LOG-DEBUG 1) 15 | 16 | (defconst lspce--{} (make-hash-table) "The empty JSON object.") 17 | 18 | (defcustom lspce-log-level LSPCE-LOG-WARN 19 | "lspce log level, in elisp side." 20 | :type 'integer 21 | :group 'stock) 22 | 23 | 24 | (defun lspce-current-column () (- (point) (point-at-bol))) 25 | 26 | (defun lspce-lsp-abiding-column () 27 | "Calculate current COLUMN as defined by the LSP spec." 28 | (/ (- (length (encode-coding-region (line-beginning-position) 29 | (point) 'utf-16 t)) 30 | 2) 31 | 2)) 32 | 33 | (cl-defmacro lspce--widening (&rest body) 34 | "Save excursion and restriction. Widen. Then run BODY." (declare (debug t)) 35 | `(save-excursion (save-restriction (widen) ,@body))) 36 | 37 | (cl-defmacro lspce--when-live-buffer (buf &rest body) 38 | "Check BUF live, then do BODY in it." (declare (indent 1) (debug t)) 39 | (let ((b (cl-gensym))) 40 | `(let ((,b ,buf)) (if (buffer-live-p ,b) (with-current-buffer ,b ,@body))))) 41 | 42 | 43 | (defun lspce--pos-to-lsp-position (&optional pos) 44 | "Convert point POS to LSP position." 45 | (lspce--widening 46 | (list :line (1- (line-number-at-pos pos t)) ; F!@&#$CKING OFF-BY-ONE 47 | :character (progn (when pos (goto-char pos)) 48 | (funcall lspce-current-column-function))))) 49 | 50 | (defun lspce-move-to-column (column) 51 | "Move to COLUMN without closely following the LSP spec." 52 | ;; We cannot use `move-to-column' here, because it moves to *visual* 53 | ;; columns, which can be different from LSP columns in case of 54 | ;; `whitespace-mode', `prettify-symbols-mode', etc. (github#296, 55 | ;; github#297) 56 | (goto-char (min (+ (line-beginning-position) column) 57 | (line-end-position)))) 58 | 59 | (defun lspce-move-to-lsp-abiding-column (column) 60 | "Move to COLUMN abiding by the LSP spec." 61 | (cl-loop 62 | initially (move-to-column column) 63 | with lbp = (line-beginning-position) 64 | for diff = (- column 65 | (/ (- (length (encode-coding-region lbp (point) 'utf-16 t)) 66 | 2) 67 | 2)) 68 | until (zerop diff) 69 | do (forward-char (/ (if (> diff 0) (1+ diff) (1- diff)) 2)))) 70 | 71 | ;; copied from eglot 72 | (defconst lspce--uri-path-allowed-chars 73 | (let ((vec (copy-sequence url-path-allowed-chars))) 74 | (aset vec ?: nil) 75 | vec) 76 | "Like `url-path-allows-chars' but more restrictive.") 77 | 78 | (defun lspce--path-to-uri (path) 79 | "URIfy PATH." 80 | (let* ((truepath (file-truename path)) 81 | (full-name (directory-file-name (file-local-name truepath)))) 82 | (if (eq system-type 'windows-nt) 83 | (let ((label (url-type (url-generic-parse-url path))) 84 | prefix) 85 | (setq prefix (concat label ":")) 86 | (concat "file:///" 87 | prefix 88 | (url-hexify-string 89 | (substring full-name (length prefix)) 90 | lspce--uri-path-allowed-chars))) 91 | (concat "file://" 92 | (url-hexify-string 93 | ;; Again watch out for trampy paths. 94 | (directory-file-name (file-local-name truepath)) 95 | lspce--uri-path-allowed-chars))))) 96 | 97 | (defun lspce--uri-to-path (uri) 98 | "Convert URI to a file path." 99 | (when (keywordp uri) 100 | (setq uri (substring (symbol-name uri) 1))) 101 | (let ((retval (url-unhex-string (url-filename (url-generic-parse-url uri))))) 102 | (if (eq system-type 'windows-nt) 103 | (substring retval 1) 104 | retval))) 105 | 106 | (defvar lspce--jsonrpc-id 1000000000) 107 | (defsubst lspce--next-jsonrpc-id () 108 | (setq lspce--jsonrpc-id (1+ lspce--jsonrpc-id)) 109 | (format "%d" lspce--jsonrpc-id)) 110 | 111 | (defun lspce--ensure-dir (path) 112 | "Ensure that directory PATH exists." 113 | (unless (file-directory-p path) 114 | (make-directory path t))) 115 | 116 | (defun lspce--message (format &rest args) 117 | "Message out with FORMAT with ARGS." 118 | (message "[lspce] %s %s" (format-time-string "%Y-%m-%d %H:%M:%S.%3N") (apply #'format format args))) 119 | 120 | (defun lspce--log (level format &rest args) 121 | "Message out with FORMAT with ARGS." 122 | (message "[lspce] [%s] %s %s" level (format-time-string "%Y-%m-%d %H:%M:%S.%3N") (apply #'format format args))) 123 | 124 | (defmacro lspce--error (format &rest args) 125 | `(when (<= lspce-log-level LSPCE-LOG-ERROR) 126 | (apply #'lspce--log "ERROR" ,format (list ,@args)))) 127 | 128 | (defmacro lspce--info (format &rest args) 129 | `(when (<= lspce-log-level LSPCE-LOG-INFO) 130 | (apply #'lspce--log "INFO" ,format (list ,@args)))) 131 | 132 | (defmacro lspce--warn (format &rest args) 133 | `(when (<= lspce-log-level LSPCE-LOG-WARN) 134 | (apply #'lspce--log "WARN" ,format (list ,@args)))) 135 | 136 | (defmacro lspce--debug (format &rest args) 137 | `(when (<= lspce-log-level LSPCE-LOG-DEBUG) 138 | (apply #'lspce--log "DEBUG" ,format (list ,@args)))) 139 | 140 | (defvar lspce--log-perf-enabled nil) 141 | (defmacro lspce--log-perf (format &rest args) 142 | `(when lspce--log-perf-enabled 143 | (apply #'lspce--log "PERF" ,format (list ,@args)))) 144 | 145 | (defvar lspce--log-temp-enabled nil) 146 | (defmacro lspce--log-temp (format &rest args) 147 | `(when lspce--log-temp-enabled 148 | (apply #'lspce--log "TEMP" ,format (list ,@args)))) 149 | 150 | (defun lspce--download-file (source-url dest-location) 151 | "Download a file from a URL at SOURCE-URL and save it to file at DEST-LOCATION." 152 | (let* ((dest-dir (file-name-directory dest-location)) 153 | (dest-abspath (expand-file-name dest-location))) 154 | (unless (file-exists-p dest-dir) 155 | (make-directory dest-dir t)) 156 | (lspce--message "Downloading %s\n to %s." source-url dest-abspath) 157 | (url-copy-file source-url dest-abspath t))) 158 | 159 | (defun lspce--yas-expand-snippet (snippet &optional start end expand-env) 160 | "Expand SNIPPET at current point. 161 | 162 | Text between START and END will be deleted before inserting 163 | template. EXPAND-ENV is a list of (SYM VALUE) let-style dynamic 164 | bindings considered when expanding the snippet. If omitted, use 165 | SNIPPET's expand-env field. 166 | 167 | SNIPPET may be a snippet structure (e.g., as returned by 168 | `yas-lookup-snippet'), or just a snippet body (which is a string 169 | for normal snippets, and a list for command snippets)." 170 | ;; If not a snippet, no need to invoke the expensive snippet expanding. 171 | (if (not (string-search "$" snippet)) 172 | (insert snippet) 173 | (cl-assert (and yas-minor-mode 174 | (memq 'yas--post-command-handler post-command-hook)) 175 | nil 176 | "[yas] `yas-expand-snippet' needs properly setup `yas-minor-mode'") 177 | (run-hooks 'yas-before-expand-snippet-hook) 178 | 179 | (let* ((clear-field 180 | (let ((field (and yas--active-field-overlay 181 | (overlay-buffer yas--active-field-overlay) 182 | (overlay-get yas--active-field-overlay 'yas--field)))) 183 | (and field (yas--skip-and-clear-field-p 184 | field (point) (point) 0) 185 | field))) 186 | (start (point)) 187 | (end (point)) 188 | (to-delete (and (> end start) 189 | (buffer-substring-no-properties start end))) 190 | (yas-selected-text 191 | (cond (yas-selected-text) 192 | ((and (region-active-p) 193 | (not clear-field)) 194 | to-delete)))) 195 | (goto-char start) 196 | (setq yas--indent-original-column (current-column)) 197 | ;; Delete the region to delete, this *does* get undo-recorded. 198 | (when to-delete 199 | (delete-region start end)) 200 | 201 | (let ((content snippet)) 202 | (cond ((listp content) 203 | ;; x) This is a snippet-command. 204 | (yas--eval-for-effect content)) 205 | (t 206 | ;; x) This is a snippet-snippet :-) 207 | (setq yas--start-column (current-column)) 208 | ;; Stacked expansion: also shoosh the overlay modification hooks. 209 | (let ((yas--inhibit-overlay-hooks t)) 210 | (setq snippet 211 | (yas--snippet-create content expand-env start (point)))) 212 | 213 | ;; Stacked-expansion: This checks for stacked expansion, save the 214 | ;; `yas--previous-active-field' and advance its boundary. 215 | (let ((existing-field (and yas--active-field-overlay 216 | (overlay-buffer yas--active-field-overlay) 217 | (overlay-get yas--active-field-overlay 'yas--field)))) 218 | (when existing-field 219 | (setf (yas--snippet-previous-active-field snippet) existing-field) 220 | (yas--advance-end-maybe-previous-fields 221 | existing-field (overlay-end yas--active-field-overlay) 222 | (cdr yas--active-snippets)))) 223 | 224 | ;; Exit the snippet immediately if no fields. 225 | (unless (yas--snippet-fields snippet) 226 | (yas-exit-snippet snippet)) 227 | 228 | ;; Now, schedule a move to the first field. 229 | (let ((first-field (car (yas--snippet-fields snippet)))) 230 | (when first-field 231 | (sit-for 0) ;; fix issue 125 232 | (yas--letenv (yas--snippet-expand-env snippet) 233 | (yas--move-to-field snippet first-field)) 234 | (when (and (eq (yas--field-number first-field) 0) 235 | (> (length (yas--field-text-for-display 236 | first-field)) 237 | 0)) 238 | ;; Keep region for ${0:exit text}. 239 | (setq deactivate-mark nil)))) 240 | (yas--message 4 "snippet %d expanded." (yas--snippet-id snippet)) 241 | t)))))) 242 | 243 | (defun lspce--json-deserialize (str) 244 | "Parse the JSON STRING into a Lisp object." 245 | (json-parse-string str :array-type 'list :null-object nil :false-object nil)) 246 | 247 | (defalias 'lspce--json-serialize #'json-encode) 248 | 249 | (defmacro lspce--add-option (option value options) 250 | `(setq ,options (lspce--add-option-internal ,option ,value ,options))) 251 | 252 | (defun lspce--add-option-internal (option value options) 253 | (let ((sep (string-search "." option)) 254 | left remain ht) 255 | (if (null sep) 256 | (progn 257 | (when (null options) 258 | (setq options (make-hash-table :test #'equal))) 259 | (puthash option value options)) 260 | (progn 261 | (setq left (substring option 0 sep) 262 | remain (substring option (+ sep 1))) 263 | (when (null options) 264 | (setq options (make-hash-table :test #'equal))) 265 | (setq ht (gethash left options)) 266 | (puthash left (lspce--add-option-internal remain value ht) options))) 267 | options)) 268 | 269 | (defmacro lspce--add-options-internal (options kvs) 270 | (declare (indent 1) (debug t)) 271 | (let ((tmpvar-key (make-symbol "key")) 272 | (tmpvar-value (make-symbol "value")) 273 | (tmpvar-params (make-symbol "params")) 274 | (tmpvar-result (make-symbol "result"))) 275 | `(progn (unless (cl-oddp (length ,kvs)) 276 | (let ((,tmpvar-key nil) 277 | (,tmpvar-value nil) 278 | (,tmpvar-params ,kvs) 279 | (,tmpvar-result ,options)) 280 | (while ,tmpvar-params 281 | (setq ,tmpvar-key (car ,tmpvar-params) 282 | ,tmpvar-value (cadr ,tmpvar-params)) 283 | (setq ,tmpvar-result (lspce--add-option-internal ,tmpvar-key ,tmpvar-value ,tmpvar-result)) 284 | (setq ,tmpvar-params (cddr ,tmpvar-params))) 285 | (setq ,options ,tmpvar-result))) 286 | ,options))) 287 | 288 | (defmacro lspce--add-options (options &rest kvs) 289 | `(lspce--add-options-internal ,options (list ,@kvs))) 290 | 291 | (provide 'lspce-util) 292 | -------------------------------------------------------------------------------- /lspce-langs.el: -------------------------------------------------------------------------------- 1 | ;;; lspce.el --- LSP Client for Emacs -*- lexical-binding: t; -*- 2 | 3 | (require 'f) 4 | (eval-and-compile 5 | (require 'lspce-util)) 6 | (eval-when-compile 7 | (require 'cl-macs)) 8 | 9 | (declare-function lspce--request "lspce") 10 | 11 | ;;; rust rust-analyzer 12 | (defun lspce-ra-initializationOptions () 13 | (let ((options (make-hash-table :test #'equal))) 14 | (lspce--add-option "diagnostics.enable" t options) 15 | (lspce--add-option "enableExperimental" :json-false options) 16 | (lspce--add-option "cargo.features" "all" options) 17 | (lspce--add-option "cargo.noDefaultFeatures" :json-false options) 18 | (lspce--add-option "cargo.runBuildScripts" t options) 19 | (lspce--add-option "cargo.loadOutDirsFromCheck" t options) 20 | (lspce--add-option "cargo.autoreload" t options) 21 | (lspce--add-option "cargo.useRustcWrapperForBuildScripts" t options) 22 | (lspce--add-option "completion.addCallParenthesis" t options) 23 | (lspce--add-option "completion.addCallArgumentSnippets" t options) 24 | (lspce--add-option "completion.postfix.enable" :json-false options) 25 | (lspce--add-option "completion.autoimport.enable" t options) 26 | (lspce--add-option "procMacro.enable" t options) 27 | (lspce--add-option "lens.enable" :json-false options))) 28 | 29 | ;;; java jdtls 30 | (defcustom lspce-jdtls-workspace-dir (expand-file-name "~/.jdtls/workspace/") 31 | "jdtls workspace directory." 32 | :group 'lspce 33 | :type 'directory) 34 | 35 | (defcustom lspce-java-vmargs '("--add-modules=ALL-SYSTEM" 36 | "--add-opens java.base/java.util=ALL-UNNAMED" 37 | "--add-opens java.base/java.lang=ALL-UNNAMED" 38 | "-XX:+UseParallelGC" 39 | "-XX:GCTimeRatio=4" 40 | "-XX:AdaptiveSizePolicyWeight=90" 41 | "-Dsun.zip.disableMemoryMapping=true" 42 | "-Xmx1536m" ) 43 | "Specifies extra VM arguments used to launch the Java Language Server." 44 | :group 'lspce 45 | :risky t 46 | :type '(repeat string)) 47 | 48 | ;;;###autoload 49 | (defcustom lspce-java-path "java" 50 | "Path of the java executable." 51 | :group 'lspce 52 | :type 'string) 53 | 54 | (defcustom lspce-jdtls-download-url 55 | "https://download.eclipse.org/jdtls/snapshots/jdt-language-server-latest.tar.gz" 56 | "URL to download the Eclipse JDT language server." 57 | :type 'string 58 | :group 'lspce) 59 | 60 | (defcustom lspce-jdtls-install-dir nil 61 | "Install directory for eclipse.jdt.ls-server." 62 | :group 'lspce 63 | :type 'directory) 64 | 65 | (defcustom lspce-jdtls-launch-mode "Hybrid" 66 | "The launch mode for the Java extension" 67 | :group 'lspce 68 | :type '(choice (:tag "Standard" "LightWeight" "Hybrid"))) 69 | 70 | (defcustom lspce-jdtls-completion-max-results 30 71 | "The max number of completion results jdtls can return." 72 | :type 'integer 73 | :group 'lspce) 74 | 75 | (declare-function tar-untar-buffer "tar-mode" ()) 76 | ;;;###autoload 77 | (defun lspce-install-jdtls-server () 78 | "Install the Eclipse JDT LSP server." 79 | (interactive) 80 | (let* ((dest-dir (expand-file-name lspce-jdtls-install-dir)) 81 | (dest-dir-bak (concat (string-trim-right dest-dir (f-path-separator)) 82 | ".bak" 83 | (format ".%s" (format-time-string "%Y%m%d%H%M%S")))) 84 | (download-url lspce-jdtls-download-url) 85 | (dest-filename (file-name-nondirectory download-url)) 86 | (dest-abspath (expand-file-name dest-filename dest-dir)) 87 | (large-file-warning-threshold nil)) 88 | (when (file-exists-p dest-dir) 89 | (f-move dest-dir dest-dir-bak)) 90 | (f-mkdir-full-path dest-dir) 91 | (lspce--message "Installing Eclipse JDT LSP server, please wait...") 92 | (lspce--download-file download-url dest-abspath) 93 | (lspce--message "Extracting Eclipse JDT LSP archive, please wait...") 94 | (with-temp-buffer 95 | (let ((temporary-buffer (find-file dest-abspath))) 96 | (goto-char (point-min)) 97 | (tar-untar-buffer) 98 | (kill-buffer temporary-buffer))) 99 | (lspce--message "Eclipse JDT LSP server installed in folder \n\"%s\"." dest-dir))) 100 | 101 | (defun lspce--jdtls-workspace-dir () 102 | (let ((proj (project-current)) 103 | workspace) 104 | (lspce--ensure-dir lspce-jdtls-workspace-dir) 105 | (setq workspace (if proj 106 | (file-truename (project-root proj)) 107 | "DEFAULT")) 108 | (f-join lspce-jdtls-workspace-dir (string-replace "/" "!" workspace)))) 109 | 110 | (defun lspce--jdtls-workspace-cache-dir () 111 | (let ((cache-dir (f-join (lspce--jdtls-workspace-dir) ".cache/"))) 112 | (lspce--ensure-dir cache-dir) 113 | cache-dir)) 114 | 115 | (defun lspce--jdtls-project-cache-dir () 116 | (let ((cache-dir (f-join (lspce--project-root-dir) ".lspce/"))) 117 | (lspce--ensure-dir cache-dir) 118 | cache-dir)) 119 | 120 | (defun lspce--jdtls-locate-server-jar () 121 | "Return the jar file location of the language server. 122 | The entry point of the language server is in 123 | `lspce-jdtls-install-dir'/plugins/org.eclipse.equinox.launcher_`version'.jar." 124 | (pcase (f-glob "org.eclipse.equinox.launcher_*.jar" 125 | (expand-file-name "plugins" lspce-jdtls-install-dir)) 126 | (`(,single-entry) single-entry) 127 | (`nil nil) 128 | (server-jar-filenames 129 | (error "Unable to find single point of entry %s" server-jar-filenames)))) 130 | 131 | (defun lspce--jdtls-locate-server-config () 132 | "Return the server config based on OS." 133 | (let ((config (cond 134 | ((string-equal system-type "windows-nt") ; Microsoft Windows 135 | "config_win") 136 | ((string-equal system-type "darwin") ; Mac OS X 137 | "config_mac") 138 | (t "config_linux")))) 139 | (let ((inhibit-message t)) 140 | (message (format "using config for %s" config))) 141 | (expand-file-name config lspce-jdtls-install-dir))) 142 | 143 | (defun lspce-jdtls-cmd-args () 144 | (let ((server-jar (lspce--jdtls-locate-server-jar)) 145 | (server-config (lspce--jdtls-locate-server-config)) 146 | (data (lspce--jdtls-workspace-dir))) 147 | (mapconcat #'identity `("-Declipse.application=org.eclipse.jdt.ls.core.id1" 148 | "-Dosgi.bundles.defaultStartLevel=4" 149 | "-Declipse.product=org.eclipse.jdt.ls.core.product" 150 | "-Dlog.protocol=true" 151 | "-Dlog.level=ALL" 152 | ,@lspce-java-vmargs 153 | "-jar" 154 | ,server-jar 155 | "-configuration" 156 | ,server-config 157 | "-data" 158 | ,data 159 | ) " "))) 160 | 161 | (defvar lspce--jdt-link-pattern "jdt://contents/\\(.*?\\)/\\(.*\\)\.class\\?") 162 | (defun lspce--jdtls-get-jdt-filename (uri) 163 | "Get the name of the buffer calculating it based on URL." 164 | (or (save-match-data 165 | (when (string-match lspce--jdt-link-pattern uri) 166 | (format "%s.java" 167 | (replace-regexp-in-string "/" "." (match-string 2 uri) t t)))) 168 | (save-match-data 169 | (when (string-match 170 | "jdt://.*?/\\(.*?\\)\\?=\\(.*?\\)/.*/\\(.*\\)" 171 | (url-unhex-string uri)) 172 | (format "%s(%s)" (match-string 2 uri) 173 | (string-replace "\\" "" 174 | (string-replace "/" "" (match-string 4 uri)))))) 175 | (save-match-data 176 | (when (string-match "chelib://\\(.*\\)" uri) 177 | (let ((matched (match-string 1 uri))) 178 | (replace-regexp-in-string (regexp-quote ".jar") "jar" matched t t)))) 179 | (error "Unable to match %s" uri))) 180 | 181 | (defun lspce--jdtls-open-jdt-link (uri) 182 | (let ((filename (lspce--jdtls-get-jdt-filename uri)) 183 | fullname content) 184 | (when filename 185 | (setq fullname (f-join (lspce--jdtls-project-cache-dir) filename)) 186 | ;; FIXME use a cache to reduce requesting 187 | (lspce--debug "jdt link uri %s" uri) 188 | (setq content (lspce--request "java/classFileContents" (list :uri uri))) 189 | (when content 190 | (with-temp-file fullname 191 | (erase-buffer) 192 | (insert content)))) 193 | fullname)) 194 | 195 | (defun lspce-jdtls-initializationOptions () 196 | (let ((options (make-hash-table :test #'equal))) 197 | (lspce--add-option "settings.java.server.launchMode" 198 | lspce-jdtls-launch-mode options) 199 | (lspce--add-option "settings.java.completion.enabled" t options) 200 | (lspce--add-option "settings.java.completion.maxResults" 201 | (if (> lspce-jdtls-completion-max-results 0) 202 | lspce-jdtls-completion-max-results 203 | 30) 204 | options) 205 | (lspce--add-option "settings.java.completion.importOrder" 206 | (vector "java" "javax" "com" "org") options) 207 | (lspce--add-option "settings.java.completion.guessMethodArguments" 208 | t options) 209 | (lspce--add-option "settings.java.signatureHelp.enabled" t options) 210 | (lspce--add-option "settings.java.progressReports.enabled" t options) 211 | (lspce--add-option "settings.java.foldingRange.enabled" :json-false options) 212 | (lspce--add-option "settings.java.maxConcurrentBuilds" 1 options) 213 | (lspce--add-option "settings.java.autobuild.enabled" t options) 214 | (lspce--add-option "settings.java.import.maven.enabled" t options) 215 | (lspce--add-option "settings.java.import.gradle.enabled" t options) 216 | (lspce--add-option "settings.java.import.gradle.wrapper.enabled" t options) 217 | (lspce--add-option "settings.java.import.gradle.offline.enabled" t options) 218 | (lspce--add-option "settings.java.maven.downloadSources" t options) 219 | (lspce--add-option "settings.java.maven.updateSnapshots" t options) 220 | (lspce--add-option "settings.java.project.importHint" t options) 221 | (lspce--add-option "settings.java.project.importOnFirstTimeStartup" 222 | "automatic" options) 223 | (lspce--add-option "settings.java.project.referencedLibraries" 224 | (vector "lib/**/*.jar") options) 225 | (lspce--add-option "settings.java.trace.server" "off" options) 226 | (lspce--add-option "settings.java.configuration.updateBuildConfiguration" 227 | "automatic" options) 228 | (lspce--add-option "settings.java.configuration.checkProjectSettingsExclusions" 229 | t options) 230 | (lspce--add-option "settings.java.showBuildStatusOnStart.enabled" t options) 231 | (lspce--add-option "extendedClientCapabilities.classFileContentsSupport" 232 | t options))) 233 | 234 | ;;; python pylsp 235 | (defun lspce-pylsp-initializationOptions () 236 | (let ((options (make-hash-table :test #'equal))) 237 | (lspce--add-option "pylsp.plugins.jedi_completion.include_params" t options) 238 | (lspce--add-option "pylsp.plugins.jedi_completion.fuzzy" t options) 239 | (when (boundp 'lspce-jedi-environment) 240 | (lspce--add-option "pylsp.plugins.jedi.environment" 241 | lspce-jedi-environment options)) 242 | (lspce--add-option "pylsp.plugins.pylint.enabled" :json-false options) 243 | options)) 244 | 245 | ;;; python jedi-language-server 246 | (defun lspce-jedi-initializationOptions () 247 | (let ((options (make-hash-table :test #'equal))) 248 | (when (boundp 'lspce-jedi-environment) 249 | (lspce--add-option "workspace.environmentPath" 250 | lspce-jedi-environment options)) 251 | (lspce--add-option "completion.disableSnippets" :json-false options) 252 | (lspce--add-option "completion.resolveEagerly" :json-false options) 253 | (lspce--add-option "diagnostics.enable" t options) 254 | (lspce--add-option "hover.enable" t options) 255 | (lspce--add-option "jediSettings.caseInsensitiveCompletion" t options) 256 | (lspce--add-option "jediSettings.debug" :json-false options) 257 | (lspce--add-option "markupKindPreferred" "markdown" options) 258 | options)) 259 | 260 | ;;; go gopls 261 | (defun lspce-gopls-initializationOptions () 262 | (let ((options (make-hash-table :test #'equal))) 263 | (lspce--add-option "settings.gopls.usePlaceholders" t options))) 264 | 265 | ;;; typescript deno 266 | (defun lspce-deno-initializationOptions () 267 | (let ((options (make-hash-table :test #'equal))) 268 | (lspce--add-option "enable" t options) 269 | (lspce--add-option "lint" t options) 270 | (lspce--add-option "unstable" :json-false options) 271 | options)) 272 | 273 | (provide 'lspce-langs) 274 | -------------------------------------------------------------------------------- /src/msg.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | io::{self, BufRead, Read, Write}, 4 | thread, time, 5 | }; 6 | 7 | use bytes::Buf; 8 | use bytes::BytesMut; 9 | use serde::{de::DeserializeOwned, Deserialize, Serialize}; 10 | 11 | use crate::{error::ExtractError, logger::Logger}; 12 | 13 | #[derive(Serialize, Deserialize, Debug, Clone)] 14 | #[serde(untagged)] 15 | pub enum Message { 16 | Request(Request), 17 | Response(Response), 18 | Notification(Notification), 19 | } 20 | 21 | impl From for Message { 22 | fn from(request: Request) -> Message { 23 | Message::Request(request) 24 | } 25 | } 26 | 27 | impl From for Message { 28 | fn from(response: Response) -> Message { 29 | Message::Response(response) 30 | } 31 | } 32 | 33 | impl From for Message { 34 | fn from(notification: Notification) -> Message { 35 | Message::Notification(notification) 36 | } 37 | } 38 | 39 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] 40 | #[serde(transparent)] 41 | pub struct RequestId(IdRepr); 42 | 43 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] 44 | #[serde(untagged)] 45 | enum IdRepr { 46 | I32(i32), 47 | String(String), 48 | } 49 | 50 | impl From for RequestId { 51 | fn from(id: i32) -> RequestId { 52 | RequestId(IdRepr::I32(id)) 53 | } 54 | } 55 | 56 | impl From for RequestId { 57 | fn from(id: String) -> RequestId { 58 | RequestId(IdRepr::String(id)) 59 | } 60 | } 61 | 62 | impl fmt::Display for RequestId { 63 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 64 | match &self.0 { 65 | IdRepr::I32(it) => fmt::Display::fmt(it, f), 66 | // Use debug here, to make it clear that `92` and `"92"` are 67 | // different, and to reduce WTF factor if the sever uses `" "` as an 68 | // ID. 69 | IdRepr::String(it) => fmt::Debug::fmt(it, f), 70 | } 71 | } 72 | } 73 | 74 | #[derive(Debug, Serialize, Deserialize, Clone)] 75 | pub struct Request { 76 | pub id: RequestId, 77 | pub method: String, 78 | #[serde(default = "serde_json::Value::default")] 79 | #[serde(skip_serializing_if = "serde_json::Value::is_null")] 80 | pub params: serde_json::Value, 81 | #[serde(skip)] 82 | pub content: String, 83 | pub request_tick: Option, 84 | } 85 | 86 | #[derive(Debug, Serialize, Deserialize, Clone)] 87 | pub struct Response { 88 | // JSON RPC allows this to be null if it was impossible 89 | // to decode the request's id. Ignore this special case 90 | // and just die horribly. 91 | pub id: RequestId, 92 | #[serde(skip_serializing_if = "Option::is_none")] 93 | pub result: Option, 94 | #[serde(skip_serializing_if = "Option::is_none")] 95 | pub error: Option, 96 | #[serde(skip)] 97 | pub content: String, 98 | #[serde(skip)] 99 | pub request_tick: String, 100 | } 101 | 102 | #[derive(Debug, Serialize, Deserialize, Clone)] 103 | pub struct ResponseError { 104 | pub code: i32, 105 | pub message: String, 106 | #[serde(skip_serializing_if = "Option::is_none")] 107 | pub data: Option, 108 | } 109 | 110 | #[derive(Clone, Copy, Debug)] 111 | #[allow(unused)] 112 | pub enum ErrorCode { 113 | // Defined by JSON RPC: 114 | ParseError = -32700, 115 | InvalidRequest = -32600, 116 | MethodNotFound = -32601, 117 | InvalidParams = -32602, 118 | InternalError = -32603, 119 | ServerErrorStart = -32099, 120 | ServerErrorEnd = -32000, 121 | 122 | /// Error code indicating that a server received a notification or 123 | /// request before the server has received the `initialize` request. 124 | ServerNotInitialized = -32002, 125 | UnknownError = -32001, 126 | 127 | // Defined by the protocol: 128 | /// The client has canceled a request and a server has detected 129 | /// the cancel. 130 | RequestCanceled = -32800, 131 | 132 | /// The server detected that the content of a document got 133 | /// modified outside normal conditions. A server should 134 | /// NOT send this error code if it detects a content change 135 | /// in it unprocessed messages. The result even computed 136 | /// on an older state might still be useful for the client. 137 | /// 138 | /// If a client decides that a result is not of any use anymore 139 | /// the client should cancel the request. 140 | ContentModified = -32801, 141 | 142 | /// The server cancelled the request. This error code should 143 | /// only be used for requests that explicitly support being 144 | /// server cancellable. 145 | /// 146 | /// @since 3.17.0 147 | ServerCancelled = -32802, 148 | } 149 | 150 | #[derive(Debug, Serialize, Deserialize, Clone)] 151 | pub struct Notification { 152 | pub method: String, 153 | #[serde(default = "serde_json::Value::default")] 154 | #[serde(skip_serializing_if = "serde_json::Value::is_null")] 155 | pub params: serde_json::Value, 156 | #[serde(skip)] 157 | pub content: String, 158 | } 159 | 160 | impl Message { 161 | pub fn read(r: &mut impl BufRead) -> io::Result> { 162 | Message::_read(r) 163 | } 164 | fn _read(r: &mut dyn BufRead) -> io::Result> { 165 | let text = match read_msg_text(r)? { 166 | None => return Ok(None), 167 | Some(text) => text, 168 | }; 169 | // Logger::log(&format!("Message::_read {}", &text)); 170 | let msg = serde_json::from_str::(&text)?; 171 | match msg { 172 | Message::Request(mut r) => { 173 | r.content = text; 174 | Ok(Some(Message::Request(r))) 175 | } 176 | Message::Response(mut r) => { 177 | r.content = text; 178 | Ok(Some(Message::Response(r))) 179 | } 180 | Message::Notification(mut r) => { 181 | r.content = text; 182 | Ok(Some(Message::Notification(r))) 183 | } 184 | } 185 | } 186 | pub fn write(self, w: &mut impl Write) -> io::Result<()> { 187 | self._write(w) 188 | } 189 | fn _write(self, w: &mut dyn Write) -> io::Result<()> { 190 | #[derive(Serialize)] 191 | struct JsonRpc { 192 | jsonrpc: &'static str, 193 | #[serde(flatten)] 194 | msg: Message, 195 | } 196 | let text = serde_json::to_string(&JsonRpc { 197 | jsonrpc: "2.0", 198 | msg: self, 199 | })?; 200 | // Logger::log(&format!("Message::_write {}", &text)); 201 | write_msg_text(w, &text) 202 | } 203 | } 204 | 205 | impl Response { 206 | pub fn new_ok(id: RequestId, result: R) -> Response { 207 | Response { 208 | id, 209 | result: Some(serde_json::to_value(result).unwrap()), 210 | error: None, 211 | content: "".to_string(), 212 | request_tick: "".to_string(), 213 | } 214 | } 215 | pub fn new_err(id: RequestId, code: i32, message: String) -> Response { 216 | let error = ResponseError { 217 | code, 218 | message, 219 | data: None, 220 | }; 221 | Response { 222 | id, 223 | result: None, 224 | error: Some(error), 225 | content: "".to_string(), 226 | request_tick: "".to_string(), 227 | } 228 | } 229 | } 230 | 231 | impl Request { 232 | pub fn new(id: RequestId, method: String, params: P) -> Request { 233 | Request { 234 | id, 235 | method, 236 | params: serde_json::to_value(params).unwrap(), 237 | content: "".to_string(), 238 | request_tick: None, 239 | } 240 | } 241 | pub fn extract( 242 | self, 243 | method: &str, 244 | ) -> Result<(RequestId, P), ExtractError> { 245 | if self.method == method { 246 | let params = 247 | serde_json::from_value(self.params).map_err(|error| ExtractError::JsonError { 248 | method: self.method, 249 | error, 250 | })?; 251 | Ok((self.id, params)) 252 | } else { 253 | Err(ExtractError::MethodMismatch(self)) 254 | } 255 | } 256 | 257 | pub(crate) fn is_shutdown(&self) -> bool { 258 | self.method == "shutdown" 259 | } 260 | pub(crate) fn is_initialize(&self) -> bool { 261 | self.method == "initialize" 262 | } 263 | } 264 | 265 | impl Notification { 266 | pub fn new(method: String, params: impl Serialize) -> Notification { 267 | Notification { 268 | method, 269 | params: serde_json::to_value(params).unwrap(), 270 | content: "".to_string(), 271 | } 272 | } 273 | pub fn extract( 274 | self, 275 | method: &str, 276 | ) -> Result> { 277 | if self.method == method { 278 | serde_json::from_value(self.params).map_err(|error| ExtractError::JsonError { 279 | method: self.method, 280 | error, 281 | }) 282 | } else { 283 | Err(ExtractError::MethodMismatch(self)) 284 | } 285 | } 286 | pub(crate) fn is_exit(&self) -> bool { 287 | self.method == "exit" 288 | } 289 | pub(crate) fn is_initialized(&self) -> bool { 290 | self.method == "initialized" 291 | } 292 | } 293 | 294 | fn read_msg_text(inp: &mut dyn BufRead) -> io::Result> { 295 | fn invalid_data(error: impl Into>) -> io::Error { 296 | io::Error::new(io::ErrorKind::InvalidData, error) 297 | } 298 | macro_rules! invalid_data { 299 | ($($tt:tt)*) => (invalid_data(format!($($tt)*))) 300 | } 301 | 302 | let mut size = None; 303 | let mut buf = String::new(); 304 | loop { 305 | buf.clear(); 306 | if inp.read_line(&mut buf)? == 0 { 307 | return Ok(None); 308 | } 309 | if !buf.ends_with("\r\n") { 310 | return Err(invalid_data!("malformed header: {:?}", buf)); 311 | } 312 | let buf = &buf[..buf.len() - 2]; 313 | if buf.is_empty() { 314 | break; 315 | } 316 | let mut parts = buf.splitn(2, ": "); 317 | let header_name = parts.next().unwrap(); 318 | let header_value = parts 319 | .next() 320 | .ok_or_else(|| invalid_data!("malformed header: {:?}", buf))?; 321 | if header_name == "Content-Length" { 322 | size = Some(header_value.parse::().map_err(invalid_data)?); 323 | } 324 | } 325 | let size: usize = size.ok_or_else(|| invalid_data!("no Content-Length"))?; 326 | let mut buf = buf.into_bytes(); 327 | buf.resize(size, 0); 328 | inp.read_exact(&mut buf)?; 329 | let buf = String::from_utf8(buf).map_err(invalid_data)?; 330 | 331 | Ok(Some(buf)) 332 | } 333 | 334 | fn write_msg_text(out: &mut dyn Write, msg: &str) -> io::Result<()> { 335 | out.write_all(format!("Content-Length: {}\r\n\r\n{}", msg.len(), &msg).as_bytes())?; 336 | out.flush()?; 337 | 338 | Ok(()) 339 | } 340 | 341 | #[cfg(test)] 342 | mod tests { 343 | use super::{Message, Notification, Request, RequestId}; 344 | 345 | #[test] 346 | fn shutdown_with_explicit_null() { 347 | let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\", \"params\": null }"; 348 | let msg: Message = serde_json::from_str(text).unwrap(); 349 | 350 | assert!( 351 | matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") 352 | ); 353 | } 354 | 355 | #[test] 356 | fn shutdown_with_no_params() { 357 | let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\"}"; 358 | let msg: Message = serde_json::from_str(text).unwrap(); 359 | 360 | assert!( 361 | matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") 362 | ); 363 | } 364 | 365 | #[test] 366 | fn notification_with_explicit_null() { 367 | let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\", \"params\": null }"; 368 | let msg: Message = serde_json::from_str(text).unwrap(); 369 | 370 | assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); 371 | } 372 | 373 | #[test] 374 | fn notification_with_no_params() { 375 | let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\"}"; 376 | let msg: Message = serde_json::from_str(text).unwrap(); 377 | 378 | assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); 379 | } 380 | 381 | #[test] 382 | fn serialize_request_with_null_params() { 383 | let msg = Message::Request(Request { 384 | id: RequestId::from(3), 385 | method: "shutdown".into(), 386 | params: serde_json::Value::Null, 387 | content: "".to_string(), 388 | request_tick: Some("".to_string()), 389 | }); 390 | let serialized = serde_json::to_string(&msg).unwrap(); 391 | 392 | assert_eq!("{\"id\":3,\"method\":\"shutdown\"}", serialized); 393 | } 394 | 395 | #[test] 396 | fn serialize_notification_with_null_params() { 397 | let msg = Message::Notification(Notification { 398 | method: "exit".into(), 399 | params: serde_json::Value::Null, 400 | content: "".to_string(), 401 | }); 402 | let serialized = serde_json::to_string(&msg).unwrap(); 403 | 404 | assert_eq!("{\"method\":\"exit\"}", serialized); 405 | } 406 | } 407 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "anyhow" 7 | version = "1.0.56" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27" 10 | 11 | [[package]] 12 | name = "autocfg" 13 | version = "1.1.0" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 16 | 17 | [[package]] 18 | name = "bitflags" 19 | version = "1.3.2" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 22 | 23 | [[package]] 24 | name = "bytes" 25 | version = "1.1.0" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" 28 | 29 | [[package]] 30 | name = "cfg-if" 31 | version = "1.0.0" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 34 | 35 | [[package]] 36 | name = "chrono" 37 | version = "0.4.19" 38 | source = "registry+https://github.com/rust-lang/crates.io-index" 39 | checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" 40 | dependencies = [ 41 | "libc", 42 | "num-integer", 43 | "num-traits", 44 | "time", 45 | "winapi", 46 | ] 47 | 48 | [[package]] 49 | name = "crossbeam-channel" 50 | version = "0.5.4" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" 53 | dependencies = [ 54 | "cfg-if", 55 | "crossbeam-utils", 56 | ] 57 | 58 | [[package]] 59 | name = "crossbeam-utils" 60 | version = "0.8.8" 61 | source = "registry+https://github.com/rust-lang/crates.io-index" 62 | checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" 63 | dependencies = [ 64 | "cfg-if", 65 | "lazy_static", 66 | ] 67 | 68 | [[package]] 69 | name = "ctor" 70 | version = "0.1.22" 71 | source = "registry+https://github.com/rust-lang/crates.io-index" 72 | checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c" 73 | dependencies = [ 74 | "quote", 75 | "syn", 76 | ] 77 | 78 | [[package]] 79 | name = "darling" 80 | version = "0.10.2" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858" 83 | dependencies = [ 84 | "darling_core", 85 | "darling_macro", 86 | ] 87 | 88 | [[package]] 89 | name = "darling_core" 90 | version = "0.10.2" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b" 93 | dependencies = [ 94 | "fnv", 95 | "ident_case", 96 | "proc-macro2", 97 | "quote", 98 | "strsim", 99 | "syn", 100 | ] 101 | 102 | [[package]] 103 | name = "darling_macro" 104 | version = "0.10.2" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" 107 | dependencies = [ 108 | "darling_core", 109 | "quote", 110 | "syn", 111 | ] 112 | 113 | [[package]] 114 | name = "emacs" 115 | version = "0.18.0" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "6797a940189d353de79bec32abe717aeeecd79a08236e84404c888354e040665" 118 | dependencies = [ 119 | "anyhow", 120 | "ctor", 121 | "emacs-macros", 122 | "emacs_module", 123 | "once_cell", 124 | "rustc_version", 125 | "thiserror", 126 | ] 127 | 128 | [[package]] 129 | name = "emacs-macros" 130 | version = "0.17.0" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "69656fdfe7c2608b87164964db848b5c3795de7302e3130cce7131552c6be161" 133 | dependencies = [ 134 | "darling", 135 | "proc-macro2", 136 | "quote", 137 | "syn", 138 | ] 139 | 140 | [[package]] 141 | name = "emacs_module" 142 | version = "0.18.0" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "b3067bc974045ed2c6db333bd4fc30d3bdaafa6421a9a889fa7b2826b6f7f2fa" 145 | 146 | [[package]] 147 | name = "fnv" 148 | version = "1.0.7" 149 | source = "registry+https://github.com/rust-lang/crates.io-index" 150 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" 151 | 152 | [[package]] 153 | name = "form_urlencoded" 154 | version = "1.0.1" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" 157 | dependencies = [ 158 | "matches", 159 | "percent-encoding", 160 | ] 161 | 162 | [[package]] 163 | name = "ident_case" 164 | version = "1.0.1" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" 167 | 168 | [[package]] 169 | name = "idna" 170 | version = "0.2.3" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" 173 | dependencies = [ 174 | "matches", 175 | "unicode-bidi", 176 | "unicode-normalization", 177 | ] 178 | 179 | [[package]] 180 | name = "itoa" 181 | version = "1.0.1" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" 184 | 185 | [[package]] 186 | name = "lazy_static" 187 | version = "1.4.0" 188 | source = "registry+https://github.com/rust-lang/crates.io-index" 189 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 190 | 191 | [[package]] 192 | name = "libc" 193 | version = "0.2.124" 194 | source = "registry+https://github.com/rust-lang/crates.io-index" 195 | checksum = "21a41fed9d98f27ab1c6d161da622a4fa35e8a54a8adc24bbf3ddd0ef70b0e50" 196 | 197 | [[package]] 198 | name = "lsp-types" 199 | version = "0.95.0" 200 | source = "registry+https://github.com/rust-lang/crates.io-index" 201 | checksum = "158c1911354ef73e8fe42da6b10c0484cb65c7f1007f28022e847706c1ab6984" 202 | dependencies = [ 203 | "bitflags", 204 | "serde", 205 | "serde_json", 206 | "serde_repr", 207 | "url", 208 | ] 209 | 210 | [[package]] 211 | name = "lspce-module" 212 | version = "1.1.0" 213 | dependencies = [ 214 | "bytes", 215 | "chrono", 216 | "crossbeam-channel", 217 | "emacs", 218 | "lazy_static", 219 | "lsp-types", 220 | "serde", 221 | "serde_json", 222 | ] 223 | 224 | [[package]] 225 | name = "matches" 226 | version = "0.1.9" 227 | source = "registry+https://github.com/rust-lang/crates.io-index" 228 | checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" 229 | 230 | [[package]] 231 | name = "num-integer" 232 | version = "0.1.44" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" 235 | dependencies = [ 236 | "autocfg", 237 | "num-traits", 238 | ] 239 | 240 | [[package]] 241 | name = "num-traits" 242 | version = "0.2.14" 243 | source = "registry+https://github.com/rust-lang/crates.io-index" 244 | checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" 245 | dependencies = [ 246 | "autocfg", 247 | ] 248 | 249 | [[package]] 250 | name = "once_cell" 251 | version = "1.10.0" 252 | source = "registry+https://github.com/rust-lang/crates.io-index" 253 | checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" 254 | 255 | [[package]] 256 | name = "percent-encoding" 257 | version = "2.1.0" 258 | source = "registry+https://github.com/rust-lang/crates.io-index" 259 | checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" 260 | 261 | [[package]] 262 | name = "proc-macro2" 263 | version = "1.0.36" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" 266 | dependencies = [ 267 | "unicode-xid", 268 | ] 269 | 270 | [[package]] 271 | name = "quote" 272 | version = "1.0.16" 273 | source = "registry+https://github.com/rust-lang/crates.io-index" 274 | checksum = "b4af2ec4714533fcdf07e886f17025ace8b997b9ce51204ee69b6da831c3da57" 275 | dependencies = [ 276 | "proc-macro2", 277 | ] 278 | 279 | [[package]] 280 | name = "rustc_version" 281 | version = "0.2.3" 282 | source = "registry+https://github.com/rust-lang/crates.io-index" 283 | checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" 284 | dependencies = [ 285 | "semver", 286 | ] 287 | 288 | [[package]] 289 | name = "ryu" 290 | version = "1.0.9" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" 293 | 294 | [[package]] 295 | name = "semver" 296 | version = "0.9.0" 297 | source = "registry+https://github.com/rust-lang/crates.io-index" 298 | checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" 299 | dependencies = [ 300 | "semver-parser", 301 | ] 302 | 303 | [[package]] 304 | name = "semver-parser" 305 | version = "0.7.0" 306 | source = "registry+https://github.com/rust-lang/crates.io-index" 307 | checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" 308 | 309 | [[package]] 310 | name = "serde" 311 | version = "1.0.136" 312 | source = "registry+https://github.com/rust-lang/crates.io-index" 313 | checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" 314 | dependencies = [ 315 | "serde_derive", 316 | ] 317 | 318 | [[package]] 319 | name = "serde_derive" 320 | version = "1.0.136" 321 | source = "registry+https://github.com/rust-lang/crates.io-index" 322 | checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" 323 | dependencies = [ 324 | "proc-macro2", 325 | "quote", 326 | "syn", 327 | ] 328 | 329 | [[package]] 330 | name = "serde_json" 331 | version = "1.0.79" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" 334 | dependencies = [ 335 | "itoa", 336 | "ryu", 337 | "serde", 338 | ] 339 | 340 | [[package]] 341 | name = "serde_repr" 342 | version = "0.1.7" 343 | source = "registry+https://github.com/rust-lang/crates.io-index" 344 | checksum = "98d0516900518c29efa217c298fa1f4e6c6ffc85ae29fd7f4ee48f176e1a9ed5" 345 | dependencies = [ 346 | "proc-macro2", 347 | "quote", 348 | "syn", 349 | ] 350 | 351 | [[package]] 352 | name = "strsim" 353 | version = "0.9.3" 354 | source = "registry+https://github.com/rust-lang/crates.io-index" 355 | checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" 356 | 357 | [[package]] 358 | name = "syn" 359 | version = "1.0.89" 360 | source = "registry+https://github.com/rust-lang/crates.io-index" 361 | checksum = "ea297be220d52398dcc07ce15a209fce436d361735ac1db700cab3b6cdfb9f54" 362 | dependencies = [ 363 | "proc-macro2", 364 | "quote", 365 | "unicode-xid", 366 | ] 367 | 368 | [[package]] 369 | name = "thiserror" 370 | version = "1.0.30" 371 | source = "registry+https://github.com/rust-lang/crates.io-index" 372 | checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" 373 | dependencies = [ 374 | "thiserror-impl", 375 | ] 376 | 377 | [[package]] 378 | name = "thiserror-impl" 379 | version = "1.0.30" 380 | source = "registry+https://github.com/rust-lang/crates.io-index" 381 | checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" 382 | dependencies = [ 383 | "proc-macro2", 384 | "quote", 385 | "syn", 386 | ] 387 | 388 | [[package]] 389 | name = "time" 390 | version = "0.1.44" 391 | source = "registry+https://github.com/rust-lang/crates.io-index" 392 | checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" 393 | dependencies = [ 394 | "libc", 395 | "wasi", 396 | "winapi", 397 | ] 398 | 399 | [[package]] 400 | name = "tinyvec" 401 | version = "1.5.1" 402 | source = "registry+https://github.com/rust-lang/crates.io-index" 403 | checksum = "2c1c1d5a42b6245520c249549ec267180beaffcc0615401ac8e31853d4b6d8d2" 404 | dependencies = [ 405 | "tinyvec_macros", 406 | ] 407 | 408 | [[package]] 409 | name = "tinyvec_macros" 410 | version = "0.1.0" 411 | source = "registry+https://github.com/rust-lang/crates.io-index" 412 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 413 | 414 | [[package]] 415 | name = "unicode-bidi" 416 | version = "0.3.7" 417 | source = "registry+https://github.com/rust-lang/crates.io-index" 418 | checksum = "1a01404663e3db436ed2746d9fefef640d868edae3cceb81c3b8d5732fda678f" 419 | 420 | [[package]] 421 | name = "unicode-normalization" 422 | version = "0.1.19" 423 | source = "registry+https://github.com/rust-lang/crates.io-index" 424 | checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" 425 | dependencies = [ 426 | "tinyvec", 427 | ] 428 | 429 | [[package]] 430 | name = "unicode-xid" 431 | version = "0.2.2" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 434 | 435 | [[package]] 436 | name = "url" 437 | version = "2.2.2" 438 | source = "registry+https://github.com/rust-lang/crates.io-index" 439 | checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" 440 | dependencies = [ 441 | "form_urlencoded", 442 | "idna", 443 | "matches", 444 | "percent-encoding", 445 | "serde", 446 | ] 447 | 448 | [[package]] 449 | name = "wasi" 450 | version = "0.10.0+wasi-snapshot-preview1" 451 | source = "registry+https://github.com/rust-lang/crates.io-index" 452 | checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" 453 | 454 | [[package]] 455 | name = "winapi" 456 | version = "0.3.9" 457 | source = "registry+https://github.com/rust-lang/crates.io-index" 458 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 459 | dependencies = [ 460 | "winapi-i686-pc-windows-gnu", 461 | "winapi-x86_64-pc-windows-gnu", 462 | ] 463 | 464 | [[package]] 465 | name = "winapi-i686-pc-windows-gnu" 466 | version = "0.4.0" 467 | source = "registry+https://github.com/rust-lang/crates.io-index" 468 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 469 | 470 | [[package]] 471 | name = "winapi-x86_64-pc-windows-gnu" 472 | version = "0.4.0" 473 | source = "registry+https://github.com/rust-lang/crates.io-index" 474 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 475 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | # -*- eval: (org-appear-mode -1); -*- 2 | #+TITLE: LSPCE 3 | #+AUTHOR: zbelial 4 | #+EMAIL: zjyzhaojiyang@gmail.com 5 | #+DATE: 2022 6 | #+LANGUAGE: en 7 | 8 | * Introduction 9 | LSPCE - LSP Client for Emacs, is a simple lsp client that is implemented as an Emacs module. 10 | 11 | It does not want to be a full-featured lsp client. The features it supports are: 12 | - find definitions/references/implementatoins (as a xref backend) 13 | - completion (as a capf function) 14 | support snippet and auto import. 15 | - diagnostics (as a flymake backend) 16 | process diagnostics when idle. 17 | - hover (triggered by ~lspce-help-at-point~) 18 | - signature/hover help (as an ~eldoc-documentation-functions~ function) 19 | - code action (triggered by ~lspce-code-actions~) 20 | - rename (triggered by ~lspce-rename~ ) 21 | - call hierarchy 22 | 23 | 24 | All features I need have been implemented now, and my next step is to make it more robust and more performant. 25 | 26 | 27 | I have tested LSPCE with `pyright` and `rust-analyzer` in Emacs 28, and I'm using it to develop itself :). 28 | 29 | Below are some images to illustrate what LSPCE looks like. 30 | 31 | Complete using company-capf. 32 | [[file:images/completion.png]] 33 | 34 | Use xref to find references. 35 | [[file:images/references.png]] 36 | 37 | Display signature and hover at the same time. 38 | [[file:images/eldoc.png]] 39 | 40 | * CAUTION 41 | I think that lspce is in good shape now, but bugs are expected. 42 | 43 | I develop, test and run lspce with Emacs 28.2 on Linux (manjaro), and since I don't have any Windows and MacOS computer, lspce may not work as expected. But @fast-90 tested it with pylsp on MacOS and found that it worked almost (except could not recognize virual env). 44 | 45 | * Dependencies 46 | Lspce depends on [[https://github.com/rejeep/f.el][f.el]], [[https://github.com/joaotavora/yasnippet][yasnippet]] and [[https://github.com/jrblevin/markdown-mode][markdown-mode]]. You should install them first. 47 | 48 | * Installation 49 | At the moment, you can only install LSPCE by cloning this repo and compile rust code manually. 50 | 51 | Before installing LSPCE, you should install rust and cargo first. 52 | 53 | ** Installing from the Git Repository 54 | #+BEGIN_SRC bash 55 | $ git clone https://github.com/zbelial/lspce.git ~/.emacs.d/site-lisp/lspce 56 | $ cd ~/.emacs.d/site-lisp/lspce 57 | $ cargo build 58 | # or, to build a release version 59 | $ cargo build --release 60 | # then you should rename the .so file (and copy it to another directory ) 61 | $ mv target/debug/liblspce_module.so lspce-module.so 62 | # or alternatively, if .d and .dylib files are created for you: (thanks @fast-90 for this) 63 | $ mv target/debug/liblspce_module.d lspce-module.d 64 | $ mv target/debug/liblspce_module.dylib lspce-module.dylib 65 | #+END_SRC 66 | 67 | ** Installing using Straight 68 | #+BEGIN_SRC elisp 69 | (straight-use-package 70 | `(lspce :type git :host github :repo "zbelial/lspce" 71 | :files (:defaults ,(pcase system-type 72 | ('gnu/linux "lspce-module.so") 73 | ('darwin "lspce-module.dylib"))) 74 | :pre-build ,(pcase system-type 75 | ('gnu/linux '(("cargo" "build" "--release") ("cp" "./target/release/liblspce_module.so" "./lspce-module.so"))) 76 | ('darwin '(("cargo" "build" "--release") ("cp" "./target/release/liblspce_module.dylib" "./lspce-module.dylib")))))) 77 | #+END_SRC 78 | 79 | * Get started 80 | #+BEGIN_SRC elisp 81 | (use-package lspce 82 | :load-path "/path/to/lspce" 83 | :config (progn 84 | (setq lspce-send-changes-idle-time 0.1) 85 | (setq lspce-show-log-level-in-modeline t) ;; show log level in mode line 86 | 87 | ;; You should call this first if you want lspce to write logs 88 | (lspce-set-log-file "/tmp/lspce.log") 89 | 90 | ;; By default, lspce will not write log out to anywhere. 91 | ;; To enable logging, you can add the following line 92 | ;; (lspce-enable-logging) 93 | ;; You can enable/disable logging on the fly by calling `lspce-enable-logging' or `lspce-disable-logging'. 94 | 95 | ;; enable lspce in particular buffers 96 | ;; (add-hook 'rust-mode-hook 'lspce-mode) 97 | 98 | ;; modify `lspce-server-programs' to add or change a lsp server, see document 99 | ;; of `lspce-lsp-type-function' to understand how to get buffer's lsp type. 100 | ;; Bellow is what I use 101 | (setq lspce-server-programs `(("rust" "rust-analyzer" "" lspce-ra-initializationOptions) 102 | ("python" "pylsp" "" ) 103 | ("C" "clangd" "--all-scopes-completion --clang-tidy --enable-config --header-insertion-decorators=0") 104 | ("java" "java" lspce-jdtls-cmd-args lspce-jdtls-initializationOptions) 105 | )) 106 | ) 107 | ) 108 | #+END_SRC 109 | 110 | ** About lsp servers' stderr 111 | Lspce support writing stderr message from lsp servers to the log file (set up by calling `lspce-set-log-file`) in the log level ERROR, and the log contains string "[stderr]". 112 | 113 | * Customization 114 | | Variable | Default | Description | 115 | |--------------------------------------------------+----------------+-----------------------------------------------------------------------------------------------------| 116 | | lspce-send-changes-idle-time | 0.5 | How much idle time to wait before sending changes to the lsp server. | 117 | | lspce-doc-tooltip-border-width | 1 | The border width of lspce tooltip. | 118 | | lspce-doc-tooltip-timeout | 30 | How long to wait before lspce tooltip disappears (only for posframe) | 119 | | lspce-completion-ignore-case | t | If non-nil, ignore case when completing. | 120 | | lspce-completion-no-annotation | nil | If non-nil, do not display completion item's annotation. | 121 | | lspce-enable-eldoc | t | If non-nil, enable eldoc. | 122 | | lspce-eldoc-enable-hover | t | If non-nil, enable hover in eldoc. | 123 | | lspce-eldoc-enable-signature | t | If non-nil, enable signature in eldoc. | 124 | | lspce-enable-flymake | t | If non-nil, enable flymake. | 125 | | lspce-connect-server-timeout | 60 | The timeout of connecting to lsp server, in seconds. | 126 | | lspce-modes-enable-single-file-root | `(python-mode) | Major modes where lspce enables even for a single file (IOW no project). | 127 | | lspce-enable-logging | nil | If non-nil, enable logging to file. | 128 | | lspce-auto-enable-within-project | t | If non-nil, enable lspce when a file is opened if lspce has already been enabled in current project | 129 | | lspce-after-text-edit-hook | nil | Functions called after finishing all text edits in a buffer. | 130 | | lspce-after-each-text-edit-hook | nil | Functions called after finishing each text edit in a buffer. | 131 | | lspce-show-log-level-in-modeline | t | If non-nil, show log level in modeline. | 132 | | lspce-inherit-exec-path | nil | If non-nil, pass `exec-path' as PATH to rust code to create the lsp subprocess. | 133 | | MAX_DIAGNOSTIC_COUNT | 30 | How many diagnostics should be retrieved. | 134 | | lspce-xref-append-implementations-to-definitions | nil | If non-nil, also fetch implementations when fetching definitions. | 135 | | lspce-envs-pass-to-subprocess | nil | Environment variables that should be passed to rust code to create the lsp subprocess. | 136 | | lspce-jdtls-completion-max-results | 30 | how many completion items jdtls can return at the most | 137 | | lspce-enable-imenu-index-function | nil | set `lspce-imenu-create' as `imenu-create-index-function'. | 138 | 139 | ** MAX_DIAGNOSTIC_COUNT 140 | This variable is defined in rust code, you can customize it via =lspce-change-max-diagnostics-count= . If it's negative, then all diagnostics will be retrieved. 141 | 142 | ** Logging 143 | On rust code side, there are 5 log level: DISABLED(0), ERROR(1), INFO(2), TRACE(3), DEBUG(4), and the default level is INFO. You can use functions =lspce-set-log-level-xxxx= to change log level to specific level. 144 | Before adding log level feature, two commands, =lspce-enable-logging= and =lspce-disable-logging=, already exist, which enable/disable logging entirely. Now =lspce-enable-logging= is equivalent of setting log level to DEBUG, and =lspce-disable-logging= is equivalent of setting log level to DISABLED. 145 | 146 | ** About python virtual environment 147 | *** pylsp and jedi-language-server 148 | ATM, you can use virtual environments with both pylsp and jedi-language-server in lspce, all you need is a variable =lspce-jedi-environment=, which can be specified to point to the python interpreter, and a =.dir-locals.el= file. 149 | The following is a simple .dir-locals.el: 150 | #+BEGIN_SRC elisp 151 | ((python-mode 152 | . ((eval . (progn 153 | (setq-local lspce-jedi-environment "/home/XXXX/tmp/venv/.venv/bin/python"))))) 154 | (python-ts-mode 155 | . ((eval . (progn 156 | (setq-local lspce-jedi-environment "/home/XXXX/tmp/venv/.venv/bin/python"))))) 157 | ) 158 | 159 | #+END_SRC 160 | 161 | And you can see how =lspce-jedi-environment= is used in =lspce-jedi-initializationOptions= and =lspce-pylsp-initializationOptions=. 162 | *** pyright 163 | If you want to use pyright with lspce, =.dir-locals.el= can also help you. But I haven't tested it throughly. 164 | #+BEGIN_SRC elisp 165 | ((python-mode 166 | . ((eval . (progn 167 | (setq-local exec-path (append (list "/home/XXXX/tmp/venv/.venv/bin/") exec-path)) 168 | (setq-local lspce-inherit-exec-path t))))) 169 | (python-ts-mode 170 | . ((eval . (progn 171 | (setq-local exec-path (append (list "/home/XXXX/tmp/venv/.venv/bin/") exec-path)) 172 | (setq-local lspce-inherit-exec-path t)))))) 173 | #+END_SRC 174 | 175 | I personally do NOT recommend to use lspce with pyright though, and please do NOT create issues about it. Thanks. 176 | 177 | ** About environment variables 178 | Sometime, you may need to pass some environment variables to rust code so that lspce can use these environment variables to start lsp server processes. You can use =lspce-envs-pass-to-subprocess= then, which is a list of environment variables, and the values of these environment variables are retrieved from =process-environment=, except ~PATH~, which is from =exec-path=. 179 | 180 | The reason why this feature works in this way is I don't want lspce to be tightly bound with other tools, such as direnv, python's venv, and so on. So you should use someway to populate =process-environment= first if you want to use this feature. 181 | 182 | =lspce-envs-pass-to-subprocess= has made =lspce-inherit-exec-path= obsolete, even you can still use it. The logic is: all environment variables will be passed, and if =lspce-inherit-exec-path= is set true, PATH will be passed too. 183 | 184 | * Architecture 185 | [[file:images/Architecture_of_LSPCE.png]] 186 | 187 | Some notes about the architecture: 188 | 1. Every project is represented by a ~Project~ struct in LSPCE (aka the largest Box in the above image). 189 | 2. LSPCE sends requests/notifications to LSP server(rust-analyzer, pyright, etc.) processes via a ~Transport~. 190 | 3. Responses/notifications/requests issued by LSP servers are sent to ~Transport~ and then dispatched into three different queues by ~Message Dispatcher~. 191 | Note that diagnositcs are disptched into a separate queue, from where LSPCE reads them and shows them using flymake. 192 | 4. After sending a request, LSPCE will read the response from the response queue in an interruptable way, so it won't block Emacs. 193 | 194 | * Lspce vs Eglot/lsp-mode/lsp-bridge 195 | ** lspce vs eglot 196 | *** pros 197 | - lspce has less chance to block user input or freeze Emacs 198 | - lspce supports multiple servers in a single project 199 | For projects containing, for example python files and rust files, lspce can start a pylsp server and a rust-analyzer server respectively. 200 | IIRC, eglot does not support this. Corret me if I'm wrong. 201 | - lspce's code is easier to understand for elisp newbies like me. 202 | Lspce does not use cl-loop, pcase-xxx etc, which I think is not easy to understand. 203 | 204 | *** cons 205 | - lspce supports a smaller set of LSP features 206 | - lspce has only been tested with several lsp servers 207 | Eglot supports much more lsp servers than lspce 208 | - lower code quality 209 | I've heard several times that eglot has high code quality. 210 | - lspce does not support tramp 211 | 212 | ** lspce vs lsp-mode 213 | *** pros 214 | - lspce has less chance to block user input or freeze Emacs 215 | - lspce's code is easier to understand for elisp newbies like me. 216 | I tried to understand lsp-mode's code but I failed. I really think lsp-mode's code is hard to understand, but I'm absolutely not an elisp export at all. 217 | 218 | *** cons 219 | - lspce supports a much smaller set of LSP features 220 | - lspce has only been tested with several lsp servers 221 | lsp-mode supports much more lsp servers than lspce 222 | - lspce does not support running multiple servers in a single buffer 223 | - lspce does not support dap 224 | 225 | ** lspce vs lsp-bridge 226 | *** pros 227 | - lspce is compatible with xre/capf/imenu etc. 228 | 229 | *** cons 230 | - lspce support a smaller set of LSP features 231 | - In theory, lspce is slower than lsp-bridge 232 | - lspce does not support running multiple servers in a single buffer 233 | - lsp-bridge has built-in remote editing support 234 | - lsp-bridge provides other completing backends 235 | 236 | * License 237 | GPLv3 238 | 239 | * Acknowledgements 240 | Thanks to [[https://github.com/ubolonton/emacs-module-rs][emacs-module-rs]], which makes implementing LSPCE possible. 241 | 242 | Thanks to [[https://github.com/joaotavora/eglot][eglot]] and [[https://github.com/emacs-lsp/lsp-mode][lsp-mode]], I learned a lot about LSP from both of them during developing this package. 243 | 244 | Thanks to [[https://crates.io/crates/lsp-server][lsp-server]] from rust-analyzer, I used a lot of code from it (and modified them a little to make it suitable for a client). 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | 3 | mod connection; 4 | mod error; 5 | mod logger; 6 | mod msg; 7 | mod socket; 8 | mod stdio; 9 | 10 | use bytes::Buf; 11 | use bytes::BytesMut; 12 | use chrono::Local; 13 | use connection::Connection; 14 | use crossbeam_channel::SendError; 15 | use emacs::{defun, Env, IntoLisp, Result, Value}; 16 | use error::LspceError; 17 | use logger::Logger; 18 | use logger::LOG_DEBUG; 19 | use logger::LOG_DISABLED; 20 | use logger::LOG_FILE_NAME; 21 | use logger::LOG_LEVEL; 22 | 23 | use lsp_types::Diagnostic; 24 | use lsp_types::DidChangeTextDocumentParams; 25 | use lsp_types::InitializeParams; 26 | use lsp_types::InitializeResult; 27 | use lsp_types::InitializedParams; 28 | use lsp_types::PublishDiagnosticsParams; 29 | use msg::Message; 30 | use msg::Notification; 31 | use msg::Request; 32 | use msg::RequestId; 33 | use msg::Response; 34 | use serde::Deserialize; 35 | use serde::Serialize; 36 | use serde_json::json; 37 | use std::error::Error; 38 | use std::fmt::{self, Display, Formatter}; 39 | use std::fs::File; 40 | use std::io::Result as IoResult; 41 | use std::result::Result as RustResult; 42 | use std::str::Utf8Error; 43 | 44 | use std::sync::atomic::AtomicI32; 45 | use std::sync::atomic::AtomicU32; 46 | use std::sync::atomic::AtomicU8; 47 | use std::sync::atomic::Ordering; 48 | use std::time::Instant; 49 | use stdio::IoThreads; 50 | 51 | use std::{ 52 | collections::{HashMap, VecDeque}, 53 | fmt::{format, Debug}, 54 | io::{Read, Write}, 55 | mem::MaybeUninit, 56 | process::{Child, ChildStdin, ChildStdout, Command, Stdio}, 57 | sync::{Arc, Mutex, Once}, 58 | thread::{self, JoinHandle, Thread}, 59 | }; 60 | 61 | pub static MAX_DIAGNOSTICS_COUNT: AtomicI32 = AtomicI32::new(30); 62 | 63 | #[derive(Debug)] 64 | struct FileInfo { 65 | pub uri: String, // file name 66 | pub diagnostics: Vec, 67 | } 68 | 69 | impl FileInfo { 70 | pub fn new(uri: String) -> FileInfo { 71 | FileInfo { 72 | uri, 73 | diagnostics: Vec::new(), 74 | } 75 | } 76 | } 77 | 78 | #[derive(Serialize, Deserialize, Debug, Clone)] 79 | struct LspServerInfo { 80 | pub name: String, 81 | pub version: String, 82 | pub id: String, // server_id at the moment 83 | pub capabilities: String, 84 | } 85 | 86 | impl LspServerInfo { 87 | pub fn new() -> LspServerInfo { 88 | LspServerInfo { 89 | name: "".to_string(), 90 | version: "".to_string(), 91 | id: "".to_string(), 92 | capabilities: "".to_string(), 93 | } 94 | } 95 | } 96 | 97 | const SERVER_STATUS_NEW: u8 = 0; 98 | const SERVER_STATUS_STARTING: u8 = 1; 99 | const SERVER_STATUS_RUNNING: u8 = 2; 100 | const SERVER_STATUS_EXITING: u8 = 3; 101 | 102 | struct LspServerData { 103 | latest_request_id: RequestId, 104 | latest_request_tick: String, 105 | latest_response_id: RequestId, 106 | latest_response_tick: String, 107 | request_ticks: HashMap, 108 | file_infos: HashMap, 109 | requests: VecDeque, 110 | responses: VecDeque, 111 | notifications: VecDeque, 112 | } 113 | 114 | impl LspServerData { 115 | pub fn new() -> LspServerData { 116 | LspServerData { 117 | latest_request_id: RequestId::from(-1), 118 | latest_request_tick: String::new(), 119 | latest_response_id: RequestId::from(-1), 120 | latest_response_tick: String::new(), 121 | request_ticks: HashMap::new(), 122 | file_infos: HashMap::new(), 123 | requests: VecDeque::new(), 124 | responses: VecDeque::new(), 125 | notifications: VecDeque::new(), 126 | } 127 | } 128 | } 129 | 130 | /// Represents a Language Server Protocol (LSP) server instance. 131 | /// 132 | /// This struct manages the lifecycle of an LSP server process, including: 133 | /// - The child process handle 134 | /// - Server information (name, version, capabilities) 135 | /// - Connection state and transport threads 136 | /// - Server data and exit flag 137 | struct LspServer { 138 | pub child: Option, 139 | pub server_info: LspServerInfo, 140 | pub status: u8, 141 | transport: Arc>>, 142 | transport_threads: Option, 143 | dispatcher: Option>, 144 | server_data: Arc>, 145 | exit: Arc>, 146 | } 147 | 148 | impl LspServer { 149 | pub fn new( 150 | root_uri: String, 151 | cmd: String, 152 | cmd_args: String, 153 | initialize_req: String, 154 | emacs_envs: String, 155 | ) -> Option { 156 | let args = cmd_args.split_ascii_whitespace().collect::>(); 157 | 158 | Logger::info(&format!("emacs_envs: {}", &emacs_envs)); 159 | 160 | let mut child; 161 | if !emacs_envs.is_empty() { 162 | let envs = serde_json::from_str::>(&emacs_envs); 163 | match envs { 164 | Ok(envs) => { 165 | child = Command::new(cmd) 166 | .args(args) 167 | .stdin(Stdio::piped()) 168 | .stdout(Stdio::piped()) 169 | .stderr(Stdio::piped()) 170 | .envs(envs) 171 | .spawn(); 172 | } 173 | Err(e) => { 174 | Logger::error(&format!( 175 | "deserializing emacs_envs failed with error {:?}", e 176 | )); 177 | return None; 178 | } 179 | } 180 | } else { 181 | child = Command::new(cmd) 182 | .args(args) 183 | .stdin(Stdio::piped()) 184 | .stdout(Stdio::piped()) 185 | .stderr(Stdio::piped()) 186 | .spawn(); 187 | } 188 | 189 | if let Ok(mut c) = child { 190 | let mut stdin = c.stdin.take().unwrap(); 191 | let mut stdout = c.stdout.take().unwrap(); 192 | let mut stderr = c.stderr.take().unwrap(); 193 | 194 | let (mut transport, mut transport_threads) = Connection::stdio(stdin, stdout, stderr); 195 | 196 | let mut server_info = LspServerInfo::new(); 197 | server_info.id = c.id().to_string(); 198 | let mut server = LspServer { 199 | child: Some(c), 200 | server_info, 201 | status: SERVER_STATUS_STARTING, 202 | transport: Arc::new(Mutex::new(Some(transport))), 203 | transport_threads: Some(transport_threads), 204 | dispatcher: None, 205 | server_data: Arc::new(Mutex::new(LspServerData::new())), 206 | exit: Arc::new(Mutex::new(false)), 207 | }; 208 | server.dispatcher = Some(LspServer::start_dispatcher( 209 | Arc::clone(&server.transport), 210 | Arc::clone(&server.exit), 211 | Arc::clone(&server.server_data), 212 | )); 213 | 214 | Some(server) 215 | } else { 216 | Logger::error(&format!( 217 | "create child process failed with error {:?}", 218 | child.err().unwrap(), 219 | )); 220 | None 221 | } 222 | } 223 | 224 | fn start_dispatcher( 225 | transport: Arc>>, 226 | exit: Arc>, 227 | server_data: Arc>, 228 | ) -> thread::JoinHandle<()> { 229 | let handle = thread::spawn(move || loop { 230 | { 231 | let exit = exit.lock().unwrap(); 232 | if *exit { 233 | break; 234 | } 235 | } 236 | 237 | let mut message: Option = None; 238 | { 239 | let transport = transport.lock().unwrap(); 240 | message = transport.as_ref().unwrap().read(); 241 | } 242 | 243 | if let Some(m) = message { 244 | match m { 245 | Message::Request(r) => { 246 | if r.method.eq("workspace/configuration") { 247 | let mut server_data = server_data.lock().unwrap(); 248 | server_data.requests.push_back(r); 249 | } 250 | // save request into the queue FIXME 251 | // { 252 | // let mut requests = requests2.lock().unwrap(); 253 | // requests.push_back(r); 254 | // } 255 | } 256 | Message::Response(mut r) => { 257 | Logger::trace(&format!("Response {}", &r.content)); 258 | let id = r.id.clone(); 259 | 260 | let mut server_data = server_data.lock().unwrap(); 261 | let request_tick = server_data.request_ticks.get(&id); 262 | if (request_tick.is_some()) { 263 | let request_tick = request_tick.unwrap().clone(); 264 | Logger::debug(&format!( 265 | "Request tick for id {} is {}", 266 | &id, &request_tick 267 | )); 268 | if (request_tick.eq(&server_data.latest_request_tick)) { 269 | r.request_tick = request_tick.clone(); 270 | server_data.responses.push_back(r); 271 | } 272 | Logger::debug(&format!( 273 | "Latest response id is {}, current response id {}", 274 | &server_data.latest_response_id, &id 275 | )); 276 | if server_data.latest_response_id.lt(&id) { 277 | server_data.latest_response_id = id.clone(); 278 | server_data.latest_response_tick = request_tick.clone(); 279 | Logger::debug(&format!( 280 | "Change Latest response tick for id {} to {}", 281 | &server_data.latest_response_id, &request_tick 282 | )); 283 | } 284 | 285 | server_data.request_ticks.remove(&id); 286 | } else { 287 | Logger::trace(&format!("No request tick for id {}", id)); 288 | // if server_data.latest_response_id.lt(&id) { 289 | // server_data.latest_response_id = id.clone(); 290 | // } 291 | } 292 | } 293 | Message::Notification(r) => { 294 | // cacha diagnostics so they won't pour into Emacs 295 | if r.method.eq("textDocument/publishDiagnostics") { 296 | let mut params = 297 | serde_json::from_value::(r.params) 298 | .unwrap(); 299 | 300 | let uri = params.uri.as_str().to_string(); 301 | let mut file_info = FileInfo::new(uri.clone()); 302 | // cache no more than MAX_DIAGNOSTICS_COUNT diagnostics 303 | let max_diagnostic_count = 304 | MAX_DIAGNOSTICS_COUNT.load(Ordering::Relaxed); 305 | if max_diagnostic_count < 0 { 306 | file_info.diagnostics = params.diagnostics; 307 | } else if params.diagnostics.len() > max_diagnostic_count as usize { 308 | params.diagnostics.truncate(max_diagnostic_count as usize); 309 | file_info.diagnostics = params.diagnostics; 310 | } else { 311 | file_info.diagnostics = params.diagnostics; 312 | } 313 | 314 | let mut server_data = server_data.lock().unwrap(); 315 | server_data.file_infos.insert(uri.clone(), file_info); 316 | } else { 317 | // other notifications 318 | let mut server_data = server_data.lock().unwrap(); 319 | if server_data.notifications.len() > 10 { 320 | server_data.notifications.pop_front(); 321 | } 322 | server_data.notifications.push_back(r); 323 | } 324 | } 325 | } 326 | } else { 327 | thread::sleep(std::time::Duration::from_millis(1)); 328 | } 329 | }); 330 | 331 | handle 332 | } 333 | 334 | pub fn stop_dispatcher(&mut self) { 335 | let mut exit = self.exit.lock().unwrap(); 336 | *exit = true; 337 | } 338 | 339 | pub fn kill_child(&mut self) { 340 | if self.child.is_some() { 341 | self.child.take().unwrap().kill(); 342 | self.child = None; 343 | } 344 | } 345 | 346 | pub fn update_request_info(&self, id: RequestId, tick: String) { 347 | let mut server_data = self.server_data.lock().unwrap(); 348 | if server_data.latest_request_id < id { 349 | server_data.latest_request_id = id.clone(); 350 | } 351 | server_data.latest_request_tick = tick.clone(); 352 | server_data.request_ticks.insert(id, tick); 353 | } 354 | 355 | pub fn get_latest_response_id(&self) -> RequestId { 356 | let server_data = self.server_data.lock().unwrap(); 357 | server_data.latest_response_id.clone() 358 | } 359 | 360 | pub fn get_latest_response_tick(&self) -> String { 361 | let server_data = self.server_data.lock().unwrap(); 362 | server_data.latest_response_tick.clone() 363 | } 364 | 365 | pub fn exit_transport(&self) { 366 | let transport = self.transport.lock().unwrap(); 367 | if transport.is_some() { 368 | transport.as_ref().unwrap().to_exit(); 369 | } 370 | } 371 | 372 | pub fn write(&self, request: Message) -> RustResult<(), LspceError> { 373 | let transport = self.transport.lock().unwrap(); 374 | if transport.is_some() { 375 | let result = transport.as_ref().unwrap().write(request); 376 | match result { 377 | Ok(_) => Ok(()), 378 | Err(e) => Err(LspceError(e.to_string())), 379 | } 380 | } else { 381 | Err(LspceError("transport is not established.".to_string())) 382 | } 383 | } 384 | 385 | pub fn read_response(&self) -> Option { 386 | let mut server_data = self.server_data.lock().unwrap(); 387 | server_data.responses.pop_front() 388 | } 389 | 390 | // 391 | pub fn read_response_exact(&self, id: RequestId, method: String) -> Option { 392 | let mut result: Option = None; 393 | let mut server_data = self.server_data.lock().unwrap(); 394 | 395 | let latest_request_tick = server_data.latest_request_tick.clone(); 396 | let mut reserved: VecDeque = VecDeque::new(); 397 | for iter in server_data.responses.iter() { 398 | Logger::debug(&format!("read_response_exact response {:#?}", &iter)); 399 | if iter.id.eq(&id) { 400 | result = Some(iter.clone()); 401 | } 402 | 403 | let request_tick = iter.request_tick.clone(); 404 | if request_tick.eq(&latest_request_tick) && iter.id.ne(&id) { 405 | reserved.push_back(iter.clone()); 406 | } 407 | } 408 | 409 | server_data.responses.clear(); 410 | server_data.responses.append(&mut reserved); 411 | 412 | if result.is_none() { 413 | Logger::trace(&format!( 414 | "read_response_exact get null for request_id {}, method {}", 415 | id, method 416 | )); 417 | } 418 | 419 | result 420 | } 421 | 422 | pub fn read_notification(&self) -> Option { 423 | let mut server_data = self.server_data.lock().unwrap(); 424 | server_data.notifications.pop_front() 425 | } 426 | 427 | pub fn read_request(&self) -> Option { 428 | let mut server_data = self.server_data.lock().unwrap(); 429 | server_data.requests.pop_front() 430 | } 431 | 432 | pub fn clear_diagnostics(&self, uri: &str) { 433 | let mut server_data = self.server_data.lock().unwrap(); 434 | 435 | if let Some(mut file_info) = server_data.file_infos.get_mut(uri) { 436 | let result = serde_json::to_string(&file_info.diagnostics); 437 | file_info.diagnostics = Vec::new(); 438 | } 439 | } 440 | } 441 | 442 | struct Project { 443 | pub root_uri: String, // 444 | pub servers: HashMap, // map each language_id to a lsp server 445 | } 446 | 447 | impl Project { 448 | pub fn new(root_uri: String) -> Project { 449 | Project { 450 | root_uri, 451 | servers: HashMap::new(), 452 | } 453 | } 454 | } 455 | 456 | // Emacs won't load the module without this. 457 | emacs::plugin_is_GPL_compatible!(); 458 | 459 | // Register the initialization hook that Emacs will call when it loads the module. 460 | #[emacs::module(name("lspce-module"))] 461 | fn init(env: &Env) -> Result> { 462 | env.message("Done loading!") 463 | } 464 | 465 | #[defun] 466 | fn change_max_diagnostics_count(env: &Env, count: i32) -> Result> { 467 | MAX_DIAGNOSTICS_COUNT.store(count, Ordering::Relaxed); 468 | 469 | env.message(format!("max diagnostics changed to {}!", count)) 470 | } 471 | 472 | #[defun] 473 | fn read_max_diagnostics_count(env: &Env) -> Result { 474 | let count = MAX_DIAGNOSTICS_COUNT.load(Ordering::Relaxed); 475 | 476 | Ok(count) 477 | } 478 | 479 | /// disable logging to /tmp/lspce.log 480 | #[defun] 481 | fn disable_logging(env: &Env) -> Result> { 482 | LOG_LEVEL.store(LOG_DISABLED, Ordering::Relaxed); 483 | 484 | env.message("Logging is disabled!") 485 | } 486 | 487 | /// enable logging to /tmp/lspce.log 488 | #[defun] 489 | fn enable_logging(env: &Env) -> Result> { 490 | LOG_LEVEL.store(LOG_DEBUG, Ordering::Relaxed); 491 | 492 | env.message("Logging is enabled!") 493 | } 494 | 495 | #[defun] 496 | fn set_log_level(env: &Env, level: u8) -> Result> { 497 | LOG_LEVEL.store(level, Ordering::Relaxed); 498 | 499 | env.message(format!("log level set to {}!", level)) 500 | } 501 | 502 | #[defun] 503 | fn get_log_level(env: &Env) -> Result { 504 | let log_level = LOG_LEVEL.load(Ordering::Relaxed); 505 | 506 | return Ok(log_level); 507 | } 508 | 509 | /// set logging file name 510 | #[defun] 511 | fn set_log_file(env: &Env, file: String) -> Result> { 512 | *LOG_FILE_NAME.lock().unwrap() = file.clone(); 513 | 514 | env.message(format!("Set logging file to {}", file)) 515 | } 516 | 517 | fn projects() -> &'static Arc>> { 518 | static mut PROJECTS: MaybeUninit>>> = MaybeUninit::uninit(); 519 | static ONCE: Once = Once::new(); 520 | 521 | ONCE.call_once(|| unsafe { 522 | PROJECTS 523 | .as_mut_ptr() 524 | .write(Arc::new(Mutex::new(HashMap::new()))) 525 | }); 526 | 527 | unsafe { &*PROJECTS.as_mut_ptr() } 528 | } 529 | 530 | /// Connect to an existing server or create a server subprocess and then connect to it. 531 | #[defun] 532 | fn connect( 533 | env: &Env, 534 | root_uri: String, 535 | lsp_type: String, 536 | cmd: String, 537 | cmd_args: String, 538 | initialize_req: String, 539 | timeout: i32, 540 | emacs_envs: String, 541 | ) -> Result> { 542 | Logger::info(&format!( 543 | "start initializing server for lsp_type {} in project {}", 544 | lsp_type, root_uri 545 | )); 546 | 547 | let mut projects = projects().lock().unwrap(); 548 | 549 | if let Some(p) = projects.get(&root_uri) { 550 | if let Some(s) = p.servers.get(&lsp_type) { 551 | Logger::info(&format!( 552 | "server created already for lsp_type {} in project {}", 553 | lsp_type, root_uri 554 | )); 555 | 556 | return Ok(Some(serde_json::to_string(&s.server_info).unwrap())); 557 | } 558 | } 559 | 560 | let mut server = LspServer::new( 561 | root_uri.clone(), 562 | cmd.clone(), 563 | cmd_args.clone(), 564 | initialize_req.clone(), 565 | emacs_envs.clone(), 566 | ); 567 | if let Some(mut s) = server { 568 | let server_info: LspServerInfo; 569 | 570 | let mut project = projects.get_mut(&root_uri); 571 | if let Some(p) = project.as_mut() { 572 | if initialize(env, root_uri.clone(), &mut s, initialize_req, timeout) { 573 | server_info = s.server_info.clone(); 574 | p.servers.insert(lsp_type, s); 575 | } else { 576 | s.kill_child(); 577 | return Ok(None); 578 | } 579 | } else { 580 | let mut proj = Project::new(root_uri.clone()); 581 | if initialize(env, root_uri.clone(), &mut s, initialize_req, timeout) { 582 | server_info = s.server_info.clone(); 583 | proj.servers.insert(lsp_type, s); 584 | 585 | projects.insert(root_uri.clone(), proj); 586 | } else { 587 | s.kill_child(); 588 | return Ok(None); 589 | } 590 | } 591 | 592 | Logger::info(&format!( 593 | "Connected to server successfully. server capabilities {}", 594 | &server_info.capabilities 595 | )); 596 | Ok(Some(serde_json::to_string(&server_info).unwrap())) 597 | } else { 598 | Logger::error(&format!( 599 | "Failed to connect to server {}, {} for project {} {}.", 600 | cmd.clone(), 601 | cmd_args.clone(), 602 | root_uri.clone(), 603 | lsp_type.clone() 604 | )); 605 | Ok(None) 606 | } 607 | } 608 | 609 | fn initialize( 610 | env: &Env, 611 | root_uri: String, 612 | server: &mut LspServer, 613 | req_str: String, 614 | timeout: i32, 615 | ) -> bool { 616 | Logger::debug(&format!("raw initialize request {:#?}", req_str)); 617 | 618 | let msg = serde_json::from_str::(&req_str); 619 | if msg.is_err() { 620 | Logger::error(&format!("request is not valid json {}", &req_str)); 621 | return false; 622 | } 623 | 624 | let msg = msg.unwrap(); 625 | let id = msg.id.clone(); 626 | 627 | Logger::info(&format!("initialize request {}", serde_json::to_string_pretty(&msg).unwrap())); 628 | 629 | if !_request_async(server, msg) { 630 | return false; 631 | } 632 | 633 | let start_time = Instant::now(); 634 | loop { 635 | let response = server.read_response(); 636 | match response { 637 | Some(m) => { 638 | if m.error.is_some() { 639 | Logger::error(&format!("Lsp error {:?}", m.error)); 640 | return false; 641 | } 642 | Logger::info(&format!("initialize response {}", serde_json::to_string_pretty(&m).unwrap())); 643 | 644 | if let Ok(ir) = serde_json::from_value::(m.result.unwrap()) { 645 | let initialized = Notification::new( 646 | "initialized".to_string(), 647 | serde_json::to_value(InitializedParams {}).unwrap(), 648 | ); 649 | 650 | _notify(server, initialized); 651 | 652 | server.status = SERVER_STATUS_RUNNING; 653 | 654 | if let Some(si) = ir.server_info { 655 | server.server_info.name = si.name.clone(); 656 | server.server_info.version = si.version.expect(""); 657 | } 658 | server.server_info.capabilities = 659 | serde_json::to_string(&ir.capabilities).unwrap(); 660 | 661 | return true; 662 | } else { 663 | return false; 664 | } 665 | } 666 | None => { 667 | thread::sleep(std::time::Duration::from_millis(10)); 668 | } 669 | } 670 | if timeout > 0 671 | && Instant::now().duration_since(start_time).as_millis() > timeout as u128 * 1000 672 | { 673 | Logger::error("timeout when initializing server."); 674 | 675 | return false; 676 | } 677 | } 678 | } 679 | 680 | #[defun] 681 | fn shutdown(env: &Env, root_uri: String, file_type: String, req: String) -> Result> { 682 | let mut projects = projects().lock().unwrap(); 683 | if let Some(mut p) = projects.get_mut(&root_uri) { 684 | if let Some(mut server) = p.servers.remove(&file_type) { 685 | // shut down in a seperate thread so as not to block Emacs 686 | thread::spawn(move || { 687 | let server_name = server.server_info.name.clone(); 688 | let server_id = server.server_info.id.clone(); 689 | Logger::info(&format!( 690 | "start to shut down server {}, server_id {}", 691 | &server_name, &server_id 692 | )); 693 | 694 | let msg = serde_json::from_str::(&req); 695 | if msg.is_err() { 696 | Logger::error(&format!("request is not valid json {}", &req)); 697 | return; 698 | } 699 | 700 | let msg = msg.unwrap(); 701 | let id = msg.id.clone(); 702 | 703 | if !_request_async(&mut server, msg) { 704 | return; 705 | } 706 | 707 | let start_time = Instant::now(); 708 | loop { 709 | let response = server.read_response(); 710 | match response { 711 | Some(r) => { 712 | let r_id = r.id.clone(); 713 | if r_id.eq(&id) { 714 | let exit = Notification::new("exit".to_string(), json!({})); 715 | 716 | _notify(&mut server, exit); 717 | 718 | server.stop_dispatcher(); 719 | server.exit_transport(); 720 | Logger::info(&format!( 721 | "after exit transport for server {}, server_id {}.", 722 | &server_name, &server_id 723 | )); 724 | // waiting for transport_threads to exit 725 | server.transport_threads.take().unwrap().join(); 726 | Logger::info(&format!( 727 | "after thread join for server {}, server_id {}.", 728 | &server_name, &server_id 729 | )); 730 | // waiting for child to exit 731 | server.child.take().unwrap().wait(); 732 | Logger::info(&format!( 733 | "after child wait for server {}, server_id {}.", 734 | &server_name, &server_id 735 | )); 736 | 737 | return; 738 | } 739 | } 740 | None => { 741 | thread::sleep(std::time::Duration::from_millis(10)); 742 | } 743 | } 744 | 745 | if Instant::now().duration_since(start_time).as_millis() > 3 * 1000 { 746 | server.stop_dispatcher(); 747 | server.exit_transport(); 748 | server.kill_child(); 749 | 750 | return; 751 | } 752 | } 753 | }); 754 | } else { 755 | env.message(&format!("No server for {}", &file_type)); 756 | 757 | return Ok(None); 758 | } 759 | } else { 760 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 761 | 762 | return Ok(None); 763 | } 764 | 765 | Ok(None) 766 | } 767 | 768 | #[defun] 769 | fn server(env: &Env, root_uri: String, file_type: String) -> Result> { 770 | let projects = projects().lock().unwrap(); 771 | 772 | if let Some(p) = projects.get(&root_uri) { 773 | if let Some(s) = p.servers.get(&file_type) { 774 | return Ok(Some(serde_json::to_string(&s.server_info).unwrap())); 775 | } 776 | } 777 | 778 | Ok(None) 779 | } 780 | 781 | fn _request_async(server: &mut LspServer, req: Request) -> bool { 782 | let method = req.method.clone(); 783 | let id = req.id.clone(); 784 | let request_tick = req.request_tick.clone().unwrap(); 785 | 786 | server.update_request_info(id.clone(), request_tick); 787 | 788 | if method == "textDocument/didChange" || method == "textDocument/didClose" { 789 | let param = serde_json::from_value::(req.params.clone()); 790 | if let Ok(param) = param { 791 | server.clear_diagnostics(param.text_document.uri.as_ref()); 792 | } 793 | } 794 | 795 | let write_result = server.write(Message::Request(req)); 796 | match write_result { 797 | Ok(_) => true, 798 | Err(e) => { 799 | Logger::error(&format!("request error {:#?}", e)); 800 | 801 | false 802 | } 803 | } 804 | } 805 | 806 | #[defun] 807 | fn request_async( 808 | env: &Env, 809 | root_uri: String, 810 | file_type: String, 811 | req: String, 812 | ) -> Result> { 813 | let mut projects = projects().lock().unwrap(); 814 | if let Some(mut p) = projects.get_mut(&root_uri) { 815 | if let Some(mut server) = p.servers.get_mut(&file_type) { 816 | if server.status != SERVER_STATUS_RUNNING { 817 | return Ok(None); 818 | } 819 | Logger::trace(&format!("request {}", &req)); 820 | 821 | let msg = serde_json::from_str::(&req); 822 | if msg.is_err() { 823 | Logger::error(&format!("request is not valid json {}", &req)); 824 | return Ok(None); 825 | } 826 | let msg = msg.unwrap(); 827 | 828 | if msg.request_tick.is_none() { 829 | Logger::error(&format!("no request_tick is req {}", &req)); 830 | return Ok(None); 831 | } 832 | 833 | if _request_async(server, msg) { 834 | Ok(Some(true)) 835 | } else { 836 | Ok(None) 837 | } 838 | } else { 839 | env.message(&format!("No server for {}", &file_type)); 840 | 841 | Ok(None) 842 | } 843 | } else { 844 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 845 | 846 | Ok(None) 847 | } 848 | } 849 | 850 | fn _notify(server: &mut LspServer, req: Notification) -> Result> { 851 | let write_result = server.write(Message::Notification(req)); 852 | 853 | match write_result { 854 | Ok(_) => { 855 | return Ok(Some(true)); 856 | } 857 | Err(e) => { 858 | Logger::error(&format!("notify error {:#?}", e)); 859 | return Ok(None); 860 | } 861 | } 862 | 863 | Ok(None) 864 | } 865 | 866 | #[defun] 867 | fn notify(env: &Env, root_uri: String, file_type: String, req: String) -> Result> { 868 | let mut projects = projects().lock().unwrap(); 869 | if let Some(mut p) = projects.get_mut(&root_uri) { 870 | if let Some(mut server) = p.servers.get_mut(&file_type) { 871 | if server.status != SERVER_STATUS_RUNNING { 872 | env.message("Server is not ready."); 873 | return Ok(None); 874 | } 875 | Logger::trace(&format!("notify {}", &req)); 876 | 877 | let json_object = serde_json::from_str::(&req); 878 | match json_object { 879 | Ok(notification) => { 880 | return _notify(server, notification); 881 | } 882 | Err(e) => { 883 | env.message(&format!("Invalid json string {}", &req)); 884 | } 885 | } 886 | } else { 887 | env.message(&format!("No server for {}", &file_type)); 888 | } 889 | } else { 890 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 891 | } 892 | 893 | Ok(None) 894 | } 895 | 896 | /// precondition: have called read_latest_response_id and gotten the id. 897 | #[defun] 898 | fn read_response_exact( 899 | env: &Env, 900 | root_uri: String, 901 | file_type: String, 902 | id: String, 903 | method: String, 904 | ) -> Result> { 905 | let req_id = RequestId::from(id); 906 | 907 | let projects = projects().lock().unwrap(); 908 | if let Some(p) = projects.get(&root_uri) { 909 | if let Some(server) = p.servers.get(&file_type) { 910 | let response = server.read_response_exact(req_id, method); 911 | match response { 912 | Some(r) => { 913 | return Ok(Some(r.content)); 914 | } 915 | None => { 916 | return Ok(None); 917 | } 918 | } 919 | } else { 920 | env.message(&format!("No server for {}", &file_type)); 921 | } 922 | } else { 923 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 924 | } 925 | 926 | Ok(None) 927 | } 928 | 929 | #[defun] 930 | fn read_notification(env: &Env, root_uri: String, file_type: String) -> Result> { 931 | let projects = projects().lock().unwrap(); 932 | if let Some(p) = projects.get(&root_uri) { 933 | if let Some(server) = p.servers.get(&file_type) { 934 | let notification = server.read_notification(); 935 | match notification { 936 | Some(r) => { 937 | return Ok(Some(r.content)); 938 | } 939 | None => { 940 | return Ok(None); 941 | } 942 | } 943 | } else { 944 | env.message(&format!("No server for {}", &file_type)); 945 | } 946 | } else { 947 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 948 | } 949 | 950 | Ok(None) 951 | } 952 | 953 | #[defun] 954 | fn read_file_diagnostics( 955 | env: &Env, 956 | root_uri: String, 957 | file_type: String, 958 | uri: String, 959 | ) -> Result> { 960 | let projects = projects().lock().unwrap(); 961 | if let Some(p) = projects.get(&root_uri) { 962 | if let Some(server) = p.servers.get(&file_type) { 963 | let mut server_data = server.server_data.lock().unwrap(); 964 | if let Some(file_info) = server_data.file_infos.get_mut(&uri) { 965 | let result = serde_json::to_string(&file_info.diagnostics); 966 | 967 | if let Ok(result) = result { 968 | return Ok(Some(result)); 969 | } 970 | } 971 | } else { 972 | env.message(&format!("No server for {}", &file_type)); 973 | } 974 | } else { 975 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 976 | } 977 | 978 | Ok(None) 979 | } 980 | 981 | #[defun] 982 | fn read_latest_response_id( 983 | env: &Env, 984 | root_uri: String, 985 | file_type: String, 986 | ) -> Result> { 987 | let projects = projects().lock().unwrap(); 988 | if let Some(p) = projects.get(&root_uri) { 989 | if let Some(server) = p.servers.get(&file_type) { 990 | let lrid = server.get_latest_response_id(); 991 | 992 | return Ok(Some(lrid.to_string())); 993 | } else { 994 | env.message(&format!("No server for {}", &file_type)); 995 | } 996 | } else { 997 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 998 | } 999 | 1000 | Ok(None) 1001 | } 1002 | 1003 | #[defun] 1004 | fn read_latest_response_tick( 1005 | env: &Env, 1006 | root_uri: String, 1007 | file_type: String, 1008 | ) -> Result> { 1009 | let projects = projects().lock().unwrap(); 1010 | if let Some(p) = projects.get(&root_uri) { 1011 | if let Some(server) = p.servers.get(&file_type) { 1012 | let tick = server.get_latest_response_tick(); 1013 | 1014 | return Ok(Some(tick)); 1015 | } else { 1016 | env.message(&format!("No server for {}", &file_type)); 1017 | } 1018 | } else { 1019 | env.message(&format!("No project for {} {}", &root_uri, &file_type)); 1020 | } 1021 | 1022 | Ok(None) 1023 | } 1024 | -------------------------------------------------------------------------------- /lspce-core.el: -------------------------------------------------------------------------------- 1 | ;;; lspce.el --- LSP Client for Emacs -*- lexical-binding: t; -*- 2 | 3 | 4 | ;;; Require 5 | (require 'json) 6 | (eval-when-compile 7 | (require 'cl-lib)) 8 | (require 'project) 9 | (require 'url-util) 10 | (require 'compile) ; for some faces 11 | (require 'warnings) 12 | (require 'markdown-mode) 13 | (require 'yasnippet) 14 | (require 'flymake) 15 | 16 | (require 'lspce-module) 17 | (eval-and-compile 18 | (require 'lspce-util)) 19 | (require 'lspce-snippet) 20 | 21 | 22 | ;;; User tweakable stuff 23 | (defgroup lspce nil 24 | "Interaction with Language Server Protocol servers" 25 | :prefix "lspce-" 26 | :group 'applications) 27 | 28 | (defcustom lspce-connect-server-timeout 60 29 | "The timeout of connecting to lsp server, in seconds." 30 | :group 'lspce 31 | :type 'integer) 32 | 33 | (defcustom lspce-modes-enable-single-file-root '(python-mode python-ts-mode) 34 | "Major modes where lspce enables even for a single file (IOW no project)." 35 | :group 'lspce 36 | :type 'list) 37 | 38 | (defcustom lspce-inherit-exec-path nil 39 | "If non-nil, pass `exec-path' as PATH to rust code to 40 | create the lsp server subprocesses." 41 | :group 'lspce 42 | :type 'boolean) 43 | 44 | ;;; Constants 45 | ;;; 46 | (defconst lspce--symbol-kind-names 47 | `((1 . "File") (2 . "Module") 48 | (3 . "Namespace") (4 . "Package") (5 . "Class") 49 | (6 . "Method") (7 . "Property") (8 . "Field") 50 | (9 . "Constructor") (10 . "Enum") (11 . "Interface") 51 | (12 . "Function") (13 . "Variable") (14 . "Constant") 52 | (15 . "String") (16 . "Number") (17 . "Boolean") 53 | (18 . "Array") (19 . "Object") (20 . "Key") 54 | (21 . "Null") (22 . "EnumMember") (23 . "Struct") 55 | (24 . "Event") (25 . "Operator") (26 . "TypeParameter"))) 56 | 57 | (defconst lspce--kind-names 58 | `((1 . "Text") (2 . "Method") (3 . "Function") (4 . "Constructor") 59 | (5 . "Field") (6 . "Variable") (7 . "Class") (8 . "Interface") 60 | (9 . "Module") (10 . "Property") (11 . "Unit") (12 . "Value") 61 | (13 . "Enum") (14 . "Keyword") (15 . "Snippet") (16 . "Color") 62 | (17 . "File") (18 . "Reference") (19 . "Folder") (20 . "EnumMember") 63 | (21 . "Constant") (22 . "Struct") (23 . "Event") (24 . "Operator") 64 | (25 . "TypeParameter"))) 65 | 66 | 67 | ;;; Variables and custom 68 | (defvar lspce-envs-pass-to-subprocess '() 69 | "Environment variables that should be passed to rust to start lsp server 70 | subprocesses. Should be a list of string, e.g. '(\"PATH\")") 71 | 72 | (defvar lspce-current-column-function #'lspce-current-column 73 | "Function to calculate the current column. 74 | 75 | This is the inverse operation of 76 | `lspce-move-to-column-function' (which see). It is a function of 77 | no arguments returning a column number. For buffers managed by 78 | fully LSP-compliant servers, this should be set to 79 | `lspce-lsp-abiding-column', and `lspce-current-column' (the default) 80 | for all others.") 81 | 82 | (defvar lspce-move-to-column-function #'lspce-move-to-column 83 | "Function to move to a column reported by the LSP server. 84 | 85 | According to the standard, LSP column/character offsets are based 86 | on a count of UTF-16 code units, not actual visual columns. So 87 | when LSP says position 3 of a line containing just \"aXbc\", 88 | where X is a multi-byte character, it actually means `b', not 89 | `c'. However, many servers don't follow the spec this closely. 90 | 91 | For buffers managed by fully LSP-compliant servers, this should 92 | be set to `lspce-move-to-lsp-abiding-column', and 93 | `lspce-move-to-column' (the default) for all others.") 94 | 95 | (defvar lspce--lsp-type-map (make-hash-table :test #'equal) 96 | "Use file name extension to determine lsp type.") 97 | 98 | (defun lspce--lsp-type-default () 99 | "The return value is also used as language-id." 100 | (let ((suffix "") 101 | (mm (symbol-name major-mode)) 102 | lsp-type) 103 | (when buffer-file-name 104 | (setq suffix (file-name-extension buffer-file-name))) 105 | (setq lsp-type (gethash suffix lspce--lsp-type-map)) 106 | (unless lsp-type 107 | (setq lsp-type 108 | (cond 109 | ((member suffix '("js")) 110 | "javascript") 111 | ((member suffix '("ts")) 112 | "typescript") 113 | ((member suffix '("tsx")) 114 | "typescriptreact") 115 | ((member suffix '("c" "c++" "cpp" "h" "hpp" "cxx" "cc")) 116 | "C") 117 | ((member mm '("go-mode" "go-ts-mode")) 118 | "go") 119 | ((string-suffix-p "-ts-mode" mm) 120 | (string-remove-suffix "-ts-mode" mm)) 121 | (t 122 | (string-remove-suffix "-mode" (symbol-name major-mode)))))) 123 | lsp-type)) 124 | 125 | (defalias 'lspce--buffer-language-id 126 | 'lspce--lsp-type-default "lspce--buffer-language-id") 127 | 128 | (defvar lspce-lsp-type-function #'lspce--lsp-type-default 129 | "Function to figure out the lsp type of current buffer.") 130 | 131 | ;;; Lsp types 132 | 133 | (cl-defstruct lspce-documentChange 134 | (kind) ;; change, documentChange, create, rename or delete 135 | (change) ;; 136 | ) 137 | 138 | (cl-defstruct lspce-completionCache 139 | (prefix-start) 140 | (candidates) 141 | (lsp-items) 142 | (markers) 143 | (prefix)) 144 | 145 | (defun lspce--make-request (method &optional params request-tick) 146 | "jsonrpc is added in the module." 147 | (let ((request (make-hash-table))) 148 | (puthash :id (lspce--next-jsonrpc-id) request) 149 | (puthash :method method request) 150 | (puthash :request_tick request-tick request) 151 | (when params 152 | (puthash :params params request)) 153 | request)) 154 | 155 | (defun lspce--make-notification (method &optional params) 156 | "jsonrpc is added in the module." 157 | (let ((notification (make-hash-table))) 158 | (puthash :method method notification) 159 | (when params 160 | (puthash :params params notification)) 161 | notification)) 162 | 163 | (defun lspce--documentationFormat () 164 | (let (format) 165 | (setq format (vector "plaintext")) 166 | (when (fboundp 'markdown-mode) 167 | (setq format (vector "markdown" "plaintext"))) 168 | format)) 169 | 170 | (defun lspce--clientInfo () 171 | (let ((params (make-hash-table))) 172 | (puthash :name LSPCE-NAME params) 173 | (puthash :version LSPCE-VERSION params) 174 | params)) 175 | 176 | (defun lspce--clientCapabilities () 177 | (list 178 | :workspace (list 179 | :applyEdit :json-false 180 | :executeCommand (list 181 | :dynamicRegistration :json-false) 182 | :workspaceEdit (list 183 | :documentChanges t 184 | :resourceOperations (vector "create" "rename" "delete")) 185 | :symbol (list 186 | :dynamicRegistration :json-false) 187 | :configuration :json-false 188 | :workspaceFolders :json-false) 189 | :textDocument (list 190 | :synchronization (list 191 | :dynamicRegistration :json-false 192 | :willSave t 193 | :didSave t) 194 | :completion (list 195 | :dynamicRegistration :json-false 196 | :completionItem (list 197 | :snippetSupport (if (lspce--snippet-expansion-fn) 198 | t 199 | :json-false) 200 | :commitCharactersSupport :json-false 201 | :documentationFormat (if (fboundp 'gfm-view-mode) 202 | ["markdown" "plaintext"] 203 | ["plaintext"]) 204 | :deprecatedSupport t 205 | :tagSupport (list :valueSet [1]) 206 | :preselectSupoort :json-false 207 | :insertReplaceSupport :json-false 208 | :resolveSupport (list :properties (vector "documentation" "details" "additionalTextEdits")) 209 | ) 210 | :contextSupport t) 211 | :hover (list 212 | :dynamicRegistration :json-false 213 | :contentFormat (if (fboundp 'gfm-view-mode) 214 | ["markdown" "plaintext"] 215 | ["plaintext"])) 216 | :signatureHelp (list :dynamicRegistration :json-false 217 | :signatureInformation (list 218 | :documentationFormat (if (fboundp 'gfm-view-mode) 219 | ["markdown" "plaintext"] 220 | ["plaintext"]) 221 | :parameterInformation (list 222 | :labelOffsetSupport :json-false) 223 | :activeParameterSupport :json-false) 224 | :contextSupport :json-false) 225 | :references (list 226 | :dynamicRegistration :json-false) 227 | :definition (list 228 | :dynamicRegistration :json-false 229 | :linkSupport :json-false) 230 | :declaration (list 231 | :dynamicRegistration :json-false 232 | :linkSupport :json-false) 233 | :implementation (list 234 | :dynamicRegistration :json-false 235 | :linkSupport :json-false) 236 | :typeDefinition (list 237 | :dynamicRegistration :json-false 238 | :linkSupport :json-false) 239 | :documentHighlight (list 240 | :dynamicRegistration :json-false) 241 | :documentSymbol (list 242 | :dynamicRegistration :json-false 243 | :hierarchicalDocumentSymbolSupport t 244 | :symbolKind `(:valueSet 245 | [,@(mapcar 246 | #'car lspce--symbol-kind-names)])) 247 | :codeAction (list 248 | :dynamicRegistration :json-false 249 | :codeActionLiteralSupport (list 250 | :codeActionKind (list :valueSet 251 | ["quickfix" 252 | "refactor" "refactor.extract" 253 | "refactor.inline" "refactor.rewrite" 254 | "source" "source.organizeImports"])) 255 | :isPreferredSupport t 256 | :disabledSupport :json-false 257 | :dataSupport :json-false) 258 | :formatting (list 259 | :dynamicRegistration :json-false) 260 | :rangeFormatting (list 261 | :dynamicRegistration :json-false) 262 | :rename (list 263 | :dynamicRegistration :json-false 264 | :prepareSupport :json-false 265 | :honorsChangeAnnotations :json-false) 266 | :inlayHint (list 267 | :dynamicRegistration :json-false) 268 | :publishDiagnostics (list 269 | :relatedInformation :json-false 270 | :codeDescriptionSupport :json-false 271 | :codeDescriptionSupport :json-false 272 | :dataSupport :json-false 273 | :versionSupport :json-false 274 | :tagSupport (list :valueSet [1 2])) 275 | :callHierarchy (list 276 | :dynamicRegistration :json-false)) 277 | :experimental lspce--{}) 278 | ) 279 | 280 | (defun lspce--initializeParams (rootUri &optional initializationOptions trace workspaceFolders) 281 | "初始化参数" 282 | (let ((params (make-hash-table))) 283 | (puthash :processId (emacs-pid) params) 284 | ;; some lsp servers don't support rootUri well 285 | (puthash :rootPath rootUri params) 286 | (puthash :rootUri rootUri params) 287 | (puthash :capabilities (lspce--clientCapabilities) params) 288 | (when initializationOptions 289 | (puthash :initializationOptions initializationOptions params)) 290 | (puthash :clientInfo (lspce--clientInfo) params) 291 | (when trace 292 | (puthash :trace trace params)) 293 | (when workspaceFolders 294 | (puthash :workspaceFolders workspaceFolders params)) 295 | 296 | params)) 297 | 298 | (defun lspce--textDocumentItem (uri languageId version text) 299 | (let ((params (make-hash-table))) 300 | (puthash :uri uri params) 301 | (puthash :languageId languageId params) 302 | (puthash :version version params) 303 | (puthash :text text params) 304 | params)) 305 | 306 | (defun lspce--versionedTextDocumentIdenfitier (uri version) 307 | (let ((params (make-hash-table))) 308 | (puthash :uri uri params) 309 | (puthash :version version params) 310 | params)) 311 | 312 | 313 | (defun lspce--didOpenTextDocumentParams (textDocument) 314 | "For didOpen, textDocument is a TextDocumentItem, but for didClose, it's TextDocumentIdentifier." 315 | (let ((params (make-hash-table))) 316 | (puthash :textDocument textDocument params) 317 | params)) 318 | (defalias 'lspce--didCloseTextDocumentParams 'lspce--didOpenTextDocumentParams "lspce--didCloseTextDocumentParams") 319 | 320 | (defun lspce--textDocumentContentChangeEvent (range rangeLength text) 321 | (let ((params (make-hash-table))) 322 | (puthash :range range params) 323 | (puthash :rangeLength rangeLength params) 324 | (puthash :text text params) 325 | params)) 326 | 327 | (defun lspce--didChangeTextDocumentParams (textDocument contentChanges) 328 | "textDocument is a VersionedTextDocumentIdentifier." 329 | (let ((params (make-hash-table))) 330 | (puthash :textDocument textDocument params) 331 | (puthash :contentChanges contentChanges params) 332 | params)) 333 | 334 | (defun lspce--position (line character) 335 | (let ((params (make-hash-table))) 336 | (puthash :line line params) 337 | (puthash :character character params) 338 | params)) 339 | 340 | (defun lspce--range (start end) 341 | (let ((params (make-hash-table))) 342 | (puthash :start start params) 343 | (puthash :end end params) 344 | params)) 345 | 346 | (defun lspce--textDocumentIdenfitier (uri) 347 | (let ((params (make-hash-table))) 348 | (puthash :uri uri params) 349 | params)) 350 | 351 | (defun lspce--referenceContext () 352 | (let ((params (make-hash-table))) 353 | (puthash :includeDeclaration t params) 354 | params)) 355 | 356 | (defun lspce--textDocumentPositionParams (textDocument position &optional context) 357 | "context is only used for references, signature help and completion." 358 | (let ((params (make-hash-table))) 359 | (puthash :textDocument textDocument params) 360 | (puthash :position position params) 361 | (when context 362 | (puthash :context context params)) 363 | params)) 364 | 365 | (defalias 'lspce--declarationParams 'lspce--textDocumentPositionParams "lspce--definitionParams") 366 | (defalias 'lspce--definitionParams 'lspce--textDocumentPositionParams "lspce--definitionParams") 367 | (defalias 'lspce--referencesParams 'lspce--textDocumentPositionParams "lspce--referencesParams") 368 | (defalias 'lspce--typeDefinitionParams 'lspce--textDocumentPositionParams "lspce--typeDefinitionParams") 369 | (defalias 'lspce--implementationParams 'lspce--textDocumentPositionParams "lspce--implementationParams") 370 | (defalias 'lspce--hoverParams 'lspce--textDocumentPositionParams "lspce--hoverParams") 371 | (defalias 'lspce--signatureHelpParams 'lspce--textDocumentPositionParams "lspce--signatureHelpParams") 372 | 373 | (defun lspce--workspaceSymbolParams (query) 374 | (let ((params (make-hash-table))) 375 | (puthash :query query params) 376 | params)) 377 | 378 | (defconst LSPCE-Invoked 1 "Completion was triggered by typing an identifier or via API") 379 | (defconst LSPCE-TriggerCharacter 2 "Completion was triggered by a trigger character") 380 | (defconst LSPCE-TriggerForIncompleteCompletions 3 "Completion was re-triggered as the current completion list is incomplete") 381 | 382 | (defun lspce--completionContext (trigger-kind trigger-character) 383 | (let ((params (make-hash-table))) 384 | (when trigger-kind 385 | (puthash :triggerKind trigger-kind params)) 386 | (when trigger-character 387 | (puthash :triggerCharacter trigger-character params)) 388 | params)) 389 | (defalias 'lspce--completionParams 'lspce--textDocumentPositionParams "lspce--definitionParams") 390 | 391 | (defun lspce--codeActionContext (diagnostics &optional only) 392 | (let ((params (make-hash-table))) 393 | (puthash :diagnostics diagnostics params) 394 | (when only 395 | (puthash :only only params)) 396 | params)) 397 | 398 | (defun lspce--codeActionParams (textDocument range context) 399 | (let ((params (make-hash-table))) 400 | (puthash :textDocument textDocument params) 401 | (puthash :range range params) 402 | (puthash :context context params) 403 | params)) 404 | 405 | (defun lspce--renameParams (textDocument position newName) 406 | (let ((params (make-hash-table))) 407 | (puthash :textDocument textDocument params) 408 | (puthash :position position params) 409 | (puthash :newName newName params) 410 | params)) 411 | 412 | (defun lspce--inlayHintsParams (textDocument range) 413 | (let ((params (make-hash-table))) 414 | (puthash :textDocument textDocument params) 415 | (puthash :range range params) 416 | params)) 417 | 418 | ;;; Create LSP params 419 | (defun lspce--make-didOpenTextDocumentParams () 420 | (let ((uri (lspce--path-to-uri buffer-file-name)) 421 | (language-id (lspce--buffer-language-id)) 422 | (version lspce--identifier-version) 423 | (text (lspce--widening (buffer-substring-no-properties 424 | (point-min) (point-max))))) 425 | (lspce--didOpenTextDocumentParams 426 | (lspce--textDocumentItem uri language-id version text)))) 427 | 428 | (defun lspce--make-didCloseTextDocumentParams () 429 | (let ((uri (lspce--path-to-uri buffer-file-name))) 430 | (lspce--didCloseTextDocumentParams (lspce--textDocumentIdenfitier uri)))) 431 | 432 | (defun lspce--make-didChangeTextDocumentParams (&optional full) 433 | (let ((uri (lspce--path-to-uri buffer-file-name)) 434 | (version lspce--identifier-version) 435 | beg end len text changes) 436 | (if full 437 | (setq changes (vector `(:text ,(lspce--widening 438 | (buffer-substring-no-properties 439 | (point-min) 440 | (point-max)))))) 441 | (dolist (change lspce--recent-changes) 442 | (setq beg (nth 0 change) 443 | end (nth 1 change) 444 | len (nth 2 change) 445 | text (nth 3 change)) 446 | (push (lspce--textDocumentContentChangeEvent 447 | (lspce--range beg end) 448 | len 449 | text) 450 | changes)) 451 | (setq changes (vconcat changes))) 452 | (lspce--didChangeTextDocumentParams 453 | (lspce--versionedTextDocumentIdenfitier uri version) 454 | changes))) 455 | 456 | (defun lspce--make-position (&optional pos) 457 | (save-excursion 458 | (let (line character) 459 | (setq line (1- (line-number-at-pos pos t))) 460 | (setq character (progn (when pos (goto-char pos)) 461 | (funcall lspce-current-column-function))) 462 | (lspce--position line character)))) 463 | 464 | (defun lspce--make-range (start end) 465 | (list :start (lspce--make-position start) :end (lspce--make-position end))) 466 | 467 | (defun lspce--make-declarationParams () 468 | (lspce--declarationParams 469 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 470 | (lspce--make-position))) 471 | 472 | (defun lspce--make-definitionParams (&optional context) 473 | (lspce--definitionParams 474 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 475 | (lspce--make-position))) 476 | 477 | (defun lspce--make-implementationParams () 478 | (lspce--implementationParams 479 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 480 | (lspce--make-position))) 481 | 482 | (defun lspce--make-referenceParams () 483 | (lspce--referencesParams 484 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 485 | (lspce--make-position) 486 | (lspce--referenceContext))) 487 | 488 | (defun lspce--make-typeDefinitionParams () 489 | (lspce--typeDefinitionParams 490 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 491 | (lspce--make-position))) 492 | 493 | (defun lspce--make-hoverParams (&optional context) 494 | (lspce--hoverParams 495 | (lspce--textDocumentIdenfitier (lspce--path-to-uri buffer-file-name)) 496 | (lspce--make-position))) 497 | 498 | (defun lspce--make-textDocumentPositionParams (&optional context) 499 | (lspce--textDocumentPositionParams 500 | (lspce--textDocumentIdenfitier (lspce--uri)) 501 | (lspce--make-position) 502 | context)) 503 | (defalias 'lspce--make-signatureHelpParams 504 | 'lspce--make-textDocumentPositionParams 505 | "lspce--make-signatureHelpParams") 506 | 507 | (defun lspce--make-workspaceSymbolParams (pattern) 508 | (lspce--workspaceSymbolParams pattern)) 509 | 510 | (defun lspce--make-initializeParams (root-uri initializationOptions) 511 | (lspce--initializeParams root-uri initializationOptions)) 512 | 513 | (defun lspce--make-inlayHintsParams (start end) 514 | (lspce--inlayHintsParams 515 | (lspce--textDocumentIdenfitier (lspce--uri)) 516 | (lspce--make-range start end))) 517 | 518 | (defun lspce--make-completionParams() 519 | (lspce--completionParams (lspce--textDocumentIdenfitier (lspce--uri)) 520 | (lspce--make-position) 521 | (lspce--make-completionContext))) 522 | 523 | (defun lspce--make-codeActionContext (begin end &optional action-kind) 524 | (let ((flymake-diags (flymake-diagnostics begin end)) 525 | (diagnostics (vector)) 526 | diag) 527 | (dolist (d flymake-diags) 528 | (setq diag (cdr (assoc 'lspce-lsp-diag (flymake-diagnostic-data d)))) 529 | (when diag 530 | (setq diagnostics (vconcat diagnostics (list diag))))) 531 | (lspce--codeActionContext diagnostics (when action-kind (vector action-kind))))) 532 | 533 | (defun lspce--make-codeActionParams (begin end &optional action-kind) 534 | (lspce--codeActionParams 535 | (lspce--textDocumentIdenfitier (lspce--uri)) 536 | (lspce--make-range begin end) 537 | (lspce--make-codeActionContext begin end action-kind))) 538 | 539 | 540 | ;;; Macros 541 | (defmacro lspce--while-no-input (&rest body) 542 | "Wrap BODY in `while-no-input' and respecting `non-essential'. 543 | Return value of `body', or nil if interrupted." 544 | (declare (debug t) (indent 0)) 545 | `(if non-essential 546 | (let ((res (while-no-input ,@body))) 547 | (cond 548 | ;; interrupted or input arriving 549 | ((booleanp res) 550 | nil) 551 | ;; execute normally 552 | (t 553 | res))) 554 | ,@body)) 555 | 556 | 557 | ;;; LSP functions 558 | (defun lspce--server-capable (capability) 559 | (gethash capability lspce--server-capabilities)) 560 | 561 | (defun lspce--server-capable-chain (&rest cs) 562 | (let ((capabilities lspce--server-capabilities)) 563 | (dolist (c cs) 564 | (when (and capabilities 565 | (hash-table-p capabilities)) 566 | (setq capabilities (gethash c capabilities)))) 567 | capabilities)) 568 | 569 | (defun lspce--project-root () 570 | (let ((proj (project-current)) 571 | proj-root) 572 | (setq proj-root 573 | (if proj 574 | (project-root proj) 575 | (when (and 576 | buffer-file-name 577 | (member major-mode lspce-modes-enable-single-file-root)) 578 | buffer-file-name))) 579 | proj-root)) 580 | 581 | (defun lspce--root-uri () 582 | (let ((proj-root (lspce--project-root))) 583 | (when proj-root 584 | (lspce--path-to-uri proj-root)))) 585 | 586 | (defun lspce--project-root-dir () 587 | (let ((proj-root (lspce--project-root))) 588 | (when proj-root 589 | (if (file-directory-p proj-root) 590 | proj-root 591 | (file-name-directory proj-root))))) 592 | 593 | (defun lspce--lsp-type () 594 | (funcall lspce-lsp-type-function)) 595 | 596 | (defun lspce--uri () 597 | (lspce--path-to-uri (buffer-file-name))) 598 | 599 | (defvar lspce--request-ticks (make-hash-table :test #'equal)) ;; key: request id 600 | (defvar lspce--latest-tick nil) 601 | 602 | (defun lspce--current-tick () 603 | (format "%d_%d_%s" (buffer-chars-modified-tick) (point) (buffer-file-name))) 604 | 605 | (defvar lspce--default-sit-for-interval 0.02) 606 | (defvar lspce-sit-for-interval-alist 607 | '(("java" . 0.05)) 608 | "Map language id to a sit-for interval used to retrieve response.") 609 | (defun lspce--sit-for-interval (language-id) 610 | (let ((interval (or (assoc-default language-id lspce-sit-for-interval-alist) 611 | lspce--default-sit-for-interval))) 612 | interval)) 613 | 614 | (cl-defun lspce--get-response 615 | (request-id method &optional timeout root-uri lsp-type) 616 | (let ((trying t) 617 | (lspce--root-uri (or root-uri lspce--root-uri)) 618 | (lspce--lsp-type (or lsp-type lspce--lsp-type)) 619 | (start-time (float-time)) 620 | (request-tick (gethash request-id lspce--request-ticks)) 621 | response-tick 622 | response msg response-error response-data) 623 | (lspce--debug "lspce--get-response for request-id %s" request-id) 624 | (when (member method '("textDocument/completion")) 625 | (lspce--log-perf 626 | "before getting response ===== request-id %s, method %s, start-time %s" 627 | request-id method start-time)) 628 | (while (and trying 629 | (or (null timeout) 630 | (> (+ start-time timeout) (float-time)))) 631 | (lspce--debug "request-tick: %s, lspce--latest-tick: %s" 632 | request-tick lspce--latest-tick) 633 | (unless (string-equal request-tick lspce--latest-tick) 634 | (lspce--debug 635 | "lspce--get-response request outdated, request-tick: %s, lspce--latest-tick: %s" 636 | request-tick lspce--latest-tick) 637 | (cl-return-from lspce--get-response nil)) 638 | (if (sit-for (lspce--sit-for-interval lspce--lsp-type) t) 639 | (progn 640 | (setq response-tick (lspce-module-read-latest-response-tick 641 | lspce--root-uri lspce--lsp-type)) 642 | (lspce--debug "response-tick %S" response-tick) 643 | (lspce--debug "response-tick %S" response-tick) 644 | 645 | (when (string-equal response-tick request-tick) 646 | (lspce--debug "start to read response %s" request-id) 647 | (setq response 648 | (lspce-module-read-response-exact 649 | lspce--root-uri lspce--lsp-type request-id method)) 650 | (lspce--debug "response %s" response) 651 | 652 | (when response 653 | (setq trying nil) 654 | (setq msg (lspce--json-deserialize response)) 655 | (setq response-error (gethash "error" msg)) 656 | (if response-error 657 | (lspce--warn "LSP error %s" 658 | (gethash "message" response-error)) 659 | (setq response-data (gethash "result" msg)))))) 660 | (lspce--debug "sit-for is interrupted.") 661 | (setq trying nil))) 662 | (when (member method '("textDocument/completion")) 663 | (lspce--log-perf 664 | "after getting response ===== request-id %s, method %s, end-time %s" 665 | request-id method (float-time))) 666 | response-data)) 667 | 668 | (defun lspce--request (method &optional params timeout root-uri lsp-type) 669 | (lspce--while-no-input 670 | (let (response) 671 | (when-let (request-id 672 | (lspce--request-async method params root-uri lsp-type)) 673 | (setq response 674 | (lspce--get-response request-id method timeout root-uri lsp-type)) 675 | (when (string-equal method "textDocument/completion") 676 | (lspce--log-perf 677 | "response ===== request_id: %s, method: %s" request-id method))) 678 | response))) 679 | 680 | (cl-defun lspce--notify (method &optional params root-uri lsp-type) 681 | (let ((notification (lspce--make-notification method params)) 682 | (root-uri (or root-uri lspce--root-uri)) 683 | (lsp-type (or lsp-type lspce--lsp-type))) 684 | (unless (and root-uri lsp-type) 685 | (user-error 686 | "lspce--notify: Can not get root-uri or lsp-type of current buffer.") 687 | (cl-return-from lspce--notify nil)) 688 | (lspce-module-notify root-uri lsp-type (json-encode notification)))) 689 | 690 | (defun lspce--notify-textDocument/didChange () 691 | "Send textDocument/didChange to server." 692 | (when lspce--recent-changes 693 | (let* ((sync-capability (lspce--server-capable "textDocumentSync")) 694 | (sync-kind (if (numberp sync-capability) sync-capability 695 | (or (and (hash-table-p sync-capability) 696 | (gethash "change" sync-capability)) 697 | 2))) 698 | (full-sync-p (or (eq sync-kind 1) 699 | (eq :emacs-messup lspce--recent-changes)))) 700 | (when (not (eq sync-kind 0)) 701 | (lspce--notify "textDocument/didChange" 702 | (lspce--make-didChangeTextDocumentParams full-sync-p))) 703 | (setq lspce--recent-changes nil)))) 704 | 705 | (defun lspce--notify-textDocument/didOpen () 706 | "Send textDocument/didOpen to server." 707 | (lspce--notify 708 | "textDocument/didOpen" (lspce--make-didOpenTextDocumentParams))) 709 | 710 | (defun lspce--notify-textDocument/didClose () 711 | "Send textDocument/didClose to server." 712 | (with-demoted-errors 713 | "[lspce] error sending textDocument/didClose: %s" 714 | (lspce--notify 715 | "textDocument/didClose" (lspce--make-didCloseTextDocumentParams)))) 716 | 717 | (defun lspce--notify-textDocument/willSave () 718 | "Send textDocument/willSave to server." 719 | (when (lspce--server-capable-chain "textDocumentSync" "willSave") 720 | (lspce--notify 721 | "textDocument/willSave" 722 | (list :textDocument 723 | (lspce--textDocumentIdenfitier (lspce--uri)) :reason 1)))) 724 | 725 | (defun lspce--notify-textDocument/didSave () 726 | "Send textDocument/willSave to server." 727 | (let ((capability (lspce--server-capable-chain "textDocumentSync" "save")) 728 | (includeText nil)) 729 | (when capability 730 | (when (hash-table-p capability) 731 | (setq includeText (gethash "includeText" capability))) 732 | (if includeText 733 | (lspce--notify 734 | "textDocument/didSave" 735 | (list :textDocument 736 | (lspce--textDocumentIdenfitier (lspce--uri)) 737 | :text 738 | (lspce--widening 739 | (buffer-substring-no-properties (point-min) (point-max))))) 740 | (lspce--notify 741 | "textDocument/didSave" 742 | (list :textDocument (lspce--textDocumentIdenfitier (lspce--uri)))))))) 743 | 744 | (cl-defun lspce--request-async (method &optional params root-uri lsp-type) 745 | ;; (unless (and buffer-file-name 746 | ;; (file-exists-p buffer-file-name)) 747 | ;; (lspce--warn "lspce--request-async: current buffer has no disk file.") 748 | ;; (cl-return-from lspce--request-async nil)) 749 | (setq lspce--latest-tick (lspce--current-tick)) 750 | (let* ((request (lspce--make-request method params lspce--latest-tick)) 751 | (root-uri (or root-uri lspce--root-uri)) 752 | (lsp-type (or lsp-type lspce--lsp-type)) 753 | (request-id (gethash :id request))) 754 | (unless (and root-uri lsp-type) 755 | (user-error 756 | "lspce--request-async: Can not get root-uri or lsp-type.") 757 | (cl-return-from lspce--request-async nil)) 758 | 759 | (lspce--notify-textDocument/didChange) 760 | 761 | (when (string-equal method "textDocument/completion") 762 | (lspce--log-perf "request ===== request_id: %s, method: %s" 763 | request-id method)) 764 | (lspce--debug "lspce--request-async request: %s" (json-encode request)) 765 | (when (lspce-module-request-async root-uri lsp-type (json-encode request)) 766 | (puthash request-id lspce--latest-tick lspce--request-ticks) 767 | request-id))) 768 | 769 | (defun lspce--process-environment () 770 | (let ((ht (make-hash-table :test #'equal)) 771 | key value) 772 | (dolist (env process-environment) 773 | (when-let (pos (string-search "=" env)) 774 | (setq key (substring env 0 pos) 775 | value (substring env (1+ pos))) 776 | (puthash key value ht))) 777 | ht)) 778 | 779 | (defun lspce--envs-pass-to-subprocess () 780 | (let ((ht (make-hash-table :test #'equal)) 781 | (process-envs (lspce--process-environment))) 782 | (dolist (env lspce-envs-pass-to-subprocess) 783 | (when-let (value (gethash env process-envs)) 784 | (if (string-equal env "PATH") 785 | (puthash "PATH" (mapconcat 'identity exec-path ":") ht) 786 | (puthash env value ht)))) 787 | (when lspce-inherit-exec-path 788 | (puthash "PATH" (mapconcat 'identity exec-path ":") ht)) 789 | (lspce--json-serialize ht))) 790 | 791 | 792 | ;;;###autoload 793 | (defvar-local lspce-workspace-configuration nil 794 | "Configure LSP servers specifically for a given project.") 795 | 796 | ;;;###autoload 797 | (put 'lspce-workspace-configuration 'safe-local-variable 'listp) 798 | 799 | (defun lspce--workspace-configuration-plist (&optional current-buffer) 800 | "Returns workspace configuration of current server as a plist." 801 | (with-current-buffer (or current-buffer (current-buffer)) 802 | lspce-workspace-configuration)) 803 | 804 | (defun lspce--notify-workspace/didChangeConfiguration (configuration) 805 | (let ((settings (make-hash-table :test #'equal))) 806 | (lspce--add-options-internal settings configuration) 807 | (lspce--notify 808 | "workspace/didChangeConfiguration" (list :settings (or settings lspce--{}))))) 809 | 810 | ;; 返回server info. 811 | (defun lspce--connect-existing-server (root-uri lsp-type) 812 | (let (lsp-server) 813 | (setq lsp-server (lspce-module-server root-uri lsp-type)) 814 | (when lsp-server 815 | (lspce--info 816 | "lspce--connect: Server for (%s %s) is running." root-uri lsp-type)) 817 | lsp-server)) 818 | 819 | (cl-defun lspce--connect (root-uri lsp-type server-cmd server-args initialize-options) 820 | (let ((initialize-params nil) 821 | lsp-server 822 | response-str) 823 | 824 | (setq lsp-server (lspce-module-server root-uri lsp-type)) 825 | (when lsp-server 826 | (lspce--info 827 | "lspce--connect: Server for (%s %s) is running." root-uri lsp-type) 828 | (cl-return-from lspce--connect lsp-server)) 829 | 830 | (setq initialize-params 831 | (lspce--make-initializeParams root-uri initialize-options)) 832 | 833 | (lspce--debug "lspce--connect initialize-params: %s" 834 | (json-encode initialize-params)) 835 | 836 | (setq lspce--latest-tick (lspce--current-tick)) 837 | (setq response-str 838 | (lspce-module-connect root-uri 839 | lsp-type 840 | server-cmd 841 | server-args 842 | (json-encode 843 | (lspce--make-request "initialize" 844 | initialize-params 845 | lspce--latest-tick)) 846 | lspce-connect-server-timeout 847 | (lspce--envs-pass-to-subprocess))) 848 | (lspce--debug "lspce--connect response: %s" response-str) 849 | 850 | (when response-str 851 | (let ((configuration (lspce--workspace-configuration-plist (current-buffer)))) 852 | (lspce--notify-workspace/didChangeConfiguration configuration))) 853 | 854 | response-str)) 855 | 856 | (defvar-local lspce--uri nil) 857 | (defvar-local lspce--root-uri nil) 858 | (defvar-local lspce--lsp-type nil) 859 | (defvar-local lspce--server-info nil) 860 | (defvar-local lspce--server-capabilities nil) 861 | 862 | (defvar lspce--notification-idle-timer nil) 863 | 864 | ;;;###autoload 865 | (defun lspce-enable-notification-handler () 866 | (interactive) 867 | (when lspce--notification-idle-timer 868 | (cancel-timer lspce--notification-idle-timer)) 869 | (setq lspce--notification-idle-timer 870 | (run-with-idle-timer 1 t #'lspce--notification-handler))) 871 | 872 | ;;;###autoload 873 | (defun lspce-disable-notification-handler () 874 | (interactive) 875 | (when lspce--notification-idle-timer 876 | (cancel-timer lspce--notification-idle-timer))) 877 | 878 | (defun lspce--notification-handler () 879 | (let (notification 880 | method params 881 | message-type 882 | message) 883 | (with-current-buffer (current-buffer) 884 | (when (and lspce-mode 885 | lspce--root-uri 886 | lspce--lsp-type) 887 | (setq notification 888 | (lspce-module-read-notification lspce--root-uri lspce--lsp-type)) 889 | (lspce--debug "notification: %s" notification) 890 | (when notification 891 | (setq notification (lspce--json-deserialize notification)) 892 | (setq method (gethash "method" notification) 893 | params (gethash "params" notification)) 894 | (cond 895 | ((or (string-equal method "window/showMessage") 896 | (string-equal method "window/logMessage")) 897 | (setq message-type (gethash "type" params) 898 | message (gethash "message" params)) 899 | (cond 900 | ((eq message-type 1) 901 | (lspce--error "Server message: %s" message)) 902 | ((eq message-type 2) 903 | (lspce--warn "Server message: %s" message)) 904 | ((eq message-type 3) 905 | (lspce--info "Server message: %s" message)) 906 | ((eq message-type 4) 907 | (lspce--debug "Server message: %s" message)))) 908 | (t 909 | ))))))) 910 | 911 | 912 | (provide 'lspce-core) 913 | --------------------------------------------------------------------------------