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.
7
  • vim is good in syntax highlight, but very bad in autoformat. Maybe somebody will be able to say some useful. Until then, +1.
    – peterh
    Sep 1, 2014 at 9:10
  • @PeterHorvath Maybe there some tools can connect with vim, and make vim powerful... :)
    – Marslo
    Sep 1, 2014 at 9:17
  • @Marslo works for me. Do you have filetype plugin indent on in your vimrc and does set ft? return filetype=perl?
    – FDinoff
    Sep 1, 2014 at 18:37
  • Hi @FDinoff, This is my vimrc, the filetype plugin indent on has been set at line 110. Have you added some plugin for perl syntax?
    – Marslo
    Sep 2, 2014 at 1:46
  • 1
    @Marslo No. I can replicate the behavior with vim -u NONE -N a.pl -c 'filetype plugin indent on' -c 'filetype detect' which means its not my vim configuration. I'm running vim 7.4.258.
    – FDinoff
    Sep 2, 2014 at 2:09

3 Answers 3

6

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).

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.

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.

You must log in to answer this question.

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