8.8.3 ptopu unit

The source of the PtoP program is conveniently split in two files: one is a unit containing an object that does the actual beautifying of the source, the other is a shell built around this object so it can be used from the command line. This design makes it possible to include the object in a program (e.g. an IDE) and use its features to format code.

The object resides in the PtoPU unit, and is declared as follows

  TPrettyPrinter=Object(TObject)  
      Indent : Integer;    { How many characters to indent ? }  
      InS    : PStream;  
      OutS   : PStream;  
      DiagS  : PStream;  
      CfgS : PStream;  
      Constructor Create;  
      Function PrettyPrint : Boolean;  
    end;

Using this object is very simple. The procedure is as follows:

1.
Create the object, using its constructor.
2.
Set the InS stream. This is an open stream, from which Pascal source will be read. This is a mandatory step.
3.
Set the OutS stream. This is an open stream, to which the beautified Pascal source will be written. This is a mandatory step.
4.
Set the DiagS stream. Any diagnostics will be written to this stream. This step is optional. If you don’t set this, no diagnostics are written.
5.
Set the CfgS stream. A configuration is read from this stream. (see the previous section for more information about configuration). This step is optional. If you don’t set this, a default configuration is used.
6.
Set the Indent variable. This is the number of spaces to use when indenting. Tab characters are not used in the program. This step is optional. The indent variable is initialized to 2.
7.
Call PrettyPrint. This will pretty-print the source in InS and write the result to OutS. The function returns True if no errors occurred, False otherwise.

So, a minimal procedure would be:

Procedure CleanUpCode;  
 
var  
  Ins,OutS : PBufStream;  
  PPRinter : TPrettyPrinter;  
 
begin  
  Ins:=New(PBufStream,Init(’ugly.pp’,StopenRead,TheBufSize));  
  OutS:=New(PBufStream,Init(’beauty.pp’,StCreate,TheBufSize));  
  PPrinter.Create;  
  PPrinter.Ins:=Ins;  
  PPrinter.outS:=OutS;  
  PPrinter.PrettyPrint;  
end;

Using memory streams allows very fast formatting of code, and is particularly suitable for editors.