I like formating code this way:

class A

unlike another common way:

class B {

The thing is, when using the % command to go to the enclosing bracket, which is very useful for copying/deleting loops/functions, it doesn't work so well on the first case - it just doesn't work if my cursor is on the line without the brackets.

Does anyone know how to change this?


I tried to figure if Vim had some option for this and I believe it doesn't. So I wrote a Vim script to do the job. Just add it to your .vimrc.

function Percent_nextline()
    let line = getline('.')
    if line =~ "{"
        normal! %
        let line = getline(line('.')+1)
        if line =~ "{"
            normal! j%

nnoremap g% :<C-u>call Percent_nextline()<cr>
onoremap g% :<C-u>execute 'normal! V'<Bar>call Percent_nextline()<cr>

This script maps the behaviour you want to g%. With the cursor on the line class A you can type g% and the cursor will jump to the closing curly bracket. It can be preceded with commands like c, d and y.

I implemented this by simply checking if the current line contains a {. If it does then the command behaves as %. If it doesn't the following line is checked and if a { is found the % command is called upon that line. The onoremap makes it possible to use the mapping in operator-pending mode, which is used by c, d and y.

I am sure this script could be improved. It is my first :)

I want to thank @IngoKarkat for helping me in How to make a movement function work with delete, yank, etc.

  • 1
    You should add the case for when you are on } to keep the muscle memory the same.
    – jecxjo
    May 4 '15 at 3:04

With the vim-textobj-user plugin, it is very easy to define your own motions.

You didn't mention which language you're using, but a naive example for C++ might be something like:

call textobj#user#plugin('cpp', {
    \   'code': {
        \     'pattern': ['^class .*\n{', '^}'],
        \     'select-a': 'ac',
        \     'select-i': 'ic',
    \ },

You can use vac to select "A class", or vic to select the inner class; or dic to delete the entire inner class, yic to yank it, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.