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

      Indent : Integer;    { How many characters to indent ? }  
      InS    : PStream;  
      OutS   : PStream;  
      DiagS  : PStream;  
      CfgS : PStream;  
      Constructor Create;  
      Function PrettyPrint : Boolean;  

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

Create the object, using its constructor.
Set the InS stream. This is an open stream, from which Pascal source will be read. This is a mandatory step.
Set the OutS stream. This is an open stream, to which the beautified Pascal source will be written. This is a mandatory step.
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.
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.
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.
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;  
  Ins,OutS : PBufStream;  
  PPRinter : TPrettyPrinter;  

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