perl 5.003_05: unixish.h
[p5sagit/p5-mst-13.2.git] / lib / Text / Wrap.pm
1 package Text::Wrap;
2
3 require Exporter;
4
5 @ISA = (Exporter);
6 @EXPORT = qw(wrap);
7 @EXPORT_OK = qw($columns);
8
9 $VERSION = 96.041801;
10
11 use vars qw($VERSION $columns $debug);
12
13 BEGIN   {
14         $columns = 76;  # <= screen width
15         $debug = 0;
16 }
17
18 use Text::Tabs;
19 use strict;
20
21 sub wrap
22 {
23         my ($ip, $xp, @t) = @_;
24
25         my $r = "";
26         my $t = expand(join(" ",@t));
27         my $lead = $ip;
28         my $ll = $columns - length(expand($lead)) - 1;
29         my $nl = "";
30
31         # remove up to a line length of things that aren't
32         # new lines and tabs.
33
34         if ($t =~ s/^([^\n]{0,$ll})(\s|\Z(?!\n))//xm) {
35
36                 # accept it.
37                 $r .= unexpand($lead . $1);
38
39                 # recompute the leader
40                 $lead = $xp;
41                 $ll = $columns - length(expand($lead)) - 1;
42                 $nl = $2;
43
44                 # repeat the above until there's none left
45                 while ($t and $t =~ s/^([^\n]{0,$ll})(\s|\Z(?!\n))//xm) {
46                         print "\$2 is '$2'\n" if $debug;
47                         $nl = $2;
48                         $r .= unexpand("\n" . $lead . $1);
49                 }
50                 $r .= $nl;
51         } 
52
53         die "couldn't wrap '$t'" 
54                 if length($t) > $ll;
55
56         print "-----------$r---------\n" if $debug;
57
58         print "Finish up with '$lead', '$t'\n" if $debug;
59
60         $r .= $lead . $t if $t ne "";
61
62         print "-----------$r---------\n" if $debug;;
63         return $r;
64 }
65
66 1;
67 __DATA__
68
69 =head1 NAME
70
71 Text::Wrap - line wrapping to form simple paragraphs
72
73 =head1 SYNOPSIS 
74
75         use Text::Wrap
76
77         print wrap($initial_tab, $subsequent_tab, @text);
78
79         use Text::Wrap qw(wrap $columns);
80
81         $columns = 132;
82
83 =head1 DESCRIPTION
84
85 Text::Wrap is a very simple paragraph formatter.  It formats a
86 single paragraph at a time by breaking lines at word boundries.
87 Indentation is controlled for the first line ($initial_tab) and
88 all subsquent lines ($subsequent_tab) independently.  $Text::Wrap::columns
89 should be set to the full width of your output device.
90
91 =head1 EXAMPLE
92
93         print wrap("\t","","This is a bit of text that forms 
94                 a normal book-style paragraph");
95
96 =head1 AUTHOR
97
98 David Muir Sharnoff <muir@idiom.com>
99
100 =cut