From 94ea7a8cd41b5b0cebf2606f4319ca5050e80520 Mon Sep 17 00:00:00 2001 From: "B. Watson" Date: Sun, 5 Jul 2020 21:03:38 -0400 Subject: Add some new stuff --- smartfmt | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100755 smartfmt (limited to 'smartfmt') diff --git a/smartfmt b/smartfmt new file mode 100755 index 0000000..71ca8c7 --- /dev/null +++ b/smartfmt @@ -0,0 +1,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() { + 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; -- cgit v1.2.3