Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move to the beginning of next code block in Vim

Tags:

vim

perl

Assuming I have the following Perl code open in Vim:

if (@arr = shomething()) {
   for (@arr) {
       some_function($_->{some_key});
       # some
       # more
       # code
       while (some_other_funtion($_)) {
           write_log('working');
       }
   }
}

and the cursor at the beginning of the line with some_function, how I can move the cursor to any of:

  • the start of the while
  • the { of the while
  • the first line inside the while block (with the call to write_log)

Searching for { is not an option, because there could be many of { that do not start new inner code block - for example, see parameter of some_function.

like image 386
cub-uanic Avatar asked Sep 29 '22 15:09

cub-uanic


1 Answers

It seems you are defining a “code block” to be { } that contain at least one line. You can most easily search for those just by searching for a { at the end of a line:

/{$

/{ means search for a {, and $ represents an anchor to the end of the line.

There might be cases where a { opens a block, but is not the last character of a line:

while (some_other_funtion($_)) { # this while is very important
   write_log('working');
}

To take this into account, do the following search for a { that is not closed on the same line:

/{[^}]*$
  1. / – search for
  2. { – a { character
  3. [^}] – followed by any character that is not a }
  4. * – repeated 0 or more times
  5. $ – until the end of the line

(Vim regexes are not always the same as in Perl, but this particular one is.)

You could define a mapping for that second search by putting this in your .vimrc:

noremap <Leader>nb /{[^}]*$<CR>

That would let you jump to the next block by pressing <Leader> (\ by default) n b.

Since it uses :noremap, it affects Select mode too. You won’t want that if your <Leader> is a printable character (which it is by default). In that case, add the line sunmap <Leader>nb below the previous line to fix Select mode.

like image 138
Rory O'Kane Avatar answered Oct 10 '22 19:10

Rory O'Kane