sync_lsp/text_document/
formatting.rs

1//! implementation of the `textDocument/formatting` request
2//! 
3//! # Usage
4//! Some server may be capable of formatting a document. If so, [`Server::on_formatting`] can be used to
5//! provide this functionality to the client. It can be triggered either manually or automatically.
6
7use crate::TypeProvider;
8use crate::{Server, connection::Endpoint};
9use crate::connection::Callback;
10use super::{TextDocumentIdentifer, TextEdit};
11use serde::Deserialize;
12
13#[derive(Default, Clone)]
14pub(crate) struct DocumentFormattingOptions;
15
16#[derive(Deserialize)]
17#[serde(rename_all = "camelCase")]
18struct DocumentFormattingParams {
19    text_document: TextDocumentIdentifer,
20    options: FormattingOptions
21}
22
23/// Specifies how a document should be formatted.
24#[derive(Deserialize, Debug)]
25#[serde(rename_all = "camelCase")]
26pub struct FormattingOptions<T = ()> {
27    /// The size of tabs in spaces.
28    pub tab_size: u32,
29    /// Specifies whether tabs should be used instead of spaces.
30    pub insert_spaces: bool,
31    /// Additional options can be handled by the server if a struct with the corresponding fields is provided here.
32    #[serde(flatten)]
33    pub properties: T
34}
35
36impl DocumentFormattingOptions {
37
38    pub(crate) const METHOD: &'static str = "textDocument/formatting";
39    
40    pub(super) fn endpoint<T: TypeProvider>() -> Endpoint<T, DocumentFormattingOptions> {
41        Endpoint::new(Callback::request(|_, _: DocumentFormattingParams| Vec::<TextEdit>::new()))
42    }
43}
44
45impl<T: TypeProvider> Server<T> {
46
47    /// Sets the callback that will be called to [format a document](self).
48    ///
49    /// # Argument
50    /// * `callback` - A callback which is called with the following parameters as soon as a document is formatted:
51    ///     * `server` - The server on which the request was received.
52    ///     * `document` - The [`TextDocumentIdentifer`] of the target document.
53    ///     * `options` - The [`FormattingOptions`] that specify how the document should be formatted.
54    ///     * `return` - A list of edits to apply to the document.
55
56    pub fn on_formatting(&mut self, callback: fn(&mut Server<T>, TextDocumentIdentifer, FormattingOptions) -> Vec<TextEdit>) {
57        self.text_document.formatting.set_callback(Callback::request(move |server, params: DocumentFormattingParams | {
58            callback(server, params.text_document, params.options)
59        }))
60    }
61}