Vim Tips Wiki
Register
Advertisement
Tip 7 Printable Monobook Previous Next

created February 24, 2001 · complexity basic · author Yegappan · version 5.7


To jump to the beginning of a C code block (while, switch, if etc), use the [{ command.

To jump to the end of a C code block (while, switch, if etc), use the ]} command.

The above two commands will work from anywhere inside the code block.

To jump to the beginning of a parenthesis use the [( command.

To jump to the end of a parenthesis use the ]) command.

References[]

Comments[]

Related to these motion commands are [[ and ]]

  • [[ : sections backward or to the previous '{' in the first column.
  • ]] : sections forward or to the next '{' in the first column.
  • [] : sections backward or to the previous '}' in the first column.
  • ][ : sections forward or to the next '}' in the first column.

This is particularly useful for jumping to the top of the functions and jumping from one function to the next function. For instance, the first command takes you to the beginning of the current function. The second command takes you to the beginning of the next function. The third takes you to the end of the previous function.

Certain coding conventions work better for this practice than others.


To jump to the beginning/end of a function that does not have a "{" in the first column, there is a work around in the Vim documentation. Try ":help [[" and search for "map" in that text.

  • I didn't like that the mappings proposed in the help function used / and ?, and therefore changed the last search pattern and activated hlsearch. As a workaround I use this instead (note that I'm a novice in Vimscrip, so it's very much possible that this is very suboptimal):
map [[ :silent! eval search('{', 'b')<CR>w99[{
map ][ :silent! eval search('}')<CR>b99]}
map ]] j0[[%:silent! eval search('{')<CR>
map [] k$][%:silent! eval search('}', 'b')<CR>

Basically they're the same thing as the mappings in the docs, except that they use search() instead of / and ?.


What's the different between this and just searching "/ or ?" for the braces?

I thought this might be a smarter search, but "[{" will still match in open curlies inside a comment.

 /} will not work for nested {}.

The advantage is the following. Say you want to go to the beginning of the block that the cursor is in. between the cursor position and the beginning of the block, there may be several blocks at the same level as the cursor, so [{ will skip them, but ?{ won't. This is even more useful if you want to go to the beginning of a block multiple levels above the cursor position, because there could be a lot more blocks that you want to skip.

Advertisement