Word wrap: Difference between revisions

64,727 bytes added ,  3 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(39 intermediate revisions by 29 users not shown)
Line 17:
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimimumminimum length algorithm.
 
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
 
 
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Go}}
 
<syntaxhighlight lang="11l">F word_wrap(text, line_width)
V words = text.split_py()
I words.empty
R ‘’
V wrapped = words[0]
V space_left = line_width - wrapped.len
L(word) words[1..]
I word.len + 1 > space_left
wrapped ‘’= "\n"word
space_left = line_width - word.len
E
wrapped ‘’= ‘ ’word
space_left -= 1 + word.len
R wrapped
 
V frog = ‘
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.’
 
L(width) (72, 80)
print(‘Wrapped at ’width":\n"word_wrap(frog, width))
print()</syntaxhighlight>
 
{{out}}
<pre>
Wrapped at 72:
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime-tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.
 
Wrapped at 80:
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime-tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
 
</pre>
 
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Word wrap 29/01/2017
WORDWRAP CSECT
USING WORDWRAP,R13
Line 189 ⟶ 250:
LA R4,S1
LH R5,LENS1
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s1,1,lens1)
XPRNT PG,L'PG put skip list(pg)
Line 210 ⟶ 271:
LA R4,S2
LH R5,LENS2
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s2,1,lens2)
XPRNT PG,L'PG put skip list(pg)
Line 247 ⟶ 308:
PG DS CL80
YREGS
END WORDWRAP</langsyntaxhighlight>
{{out}}
<pre>
Line 268 ⟶ 329:
caught it, and this ball was her
favorite plaything.
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">CHAR ARRAY text(1000)
CARD length
 
PROC AppendText(CHAR ARRAY part)
BYTE i
 
FOR i=1 TO part(0)
DO
text(length)=part(i)
length==+1
OD
RETURN
 
INT FUNC GetPosForWrap(BYTE lineLen INT start)
INT pos
 
pos=start+lineLen
IF pos>=length THEN
RETURN (length-1)
FI
 
WHILE pos>start AND text(pos)#32
DO
pos==-1
OD
 
IF pos=start THEN
pos=start+lineLen
ELSE
pos==-1
FI
RETURN (pos)
 
PROC PrintTextWrapped(BYTE lineLen)
INT i,pos
BYTE wrap,screenWidth=[40]
 
i=0
WHILE i<length
DO
pos=GetPosForWrap(lineLen,i)
IF pos-i=screenWidth-1 OR pos=length-1 THEN
wrap=0
ELSE
wrap=1
FI
 
WHILE i<=pos
DO
Put(text(i))
i==+1
OD
WHILE i<length AND text(i)=32
DO
i==+1
OD
 
IF wrap THEN
PutE()
FI
OD
RETURN
 
PROC Test(BYTE lineLen)
BYTE CH=$02FC
 
Put(125) ;clear screen
PrintF("Line length=%B%E%E",lineLen)
PrintTextWrapped(lineLen)
PrintF("%E%EPress any key to continue...")
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN
 
PROC Main()
BYTE LMARGIN=$52,old
 
length=0
AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ")
AppendText("Maecenas varius sapien vel purus hendrerit vehicula. ")
AppendText("Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. ")
AppendText("Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. ")
AppendText("Proin blandit lacus vitae nibh tincidunt cursus. ")
AppendText("Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. ")
AppendText("Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. ")
AppendText("Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. ")
AppendText("Nam vel tortor nisi. Sed eget porta tortor. ")
AppendText("Aliquam suscipit lacus vel odio faucibus tempor. ")
AppendText("Sed ipsum est, condimentum eget eleifend ac, ultricies non dui.")
 
old=LMARGIN
LMARGIN=0 ;remove left margin on the screen
 
Test(40)
Test(30)
Test(20)
 
LMARGIN=old ;restore left margin on the screen
RETURN
</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Word_wrap.png Screenshot from Atari 8-bit computer]
<pre>
Line length=40
 
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas varius sapien
...
Sed ipsum est, condimentum eget eleifend
ac, ultricies non dui.
 
Press any key to continue...
 
Line length=30
 
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
...
condimentum eget eleifend ac,
ultricies non dui.
 
Press any key to continue...
 
Line length=20
 
Lorem ipsum dolor
sit amet,
...
eleifend ac,
ultricies non dui.
</pre>
 
=={{header|Ada}}==
The specification of a class '''Word_Wrap.Basic''' in a package '''Word_Wrap''':
<langsyntaxhighlight Adalang="ada">generic
with procedure Put_Line(Line: String);
package Word_Wrap is
Line 289 ⟶ 484:
end record;
 
end Word_Wrap;</langsyntaxhighlight>
 
The implementation of that package:
 
<langsyntaxhighlight Adalang="ada">package body Word_Wrap is
 
procedure Push_Word(State: in out Basic; Word: String) is
Line 328 ⟶ 523:
end Finish;
 
end Word_Wrap;</langsyntaxhighlight>
 
Finally, the main program:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line;
 
procedure Wrap is
Line 393 ⟶ 588:
end loop;
Wrapper.Finish;
end Wrap;</langsyntaxhighlight>
 
{{out}} set to 72 lines (with input picked by cut-and-paste from the task description):
Line 418 ⟶ 613:
For more sophisticated algorithms (the extra credit), one could derive
a class '''Word_Wrap.<something>''' from '''Word_Wrap.Basic'''.
 
=={{header|AppleScript}}==
Being a scripting language, AppleScript would normally be used just to tell some scriptable text process what fonts and margins to use and leave that process to sort out its own wraps. But the "greedy" algorithm's easy to implement for line widths measured in characters:
 
<syntaxhighlight lang="applescript">on wrapParagraph(para, lineWidth)
if (para is "") then return para
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {space, tab} -- Doesn't include character id 160 (NO-BREAK SPACE).
script o
property wrds : para's text items -- Space- or tab-delimited chunks.
end script
set spaceWidth to (count space) -- ;-)
set spaceLeft to lineWidth
set theLines to {}
set i to 1
repeat with j from 1 to (count o's wrds)
set wordWidth to (count item j of o's wrds)
if (wordWidth + spaceWidth > spaceLeft) then
set end of theLines to text 1 thru (-1 - wordWidth) of (text from text item i to text item j of para)
set i to j
set spaceLeft to lineWidth - wordWidth
else
set spaceLeft to spaceLeft - (wordWidth + spaceWidth)
end if
end repeat
set end of theLines to text from text item i to end of para
set AppleScript's text item delimiters to character id 8232 -- U+2028 (LINE SEPARATOR).
set output to theLines as text
set AppleScript's text item delimiters to astid
return output
end wrapParagraph
 
local para
set para to "If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia."
return wrapParagraph(para, 70) & (linefeed & linefeed) & wrapParagraph(para, 40)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"If there is a way to do this that is built-in, trivial, or provided
in a standard library, show that. Otherwise implement the minimum
length greedy algorithm from Wikipedia.
 
If there is a way to do this that is
built-in, trivial, or provided in a
standard library, show that. Otherwise
implement the minimum length greedy
algorithm from Wikipedia."</syntaxhighlight>
 
However, it's more efficient to look for the last space in each line than to see how many "words" will fit:
 
<syntaxhighlight lang="applescript">on wrapParagraph(para, lineWidth)
set theLines to {}
set spaceTab to space & tab
set len to (count para)
set i to 1
repeat until (i > len)
set j to i + lineWidth - 1
if (j < len) then
repeat with j from j to i by -1
if (character j of para is in spaceTab) then exit repeat
end repeat
-- The "greedy" algorithm keeps words which are longer than or
-- the same length as the line width intact. Do the same here.
if (j = i) then
repeat with j from (i + lineWidth) to len
if (character j of para is in spaceTab) then exit repeat
end repeat
end if
else
set j to len
end if
set end of theLines to text i thru j of para
set i to j + 1
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to character id 8232 -- U+2028 (LINE SEPARATOR).
set output to theLines as text
set AppleScript's text item delimiters to astid
return output
end wrapParagraph</syntaxhighlight>
 
Using AppleScriptObjC, the second approach can be achieved with a regular expression:
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
on wrapParagraph(para, lineWidth)
if (para is "") then return para
set str to current application's class "NSMutableString"'s stringWithString:(para)
-- Replace each run of up to (lineWidth - 1) characters followed by a space or a tab,
-- or by the end of the paragraph, with itself and a LINE SEPARATOR character.
tell str to replaceOccurrencesOfString:(".{1," & (lineWidth - 1) & "}(?:[ \\t]|\\Z)") withString:("$0" & character id 8232) ¬
options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})
-- Remove the LINE SEPARATOR inserted at the end.
tell str to replaceOccurrencesOfString:(character id 8232) withString:("") ¬
options:(0) range:({(its |length|()) - 2, 2})
return str as text
end wrapParagraph</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">txt: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."
 
print wordwrap txt
print ""
print wordwrap.at:45 txt</syntaxhighlight>
 
{{out}}
 
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec
consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero
egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem
lacinia consectetur.
 
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Donec a diam lectus. Sed sit
amet ipsum mauris. Maecenas congue ligula ac
quam viverra nec consectetur ante hendrerit.
Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue.
Nam tincidunt congue enim, ut porta lorem
lacinia consectetur.</pre>
 
=={{header|AutoHotkey}}==
Basic word-wrap. Formats text that has been copied to the clipboard.
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
return
 
WrapText(Text, LineLength) {
StringReplace, Text, Text, `r`n, %A_Space%, All
while (p := RegExMatch(Text, "(.{1," LineLength "})(\s|\R+|$)", Match, p ? p + StrLen(Match) : 1))
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
return, Result
}</langsyntaxhighlight>
{{Out}}
<pre>72
Line 456 ⟶ 779:
Basic word wrap.
 
<langsyntaxhighlight lang="awk">function wordwrap_paragraph(p)
{
if ( length(p) < 1 ) return
Line 495 ⟶ 818:
END {
wordwrap_paragraph(par)
}</langsyntaxhighlight>
 
To test it,
Line 504 ⟶ 827:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">paragraph$ = "In olden times when wishing still helped one," \
" there lived a king whose daughters were all beautiful, but" \
" the youngest was so beautiful that the sun itself, which has" \
Line 516 ⟶ 839:
 
PRINT ALIGN$(paragraph$, 72, 0)
PRINT ALIGN$(paragraph$, 90, 0)</langsyntaxhighlight>
BaCon has the ALIGN$ function which can align text left-side, right-side, centered or both sides at any given column.
{{out}}
Line 540 ⟶ 863:
=={{header|Batch File}}==
Basic word wrap.
<langsyntaxhighlight lang="dos">@echo off
 
set "input=Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur!"
Line 579 ⟶ 902:
)
endlocal & set "line=%line%"
goto proc_loop</langsyntaxhighlight>
{{Out}}
<pre>Lorem ipsum dolor sit amet, consectetur
Line 598 ⟶ 921:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( str
$ ( "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
Line 626 ⟶ 949:
& out$(str$("72 columns:\n" wrap$(!Text.72)))
& out$(str$("\n80 columns:\n" wrap$(!Text.80)))
);</langsyntaxhighlight>
{{out}}
<pre>72 columns:
Line 650 ⟶ 973:
 
=={{header|C}}==
===Smart wrapping===
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 657 ⟶ 981:
/* nonsensical hyphens to make greedy wrapping method look bad */
const char *string = "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
"that the sun itself, which has seen so much, was astonished whenever "
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "
"forest, and under an old lime-tree in the forest was a well, and when "
"the day was very warm, the king's child went out into the forest and "
"sat down by the side of the cool-fountain, and when she was bored she "
"took a golden ball, and threw it up on high and caught it, and this "
"ball was her favorite plaything.";
 
/* Each but the last of wrapped lines comes with some penalty as the square
of the diff between line length and desired line length. If the line
is longer than desired length, the penalty is multiplied by 100. This
pretty much prohibits the wrapping routine from going over right margin.
If is ok to exceed the margin just a little, something like 20 or 40 will
do.
 
Knuth uses a per-paragraph penalty for line-breaking in TeX, which is--
unlike what I have here--probably bug-free.
*/
 
#define PENALTY_LONG 100
#define PENALTY_SHORT 1
 
typedef struct word_t {
const char *s;
int len;
} *word;
 
word make_word_list(const char *s, int *n)
{
int max_n = 0;
word words = 0;
 
*n = 0;
while (1) {
while (*s && isspace(*s)) s++;
if (!*s) break;
 
if (*n >= max_n) {
if (!(max_n *= 2)) max_n = 2;
words = realloc(words, max_n * sizeof(*words));
}
}
words[*n].s = s;
while (*s && !isspace(*s)) s++;
words[*n].len = s - words[*n].s;
(*n) ++;
}
}
 
return words;
}
 
int greedy_wrap(word words, int count, int cols, int *breaks)
{
int score = 0, line, i, j, d;
 
i = j = line = 0;
while (1) {
if (i == count) {
breaks[j++] = i;
break;
}
}
 
if (!line) {
line = words[i++].len;
continue;
}
}
 
if (line + words[i].len < cols) {
line += words[i++].len + 1;
continue;
}
}
 
breaks[j++] = i;
if (i < count) {
d = cols - line;
if (d > 0) score += PENALTY_SHORT * d * d;
else if (d < 0) score += PENALTY_LONG * d * d;
}
}
 
line = 0;
}
}
breaks[j++] = 0;
 
return score;
}
 
/* tries to make right margin more even; pretty sure there's an off-by-one bug
here somewhere */
int balanced_wrap(word words, int count, int cols, int *breaks)
{
int *best = malloc(sizeof(int) * (count + 1));
 
/* do a greedy wrap to have some baseline score to work with, else
we'll end up with O(2^N) behavior */
int best_score = greedy_wrap(words, count, cols, breaks);
 
void test_wrap(int line_no, int start, int score) {
int line = 0, current_score = -1, d;
 
while (start <= count) {
if (line) line ++;
line += words[start++].len;
d = cols - line;
if (start < count || d < 0) {
if (d > 0)
current_score = score + PENALTY_SHORT * d * d;
else
else
current_score = score + PENALTY_LONG * d * d;
} else {
current_score = score;
}
}
 
if (current_score >= best_score) {
if (d <= 0) return;
continue;
}
}
 
best[line_no] = start;
test_wrap(line_no + 1, start, current_score);
}
}
if (current_score >= 0 && current_score < best_score) {
best_score = current_score;
memcpy(breaks, best, sizeof(int) * (line_no));
}
}
}
}
test_wrap(0, 0, 0);
free(best);
 
return best_score;
}
 
void show_wrap(word list, int count, int *breaks)
{
int i, j;
for (i = j = 0; i < count && breaks[i]; i++) {
while (j < breaks[i]) {
printf("%.*s", list[j].len, list[j].s);
if (j < breaks[i] - 1)
putchar(' ');
j++;
}
}
if (breaks[i]) putchar('\n');
}
}
}
 
int main(void)
{
int len, score, cols;
word list = make_word_list(string, &len);
int *breaks = malloc(sizeof(int) * (len + 1));
 
cols = 80;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
 
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
 
 
cols = 32;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
 
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
 
return 0;
}</langsyntaxhighlight>
 
===In-place greedy===
Long words exceeding the line length are not wrapped.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <string.h>
 
void wrap_text(char *line_start, int width) {
char *last_space = 0;
char *p;
 
for (p = line_start; *p; p++) {
if (*p == '\n') {
line_start = p + 1;
}
 
if (*p == ' ') {
last_space = p;
}
 
if (p - line_start > width && last_space) {
*last_space = '\n';
line_start = last_space + 1;
last_space = 0;
}
}
}
 
char const text[] =
"In olden times when wishing still helped one, there lived a king whose "
"daughters were all beautiful, but the youngest was so beautiful that the "
"sun itself, which has seen so much, was astonished whenever it shone in "
"her face. Close by the king's castle lay a great dark forest, and under "
"an old lime-tree in the forest was a well, and when the day was very "
"warm, the king's child went out into the forest and sat down by the side "
"of the cool fountain, and when she was bored she took a golden ball, and "
"threw it up on high and caught it, and this ball was her favorite "
"plaything.";
 
int main(void) {
char buf[sizeof(text)];
 
puts("--- 80 ---");
memcpy(buf, text, sizeof(text));
wrap_text(buf, 80);
puts(buf);
 
puts("\n--- 72 ---");
memcpy(buf, text, sizeof(text));
wrap_text(buf, 72);
puts(buf);
}
</syntaxhighlight>
{{out}}
<pre>
--- 80 ---
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime-tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
 
--- 72 ---
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime-tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.
</pre>
 
=={{header|C sharp}}==
Greedy algorithm:
<langsyntaxhighlight lang="csharp">namespace RosettaCode.WordWrap
{
using System;
Line 895 ⟶ 1,295:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>------------------------------------------------------------------------
Line 926 ⟶ 1,326:
Basic task.
{{trans|Go}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <string>
Line 969 ⟶ 1,369:
std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 994 ⟶ 1,394:
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">;; Wrap line naive version
(defn wrap-line [size text]
(loop [left size line [] lines []
Line 1,006 ⟶ 1,406:
(recur (- size wlen) [word] (conj lines (apply str line)) (next words))))
(when (seq line)
(conj lines (apply str line))))))</langsyntaxhighlight>
 
<langsyntaxhighlight Clojurelang="clojure">;; Wrap line base on regular expression
(defn wrap-line [size text]
(re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}"))
(clojure.string/replace text #"\n" " ")))</langsyntaxhighlight>
 
<langsyntaxhighlight Clojurelang="clojure">;; cl-format based version
(defn wrap-line [size text]
(clojure.pprint/cl-format nil (str "~{~<~%~1," size ":;~A~> ~}") (clojure.string/split text #" ")))</langsyntaxhighlight>
 
Usage example :
<langsyntaxhighlight Clojurelang="clojure">(def text "In olden times when wishing still helped one, there lived
a king whose daughters were all beautiful, but the youngest was so
beautiful that the sun itself, which has seen so much, was astonished
Line 1,029 ⟶ 1,429:
 
(doseq [line (wrap-line 72 text)]
(println line))</langsyntaxhighlight>
 
{{out}}
Line 1,041 ⟶ 1,441:
threw it up on high and caught it, and this ball was her favorite
plaything.</pre>
 
=={{header|Commodore BASIC}}==
 
Nothing terribly fancy. Except for screen control codes, this should actually work on a wide variety of 8-bit BASIC outside of the Commodore realm. Note that strings are limited to 255 total characters, and <code>INPUT</code> will retrieve only a limited number of characters (less than 80 on the Commodore 64) even for a string, not to mention that special characters such as comma, semicolon, etc. have special meaning and are not captured.
 
<syntaxhighlight lang="gwbasic">10 rem word wrap - commodore basic
20 rem rosetta code
30 s$="":co=40:gosub 200
35 print chr$(147);chr$(14)
40 print "The current string is:"
41 print chr$(18);s$;chr$(146)
42 print:print "Enter a string, blank to keep previous,"
43 print "or type 'sample' to use a preset"len(z$)" character string."
44 print:input s$:if s$="sample" then s$=z$
45 print:print "enter column limit, 10-80 [";co;"{left}]";:input co
46 if co<12 or co>80 then goto 45
50 print chr$(147);"Wrapping on column";co;"results as:"
55 gosub 400
60 print
65 print r$
70 print
80 input "Again (y/n)";yn$
90 if yn$="y" then goto 35
100 end
200 rem set up sample string
205 data "Lorem Ipsum is typically a corrupted version of 'De finibus "
210 data "bonorum et malorum', a first-century BC text by the Roman statesman "
215 data "and philosopher Cicero, with words altered, added, and removed to "
220 data "make it nonsensical, improper Latin."
225 data "zzz"
230 z$=""
235 read tp$:if tp$<>"zzz" then z$=z$+tp$:goto 235
240 return
400 rem word-wrap string
401 tp$=s$:as$=""
405 if len(tp$)<=co then goto 440
410 for i=0 to co-1:c$=mid$(tp$,co-i,1)
420 if c$<>" " and c$<>"-" then next i
425 ad$=chr$(13):if c$="-" then ad$="-"+chr$(13)
430 as$=as$+left$(tp$,co-1-i)+ad$:tp$=mid$(tp$,co-i+1,len(tp$)):i=0
435 goto 405
440 as$=as$+tp$
450 r$=as$
460 return</syntaxhighlight>
 
{{out}}
 
<pre>Wrapping on column 40 results as:
Lorem Ipsum is typically a corrupted
version of 'De finibus bonorum et
malorum', a first-century BC text by
the Roman statesman and philosopher
Cicero, with words altered, added, and
removed to make it nonsensical,
improper Latin.
Again (y/n)? y
 
 
...
 
 
Wrapping on column 20 results as:
Lorem Ipsum is
typically a
corrupted version
of 'De finibus
bonorum et
malorum', a first-
century BC text by
the Roman statesman
and philosopher
Cicero, with words
altered, added, and
removed to make it
nonsensical,
improper Latin.
Again (y/n)? n
 
ready.
&#9608;</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight Lisplang="lisp">;; Greedy wrap line
 
(defun greedy-wrap (str width)
Line 1,056 ⟶ 1,540:
(push (subseq str begin-curr-line prev-space) lines)
(setq begin-curr-line (1+ prev-space)) )))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,091 ⟶ 1,575:
=={{header|D}}==
===Standard Version===
<langsyntaxhighlight lang="d">void main() {
immutable frog =
"In olden times when wishing still helped one, there lived a king
Line 1,106 ⟶ 1,590:
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</langsyntaxhighlight>
{{out}}
<pre>Wrapped at 72:
Line 1,133 ⟶ 1,617:
Basic algorithm. The text splitting is lazy.
{{trans|Go}}
<langsyntaxhighlight lang="d">import std.algorithm;
 
string wrap(in string text, in int lineWidth) {
Line 1,167 ⟶ 1,651:
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</langsyntaxhighlight>
{{out}}
<pre>Wrapped at 72:
Line 1,189 ⟶ 1,673:
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
const TestStr: string =
'In olden times when wishing still helped one, there lived a king whose '+
'daughters were all beautiful, but the youngest was so beautiful that the '+
'sun itself, which has seen so much, was astonished whenever it shone in '+
'her face. Close by the king''''s castle lay a great dark forest, and under '+
'an old lime tree in the forest was a well, and when the day was very '+
'warm, the king''''s child went out into the forest and sat down by the side '+
'of the cool fountain, and when she was bored she took a golden ball, and '+
'threw it up on high and caught it, and this ball was her favorite plaything.';
 
 
function ExtractToken(S: string; Sep: TASCIICharSet; var P: integer): string;
{Extract token from S, starting at P up to but not including Sep}
{Terminates with P pointing past Sep or past end of string}
var C: char;
begin
Result:='';
while P<=Length(S) do
begin
C:=S[P]; Inc(P);
if C in Sep then break
else Result:=Result+C;
end;
end;
 
 
 
function WrapLines(S: string; WrapCol: integer): string;
{Returns S, with lines wrapped a specified column}
var Inx,J: integer;
var WordStr,LineStr: string;
begin
Result:='';
Inx:=1;
LineStr:='';
while true do
begin
{Grab next word}
WordStr:=ExtractToken(S,[#$20,#$09,#$0D,#$0A],Inx);
{Check to see if adding this word will exceed the column}
if (Length(LineStr)+Length(WordStr))<WrapCol then
begin
{If not, add to current line}
if Length(LineStr)>0 then LineStr:=LineStr+' ';
LineStr:=LineStr+WordStr;
end
else
begin
{Save the line to the output string}
Result:=Result+LineStr+CRLF;
LineStr:=WordStr;
end;
if Inx>Length(S) then break;
end;
if Length(LineStr)>0 then Result:=Result+LineStr;
end;
 
 
procedure DrawRuler(Memo: TMemo);
begin
Memo.Lines.Add(' 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80');
Memo.Lines.Add('----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|');
end;
 
 
procedure ShowWordWrap(Memo: TMemo);
var S: string;
begin
DrawRuler(Memo);
S:=WrapLines(TestStr,60);
Memo.Lines.Add(S);
 
DrawRuler(Memo);
S:=WrapLines(TestStr,40);
Memo.Lines.Add(S);
 
DrawRuler(Memo);
S:=WrapLines(TestStr,20);
Memo.Lines.Add(S);
end;
 
 
 
 
</syntaxhighlight>
{{out}}
<pre>
Wrap at column 60
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80
----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
In olden times when wishing still helped one, there lived a
king whose daughters were all beautiful, but the youngest
was so beautiful that the sun itself, which has seen so
much, was astonished whenever it shone in her face. Close
by the king''s castle lay a great dark forest, and under an
old lime tree in the forest was a well, and when the day
was very warm, the king''s child went out into the forest
and sat down by the side of the cool fountain, and when she
was bored she took a golden ball, and threw it up on high
and caught it, and this ball was her favorite plaything.
 
Wrap at column 40
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80
----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
In olden times when wishing still
helped one, there lived a king whose
daughters were all beautiful, but the
youngest was so beautiful that the sun
itself, which has seen so much, was
astonished whenever it shone in her
face. Close by the king''s castle lay a
great dark forest, and under an old
lime tree in the forest was a well,
and when the day was very warm, the
king''s child went out into the forest
and sat down by the side of the cool
fountain, and when she was bored she
took a golden ball, and threw it up on
high and caught it, and this ball was
her favorite plaything.
 
Wrap at column 20
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80
----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
In olden times when
wishing still helped
one, there lived a
king whose daughters
were all beautiful,
but the youngest was
so beautiful that
the sun itself,
which has seen so
much, was astonished
whenever it shone in
her face. Close by
the king''s castle
lay a great dark
forest, and under an
old lime tree in
the forest was a
well, and when the
day was very warm,
the king''s child
went out into the
forest and sat down
by the side of the
cool fountain, and
when she was bored
she took a golden
ball, and threw it
up on high and
caught it, and this
ball was her
favorite plaything.
 
Elapsed Time: 27.316 ms.
 
</pre>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">let loremIpsum = <[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.]>
func wrap(text, lineWidth) {
String.Concat(values: wrapWords(text.Split('\s', '\r', '\n'), lineWidth))
}
and wrapWords(words, lineWidth) {
var currentWidth = 0
for word in words {
if currentWidth != 0 {
if currentWidth + word.Length() < lineWidth {
currentWidth += 1
yield " "
} else {
currentWidth = 0
yield "\n"
}
}
currentWidth += word.Length()
yield word
}
}
and printWrap(at) {
print("Wrap at \(at):")
print(wrap(loremIpsum, at))
print()
}
printWrap(at: 72)
printWrap(at: 80)</syntaxhighlight>
 
{{out}}
 
<pre>Wrap at 72:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius
sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis,
ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet
rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt
cursus. Cum sociis natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et
aliquam dui gravida. Nulla consectetur sem vel felis vulputate et
imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor.
Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc
sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus
enim eu nibh.
 
Wrap at 80:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.</pre>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
linew = 40
#
ind = 1
repeat
if ind > len words$[]
inp$ = input
words$[] = strsplit inp$ " "
ind = 1
.
until inp$ = ""
w$ = words$[ind]
ind += 1
if len out$ + len w$ + 1 <= linew
if out$ <> ""
out$ &= " "
.
out$ &= w$
else
print out$
out$ = w$
.
.
print out$
#
input_data
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.’
 
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import extensions'text;
Line 1,215 ⟶ 1,978:
^ TokenEnumerator
.new(self)
.selectBy::(word)
{
currentWidth += word.Length;
Line 1,222 ⟶ 1,985:
currentWidth := word.Length + 1;
^ newLinenewLineConstant + word + " "
}
else
Line 1,241 ⟶ 2,004:
console.printLine(new StringWriter("-", 80));
console.printLine(text.wrap(80));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,267 ⟶ 2,030:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Word_wrap do
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
Line 1,293 ⟶ 2,056:
IO.puts String.duplicate("-", len)
IO.puts Word_wrap.paragraph(text, len)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,313 ⟶ 2,076:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( word_wrap ).
 
Line 1,319 ⟶ 2,082:
 
paragraph( String, Max_line_length ) ->
Lines = lines( string:tokens(String, " "), Max_line_length ),
string:join( Lines, "\n" ).
 
task() ->
Paragraph = "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.",
io:fwrite( "~s~n~n", [paragraph(Paragraph, 72)] ),
io:fwrite( "~s~n~n", [paragraph(Paragraph, 80)] ).
 
 
 
lines( [Word | T], Max_line_length ) ->
{Max_line_length, _Length, Last_line, Lines} = lists:foldl( fun lines_assemble/2, {Max_line_length, erlang:length(Word), Word, []}, T ),
lists:reverse( [Last_line | Lines] ).
 
lines_assemble( Word, {Max, Line_length, Line, Acc} ) when erlang:length(Word) + Line_length > Max -> {Max, erlang:length(Word), Word, [Line | Acc]};
lines_assemble( Word, {Max, Line_length, Line, Acc} ) -> {Max, Line_length + 1 + erlang:length(Word), Line ++ " " ++ Word, Acc}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,355 ⟶ 2,118:
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang="fsharp">open System
 
let LoremIpsum = "
Line 1,394 ⟶ 2,157:
Wrap l n |> Seq.iter (printf "%s")
printfn ""
0</langsyntaxhighlight>
{{out}}
<pre style="font-size:smaller">------------------------------------------------------------------------
Line 1,423 ⟶ 2,186:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: wrap.strings
IN: scratchpad "Most languages in widespread use today are applicative languages
: the central construct in the language is some form of function call, where a f
Line 1,434 ⟶ 2,197:
ns are invoked simply by mentioning their name without any additional syntax, Fo
rth and Factor refer to functions as words, because in the syntax they really ar
e just words." [ 60 wrap-string print nl ] [ 45 wrap-string print ] bi</langsyntaxhighlight>
{{out}}
<pre>
Line 1,474 ⟶ 2,237:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ wrap text
\ usage: gforth wrap.f in.txt 72
 
Line 1,499 ⟶ 2,262:
2dup strip-nl
.wrapped
bye</langsyntaxhighlight>
 
=={{header|Fortran}}==
Early Fortran provided no facility for manipulating text until the A format code was introduced by Fortran 4 that allowed characters to be read into variables, which could then be manipulated and written out. F77 introduced the CHARACTER data type which however did not have a notion of a variable-length string, other than via the programmer keeping track with auxiliary variables. F90 enabled the introduction via user-written functions and data types of a string-like facility, whereby a CHARACTER type variable would be resized on assignment. F95 formalised this facility as a part of the language.
 
There are no facilities for "flowing" text on output according to a specified width, though various direct methods are possible. For instance, given a variable containing thousands of characters, <langsyntaxhighlight Fortranlang="fortran"> CHARACTER*12345 TEXT
...
DO I = 0,120
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
END DO</langsyntaxhighlight>
would write forth the text with eighty characters per line, paying no attention to the content when it splits a line.
 
Line 1,518 ⟶ 2,281:
 
Should there be no suitable split in the fragment being appended, then, arbitrarily, if that fragment is short then it is not appended: the line is rolled with trailing spaces. But if it has more than six characters, it will be placed and a crude chop made.
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE RIVERRUN !Schemes for re-flowing wads of text to a specified line length.
INTEGER BL,BLIMIT,BM !Fingers for the scratchpad.
PARAMETER (BLIMIT = 222) !This should be enough for normal widths.
CHARACTER*(BLIMIT) BUMF !The scratchpad, accumulating text.
INTEGER OUTBUMF !Output unit number.
DATA OUTBUMF/0/ !Thus detect inadequate initialisation.
PRIVATE BL,BLIMIT,BM !These names are not so unusual
PRIVATE BUMF,OUTBUMF !That no other routine will use them.
CONTAINS
INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank.
Concocted yet again by R.N.McLean (whom God preserve) December MM.
Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!
Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces.
Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.
Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.
Line 1,538 ⟶ 2,301:
Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!
Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.
CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back.
INTEGER L !The length of the bumf.
L = LEN(TEXT) !So, what is it?
1 IF (L.LE.0) GO TO 2 !Are we there yet?
IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also.
L = L - 1 !Step back one.
GO TO 1 !And try again.
2 LSTNB = L !The last non-blank, possibly zero.
RETURN !Unsafe to use LSTNB as a variable.
END FUNCTION LSTNB !Compilers can bungle it.
 
SUBROUTINE STARTFLOW(OUT,WIDTH) !Preparation.
INTEGER OUT !Output device.
INTEGER WIDTH !Width limit.
OUTBUMF = OUT !Save these
BM = WIDTH !So that they don't have to be specified every time.
IF (BM.GT.BLIMIT) STOP "Too wide!" !Alas, can't show the values BLIMIT and WIDTH.
BL = 0 !No text already waiting in BUMF
END SUBROUTINE STARTFLOW!Simple enough.
 
SUBROUTINE FLOW(TEXT) !Add to the ongoing BUMF.
CHARACTER*(*) TEXT !The text to append.
INTEGER TL !Its last non-blank.
INTEGER T1,T2 !Fingers to TEXT.
INTEGER L !A length.
IF (OUTBUMF.LT.0) STOP "Call STARTFLOW first!" !Paranoia.
TL = LSTNB(TEXT) !No trailing spaces, please.
IF (TL.LE.0) THEN !A blank (or null) line?
CALL FLUSH !Thus end the paragraph.
RETURN !Perhaps more text will follow, later.
END IF !Curse the (possible) full evaluation of .OR. expressions!
IF (TEXT(1:1).LE." ") CALL FLUSH !This can't be checked above in case LEN(TEXT) = 0.
Chunks of TEXT are to be appended to BUMF.
T1 = 1 !Start at the start, blank or not.
10 IF (BL.GT.0) THEN !If there is text waiting in BUMF,
BL = BL + 1 !Then this latest text is to be appended
BUMF(BL:BL) = " " !After one space.
END IF !So much for the join.
Consider the amount of text to be placed, TEXT(T1:TL)
L = TL - T1 + 1 !Length of text to be placed.
IF (BM - BL .GE. L) THEN !Sufficient space available?
BUMF(BL + 1:BM + L) = TEXT(T1:TL) !Yes. Copy all the remaining text.
BL = BL + L !Advance the finger.
IF (BL .GE. BM - 1) CALL FLUSH !If there is no space for an addendum.
RETURN !Done.
END IF !Otherwise, there is an overhang.
Calculate the available space up to the end of a line. BUMF(BL + 1:BM)
L = BM - BL !The number of characters available in BUMF.
T2 = T1 + L !Finger the first character beyond the take.
IF (TEXT(T2:T2) .LE. " ") GO TO 12 !A splitter character? Happy chance!
T2 = T2 - 1 !Thus the last character of TEXT that could be placed in BUMF.
11 IF (TEXT(T2:T2) .GT. " ") THEN !Are we looking at a space yet?
T2 = T2 - 1 !No. step back one.
IF (T2 .GT. T1) GO TO 11 !And try again, if possible.
IF (L .LE. 6) THEN !No splitter found. For short appendage space,
CALL FLUSH !Starting a new line gives more scope.
GO TO 10 !At the cost of spaces at the end.
END IF !But splitting words is unsavoury too.
T2 = T1 + L - 1 !Alas, no split found.
END IF !So the end-of-line will force a split.
L = T2 - T1 + 1 !The length I settle on.
12 BUMF(BL + 1:BL + L) = TEXT(T1:T1 + L - 1) !I could add a hyphen at the arbitrary chop...
BL = BL + L !The last placed.
CALL FLUSH !The line being full.
Consider what the flushed line didn't take. TEXT(T1 + L:TL)
T1 = T1 + L !Advance to fresh grist.
13 IF (T1.GT.TL) RETURN !Perhaps there is no more. No compound testing, alas.
IF (TEXT(T1:T1).LE." ") THEN !Does a space follow a line split?
T1 = T1 + 1 !Yes. It would appear as a leading space in the output.
GO TO 13 !But the line split stands in for all that.
END IF !So, speed past all such.
IF (T1.LE.TL) GO TO 10!Does anything remain?
RETURN !Nope.
CONTAINS !A convenience.
SUBROUTINE FLUSH !Save on repetition.
IF (BL.GT.0) WRITE (OUTBUMF,"(A)") BUMF(1:BL) !Roll the bumf, if any.
BL = 0 !And be ready for more.
END SUBROUTINE FLUSH !Thus avoid the verbosity of repeated begin ... end blocks.
END SUBROUTINE FLOW !Invoke with one large blob, or, pieces.
END MODULE RIVERRUN !Flush the tail end with a null text.
 
PROGRAM TEST
Line 1,636 ⟶ 2,399:
1 READ (IN,2) BUMF
2 FORMAT (A)
IF (BUMF(1:1).NE."C") GO TO 1 !No comment block yet.
CALL STARTFLOW(MSG,66) !Found it!
3 CALL FLOW(BUMF) !Roll its text.
READ (IN,2) BUMF !Grab another line.
IF (BUMF(1:1).EQ."C") GO TO 3 !And if a comment, append.
CALL FLOW("")
CLOSE (IN)
END</langsyntaxhighlight>
Output: note that the chorus is presented with a leading space so as to force a new line start for it.
<pre>
Line 1,671 ⟶ 2,434:
</pre>
For text flowing purposes the actual source lister expected to find block comments with a space after the C (so that column three was the first character of the text to be flowed), so the above source would be listed as-is - except for overprinting key words and underlining, easy with a lineprinter but much more difficult on modern printers that expect a markup language instead.
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim Shared As String texto, dividido()
 
texto = "In olden times when wishing still helped one, there lived a king " &_
"whose daughters were all beautiful, but the youngest was so beautiful "&_
"that the sun itself, which has seen so much, was astonished whenever "&_
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "&_
"forest, and under an old lime-tree in the forest was a well, and when "&_
"the day was very warm, the king's child went out into the forest and "&_
"sat down by the side of the cool-fountain, and when she was bored she "&_
"took a golden ball, and threw it up on high and caught it, and this "&_
"ball was her favorite plaything."
 
Sub Split(splitArray() As String, subject As String, delimitador As String = " ")
Dim As Integer esteDelim, sgteDelim, toks
Dim As String tok
Redim splitArray(toks)
Do While Strptr(subject)
sgteDelim = Instr(esteDelim + 1, subject, delimitador)
splitArray(toks) = Mid(subject, esteDelim + 1, sgteDelim - esteDelim - 1)
If sgteDelim = FALSE Then Exit Do
toks += 1
Redim Preserve splitArray(toks)
esteDelim = sgteDelim
Loop
End Sub
 
Sub WordWrap(s As String, n As Integer)
Split(dividido(),s," ")
Dim As String fila = ""
For i As Integer = 0 To Ubound(dividido)
If Len(fila) = 0 Then
fila = fila & dividido(i)
Elseif Len(fila & " " & dividido(i)) <= n Then
fila = fila & " " & dividido(i)
Else
Print fila
fila = dividido(i)
End If
Next i
If Len(fila) > 0 Then Print dividido(Ubound(dividido))
End Sub
 
Print "Ajustado a 72:"
WordWrap(texto,72)
Print !"\nAjustado a 80:"
WordWrap(texto,80)
Sleep
</syntaxhighlight>
{{out}}
<pre>
Ajustado a 72:
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it
shone-in-her-face. Close-by-the-king's castle lay a great dark forest,
and under an old lime-tree in the forest was a well, and when the day
was very warm, the king's child went out into the forest and sat down by
the side of the cool-fountain, and when she was bored she took a golden
ball, and threw it up on high and caught it, and this ball was her
plaything.
 
Ajustado a 80:
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone-in-her-face.
Close-by-the-king's castle lay a great dark forest, and under an old lime-tree
in the forest was a well, and when the day was very warm, the king's child went
out into the forest and sat down by the side of the cool-fountain, and when she
was bored she took a golden ball, and threw it up on high and caught it, and
plaything.
</pre>
 
 
=={{header|Go}}==
Basic task, no extra credit.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,716 ⟶ 2,556:
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,743 ⟶ 2,583:
 
'''Solution 1: Imperative Style'''
<langsyntaxhighlight lang="groovy">def wordWrap(text, length = 80) {
def sb = new StringBuilder()
def line = ''
Line 1,755 ⟶ 2,595:
}
sb.append(line.trim()).toString()
}</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="groovy">def text = """\
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
Line 1,769 ⟶ 2,609:
 
println wordWrap(text)
println wordWrap(text, 120)</langsyntaxhighlight>
{{out}}
<pre>In olden times when wishing still helped one, there lived a king whose daughters
Line 1,789 ⟶ 2,629:
A solution using the groovy list.inject method which corresponds to foldLeft in other languages.
 
<langsyntaxhighlight lang="groovy">
String wordWrap(str, width=80) {
str.tokenize(' ').inject([[]]) { rows, word ->
Line 1,796 ⟶ 2,636:
}.collect { it.join(' ') }.join('\n')
}
</syntaxhighlight>
</lang>
 
this solution shows off the more functional aspects of groovy.
Line 1,806 ⟶ 2,646:
Throwing away all readability, using a number of groovy tricks (abusing default parameter values etc) and just going for performance and terseness of code we get the following:
 
<langsyntaxhighlight lang="groovy">
import groovy.transform.TailRecursive
import static java.lang.Math.min
Line 1,815 ⟶ 2,655:
b.length()+w >= len ? b << str[i..-1] : wordWrap(str, w, min(x+w+1, len), b, len, 0)
}
</syntaxhighlight>
</lang>
 
Should be noted that this is not idiomatic groovy or a recommended way of programming, but it is interesting as an exercise.
Line 1,825 ⟶ 2,665:
Note that this solution uses recursion and the @TailRecursive annotation which expands the recursive calls into a non-recursive loop at runtime, thus avoiding stack overflow exceptions for large data sets. Note also that the following expressions are equivalent:
 
<langsyntaxhighlight lang="groovy">
def a = new StringBuilder()
def a = '' << ''
</langsyntaxhighlight>
 
Should also be noted that this solution ignores and breaks for the case where words are longer than a line. I have a version which takes this case into account but I figured this was unreadable enough.
Line 1,838 ⟶ 2,678:
=={{header|Haskell}}==
Greedy wrapping:
<langsyntaxhighlight lang="haskell">ss =
concat
[ "In olden times when wishing still helped one, there lived a king"
Line 1,862 ⟶ 2,702:
lw = length w
 
main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]</langsyntaxhighlight>
 
 
Alternative greedy wrapping: <langsyntaxhighlight lang="haskell">import Data.List (inits, tailstail, tailtails)
 
wWrap :: Int -> String -> String
testString =
wWrap n =
concat
unlines
[ "In olden times when wishing still helped one, there lived a king"
. map unwords
, " whose daughters were all beautiful, but the youngest was so beautiful"
. wWrap'' n
, " that the sun itself, which has seen so much, was astonished whenever"
. words
, " it shone in her face. Close by the king's castle lay a great dark"
. concat
, " forest, and under an old lime-tree in the forest was a well, and when"
. lines
, " the day was very warm, the king's child went out into the forest and"
, " sat down by the side of the cool fountain, and when she was bored she"
, " took a golden ball, and threw it up on high and caught it, and this"
, " ball was her favorite plaything."
]
 
wWrap'' :: Int -> [String] -> [[String]]
wWrap'' _ [] = []
wWrap'' in ss =
(\(a, b) -> a : wWrap'' in b) $
last . filter ((<= in) . length . unwords . fst) $ zip (inits ss) (tails ss)
zip (inits ss) (tails ss)
 
wWrap :: Int -> String -> String
wWrap i = unlines . map unwords . wWrap'' i . words . concat . lines
 
main :: IO ()
main = putStrLn $ wWrap 80 testString</lang>
main =
putStrLn $
wWrap 80 $
concat
[ "In olden times when wishing still helped one,",
" there lived a king whose daughters were all",
" beautiful, but the youngest was so beautiful",
" that the sun itself, which has seen so much,",
" was astonished whenever, it shone in her",
" face. Close by the king's castle lay a great",
" dark forest, and under an old lime-tree in",
" the forest was a well, and when the day was",
" very warm, the king's child went out into the",
" forest and sat down by the side of the cool",
" fountain, and when she was bored she took a",
" golden ball, and threw it up on high and",
" caught it, and this ball was her favorite",
" plaything."
]</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,894 ⟶ 2,749:
The following works in both languages.
 
<langsyntaxhighlight lang="unicon">
procedure main(A)
ll := integer(A[1]) | 72
Line 1,915 ⟶ 2,770:
if *trim(l) = 0 then suspend "\n" # Paragraph boundary
}
end</langsyntaxhighlight>
 
Sample runs:
Line 1,952 ⟶ 2,807:
=={{header|IS-BASIC}}==
The word warp, any kind of text alignment, specifying tab positions are basic services of the EXOS operating system.
<langsyntaxhighlight ISlang="is-BASICbasic">100 TEXT 80
110 CALL WRITE(12,68,0)
120 PRINT :CALL WRITE(10,70,1)
Line 1,970 ⟶ 2,825:
260 DATA "Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, "
270 DATA "and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything."
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,997 ⟶ 2,852:
 
=={{header|J}}==
'''Solution''':<langsyntaxhighlight lang="j">ww =: 75&$: : wrap
wrap =: (] turn edges) ,&' '
turn =: LF"_`]`[}
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="j"> GA =: 'Four score and seven years ago, our forefathers brought forth upon this continent a new nation, dedicated to the proposition that all men were created equal.'
 
ww GA NB. Wrap at 75 chars by default
Line 2,016 ⟶ 2,871:
dedicated to the
proposition that all men
were created equal.</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
package rosettacode;
 
Line 2,026 ⟶ 2,881:
public class WordWrap
{
int defaultLineWidth=80;
int defaultSpaceWidth=1;
void minNumLinesWrap(String text)
{
{
minNumLinesWrap(text,defaultLineWidth);
}
}
void minNumLinesWrap(String text,int LineWidth)
{
{
StringTokenizer st=new StringTokenizer(text);
int SpaceLeft=LineWidth;
int SpaceWidth=defaultSpaceWidth;
while(st.hasMoreTokens())
{
{
String word=st.nextToken();
if((word.length()+SpaceWidth)>SpaceLeft)
{
{
System.out.print("\n"+word+" ");
SpaceLeft=LineWidth-word.length();
}
}
else
{
{
System.out.print(word+" ");
SpaceLeft-=(word.length()+SpaceWidth);
}
}
}
}
}
}
public static void main(String[] args)
{
{
WordWrap now=new WordWrap();
String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
System.out.println("DEFAULT:");
now.minNumLinesWrap(wodehouse);
System.out.println("\n\nLINEWIDTH=120");
now.minNumLinesWrap(wodehouse,120);
}
}
 
}
 
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
 
===Recursive===
'''Solution''':<langsyntaxhighlight lang="javascript">
function wrap (text, limit) {
if (text.length > limit) {
Line 2,082 ⟶ 2,937:
return text;
}
</syntaxhighlight>
</lang>
'''Example''':<langsyntaxhighlight lang="javascript">
console.log(wrap(text, 80));
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,095 ⟶ 2,950:
</pre>
 
'''Example''':<langsyntaxhighlight lang="javascript">
console.log(wrap(text, 42));
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,114 ⟶ 2,969:
A simple regex suffices (and proves fastest) for the greedy version:
 
<langsyntaxhighlight lang="javascript">(function (width) {
'use strict';
 
Line 2,136 ⟶ 2,991:
)
 
})(60);</langsyntaxhighlight>
 
{{Out}}
Line 2,148 ⟶ 3,003:
 
=== EcmaScript 6 ===
<langsyntaxhighlight lang="javascript">
/**
* [wordwrap description]
Line 2,205 ⟶ 3,060:
}).join('\n'); // Объединяем элементы массива по LF
}
</syntaxhighlight>
</lang>
 
'''Example'''<langsyntaxhighlight lang="javascript">
console.log(wordwrap("The quick brown fox jumped over the lazy dog.", 20, "<br />\n"));
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,221 ⟶ 3,076:
 
In jq, all strings are Unicode strings, for which the length is calculated as the number of codepoints.
<langsyntaxhighlight lang="jq"># Simple greedy algorithm.
# Note: very long words are not truncated.
# input: a string
Line 2,234 ⟶ 3,089:
then .[-1] += ($pad * " ") + $word
else . + [ $word]
end );</langsyntaxhighlight>
'''Task 1''':
<langsyntaxhighlight lang="jq">"aaa bb cc ddddd" | wrap_text(6)[] # wikipedia example</langsyntaxhighlight>
{{Out}}
aaa bb
Line 2,242 ⟶ 3,097:
ddddd
'''Task 2''':
<langsyntaxhighlight lang="jq">"aaa bb cc ddddd" | wrap_text(5)[]</langsyntaxhighlight>
{{Out}}
aaa
Line 2,250 ⟶ 3,105:
'''With input from a file''': Russian.txt
<div style="overflow:scroll; height:100px;">
<langsyntaxhighlight lang="sh">советских военных судов и самолетов была отмечена в Японском море после появления там двух американских авианосцев. Не
менее 100 советских самолетов поднялись в воздух, когдаамериканские
авианосцы "Уинсон" и "Мидуэй" приблизились на 50 миль к Владивостоку.
</langsyntaxhighlight></div>
'''Main''':
wrap_text(40)[]
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -R -s -r -f Word_wrap.jq Russian.txt
советских военных судов и самолетов была
отмечена в Японском море после появления
Line 2,265 ⟶ 3,120:
"Уинсон" и "Мидуэй" приблизились на 50
миль к Владивостоку.
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 2,272 ⟶ 3,127:
Using [https://github.com/carlobaldassi/TextWrap.jl TextWrap.jl] library.
 
<langsyntaxhighlight lang="julia">using TextWrap
 
text = """Reformat the single paragraph in 'text' to fit in lines of no more
Line 2,283 ⟶ 3,138:
print_wrapped(text, width=80)
println("\n\n# Wrapped at 70 chars")
print_wrapped(text, width=70)</langsyntaxhighlight>
 
{{out}}
Line 2,299 ⟶ 3,154:
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.</pre>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">:wordwrap %long !long
%ps 0 !ps
split
len [ drop
pop swap len $ps + !ps
$ps $long > [ len !ps nl ] if
print " " print
$ps 1 + !ps
] for
drop
;
 
"tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH. boQchugh Hoch, mu'ghom Dun mojlaH.
tlhIngan maH! Qapla'! DaH tlhIngan Hol mu'ghom'a' Dalegh. qawHaqvam chenmoHlu'DI' 'oHvaD wIqIpe'DIya ponglu'.
'ach jInmolvamvaD Saghbe'law' tlhIngan Hol, DIS 2005 'oH mevmoHlu'. 'ach DIS 2006 jar wa'maHcha'DIch Wikia jInmolDaq vIHta'.
Hov lengvaD chenmoHlu' tlhIngan Hol'e' 'ej DaH 'oH ghojtaH ghot law'. Qapbej Holvam wIcha'meH, qawHaqvam chenmoHlu'.
taHjaj wo', taHjaj Hol! Sov qawHaq tlhab 'oH 'ej ghItlhmey DIqonmeH tlhIngan Hol wIlo'. ghItlhmey chenmoHlaH 'ej choHlaH tlhIngan Hol
jatlhlaHbogh Hoch ghotpu''e'. wej tIn Sov qawHaqvam, 'ach ghurlI' 'e' wItul. DaH 229 ghItlhmey ngaS.
vay' Daghel DaneHchugh qoj vay' Dachup DaneHchugh, vaj tachDaq maghom."
 
dup
 
72 wordwrap nl nl
100 wordwrap nl nl
 
"End " input</syntaxhighlight>
{{out}}
<pre>tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH.
boQchugh Hoch, mu'ghom Dun mojlaH. tlhIngan maH! Qapla'! DaH tlhIngan
Hol mu'ghom'a' Dalegh. qawHaqvam chenmoHlu'DI' 'oHvaD wIqIpe'DIya
ponglu'. 'ach jInmolvamvaD Saghbe'law' tlhIngan Hol, DIS 2005 'oH
mevmoHlu'. 'ach DIS 2006 jar wa'maHcha'DIch Wikia jInmolDaq vIHta'. Hov
lengvaD chenmoHlu' tlhIngan Hol'e' 'ej DaH 'oH ghojtaH ghot law'. Qapbej
Holvam wIcha'meH, qawHaqvam chenmoHlu'. taHjaj wo', taHjaj Hol! Sov
qawHaq tlhab 'oH 'ej ghItlhmey DIqonmeH tlhIngan Hol wIlo'. ghItlhmey
chenmoHlaH 'ej choHlaH tlhIngan Hol jatlhlaHbogh Hoch ghotpu''e'. wej
tIn Sov qawHaqvam, 'ach ghurlI' 'e' wItul. DaH 229 ghItlhmey ngaS. vay'
Daghel DaneHchugh qoj vay' Dachup DaneHchugh, vaj tachDaq maghom.
 
tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH. boQchugh Hoch, mu'ghom Dun
mojlaH. tlhIngan maH! Qapla'! DaH tlhIngan Hol mu'ghom'a' Dalegh. qawHaqvam chenmoHlu'DI' 'oHvaD
wIqIpe'DIya ponglu'. 'ach jInmolvamvaD Saghbe'law' tlhIngan Hol, DIS 2005 'oH mevmoHlu'. 'ach DIS
2006 jar wa'maHcha'DIch Wikia jInmolDaq vIHta'. Hov lengvaD chenmoHlu' tlhIngan Hol'e' 'ej DaH 'oH
ghojtaH ghot law'. Qapbej Holvam wIcha'meH, qawHaqvam chenmoHlu'. taHjaj wo', taHjaj Hol! Sov qawHaq
tlhab 'oH 'ej ghItlhmey DIqonmeH tlhIngan Hol wIlo'. ghItlhmey chenmoHlaH 'ej choHlaH tlhIngan Hol
jatlhlaHbogh Hoch ghotpu''e'. wej tIn Sov qawHaqvam, 'ach ghurlI' 'e' wItul. DaH 229 ghItlhmey ngaS.
vay' Daghel DaneHchugh qoj vay' Dachup DaneHchugh, vaj tachDaq maghom.
 
End</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
val text =
Line 2,337 ⟶ 3,245:
println("\nGreedy algorithm - wrapped at 80:")
println(greedyWordwrap(text, 80))
}</langsyntaxhighlight>
 
{{out}}
Line 2,366 ⟶ 3,274:
 
The test text will be the third first paragraphs of Jules Verne's book, The Mysterious Island.
<langsyntaxhighlight lang="scheme">
{def text
Personne n’a sans doute oublié le terrible coup de vent de nord-est qui se déchaîna au milieu de l’équinoxe de cette année, et pendant lequel le baromètre tomba à sept cent dix millimètres. Ce fut un ouragan, sans intermittence, qui dura du 18 au 26 mars. Les ravages qu’il produisit furent immenses en Amérique, en Europe, en Asie, sur une zone large de dix-huit cents milles, qui se dessinait obliquement à l’équateur, depuis le trente-cinquième parallèle nord jusqu’au quarantième parallèle sud ! (L’île mystérieuse / Jules Verne)}
-> text
</syntaxhighlight>
</lang>
 
1) lambdatalk can simply call HTML tags and CSS rules:
<langsyntaxhighlight lang="scheme">
{def wrap1
{lambda {:n}
Line 2,390 ⟶ 3,298:
à l’équateur, depuis le trente-cinquième parallèle nord jusqu’au
quarantième parallèle sud ! (L’île mystérieuse / Jules Verne)
</syntaxhighlight>
</lang>
 
2) a lambdatalk function
 
A translation from the Kotlin entry:
<langsyntaxhighlight lang="scheme">
{def wrap2 // the function's name
 
Line 2,435 ⟶ 3,343:
jusqu’au quarantième parallèle sud ! (L’île mystérieuse /
Jules Verne)
</syntaxhighlight>
</lang>
 
3) A translation of the javascript entry. The {jswrap n text} function contains lines until n characters
 
<langsyntaxhighlight lang="javascript">
LAMBDATALK.DICT['jswrap'] = function() {
var wrap = function(text, limit) {
Line 2,469 ⟶ 3,377:
parallèle nord jusqu’au quarantième parallèle sud ! (L’île
mystérieuse / Jules Verne)
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define wordwrap(
text::string,
row_length::integer = 75
) => {
return regexp(`(?is)(.{1,` + #row_length + `})(?:$|\W)+`, '$1<br />\n', #text, true) -> replaceall
}
 
Line 2,485 ⟶ 3,393:
wordwrap(#text)
'<hr />'
wordwrap(#text, 90)</langsyntaxhighlight>
 
-><pre>Lorem ipsum dolor sit amet, consectetur
Line 2,513 ⟶ 3,421:
{{trans|Erlang}}
 
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun wrap-text (text)
(wrap-text text 78))
Line 2,539 ⟶ 3,447:
((word `#(,max ,line-len ,line ,acc))
`#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))
</syntaxhighlight>
</lang>
 
=== Regex Implementation ===
 
<langsyntaxhighlight lang="lisp">
(defun make-regex-str (max-len)
(++ "(.{1," (integer_to_list max-len) "}|\\S{"
Line 2,553 ⟶ 3,461:
(re:replace text find-patt replace-patt
'(global #(return list)))))
</syntaxhighlight>
</lang>
 
Usage examples:
 
<syntaxhighlight lang="lisp">
<lang Lisp>
> (set test-text (++ "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. "
"The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or "
"provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.")
> (io:format (wrap-text text 80))
</syntaxhighlight>
</lang>
<pre>
Even today, with proportional fonts and complex layouts, there are still cases
Line 2,571 ⟶ 3,479:
ok
</pre>
<langsyntaxhighlight lang="lisp">
> (io:format (wrap-text text 50))
</syntaxhighlight>
</lang>
<pre>
Even today, with proportional fonts and complex
Line 2,589 ⟶ 3,497:
Lingo/Director has 2 visual components for displaying text, text and field members. Both can soft-wrap text directly. In cases where you need a hard-wrapped representation of a text, this could e.g. be implemented like this:
(Note: this solution is meant for proportional fonts and based on actual text rendering. For the more trivial case of non-proportial font word wrapping, just pass a non-proportinal font like e.g. Courier in the 'style' argument)
<langsyntaxhighlight lang="lingo">-- in some movie script
 
----------------------------------------
Line 2,630 ⟶ 3,538:
channel(1).removeScriptedSprite()
return lines
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lingo">str = "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed "&\
"eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim "&\
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi "&\
Line 2,643 ⟶ 3,551:
repeat with l in lines
put l
end repeat</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,666 ⟶ 3,574:
=={{header|Lua}}==
 
<langsyntaxhighlight lang="lua">function splittokens(s)
local res = {}
for w in s:gmatch("%S+") do
Line 2,710 ⟶ 3,618:
print(textwrap(example1))
print()
print(textwrap(example1, 60))</langsyntaxhighlight>
 
{{out}}
Line 2,751 ⟶ 3,659:
All of these statements not handle tab character (9) as tab. Editor change tab with spaces, and Print/report/Legend prints tab as a square character (as for 9.4 version of M2000 Environment and Interpreter).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ leading space from begin of paragraph stay as is
Line 2,833 ⟶ 3,741:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">string="In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything.";
wordWrap[textWidth_,spaceWidth_,string_]:=Module[{start,spaceLeft,masterString},
spaceLeft=textWidth;
Line 2,862 ⟶ 3,770:
];
StringJoin@@Riffle[masterString,"\n"]
];</langsyntaxhighlight>
{{out}} for width 72 and 80:
<syntaxhighlight lang="text">wordWrap[72, 1, string]
wordWrap[80, 1, string]</langsyntaxhighlight>
{{out}}
<pre>In olden times when wishing still helped one, there lived a king
Line 2,887 ⟶ 3,795:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">str = "one two three four five six seven eight nine ten eleven!"
width = 15
words = str.split
Line 2,902 ⟶ 3,810:
end if
end for
print line[:-1]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,914 ⟶ 3,822:
=={{header|NetRexx}}==
===version 1===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols
 
Line 2,990 ⟶ 3,898:
''
return speech01
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:15em; overflow:scroll">
Line 3,013 ⟶ 3,921:
 
===version 2===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx ************************************************************
* 23.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
Line 3,040 ⟶ 3,948:
If s>'' Then
say s
return</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutilsstd/wordwrap
 
let txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."
echo wordWrap(txt.wrapWords()
echo ""
echo wordWrap(txt, .wrapWords(45)
</syntaxhighlight>
</lang>
{{out}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 3,068 ⟶ 3,976:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">#load "str.cma"
 
let txt = "In olden times when wishing still helped one, there lived
Line 3,100 ⟶ 4,008:
) (0, "") words
in
print_endline (Buffer.contents buf)</langsyntaxhighlight>
 
Testing:
Line 3,111 ⟶ 4,019:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (get-one-word start)
(let loop ((chars #null) (end start))
Line 3,147 ⟶ 4,055:
(lines (get-all-lines words width)))
lines))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,166 ⟶ 4,074:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">wrap(s,len)={
my(t="",cur);
s=Vec(s);
Line 3,191 ⟶ 4,099:
King="And so let freedom ring from the prodigious hilltops of New Hampshire; let freedom ring from the mighty mountains of New York; let freedom ring from the heightening Alleghenies of Pennsylvania; let freedom ring from the snow-capped Rockies of Colorado; let freedom ring from the curvaceous slopes of California. But not only that: let freedom ring from Stone Mountain of Georgia; let freedom ring from Lookout Mountain of Tennessee; let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring.";
wrap(King, 75)
wrap(King, 50)</langsyntaxhighlight>
 
{{out}}
Line 3,219 ⟶ 4,127:
=={{header|Perl}}==
Regex. Also showing degraded behavior on very long words:
<langsyntaxhighlight lang="perl">my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
Line 3,236 ⟶ 4,144:
 
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print;</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>string s = substitute("""In olden times when wishing still helped one, there lived a king
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"""In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful that the sun itself,
whose daughters were all beautiful, but the youngest was so beautiful that the sun itself,
which has seen so much, was astonished whenever it shone in her face. Close by the king's
which has seen so much, was astonished whenever it shone in her face. Close by the king's
castle lay a great dark forest, and under an old lime-tree in the forest was a well, and
when castle thelay daya wasgreat verydark warmforest, theand king'sunder childan wentold outlime-tree intoin the forest andwas sata downwell, by theand
side of when the coolday fountain,was andvery whenwarm, shethe wasking's boredchild shewent tookout ainto goldenthe ball,forest and threwsat itdown upby the
side of the cool fountain, and when she was bored she took a golden ball, and threw it up
on high and caught it, and this ball was her favorite plaything.""","\n"," ")
on high and caught it, and this ball was her favorite plaything."""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
 
procedure word_wrap(string s, integer maxwidth)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">word_wrap</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">maxwidth</span><span style="color: #0000FF;">)</span>
sequence words = split(s)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
string line = words[1]
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
for i=2 to length(words) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string word = words[i]
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
if length(line)+length(word)+1>maxwidth then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxwidth</span> <span style="color: #008080;">then</span>
puts(1,line&"\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
line = word
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span>
else
<span line &style= "color: #008080;"&word>else</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">word</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,line&"\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
word_wrap(s,72)
<span style="color: #000000;">word_wrap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">72</span><span style="color: #0000FF;">)</span>
word_wrap(s,80)</lang>
<span style="color: #000000;">word_wrap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">80</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 3,284 ⟶ 4,194:
favorite plaything.
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
72 var long
0 >ps
 
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh."
 
split
len for drop
pop swap len ps> + >ps
tps long > if ps> drop len >ps nl endif
print " " print
ps> 1 + >ps
endfor
drop ps> drop
</syntaxhighlight>
{{out}} 72 and 100.
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius
sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis,
ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet
rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt
cursus. Cum sociis natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et
aliquam dui gravida. Nulla consectetur sem vel felis vulputate et
imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor.
Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc
sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus
enim eu nibh.</pre>
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit
vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui
posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum
sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel felis vulputate et
imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor. Aliquam suscipit lacus vel odio
faucibus tempor. Sed ipsum est, condimentum eget eleifend ac, ultricies non dui. Integer tempus,
nunc sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu nibh.</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
 
$text = <<<ENDTXT
Line 3,316 ⟶ 4,275:
 
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
</syntaxhighlight>
</lang>
{{Out}}
<pre style="font-size:84%;height:55ex">
Line 3,363 ⟶ 4,322:
be together forever with you
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
go =>
text(1,Text),
foreach(LineWidth in [60,80])
println(lineWidth=LineWidth),
println(wrap(Text,LineWidth)),
nl
end,
nl.
 
wrap(Text,LineWidth) = Wrapped =>
Words = Text.split(),
Wrapped = Words[1],
SpaceLeft = LineWidth - Wrapped.len,
foreach(Word in Words.tail)
WordLen = Word.length,
if (WordLen + 1) > SpaceLeft then
Wrapped := Wrapped ++ "\n" ++ Word,
SpaceLeft := LineWidth - WordLen
else
Wrapped := Wrapped ++ " " ++ Word,
SpaceLeft := SpaceLeft - WordLen - 1
end
end.
 
text(1,"Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.").</syntaxhighlight>
 
{{out}}
<pre>lineWidth = 60
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
 
lineWidth = 80
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.</pre>
 
 
=={{header|PicoLisp}}==
'[http://software-lab.de/doc/refW.html#wrap wrap]' is a built-in.
<langsyntaxhighlight PicoLisplang="picolisp">: (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog")))
The quick
brown fox
jumps over
the lazy dog
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog"</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
ww: proc Options(main);
/*********************************************************************
Line 3,405 ⟶ 4,420:
End;
End;
End;</langsyntaxhighlight>
Test result using this:
<pre>
Line 3,425 ⟶ 4,440:
=={{header|PowerShell}}==
Basic word wrap.
<langsyntaxhighlight lang="powershell">function wrap{
$divide=$args[0] -split " "
$width=$args[1]
Line 3,431 ⟶ 4,446:
 
foreach($word in $divide){
if($word.length+1 -gt $spaceleft){
$output+="`n$word "
$spaceleft=$width-($word.length+1)
} else {
$output+="$word "
$spaceleft-=$word.length+1
}
}
}
 
Line 3,453 ⟶ 4,468:
wrap $paragraph 100
 
### End script</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,483 ⟶ 4,498:
===Pipeline Version===
Slightly modified the previous to become the guts of this version. Now there is a default (80 characters) and a lower and upper limit for the -Width parameter. An unlimited number of strings may be passed to the helper function, New-WordWrap, through the pipeline.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Out-WordWrap
{
Line 3,513 ⟶ 4,528:
foreach ($word in $words)
{
if($word.Length + 1 -gt $remaining)
{
$output += "`n$word "
$remaining = $Width - ($word.Length + 1)
}
else
{
$output += "$word "
$remaining -= $word.Length + 1
}
}
 
Line 3,536 ⟶ 4,551:
}
}
</syntaxhighlight>
</lang>
Grab some data and send it down the pipeline:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[string[]]$paragraphs = "Rebum everti delicata an vel, quo ut temporibus interpretaris, mea debet mnesarchum disputando ad. Id has dolorum contentiones, mel ea noster adipisci. Id persius appareat eos, aeque dolorum fastidii eam in. Partem assentior contentiones ut mea. Cu augue facilis fabellas cum, vix eu sanctus denique imperdiet, appareat percipit qui ex.",
"Nihil discere phaedrum at duo, no eum adhuc autem error. Quo aliquam delicata contentiones et, in sed ferri legimus sententiae, nihil solet docendi id eum. Ius ut meliore vulputate adipiscing, sea cu virtute praesent. Euripidis instructior est eu. Veri cotidieque ex vel, aliquam eruditi nusquam sea ne, eu wisi ubique ullamcorper est. Qui doctus epicuri ei. Cum esse detracto concludaturque ea, veri erant per ad, vide ancillae principes ius id.",
Line 3,551 ⟶ 4,566:
 
$paragraphs | Out-WordWrap -Width 100
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,597 ⟶ 4,612:
possim ex. Theophrastus conclusionemque ad quo, inimicus deseruisse voluptatibus eum et. Duis
delectus mandamus an mei, usu timeam nostrum suscipiantur id.
</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">% See https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_number_of_lines
word_wrap(String, Length, Wrapped):-
re_split("\\S+", String, Words),
wrap(Words, Length, Length, Wrapped, '').
 
wrap([_], _, _, Result, Result):-!.
wrap([Space, Word|Words], Line_length, Space_left, Result, String):-
string_length(Word, Word_len),
string_length(Space, Space_len),
(Space_left < Word_len + Space_len ->
Space1 = '\n',
Space_left1 is Line_length - Word_len
;
Space1 = Space,
Space_left1 is Space_left - Word_len - Space_len
),
atomic_list_concat([String, Space1, Word], String1),
wrap(Words, Line_length, Space_left1, Result, String1).
 
sample_text("Lorem ipsum dolor sit amet, consectetur adipiscing \
elit, sed do eiusmod tempor incididunt ut labore et dolore magna \
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco \
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure \
dolor in reprehenderit in voluptate velit esse cillum dolore eu \
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non \
proident, sunt in culpa qui officia deserunt mollit anim id est \
laborum.").
 
test_word_wrap(Line_length):-
sample_text(Text),
word_wrap(Text, Line_length, Wrapped),
writef('Wrapped at %w characters:\n%w\n',
[Line_length, Wrapped]).
 
main:-
test_word_wrap(60),
nl,
test_word_wrap(80).</syntaxhighlight>
 
{{out}}
<pre>
Wrapped at 60 characters:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
 
Wrapped at 80 characters:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">
DataSection
Data.s "In olden times when wishing still helped one, there lived a king "+
"whose daughters were all beautiful, but the youngest was so beautiful "+
"that the sun itself, which has seen so much, was astonished whenever "+
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "+
"forest, and under an old lime-tree in the forest was a well, and when "+
"the day was very warm, the king's child went out into the forest and "+
"sat down by the side of the cool-fountain, and when she was bored she "+
"took a golden ball, and threw it up on high and caught it, and this "+
"ball was her favorite plaything."
EndDataSection
 
Line 3,647 ⟶ 4,724:
Repeat : d$=Inkey() : Delay(50) : Until FindString("lr",d$,1,#PB_String_NoCase) : PrintN(d$+#CRLF$)
main(t$,lw) : Input()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,693 ⟶ 4,770:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> import textwrap
>>> help(textwrap.fill)
Help on function fill in module textwrap:
Line 3,732 ⟶ 4,809:
wrap(), tabs are expanded and other whitespace characters converted to space. See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> $ "Consider the inexorable logic of the Big Lie. If a man has
a consuming love for cats and dedicates himself to the
protection of cats, you have only to accuse him of killing
and mistreating cats. Your lie will have the unmistakable
ring of truth, whereas his outraged denials will reek of
falsehood and evasion. Those who have heard voices from the
nondominant brain hemisphere remark of the absolute
authority of the voice. They know they are hearing the
Truth. The fact that no evidence is adduced and that the
voice may be talking utter nonsense has nothing to do with
facts. Those who manipulate Truth to their advantage, the
people of the Big Lie, are careful to shun facts. In fact
nothing is more deeply offensive to such people than the
concept of fact. To adduce fact in your defense is to rule
yourself out of court."
nest$ dup
55 wrap$ cr
75 wrap$ cr
say "-- William S. Burroughs, Ghost Of Chance, 1981" cr</syntaxhighlight>
 
{{out}}
 
<pre>Consider the inexorable logic of the Big Lie. If a man
has a consuming love for cats and dedicates himself to
the protection of cats, you have only to accuse him of
killing and mistreating cats. Your lie will have the
unmistakable ring of truth, whereas his outraged
denials will reek of falsehood and evasion. Those who
have heard voices from the nondominant brain hemisphere
remark of the absolute authority of the voice. They
know they are hearing the Truth. The fact that no
evidence is adduced and that the voice may be talking
utter nonsense has nothing to do with facts. Those who
manipulate Truth to their advantage, the people of the
Big Lie, are careful to shun facts. In fact nothing is
more deeply offensive to such people than the concept
of fact. To adduce fact in your defense is to rule
yourself out of court.
 
 
Consider the inexorable logic of the Big Lie. If a man has a consuming love
for cats and dedicates himself to the protection of cats, you have only to
accuse him of killing and mistreating cats. Your lie will have the
unmistakable ring of truth, whereas his outraged denials will reek of
falsehood and evasion. Those who have heard voices from the nondominant
brain hemisphere remark of the absolute authority of the voice. They know
they are hearing the Truth. The fact that no evidence is adduced and that
the voice may be talking utter nonsense has nothing to do with facts. Those
who manipulate Truth to their advantage, the people of the Big Lie, are
careful to shun facts. In fact nothing is more deeply offensive to such
people than the concept of fact. To adduce fact in your defense is to rule
yourself out of court.
 
-- William S. Burroughs, Ghost Of Chance, 1981</pre>
 
=={{header|R}}==
Line 3,739 ⟶ 4,874:
 
Use <code>strwrap()</code>:
<langsyntaxhighlight lang="rsplus">> x <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. "
> cat(paste(strwrap(x=c(x, "\n"), width=80), collapse="\n"))
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 3,752 ⟶ 4,887:
hendrerit. Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.</langsyntaxhighlight>
 
=== Using the stringr tidyverse library ===
 
Another option, using <code>stringr::str_wrap</code>
<langsyntaxhighlight lang="rsplus">
> x <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. "
> cat(stringr::str_wrap(x, 60))
Line 3,766 ⟶ 4,901:
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
Using a library function:
<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket
(require scribble/text/wrap)
Line 3,785 ⟶ 4,920:
high and caught it, and this ball was her favorite plaything.})
(for-each displayln (wrap-line text 60))
</syntaxhighlight>
</lang>
 
Explicit (and simple) implementation:
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,811 ⟶ 4,946:
;;; Usage:
(wrap (string-split text) 70)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
Line 3,829 ⟶ 4,964:
 
say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g);
say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g);</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 0===
This version was the original (of version 1) and has no error checking and only does left-margin justification.
<langsyntaxhighlight lang="rexx">/*REXX program reads a file and displays it to the screen (with word wrap). */
parse arg iFID width . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID='LAWS.TXT' /*Not specified? Then use the default.*/
Line 3,851 ⟶ 4,986:
end /*m*/
if $\=='' then say $ /*handle any residual words (overflow).*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; is the same as version 1 using the &nbsp; '''L'''eft &nbsp; option (the default).
 
Line 3,875 ⟶ 5,010:
<br>Instead of appending lines of a file to a character string, the words are picked off and stored in a stemmed array.
<br>This decreases the amount of work that REXX has to do to retrieve (get) the next word in the (possibly) ginormous string.
<langsyntaxhighlight lang="rexx">/*REXX program reads a file and displays it to the screen (with word wrap). */
parse arg iFID width kind _ . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID = 'LAWS.TXT' /*Not specified? Then use the default.*/
Line 3,916 ⟶ 5,051:
say $ /*display the line of words to terminal*/
_= x /*handle any word overflow. */
return /*go back and keep truckin'. */</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''LINESIZE''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
 
Line 4,196 ⟶ 5,331:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 20.08.2013 Walter Pachl "my way"
* 23.08.2013 Walter Pachl changed to use lastpos bif
Line 4,223 ⟶ 5,358:
Call o s
Return
o:Return lineout(oid,arg(1))</langsyntaxhighlight>
{{out}} for widths 72 and 9
<pre>
Line 4,250 ⟶ 5,385:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Word wrap
 
Line 4,281 ⟶ 5,416:
next
see line + nl + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,305 ⟶ 5,440:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class String
def wrap(width)
txt = gsub("\n", " ")
Line 4,335 ⟶ 5,470:
puts "." * w
puts text.wrap(w)
end</langsyntaxhighlight>
 
{{out}}
Line 4,363 ⟶ 5,498:
Word Wrap style for different browsers.
This automatically adjusts the text if the browser window is stretched in any direction
<langsyntaxhighlight lang="runbasic">doc$ = "In olden times when wishing still helped one, there lived a king ";_
"whose daughters were all beautiful, but the youngest was so beautiful ";_
"that the sun itself, which has seen so much, was astonished whenever ";_
Line 4,372 ⟶ 5,507:
 
html "<table border=1 cellpadding=2 cellspacing=0><tr" + wrap$ +" valign=top>"
html "<td width=60%>" + doc$ + "</td><td width=40%>" + doc$ + "</td></tr></table>"</langsyntaxhighlight>
output will adjust as you stretch the browser and maintain a 60 to 40 ratio of the width of the screen.
<pre>
Line 4,379 ⟶ 5,514:
whose daughters were all beautiful, but the youngest was so | one, there lived a king whose daughters
beautiful that the sun itself, which has seen so much, was | were all beautiful, but the youngest was
astonished whenever it shone in her face. | so beautiful that the sun itself, which
| has seen so much, was astonished whenever
| it shone in her face.
</pre>
Without Browser
<langsyntaxhighlight lang="runbasic">doc$ = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
Line 4,406 ⟶ 5,541:
docOut$ = docOut$ + thisWord$
wend
print docOut$</langsyntaxhighlight>
 
=={{header|Rust}}==
This is an implementation of the simple greedy algorithm.
 
<syntaxhighlight lang="rust">#[derive(Clone, Debug)]
pub struct LineComposer<I> {
words: I,
width: usize,
current: Option<String>,
}
 
impl<I> LineComposer<I> {
pub(crate) fn new<S>(words: I, width: usize) -> Self
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
LineComposer {
words,
width,
current: None,
}
}
}
 
impl<I, S> Iterator for LineComposer<I>
where
I: Iterator<Item = S>,
S: AsRef<str>,
{
type Item = String;
 
fn next(&mut self) -> Option<Self::Item> {
let mut next = match self.words.next() {
None => return self.current.take(),
Some(value) => value,
};
 
let mut current = self.current.take().unwrap_or_else(String::new);
 
loop {
let word = next.as_ref();
if self.width <= current.len() + word.len() {
self.current = Some(String::from(word));
// If the first word itself is too long, avoid producing an
// empty line. Continue instead with the next word.
if !current.is_empty() {
return Some(current);
}
}
 
if !current.is_empty() {
current.push_str(" ")
}
 
current.push_str(word);
 
match self.words.next() {
None => return Some(current), // Last line, current remains None
Some(word) => next = word,
}
}
}
}
 
// This part is just to extend all suitable iterators with LineComposer
 
pub trait ComposeLines: Iterator {
fn compose_lines(self, width: usize) -> LineComposer<Self>
where
Self: Sized,
Self::Item: AsRef<str>,
{
LineComposer::new(self, width)
}
}
 
impl<T, S> ComposeLines for T
where
T: Iterator<Item = S>,
S: AsRef<str>,
{
}
 
fn main() {
let text = r"
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.";
 
text.split_whitespace()
.compose_lines(80)
.for_each(|line| println!("{}", line));
}
</syntaxhighlight>
 
{{out}}
<pre>
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
</pre>
 
=={{header|Scala}}==
===Intuitive approach===
{{libheader|Scala}}<langsyntaxhighlight lang="scala">import java.util.StringTokenizer
 
object WordWrap extends App {
Line 4,453 ⟶ 5,701:
letsWrap(ewd)
letsWrap(ewd, 120)
} // 44 lines</langsyntaxhighlight>{{out}}<pre>Wrapped at: 80
................................................................................
Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme.
Line 4,496 ⟶ 5,744:
The simple, greedy algorithm:
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 4,536 ⟶ 5,784:
(show-para simple-word-wrap 50)
(show-para simple-word-wrap 60)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,566 ⟶ 5,814:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: wrap (in string: aText, in integer: lineWidth) is func
Line 4,609 ⟶ 5,857:
writeln(wrap(frog, width));
end for;
end func;</langsyntaxhighlight>{{out}}<pre>Wrapped at 72:
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
Line 4,633 ⟶ 5,881:
=={{header|Sidef}}==
===Greedy word wrap===
<langsyntaxhighlight lang="ruby">class String {
method wrap(width) {
var txt = self.gsub(/\s+/, " ");
var len = txt.len;
var para = [];
var i = 0;
while (i < len) {
var j = (i + width);
while ((j < len) && (txt.char_at(j)  != ' ')) { --j };
para.append(txt.substr(i, j-i));
i = j+1;
};
return para.join("\n");
}
}
 
var text = 'aaa bb cc ddddd';
say text.wrap(6);</langsyntaxhighlight>
 
{{out}}
Line 4,660 ⟶ 5,908:
 
===Smart word wrap===
<langsyntaxhighlight lang="ruby">class SmartWordWrap {
 
has width = 80
Line 4,686 ⟶ 5,934:
root << [
array.first(i+1).join(' '),
self.prepare_words(array.ftslice(i+1), depth+1, callback)
]
 
Line 4,729 ⟶ 5,977:
self.combine([], path, { |combination|
var score = 0
combination.ftfirst(0, -21).each { |line|
score += (width - line.len -> sqr)
}
Line 4,743 ⟶ 5,991:
}
}
 
 
var sww = SmartWordWrap();
 
 
var words = %w(aaa bb cc ddddd);
var wrapped = sww.wrap(words, 6);
 
 
say wrapped;</langsyntaxhighlight>
{{out}}
<pre>
Line 4,755 ⟶ 6,003:
bb cc
ddddd
</pre>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">fun wordWrap n s =
let
fun appendLine (line, text) =
text ^ line ^ "\n"
fun wrap (word, prev as (line, text)) =
if size line + 1 + size word > n
then (word, appendLine prev)
else (line ^ " " ^ word, text)
in
case String.tokens Char.isSpace s of
[] => ""
| (w :: ws) => appendLine (foldl wrap (w, "") ws)
end
 
val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn</syntaxhighlight>
{{in}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</pre>
{{out}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</pre>
 
=={{header|Tailspin}}==
A simple greedy algorithm that will always put one word on a line even if the word is longer than the desired width.
<syntaxhighlight lang="tailspin">
templates break&{width:}
composer words
<word>* (<WS>*)
rule word: (<WS>*) [<'\S'>+]
end words
def chars: [$ -> words];
@: $chars(first);
[$chars(first~..last)... -> #] -> '$... -> '$;$#10;';$@...;' !
 
when <[](..~($width-$@::length))> do ..|@: ' '; $... -> ..|@: $;
otherwise '$@...;' ! @: $;
end break
 
'In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king''s castle lay a great dark forest, and under
an old lime-tree in the forest was a well, and when the day was very
warm, the king''s child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.' -> break&{width: 80} -> !OUT::write</syntaxhighlight>
{{out}}
<pre>
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime-tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
</pre>
 
=={{header|Tcl}}==
Using a simple greedy algorithm to wrap the same text as used in the [[#Go|Go]] solution. Note that it assumes that the line length is longer than the longest word length.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc wrapParagraph {n text} {
Line 4,765 ⟶ 6,080:
set RE "^(.{1,$n})(?:\\s+(.*))?$"
for {set result ""} {[regexp $RE $text -> line text]} {} {
append result $line "\n"
}
return [string trimright $result "\n"]
Line 4,784 ⟶ 6,099:
puts [wrapParagraph 80 $txt]
puts "[string repeat - 72]"
puts [wrapParagraph 72 $txt]</langsyntaxhighlight>
{{out}}
<pre>--------------------------------------------------------------------------------
Line 4,809 ⟶ 6,124:
The text presentation program automatically provides word wrap:
 
<langsyntaxhighlight lang="tpp"> The kings youngest daughter was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face.</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
text="In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything."
Line 4,831 ⟶ 6,146:
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext
</syntaxhighlight>
</lang>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 4,856 ⟶ 6,171:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
column = 60
text = "In olden times when wishing still helped one, there lived a king " &_
"whose daughters were all beautiful, but the youngest was so beautiful "&_
"that the sun itself, which has seen so much, was astonished whenever "&_
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "&_
"forest, and under an old lime-tree in the forest was a well, and when "&_
"the day was very warm, the king's child went out into the forest and "&_
"sat down by the side of the cool-fountain, and when she was bored she "&_
"took a golden ball, and threw it up on high and caught it, and this "&_
"ball was her favorite plaything."
 
Call wordwrap(text,column)
 
Sub wordwrap(s,n)
word = Split(s," ")
row = ""
For i = 0 To UBound(word)
If Len(row) = 0 Then
row = row & word(i)
ElseIf Len(row & " " & word(i)) <= n Then
row = row & " " & word(i)
Else
WScript.StdOut.WriteLine row
row = word(i)
End If
Next
If Len(row) > 0 Then
WScript.StdOut.WriteLine row
End If
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,903 ⟶ 6,218:
on high and caught it, and this ball was her favorite
plaything.
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascript">fn wrap(text string, line_width int) string {
mut wrapped := ''
words := text.fields()
if words.len == 0 {
return wrapped
}
wrapped = words[0]
mut space_left := line_width - wrapped.len
for word in words[1..] {
if word.len+1 > space_left {
wrapped += "\n" + word
space_left = line_width - word.len
} else {
wrapped += " " + word
space_left -= 1 + word.len
}
}
return wrapped
}
const frog = "
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything."
fn main() {
println("wrapped at 80:")
println(wrap(frog, 80))
println("wrapped at 72:")
println(wrap(frog, 72))
}</syntaxhighlight>
 
{{out}}
<pre>
wrapped at 80:
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime-tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
wrapped at 72:
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime-tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.
 
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">var greedyWordWrap = Fn.new { |text, lineWidth|
var words = text.split(" ")
var sb = words[0]
var spaceLeft = lineWidth - words[0].count
for (word in words.skip(1)) {
var len = word.count
if (len + 1 > spaceLeft) {
sb = sb + "\n" + word
spaceLeft = lineWidth - len
} else {
sb = sb + " " + word
spaceLeft = spaceLeft - len - 1
}
}
return sb
}
 
var text =
"In olden times when wishing still helped one, there lived a king " +
"whose daughters were all beautiful, but the youngest was so beautiful " +
"that the sun itself, which has seen so much, was astonished whenever " +
"it shone in her face. Close by the king's castle lay a great dark " +
"forest, and under an old lime tree in the forest was a well, and when " +
"the day was very warm, the king's child went out into the forest and " +
"sat down by the side of the cool fountain, and when she was bored she " +
"took a golden ball, and threw it up on high and caught it, and this " +
"ball was her favorite plaything."
 
System.print("Greedy algorithm - wrapped at 72:")
System.print(greedyWordWrap.call(text, 72))
System.print("\nGreedy algorithm - wrapped at 80:")
System.print(greedyWordWrap.call(text, 80))</syntaxhighlight>
 
{{out}}
<pre>
Greedy algorithm - wrapped at 72:
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.
 
Greedy algorithm - wrapped at 80:
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">string 0;
proc WordWrap(Text, LineWidth); \Display Text string wrapped at LineWidth
char Text, LineWidth, Word, SpaceLeft, WordWidth, I;
[SpaceLeft:= 0;
loop [loop [if Text(0) = 0 then return; \skip whitespace (like CR)
if Text(0) > $20 then quit;
Text:= Text+1;
];
Word:= Text; WordWidth:= 0;
while Word(WordWidth) > $20 do
WordWidth:= WordWidth+1;
Text:= Text + WordWidth; \move to Word terminator
if WordWidth+1 > SpaceLeft then
[CrLf(0);
for I:= 0 to WordWidth-1 do ChOut(0, Word(I));
SpaceLeft:= LineWidth - WordWidth;
]
else [ChOut(0, ^ );
for I:= 0 to WordWidth-1 do ChOut(0, Word(I));
SpaceLeft:= SpaceLeft - WordWidth - 1;
];
];
];
 
char Text;
[Text:=
"In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite plaything.
";
WordWrap(Text, 72); CrLf(0);
WordWrap(Text, 80); CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
 
In olden times when wishing still helped one, there lived a king whose
daughters were all beautiful, but the youngest was so beautiful that the
sun itself, which has seen so much, was astonished whenever it shone in
her face. Close by the king's castle lay a great dark forest, and under
an old lime tree in the forest was a well, and when the day was very
warm, the king's child went out into the forest and sat down by the side
of the cool fountain, and when she was bored she took a golden ball, and
threw it up on high and caught it, and this ball was her favorite
plaything.
 
In olden times when wishing still helped one, there lived a king whose daughters
were all beautiful, but the youngest was so beautiful that the sun itself, which
has seen so much, was astonished whenever it shone in her face. Close by the
king's castle lay a great dark forest, and under an old lime tree in the forest
was a well, and when the day was very warm, the king's child went out into the
forest and sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this ball was her
favorite plaything.
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">t$ = "In olden times when wishing still helped one, there lived a king "
t$ = t$ + "whose daughters were all beautiful, but the youngest was so beautiful "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
Line 4,932 ⟶ 6,433:
 
sub words(w$, p$(), d$)
local n, i, p
n = split(w$, p$(), d$)
p = 1
for i = 1 to n
p$(i) = p$(i) + mid$(w$, p + len(p$(i)), 1)
p = p + len(p$(i))
next i
return n
end sub</langsyntaxhighlight>
 
{{trans|Run BASIC}}
<langsyntaxhighlight Yabasiclang="yabasic">t$ = "In olden times when wishing still helped one, there lived a king "
t$ = t$ + "whose daughters were all beautiful, but the youngest was so beautiful "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
Line 4,959 ⟶ 6,460:
close #f
 
void = system("explorer WordWrap.html")</langsyntaxhighlight>
 
=={{header|zkl}}==
This is a greedy algorithm for mono spaced text with ragged right. In addition, it can look at the first two lines to do "smart indenting". It handles multiple paragraphs and a variety of input sources.
<langsyntaxhighlight lang="zkl">fcn formatText(text, // text can be String,Data,File, -->Data
length=72, calcIndents=True){
sink:=Data();
getIndents:='wrap(w){ // look at first two lines to indent paragraph
reg lines=L(), len=0, prefix="", one=True;
do(2){
if(w._next()){
lines.append(line:=w.value);
word:=line.split(Void,1)[0,1]; // get first word, if line !blank
if(word){
p:=line[0,line.find(word[0]]);
if(one){ sink.write(p); len=p.len(); one=False; }
else prefix=p;
}
}
}
w.push(lines.xplode()); // put first two lines back to be formated
Line 4,983 ⟶ 6,484:
};
 
reg len=0, prefix="", w=text.walker(1); // lines
if(calcIndents) len,prefix=getIndents(w);
foreach line in (w){
if(not line.strip()){ // blank line
sink.write("\n",line); // blank line redux
if(calcIndents) len,prefix=getIndents(w);
else len=0; // restart formating
}else
len=line.split().reduce('wrap(len,word){
n:=word.len();
if(len==0) { sink.write(word); return(n); }
nn:=n+1+len; if(nn<=length) { sink.write(" ",word); return(nn); }
sink.write("\n",prefix,word); return(prefix.len()+word.len());
},len);
}
sink
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">formatText(File("frog.txt")).text.println();</langsyntaxhighlight>
{{out}}
<pre>
Line 5,012 ⟶ 6,513:
times ...
</pre>
<langsyntaxhighlight lang="zkl">[1..].zipWith("%2d: %s".fmt,formatText(File("frog.txt")).walker(1))
.pump(String).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 5,021 ⟶ 6,522:
9: favorite plaything.
</pre>
<langsyntaxhighlight lang="zkl">formatText("this\n is a test foo bar\n\ngreen eggs and spam",10).text.println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits