tags:

views:

348

answers:

4

At my current job, we have coding-style standards that are different from the ones I normally follow. Fortunately, we have a canned RC file for perltidy that I can apply to reformat files before I submit them to our review process.

I have code for emacs that I use to run a command over a buffer and replace the buffer with the output, which I have adapted for this. But I sometimes alternate between emacs and vim, and would like to have the same capabilities there. I'm sure that this or something similar is simple and had been done and re-done many times over. But I've not had much luck finding any examples of vim-script that seem to do what I need. Which is, in essence, to be able to hit a key combo (like Ctrl-F6, what I use in emacs) and have the buffer be reformatted in-place by perltidy. While I'm a comfortable vim-user, I'm completely clueless at writing this sort of thing for vim.

+2  A: 

The command to filter the entire buffer through an external program is:

:%!command

Put the following in ~/.vimrc to bind it to Ctrl-F6 in normal mode:

:nmap <C-F6> :%!command<CR>

EDIT:

For added fun:

:au Filetype perl nmap <C-F6> :%!command<CR>

This will only map the filter if editing a Perl file.

Ignacio Vazquez-Abrams
Remove the initial : if putting it in .vimrc. It's only needed for starting a command line within the editor.
Philip Potter
+3  A: 

My tidy command:

command -range=% -nargs=* Tidy <line1>,<line2>!
  \perltidy (your default options go here) <args>

If you use a visual selection or provide a range then it will tidy the selected range, otherwise it will use the whole file. You can put a set of default options (if you have any) at the point where I wrote (your default options go here), but any arguments that you provide to :Tidy will be appended to the perltidy commandline, overriding your defaults. (If you use a .perltidyrc you might not have default args -- that's fine -- but then again you might want to have a default like --profile=vim that sets up defaults only for when you're working in vim. Whatever works.)

hobbs
A: 

I'm used to select text using line oriented visual Shift+V and then I press : an I have !perltidy -pbp -et4 somewhere in history so I hit once or more up arrow.

Hynek -Pichi- Vychodil
+2  A: 

Taking hobbs' answer a step further, you can map that command to a shortcut key:

command -range=% -nargs=* Tidy <line1>,<line2>!perltidy -q
noremap <C-F6> :Tidy<CR>

And another step further: Only map the command when you're in a Perl buffer (since you probably wouldn't want to run perltidy on any other language):

autocmd BufRead,BufNewFile *.pl,*.plx,*.pm command! -range=% -nargs=* Tidy <line1>,<line2>!perltidy -q
autocmd BufRead,BufNewFile *.pl,*.plx,*.pm noremap <C-F6> :Tidy<CR>

Now you can press Ctrl-F6 without an active selection to format the whole file, or with an active selection to format just that section.

mkerley