Reformatting text with Perl

Text::Autoformat | Perl::Tidy | JavaScript


For day-to-day text formatting needs, for example in e-mail messages or comments in code, I use Text::Autoformat via a custom autoformat script. This allows poorly formatted e-mails to be cleaned up in a hurry, or outgoing text to be reformatted without wasting time lining up lists or fixing long lines. Text::Autoformat works like the fmt(1) command, but offers more features and magic.

In vi, I hijack the T key to do formatting with a custom .exrc entry:

map T !Gautoformat

Under vim 6.3+, I use the keepmark entry to preserve marks across filters:

map T :keepmark .,$!autoformat

For BBEdit, I use a BBEdit filter.


Use Perl::Tidy to reformat Perl code, similar to indent(1) for C. This module includes a perltidy utility for command line use. Groups of coders should compromise on a standard format, as otherwise various individuals may write code in various styles, thereby needlessly increasing the effort required by others to read the code. Similar standards should also be implemented for code comments, documentation, and so forth.

Some time may need to be spent tweaking the code formatting options. I use the following defaults, set in ~/.perltidyrc.

# Custom prefs for the perltidy utility
# Output control
-st # output to STDOUT (so works with BBEdit or vi as Filter)
-se # errors to STDERR
-q # deativate error messages and syntax checking
-nsyn # no syntax checking

# Perl style preferences
-l=78 # max line length
-i=2 # indentation level
-ci=2 # continuation indentation level
-cti=0 # non-block closing indentation
-ce # else cuddling
-pt=1 # space within ()'s
-sbt=1 # space within []'s
-bt=1 # space within {}'s
-bbt=0 # block brace spacing
-nlp # line up stuff inside ()'s
-vt=2 # vertical tightness
-vtc=0 # ditto, closing
-nsfs # no space around ; in for loops
#-nasc # do not add missing optional ;
-bar # opening brace on right
-nbbc # no blanks before comments

In vi, I hijack the t key to quickly run the tidy (or again with keepmark for vim):

map t :%!perltidy

Mixing this with indent support is tricky:

if !exists("autocommands_loaded")
let autocommands_loaded = 1

au BufNewFile,BufRead *.c call SetupForC()

" TODO this busts t for perl file afterwards...
function SetupForC()
map t :keepmark %!indent -st

For BBEdit, I use a BBEdit filter.


Consider using the JavaScript::Beautifier Perl module to tidy JavaScript code.