xref: /openbsd-src/gnu/usr.bin/perl/cpan/Text-Tabs/lib/Text/Tabs.pm (revision 898184e3e61f9129feb5978fad5a8c6865f00b92)
1
2package Text::Tabs;
3
4require Exporter;
5
6@ISA = (Exporter);
7@EXPORT = qw(expand unexpand $tabstop);
8
9use vars qw($VERSION $tabstop $debug);
10$VERSION = 2009.0305;
11
12use strict;
13
14BEGIN	{
15	$tabstop = 8;
16	$debug = 0;
17}
18
19sub expand {
20	my @l;
21	my $pad;
22	for ( @_ ) {
23		my $s = '';
24		for (split(/^/m, $_, -1)) {
25			my $offs = 0;
26			s{\t}{
27				$pad = $tabstop - (pos() + $offs) % $tabstop;
28				$offs += $pad - 1;
29				" " x $pad;
30			}eg;
31			$s .= $_;
32		}
33		push(@l, $s);
34	}
35	return @l if wantarray;
36	return $l[0];
37}
38
39sub unexpand
40{
41	my (@l) = @_;
42	my @e;
43	my $x;
44	my $line;
45	my @lines;
46	my $lastbit;
47	my $ts_as_space = " "x$tabstop;
48	for $x (@l) {
49		@lines = split("\n", $x, -1);
50		for $line (@lines) {
51			$line = expand($line);
52			@e = split(/(.{$tabstop})/,$line,-1);
53			$lastbit = pop(@e);
54			$lastbit = ''
55				unless defined $lastbit;
56			$lastbit = "\t"
57				if $lastbit eq $ts_as_space;
58			for $_ (@e) {
59				if ($debug) {
60					my $x = $_;
61					$x =~ s/\t/^I\t/gs;
62					print "sub on '$x'\n";
63				}
64				s/  +$/\t/;
65			}
66			$line = join('',@e, $lastbit);
67		}
68		$x = join("\n", @lines);
69	}
70	return @l if wantarray;
71	return $l[0];
72}
73
741;
75__END__
76
77sub expand
78{
79	my (@l) = @_;
80	for $_ (@l) {
81		1 while s/(^|\n)([^\t\n]*)(\t+)/
82			$1. $2 . (" " x
83				($tabstop * length($3)
84				- (length($2) % $tabstop)))
85			/sex;
86	}
87	return @l if wantarray;
88	return $l[0];
89}
90
91
92=head1 NAME
93
94Text::Tabs -- expand and unexpand tabs per the unix expand(1) and unexpand(1)
95
96=head1 SYNOPSIS
97
98  use Text::Tabs;
99
100  $tabstop = 4;  # default = 8
101  @lines_without_tabs = expand(@lines_with_tabs);
102  @lines_with_tabs = unexpand(@lines_without_tabs);
103
104=head1 DESCRIPTION
105
106Text::Tabs does about what the unix utilities expand(1) and unexpand(1)
107do.  Given a line with tabs in it, expand will replace the tabs with
108the appropriate number of spaces.  Given a line with or without tabs in
109it, unexpand will add tabs when it can save bytes by doing so (just
110like C<unexpand -a>).  Invisible compression with plain ASCII!
111
112=head1 EXAMPLE
113
114  #!perl
115  # unexpand -a
116  use Text::Tabs;
117
118  while (<>) {
119    print unexpand $_;
120  }
121
122Instead of the C<expand> comand, use:
123
124  perl -MText::Tabs -n -e 'print expand $_'
125
126Instead of the C<unexpand -a> command, use:
127
128  perl -MText::Tabs -n -e 'print unexpand $_'
129
130=head1 LICENSE
131
132Copyright (C) 1996-2002,2005,2006 David Muir Sharnoff.
133Copyright (C) 2005 Aristotle Pagaltzis
134This module may be modified, used, copied, and redistributed at your own risk.
135Publicly redistributed modified versions must use a different name.
136
137