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