VonHeikemen / lsp-zero.nvim

A starting point to setup some lsp related features in neovim.
https://lsp-zero.netlify.app/docs/
MIT License
3.78k stars 96 forks source link

question: how can i format some text selection? #343

Closed nicolimo86 closed 10 months ago

nicolimo86 commented 10 months ago

Right now I can only format the whole buffer. I would like to be more precise and just format the selected lines.

My current config:

local function lsp_keymaps(bufnr)
    local opts = { noremap = true, silent = true }
    local keymap = vim.api.nvim_buf_set_keymap
   ...
    keymap(bufnr, "n", "<leader>lf", "<cmd>lua vim.lsp.buf.format{ async = true }<cr>", opts)
    ...
end

lsp.on_attach(function(client, bufnr)
    local opts = { buffer = bufnr, remap = false }

    lsp.default_keymaps({ buffer = bufnr })
    lsp_keymaps(bufnr)
end)

Adding a new key mapping in visual mode doesn't seem to work:

local function lsp_keymaps(bufnr)
    local opts = { noremap = true, silent = true }
    local keymap = vim.api.nvim_buf_set_keymap
   ...
    keymap(bufnr, "n", "<leader>lf", "<cmd>lua vim.lsp.buf.format{ async = true }<cr>", opts)
    keymap(bufnr, "v", "lf", "<cmd>lua vim.lsp.buf.format{ async = true }<cr>", opts)  <-- new mapping
    ...
end

lsp.on_attach(function(client, bufnr)
    local opts = { buffer = bufnr, remap = false }

    lsp.default_keymaps({ buffer = bufnr })
    lsp_keymaps(bufnr)
end)

Can you please share your solution?

VonHeikemen commented 10 months ago

Your new keymap should work. I tested in my own config.

What language server are you using to format?

nicolimo86 commented 10 months ago

I tested on a terraform file (.tf). I have 2 language servers attached to the buffer:

 Client: terraformls (id: 1, bufnr: [1])
 Client: tflint (id: 2, bufnr: [1])

I have the same behaviour (pressing lf after a selection does nothing) on bash file with bashls language server attached to the buffer.

nicolimo86 commented 10 months ago

It works on python and lua files! This means that the language servers i'm using for terraform and bash don't support range formatting i guess.