3 # Clean a text file -- or directory of text files -- of stealth whitespace.
4 # WARNING: this can be a highly destructive operation. Use with caution.
11 # Clean up space-tab sequences, either by removing spaces or
12 # replacing them with tabs.
13 sub clean_space_tabs($)
15 no bytes; # Tab alignment depends on characters
23 for ($i = 0; $i < length($li); $i++) {
24 $c = substr($li, $i, 1);
26 my $npos = ($pos+$nsp+8) & ~7;
27 my $ntab = ($npos >> 3) - ($pos >> 3);
31 } elsif ($c eq "\n" || $c eq "\r") {
53 foreach $f ( @ARGV ) {
54 print STDERR "$name: $f\n";
57 print STDERR "$f: not a file\n";
61 if (!open(FILE, '+<', $f)) {
62 print STDERR "$name: Cannot open file: $f: $!\n";
68 # First, verify that it is not a binary file; consider any file
69 # with a zero byte to be a binary file. Is there any better, or
70 # additional, heuristic that should be applied?
73 while (read(FILE, $data, 65536) > 0) {
81 print STDERR "$name: $f: binary file\n";
94 while ( defined($line = <FILE>) ) {
95 $in_bytes += length($line);
96 $line =~ s/[ \t\r]*$//; # Remove trailing spaces
97 $line = clean_space_tabs($line);
99 if ( $line eq "\n" ) {
100 push(@blanks, $line);
101 $blank_bytes += length($line);
103 push(@lines, @blanks);
104 $out_bytes += $blank_bytes;
106 $out_bytes += length($line);
112 # Any blanks at the end of the file are discarded
114 if ($in_bytes != $out_bytes) {
115 # Only write to the file if changed
119 if ( !defined($where = tell(FILE)) ||
120 !truncate(FILE, $where) ) {
121 die "$name: Failed to truncate modified file: $f: $!\n";