Friday, May 9, 2014

"Prettify" Fortran Code

Some Fortran code that I wrote a long time ago looks downright ugly to my eyes today. Interestingly, the direction of this trend is the opposite of my handwriting, which has gotten progressively more illegible.

Anyway, wouldn't it be nice of one could pick some old Fortran 90 code, and deck it up by consistent indentation, proper alignment of comments, and getting all keywords in the same case (upper or lower or whatever).

Fortunately, there is a program which does just that. It is called f90ppr, which is actually a fortran program itself written by Michael Olagnon. It is also mirrored over here. You only need the f90ppr.f90 program, and perhaps f90ppr.1 (which is a man page that can be read by typing man f90ppr.1 on a unix type system).

Compile the f90ppr.f90 program (gfortran f90ppr.f90 -o f90ppr), and you are ready to "prettify".

Suppose you start with a lousy unindented program like this.

Note that you can "unindent" any inconsistently indented program on an editor like Geany by selecting all, and repeatedly pressing Shift+Tab.

The next step is to manually add the following lines to the top of the "unindented" program. These are line that direct f90ppr to do the needful.

$define FPPR_MAX_LINE 100
$define FPPR_USR_CASE 0
$define FPPR_FXD_IN 0
$define FPPR_FXD_OUT 0

It sets up the max number of columns (100), treatment of keywords (lower), tab size (4 spaces) etc. The manual has details of other options.

With this lines pasted in the header of the ugly.f90 program, you say

./f90ppr < ugly.f90 > pretty.f90

And you are set. Here is the result.

It adds a "!" on  all empty lines. If you find that pesky, you can clean it up easily with the following sed script:

sed 's/^!$//g' pretty.f90

No comments: