Vim - how to jump to start/end of paragraph (which works in all cases)

Viewed 774

Is there really no simple mapping to jump to the first or last line of a paragraph?

{ and } are "exclusive" commands, so they jump to the empty line before or after a paragraph if there is one, but otherwise to the actual first or last line of the paragraph (namely, when the paragraph is at the top or bottom of the buffer).

That difference seemingly makes it impossible to compensate in any straightforward way, e.g. {w jumps to the start for paragraphs if there is an empty line before, but does the wrong thing for the first paragraph in a file.

1 Answers

For the time being, there is no such motion in Vim.

Although, in :h todo it's marked as 7 (i.e. ASAP):

7   Add "g{" and "g}" to move to the first/last character of a paragraph
    (instead of the line just before/after a paragraph as with "{" and "}").

If we will limit ourselves only to current paragraph, then I can propose as for temporary solution:

nnoremap g{ vipo<Esc>
nnoremap g} vipoo<Esc>

And if we want something closer to the real thing, then we can use function:

function! Foo(x,y) abort
  if empty(getline(line('.') + (a:x == '{' ? -1 : 1)))
     exec "norm! ".a:x
   endif
  exec "norm! ".a:x
  if empty(getline('.')) | exec "norm! ".a:y | endif
endfunction

nnoremap <silent> g{ :call Foo('{', 'w')<CR>
nnoremap <silent> g} :call Foo('}', 'ge')<CR>
Related