Preserve internal formatting when using gq motion

Hello :wave:,

I noted today that formatting lines with gq (with formatoptions set to qtjcrl and unset formatexpr) no longer works when I have the LSP enabled. As soon as I run :LspStop and use gq it works as expected.

How can I properly configure Neovim and the LSP so it preserves the internal formatting behavior when using gq?

Thank you in advance! :pray:

I was also missing the ability to use gq on Neovim 0.8. Thanks for mentioning that the problem disappears when stopping the LSP. Nevertheless, I still wanted to be able to run gq and my LSP.

From I learned that since Neovim 0.8.0 the formatexpr is by default bound to vim.lsp.formatexpr as soon the LSP gets attached to the current buffer. So, a solution to it would be to override it inside the on_attach function in lsp-config.

For example:

-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
  -- Disable lsp formatexpr (use the internal one)
  vim.opt.formatexpr = ""

require('lspconfig')["pylsp"].setup {
  on_attach = on_attach,

It’s working for me. The only drawback I found with this is that this is applied to every LSP that uses this on_attach function, and maybe one would want to actually use the formatter that the LSP provides. A solution would be to write a different on_attach function for those.

Hope this helps!