3

Is there a set of commands to jump between various elements of the C/C++ source code in vim? I know ctags but that offers limited functionality.

For example, is it possible to jump to the first line of the C/C++ function and come back from any line within the function.

I find myself keep scrolling up to find which function I am in while reviewing the code or searching a text/pattern in the source code.

2 Answers 2

3

In languages where code is structured as methods in classes, [m jumps to the start of the method. That's good in a C++ class, but in a C or C++ toplevel function it'll bring you to the start of the second-outermost block. Another [{ will bring you to the outermost brace.

In languages with C-like syntax, in files formatted with { on its own line at the start of a function, [[ jumps to the previous brace in column 1.

Press Ctrl-O to jump back.

1
  • Thanks for the reply. I am aware of [{ but it only takes you to previous unmatched brace - not the outermost. [[ could be a solution for those have { in the first column but not all code follows that convention so unfortunately that does not work too.
    – Rahul
    Apr 25, 2020 at 14:42
1

As far as I know that is not possible with a simple vim command.

From the vim manual (:help section):

The "]" and "[" commands stop at the '{' or '}' in the first column. This is useful to find the start or end of a function in a C program.

(...)

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>


If you need it for code orientation consider using folds. For example with set foldmethod=syntax press zC while in a function to close it and see the function name, zO to reverse it and jump back to the line you were on.

Another possibility for orientation is to use a plugin such as tagbar that among others highlights the current function.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .