3

My code (PostScriptForm) returns a long string, about 7k characters, in which there are eight deliberate “\r\n” ‘paragraph’ breaks.

Copying the long string into a text editor reveals “\\r” line breaks at the word breaks immediately prior to column 72. These are not wanted. But I would like “\r” (so without the visible back-slash) line breaks at the word break immediately prior to column 250.

Please, is this trivial in Mathematica? There seems not to be a “StringWrap” function—is there anything conceptually similar?

Update

I find the idea of using InsertLineBreaks appealing, even though it is available only in V10.1 or later.

jdaw1
  • 499
  • 2
  • 9

1 Answers1

1

I am not sure I correctly understand what you are asking, but I tried the following:

fox = "The quick brown fox jumped over the lazy dog. ";
longFox[n_] := StringJoin[Table[fox, {n}]]
long = longFox[10];
StringLength[long]

460

pw = CurrentValue[EvaluationNotebook[], "PageWidth"];
CurrentValue[EvaluationNotebook[], "PageWidth"] = 300 72;
Print[Style[InsertLinebreaks[long, 240], "Text"]];
CurrentValue[EvaluationNotebook[], "PageWidth"] = pw;

I then copied and pasted the the contents of the Print cell produced by the code into my text editor and the results were two lines of text, the 1st being 239 characters long and 2nd being 220 characters long.

I did this with V10.3.0 running on OS X 10.10.2. I state this because what happens with copy and paste may have OS dependencies.

This seems rather cumbersome to me, so I wouldn't be surprised that if somebody came up with a simpler method than this. Something based on Export might be such a simpler approach, but I did not explore in that direction because you seem to be specifically asking for something that works with copy and paste.

Update

Here is code using Export that I think will work with V.9.

makeLine[max_, size_: 0, line_: {}] :=
  Module[{word, chars = size,},
    If[Length[words] < 1, Return[StringRiffle[line]]];
    word = First[words];
    chars = size + StringLength[word] + 1;
    If[chars > max, Return[StringRiffle[line]]];
    words = Rest[words]; 
    makeLine[max, chars, Append[line, word]]]

makeLines[s_String, max_Integer: 78] /; max > 0 := Block[{words, lines = {}}, words = StringSplit[s]; If[Max[Length /@ words] > max, Return[{s}]]; While[Length[words] > 0, AppendTo[lines, makeLine[max]]]; lines]

Export[ FileNameJoin[{$HomeDirectory, "Desktop", "long.txt"}], makeLines[long, 240], "Lines"]

The Export expression writes the long string out to the desktop as two strings, the 1st being 239 characters long and 2nd being 220 characters long.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257