When using {
and }
to skip to the next paragraph, the behavior is unpredictable since I can't see white spaces. I have tried to show line endings to see which lines have spaces, but I don't like the cluttered look. I would like {
and }
to treat lines with white spaces as empty lines. How can I achieve this?
1 Answer
As per the comments, you can search for the next blank line with /^\s*$
. However, this will clobber the search register (@/
) and interfere with the search history. It will also highlight all blank lines if the 'hlsearch' setting is on.
I'd recommend something similar, search()
. Like /
, it searches for a pattern, but without the quirks mentioned above. Specifically,
search('^\s*$', 'W')
will search forward for the first blank line (without wrapping around the end of the buffer), andsearch('^\s*$', 'bW')
will search backwards.
Finally, override the default behavior of {
,}
with the mappings
nnoremap } <cmd>call search('^\s*$', 'W')<cr>
nnoremap { <cmd>call search('^\s*$', 'bW')<cr>
For visual mode, use xnoremap
in place of nnoremap
.
EDIT: Note that the use of <cmd>...<cr>
requires Vim 8.2 (specifically, 8.2.2026) or Neovim.
-
Typing
nnoremap } :call search('^\s*$', 'W')<cr>
in command mode seems to do just the thing, but I can't figure out what to put in the.vimrc
. Also, if I doxnoremap } :call search('^\s*$', 'W')<cr>
, I'm kicked out of visual mode when I type}
.– nixlarfsMar 21, 2022 at 15:04 -
-
@Biggybi I copied these lines exactly but it didn't work. Swapping
<cmd>
for:
works in command mode, but having to input this for every session doesn't beat the auto trim trailing white spaces solution.– nixlarfsMar 22, 2022 at 8:54 -
1It works as expected for me (both in normal and visual mode).
<cmd>
was introduced in a fairly recent version though, so you might need to update your vim. Else, use:
as you have, and try to addgv
for visual maps (to go back to visual selection). Put these lines in your vimrc, they will be read when vim starts and you won't need to input them anymore.– BiggybiMar 22, 2022 at 12:04 -
2Upgrading from 8.1 to 8.2 solved both the problem with putting the lines in the
.vimrc
, and the problem of being kicked out of visual mode withxnoremap
.– nixlarfsMar 28, 2022 at 11:52
nnoremap <LEADER>} /^\s*&/<CR>
&
supposed to be a$
?:nnoremap <leader>} /^\s*$/<cr>
and press enter (or put the same line in a vimrc or other config file), and then type\}
(unless you have changedmapleader
, see:help <Leader>
). You might however instead prefer to eliminate such trailing spaces::%substitute/\s*$//
<leader>
thing doesn't seem to work in visual mode. Also, I'd prefer not to have to use<leader>
if that's possible. I'm divided on the elimination of white spaces in case I share code with people, but maybe that's the best solution.xnoremap
!