brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: gq with textwidth makes Vim rewrap long lines of text

Vim
~/tips/tip-vim-gq-textwidth-format-text

:set textwidth=72

Rewraps a paragraph or a selection to a fixed line width, such as 72 characters.

Editing a commit message, a README or an email in Vim often ends with one paragraph that has a few very long lines and a few very short ones. Vim can reflow it for you.

:set textwidth=72
gqip

The textwidth option, or tw for short, sets the maximum line width. gq is an operator that formats the lines a motion covers, and ip means the current paragraph. So gqip rewraps the paragraph under the cursor to 72 columns. In visual mode, select lines and press gq. gqq formats just the current line, and gqG goes to the end of the file.

With textwidth set, Vim also breaks lines automatically while you type after a space, as long as the t flag is in formatoptions.

One caveat from :help gq: if textwidth is 0, the lines are formatted to the screen width with a maximum of 79 characters. Also, gq reflows by paragraph, split at blank lines. Do not run it on code or a table, because it joins lines it thinks belong together. Use it on prose, and undo with u if the result is not what you wanted.

Further reading: Vim help: change, gq, Vim help: options, 'textwidth'

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :mksession All Vim tips (45) All topics

Link