]> git.donarmstrong.com Git - perltidy.git/blob - lib/Perl/Tidy.pod
New upstream version 20210717
[perltidy.git] / lib / Perl / Tidy.pod
1 =head1 NAME
2
3 Perl::Tidy - Parses and beautifies perl source
4
5 =head1 SYNOPSIS
6
7     use Perl::Tidy;
8
9     my $error_flag = Perl::Tidy::perltidy(
10         source            => $source,
11         destination       => $destination,
12         stderr            => $stderr,
13         argv              => $argv,
14         perltidyrc        => $perltidyrc,
15         logfile           => $logfile,
16         errorfile         => $errorfile,
17         teefile           => $teefile,
18         debugfile         => $debugfile,
19         formatter         => $formatter,           # callback object (see below)
20         dump_options      => $dump_options,
21         dump_options_type => $dump_options_type,
22         prefilter         => $prefilter_coderef,
23         postfilter        => $postfilter_coderef,
24     );
25
26 =head1 DESCRIPTION
27
28 This module makes the functionality of the perltidy utility available to perl
29 scripts.  Any or all of the input parameters may be omitted, in which case the
30 @ARGV array will be used to provide input parameters as described
31 in the perltidy(1) man page.
32
33 For example, the perltidy script is basically just this:
34
35     use Perl::Tidy;
36     Perl::Tidy::perltidy();
37
38 The call to B<perltidy> returns a scalar B<$error_flag> which is TRUE if an
39 error caused premature termination, and FALSE if the process ran to normal
40 completion.  Additional discuss of errors is contained below in the L<ERROR
41 HANDLING> section.
42
43 The module accepts input and output streams by a variety of methods.
44 The following list of parameters may be any of the following: a
45 filename, an ARRAY reference, a SCALAR reference, or an object with
46 either a B<getline> or B<print> method, as appropriate.
47
48         source            - the source of the script to be formatted
49         destination       - the destination of the formatted output
50         stderr            - standard error output
51         perltidyrc        - the .perltidyrc file
52         logfile           - the .LOG file stream, if any 
53         errorfile         - the .ERR file stream, if any
54         dump_options      - ref to a hash to receive parameters (see below), 
55         dump_options_type - controls contents of dump_options
56         dump_getopt_flags - ref to a hash to receive Getopt flags
57         dump_options_category - ref to a hash giving category of options
58         dump_abbreviations    - ref to a hash giving all abbreviations
59
60 The following chart illustrates the logic used to decide how to
61 treat a parameter.
62
63    ref($param)  $param is assumed to be:
64    -----------  ---------------------
65    undef        a filename
66    SCALAR       ref to string
67    ARRAY        ref to array
68    (other)      object with getline (if source) or print method
69
70 If the parameter is an object, and the object has a B<close> method, that
71 close method will be called at the end of the stream.
72
73 =over 4
74
75 =item source
76
77 If the B<source> parameter is given, it defines the source of the input stream.
78 If an input stream is defined with the B<source> parameter then no other source
79 filenames may be specified in the @ARGV array or B<argv> parameter.
80
81 =item destination
82
83 If the B<destination> parameter is given, it will be used to define the
84 file or memory location to receive output of perltidy.  
85
86 =item stderr
87
88 The B<stderr> parameter allows the calling program to redirect the stream that
89 would otherwise go to the standard error output device to any of the stream
90 types listed above.  This stream contains important warnings and errors 
91 related to the parameters passed to perltidy.
92
93 =item perltidyrc
94
95 If the B<perltidyrc> file is given, it will be used instead of any
96 F<.perltidyrc> configuration file that would otherwise be used. 
97
98 =item errorfile
99
100 The B<errorfile> parameter allows the calling program to capture
101 the stream that would otherwise go to either a .ERR file.  This
102 stream contains warnings or errors related to the contents of one
103 source file or stream. 
104
105 The reason that this is different from the stderr stream is that when perltidy
106 is called to process multiple files there will be up to one .ERR file created
107 for each file and it would be very confusing if they were combined.  
108
109 However if perltidy is called to process just a single perl script then it may
110 be more convenient to combine the B<errorfile> stream with the B<stderr>
111 stream.  This can be done by setting the B<-se> parameter, in which case this
112 parameter is ignored.
113
114 =item logfile
115
116 The B<logfile> parameter allows the calling program to capture the log stream.
117 This stream is only created if requested with a B<-g> parameter.  It contains
118 detailed diagnostic information about a script which may be useful for
119 debugging.
120
121 =item teefile
122
123 The B<teefile> parameter allows the calling program to capture the tee stream.
124 This stream is only created if requested with one of the 'tee' parameters,
125 a B<--tee-pod> , B<--tee-block-comments>, B<--tee-side-commnts>, or B<--tee-all-comments>.
126
127 =item debugfile
128
129 The B<debugfile> parameter allows the calling program to capture the stream
130 produced by the B<--DEBUG> parameter.  This parameter is mainly used for 
131 debugging perltidy itself.
132
133 =item argv
134
135 If the B<argv> parameter is given, it will be used instead of the
136 B<@ARGV> array.  The B<argv> parameter may be a string, a reference to a
137 string, or a reference to an array.  If it is a string or reference to a
138 string, it will be parsed into an array of items just as if it were a
139 command line string.
140
141 =item dump_options
142
143 If the B<dump_options> parameter is given, it must be the reference to a hash.
144 In this case, the parameters contained in any perltidyrc configuration file
145 will be placed in this hash and perltidy will return immediately.  This is
146 equivalent to running perltidy with --dump-options, except that the parameters
147 are returned in a hash rather than dumped to standard output.  Also, by default
148 only the parameters in the perltidyrc file are returned, but this can be
149 changed (see the next parameter).  This parameter provides a convenient method
150 for external programs to read a perltidyrc file.  An example program using
151 this feature, F<perltidyrc_dump.pl>, is included in the distribution.
152
153 Any combination of the B<dump_> parameters may be used together.
154
155 =item dump_options_type
156
157 This parameter is a string which can be used to control the parameters placed
158 in the hash reference supplied by B<dump_options>.  The possible values are
159 'perltidyrc' (default) and 'full'.  The 'full' parameter causes both the
160 default options plus any options found in a perltidyrc file to be returned.
161
162 =item dump_getopt_flags
163
164 If the B<dump_getopt_flags> parameter is given, it must be the reference to a
165 hash.  This hash will receive all of the parameters that perltidy understands
166 and flags that are passed to Getopt::Long.  This parameter may be
167 used alone or with the B<dump_options> flag.  Perltidy will
168 exit immediately after filling this hash.  See the demo program
169 F<perltidyrc_dump.pl> for example usage.
170
171 =item dump_options_category
172
173 If the B<dump_options_category> parameter is given, it must be the reference to a
174 hash.  This hash will receive a hash with keys equal to all long parameter names
175 and values equal to the title of the corresponding section of the perltidy manual.
176 See the demo program F<perltidyrc_dump.pl> for example usage.
177
178 =item dump_abbreviations
179
180 If the B<dump_abbreviations> parameter is given, it must be the reference to a
181 hash.  This hash will receive all abbreviations used by Perl::Tidy.  See the
182 demo program F<perltidyrc_dump.pl> for example usage.
183
184 =item prefilter
185
186 A code reference that will be applied to the source before tidying. It is
187 expected to take the full content as a string in its input, and output the
188 transformed content.
189
190 =item postfilter
191
192 A code reference that will be applied to the tidied result before outputting.
193 It is expected to take the full content as a string in its input, and output
194 the transformed content.
195
196 Note: A convenient way to check the function of your custom prefilter and
197 postfilter code is to use the --notidy option, first with just the prefilter
198 and then with both the prefilter and postfilter.  See also the file
199 B<filter_example.pl> in the perltidy distribution.
200
201 =back
202
203 =head1 ERROR HANDLING
204
205 An exit value of 0, 1, or 2 is returned by perltidy to indicate the status of the result.
206
207 A exit value of 0 indicates that perltidy ran to completion with no error messages.
208
209 An exit value of 1 indicates that the process had to be terminated early due to
210 errors in the input parameters.  This can happen for example if a parameter is
211 misspelled or given an invalid value.  The calling program should check for
212 this flag because if it is set the destination stream will be empty or
213 incomplete and should be ignored.  Error messages in the B<stderr> stream will
214 indicate the cause of any problem.  
215
216 An exit value of 2 indicates that perltidy ran to completion but there there
217 are warning messages in the B<stderr> stream related to parameter errors or
218 conflicts and/or warning messages in the B<errorfile> stream relating to
219 possible syntax errors in the source code being tidied. 
220
221 In the event of a catastrophic error for which recovery is not possible
222 B<perltidy> terminates by making calls to B<croak> or B<confess> to help the
223 programmer localize the problem.  These should normally only occur during
224 program development.  
225
226 =head1 NOTES ON FORMATTING PARAMETERS
227
228 Parameters which control formatting may be passed in several ways: in a
229 F<.perltidyrc> configuration file, in the B<perltidyrc> parameter, and in the
230 B<argv> parameter.
231
232 The B<-syn> (B<--check-syntax>) flag may be used with all source and
233 destination streams except for standard input and output.  However 
234 data streams which are not associated with a filename will 
235 be copied to a temporary file before being passed to Perl.  This
236 use of temporary files can cause somewhat confusing output from Perl.
237
238 If the B<-pbp> style is used it will typically be necessary to also
239 specify a B<-nst> flag.  This is necessary to turn off the B<-st> flag
240 contained in the B<-pbp> parameter set which otherwise would direct
241 the output stream to the standard output.  
242
243 =head1 EXAMPLES
244
245 The following example uses string references to hold the input and output
246 code and error streams, and illustrates checking for errors.
247
248   use Perl::Tidy;
249   
250   my $source_string = <<'EOT';
251   my$error=Perl::Tidy::perltidy(argv=>$argv,source=>\$source_string,
252     destination=>\$dest_string,stderr=>\$stderr_string,
253   errorfile=>\$errorfile_string,);
254   EOT
255   
256   my $dest_string;
257   my $stderr_string;
258   my $errorfile_string;
259   my $argv = "-npro";   # Ignore any .perltidyrc at this site
260   $argv .= " -pbp";     # Format according to perl best practices
261   $argv .= " -nst";     # Must turn off -st in case -pbp is specified
262   $argv .= " -se";      # -se appends the errorfile to stderr
263   ## $argv .= " --spell-check";  # uncomment to trigger an error
264   
265   print "<<RAW SOURCE>>\n$source_string\n";
266   
267   my $error = Perl::Tidy::perltidy(
268       argv        => $argv,
269       source      => \$source_string,
270       destination => \$dest_string,
271       stderr      => \$stderr_string,
272       errorfile   => \$errorfile_string,    # ignored when -se flag is set
273       ##phasers   => 'stun',                # uncomment to trigger an error
274   );
275   
276   if ($error) {
277   
278       # serious error in input parameters, no tidied output
279       print "<<STDERR>>\n$stderr_string\n";
280       die "Exiting because of serious errors\n";
281   }
282   
283   if ($dest_string)      { print "<<TIDIED SOURCE>>\n$dest_string\n" }
284   if ($stderr_string)    { print "<<STDERR>>\n$stderr_string\n" }
285   if ($errorfile_string) { print "<<.ERR file>>\n$errorfile_string\n" }
286
287 Additional examples are given in examples section of the perltidy distribution.  
288
289 =head1 Using the B<formatter> Callback Object
290
291 The B<formatter> parameter is an optional callback object which allows
292 the calling program to receive tokenized lines directly from perltidy for
293 further specialized processing.  When this parameter is used, the two
294 formatting options which are built into perltidy (beautification or
295 html) are ignored.  The following diagram illustrates the logical flow:
296
297                     |-- (normal route)   -> code beautification
298   caller->perltidy->|-- (-html flag )    -> create html 
299                     |-- (formatter given)-> callback to write_line
300
301 This can be useful for processing perl scripts in some way.  The 
302 parameter C<$formatter> in the perltidy call,
303
304         formatter   => $formatter,  
305
306 is an object created by the caller with a C<write_line> method which
307 will accept and process tokenized lines, one line per call.  Here is
308 a simple example of a C<write_line> which merely prints the line number,
309 the line type (as determined by perltidy), and the text of the line:
310
311  sub write_line {
312  
313      # This is called from perltidy line-by-line
314      my $self              = shift;
315      my $line_of_tokens    = shift;
316      my $line_type         = $line_of_tokens->{_line_type};
317      my $input_line_number = $line_of_tokens->{_line_number};
318      my $input_line        = $line_of_tokens->{_line_text};
319      print "$input_line_number:$line_type:$input_line";
320  }
321
322 The complete program, B<perllinetype>, is contained in the examples section of
323 the source distribution.  As this example shows, the callback method
324 receives a parameter B<$line_of_tokens>, which is a reference to a hash
325 of other useful information.  This example uses these hash entries:
326
327  $line_of_tokens->{_line_number} - the line number (1,2,...)
328  $line_of_tokens->{_line_text}   - the text of the line
329  $line_of_tokens->{_line_type}   - the type of the line, one of:
330
331     SYSTEM         - system-specific code before hash-bang line
332     CODE           - line of perl code (including comments)
333     POD_START      - line starting pod, such as '=head'
334     POD            - pod documentation text
335     POD_END        - last line of pod section, '=cut'
336     HERE           - text of here-document
337     HERE_END       - last line of here-doc (target word)
338     FORMAT         - format section
339     FORMAT_END     - last line of format section, '.'
340     DATA_START     - __DATA__ line
341     DATA           - unidentified text following __DATA__
342     END_START      - __END__ line
343     END            - unidentified text following __END__
344     ERROR          - we are in big trouble, probably not a perl script
345
346 Most applications will be only interested in lines of type B<CODE>.  For
347 another example, let's write a program which checks for one of the
348 so-called I<naughty matching variables> C<&`>, C<$&>, and C<$'>, which
349 can slow down processing.  Here is a B<write_line>, from the example
350 program B<find_naughty.pl>, which does that:
351
352  sub write_line {
353  
354      # This is called back from perltidy line-by-line
355      # We're looking for $`, $&, and $'
356      my ( $self, $line_of_tokens ) = @_;
357  
358      # pull out some stuff we might need
359      my $line_type         = $line_of_tokens->{_line_type};
360      my $input_line_number = $line_of_tokens->{_line_number};
361      my $input_line        = $line_of_tokens->{_line_text};
362      my $rtoken_type       = $line_of_tokens->{_rtoken_type};
363      my $rtokens           = $line_of_tokens->{_rtokens};
364      chomp $input_line;
365  
366      # skip comments, pod, etc
367      return if ( $line_type ne 'CODE' );
368  
369      # loop over tokens looking for $`, $&, and $'
370      for ( my $j = 0 ; $j < @$rtoken_type ; $j++ ) {
371  
372          # we only want to examine token types 'i' (identifier)
373          next unless $$rtoken_type[$j] eq 'i';
374  
375          # pull out the actual token text
376          my $token = $$rtokens[$j];
377  
378          # and check it
379          if ( $token =~ /^\$[\`\&\']$/ ) {
380              print STDERR
381                "$input_line_number: $token\n";
382          }
383      }
384  }
385
386 This example pulls out these tokenization variables from the $line_of_tokens
387 hash reference:
388
389      $rtoken_type = $line_of_tokens->{_rtoken_type};
390      $rtokens     = $line_of_tokens->{_rtokens};
391
392 The variable C<$rtoken_type> is a reference to an array of token type codes,
393 and C<$rtokens> is a reference to a corresponding array of token text.
394 These are obviously only defined for lines of type B<CODE>.
395 Perltidy classifies tokens into types, and has a brief code for each type.
396 You can get a complete list at any time by running perltidy from the
397 command line with
398
399      perltidy --dump-token-types
400
401 In the present example, we are only looking for tokens of type B<i>
402 (identifiers), so the for loop skips past all other types.  When an
403 identifier is found, its actual text is checked to see if it is one
404 being sought.  If so, the above write_line prints the token and its
405 line number.
406
407 The B<formatter> feature is relatively new in perltidy, and further
408 documentation needs to be written to complete its description.  However,
409 several example programs have been written and can be found in the
410 B<examples> section of the source distribution.  Probably the best way
411 to get started is to find one of the examples which most closely matches
412 your application and start modifying it.
413
414 For help with perltidy's peculiar way of breaking lines into tokens, you
415 might run, from the command line, 
416
417  perltidy -D filename
418
419 where F<filename> is a short script of interest.  This will produce
420 F<filename.DEBUG> with interleaved lines of text and their token types.
421 The B<-D> flag has been in perltidy from the beginning for this purpose.
422 If you want to see the code which creates this file, it is
423 C<write_debug_entry> in Tidy.pm.
424
425 =head1 EXPORT
426
427   &perltidy
428
429 =head1 INSTALLATION
430
431 The module 'Perl::Tidy' comes with a binary 'perltidy' which is installed when the module is installed.  The module name is case-sensitive.  For example, the basic command for installing with cpanm is 'cpanm Perl::Tidy'.
432
433 =head1 VERSION
434
435 This man page documents Perl::Tidy version 20210717
436
437 =head1 LICENSE
438
439 This package is free software; you can redistribute it and/or modify it
440 under the terms of the "GNU General Public License".
441
442 Please refer to the file "COPYING" for details.
443
444 =head1 BUG REPORTS
445
446 A list of current bugs and issues can be found at the CPAN site L<https://rt.cpan.org/Public/Dist/Display.html?Name=Perl-Tidy>
447
448 To report a new bug or problem, use the link on this page.  
449
450 The source code repository is at L<https://github.com/perltidy/perltidy>.
451
452 =head1 SEE ALSO
453
454 The perltidy(1) man page describes all of the features of perltidy.  It
455 can be found at http://perltidy.sourceforge.net.
456
457 =cut