# Line break a long expression only at whitespace

Suppose I have some long string expression. I want to break this into multiple lines,with an ampersand at the end of each line.

My first attempt was of the form,

StringInsert[expr, " &\n", #] &@Range[120, StringLength@expr, 120]


where expr is some long expression.

This works but has the problem that sometimes variables are split over multiple lines e.g.

variable ---> var / iable


Is there a way to force new lines, only at whitespace,thus avoiding the variable-splitting problem?

Thanks

Mathematica has an InsertLinebreaks function that, it seems to me, almost completely fulfills your needs, expect that it defaults to using a simple carriage return to break lines.

Fortunately for us, the function is implemented at the top level, so we can peer into its code. The functionality is implemented in GeneralUtilitiesStringsPackagePrivateiInsertLinebreaks; the heavy lifting is carried out by two functions, GeneralUtilitiesStringsPackagePrivateilb, which ultimately calls GeneralUtilitiesStringsPackagePrivatefindSplits to find the appropriate positions to split the string, which is really the cumbersome part. We can use that function directly though, and write out own wrapper to which we can feed a customized end-of-line character:

Clear[insertLineBreaks]
insertLineBreaks[str_String, n_Integer: 78, EOLseparator_String: "\n"] :=
StringJoin@
If[StringLength[str] < n, str,
Riffle[
StringTake[str, GeneralUtilitiesStringsPackagePrivatefindSplits[StringPosition[str, Whitespace | EndOfLine], n]],
EOLseparator
]
]


Let's generate some sample data and try the function out:

string = StringRiffle@RandomWord["CommonWords", 50];

insertLineBreaks[string, 45, "& \n"]

(* Out:
"scruple bedsitter pus applicable confide&
pillbox tabbouleh gosling thumping elocution&
pharyngitis pungent spiller willful worksheet&
banger twinkling arithmetically sheared&