aboutsummaryrefslogtreecommitdiff
path: root/smartfmt
blob: 71ca8c7885a9c1975f87ece111fbe74aea4a60ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/perl -w

# wrapper for fmt, detects when every line has
# the same prefix (or is blank) and passes the prefix
# as a -p option to fmt. Called by ~/.vimrc, F mapping.

sub shortest {
	my $oldprefix = shift;
	my $line = shift;
	my $newprefix = "";

	for(my $i = 0; $i < length($oldprefix) && $i < length($line); $i++) {
		last if substr($line, $i, 1) ne substr($oldprefix, $i, 1);
		$newprefix .= substr($line, $i, 1);
	}

	return $newprefix;
}

$nonblank = 0;
while(<STDIN>) {
	chomp;
	s/^\s+$//;
	push @lines, $_;
	next if /^$/;

	$nonblank++;

	if(not defined $prefix) {
		$prefix = $_;
	} elsif($prefix ne "") {
		$prefix = shortest($prefix, $_);
	}
}

$width = 71;
if($nonblank > 1 && $prefix ne "" && ($prefix =~ /[^A-Za-z]$/)) {
	$opt = ' -p' . quotemeta($prefix) . ' ';
	if(@ARGV && ($ARGV[0] eq '-s')) {
		$width = (length($prefix) + 71);
	}
}

$opt.= "-w $width -g $width";

#warn "line: $_" for @lines;
#warn "opt: $opt";

open OUT,"|fmt $opt" or die $!;
print OUT "$_\n" for @lines;
close OUT;