aboutsummaryrefslogtreecommitdiff
path: root/smartfmt
diff options
context:
space:
mode:
Diffstat (limited to 'smartfmt')
-rwxr-xr-xsmartfmt51
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;