diff options
author | pommicket <pommicket@gmail.com> | 2023-09-08 22:59:47 -0400 |
---|---|---|
committer | pommicket <pommicket@gmail.com> | 2023-09-08 22:59:47 -0400 |
commit | 0dcfd5a4f1fd865c24c01b17b214e1f72e4c06fe (patch) | |
tree | d693d70a57713cf4dbe48d30159100bab279c77d /ide-format.c | |
parent | f86b0aa1e843646056c08a91fcc759aa0d8a57ba (diff) |
LSP code formatting (not entirely working yet)
Diffstat (limited to 'ide-format.c')
-rw-r--r-- | ide-format.c | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/ide-format.c b/ide-format.c new file mode 100644 index 0000000..70103c7 --- /dev/null +++ b/ide-format.c @@ -0,0 +1,70 @@ +#include "ted-internal.h" + +struct Formatting { + LSPServerRequestID last_request_id; +}; + +void format_init(Ted *ted) { + ted->formatting = calloc(1, sizeof (Formatting)); +} + +static void format_common(Ted *ted, bool selection) { + Formatting *formatting = ted->formatting; + ted_cancel_lsp_request(ted, &formatting->last_request_id); + TextBuffer *buffer = ted_active_buffer(ted); + if (!buffer) return; + if (selection && !buffer_has_selection(buffer)) return; + LSP *lsp = buffer_lsp(buffer); + if (!lsp) return; + Settings *settings = buffer_settings(buffer); + LSPRequest request = { + .type = selection ? LSP_REQUEST_RANGE_FORMATTING : LSP_REQUEST_FORMATTING + }; + LSPRequestFormatting *req_data = &request.data.formatting; + req_data->document = buffer_lsp_document_id(buffer); + req_data->indent_with_spaces = settings->indent_with_spaces; + req_data->tab_width = settings->tab_width; + if (selection) { + req_data->use_range = true; + req_data->range = buffer_selection_as_lsp_range(buffer); + } + formatting->last_request_id = lsp_send_request(lsp, &request); +} + +void format_selection(Ted *ted) { + format_common(ted, true); +} + +void format_file(Ted *ted) { + format_common(ted, false); +} + +void format_cancel_request(Ted *ted) { + Formatting *formatting = ted->formatting; + ted_cancel_lsp_request(ted, &formatting->last_request_id); +} + +void format_process_lsp_response(Ted *ted, const LSPResponse *response) { + Formatting *formatting = ted->formatting; + const LSPRequest *request = &response->request; + if (request->id != formatting->last_request_id.id) + return; + if (!(request->type == LSP_REQUEST_RANGE_FORMATTING + || request->type == LSP_REQUEST_FORMATTING)) { + return; + } + TextBuffer *buffer = ted->active_buffer; + if (!buffer) return; + if (buffer_lsp_document_id(buffer) != request->data.formatting.document) + return; // switched document + + const LSPResponseFormatting *f = &response->data.formatting; + arr_foreach_ptr(f->edits, const LSPTextEdit, edit) { + buffer_apply_lsp_text_edit(buffer, response, edit); + } +} + +void format_quit(Ted *ted) { + free(ted->formatting); + ted->formatting = NULL; +} |