18

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?

5
  • Welcome to Vi and Vim! Check out How to debug my vimrc and try to post a minimal set of instructions that demonstrates the problem Commented Nov 14, 2022 at 16:30
  • 3
    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. Commented Nov 18, 2022 at 9:04
  • Thanks! :set formatexpr= made gq work again. Although I'm curious, what else might I be losing by un-setting formatexpr? Commented Nov 18, 2022 at 16:51
  • Also seems to have suddenly stopped working for me, and also fixed by :set formatexpr=. Commented Jan 11, 2023 at 19:58
  • 1
    github.com/neovim/neovim/pull/19677 Commented Jan 11, 2023 at 20:12

1 Answer 1

29

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, -- ... }) 
4
  • 11
    Thanks! I didn't know :gw was thing (:gq was baked into my brain for years). That worked for me! Commented Jan 20, 2023 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? Commented Jun 2, 2023 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. Commented Jun 3, 2023 at 13:25
  • what is default_lsp_on_attach Commented Sep 1 at 16:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.