]> git.donarmstrong.com Git - perltidy.git/blob - docs/stylekey.pod
upgrade to new version
[perltidy.git] / docs / stylekey.pod
1 =head1 Perltidy Style Key
2
3 When perltidy was first developed, the main parameter choices were the number
4 of indentation spaces and if the user liked cuddled else's.  As the number of
5 users has grown so has the number of parameters.  Now there are so many that it
6 can be difficult for a new user to find a good initial set.  This document is
7 one attempt to help with this problem, and some other suggestions are given at
8 the end.
9
10 Use this document to methodically find a starting set of perltidy parameters to
11 approximate your style.  We will be working on just one aspect of formatting at
12 a time.  Just read each question and select the best answer.  Enter your
13 parameters in a file named F<.perltidyrc> (examples are listed at the end).
14 Then move it to one of the places where perltidy will find it.  You can run
15 perltidy with the parameter B<-dpro> to see where these places are for your
16 system.
17
18 =head2 Before You Start
19
20 Before you begin, experiment using just C<perltidy filename.pl> on some
21 of your files.  From the results (which you will find in files with a
22 F<.tdy> extension), you will get a sense of what formatting changes, if
23 any, you'd like to make.  If the default formatting is acceptable, you
24 do not need a F<.perltidyrc> file.
25
26 =head2 Use as Filter?
27
28 Do you almost always want to run perltidy as a standard filter on just
29 one input file?  If yes, use B<-st> and B<-se>.  
30
31 =head2 Line Length Setting
32
33 Perltidy will set line breaks to prevent lines from exceeding the
34 maximum line length.  
35
36 Do you want the maximum line length to be 80 columns?  If no, use
37 B<-l=n>, where B<n> is the number of columns you prefer.
38
39 =head2 Indentation in Code Blocks
40
41 In the block below, the variable C<$anchor> is one indentation level deep
42 and is indented by 4 spaces as shown here: 
43
44     if ( $flag eq "a" ) {
45         $anchor = $header;
46     }  
47
48 If you want to change this to be a different number B<n> of spaces
49 per indentation level, use B<-i=n>.
50
51 =head2 Continuation Indentation
52
53 Look at the statement beginning with C<$anchor>:
54
55     if ( $flag eq "a" ) {
56         $anchor =
57           substr( $header, 0, 6 )
58           . substr( $char_list, $place_1, 1 )
59           . substr( $char_list, $place_2, 1 );
60     }
61
62 The statement is too long for the line length (80 characters by default), so it
63 has been broken into 4 lines.  The second and later lines have some extra
64 "continuation indentation" to help make the start of the statement easy to
65 find.  The default number of extra spaces is 2.  If you prefer a number n
66 different from 2, you may specify this with B<-ci=n>.  It is probably best if
67 it does not exceed the value of the primary indentation.
68
69 =head2 Tabs
70
71 The default, and recommendation, is to represent leading whitespace
72 with actual space characters.  However, if you prefer to entab
73 leading whitespace with one tab character for each B<n> spaces,
74 use B<-et=n>.  Typically, B<n> would be 8.  
75
76 =head2 Opening Block Brace Right or Left?
77
78 Opening and closing curly braces, parentheses, and square brackets are divided
79 into two separate categories and controlled separately in most cases.  The two
80 categories are (1) code block curly braces, which contain perl code, and (2)
81 everything else.  Basically, a code block brace is one which could contain
82 semicolon-terminated lines of perl code.  We will first work on the scheme for
83 code block curly braces.  
84
85 Decide which of the following opening brace styles you prefer for most blocks
86 of code (with the possible exception of a B<sub block brace> which will
87 be covered later):
88
89 If you like opening braces on the right, like this, go to 
90 L<Opening Braces Right>.
91
92     if ( $flag eq "h" ) {
93         $headers = 0;
94     }  
95
96 If you like opening braces on the left, like this, go to 
97 L<Opening Braces Left>.
98
99     if ( $flag eq "h" )
100     {
101         $headers = 0;
102     }
103
104 =head2 Opening Braces Right
105
106 In a multi-line B<if> test expression, the default is to place
107 the opening brace on the left, like this:
108
109     if ( $bigwasteofspace1 && $bigwasteofspace2
110         || $bigwasteofspace3 && $bigwasteofspace4 )
111     {
112         big_waste_of_time();
113     }
114
115 This helps to visually separate the block contents from the test
116 expression.  
117
118 An alternative is to keep the brace on the right even for
119 multiple-line test expressions, like this:
120
121     if ( $bigwasteofspace1 && $bigwasteofspace2
122         || $bigwasteofspace3 && $bigwasteofspace4 ) {
123         big_waste_of_time();
124     }
125
126 If you prefer this alternative, use B<-bar>.
127
128 =head2 Cuddled Else?
129
130 Do you prefer this B<Cuddled Else> style
131
132     if ( $flag eq "h" ) {
133         $headers = 0;
134     } elsif ( $flag eq "f" ) {
135         $sectiontype = 3;
136     } else {
137         print "invalid option: " . substr( $arg, $i, 1 ) . "\n";
138         dohelp();
139     }
140
141 instead of this default style?
142
143     if ( $flag eq "h" ) {
144         $headers = 0;
145     }  
146     elsif ( $flag eq "f" ) {
147         $sectiontype = 3;
148     } 
149     else {    
150         print "invalid option: " . substr( $arg, $i, 1 ) . "\n";
151         dohelp();
152     }
153
154 If yes, you should use B<-ce>.
155 Now skip ahead to L<Opening Sub Braces>.
156
157 =head2 Opening Braces Left
158
159 Use B<-bl> if you prefer this style:
160
161     if ( $flag eq "h" )
162     {
163         $headers = 0;
164     }
165
166 Use B<-bli> if you prefer this indented-brace style:
167
168     if ( $flag eq "h" )
169       {
170         $headers = 0;
171       }
172
173 The number of spaces of extra indentation will be the value specified
174 for continuation indentation with the B<-ci=n> parameter (2 by default).
175
176 =head2 Opening Sub Braces
177
178 By default, the opening brace of a sub block will be treated
179 the same as other code blocks.  If this is okay, skip ahead
180 to L<Block Brace Vertical Tightness>.
181
182 If you prefer an opening sub brace to be on a new line,
183 like this: 
184
185     sub message
186     {
187         # -sbl
188     }
189
190 use B<-sbl>.  If you prefer the sub brace on the right like this
191
192     sub message {
193
194         # -nsbl
195     }
196
197 use B<-nsbl>.
198
199 If you wish to give this opening sub brace some indentation you can do
200 that with the parameters B<-bli> and B<-blil> which are described in the
201 manual.
202
203 =head2 Block Brace Vertical Tightness
204
205 If you chose to put opening block braces of all types to the right, skip
206 ahead to L<Closing Block Brace Indentation>.
207
208 If you chose to put braces of any type on the left, the default is to leave the
209 opening brace on a line by itself, like this (shown for B<-bli>, but also true
210 for B<-bl>):
211
212     if ( $flag eq "h" )
213       {
214         $headers = 0;
215       }
216
217 But you may also use this more compressed style if you wish:
218
219     if ( $flag eq "h" )
220       { $headers = 0;
221       }
222
223 If you do not prefer this more compressed form, go to 
224 L<Opening Sub Braces>.
225
226 Otherwise use parameter B<-bbvt=n>, where n=1 or n=2.  To decide,
227 look at this snippet:
228
229     # -bli -bbvt=1
230     sub _directives
231       {
232         {
233             'ENDIF' => \&_endif,
234                'IF' => \&_if,
235         };
236       }
237
238     # -bli -bbvt=2
239     sub _directives
240     {   {
241             'ENDIF' => \&_endif,
242             'IF'    => \&_if,
243         };
244     }
245
246 The difference is that B<-bbvt=1> breaks after an opening brace if
247 the next line is unbalanced, whereas B<-bbvt=2> never breaks.  
248
249 If you were expecting the 'ENDIF' word to move up vertically here, note that
250 the second opening brace in the above example is not a code block brace (it is
251 a hash brace), so the B<-bbvt> does not apply to it (another parameter will).
252
253 =head2 Closing Block Brace Indentation
254
255 The default is to place closing braces at the same indentation as the
256 opening keyword or brace of that code block, as shown here:
257
258         if ($task) {
259             yyy();
260         }            # default
261
262 If you chose the B<-bli> style, however, the default closing braces will be
263 indented one continuation indentation like the opening brace:
264
265         if ($task)
266           {
267             yyy();
268           }    # -bli
269
270 If you prefer to give closing block braces one full level of
271 indentation, independently of how the opening brace is treated,
272 for example like this:
273
274         if ($task) {
275             yyy();
276             }          # -icb
277
278 use B<-icb>.
279
280 This completes the definition of the placement of code block braces.
281
282 =head2 Indentation Style for Other Containers
283
284 You have a choice of two basic indentation schemes for non-block containers.
285 The default is to use a fixed number of spaces per indentation level (the same
286 number of spaces used for code blocks, which is 4 by default).  Here is an
287 example of the default:
288
289     $dbh = DBI->connect(
290         undef, undef, undef,
291         {
292             PrintError => 0,
293             RaiseError => 1
294         }
295     );
296
297 In this default indentation scheme, a simple formula is used to find the
298 indentation of every line.  Notice how the first 'undef' is indented 4
299 spaces (one level) to the right, and how 'PrintError' is indented 4 more
300 speces (one more level) to the right.  
301
302 The alternate is to let the location of the opening paren (or square
303 bracket, or curly brace) define the indentation, like this:
304
305     $dbh = DBI->connect(
306                          undef, undef, undef,
307                          {
308                            PrintError => 0,
309                            RaiseError => 1
310                          }
311     );
312
313 The first scheme is completely robust.  The second scheme often looks a little
314 nicer, but be aware that deeply nested structures it can be spoiled if the line
315 length limit is exceeded.  Also, if there are comments or blank lines within a
316 complex structure perltidy will temporarily fall back on the default
317 indentation scheme.  You may want to try both on large sections of code to see
318 which works best.
319
320 If you prefer the first (default) scheme, no parameter is needed.
321
322 If you prefer the latter scheme, use B<-lp>. 
323
324 =head2 Opening Vertical Tightness
325
326 The information in this section applies mainly to the B<-lp>
327 style but it also applies in some cases to the default style.
328 It will be illustrated for the B<-lp> indentation style.
329
330 The default B<-lp> indentation style ends a line at the
331 opening tokens, like this:
332
333     $dbh = DBI->connect(
334                          undef, undef, undef,
335                          {
336                            PrintError => 0,
337                            RaiseError => 1
338                          }
339     );
340
341 Here is a tighter alternative, which does not end a line
342 with the opening tokens:
343
344     $dbh = DBI->connect( undef, undef, undef,
345                          { PrintError => 0,
346                            RaiseError => 1
347                          }
348     );
349
350 The difference is that the lines have been compressed vertically without
351 any changes to the indentation.  This can almost always be done with the
352 B<-lp> indentation style, but only in limited cases for the default
353 indentation style. 
354
355 If you prefer the default, skip ahead to L<Closing Token Placement>.
356
357 Otherwise, use B<-vt=n>, where B<n> should be either 1 or 2.  To help
358 decide, observe the first three opening parens in the following snippet
359 and choose the value of n you prefer.  Here it is with B<-lp -vt=1>:
360
361     if (
362          !defined(
363                    start_slip( $DEVICE, $PHONE,  $ACCOUNT, $PASSWORD,
364                                $LOCAL,  $REMOTE, $NETMASK, $MTU
365                    )
366          )
367          && $continuation_flag
368       )
369     {
370         do_something_about_it();
371     }
372
373 And here it is again formatted with B<-lp -vt=2>:
374
375     if ( !defined( start_slip( $DEVICE, $PHONE,  $ACCOUNT, $PASSWORD,
376                                $LOCAL,  $REMOTE, $NETMASK, $MTU
377                    )
378          )
379          && $continuation_flag
380       )
381     {
382         do_something_about_it();
383     }
384
385 The B<-vt=1> style tries to display the structure by preventing more
386 than one step in indentation per line. In this example, the first two
387 opening parens were not followed by balanced lines, so B<-vt=1> broke
388 after them.  
389
390 The B<-vt=2> style does not limit itself to a single indentation step
391 per line.
392
393 Note that in the above example the function 'do_sumething_about_it'
394 started on a new line. This is because it follows an opening code
395 block brace and is governed by the flag previously set in 
396 L<Block Brace Vertical Tightness>.
397
398 =head2 Closing Token Placement
399
400 You have several options for dealing with the terminal closing tokens of
401 non-blocks.  In the following examples, a closing parenthesis is shown, but
402 these parameters apply to closing square brackets and non-block curly braces as
403 well.  
404
405 The default behavior for parenthesized relatively large lists is to place the
406 closing paren on a separate new line.  The flag B<-cti=n> controls the amount
407 of indentation of such a closing paren.
408
409 The default, B<-cti=0>, for a line beginning with a closing paren, is to use
410 the indentation defined by the next (lower) indentation level.  This works
411 well for the default indentation scheme:
412
413     # perltidy
414     @month_of_year = (
415         'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
416         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
417     );
418
419 but it may not look very good with the B<-lp> indentation scheme:
420
421     # perltidy -lp
422     @month_of_year = (
423                        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
424                        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
425     );
426
427 An alternative which works well with B<-lp> indentation is B<-cti=1>,
428 which aligns the closing paren vertically with its
429 opening paren, if possible:  
430
431     # perltidy -lp -cti=1
432     @month_of_year = (
433                        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
434                        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
435                      );
436
437 Another alternative, B<-cti=3>, indents a line with leading closing
438 paren one full indentation level:
439
440     # perltidy -lp -cti=3
441     @month_of_year = (
442                        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
443                        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
444                        );
445
446 If you prefer the closing paren on a separate line like this, 
447 note the value of B<-cti=n> that you prefer and skip ahead to 
448 L<Define Horizontal Tightness>. 
449
450 Finally, the question of paren indentation can be avoided by placing it
451 at the end of the previous line, like this:
452
453     @month_of_year = (
454         'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
455         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
456
457 Perltidy will automatically do this to save space for very short lists but not
458 for longer lists.
459
460 Use B<-vtc=n> if you prefer to usually do this, where B<n> is either 1 or 2. To
461 determine B<n>, we have to look at something more complex.  Observe the
462 behavior of the closing tokens in the following snippet:
463
464 Here is B<-lp -vtc=1>:
465
466     $srec->{'ACTION'} = [
467                           $self->read_value(
468                                              $lookup->{'VFMT'},
469                                              $loc, $lookup, $fh
470                           ),
471                           $self->read_value(
472                                              $lookup->{'VFMT2'},
473                                              $loc, $lookup, $fh
474                           ) ];
475
476 Here is B<-lp -vtc=2>:
477
478     $srec->{'ACTION'} = [
479                           $self->read_value(
480                                              $lookup->{'VFMT'},
481                                              $loc, $lookup, $fh ),
482                           $self->read_value(
483                                              $lookup->{'VFMT2'},
484                                              $loc, $lookup, $fh ) ];
485
486 Choose the one that you prefer.  The difference is that B<-vtc=1> leaves
487 closing tokens at the start of a line within a list, which can assist in
488 keeping hierarchical lists readable.  The B<-vtc=2> style always tries
489 to move closing tokens to the end of a line.  
490
491 If you choose B<-vtc=1>,
492 you may also want to specify a value of B<-cti=n> (previous section) to
493 handle cases where a line begins with a closing paren.
494
495 =head2 Stack Opening Tokens
496
497 In the following snippet the opening hash brace has been placed
498 alone on a new line.  
499
500     $opt_c = Text::CSV_XS->new(
501         {
502             binary       => 1,
503             sep_char     => $opt_c,
504             always_quote => 1,
505         }
506     );
507
508 If you prefer to avoid isolated opening opening tokens by
509 "stacking" them together with other opening tokens like this:
510
511     $opt_c = Text::CSV_XS->new( {
512             binary       => 1,
513             sep_char     => $opt_c,
514             always_quote => 1,
515         }
516     );
517
518 use B<-sot>.
519
520 =head2 Stack Closing Tokens
521
522 Likewise, in the same snippet the default formatting leaves
523 the closing paren on a line by itself here:
524
525     $opt_c = Text::CSV_XS->new(
526         {
527             binary       => 1,
528             sep_char     => $opt_c,
529             always_quote => 1,
530         }
531     );
532
533 If you would like to avoid leaving isolated closing tokens by
534 stacking them with other closing tokens, like this:
535
536     $opt_c = Text::CSV_XS->new(
537         {
538             binary       => 1,
539             sep_char     => $opt_c,
540             always_quote => 1,
541         } );
542
543 use B<-sct>.
544
545 The B<-sct> flag is somewhat similar to the B<-vtc> flags, and in some cases it
546 can give a similar result.  The difference is that the B<-vtc> flags try to
547 avoid lines with leading opening tokens by "hiding" them at the end of a
548 previous line, whereas the B<-sct> flag merely tries to reduce the number of
549 lines with isolated closing tokens by stacking multiple closing tokens
550 together, but it does not try to hide them.  
551
552 The manual shows how all of these vertical tightness controls may be applied
553 independently to each type of non-block opening and opening token.
554
555 =head2 Define Horizontal Tightness
556
557 Horizontal tightness parameters define how much space is included
558 within a set of container tokens.
559
560 For parentheses, decide which of the following values of B<-pt=n>
561 you prefer: 
562
563  if ( ( my $len_tab = length( $tabstr ) ) > 0 ) {  # -pt=0
564  if ( ( my $len_tab = length($tabstr) ) > 0 ) {    # -pt=1 (default)
565  if ((my $len_tab = length($tabstr)) > 0) {        # -pt=2
566
567 For n=0, space is always used, and for n=2, space is never used.  For
568 the default n=1, space is used if the parentheses contain more than
569 one token.
570
571 For square brackets, decide which of the following values of B<-sbt=n>
572 you prefer:
573
574  $width = $col[ $j + $k ] - $col[ $j ];  # -sbt=0
575  $width = $col[ $j + $k ] - $col[$j];    # -sbt=1 (default)
576  $width = $col[$j + $k] - $col[$j];      # -sbt=2 
577
578 For curly braces, decide which of the following values of B<-bt=n>
579 you prefer:
580
581  $obj->{ $parsed_sql->{ 'table' }[0] };    # -bt=0
582  $obj->{ $parsed_sql->{'table'}[0] };      # -bt=1 (default)
583  $obj->{$parsed_sql->{'table'}[0]};        # -bt=2
584
585 For code block curly braces, decide which of the following values of
586 B<-bbt=n> you prefer: 
587
588  %bf = map { $_ => -M $_ } grep { /\.deb$/ } dirents '.'; # -bbt=0 (default)
589  %bf = map { $_ => -M $_ } grep {/\.deb$/} dirents '.';   # -bbt=1
590  %bf = map {$_ => -M $_} grep {/\.deb$/} dirents '.';     # -bbt=2
591
592 =head2 Spaces between function names and opening parens
593
594 The default is not to place a space after a function call:
595
596   myfunc( $a, $b, $c );    # default 
597
598 If you prefer a space:
599
600   myfunc ( $a, $b, $c );   # -sfp
601
602 use B<-sfp>.
603
604 =head2 Spaces between Perl keywords and parens
605
606 The default is to place a space between only these keywords
607 and an opening paren:
608
609    my local our and or eq ne if else elsif until unless 
610    while for foreach return switch case given when
611
612 but no others. For example, the default is:
613
614     $aa = pop(@bb);
615
616 If you want a space between all Perl keywords and an opening paren,
617
618     $aa = pop (@bb);
619
620 use B<-skp>.  For detailed control of individual keywords, see the manual.
621
622 =head2 Statement Termination Semicolon Spaces
623
624 The default is not to put a space before a statement termination
625 semicolon, like this:
626
627     $i = 1;
628
629 If you prefer a space, like this:
630
631     $i = 1 ; 
632
633 enter B<-sts>.
634
635 =head2 For Loop Semicolon Spaces
636
637 The default is to place a space before a semicolon in a for statement,
638 like this:
639
640  for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) {  # -sfs (default)
641
642 If you prefer no such space, like this:
643
644  for ( @a = @$ap, $u = shift @a; @a; $u = $v ) {    # -nsfs
645
646 enter B<-nsfs>.
647
648 =head2 Block Comment Indentation
649
650 Block comments are comments which occupy a full line, as opposed to side
651 comments.  The default is to indent block comments with the same
652 indentation as the code block that contains them (even though this
653 will allow long comments to exceed the maximum line length). 
654
655 If you would like block comments indented except when this would cause
656 the maximum line length to be exceeded, use B<-olc>.  This will cause a
657 group of consecutive block comments to be outdented by the amount needed
658 to prevent any one from exceeding the maximum line length. 
659
660 If you never want block comments indented, use B<-nibc>.
661
662 If block comments may only be indented if they have some space
663 characters before the leading C<#> character in the input file, use
664 B<-isbc>.
665
666 The manual shows many other options for controlling comments.
667
668 =head2 Outdenting Long Quotes
669
670 Long quoted strings may exceed the specified line length limit.  The
671 default, when this happens, is to outdent them to the first column.
672 Here is an example of an outdented long quote:
673
674         if ($source_stream) {
675             if ( @ARGV > 0 ) {
676                 die
677  "You may not specify any filenames when a source array is given\n";
678             }
679         }
680
681 The effect is not too different from using a here document to represent
682 the quote.  If you prefer to leave the quote indented, like this:
683
684         if ($source_stream) {
685             if ( @ARGV > 0 ) {
686                 die
687                   "You may not specify any filenames when a source array is given\n";
688             }
689         }
690
691 use B<-nolq>.
692
693 =head2 Many Other Parameters
694
695 This document has only covered the most popular parameters.  The manual
696 contains many more and should be consulted if you did not find what you need
697 here.
698
699 =head2 Example F<.perltidyrc> files
700
701 Now gather together all of the parameters you prefer and enter them
702 in a file called F<.perltidyrc>.
703
704 Here are some example F<.perltidyrc> files and the corresponding style.
705
706 Here is a little test snippet, shown the way it would appear with
707 the default style.
708
709     for (@methods) {
710         push (
711             @results,
712             {
713                 name => $_->name,
714                 help => $_->help,
715             }
716         );
717     }
718
719 You do not need a F<.perltidyrc> file for this style.
720
721 Here is the same snippet
722
723     for (@methods)
724     {
725         push(@results,
726              {  name => $_->name,
727                 help => $_->help,
728              }
729             );
730     }
731
732 for a F<.perltidyrc> file containing these parameters:
733
734  -bl
735  -lp
736  -cti=1
737  -vt=1
738  -pt=2
739
740 You do not need to place just one parameter per line, but this may be
741 convenient for long lists.  You may then hide any parameter by placing
742 a C<#> symbol before it.
743
744 And here is the snippet
745
746     for (@methods) {
747         push ( @results,
748                { name => $_->name,
749                  help => $_->help,
750                } );
751     }
752
753 for a F<.perltidyrc> file containing these parameters:
754
755  -lp
756  -vt=1
757  -vtc=1
758
759 =head2 Tidyview
760
761 There is a graphical program called B<tidyview> which you can use to read a
762 preliminary F<.perltidyrc> file, make trial adjustments and immediately see
763 their effect on a test file, and then write a new F<.perltidyrc>.  You can
764 download a copy at
765
766 http://sourceforge.net/projects/tidyview
767
768 =head2 Additional Information
769
770 This document has covered the main parameters.  Many more parameters are
771 available for special purposes and for fine-tuning a style.  For complete
772 information see the perltidy manual
773 http://perltidy.sourceforge.net/perltidy.html
774
775 For an introduction to using perltidy, see the tutorial 
776 http://perltidy.sourceforge.net/tutorial.html
777
778 Suggestions for improving this document are welcome and may be sent to
779 perltidy at users.sourceforge.net
780
781 =cut