vincent
vincent

Reputation: 1390

Jump to current function declaration from middle of function

Is there a way to jump to the signature of the function my cursor is currently in, then jump back to where I was?

For example, when I have a 1000 line function, where the prefix x + y: refers to line numbers, is there a way from me to jump from my cursor location at x + 555 to the signature at x + 0 then back to where I was at (x + 555):

x + 000: void theFn(int arg) {
x + ...:     ...
x + 555:     /// where my cursor starts
x + ...:     ...
x + 999: }

And, yes, I couldn't agree with you more that there shouldn't be 1000 line functions.

Also, is there a way to automatically jump to the end of function without being at the opening bracket of the function?

Upvotes: 2

Views: 719

Answers (1)

Jorenar
Jorenar

Reputation: 2884

Useful motions in such case are [[, ][ and <C-o>.

As we can read in help:

                            *[[*
[[          [count] sections backward or to the previous '{' in
            the first column.  |exclusive|
            Note that |exclusive-linewise| often applies.
                            *][*
][          [count] sections forward or to the next '}' in the
            first column.  |exclusive|
            Note that |exclusive-linewise| often applies.
                            *CTRL-O*
CTRL-O          Go to [count] Older cursor position in jump list
            (not a motion command).
            {not available without the |+jumplist| feature}

In short:

  • [[ to got to the beginning
  • <C-o> to go back to previous place
  • ][ to go to end

Those motions will have the desired effect only when braces are in the first column, but from your example seems like this requirement is not met.
In such case at the end of :h section we can read:

If your '{' or '}' are not in the first column, and you would like to use "[["
and "]]" anyway, try these mappings: >
   :map [[ ?{<CR>w99[{
   :map ][ /}<CR>b99]}
   :map ]] j0[[%/{<CR>
   :map [] k$][%?}<CR>

Unfortunately, Vim doesn't offer better solution as it doesn't parse syntax.
It may change though as Neovim experiments with Tree-sitter.


It also wouldn't be surprising if there was a plugin which provides better support for such motion.
Tagbar could fit this role:

  1. Toggle Tagbar window
  2. Switch to it
  3. Cursor should be already over the current tag
  4. Press enter
  5. Toggle window
  6. You are at beginning of the function
  7. Use <C-o> to get back

I also once found and had in my config a mapping which could also be useful in such case:

nnoremap <Leader>gd ?\v%(%(if|while|for|switch)\_s*)@<!\([^)]*\)\_[^;(){}]*\zs\{

Upvotes: 6

Related Questions