Line wrapping

Andreas,

I’m using the following function for line
wrapping (found it somewhere in the list
archive):

def wrap(s)
return s.gsub(/.{1,74}(?:\s|\Z)/){($& + 5.chr).
gsub(/\n\005/,“\n”).gsub(/\005/,“\n”)}
end

Any hints how I can change the function so
that it doesn’t touch lines with quoting
characters (“>”, “|”) in the beginning?

First of all, note that this routine leaves trailing spaces before the

inserted newlines (“\n”) and also requires that the string not contain any
ASCII 5 characters (“\005”). Both of these can be (mostly) fixed by
changing the routine to the much simpler:

def wrap(s)
s.gsub(/(.{1,74})(\s+|\Z)/,“\1\n”)
end

However if the string contains multiple adjacent spaces, they may not

all be removed. This can be remedied by appending a “.gsub(/ +\n/,‘’)” to
the end of the existing gsub().

Also note that this method is complicated by the fact that it allows for

preexisting newlines in the string parameter. If your strings don’t already
have newlines (and you still don’t want trailing spaces), you can rewrite
the method to:

def wrap(s)
s.gsub(/(.{1,74})(\s+|$)/,“\1\n”)
end

All that being said, your question is a little ambiguous.  The word

“lines” could refer to the method’s string parameter as a whole, or it could
refer to individual substrings in that parameter separated by newlines. If
you meant the former, any of these routines can be easily modified to ignore
strings beginning with “>” or “|” by adding one line:

def wrap(s)
return s if s =~ /[1]/
s.gsub(/(.{1,74})(\s+|$)/,“\1\n”)
end

If you meant the latter, it's a little more complicated - you basically

need to split the strings into an array, word wrap all the single lines in
the array, and then join them all back together:

def wrap(s)
s.split(“\n”).map do |t|
if t =~ /[2]/
t + “\n”
else
t.gsub(/(.{1,74})(\s+|$)/,“\1\n”)
end
end.join(‘’)
end

I hope this helps!

- Warren Brown

  1. >| ↩︎

  2. >| ↩︎

Scripsit ille aut illa »Warren Brown« wkb@airmail.net:

def wrap(s)
s.gsub(/(.{1,74})(\s+|\Z)/,“\1\n”)
end

However if the string contains multiple adjacent spaces, they may not

all be removed. This can be remedied by appending a “.gsub(/ +\n/,‘’)” to
the end of the existing gsub().

Why not just

s.gsub(/(.{0,73}\S)(\s+|\Z)/,“\1\n”)

(untested)

···


Steck Dir Deine Erkenntnisse da hin wo sie hingehören! Du kleiner\n
verklemmter Hosenmatz!\nIch wette, Du bist picklig und für jede Frau
abschreckend. Kein Wunder, daß\nDu Dich hier so produzierst.
[“Lucrezia d`Lacroix” aka “Rebecca di Lorenzo” aka “Thomas Wendt”]