-
Notifications
You must be signed in to change notification settings - Fork 256
/
Autoformat.pm
1362 lines (1105 loc) · 41.3 KB
/
Autoformat.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Autoformat; # modified by JS: remove Text:: package
# See the bottom of this file for copyright and owner information.
# Modified by Jeremy Stribling to work with SCIgen, 2/2005.
use strict; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); use Carp;
use 5.005;
$VERSION = '1.12';
require Exporter;
# modified by JS: remove Text:: package
use Reform qw( form tag break_at break_with break_wrap break_TeX );
@ISA = qw(Exporter);
@EXPORT = qw( autoformat );
@EXPORT_OK =
qw( form tag break_at break_with break_wrap break_TeX ignore_headers );
my %ignore = map {$_=>1} qw {
a an at as and are
but by
ere
for from
in into is
of on onto or over
per
the to that than
until unto upon
via
with while whilst within without
};
my @entities = qw {
Á á Â â Æ æ
À à Α α Ã ã
Ä ä Β β Ç ç
Χ χ Δ δ É é
Ê ê È è Ε ε
Η η Ð ð Ë ë
Γ γ Í í Î î
Ì ì Ι ι Ï ï
Κ κ Λ λ Μ μ
Ñ ñ Ν ν Ó ó
Ô ô Œ œ Ò ò
Ω ω Ο ο Õ õ
Ö ö Φ φ Π π
″ ′ Ψ ψ Ρ ρ
Š š Σ σ Τ τ
Θ θ Þ þ Ú ú
Û û Ù ù Υ υ
Ü ü Ξ ξ Ý ý
Ÿ ÿ Ζ ζ
};
my %lower_entities = @entities;
my %upper_entities = reverse @entities;
my %casing = (
lower => [ \%lower_entities, \%lower_entities,
sub { $_ = lc }, sub { $_ = lc } ],
upper => [ \%upper_entities, \%upper_entities,
sub { $_ = uc }, sub { $_ = uc } ],
# modified by JS: no need to lowercase everything before the ucfirst
title => [ \%upper_entities, \%lower_entities,
sub { $_ = ucfirst }, sub { $_ = lc } ],
);
my $default_margin = 72;
my $default_widow = 10;
# modified by JS: remove Text:: package
$Autoformat::widow_slack = 0.1;
sub defn($)
{
return $_[0] if defined $_[0];
return "";
}
my $ignore_headers = qr/\A(From\b.*$)?([^:]+:.*$([ \t].*$)*)+\s*\Z/m;
my $ignore_indent = qr/^[^\S\n].*(\n[^\S\n].*)*$/;
sub ignore_headers { $_[0]==1 && /$ignore_headers/ }
# BITS OF A TEXT LINE
my $quotechar = qq{[!#%=|:]};
my $quotechunk = qq{(?:$quotechar(?![a-z])|[a-z]*>+)};
my $quoter = qq{(?:(?i)(?:$quotechunk(?:[ \\t]*$quotechunk)*))};
my $separator = q/(?:[-_]{2,}|[=#*]{3,}|[+~]{4,})/;
use overload;
sub autoformat # ($text, %args)
{
my ($text,%args,$toSTDOUT);
foreach ( @_ )
{
if (ref eq 'HASH')
{ %args = (%args, %$_) }
elsif (!defined($text) && !ref || overload::Method($_,'""'))
{ $text = "$_" }
else {
croak q{Usage: autoformat([text],[{options}])}
}
}
unless (defined $text) {
$text = join("",<STDIN>);
$toSTDOUT = !defined wantarray();
}
return unless length $text;
$args{right} = $default_margin unless exists $args{right};
$args{justify} = "" unless exists $args{justify};
$args{widow} = 0 if $args{justify}||"" =~ /full/;
$args{widow} = $default_widow unless exists $args{widow};
$args{case} = '' unless exists $args{case};
$args{squeeze} = 1 unless exists $args{squeeze};
$args{gap} = 0 unless exists $args{gap};
$args{break} = break_at('-') unless exists $args{break};
$args{impfill} = ! exists $args{fill};
$args{expfill} = $args{fill};
$args{renumber} = 1 unless exists $args{renumber};
$args{autocentre} = 1 unless exists $args{autocentre};
$args{_centred} = 1 if $args{justify} =~ /cent(er(ed)?|red?)/;
# SPECIAL IGNORANCE...
if ($args{ignore}) {
$args{all} = 1;
my $ig_type = ref $args{ignore};
if ($ig_type eq 'Regexp') {
my $regex = $args{ignore};
$args{ignore} = sub { /$regex/ };
}
elsif ($args{ignore} =~ /^indent/i) {
$args{ignore} = sub { ignore_headers(@_) || /$ignore_indent/ };
}
croak "Expected suboutine reference as value for -ignore option"
if ref $args{ignore} ne 'CODE';
}
else {
$args{ignore} = \&ignore_headers;
}
# DETABIFY
my @rawlines = split /\n/, $text;
use Text::Tabs;
@rawlines = expand(@rawlines);
# PARSE EACH LINE
my $pre = 0;
my @lines;
foreach (@rawlines)
{
push @lines, { raw => $_ };
s/\A([ \t]*)($quoter?)([ \t]*)//
or die "Internal Error ($@) on '$_'";
$lines[-1]{presig} = $lines[-1]{prespace} = defn $1;
$lines[-1]{presig} .= $lines[-1]{quoter} = defn $2;
$lines[-1]{presig} .= $lines[-1]{quotespace} = defn $3;
$lines[-1]{hang} = Hang->new($_);
s/([ \t]*)(.*?)(\s*)$//
or die "Internal Error ($@) on '$_'";
$lines[-1]{hangspace} = defn $1;
$lines[-1]{text} = defn $2;
$lines[-1]{empty} = $lines[-1]{hang}->empty() && $2 !~ /\S/;
$lines[-1]{separator} = $lines[-1]{text} =~ /^$separator$/;
}
# SUBDIVIDE DOCUMENT INTO COHERENT SUBSECTIONS
my @chunks;
push @chunks, [shift @lines];
foreach my $line (@lines)
{
if ($line->{separator} ||
$line->{quoter} ne $chunks[-1][-1]->{quoter} ||
$line->{empty} ||
@chunks && $chunks[-1][-1]->{empty})
{
push @chunks, [$line];
}
else
{
push @{$chunks[-1]}, $line;
}
}
# DETECT CENTRED PARAS
CHUNK: foreach my $chunk ( @chunks )
{
next CHUNK if !$args{autocentre} || @$chunk < 2;
my @length;
my $ave = 0;
foreach my $line (@$chunk)
{
my $prespace = $line->{quoter} ? $line->{quotespace}
: $line->{prespace};
my $pagewidth =
2*length($prespace) + length($line->{text});
push @length, [length $prespace,$pagewidth];
$ave += $pagewidth;
}
$ave /= @length;
my $diffpre = 0;
foreach my $l (0..$#length)
{
next CHUNK unless abs($length[$l][1]-$ave) <= 2;
$diffpre ||= $length[$l-1][0] != $length[$l][0]
if $l > 0;
}
next CHUNK unless $diffpre;
foreach my $line (@$chunk)
{
$line->{centred} = 1;
($line->{quoter} ? $line->{quotespace}
: $line->{prespace}) = "";
}
}
# REDIVIDE INTO PARAGRAPHS
my @paras;
foreach my $chunk ( @chunks )
{
my $first = 1;
my $firstfrom;
foreach my $line ( @{$chunk} )
{
if ($first ||
$line->{quoter} ne $paras[-1]->{quoter} ||
$paras[-1]->{separator} ||
!$line->{hang}->empty
)
{
push @paras, $line;
$first = 0;
$firstfrom = length($line->{raw}) - length($line->{text});
}
else
{
my $extraspace = length($line->{raw}) - length($line->{text}) - $firstfrom;
$paras[-1]->{text} .= "\n" . q{ }x$extraspace . $line->{text};
$paras[-1]->{raw} .= "\n" . $line->{raw};
}
}
}
# SELECT PARAS TO HANDLE
my $remainder = "";
if ($args{all}) { # STOP AT MAIL TERMINATOR
for my $index (0..$#paras) {
local $_ = $paras[$index]{raw};
$paras[$index]{ignore} = $args{ignore}($index+1);
next unless /^--$/;
$remainder = join "\n", map { $_->{raw} } splice @paras, $index;
$remainder .= "\n" unless $remainder =~ /\n\z/;
last;
}
}
else { # JUST THE FIRST PARA
$remainder = join "\n", map { $_->{raw} } @paras[1..$#paras];
$remainder .= "\n" unless $remainder =~ /\n\z/;
@paras = ( $paras[0] );
}
# RE-CASE TEXT
if ($args{case}) {
foreach my $para ( @paras ) {
next if $para->{ignore};
if ($args{case} =~ /upper/i) {
$para->{text} = recase($para->{text}, 'upper');
}
if ($args{case} =~ /lower/i) {
$para->{text} = recase($para->{text}, 'lower');
}
if ($args{case} =~ /title/i) {
entitle($para->{text},0);
}
if ($args{case} =~ /highlight/i) {
entitle($para->{text},1);
}
if ($args{case} =~ /sentence(\s*)/i) {
my $trailer = $1;
$args{squeeze}=0 if $trailer && $trailer ne " ";
ensentence();
$para->{text} =~ s/(\S+(\s+|$))/ensentence($1, $trailer)/ge;
}
$para->{text} =~ s/\b([A-Z])[.]/\U$1./gi; # ABBREVS
}
}
# ALIGN QUOTERS
# DETERMINE HANGING MARKER TYPE (BULLET, ALPHA, ROMAN, ETC.)
my %sigs;
my $lastquoted = 0;
my $lastprespace = 0;
for my $i ( 0..$#paras )
{
my $para = $paras[$i];
next if $para->{ignore};
if ($para->{quoter})
{
if ($lastquoted) { $para->{prespace} = $lastprespace }
else { $lastquoted = 1; $lastprespace = $para->{prespace} }
}
else
{
$lastquoted = 0;
}
}
# RENUMBER PARAGRAPHS
for my $para ( @paras ) {
next if $para->{ignore};
my $sig = $para->{presig} . $para->{hang}->signature();
push @{$sigs{$sig}{hangref}}, $para;
$sigs{$sig}{hangfields} = $para->{hang}->fields()-1
unless defined $sigs{$sig}{hangfields};
}
while (my ($sig,$val) = each %sigs) {
next unless $sig =~ /rom/;
field: for my $field ( 0..$val->{hangfields} )
{
my $romlen = 0;
foreach my $para ( @{$val->{hangref}} )
{
my $hang = $para->{hang};
my $fieldtype = $hang->field($field);
next field
unless $fieldtype && $fieldtype =~ /rom|let/;
if ($fieldtype eq 'let') {
foreach my $para ( @{$val->{hangref}} ) {
$hang->field($field=>'let')
}
}
else {
$romlen += length $hang->val($field);
}
}
# NO ROMAN LETTER > 1 CHAR -> ALPHABETICS
if ($romlen <= @{$val->{hangref}}) {
foreach my $para ( @{$val->{hangref}} ) {
$para->{hang}->field($field=>'let')
}
}
}
}
my %prev;
for my $para ( @paras ) {
next if $para->{ignore};
my $sig = $para->{presig} . $para->{hang}->signature();
if ($args{renumber}) {
unless ($para->{quoter}) {
$para->{hang}->incr($prev{""}, $prev{$sig});
$prev{""} = $prev{$sig} = $para->{hang}
unless $para->{hang}->empty;
}
}
# COLLECT MAXIMAL HANG LENGTHS BY SIGNATURE
my $siglen = $para->{hang}->length();
$sigs{$sig}{hanglen} = $siglen
if ! $sigs{$sig}{hanglen} ||
$sigs{$sig}{hanglen} < $siglen;
}
# PROPAGATE MAXIMAL HANG LENGTH
while (my ($sig,$val) = each %sigs)
{
foreach (@{$val->{hangref}}) {
$_->{hanglen} = $val->{hanglen};
}
}
# BUILD FORMAT FOR EACH PARA THEN FILL IT
$text = "";
my $gap = $paras[0]->{empty} ? 0 : $args{gap};
for my $para ( @paras )
{
if ($para->{empty}) {
$gap += 1 + ($para->{text} =~ tr/\n/\n/);
}
if ($para->{ignore}) {
$text .= (!$para->{empty} ? "\n"x($args{gap}-$gap) : "") ;
$text .= $para->{raw};
$text .= "\n" unless $para->{raw} =~ /\n\z/;
}
else {
my $leftmargin = $args{left} ? " "x($args{left}-1)
: $para->{prespace};
my $hlen = $para->{hanglen} || $para->{hang}->length;
my $hfield = ($hlen==1 ? '~' : '>'x$hlen);
my @hang;
push @hang, $para->{hang}->stringify if $hlen;
my $format = $leftmargin
. quotemeta($para->{quoter})
. $para->{quotespace}
. $hfield
. $para->{hangspace};
# modified by JS: remove Text:: package
my $rightslack = int (($args{right}-length $leftmargin)*$Autoformat::widow_slack);
my ($widow_okay, $rightindent, $firsttext, $newtext) = (0,0);
do {
my $tlen = $args{right}-$rightindent-length($leftmargin
. $para->{quoter}
. $para->{quotespace}
. $hfield
. $para->{hangspace});
next if blockquote($text,$para, $format, $tlen, \@hang, \%args);
my $tfield = ( $tlen==1 ? '~'
: $para->{centred}||$args{_centred} ? '|'x$tlen
: $args{justify} eq 'right' ? ']'x$tlen
: $args{justify} eq 'full' ? '['x($tlen-2) . ']]'
: $para->{centred}||$args{_centred} ? '|'x$tlen
: '['x$tlen
);
my $tryformat = "$format$tfield";
$newtext = (!$para->{empty} ? "\n"x($args{gap}-$gap) : "")
. form( { squeeze=>$args{squeeze}, trim=>1,
break=>$args{break},
fill => !(!($args{expfill}
|| $args{impfill} &&
!$para->{centred}))
},
$tryformat, @hang,
$para->{text});
$firsttext ||= $newtext;
$newtext =~ /\s*([^\n]*)$/;
$widow_okay = $para->{empty} || length($1) >= $args{widow};
} until $widow_okay || ++$rightindent > $rightslack;
$text .= $widow_okay ? $newtext : $firsttext;
}
$gap = 0 unless $para->{empty};
}
# RETURN FORMATTED TEXT
if ($toSTDOUT) { print STDOUT $text . $remainder; return }
return $text . $remainder;
}
use utf8;
my $alpha = qr/[^\W\d_]/;
my $notalpha = qr/[\W\d_]/;
my $word = qr/\pL(?:\pL'?)*/;
my $upper = qr/[^\Wa-z\d_]/;
my $lower = qr/[^\WA-Z\d_]/;
my $mixed = qr/$alpha*?(?:$lower$upper|$upper$lower)$alpha*/;
sub recase {
my ($origtext, $case) = @_;
my ($entities, $other_entities, $first, $rest) = @{$casing{$case}};
my $text = "";
my @pieces = split /(&[a-z]+;)/i, $origtext;
use Data::Dumper 'Dumper';
push @pieces, "" if @pieces % 2;
return $text unless @pieces;
local $_ = shift @pieces;
if (length $_) {
$entities = $other_entities;
&$first;
$text .= $_;
}
return $text unless @pieces;
$_ = shift @pieces;
$text .= $entities->{$_} || $_;
while (@pieces) {
$_ = shift @pieces; &$rest; $text .= $_;
$_ = shift @pieces; $text .= $other_entities->{$_} || $_;
}
return $text;
}
my $alword = qr{(?:\pL|&[a-z]+;)(?:[\pL']|&[a-z]+;)*}i;
sub entitle {
my $ignore = pop;
local *_ = \shift;
# put into lowercase if on stop list, else titlecase
s{($alword)}
# modified by JS: just a formatting change
{ $ignore &&
$ignore{lc $1} ? recase($1,'lower') : recase($1,'title') }gex;
s/^($alword) /recase($1,'title')/ex; # last word always to cap
s/ ($alword)$/recase($1,'title')/ex; # first word always to cap
# treat parethesized portion as a complete title
s/\( ($alword) /'('.recase($1,'title')/ex;
s/($alword) \) /recase($1,'title').')'/ex;
# capitalize first word following colon or semi-colon
s/ ( [:;] \s+ ) ($alword) /$1 . recase($2,'title')/ex;
}
my $abbrev = join '|', qw{
# modified by JS: add al. and Jr.
etc[.] pp[.] ph[.]?d[.] U[.]S[.] al. Jr.
};
my $gen_abbrev = join '|', $abbrev, qw{
(^[^a-z]*([a-z][.])+)
};
my $term = q{(?:[.]|[!?]+)};
my $eos = 1;
my $brsent = 0;
sub ensentence {
do { $eos = 1; return } unless @_;
my ($str, $trailer) = @_;
if ($str =~ /^([^a-z]*)I[^a-z]*?($term?)[^a-z]*$/i) {
$eos = $2;
$brsent = $1 =~ /^[[(]/;
return uc $str
}
# modified by JS: Don't lc LaTeX stuff inside {}
unless ($str =~ /[a-z0-9].*[A-Z]|[A-Z].*[a-z0-9]/ or
$str =~ /^\(?\{?[A-Z]+\}?\)?/) {
$str = lc $str;
}
if ($eos) {
$str =~ s/([a-z])/uc $1/ie;
$brsent = $str =~ /^[[(]/;
}
$eos = $str !~ /($gen_abbrev)[^a-z]*\s/i
&& $str =~ /[a-z][^a-z]*$term([^a-z]*)\s/
&& !($1=~/[])]/ && !$brsent);
$str =~ s/\s+$/$trailer/ if $eos && $trailer;
return $str;
}
# blockquote($text,$para, $format, $tlen, \@hang, \%args);
sub blockquote {
my ($dummy, $para, $format, $tlen, $hang, $args) = @_;
=begin other
print STDERR "[", join("|", $para->{raw} =~
/ \A(\s*) # $1 - leading whitespace (quotation)
(["']|``) # $2 - opening quotemark
(.*) # $3 - quotation
(''|\2) # $4 closing quotemark
\s*?\n # trailing whitespace
(\1[ ]+) # $5 - leading whitespace (attribution)
(--|-) # $6 - attribution introducer
([^\n]*?$) # $7 - attribution line 1
((\5[^\n]*?$)*) # $8 - attributions lines 2-N
\s*\Z
/xsm
), "]\n";
=cut
$para->{text} =~
/ \A(\s*) # $1 - leading whitespace (quotation)
(["']|``) # $2 - opening quotemark
(.*) # $3 - quotation
(''|\2) # $4 closing quotemark
\s*?\n # trailing whitespace
(\1[ ]+) # $5 - leading whitespace (attribution)
(--|-) # $6 - attribution introducer
(.*?$) # $7 - attribution line 1
((\5.*?$)*) # $8 - attributions lines 2-N
\s*\Z
/xsm
or return;
#print "[$1][$2][$3][$4][$5][$6][$7]\n";
my $indent = length $1;
my $text = $2.$3.$4;
my $qindent = length $2;
my $aindent = length $5;
my $attribintro = $6;
my $attrib = $7.$8;
$text =~ s/\n/ /g;
$_[0] .=
form {squeeze=>$args->{squeeze}, trim=>1,
fill => $args->{expfill}
},
$format . q{ }x$indent . q{<}x$tlen,
@$hang, $text,
$format . q{ }x($qindent) . q{[}x($tlen-$qindent),
@$hang, $text,
{squeeze=>0},
$format . q{ } x $aindent . q{>> } . q{[}x($tlen-$aindent-3),
@$hang, $attribintro, $attrib;
return 1;
}
package Hang;
# ROMAN NUMERALS
sub inv($@) { my ($k, %inv)=shift; for(0..$#_) {$inv{$_[$_]}=$_*$k} %inv }
my @unit= ( "" , qw ( I II III IV V VI VII VIII IX ));
my @ten = ( "" , qw ( X XX XXX XL L LX LXX LXXX XC ));
my @hund= ( "" , qw ( C CC CCC CD D DC DCC DCCC CM ));
my @thou= ( "" , qw ( M MM MMM ));
my %rval= (inv(1,@unit),inv(10,@ten),inv(100,@hund),inv(1000,@thou));
my $rbpat= join ")(",join("|",reverse @thou), join("|",reverse @hund), join("|",reverse @ten), join("|",reverse @unit);
my $rpat= join ")(?:",join("|",reverse @thou), join("|",reverse @hund), join("|",reverse @ten), join("|",reverse @unit);
sub fromRoman($)
{
return 0 unless $_[0] =~ /^.*?($rbpat).*$/i;
return $rval{uc $1} + $rval{uc $2} + $rval{uc $3} + $rval{uc $4};
}
sub toRoman($$)
{
my ($num,$example) = @_;
return '' unless $num =~ /^([0-3]??)(\d??)(\d??)(\d)$/;
my $roman = $thou[$1||0] . $hund[$2||0] . $ten[$3||0] . $unit[$4||0];
return $example=~/[A-Z]/ ? uc $roman : lc $roman;
}
# BITS OF A NUMERIC VALUE
my $num = q/(?:\d{1,3}\b)/;
my $rom = qq/(?:(?=[MDCLXVI])(?:$rpat))/;
my $let = q/[A-Za-z]/;
my $pbr = q/[[(<]/;
my $sbr = q/])>/;
my $ows = q/[ \t]*/;
my %close = ( '[' => ']', '(' => ')', '<' => '>', "" => '' );
my $hangPS = qq{(?i:ps:|(?:p\\.?)+s\\b\\.?(?:[ \\t]*:)?)};
my $hangNB = qq{(?i:n\\.?b\\.?(?:[ \\t]*:)?)};
my $hangword = qq{(?:(?:Note)[ \\t]*:)};
my $hangbullet = qq{[*.+-]};
my $hang = qq{(?:(?i)(?:$hangNB|$hangword|$hangbullet)(?=[ \t]))};
# IMPLEMENTATION
sub new {
my ($class, $orig) = @_;
my $origlen = length $orig;
my @vals;
if ($_[1] =~ s#\A($hangPS)##) {
@vals = { type => 'ps', val => $1 }
}
elsif ($_[1] =~ s#\A($hang)##) {
@vals = { type => 'bul', val => $1 }
}
else {
local $^W;
my $cut;
while (length $_[1]) {
last if $_[1] =~ m#\A($ows)($abbrev)#
&& (length $1 || !@vals); # ws-separated or first
$cut = $origlen - length $_[1];
my $pre = $_[1] =~ s#\A($ows$pbr$ows)## ? $1 : "";
my $val = $_[1] =~ s#\A($num)## && { type=>'num', val=>$1 }
|| $_[1] =~ s#\A($rom)##i && { type=>'rom', val=>$1, nval=>fromRoman($1) }
|| $_[1] =~ s#\A($let(?!$let))##i && { type=>'let', val=>$1 }
|| { val => "", type => "" };
$_[1] = $pre.$_[1] and last unless $val->{val};
$val->{post} = $pre && $_[1] =~ s#\A($ows()[.:/]?[$close{$pre}][.:/]?)## && $1
|| $_[1] =~ s#\A($ows()[$sbr.:/])## && $1
|| "";
$val->{pre} = $pre;
$val->{cut} = $cut;
push @vals, $val;
}
while (@vals && !$vals[-1]{post}) {
$_[1] = substr($orig,pop(@vals)->{cut});
}
}
# check for orphaned years...
if (@vals==1 && $vals[0]->{type} eq 'num'
&& $vals[0]->{val} >= 1000
&& $vals[0]->{post} eq '.') {
$_[1] = substr($orig,pop(@vals)->{cut});
}
return NullHang->new if !@vals;
bless \@vals, $class;
}
sub incr {
local $^W;
my ($self, $prev, $prevsig) = @_;
my $level;
# check compatibility
return unless $prev && !$prev->empty;
for $level (0..(@$self<@$prev ? $#$self : $#$prev)) {
if ($self->[$level]{type} ne $prev->[$level]{type}) {
return if @$self<=@$prev; # no incr if going up
$prev = $prevsig;
last;
}
}
return unless $prev && !$prev->empty;
if ($self->[0]{type} eq 'ps') {
my $count = 1 + $prev->[0]{val} =~ s/(p[.]?)/$1/gi;
$prev->[0]{val} =~ /^(p[.]?).*(s[.]?[:]?)/;
$self->[0]{val} = $1 x $count . $2;
}
elsif ($self->[0]{type} eq 'bul') {
# do nothing
}
elsif (@$self>@$prev) { # going down level(s)
for $level (0..$#$prev) {
@{$self->[$level]}{'val','nval'} = @{$prev->[$level]}{'val','nval'};
}
for $level (@$prev..$#$self) {
_reset($self->[$level]);
}
}
else # same level or going up
{
for $level (0..$#$self) {
@{$self->[$level]}{'val','nval'} = @{$prev->[$level]}{'val','nval'};
}
_incr($self->[-1])
}
}
sub _incr {
local $^W;
if ($_[0]{type} eq 'rom') {
$_[0]{val} = toRoman(++$_[0]{nval},$_[0]{val});
}
else {
$_[0]{val}++ unless $_[0]{type} eq 'let' && $_[0]{val}=~/Z/i;
}
}
sub _reset {
local $^W;
if ($_[0]{type} eq 'rom') {
$_[0]{val} = toRoman($_[0]{nval}=1,$_[0]{val});
}
elsif ($_[0]{type} eq 'let') {
$_[0]{val} = $_[0]{val} =~ /[A-Z]/ ? 'A' : 'a';
}
else {
$_[0]{val} = 1;
}
}
sub stringify {
my ($self) = @_;
my ($str, $level) = ("");
for $level (@$self) {
local $^W;
$str .= join "", @{$level}{'pre','val','post'};
}
return $str;
}
sub val {
my ($self, $i) = @_;
return $self->[$i]{val};
}
sub fields { return scalar @{$_[0]} }
sub field {
my ($self, $i, $newval) = @_;
$self->[$i]{type} = $newval if @_>2;
return $self->[$i]{type};
}
sub signature {
local $^W;
my ($self) = @_;
my ($str, $level) = ("");
for $level (@$self) {
$level->{type} ||= "";
$str .= join "", $level->{pre},
($level->{type} =~ /rom|let/ ? "romlet" : $level->{type}),
$level->{post};
}
return $str;
}
sub length {
length $_[0]->stringify
}
sub empty { 0 }
package NullHang;
sub new { bless {}, $_[0] }
sub stringify { "" }
sub length { 0 }
sub incr {}
sub empty { 1 }
sub signature { "" }
sub fields { return 0 }
sub field { return "" }
sub val { return "" }
1;
__END__
=head1 NAME
Text::Autoformat - Automatic text wrapping and reformatting
=head1 VERSION
This document describes version 1.12 of Text::Autoformat,
released May 27, 2003.
=head1 SYNOPSIS
# Minimal use: read from STDIN, format to STDOUT...
use Text::Autoformat;
autoformat;
# In-memory formatting...
$formatted = autoformat $rawtext;
# Configuration...
$formatted = autoformat $rawtext, { %options };
# Margins (1..72 by default)...
$formatted = autoformat $rawtext, { left=>8, right=>70 };
# Justification (left by default)...
$formatted = autoformat $rawtext, { justify => 'left' };
$formatted = autoformat $rawtext, { justify => 'right' };
$formatted = autoformat $rawtext, { justify => 'full' };
$formatted = autoformat $rawtext, { justify => 'centre' };
# Filling (does so by default)...
$formatted = autoformat $rawtext, { fill=>0 };
# Squeezing whitespace (does so by default)...
$formatted = autoformat $rawtext, { squeeze=>0 };
# Case conversions...
$formatted = autoformat $rawtext, { case => 'lower' };
$formatted = autoformat $rawtext, { case => 'upper' };
$formatted = autoformat $rawtext, { case => 'sentence' };
$formatted = autoformat $rawtext, { case => 'title' };
$formatted = autoformat $rawtext, { case => 'highlight' };
# Selective reformatting
$formatted = autoformat $rawtext, { ignore=>qr/^\t/ };
=head1 BACKGROUND
=head2 The problem
Perl plaintext formatters just aren't smart enough. Given a typical
piece of plaintext in need of formatting:
In comp.lang.perl.misc you wrote:
: > <CN = Clooless Noobie> writes:
: > CN> PERL sux because:
: > CN> * It doesn't have a switch statement and you have to put $
: > CN>signs in front of everything
: > CN> * There are too many OR operators: having |, || and 'or'
: > CN>operators is confusing
: > CN> * VB rools, yeah!!!!!!!!!
: > CN> So anyway, how can I stop reloads on a web page?
: > CN> Email replies only, thanks - I don't read this newsgroup.
: >
: > Begone, sirrah! You are a pathetic, Bill-loving, microcephalic
: > script-infant.
: Sheesh, what's with this group - ask a question, get toasted! And how
: *dare* you accuse me of Ianuphilia!
both the venerable Unix L<fmt> tool and Perl's standard Text::Wrap module
produce:
In comp.lang.perl.misc you wrote: : > <CN = Clooless Noobie>
writes: : > CN> PERL sux because: : > CN> * It doesn't
have a switch statement and you have to put $ : > CN>signs in
front of everything : > CN> * There are too many OR
operators: having |, || and 'or' : > CN>operators is confusing
: > CN> * VB rools, yeah!!!!!!!!! : > CN> So anyway, how
can I stop reloads on a web page? : > CN> Email replies only,
thanks - I don't read this newsgroup. : > : > Begone, sirrah!
You are a pathetic, Bill-loving, microcephalic : >
script-infant. : Sheesh, what's with this group - ask a
question, get toasted! And how : *dare* you accuse me of
Ianuphilia!
Other formatting modules -- such as Text::Correct and Text::Format --
provide more control over their output, but produce equally poor results
when applied to arbitrary input. They simply don't understand the
structural conventions of the text they're reformatting.
=head2 The solution
The Text::Autoformat module provides a subroutine named C<autoformat> that
wraps text to specified margins. However, C<autoformat> reformats its
input by analysing the text's structure, so it wraps the above example
like so:
In comp.lang.perl.misc you wrote:
: > <CN = Clooless Noobie> writes:
: > CN> PERL sux because:
: > CN> * It doesn't have a switch statement and you
: > CN> have to put $ signs in front of everything
: > CN> * There are too many OR operators: having |, ||
: > CN> and 'or' operators is confusing
: > CN> * VB rools, yeah!!!!!!!!! So anyway, how can I
: > CN> stop reloads on a web page? Email replies
: > CN> only, thanks - I don't read this newsgroup.
: >
: > Begone, sirrah! You are a pathetic, Bill-loving,
: > microcephalic script-infant.
: Sheesh, what's with this group - ask a question, get toasted!
: And how *dare* you accuse me of Ianuphilia!
Note that the various quoting conventions have been observed. In fact,
their structure has been used to determine where some paragraphs begin.
Furthermore C<autoformat> correctly distinguished between the leading
'*' bullets of the nested list (which were outdented) and the leading
emphatic '*' of "*dare*" (which was inlined).
=head1 DESCRIPTION
=head2 Paragraphs
The fundamental task of the C<autoformat> subroutine is to identify and
rearrange independent paragraphs in a text. Paragraphs typically consist
of a series of lines containing at least one non-whitespace character,
followed by one or more lines containing only optional whitespace.
This is a more liberal definition than many other formatters
use: most require an empty line to terminate a paragraph. Paragraphs may
also be denoted by bulleting, numbering, or quoting (see the following
sections).
Once a paragraph has been isolated, C<autoformat> fills and re-wraps its
lines according to the margins that are specified in its argument list.
These are placed after the text to be formatted, in a hash reference:
$tidied = autoformat($messy, {left=>20, right=>60});
By default, C<autoformat> uses a left margin of 1 (first column) and a
right margin of 72.
You can also control whether (and how) C<autoformat> breaks words at the
end of a line, using the C<'break'> option:
# Turn off all hyphenation
use Text::Autoformat qw(autoformat break_wrap);
$tidied = autoformat($messy, {break=>break_wrap});
# Default hyphenation
use Text::Autoformat qw(autoformat break_at);
$tidied = autoformat($messy, {break=>break_at('-')});
# Use TeX::Hyphen module's hyphenation (module must be installed)
use Text::Autoformat qw(autoformat break_TeX);
$tidied = autoformat($messy, {break=>break_TeX});
Normally, C<autoformat> only reformats the first paragraph it encounters,
and leaves the remainder of the text unaltered. This behaviour is useful
because it allows a one-liner invoking the subroutine to be mapped
onto a convenient keystroke in a text editor, to provide