All pastes #48550 Raw Edit

jink

public text v1 · immutable
#48550 ·published 2006-04-07 18:11 UTC
rendered paste body
sub Justify {
  my $string = shift || return(undef);
  my $width = shift || 80;
  my $return = '';
  $string =~ s/\r//g;
  my $last = '';
  my $temp = '';
  my($quote, $text) = ('', '');
  foreach my $line (split(/\n/, $string)) {
    if($line =~ /^((?:>\ ?)+)(.*)$/) {
      ($quote, $text) = ($1, $2);
    } else {
      ($quote, $text) = ('', $line);
    }
    # $return .= "($quote) ($text)\n";
    if($quote eq $last) {
      if($text =~ /^\s*$/) {
        if($temp ne '') { $return .= (&Just_Sub($temp, $width - length($last), $last) . "\n"); }
        $return .= "$quote\n";
        $temp = '';
      } else {
        $temp .= "$text ";
      }
    } else {
      if($text =~ /^\s*$/) {
        if($temp ne '') { $return .= (&Just_Sub($temp, $width - length($last), $last) . "\n"); }
        $return .= "$quote\n";
        $temp = '';
      } else {
        if($temp ne '') { $return .= (&Just_Sub($temp, $width - length($last), $last) . "\n"); }
        $temp = "$text ";
      }
      $last = $quote;
    }
  }
  if($temp ne '') { $return .= (&Just_Sub($temp, $width, $last) . "\n"); }
  $return =~ s/\n$//;
  return($return);
}

sub Just_Sub {
  my $string = shift || return(undef);
  my $width = shift || 80;
  my $prefix = shift || '';
  my $return = '';
  my @words = split(/\ /, $string);
  my $retline = '';
  foreach my $word (@words) {
    if(((length($retline) + length($word) + 1) < $width) || ($retline eq '')) {
      $retline .= "$word ";
    } else {
      $retline =~ s/\ +$//;
      $return .= "$prefix$retline\n";
      $retline = "$word ";
    }
  }
  if($retline ne '') { $retline =~ s/\ +$//;  $return .= "$prefix$retline\n"; }
  $return =~ s/\n+$//;
  return($return);
}