11

I'm using neovim. When I visually select a comment in Python that is longer than my textwidth setting, and press gq, it does not wrap the comment.

I've looked at this question: visual mode gq not reflowing comment block, however my formatoptions setting looks correct:

set formatoptions=cjoqrt

What is causing this to not work?

Ben Davis
  • 213
  • 1
  • 5
  • Welcome to [vi.se]! Check out How to debug my vimrc and try to post a minimal set of instructions that demonstrates the problem – D. Ben Knoble Nov 14 '22 at 16:30
  • 2
    In the most recent versions of Neovim, formatexpr is set to v:lua.vim.lsp.formatexpr(). This makes Neovim use a language server to format, also with gq. I don't how how to preserve that and also be able to wrap text with gq. You can :set formatexpr= to just get the wrapping. – cassava Nov 18 '22 at 09:04
  • Thanks! :set formatexpr= made gq work again. Although I'm curious, what else might I be losing by un-setting formatexpr? – Ben Davis Nov 18 '22 at 16:51
  • Also seems to have suddenly stopped working for me, and also fixed by :set formatexpr=. – n8henrie Jan 11 '23 at 19:58
  • 1
    https://github.com/neovim/neovim/pull/19677 – n8henrie Jan 11 '23 at 20:12

1 Answers1

19

As mentioned by @cassava, your problem may be due to this PR, which changes formatexpr to take its initial value from the LSP (as I understand it).

There are a few suggestions for workarounds in this issue, linked to from this Reddit thread, of which using gw instead of gq seems like the easiest one-off workaround, and this snippet works for me for a more robust approach:

-- Use internal formatting for bindings like gq. 
 vim.api.nvim_create_autocmd('LspAttach', { 
   callback = function(args) 
     vim.bo[args.buf].formatexpr = nil 
   end, 
 })

Alternatively, I am using the below to restore the prior behavior specifically for Python / pylsp:

local pylsp_on_attach = function(client, bufnr)
  default_lsp_on_attach(client, bufnr)
  -- Restore gqq
  vim.api.nvim_buf_set_option(bufnr, "formatexpr", "")
end

nvim_lsp.pylsp.setup({ -- ... on_attach = pylsp_on_attach, -- ... })

n8henrie
  • 406
  • 1
  • 5
  • 9
  • 5
    Thanks! I didn't know :gw was thing (:gq was baked into my brain for years). That worked for me! – Ben Davis Jan 20 '23 at 22:26
  • For whatever reason :gw doesn't work for me either. @n8henrie do you mind adding some comments around what each of the two snippets you've listed actually does and why they fix the underlying issue?

    The first one reads like it just disables using LSP for formatting to restore :gq behavior. Is that correct?

    – ffledgling Jun 02 '23 at 23:37
  • @ffledgling the comment above explains it, if not well -- yes it disables LSP formatting so that you can use neovim's formatting, for the buffer in question. – n8henrie Jun 03 '23 at 13:25