6

I've got a piece of badly formatted Perl code:

if ($a==1){
   &err_report("$a");
while($b!=1){
                      &err_ok();
}
}

I want to reformat it in Vim. After using the command gg=G, the code is formatted as:

if ($a==1){
&err_report("$a");
while($b!=1){
&err_ok();
}
}

Actually, I want to format it in Vim as below:

if ($a==1){
  &err_report("$a");
  while($b!=1){
    &err_ok();
  }
}

What should I do?


  • After using vim-perl, the auto-formating still doesn't do what I want.
Kusalananda
  • 2,369
  • 18
  • 26
Marslo
  • 1,241

3 Answers3

7

Assuming you're on a Unix-like operating system...

Get hold of perltidy (a highly customizable Perl code indenter/formatter). Then update your ~/.vimrc file to include the following:

filetype plugin indent on
autocmd FileType perl setlocal equalprg=perltidy\ -st

This will allow you to mark whatever block of Perl code you want and then reformat it by pressing =. This assumes that perltidy is found in your $PATH, otherwise just specify the full path to the executable.

By default, perltidy will format your code as

if ( $a == 1 ) {
    &err_report("$a");
    while ( $b != 1 ) {
        &err_ok();
    }
}

... but by using -i=2 (--indent-columns=2) and -pt=2 (--paren-tightness=2) (you would put these options in your ~/.perltidyrc file, one per line) you get

if ($a == 1) {
  &err_report("$a");
  while ($b != 1) {
    &err_ok();
  }
}

This is pretty much what you asked for.

If you really must have no space after while, ever, use -nsak=while (--nospace-after-keyword=while).

Kusalananda
  • 2,369
  • 18
  • 26
0

Vim comes with a Perl indent plugin, and as long as you have :filetype indent on somewhere in your startup (such as your vimrc) it should be able to do indenting of Perl files for you. But note that it will only do indenting, it won't add or remove newlines.

Heptite
  • 20,411
0

First set the required formatting options, e.g., set cindent sw=2 expandtab (use C-like indentation, indent 2 spaces, expand tab character to spaces). Then indent the whole file/buffer.

Atafar
  • 151