2 # SPDX-License-Identifier: GPL-2.0
4 # Clean a text file -- or directory of text files -- of stealth whitespace.
5 # WARNING: this can be a highly destructive operation. Use with caution.
15 # Clean up space-tab sequences, either by removing spaces or
16 # replacing them with tabs.
17 sub clean_space_tabs($)
19 no bytes; # Tab alignment depends on characters
27 for ($i = 0; $i < length($li); $i++) {
28 $c = substr($li, $i, 1);
30 my $npos = ($pos+$nsp+8) & ~7;
31 my $ntab = ($npos >> 3) - ($pos >> 3);
35 } elsif ($c eq "\n" || $c eq "\r") {
55 # Compute the visual width of a string
57 no bytes; # Tab alignment depends on characters
64 for ($i = 0; $i < length($li); $i++) {
65 $c = substr($li,$i,1);
68 } elsif ($c eq "\n") {
69 $mlen = $pos if ($pos > $mlen);
76 $mlen = $pos if ($pos > $mlen);
84 while (defined($a = shift(@ARGV))) {
86 if ($a eq '-width' || $a eq '-w') {
87 $max_width = shift(@ARGV)+0;
89 print STDERR "Usage: $name [-width #] files...\n";
97 foreach $f ( @files ) {
98 print STDERR "$name: $f\n";
101 print STDERR "$f: not a file\n";
105 if (!open(FILE, '+<', $f)) {
106 print STDERR "$name: Cannot open file: $f: $!\n";
112 # First, verify that it is not a binary file; consider any file
113 # with a zero byte to be a binary file. Is there any better, or
114 # additional, heuristic that should be applied?
117 while (read(FILE, $data, 65536) > 0) {
125 print STDERR "$name: $f: binary file\n";
139 while ( defined($line = <FILE>) ) {
141 $in_bytes += length($line);
142 $line =~ s/[ \t\r]*$//; # Remove trailing spaces
143 $line = clean_space_tabs($line);
145 if ( $line eq "\n" ) {
146 push(@blanks, $line);
147 $blank_bytes += length($line);
149 push(@lines, @blanks);
150 $out_bytes += $blank_bytes;
152 $out_bytes += length($line);
157 $l_width = strwidth($line);
158 if ($max_width && $l_width > $max_width) {
160 "$f:$lineno: line exceeds $max_width characters ($l_width)\n";
164 # Any blanks at the end of the file are discarded
166 if ($in_bytes != $out_bytes) {
167 # Only write to the file if changed
171 if ( !defined($where = tell(FILE)) ||
172 !truncate(FILE, $where) ) {
173 die "$name: Failed to truncate modified file: $f: $!\n";