I don't set a mapping to format code because it is not something I do all the time. So previously, I used to have a command to format or range format as follows:

" format code
command! -range Format if <range> | exec 'lua vim.lsp.buf.range_formatting({ timeout_ms = 2000 })' | else | exec 'lua vim.lsp.buf.format({ timeout_ms = 2000 })' | endif

But Nvim now gives me this message:

vim.lsp.buf.range_formatting is deprecated, use vim.lsp.formatexpr or vim.lsp.buf.format > instead. See :h deprecated
This function will be removed in Nvim version 0.9.0
stack traceback:
        /usr/share/nvim/runtime/lua/vim/lsp/buf.lua:407: in function 'range_formatting'
        [string ":lua"]:1: in main chunk

How can I set a command (not a key mapping) to format the selected text, when there is any, or the entire buffer if not?

  • I see the docs have a range option for vim.lsp.buf.format but I couldn't make it work. Also, all examples I could find were for key mappings, not for a command. Apr 25 at 13:58
  • Is the solution working? How can we help you further? Apr 27 at 17:36

1 Answer 1


I would do:

command! -range Format if <range> | exec 'lua vim.lsp.buf.format({timeout_ms = 2000, range={["start"]={row=<line1>,col=0},["end"]={row=<line2>,col=0}}})' | else | exec 'lua vim.lsp.buf.format({ timeout_ms = 2000 })' | endif
  • 1
    I'm assuming execute is because lua eats the |?
    – D. Ben Knoble
    Apr 26 at 12:42
  • 1
    To highlight the changes proposed I kept as much as I could the proposed solution. I didn't test without the execute but you are right it could be that the lua eats the |. Apr 26 at 13:01
  • I'm getting an error: attempt to perform arithmetic on a nil value. I'll look deeper later to find what is happening. Thanks for now. Apr 27 at 22:06
  • Could you tell us which language and which lsp server you are using for that language? Apr 27 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.