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?



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 GeneralUtilities`Strings`PackagePrivate`iInsertLinebreaks; the heavy lifting is carried out by two functions, GeneralUtilities`Strings`PackagePrivate`ilb, which ultimately calls GeneralUtilities`Strings`PackagePrivate`findSplits 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:

insertLineBreaks[str_String, n_Integer: 78, EOLseparator_String: "\n"] :=
   If[StringLength[str] < n, str,
       StringTake[str, GeneralUtilities`Strings`PackagePrivate`findSplits[StringPosition[str, Whitespace | EndOfLine], n]], 

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&
  dropper shiftlessness addle skulker&
  self-abasement cheerfulness martial assail&
  satyr intention melted headset workbench&
  church microcode alkalize the buckboard&
  semiofficial grow potboiler farthermost&
  riverside senatorial chockablock revolve&
  profitably helpful beget scuba anarchically"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.