diff options
author | B. Watson <yalhcru@gmail.com> | 2020-07-05 21:03:38 -0400 |
---|---|---|
committer | B. Watson <yalhcru@gmail.com> | 2020-07-05 21:03:38 -0400 |
commit | 94ea7a8cd41b5b0cebf2606f4319ca5050e80520 (patch) | |
tree | 703f962eb3713871172e766565e4fa35b599b800 /smartfmt | |
parent | 135b6988a809f22a633d9a90273cd6447cfa85be (diff) | |
download | misc-scripts-94ea7a8cd41b5b0cebf2606f4319ca5050e80520.tar.gz |
Add some new stuff
Diffstat (limited to 'smartfmt')
-rwxr-xr-x | smartfmt | 51 |
1 files changed, 51 insertions, 0 deletions
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(<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; |