Hi,
Something tells me that there is no replacement for the human eye on this problem.
I completely agree with you. Nevertheless, the following script (beta version) seems to return the expected result for each and every example discussed so far in this thread. Please note however that it could not work as well with texts having more than one +extraordinarily longer+ than usual word.
Maybe you would like to try it.
--BEGINNING OF SCRIPT
splitString("one two three four five six extraordinarily_longer", 3) -- for example
on splitString(theText, N)
set theWords to words of theText
set TNW to count theWords -- total number of words
if N < 1 or N > TNW then return "Choose N between 1 and " & TNW & "."
--Provide for one extraordinarily longer word than usual :
set maxWordLength to length of item 1 of theWords
repeat with thisWord in rest of theWords
if length of thisWord > maxWordLength then set maxWordLength to length of thisWord
end repeat
set theLength to length of theText
set L0 to theLength / N -- average length of each line
if L0 < maxWordLength then set L0 to (theLength - maxWordLength) / (N - 1)
set theNewText to ""
set j to 0 -- number of lines
set CNW to 0 -- number of words in the first j lines
repeat (N - 1) times
set j to j + 1
set currentLine to ""
set L to 0 -- length of the current line
set k to 0 -- number of words in the current line
set endOfLine to false
repeat until L > L0
if TNW - CNW - k = N - j then
set endOfLine to true
exit repeat
end if
set k to k + 1
set L to length of (text 1 through word k of theText)
end repeat
if endOfLine then
set k to k + 1
set L to (length of (text 1 through word k of theText)) - (length of (word k of theText))
else
set L to L - (length of (word k of theText))
if L = 0 then
set k to k + 1
set L to (length of (text 1 through word k of theText)) - (length of word k of theText)
else -- Let's see if one more word wouldn't be better :
set k to k + 1
set L2 to (length of (text 1 through word k of theText)) - (length of (word k of theText))
if (L2 - L0) < (L0 - L) then set L to L2
end if
end if
set currentLine to text 1 through L of theText
set theText to text (L + 1) through -1 of theText -- the rest of the text
set CNW to CNW + (count words of currentLine)
set theNewText to theNewText & currentLine & character id 8232 -- end of line
end repeat
return theNewText & theText -- add the last line
end splitString
--END OF SCRIPT
Hope it can help.