Word wrap: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 29: Line 29:
{{trans|Go}}
{{trans|Go}}


<lang 11l>F word_wrap(text, line_width)
<syntaxhighlight lang="11l">F word_wrap(text, line_width)
V words = text.split_py()
V words = text.split_py()
I words.empty
I words.empty
Line 57: Line 57:
L(width) (72, 80)
L(width) (72, 80)
print(‘Wrapped at ’width":\n"word_wrap(frog, width))
print(‘Wrapped at ’width":\n"word_wrap(frog, width))
print()</lang>
print()</syntaxhighlight>


{{out}}
{{out}}
Line 86: Line 86:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<lang 360asm>* Word wrap 29/01/2017
<syntaxhighlight lang="360asm">* Word wrap 29/01/2017
WORDWRAP CSECT
WORDWRAP CSECT
USING WORDWRAP,R13
USING WORDWRAP,R13
Line 308: Line 308:
PG DS CL80
PG DS CL80
YREGS
YREGS
END WORDWRAP</lang>
END WORDWRAP</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 332: Line 332:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>CHAR ARRAY text(1000)
<syntaxhighlight lang="action!">CHAR ARRAY text(1000)
CARD length
CARD length


Line 432: Line 432:
LMARGIN=old ;restore left margin on the screen
LMARGIN=old ;restore left margin on the screen
RETURN
RETURN
</syntaxhighlight>
</lang>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Word_wrap.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Word_wrap.png Screenshot from Atari 8-bit computer]
Line 467: Line 467:
=={{header|Ada}}==
=={{header|Ada}}==
The specification of a class '''Word_Wrap.Basic''' in a package '''Word_Wrap''':
The specification of a class '''Word_Wrap.Basic''' in a package '''Word_Wrap''':
<lang Ada>generic
<syntaxhighlight lang="ada">generic
with procedure Put_Line(Line: String);
with procedure Put_Line(Line: String);
package Word_Wrap is
package Word_Wrap is
Line 484: Line 484:
end record;
end record;


end Word_Wrap;</lang>
end Word_Wrap;</syntaxhighlight>


The implementation of that package:
The implementation of that package:


<lang Ada>package body Word_Wrap is
<syntaxhighlight lang="ada">package body Word_Wrap is


procedure Push_Word(State: in out Basic; Word: String) is
procedure Push_Word(State: in out Basic; Word: String) is
Line 523: Line 523:
end Finish;
end Finish;


end Word_Wrap;</lang>
end Word_Wrap;</syntaxhighlight>


Finally, the main program:
Finally, the main program:


<lang Ada>with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line;
<syntaxhighlight lang="ada">with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line;


procedure Wrap is
procedure Wrap is
Line 588: Line 588:
end loop;
end loop;
Wrapper.Finish;
Wrapper.Finish;
end Wrap;</lang>
end Wrap;</syntaxhighlight>


{{out}} set to 72 lines (with input picked by cut-and-paste from the task description):
{{out}} set to 72 lines (with input picked by cut-and-paste from the task description):
Line 617: Line 617:
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:
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:


<lang applescript>on wrapParagraph(para, lineWidth)
<syntaxhighlight lang="applescript">on wrapParagraph(para, lineWidth)
if (para is "") then return para
if (para is "") then return para
set astid to AppleScript's text item delimiters
set astid to AppleScript's text item delimiters
Line 650: Line 650:
local para
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."
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)</lang>
return wrapParagraph(para, 70) & (linefeed & linefeed) & wrapParagraph(para, 40)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"If there is a way to do this that is built-in, trivial, or provided
<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
in a standard library, show that. Otherwise implement the minimum
length greedy algorithm from Wikipedia.
length greedy algorithm from Wikipedia.
Line 661: Line 661:
standard library, show that. Otherwise
standard library, show that. Otherwise
implement the minimum length greedy
implement the minimum length greedy
algorithm from Wikipedia."</lang>
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:
However, it's more efficient to look for the last space in each line than to see how many "words" will fit:


<lang applescript>on wrapParagraph(para, lineWidth)
<syntaxhighlight lang="applescript">on wrapParagraph(para, lineWidth)
set theLines to {}
set theLines to {}
set spaceTab to space & tab
set spaceTab to space & tab
Line 696: Line 696:
return output
return output
end wrapParagraph</lang>
end wrapParagraph</syntaxhighlight>


Using AppleScriptObjC, the second approach can be achieved with a regular expression:
Using AppleScriptObjC, the second approach can be achieved with a regular expression:


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 715: Line 715:
return str as text
return str as text
end wrapParagraph</lang>
end wrapParagraph</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<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."
<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 wordwrap txt
print ""
print ""
print wordwrap.at:45 txt</lang>
print wordwrap.at:45 txt</syntaxhighlight>


{{out}}
{{out}}
Line 744: Line 744:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Basic word-wrap. Formats text that has been copied to the clipboard.
Basic word-wrap. Formats text that has been copied to the clipboard.
<lang AutoHotkey>MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
<syntaxhighlight lang="autohotkey">MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
return
return


Line 752: Line 752:
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
return, Result
return, Result
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>72
<pre>72
Line 779: Line 779:
Basic word wrap.
Basic word wrap.


<lang awk>function wordwrap_paragraph(p)
<syntaxhighlight lang="awk">function wordwrap_paragraph(p)
{
{
if ( length(p) < 1 ) return
if ( length(p) < 1 ) return
Line 818: Line 818:
END {
END {
wordwrap_paragraph(par)
wordwrap_paragraph(par)
}</lang>
}</syntaxhighlight>


To test it,
To test it,
Line 827: Line 827:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang qbasic>paragraph$ = "In olden times when wishing still helped one," \
<syntaxhighlight lang="qbasic">paragraph$ = "In olden times when wishing still helped one," \
" there lived a king whose daughters were all beautiful, but" \
" there lived a king whose daughters were all beautiful, but" \
" the youngest was so beautiful that the sun itself, which has" \
" the youngest was so beautiful that the sun itself, which has" \
Line 839: Line 839:


PRINT ALIGN$(paragraph$, 72, 0)
PRINT ALIGN$(paragraph$, 72, 0)
PRINT ALIGN$(paragraph$, 90, 0)</lang>
PRINT ALIGN$(paragraph$, 90, 0)</syntaxhighlight>
BaCon has the ALIGN$ function which can align text left-side, right-side, centered or both sides at any given column.
BaCon has the ALIGN$ function which can align text left-side, right-side, centered or both sides at any given column.
{{out}}
{{out}}
Line 863: Line 863:
=={{header|Batch File}}==
=={{header|Batch File}}==
Basic word wrap.
Basic word wrap.
<lang dos>@echo off
<syntaxhighlight 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!"
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 902: Line 902:
)
)
endlocal & set "line=%line%"
endlocal & set "line=%line%"
goto proc_loop</lang>
goto proc_loop</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Lorem ipsum dolor sit amet, consectetur
<pre>Lorem ipsum dolor sit amet, consectetur
Line 921: Line 921:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( str
<syntaxhighlight lang="bracmat">( str
$ ( "In olden times when wishing still helped one, there lived a king "
$ ( "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
"whose daughters were all beautiful, but the youngest was so beautiful "
Line 949: Line 949:
& out$(str$("72 columns:\n" wrap$(!Text.72)))
& out$(str$("72 columns:\n" wrap$(!Text.72)))
& out$(str$("\n80 columns:\n" wrap$(!Text.80)))
& out$(str$("\n80 columns:\n" wrap$(!Text.80)))
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>72 columns:
<pre>72 columns:
Line 973: Line 973:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 1,151: Line 1,151:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
Greedy algorithm:
Greedy algorithm:
<lang csharp>namespace RosettaCode.WordWrap
<syntaxhighlight lang="csharp">namespace RosettaCode.WordWrap
{
{
using System;
using System;
Line 1,218: Line 1,218:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>------------------------------------------------------------------------
<pre>------------------------------------------------------------------------
Line 1,249: Line 1,249:
Basic task.
Basic task.
{{trans|Go}}
{{trans|Go}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <sstream>
#include <string>
#include <string>
Line 1,292: Line 1,292:
std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,317: Line 1,317:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>;; Wrap line naive version
<syntaxhighlight lang="clojure">;; Wrap line naive version
(defn wrap-line [size text]
(defn wrap-line [size text]
(loop [left size line [] lines []
(loop [left size line [] lines []
Line 1,329: Line 1,329:
(recur (- size wlen) [word] (conj lines (apply str line)) (next words))))
(recur (- size wlen) [word] (conj lines (apply str line)) (next words))))
(when (seq line)
(when (seq line)
(conj lines (apply str line))))))</lang>
(conj lines (apply str line))))))</syntaxhighlight>


<lang Clojure>;; Wrap line base on regular expression
<syntaxhighlight lang="clojure">;; Wrap line base on regular expression
(defn wrap-line [size text]
(defn wrap-line [size text]
(re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}"))
(re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}"))
(clojure.string/replace text #"\n" " ")))</lang>
(clojure.string/replace text #"\n" " ")))</syntaxhighlight>


<lang Clojure>;; cl-format based version
<syntaxhighlight lang="clojure">;; cl-format based version
(defn wrap-line [size text]
(defn wrap-line [size text]
(clojure.pprint/cl-format nil (str "~{~<~%~1," size ":;~A~> ~}") (clojure.string/split text #" ")))</lang>
(clojure.pprint/cl-format nil (str "~{~<~%~1," size ":;~A~> ~}") (clojure.string/split text #" ")))</syntaxhighlight>


Usage example :
Usage example :
<lang Clojure>(def text "In olden times when wishing still helped one, there lived
<syntaxhighlight lang="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
a king whose daughters were all beautiful, but the youngest was so
beautiful that the sun itself, which has seen so much, was astonished
beautiful that the sun itself, which has seen so much, was astonished
Line 1,352: Line 1,352:


(doseq [line (wrap-line 72 text)]
(doseq [line (wrap-line 72 text)]
(println line))</lang>
(println line))</syntaxhighlight>


{{out}}
{{out}}
Line 1,369: Line 1,369:
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.
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.


<lang gwbasic>10 rem word wrap - commodore basic
<syntaxhighlight lang="gwbasic">10 rem word wrap - commodore basic
20 rem rosetta code
20 rem rosetta code
30 s$="":co=40:gosub 200
30 s$="":co=40:gosub 200
Line 1,407: Line 1,407:
440 as$=as$+tp$
440 as$=as$+tp$
450 r$=as$
450 r$=as$
460 return</lang>
460 return</syntaxhighlight>


{{out}}
{{out}}
Line 1,450: Line 1,450:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang Lisp>;; Greedy wrap line
<syntaxhighlight lang="lisp">;; Greedy wrap line


(defun greedy-wrap (str width)
(defun greedy-wrap (str width)
Line 1,463: Line 1,463:
(push (subseq str begin-curr-line prev-space) lines)
(push (subseq str begin-curr-line prev-space) lines)
(setq begin-curr-line (1+ prev-space)) )))
(setq begin-curr-line (1+ prev-space)) )))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,498: Line 1,498:
=={{header|D}}==
=={{header|D}}==
===Standard Version===
===Standard Version===
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
immutable frog =
immutable frog =
"In olden times when wishing still helped one, there lived a king
"In olden times when wishing still helped one, there lived a king
Line 1,513: Line 1,513:
foreach (width; [72, 80])
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Wrapped at 72:
<pre>Wrapped at 72:
Line 1,540: Line 1,540:
Basic algorithm. The text splitting is lazy.
Basic algorithm. The text splitting is lazy.
{{trans|Go}}
{{trans|Go}}
<lang d>import std.algorithm;
<syntaxhighlight lang="d">import std.algorithm;


string wrap(in string text, in int lineWidth) {
string wrap(in string text, in int lineWidth) {
Line 1,574: Line 1,574:
foreach (width; [72, 80])
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Wrapped at 72:
<pre>Wrapped at 72:
Line 1,599: Line 1,599:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>let loremIpsum = <[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
<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
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
Line 1,638: Line 1,638:
printWrap(at: 72)
printWrap(at: 72)
printWrap(at: 80)</lang>
printWrap(at: 80)</syntaxhighlight>


{{out}}
{{out}}
Line 1,671: Line 1,671:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import extensions'text;
import extensions'text;
Line 1,720: Line 1,720:
console.printLine(new StringWriter("-", 80));
console.printLine(new StringWriter("-", 80));
console.printLine(text.wrap(80));
console.printLine(text.wrap(80));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,746: Line 1,746:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Word_wrap do
<syntaxhighlight lang="elixir">defmodule Word_wrap do
def paragraph( string, max_line_length ) do
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
[word | rest] = String.split( string, ~r/\s+/, trim: true )
Line 1,772: Line 1,772:
IO.puts String.duplicate("-", len)
IO.puts String.duplicate("-", len)
IO.puts Word_wrap.paragraph(text, len)
IO.puts Word_wrap.paragraph(text, len)
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,792: Line 1,792:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( word_wrap ).
-module( word_wrap ).


Line 1,814: Line 1,814:
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} ) 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}.
lines_assemble( Word, {Max, Line_length, Line, Acc} ) -> {Max, Line_length + 1 + erlang:length(Word), Line ++ " " ++ Word, Acc}.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,834: Line 1,834:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let LoremIpsum = "
let LoremIpsum = "
Line 1,873: Line 1,873:
Wrap l n |> Seq.iter (printf "%s")
Wrap l n |> Seq.iter (printf "%s")
printfn ""
printfn ""
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre style="font-size:smaller">------------------------------------------------------------------------
<pre style="font-size:smaller">------------------------------------------------------------------------
Line 1,902: Line 1,902:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: wrap.strings
<syntaxhighlight lang="factor">USE: wrap.strings
IN: scratchpad "Most languages in widespread use today are applicative languages
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
: the central construct in the language is some form of function call, where a f
Line 1,913: Line 1,913:
ns are invoked simply by mentioning their name without any additional syntax, Fo
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
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</lang>
e just words." [ 60 wrap-string print nl ] [ 45 wrap-string print ] bi</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,953: Line 1,953:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>\ wrap text
<syntaxhighlight lang="forth">\ wrap text
\ usage: gforth wrap.f in.txt 72
\ usage: gforth wrap.f in.txt 72


Line 1,978: Line 1,978:
2dup strip-nl
2dup strip-nl
.wrapped
.wrapped
bye</lang>
bye</syntaxhighlight>


=={{header|Fortran}}==
=={{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.
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, <lang Fortran> CHARACTER*12345 TEXT
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, <syntaxhighlight lang="fortran"> CHARACTER*12345 TEXT
...
...
DO I = 0,120
DO I = 0,120
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
END DO</lang>
END DO</syntaxhighlight>
would write forth the text with eighty characters per line, paying no attention to the content when it splits a line.
would write forth the text with eighty characters per line, paying no attention to the content when it splits a line.


Line 1,997: Line 1,997:


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.
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.
MODULE RIVERRUN !Schemes for re-flowing wads of text to a specified line length.
INTEGER BL,BLIMIT,BM !Fingers for the scratchpad.
INTEGER BL,BLIMIT,BM !Fingers for the scratchpad.
Line 2,122: Line 2,122:
CALL FLOW("")
CALL FLOW("")
CLOSE (IN)
CLOSE (IN)
END</lang>
END</syntaxhighlight>
Output: note that the chorus is presented with a leading space so as to force a new line start for it.
Output: note that the chorus is presented with a leading space so as to force a new line start for it.
<pre>
<pre>
Line 2,153: Line 2,153:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>Dim Shared As String texto, dividido()
<syntaxhighlight lang="freebasic">Dim Shared As String texto, dividido()


texto = "In olden times when wishing still helped one, there lived a king " &_
texto = "In olden times when wishing still helped one, there lived a king " &_
Line 2,202: Line 2,202:
WordWrap(texto,80)
WordWrap(texto,80)
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,230: Line 2,230:
=={{header|Go}}==
=={{header|Go}}==
Basic task, no extra credit.
Basic task, no extra credit.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,272: Line 2,272:
fmt.Println("wrapped at 72:")
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
fmt.Println(wrap(frog, 72))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,299: Line 2,299:


'''Solution 1: Imperative Style'''
'''Solution 1: Imperative Style'''
<lang groovy>def wordWrap(text, length = 80) {
<syntaxhighlight lang="groovy">def wordWrap(text, length = 80) {
def sb = new StringBuilder()
def sb = new StringBuilder()
def line = ''
def line = ''
Line 2,311: Line 2,311:
}
}
sb.append(line.trim()).toString()
sb.append(line.trim()).toString()
}</lang>
}</syntaxhighlight>
Testing:
Testing:
<lang groovy>def text = """\
<syntaxhighlight lang="groovy">def text = """\
In olden times when wishing still helped one, there lived a king
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
whose daughters were all beautiful, but the youngest was so beautiful
Line 2,325: Line 2,325:


println wordWrap(text)
println wordWrap(text)
println wordWrap(text, 120)</lang>
println wordWrap(text, 120)</syntaxhighlight>
{{out}}
{{out}}
<pre>In olden times when wishing still helped one, there lived a king whose daughters
<pre>In olden times when wishing still helped one, there lived a king whose daughters
Line 2,345: Line 2,345:
A solution using the groovy list.inject method which corresponds to foldLeft in other languages.
A solution using the groovy list.inject method which corresponds to foldLeft in other languages.


<lang groovy>
<syntaxhighlight lang="groovy">
String wordWrap(str, width=80) {
String wordWrap(str, width=80) {
str.tokenize(' ').inject([[]]) { rows, word ->
str.tokenize(' ').inject([[]]) { rows, word ->
Line 2,352: Line 2,352:
}.collect { it.join(' ') }.join('\n')
}.collect { it.join(' ') }.join('\n')
}
}
</syntaxhighlight>
</lang>


this solution shows off the more functional aspects of groovy.
this solution shows off the more functional aspects of groovy.
Line 2,362: Line 2,362:
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:
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:


<lang groovy>
<syntaxhighlight lang="groovy">
import groovy.transform.TailRecursive
import groovy.transform.TailRecursive
import static java.lang.Math.min
import static java.lang.Math.min
Line 2,371: Line 2,371:
b.length()+w >= len ? b << str[i..-1] : wordWrap(str, w, min(x+w+1, len), b, len, 0)
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.
Should be noted that this is not idiomatic groovy or a recommended way of programming, but it is interesting as an exercise.
Line 2,381: Line 2,381:
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:
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:


<lang groovy>
<syntaxhighlight lang="groovy">
def a = new StringBuilder()
def a = new StringBuilder()
def a = '' << ''
def a = '' << ''
</lang>
</syntaxhighlight>


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.
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 2,394: Line 2,394:
=={{header|Haskell}}==
=={{header|Haskell}}==
Greedy wrapping:
Greedy wrapping:
<lang haskell>ss =
<syntaxhighlight lang="haskell">ss =
concat
concat
[ "In olden times when wishing still helped one, there lived a king"
[ "In olden times when wishing still helped one, there lived a king"
Line 2,418: Line 2,418:
lw = length w
lw = length w


main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]</lang>
main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]</syntaxhighlight>




Alternative greedy wrapping: <lang haskell>import Data.List (inits, tail, tails)
Alternative greedy wrapping: <syntaxhighlight lang="haskell">import Data.List (inits, tail, tails)


wWrap :: Int -> String -> String
wWrap :: Int -> String -> String
Line 2,459: Line 2,459:
" caught it, and this ball was her favorite",
" caught it, and this ball was her favorite",
" plaything."
" plaything."
]</lang>
]</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 2,465: Line 2,465:
The following works in both languages.
The following works in both languages.


<lang unicon>
<syntaxhighlight lang="unicon">
procedure main(A)
procedure main(A)
ll := integer(A[1]) | 72
ll := integer(A[1]) | 72
Line 2,486: Line 2,486:
if *trim(l) = 0 then suspend "\n" # Paragraph boundary
if *trim(l) = 0 then suspend "\n" # Paragraph boundary
}
}
end</lang>
end</syntaxhighlight>


Sample runs:
Sample runs:
Line 2,523: Line 2,523:
=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
The word warp, any kind of text alignment, specifying tab positions are basic services of the EXOS operating system.
The word warp, any kind of text alignment, specifying tab positions are basic services of the EXOS operating system.
<lang IS-BASIC>100 TEXT 80
<syntaxhighlight lang="is-basic">100 TEXT 80
110 CALL WRITE(12,68,0)
110 CALL WRITE(12,68,0)
120 PRINT :CALL WRITE(10,70,1)
120 PRINT :CALL WRITE(10,70,1)
Line 2,541: Line 2,541:
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, "
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."
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}}
{{out}}
Line 2,568: Line 2,568:


=={{header|J}}==
=={{header|J}}==
'''Solution''':<lang j>ww =: 75&$: : wrap
'''Solution''':<syntaxhighlight lang="j">ww =: 75&$: : wrap
wrap =: (] turn edges) ,&' '
wrap =: (] turn edges) ,&' '
turn =: LF"_`]`[}
turn =: LF"_`]`[}
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2</lang>
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2</syntaxhighlight>
'''Example''':<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.'
'''Example''':<syntaxhighlight 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
ww GA NB. Wrap at 75 chars by default
Line 2,587: Line 2,587:
dedicated to the
dedicated to the
proposition that all men
proposition that all men
were created equal.</lang>
were created equal.</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>
<syntaxhighlight lang="java">
package rosettacode;
package rosettacode;


Line 2,635: Line 2,635:
}
}


</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


===Recursive===
===Recursive===
'''Solution''':<lang javascript>
'''Solution''':<syntaxhighlight lang="javascript">
function wrap (text, limit) {
function wrap (text, limit) {
if (text.length > limit) {
if (text.length > limit) {
Line 2,653: Line 2,653:
return text;
return text;
}
}
</syntaxhighlight>
</lang>
'''Example''':<lang javascript>
'''Example''':<syntaxhighlight lang="javascript">
console.log(wrap(text, 80));
console.log(wrap(text, 80));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,666: Line 2,666:
</pre>
</pre>


'''Example''':<lang javascript>
'''Example''':<syntaxhighlight lang="javascript">
console.log(wrap(text, 42));
console.log(wrap(text, 42));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,685: Line 2,685:
A simple regex suffices (and proves fastest) for the greedy version:
A simple regex suffices (and proves fastest) for the greedy version:


<lang javascript>(function (width) {
<syntaxhighlight lang="javascript">(function (width) {
'use strict';
'use strict';


Line 2,707: Line 2,707:
)
)


})(60);</lang>
})(60);</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,719: Line 2,719:


=== EcmaScript 6 ===
=== EcmaScript 6 ===
<lang javascript>
<syntaxhighlight lang="javascript">
/**
/**
* [wordwrap description]
* [wordwrap description]
Line 2,776: Line 2,776:
}).join('\n'); // Объединяем элементы массива по LF
}).join('\n'); // Объединяем элементы массива по LF
}
}
</syntaxhighlight>
</lang>


'''Example'''<lang javascript>
'''Example'''<syntaxhighlight lang="javascript">
console.log(wordwrap("The quick brown fox jumped over the lazy dog.", 20, "<br />\n"));
console.log(wordwrap("The quick brown fox jumped over the lazy dog.", 20, "<br />\n"));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,792: Line 2,792:


In jq, all strings are Unicode strings, for which the length is calculated as the number of codepoints.
In jq, all strings are Unicode strings, for which the length is calculated as the number of codepoints.
<lang jq># Simple greedy algorithm.
<syntaxhighlight lang="jq"># Simple greedy algorithm.
# Note: very long words are not truncated.
# Note: very long words are not truncated.
# input: a string
# input: a string
Line 2,805: Line 2,805:
then .[-1] += ($pad * " ") + $word
then .[-1] += ($pad * " ") + $word
else . + [ $word]
else . + [ $word]
end );</lang>
end );</syntaxhighlight>
'''Task 1''':
'''Task 1''':
<lang jq>"aaa bb cc ddddd" | wrap_text(6)[] # wikipedia example</lang>
<syntaxhighlight lang="jq">"aaa bb cc ddddd" | wrap_text(6)[] # wikipedia example</syntaxhighlight>
{{Out}}
{{Out}}
aaa bb
aaa bb
Line 2,813: Line 2,813:
ddddd
ddddd
'''Task 2''':
'''Task 2''':
<lang jq>"aaa bb cc ddddd" | wrap_text(5)[]</lang>
<syntaxhighlight lang="jq">"aaa bb cc ddddd" | wrap_text(5)[]</syntaxhighlight>
{{Out}}
{{Out}}
aaa
aaa
Line 2,821: Line 2,821:
'''With input from a file''': Russian.txt
'''With input from a file''': Russian.txt
<div style="overflow:scroll; height:100px;">
<div style="overflow:scroll; height:100px;">
<lang sh>советских военных судов и самолетов была отмечена в Японском море после появления там двух американских авианосцев. Не
<syntaxhighlight lang="sh">советских военных судов и самолетов была отмечена в Японском море после появления там двух американских авианосцев. Не
менее 100 советских самолетов поднялись в воздух, когдаамериканские
менее 100 советских самолетов поднялись в воздух, когдаамериканские
авианосцы "Уинсон" и "Мидуэй" приблизились на 50 миль к Владивостоку.
авианосцы "Уинсон" и "Мидуэй" приблизились на 50 миль к Владивостоку.
</lang></div>
</syntaxhighlight></div>
'''Main''':
'''Main''':
wrap_text(40)[]
wrap_text(40)[]
{{Out}}
{{Out}}
<lang sh>$ jq -M -R -s -r -f Word_wrap.jq Russian.txt
<syntaxhighlight lang="sh">$ jq -M -R -s -r -f Word_wrap.jq Russian.txt
советских военных судов и самолетов была
советских военных судов и самолетов была
отмечена в Японском море после появления
отмечена в Японском море после появления
Line 2,836: Line 2,836:
"Уинсон" и "Мидуэй" приблизились на 50
"Уинсон" и "Мидуэй" приблизились на 50
миль к Владивостоку.
миль к Владивостоку.
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
Line 2,843: Line 2,843:
Using [https://github.com/carlobaldassi/TextWrap.jl TextWrap.jl] library.
Using [https://github.com/carlobaldassi/TextWrap.jl TextWrap.jl] library.


<lang julia>using TextWrap
<syntaxhighlight lang="julia">using TextWrap


text = """Reformat the single paragraph in 'text' to fit in lines of no more
text = """Reformat the single paragraph in 'text' to fit in lines of no more
Line 2,854: Line 2,854:
print_wrapped(text, width=80)
print_wrapped(text, width=80)
println("\n\n# Wrapped at 70 chars")
println("\n\n# Wrapped at 70 chars")
print_wrapped(text, width=70)</lang>
print_wrapped(text, width=70)</syntaxhighlight>


{{out}}
{{out}}
Line 2,872: Line 2,872:


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>:wordwrap %long !long
<syntaxhighlight lang="klingphix">:wordwrap %long !long
%ps 0 !ps
%ps 0 !ps
Line 2,899: Line 2,899:
100 wordwrap nl nl
100 wordwrap nl nl


"End " input</lang>
"End " input</syntaxhighlight>
{{out}}
{{out}}
<pre>tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH.
<pre>tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH.
Line 2,925: Line 2,925:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


val text =
val text =
Line 2,961: Line 2,961:
println("\nGreedy algorithm - wrapped at 80:")
println("\nGreedy algorithm - wrapped at 80:")
println(greedyWordwrap(text, 80))
println(greedyWordwrap(text, 80))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,990: Line 2,990:


The test text will be the third first paragraphs of Jules Verne's book, The Mysterious Island.
The test text will be the third first paragraphs of Jules Verne's book, The Mysterious Island.
<lang scheme>
<syntaxhighlight lang="scheme">
{def text
{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)}
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
-> text
</syntaxhighlight>
</lang>


1) lambdatalk can simply call HTML tags and CSS rules:
1) lambdatalk can simply call HTML tags and CSS rules:
<lang scheme>
<syntaxhighlight lang="scheme">
{def wrap1
{def wrap1
{lambda {:n}
{lambda {:n}
Line 3,014: Line 3,014:
à l’équateur, depuis le trente-cinquième parallèle nord jusqu’au
à l’équateur, depuis le trente-cinquième parallèle nord jusqu’au
quarantième parallèle sud ! (L’île mystérieuse / Jules Verne)
quarantième parallèle sud ! (L’île mystérieuse / Jules Verne)
</syntaxhighlight>
</lang>


2) a lambdatalk function
2) a lambdatalk function


A translation from the Kotlin entry:
A translation from the Kotlin entry:
<lang scheme>
<syntaxhighlight lang="scheme">
{def wrap2 // the function's name
{def wrap2 // the function's name


Line 3,059: Line 3,059:
jusqu’au quarantième parallèle sud ! (L’île mystérieuse /
jusqu’au quarantième parallèle sud ! (L’île mystérieuse /
Jules Verne)
Jules Verne)
</syntaxhighlight>
</lang>


3) A translation of the javascript entry. The {jswrap n text} function contains lines until n characters
3) A translation of the javascript entry. The {jswrap n text} function contains lines until n characters


<lang javascript>
<syntaxhighlight lang="javascript">
LAMBDATALK.DICT['jswrap'] = function() {
LAMBDATALK.DICT['jswrap'] = function() {
var wrap = function(text, limit) {
var wrap = function(text, limit) {
Line 3,093: Line 3,093:
parallèle nord jusqu’au quarantième parallèle sud ! (L’île
parallèle nord jusqu’au quarantième parallèle sud ! (L’île
mystérieuse / Jules Verne)
mystérieuse / Jules Verne)
</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define wordwrap(
<syntaxhighlight lang="lasso">define wordwrap(
text::string,
text::string,
row_length::integer = 75
row_length::integer = 75
Line 3,109: Line 3,109:
wordwrap(#text)
wordwrap(#text)
'<hr />'
'<hr />'
wordwrap(#text, 90)</lang>
wordwrap(#text, 90)</syntaxhighlight>


-><pre>Lorem ipsum dolor sit amet, consectetur
-><pre>Lorem ipsum dolor sit amet, consectetur
Line 3,137: Line 3,137:
{{trans|Erlang}}
{{trans|Erlang}}


<syntaxhighlight lang="lisp">
<lang Lisp>
(defun wrap-text (text)
(defun wrap-text (text)
(wrap-text text 78))
(wrap-text text 78))
Line 3,163: Line 3,163:
((word `#(,max ,line-len ,line ,acc))
((word `#(,max ,line-len ,line ,acc))
`#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))
`#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))
</syntaxhighlight>
</lang>


=== Regex Implementation ===
=== Regex Implementation ===


<lang lisp>
<syntaxhighlight lang="lisp">
(defun make-regex-str (max-len)
(defun make-regex-str (max-len)
(++ "(.{1," (integer_to_list max-len) "}|\\S{"
(++ "(.{1," (integer_to_list max-len) "}|\\S{"
Line 3,177: Line 3,177:
(re:replace text find-patt replace-patt
(re:replace text find-patt replace-patt
'(global #(return list)))))
'(global #(return list)))))
</syntaxhighlight>
</lang>


Usage examples:
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. "
> (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 "
"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.")
"provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.")
> (io:format (wrap-text text 80))
> (io:format (wrap-text text 80))
</syntaxhighlight>
</lang>
<pre>
<pre>
Even today, with proportional fonts and complex layouts, there are still cases
Even today, with proportional fonts and complex layouts, there are still cases
Line 3,195: Line 3,195:
ok
ok
</pre>
</pre>
<lang lisp>
<syntaxhighlight lang="lisp">
> (io:format (wrap-text text 50))
> (io:format (wrap-text text 50))
</syntaxhighlight>
</lang>
<pre>
<pre>
Even today, with proportional fonts and complex
Even today, with proportional fonts and complex
Line 3,213: Line 3,213:
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:
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)
(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)
<lang lingo>-- in some movie script
<syntaxhighlight lang="lingo">-- in some movie script


----------------------------------------
----------------------------------------
Line 3,254: Line 3,254:
channel(1).removeScriptedSprite()
channel(1).removeScriptedSprite()
return lines
return lines
end</lang>
end</syntaxhighlight>
Usage:
Usage:
<lang lingo>str = "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed "&\
<syntaxhighlight 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 "&\
"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 "&\
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi "&\
Line 3,267: Line 3,267:
repeat with l in lines
repeat with l in lines
put l
put l
end repeat</lang>
end repeat</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,290: Line 3,290:
=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>function splittokens(s)
<syntaxhighlight lang="lua">function splittokens(s)
local res = {}
local res = {}
for w in s:gmatch("%S+") do
for w in s:gmatch("%S+") do
Line 3,334: Line 3,334:
print(textwrap(example1))
print(textwrap(example1))
print()
print()
print(textwrap(example1, 60))</lang>
print(textwrap(example1, 60))</syntaxhighlight>


{{out}}
{{out}}
Line 3,375: Line 3,375:
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).
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 {
Module Checkit {
\\ leading space from begin of paragraph stay as is
\\ leading space from begin of paragraph stay as is
Line 3,457: Line 3,457:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang 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.";
<syntaxhighlight lang="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},
wordWrap[textWidth_,spaceWidth_,string_]:=Module[{start,spaceLeft,masterString},
spaceLeft=textWidth;
spaceLeft=textWidth;
Line 3,486: Line 3,486:
];
];
StringJoin@@Riffle[masterString,"\n"]
StringJoin@@Riffle[masterString,"\n"]
];</lang>
];</syntaxhighlight>
{{out}} for width 72 and 80:
{{out}} for width 72 and 80:
<lang>wordWrap[72, 1, string]
<syntaxhighlight lang="text">wordWrap[72, 1, string]
wordWrap[80, 1, string]</lang>
wordWrap[80, 1, string]</syntaxhighlight>
{{out}}
{{out}}
<pre>In olden times when wishing still helped one, there lived a king
<pre>In olden times when wishing still helped one, there lived a king
Line 3,511: Line 3,511:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>str = "one two three four five six seven eight nine ten eleven!"
<syntaxhighlight lang="miniscript">str = "one two three four five six seven eight nine ten eleven!"
width = 15
width = 15
words = str.split
words = str.split
Line 3,526: Line 3,526:
end if
end if
end for
end for
print line[:-1]</lang>
print line[:-1]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,538: Line 3,538:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
===version 1===
===version 1===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols
options replace format comments java crossref symbols


Line 3,614: Line 3,614:
''
''
return speech01
return speech01
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:15em; overflow:scroll">
<pre style="height:15em; overflow:scroll">
Line 3,637: Line 3,637:


===version 2===
===version 2===
<lang NetRexx>/* NetRexx ************************************************************
<syntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* 23.08.2013 Walter Pachl translated from REXX version 2
* 23.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
**********************************************************************/
Line 3,664: Line 3,664:
If s>'' Then
If s>'' Then
say s
say s
return</lang>
return</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import std/wordwrap
<syntaxhighlight lang="nim">import std/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."
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."
Line 3,673: Line 3,673:
echo ""
echo ""
echo txt.wrapWords(45)
echo txt.wrapWords(45)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 3,692: Line 3,692:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>#load "str.cma"
<syntaxhighlight lang="ocaml">#load "str.cma"


let txt = "In olden times when wishing still helped one, there lived
let txt = "In olden times when wishing still helped one, there lived
Line 3,724: Line 3,724:
) (0, "") words
) (0, "") words
in
in
print_endline (Buffer.contents buf)</lang>
print_endline (Buffer.contents buf)</syntaxhighlight>


Testing:
Testing:
Line 3,735: Line 3,735:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (get-one-word start)
(define (get-one-word start)
(let loop ((chars #null) (end start))
(let loop ((chars #null) (end start))
Line 3,771: Line 3,771:
(lines (get-all-lines words width)))
(lines (get-all-lines words width)))
lines))
lines))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,790: Line 3,790:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>wrap(s,len)={
<syntaxhighlight lang="parigp">wrap(s,len)={
my(t="",cur);
my(t="",cur);
s=Vec(s);
s=Vec(s);
Line 3,815: Line 3,815:
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.";
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, 75)
wrap(King, 50)</lang>
wrap(King, 50)</syntaxhighlight>


{{out}}
{{out}}
Line 3,843: Line 3,843:
=={{header|Perl}}==
=={{header|Perl}}==
Regex. Also showing degraded behavior on very long words:
Regex. Also showing degraded behavior on very long words:
<lang perl>my $s = "In olden times when wishing still helped one, there lived a king
<syntaxhighlight 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
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
that the sun itself, which has seen so much, was astonished whenever
Line 3,860: Line 3,860:


$_ = $s;
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print;</lang>
s/\s*(.{1,25})\s/$1\n/g, print;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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
<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,
Line 3,889: Line 3,889:
<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>
<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>
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,912: Line 3,912:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


72 var long
72 var long
Line 3,937: Line 3,937:
endfor
endfor
drop ps> drop
drop ps> drop
</syntaxhighlight>
</lang>
{{out}} 72 and 100.
{{out}} 72 and 100.
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius
Line 3,961: Line 3,961:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php


$text = <<<ENDTXT
$text = <<<ENDTXT
Line 3,991: Line 3,991:


echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre style="font-size:84%;height:55ex">
<pre style="font-size:84%;height:55ex">
Line 4,040: Line 4,040:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>import util.
<syntaxhighlight lang="picat">import util.


go =>
go =>
Line 4,073: Line 4,073:
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.").</lang>
laborum.").</syntaxhighlight>


{{out}}
{{out}}
Line 4,097: Line 4,097:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
'[http://software-lab.de/doc/refW.html#wrap wrap]' is a built-in.
'[http://software-lab.de/doc/refW.html#wrap wrap]' is a built-in.
<lang PicoLisp>: (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog")))
<syntaxhighlight lang="picolisp">: (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog")))
The quick
The quick
brown fox
brown fox
jumps over
jumps over
the lazy dog
the lazy dog
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog"</lang>
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog"</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>*process source attributes xref or(!);
<syntaxhighlight lang="pli">*process source attributes xref or(!);
ww: proc Options(main);
ww: proc Options(main);
/*********************************************************************
/*********************************************************************
Line 4,136: Line 4,136:
End;
End;
End;
End;
End;</lang>
End;</syntaxhighlight>
Test result using this:
Test result using this:
<pre>
<pre>
Line 4,156: Line 4,156:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
Basic word wrap.
Basic word wrap.
<lang powershell>function wrap{
<syntaxhighlight lang="powershell">function wrap{
$divide=$args[0] -split " "
$divide=$args[0] -split " "
$width=$args[1]
$width=$args[1]
Line 4,184: Line 4,184:
wrap $paragraph 100
wrap $paragraph 100


### End script</lang>
### End script</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,214: Line 4,214:
===Pipeline Version===
===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.
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
function Out-WordWrap
{
{
Line 4,267: Line 4,267:
}
}
}
}
</syntaxhighlight>
</lang>
Grab some data and send it down the pipeline:
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.",
[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.",
"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 4,282: Line 4,282:


$paragraphs | Out-WordWrap -Width 100
$paragraphs | Out-WordWrap -Width 100
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,332: Line 4,332:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>% See https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_number_of_lines
<syntaxhighlight lang="prolog">% See https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap#Minimum_number_of_lines
word_wrap(String, Length, Wrapped):-
word_wrap(String, Length, Wrapped):-
re_split("\\S+", String, Words),
re_split("\\S+", String, Words),
Line 4,369: Line 4,369:
test_word_wrap(60),
test_word_wrap(60),
nl,
nl,
test_word_wrap(80).</lang>
test_word_wrap(80).</syntaxhighlight>


{{out}}
{{out}}
Line 4,393: Line 4,393:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>
<syntaxhighlight lang="purebasic">
DataSection
DataSection
Data.s "In olden times when wishing still helped one, there lived a king "+
Data.s "In olden times when wishing still helped one, there lived a king "+
Line 4,440: Line 4,440:
Repeat : d$=Inkey() : Delay(50) : Until FindString("lr",d$,1,#PB_String_NoCase) : PrintN(d$+#CRLF$)
Repeat : d$=Inkey() : Delay(50) : Until FindString("lr",d$,1,#PB_String_NoCase) : PrintN(d$+#CRLF$)
main(t$,lw) : Input()
main(t$,lw) : Input()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,486: Line 4,486:


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> import textwrap
<syntaxhighlight lang="python">>>> import textwrap
>>> help(textwrap.fill)
>>> help(textwrap.fill)
Help on function fill in module textwrap:
Help on function fill in module textwrap:
Line 4,525: Line 4,525:
wrap(), tabs are expanded and other whitespace characters converted to space. See
wrap(), tabs are expanded and other whitespace characters converted to space. See
TextWrapper class for available keyword args to customize wrapping behaviour.
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> </lang>
>>> </syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> $ "Consider the inexorable logic of the Big Lie. If a man has
<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
a consuming love for cats and dedicates himself to the
protection of cats, you have only to accuse him of killing
protection of cats, you have only to accuse him of killing
Line 4,548: Line 4,548:
55 wrap$ cr
55 wrap$ cr
75 wrap$ cr
75 wrap$ cr
say "-- William S. Burroughs, Ghost Of Chance, 1981" cr</lang>
say "-- William S. Burroughs, Ghost Of Chance, 1981" cr</syntaxhighlight>


{{out}}
{{out}}
Line 4,590: Line 4,590:


Use <code>strwrap()</code>:
Use <code>strwrap()</code>:
<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. "
<syntaxhighlight 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"))
> cat(paste(strwrap(x=c(x, "\n"), width=80), collapse="\n"))
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 4,603: Line 4,603:
hendrerit. Donec et mollis dolor. Praesent et diam eget
hendrerit. Donec et mollis dolor. Praesent et diam eget
libero egestas mattis sit amet vitae augue. Nam tincidunt
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.</lang>
congue enim, ut porta lorem lacinia consectetur.</syntaxhighlight>


=== Using the stringr tidyverse library ===
=== Using the stringr tidyverse library ===


Another option, using <code>stringr::str_wrap</code>
Another option, using <code>stringr::str_wrap</code>
<lang rsplus>
<syntaxhighlight 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. "
> 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))
> cat(stringr::str_wrap(x, 60))
Line 4,617: Line 4,617:
libero egestas mattis sit amet vitae augue. Nam tincidunt
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.
congue enim, ut porta lorem lacinia consectetur.
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


Using a library function:
Using a library function:
<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket
#lang at-exp racket
(require scribble/text/wrap)
(require scribble/text/wrap)
Line 4,636: Line 4,636:
high and caught it, and this ball was her favorite plaything.})
high and caught it, and this ball was her favorite plaything.})
(for-each displayln (wrap-line text 60))
(for-each displayln (wrap-line text 60))
</syntaxhighlight>
</lang>


Explicit (and simple) implementation:
Explicit (and simple) implementation:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 4,662: Line 4,662:
;;; Usage:
;;; Usage:
(wrap (string-split text) 70)
(wrap (string-split text) 70)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>my $s = "In olden times when wishing still helped one, there lived a king
<syntaxhighlight lang="raku" line>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
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
that the sun itself, which has seen so much, was astonished whenever
Line 4,680: Line 4,680:


say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g);
say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g);
say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g);</lang>
say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g);</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 0===
===version 0===
This version was the original (of version 1) and has no error checking and only does left-margin justification.
This version was the original (of version 1) and has no error checking and only does left-margin justification.
<lang rexx>/*REXX program reads a file and displays it to the screen (with word wrap). */
<syntaxhighlight 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*/
parse arg iFID width . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID='LAWS.TXT' /*Not specified? Then use the default.*/
if iFID=='' | iFID=="," then iFID='LAWS.TXT' /*Not specified? Then use the default.*/
Line 4,702: Line 4,702:
end /*m*/
end /*m*/
if $\=='' then say $ /*handle any residual words (overflow).*/
if $\=='' then say $ /*handle any residual words (overflow).*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; is the same as version 1 using the &nbsp; '''L'''eft &nbsp; option (the default).
'''output''' &nbsp; is the same as version 1 using the &nbsp; '''L'''eft &nbsp; option (the default).


Line 4,726: Line 4,726:
<br>Instead of appending lines of a file to a character string, the words are picked off and stored in a stemmed array.
<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.
<br>This decreases the amount of work that REXX has to do to retrieve (get) the next word in the (possibly) ginormous string.
<lang rexx>/*REXX program reads a file and displays it to the screen (with word wrap). */
<syntaxhighlight 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*/
parse arg iFID width kind _ . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID = 'LAWS.TXT' /*Not specified? Then use the default.*/
if iFID=='' | iFID=="," then iFID = 'LAWS.TXT' /*Not specified? Then use the default.*/
Line 4,767: Line 4,767:
say $ /*display the line of words to terminal*/
say $ /*display the line of words to terminal*/
_= x /*handle any word overflow. */
_= x /*handle any word overflow. */
return /*go back and keep truckin'. */</lang>
return /*go back and keep truckin'. */</syntaxhighlight>
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).
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 5,047: Line 5,047:


===version 2===
===version 2===
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* 20.08.2013 Walter Pachl "my way"
* 20.08.2013 Walter Pachl "my way"
* 23.08.2013 Walter Pachl changed to use lastpos bif
* 23.08.2013 Walter Pachl changed to use lastpos bif
Line 5,074: Line 5,074:
Call o s
Call o s
Return
Return
o:Return lineout(oid,arg(1))</lang>
o:Return lineout(oid,arg(1))</syntaxhighlight>
{{out}} for widths 72 and 9
{{out}} for widths 72 and 9
<pre>
<pre>
Line 5,101: Line 5,101:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Word wrap
# Project : Word wrap


Line 5,132: Line 5,132:
next
next
see line + nl + nl
see line + nl + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,156: Line 5,156:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>class String
<syntaxhighlight lang="ruby">class String
def wrap(width)
def wrap(width)
txt = gsub("\n", " ")
txt = gsub("\n", " ")
Line 5,186: Line 5,186:
puts "." * w
puts "." * w
puts text.wrap(w)
puts text.wrap(w)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 5,214: Line 5,214:
Word Wrap style for different browsers.
Word Wrap style for different browsers.
This automatically adjusts the text if the browser window is stretched in any direction
This automatically adjusts the text if the browser window is stretched in any direction
<lang runbasic>doc$ = "In olden times when wishing still helped one, there lived a king ";_
<syntaxhighlight 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 ";_
"whose daughters were all beautiful, but the youngest was so beautiful ";_
"that the sun itself, which has seen so much, was astonished whenever ";_
"that the sun itself, which has seen so much, was astonished whenever ";_
Line 5,223: Line 5,223:


html "<table border=1 cellpadding=2 cellspacing=0><tr" + wrap$ +" valign=top>"
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>"</lang>
html "<td width=60%>" + doc$ + "</td><td width=40%>" + doc$ + "</td></tr></table>"</syntaxhighlight>
output will adjust as you stretch the browser and maintain a 60 to 40 ratio of the width of the screen.
output will adjust as you stretch the browser and maintain a 60 to 40 ratio of the width of the screen.
<pre>
<pre>
Line 5,235: Line 5,235:
</pre>
</pre>
Without Browser
Without Browser
<lang runbasic>doc$ = "In olden times when wishing still helped one, there lived a king
<syntaxhighlight 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
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
that the sun itself, which has seen so much, was astonished whenever
Line 5,257: Line 5,257:
docOut$ = docOut$ + thisWord$
docOut$ = docOut$ + thisWord$
wend
wend
print docOut$</lang>
print docOut$</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
This is an implementation of the simple greedy algorithm.
This is an implementation of the simple greedy algorithm.


<lang Rust>#[derive(Clone, Debug)]
<syntaxhighlight lang="rust">#[derive(Clone, Debug)]
pub struct LineComposer<I> {
pub struct LineComposer<I> {
words: I,
words: I,
Line 5,358: Line 5,358:
.for_each(|line| println!("{}", line));
.for_each(|line| println!("{}", line));
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,374: Line 5,374:
=={{header|Scala}}==
=={{header|Scala}}==
===Intuitive approach===
===Intuitive approach===
{{libheader|Scala}}<lang scala>import java.util.StringTokenizer
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.util.StringTokenizer


object WordWrap extends App {
object WordWrap extends App {
Line 5,417: Line 5,417:
letsWrap(ewd)
letsWrap(ewd)
letsWrap(ewd, 120)
letsWrap(ewd, 120)
} // 44 lines</lang>{{out}}<pre>Wrapped at: 80
} // 44 lines</syntaxhighlight>{{out}}<pre>Wrapped at: 80
................................................................................
................................................................................
Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme.
Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme.
Line 5,460: Line 5,460:
The simple, greedy algorithm:
The simple, greedy algorithm:


<lang scheme>
<syntaxhighlight lang="scheme">
(import (scheme base)
(import (scheme base)
(scheme write)
(scheme write)
Line 5,500: Line 5,500:
(show-para simple-word-wrap 50)
(show-para simple-word-wrap 50)
(show-para simple-word-wrap 60)
(show-para simple-word-wrap 60)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,530: Line 5,530:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func string: wrap (in string: aText, in integer: lineWidth) is func
const func string: wrap (in string: aText, in integer: lineWidth) is func
Line 5,573: Line 5,573:
writeln(wrap(frog, width));
writeln(wrap(frog, width));
end for;
end for;
end func;</lang>{{out}}<pre>Wrapped at 72:
end func;</syntaxhighlight>{{out}}<pre>Wrapped at 72:
In olden times when wishing still helped one, there lived a king whose
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
daughters were all beautiful, but the youngest was so beautiful that the
Line 5,597: Line 5,597:
=={{header|Sidef}}==
=={{header|Sidef}}==
===Greedy word wrap===
===Greedy word wrap===
<lang ruby>class String {
<syntaxhighlight lang="ruby">class String {
method wrap(width) {
method wrap(width) {
var txt = self.gsub(/\s+/, " ");
var txt = self.gsub(/\s+/, " ");
Line 5,614: Line 5,614:


var text = 'aaa bb cc ddddd';
var text = 'aaa bb cc ddddd';
say text.wrap(6);</lang>
say text.wrap(6);</syntaxhighlight>


{{out}}
{{out}}
Line 5,624: Line 5,624:


===Smart word wrap===
===Smart word wrap===
<lang ruby>class SmartWordWrap {
<syntaxhighlight lang="ruby">class SmartWordWrap {


has width = 80
has width = 80
Line 5,713: Line 5,713:
var wrapped = sww.wrap(words, 6);
var wrapped = sww.wrap(words, 6);
say wrapped;</lang>
say wrapped;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,722: Line 5,722:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun wordWrap n s =
<syntaxhighlight lang="sml">fun wordWrap n s =
let
let
fun appendLine (line, text) =
fun appendLine (line, text) =
Line 5,736: Line 5,736:
end
end


val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn</lang>
val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn</syntaxhighlight>
{{in}}
{{in}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
Line 5,753: Line 5,753:
=={{header|Tcl}}==
=={{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.
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.
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


proc wrapParagraph {n text} {
proc wrapParagraph {n text} {
Line 5,778: Line 5,778:
puts [wrapParagraph 80 $txt]
puts [wrapParagraph 80 $txt]
puts "[string repeat - 72]"
puts "[string repeat - 72]"
puts [wrapParagraph 72 $txt]</lang>
puts [wrapParagraph 72 $txt]</syntaxhighlight>
{{out}}
{{out}}
<pre>--------------------------------------------------------------------------------
<pre>--------------------------------------------------------------------------------
Line 5,803: Line 5,803:
The text presentation program automatically provides word wrap:
The text presentation program automatically provides word wrap:


<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.</lang>
<syntaxhighlight 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.</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE 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."
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 5,825: Line 5,825:
wrappedtext=FORMAT(text,length,firstline,nextlines)
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext
FILE "text" = wrappedtext
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style='height:30ex;overflow:scroll'>
<pre style='height:30ex;overflow:scroll'>
Line 5,850: Line 5,850:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
column = 60
column = 60
text = "In olden times when wishing still helped one, there lived a king " &_
text = "In olden times when wishing still helped one, there lived a king " &_
Line 5,881: Line 5,881:
End If
End If
End Sub
End Sub
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 5,901: Line 5,901:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang ecmascript>fn wrap(text string, line_width int) string {
<syntaxhighlight lang="ecmascript">fn wrap(text string, line_width int) string {
mut wrapped := ''
mut wrapped := ''
words := text.fields()
words := text.fields()
Line 5,937: Line 5,937:
println("wrapped at 72:")
println("wrapped at 72:")
println(wrap(frog, 72))
println(wrap(frog, 72))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,965: Line 5,965:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>var greedyWordWrap = Fn.new { |text, lineWidth|
<syntaxhighlight lang="ecmascript">var greedyWordWrap = Fn.new { |text, lineWidth|
var words = text.split(" ")
var words = text.split(" ")
var sb = words[0]
var sb = words[0]
Line 5,996: Line 5,996:
System.print(greedyWordWrap.call(text, 72))
System.print(greedyWordWrap.call(text, 72))
System.print("\nGreedy algorithm - wrapped at 80:")
System.print("\nGreedy algorithm - wrapped at 80:")
System.print(greedyWordWrap.call(text, 80))</lang>
System.print(greedyWordWrap.call(text, 80))</syntaxhighlight>


{{out}}
{{out}}
Line 6,023: Line 6,023:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0;
<syntaxhighlight lang="xpl0">string 0;
proc WordWrap(Text, LineWidth); \Display Text string wrapped at LineWidth
proc WordWrap(Text, LineWidth); \Display Text string wrapped at LineWidth
char Text, LineWidth, Word, SpaceLeft, WordWidth, I;
char Text, LineWidth, Word, SpaceLeft, WordWidth, I;
Line 6,060: Line 6,060:
WordWrap(Text, 72); CrLf(0);
WordWrap(Text, 72); CrLf(0);
WordWrap(Text, 80); CrLf(0);
WordWrap(Text, 80); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 6,086: Line 6,086:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>t$ = "In olden times when wishing still helped one, there lived a king "
<syntaxhighlight lang="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$ + "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 "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
Line 6,122: Line 6,122:
next i
next i
return n
return n
end sub</lang>
end sub</syntaxhighlight>


{{trans|Run BASIC}}
{{trans|Run BASIC}}
<lang Yabasic>t$ = "In olden times when wishing still helped one, there lived a king "
<syntaxhighlight lang="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$ + "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 "
t$ = t$ + "that the sun itself, which has seen so much, was astonished whenever "
Line 6,139: Line 6,139:
close #f
close #f


void = system("explorer WordWrap.html")</lang>
void = system("explorer WordWrap.html")</syntaxhighlight>


=={{header|zkl}}==
=={{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.
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.
<lang zkl>fcn formatText(text, // text can be String,Data,File, -->Data
<syntaxhighlight lang="zkl">fcn formatText(text, // text can be String,Data,File, -->Data
length=72, calcIndents=True){
length=72, calcIndents=True){
sink:=Data();
sink:=Data();
Line 6,179: Line 6,179:
}
}
sink
sink
}</lang>
}</syntaxhighlight>
<lang zkl>formatText(File("frog.txt")).text.println();</lang>
<syntaxhighlight lang="zkl">formatText(File("frog.txt")).text.println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,192: Line 6,192:
times ...
times ...
</pre>
</pre>
<lang zkl>[1..].zipWith("%2d: %s".fmt,formatText(File("frog.txt")).walker(1))
<syntaxhighlight lang="zkl">[1..].zipWith("%2d: %s".fmt,formatText(File("frog.txt")).walker(1))
.pump(String).println();</lang>
.pump(String).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,201: Line 6,201:
9: favorite plaything.
9: favorite plaything.
</pre>
</pre>
<lang zkl>formatText("this\n is a test foo bar\n\ngreen eggs and spam",10).text.println();</lang>
<syntaxhighlight lang="zkl">formatText("this\n is a test foo bar\n\ngreen eggs and spam",10).text.println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>