Is it possible to replace only "leading tabs" with a set number of spaces per tab? I'm defining a leading tab as one that is only preceded by tabs or spaces. I'm defining a leading or an indentation tab as one that is only preceded by whitespace.
I have the following line in my .nexrc, cribbed from this one. It runs the lines between the lines containing the mark a and the mark b through a filter. that replaces tabs.
map \2 'a!'b pr -te2
However, it replaces non-leading tabs with two spaces well, which is not ideal since a literal tab is sometimes needed.
Is there an easy and portable way to replace leading tabs only with a set number of spaces per tab?
The following perl script (which could be collapsed to a one-liner) does the job of replacing leading tabs with a width supplied on the command line, but it relies on the availability of Perl and takes quadratic time (if the file consists of nothing but tabs).
#!/usr/bin/env perl
use strict;
use warnings;
my ($width) = @ARGV;
$width //= 2;
my $replacement = ' ' x $width;
while (<>) {
while (s/^(\s*)\t/$1$replacement/g) { }
print;
}
Here's an example of what I want to happen. ^I refers to a tab byte and # is a zero-width marker for the start of a line. The line below is a byte-ruler.
BEFORE:
#^I^I ^Ia^Ib
# 1 23 45 67
AFTER (tab width of 2)
# a^Ib
#12345678 90
AFTER (tab width of 4)
# a^Ib
#12345678901234 56
expand(from GNU coreutils) would seem to be the obvious generic solution e.g.expand -it3to replace each initial tab with 3 spaces