sync_lsp/text_document/
code_action.rs

1//! implementation of the `textDocument/codeAction` request
2//! 
3//! # Usage
4//! The [`Server::on_code_action`] endpoint is used to compute commands
5//! for a range of a text document. Commonly these commands are displayed
6//! in the user interface and may for example represent code fixes or
7//! refactoring options.
8
9use crate::TypeProvider;
10use crate::workspace::execute_command::CommandContainer;
11use crate::{Server, connection::Endpoint};
12use crate::connection::Callback;
13use serde::Deserialize;
14use super::publish_diagnostics::Diagnostic;
15use super::{TextDocumentIdentifer, Range};
16
17#[derive(Default, Clone)]
18pub(crate) struct CodeActionOptions;
19
20#[derive(Deserialize)]
21#[serde(rename_all = "camelCase")]
22struct CodeActionParams {
23    text_document: TextDocumentIdentifer,
24    range: Range,
25    context: CodeActionContext
26}
27
28/// Contains additional diagnostic information about the context in which a code action is run.
29#[derive(Deserialize, Debug)]
30pub struct CodeActionContext {
31    /// An array of diagnostics as defined by the server.
32    pub diagnostics: Vec<Diagnostic>
33}
34
35impl CodeActionOptions {
36
37    pub(crate) const METHOD: &'static str = "textDocument/codeAction";
38    
39    pub(super) fn endpoint<T: TypeProvider>() -> Endpoint<T, CodeActionOptions> {
40        Endpoint::new(Callback::request(|_, _: CodeActionParams| Vec::<()>::new()))
41    }
42}
43
44impl<T: TypeProvider> Server<T> {
45    
46    /// Sets the callback that will be called to [compute code actions](self).
47    /// 
48    /// # Argument
49    /// * `callback` - A callback which is called with the following parameters as soon as code actions are requested:
50    ///     * The server instance receiving the response.
51    ///     * The [`TextDocumentIdentifer`] of the document for which code actions are requested.
52    ///     * The [`Range`] of the document for which code actions are requested.
53    ///     * The [`CodeActionContext`] for which code actions are requested.
54    ///     * `return` - A list of commands to execute.
55
56    pub fn on_code_action(&mut self, callback: fn(&mut Server<T>, TextDocumentIdentifer, Range, CodeActionContext) -> Vec<T::Command>) {
57        self.text_document.code_action.set_callback(Callback::request(move |server, params: CodeActionParams| {
58            callback(server, params.text_document, params.range, params.context).into_iter()
59                .map(|command| CommandContainer(command))
60                .collect::<Vec<_>>()
61        }))
62    }
63}