2481d81ec6b22f160fe5e141dd45c386c4f62dbf
[p5sagit/p5-mst-13.2.git] / lib / Text / Tabs.pm
1 #
2 # expand and unexpand tabs as per the unix expand and 
3 # unexpand programs.
4 #
5 # expand and unexpand operate on arrays of lines.  Do not
6 # feed strings that contain newlines to them.
7 #
8 # David Muir Sharnoff <muir@idiom.com>
9
10 # Version: 9/21/95
11 #
12
13 =head1 NAME
14
15 Text::Tabs -- expand and unexpand tabs
16
17 =head1 SYNOPSIS
18
19         use Text::Tabs;
20         
21         #$tabstop = 8; # Defaults
22         print expand("Hello\tworld");
23         print unexpand("Hello,        world");
24         $tabstop = 4;
25         print join("\n",expand(split(/\n/,
26                 "Hello\tworld,\nit's a nice day.\n"
27                 )));
28
29 =head1 DESCRIPTION
30
31 This module expands and unexpands tabs into spaces, as per the unix expand
32 and unexpand programs. Either function should be passed an array of strings
33 (newlines may I<not> be included, and should be used to split an incoming
34 string into separate elements.) which will be processed and returned.
35
36 =head1 AUTHOR
37
38 David Muir Sharnoff <muir@idiom.com>
39
40 =cut
41
42 package Text::Tabs;
43
44 require Exporter;
45
46 @ISA = (Exporter);
47 @EXPORT = qw(expand unexpand $tabstop);
48
49 $tabstop = 8;
50
51 sub expand
52 {
53         my @l = @_;
54         for $_ (@l) {
55                 1 while s/^([^\t]*)(\t+)/
56                         $1 . (" " x 
57                                 ($tabstop * length($2)
58                                 - (length($1) % $tabstop)))
59                         /e;
60         }
61         return @l if wantarray;
62         return @l[0];
63 }
64
65 sub unexpand
66 {
67         my @l = &expand(@_);
68         my @e;
69         for $x (@l) {
70                 @e = split(/(.{$tabstop})/,$x);
71                 for $_ (@e) {
72                         s/  +$/\t/;
73                 }
74                 $x = join('',@e);
75         }
76         return @l if wantarray;
77         return @l[0];
78 }
79
80 1;