Word wrap: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Haskell}}: Tidied) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(12 intermediate revisions by 10 users not shown) | |||
Line 29:
{{trans|Go}}
<
V words = text.split_py()
I words.empty
Line 57:
L(width) (72, 80)
print(‘Wrapped at ’width":\n"word_wrap(frog, width))
print()</
{{out}}
Line 86:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
WORDWRAP CSECT
USING WORDWRAP,R13
Line 308:
PG DS CL80
YREGS
END WORDWRAP</
{{out}}
<pre>
Line 332:
=={{header|Action!}}==
<
CARD length
Line 432:
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]
Line 467:
=={{header|Ada}}==
The specification of a class '''Word_Wrap.Basic''' in a package '''Word_Wrap''':
<
with procedure Put_Line(Line: String);
package Word_Wrap is
Line 484:
end record;
end Word_Wrap;</
The implementation of that package:
<
procedure Push_Word(State: in out Basic; Word: String) is
Line 523:
end Finish;
end Word_Wrap;</
Finally, the main program:
<
procedure Wrap is
Line 588:
end loop;
Wrapper.Finish;
end Wrap;</
{{out}} set to 72 lines (with input picked by cut-and-paste from the task description):
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:
<
if (para is "") then return para
set astid to AppleScript's text item delimiters
Line 650:
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)</
{{output}}
<
in a standard library, show that. Otherwise implement the minimum
length greedy algorithm from Wikipedia.
Line 661:
standard library, show that. Otherwise
implement the minimum length greedy
algorithm from Wikipedia."</
However, it's more efficient to look for the last space in each line than to see how many "words" will fit:
<
set theLines to {}
set spaceTab to space & tab
Line 696:
return output
end wrapParagraph</
Using AppleScriptObjC, the second approach can be achieved with a regular expression:
<
use framework "Foundation"
Line 715:
return str as text
end wrapParagraph</
=={{header|Arturo}}==
<
print wordwrap txt
print ""
print wordwrap.at:45 txt</
{{out}}
Line 744:
=={{header|AutoHotkey}}==
Basic word-wrap. Formats text that has been copied to the clipboard.
<
return
Line 752:
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
return, Result
}</
{{Out}}
<pre>72
Line 779:
Basic word wrap.
<
{
if ( length(p) < 1 ) return
Line 818:
END {
wordwrap_paragraph(par)
}</
To test it,
Line 827:
=={{header|BaCon}}==
<
" there lived a king whose daughters were all beautiful, but" \
" the youngest was so beautiful that the sun itself, which has" \
Line 839:
PRINT ALIGN$(paragraph$, 72, 0)
PRINT ALIGN$(paragraph$, 90, 0)</
BaCon has the ALIGN$ function which can align text left-side, right-side, centered or both sides at any given column.
{{out}}
Line 863:
=={{header|Batch File}}==
Basic word wrap.
<
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:
)
endlocal & set "line=%line%"
goto proc_loop</
{{Out}}
<pre>Lorem ipsum dolor sit amet, consectetur
Line 921:
=={{header|Bracmat}}==
<
$ ( "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
Line 949:
& out$(str$("72 columns:\n" wrap$(!Text.72)))
& out$(str$("\n80 columns:\n" wrap$(!Text.80)))
);</
{{out}}
<pre>72 columns:
Line 973:
=={{header|C}}==
===Smart wrapping===
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,151 ⟶ 1,152:
return 0;
}</
===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:
<
{
using System;
Line 1,218 ⟶ 1,295:
}
}
}</
{{out}}
<pre>------------------------------------------------------------------------
Line 1,249 ⟶ 1,326:
Basic task.
{{trans|Go}}
<
#include <sstream>
#include <string>
Line 1,292 ⟶ 1,369:
std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}</
{{out}}
<pre>
Line 1,317 ⟶ 1,394:
=={{header|Clojure}}==
<
(defn wrap-line [size text]
(loop [left size line [] lines []
Line 1,329 ⟶ 1,406:
(recur (- size wlen) [word] (conj lines (apply str line)) (next words))))
(when (seq line)
(conj lines (apply str line))))))</
<
(defn wrap-line [size text]
(re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}"))
(clojure.string/replace text #"\n" " ")))</
<
(defn wrap-line [size text]
(clojure.pprint/cl-format nil (str "~{~<~%~1," size ":;~A~> ~}") (clojure.string/split text #" ")))</
Usage example :
<
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,352 ⟶ 1,429:
(doseq [line (wrap-line 72 text)]
(println line))</
{{out}}
Line 1,369 ⟶ 1,446:
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.
<
20 rem rosetta code
30 s$="":co=40:gosub 200
Line 1,407 ⟶ 1,484:
440 as$=as$+tp$
450 r$=as$
460 return</
{{out}}
Line 1,450 ⟶ 1,527:
=={{header|Common Lisp}}==
<
(defun greedy-wrap (str width)
Line 1,463 ⟶ 1,540:
(push (subseq str begin-curr-line prev-space) lines)
(setq begin-curr-line (1+ prev-space)) )))
</syntaxhighlight>
{{out}}
Line 1,498 ⟶ 1,575:
=={{header|D}}==
===Standard Version===
<
immutable frog =
"In olden times when wishing still helped one, there lived a king
Line 1,513 ⟶ 1,590:
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</
{{out}}
<pre>Wrapped at 72:
Line 1,540 ⟶ 1,617:
Basic algorithm. The text splitting is lazy.
{{trans|Go}}
<
string wrap(in string text, in int lineWidth) {
Line 1,574 ⟶ 1,651:
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}</
{{out}}
<pre>Wrapped at 72:
Line 1,596 ⟶ 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}}==
<
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
Line 1,638 ⟶ 1,882:
printWrap(at: 72)
printWrap(at: 80)</
{{out}}
Line 1,668 ⟶ 1,912:
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
<
import system'routines;
import extensions'text;
Line 1,694 ⟶ 1,978:
^ TokenEnumerator
.new(self)
.selectBy::(word)
{
currentWidth += word.Length;
Line 1,701 ⟶ 1,985:
currentWidth := word.Length + 1;
^
}
else
Line 1,720 ⟶ 2,004:
console.printLine(new StringWriter("-", 80));
console.printLine(text.wrap(80));
}</
{{out}}
<pre>
Line 1,746 ⟶ 2,030:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
Line 1,772 ⟶ 2,056:
IO.puts String.duplicate("-", len)
IO.puts Word_wrap.paragraph(text, len)
end)</
{{out}}
Line 1,792 ⟶ 2,076:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( word_wrap ).
Line 1,814 ⟶ 2,098:
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>
{{out}}
<pre>
Line 1,834 ⟶ 2,118:
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<
let LoremIpsum = "
Line 1,873 ⟶ 2,157:
Wrap l n |> Seq.iter (printf "%s")
printfn ""
0</
{{out}}
<pre style="font-size:smaller">------------------------------------------------------------------------
Line 1,902 ⟶ 2,186:
=={{header|Factor}}==
<
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,913 ⟶ 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</
{{out}}
<pre>
Line 1,953 ⟶ 2,237:
=={{header|Forth}}==
<
\ usage: gforth wrap.f in.txt 72
Line 1,978 ⟶ 2,262:
2dup strip-nl
.wrapped
bye</
=={{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, <
...
DO I = 0,120
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
END DO</
would write forth the text with eighty characters per line, paying no attention to the content when it splits a line.
Line 1,997 ⟶ 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">
MODULE RIVERRUN !Schemes for re-flowing wads of text to a specified line length.
INTEGER BL,BLIMIT,BM !Fingers for the scratchpad.
Line 2,122 ⟶ 2,406:
CALL FLOW("")
CLOSE (IN)
END</
Output: note that the chorus is presented with a leading space so as to force a new line start for it.
<pre>
Line 2,153 ⟶ 2,437:
=={{header|FreeBASIC}}==
<
texto = "In olden times when wishing still helped one, there lived a king " &_
Line 2,202 ⟶ 2,486:
WordWrap(texto,80)
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 2,230 ⟶ 2,514:
=={{header|Go}}==
Basic task, no extra credit.
<
import (
Line 2,272 ⟶ 2,556:
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
}</
{{out}}
<pre>
Line 2,299 ⟶ 2,583:
'''Solution 1: Imperative Style'''
<
def sb = new StringBuilder()
def line = ''
Line 2,311 ⟶ 2,595:
}
sb.append(line.trim()).toString()
}</
Testing:
<
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
Line 2,325 ⟶ 2,609:
println wordWrap(text)
println wordWrap(text, 120)</
{{out}}
<pre>In olden times when wishing still helped one, there lived a king whose daughters
Line 2,345 ⟶ 2,629:
A solution using the groovy list.inject method which corresponds to foldLeft in other languages.
<
String wordWrap(str, width=80) {
str.tokenize(' ').inject([[]]) { rows, word ->
Line 2,352 ⟶ 2,636:
}.collect { it.join(' ') }.join('\n')
}
</syntaxhighlight>
this solution shows off the more functional aspects of groovy.
Line 2,362 ⟶ 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:
<
import groovy.transform.TailRecursive
import static java.lang.Math.min
Line 2,371 ⟶ 2,655:
b.length()+w >= len ? b << str[i..-1] : wordWrap(str, w, min(x+w+1, len), b, len, 0)
}
</syntaxhighlight>
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 ⟶ 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:
<
def a = new StringBuilder()
def a = '' << ''
</
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 ⟶ 2,678:
=={{header|Haskell}}==
Greedy wrapping:
<
concat
[ "In olden times when wishing still helped one, there lived a king"
Line 2,418 ⟶ 2,702:
lw = length w
main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]</
Alternative greedy wrapping: <
wWrap :: Int -> String -> String
Line 2,459 ⟶ 2,743:
" caught it, and this ball was her favorite",
" plaything."
]</
=={{header|Icon}} and {{header|Unicon}}==
Line 2,465 ⟶ 2,749:
The following works in both languages.
<
procedure main(A)
ll := integer(A[1]) | 72
Line 2,486 ⟶ 2,770:
if *trim(l) = 0 then suspend "\n" # Paragraph boundary
}
end</
Sample runs:
Line 2,523 ⟶ 2,807:
=={{header|IS-BASIC}}==
The word warp, any kind of text alignment, specifying tab positions are basic services of the EXOS operating system.
<
110 CALL WRITE(12,68,0)
120 PRINT :CALL WRITE(10,70,1)
Line 2,541 ⟶ 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>
{{out}}
Line 2,568 ⟶ 2,852:
=={{header|J}}==
'''Solution''':<
wrap =: (] turn edges) ,&' '
turn =: LF"_`]`[}
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2</
'''Example''':<
ww GA NB. Wrap at 75 chars by default
Line 2,587 ⟶ 2,871:
dedicated to the
proposition that all men
were created equal.</
=={{header|Java}}==
<
package rosettacode;
Line 2,635 ⟶ 2,919:
}
</syntaxhighlight>
=={{header|JavaScript}}==
===Recursive===
'''Solution''':<
function wrap (text, limit) {
if (text.length > limit) {
Line 2,653 ⟶ 2,937:
return text;
}
</syntaxhighlight>
'''Example''':<
console.log(wrap(text, 80));
</syntaxhighlight>
{{out}}
Line 2,666 ⟶ 2,950:
</pre>
'''Example''':<
console.log(wrap(text, 42));
</syntaxhighlight>
{{out}}
Line 2,685 ⟶ 2,969:
A simple regex suffices (and proves fastest) for the greedy version:
<
'use strict';
Line 2,707 ⟶ 2,991:
)
})(60);</
{{Out}}
Line 2,719 ⟶ 3,003:
=== EcmaScript 6 ===
<
/**
* [wordwrap description]
Line 2,776 ⟶ 3,060:
}).join('\n'); // Объединяем элементы массива по LF
}
</syntaxhighlight>
'''Example'''<
console.log(wordwrap("The quick brown fox jumped over the lazy dog.", 20, "<br />\n"));
</syntaxhighlight>
{{out}}
Line 2,792 ⟶ 3,076:
In jq, all strings are Unicode strings, for which the length is calculated as the number of codepoints.
<
# Note: very long words are not truncated.
# input: a string
Line 2,805 ⟶ 3,089:
then .[-1] += ($pad * " ") + $word
else . + [ $word]
end );</
'''Task 1''':
<
{{Out}}
aaa bb
Line 2,813 ⟶ 3,097:
ddddd
'''Task 2''':
<
{{Out}}
aaa
Line 2,821 ⟶ 3,105:
'''With input from a file''': Russian.txt
<div style="overflow:scroll; height:100px;">
<
менее 100 советских самолетов поднялись в воздух, когдаамериканские
авианосцы "Уинсон" и "Мидуэй" приблизились на 50 миль к Владивостоку.
</
'''Main''':
wrap_text(40)[]
{{Out}}
<
советских военных судов и самолетов была
отмечена в Японском море после появления
Line 2,836 ⟶ 3,120:
"Уинсон" и "Мидуэй" приблизились на 50
миль к Владивостоку.
</syntaxhighlight>
=={{header|Julia}}==
Line 2,843 ⟶ 3,127:
Using [https://github.com/carlobaldassi/TextWrap.jl TextWrap.jl] library.
<
text = """Reformat the single paragraph in 'text' to fit in lines of no more
Line 2,854 ⟶ 3,138:
print_wrapped(text, width=80)
println("\n\n# Wrapped at 70 chars")
print_wrapped(text, width=70)</
{{out}}
Line 2,872 ⟶ 3,156:
=={{header|Klingphix}}==
<
%ps 0 !ps
Line 2,899 ⟶ 3,183:
100 wordwrap nl nl
"End " input</
{{out}}
<pre>tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH.
Line 2,925 ⟶ 3,209:
=={{header|Kotlin}}==
<
val text =
Line 2,961 ⟶ 3,245:
println("\nGreedy algorithm - wrapped at 80:")
println(greedyWordwrap(text, 80))
}</
{{out}}
Line 2,990 ⟶ 3,274:
The test text will be the third first paragraphs of Jules Verne's book, The Mysterious Island.
<
{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>
1) lambdatalk can simply call HTML tags and CSS rules:
<
{def wrap1
{lambda {:n}
Line 3,014 ⟶ 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>
2) a lambdatalk function
A translation from the Kotlin entry:
<
{def wrap2 // the function's name
Line 3,059 ⟶ 3,343:
jusqu’au quarantième parallèle sud ! (L’île mystérieuse /
Jules Verne)
</syntaxhighlight>
3) A translation of the javascript entry. The {jswrap n text} function contains lines until n characters
<
LAMBDATALK.DICT['jswrap'] = function() {
var wrap = function(text, limit) {
Line 3,093 ⟶ 3,377:
parallèle nord jusqu’au quarantième parallèle sud ! (L’île
mystérieuse / Jules Verne)
</syntaxhighlight>
=={{header|Lasso}}==
<
text::string,
row_length::integer = 75
Line 3,109 ⟶ 3,393:
wordwrap(#text)
'<hr />'
wordwrap(#text, 90)</
-><pre>Lorem ipsum dolor sit amet, consectetur
Line 3,137 ⟶ 3,421:
{{trans|Erlang}}
<syntaxhighlight lang="lisp">
(defun wrap-text (text)
(wrap-text text 78))
Line 3,163 ⟶ 3,447:
((word `#(,max ,line-len ,line ,acc))
`#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))
</syntaxhighlight>
=== Regex Implementation ===
<
(defun make-regex-str (max-len)
(++ "(.{1," (integer_to_list max-len) "}|\\S{"
Line 3,177 ⟶ 3,461:
(re:replace text find-patt replace-patt
'(global #(return list)))))
</syntaxhighlight>
Usage examples:
<syntaxhighlight 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>
<pre>
Even today, with proportional fonts and complex layouts, there are still cases
Line 3,195 ⟶ 3,479:
ok
</pre>
<
> (io:format (wrap-text text 50))
</syntaxhighlight>
<pre>
Even today, with proportional fonts and complex
Line 3,213 ⟶ 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)
<
----------------------------------------
Line 3,254 ⟶ 3,538:
channel(1).removeScriptedSprite()
return lines
end</
Usage:
<
"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 3,267 ⟶ 3,551:
repeat with l in lines
put l
end repeat</
{{Out}}
<pre>
Line 3,290 ⟶ 3,574:
=={{header|Lua}}==
<
local res = {}
for w in s:gmatch("%S+") do
Line 3,334 ⟶ 3,618:
print(textwrap(example1))
print()
print(textwrap(example1, 60))</
{{out}}
Line 3,375 ⟶ 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">
Module Checkit {
\\ leading space from begin of paragraph stay as is
Line 3,457 ⟶ 3,741:
}
Checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
wordWrap[textWidth_,spaceWidth_,string_]:=Module[{start,spaceLeft,masterString},
spaceLeft=textWidth;
Line 3,486 ⟶ 3,770:
];
StringJoin@@Riffle[masterString,"\n"]
];</
{{out}} for width 72 and 80:
<syntaxhighlight lang="text">wordWrap[72, 1, string]
wordWrap[80, 1, string]</
{{out}}
<pre>In olden times when wishing still helped one, there lived a king
Line 3,511 ⟶ 3,795:
=={{header|MiniScript}}==
<
width = 15
words = str.split
Line 3,526 ⟶ 3,810:
end if
end for
print line[:-1]</
{{out}}
<pre>
Line 3,538 ⟶ 3,822:
=={{header|NetRexx}}==
===version 1===
<
options replace format comments java crossref symbols
Line 3,614 ⟶ 3,898:
''
return speech01
</syntaxhighlight>
{{out}}
<pre style="height:15em; overflow:scroll">
Line 3,637 ⟶ 3,921:
===version 2===
<
* 23.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
Line 3,664 ⟶ 3,948:
If s>'' Then
say s
return</
=={{header|Nim}}==
<
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 ⟶ 3,957:
echo ""
echo txt.wrapWords(45)
</syntaxhighlight>
{{out}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 3,692 ⟶ 3,976:
=={{header|OCaml}}==
<
let txt = "In olden times when wishing still helped one, there lived
Line 3,724 ⟶ 4,008:
) (0, "") words
in
print_endline (Buffer.contents buf)</
Testing:
Line 3,735 ⟶ 4,019:
=={{header|Ol}}==
<
(define (get-one-word start)
(let loop ((chars #null) (end start))
Line 3,771 ⟶ 4,055:
(lines (get-all-lines words width)))
lines))
</syntaxhighlight>
{{out}}
Line 3,790 ⟶ 4,074:
=={{header|PARI/GP}}==
<
my(t="",cur);
s=Vec(s);
Line 3,815 ⟶ 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)</
{{out}}
Line 3,843 ⟶ 4,127:
=={{header|Perl}}==
Regex. Also showing degraded behavior on very long words:
<
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,860 ⟶ 4,144:
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print;</
=={{header|Phix}}==
<!--<
<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,
Line 3,889 ⟶ 4,173:
<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>
<!--</
{{Out}}
<pre>
Line 3,912 ⟶ 4,196:
=={{header|Phixmonti}}==
<
72 var long
Line 3,937 ⟶ 4,221:
endfor
drop ps> drop
</syntaxhighlight>
{{out}} 72 and 100.
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius
Line 3,961 ⟶ 4,245:
=={{header|PHP}}==
<
$text = <<<ENDTXT
Line 3,991 ⟶ 4,275:
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
</syntaxhighlight>
{{Out}}
<pre style="font-size:84%;height:55ex">
Line 4,040 ⟶ 4,324:
=={{header|Picat}}==
<
go =>
Line 4,073 ⟶ 4,357:
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.").</
{{out}}
Line 4,097 ⟶ 4,381:
=={{header|PicoLisp}}==
'[http://software-lab.de/doc/refW.html#wrap wrap]' is a built-in.
<
The quick
brown fox
jumps over
the lazy dog
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog"</
=={{header|PL/I}}==
<
ww: proc Options(main);
/*********************************************************************
Line 4,136 ⟶ 4,420:
End;
End;
End;</
Test result using this:
<pre>
Line 4,156 ⟶ 4,440:
=={{header|PowerShell}}==
Basic word wrap.
<
$divide=$args[0] -split " "
$width=$args[1]
Line 4,184 ⟶ 4,468:
wrap $paragraph 100
### End script</
{{Out}}
<pre>
Line 4,214 ⟶ 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">
function Out-WordWrap
{
Line 4,267 ⟶ 4,551:
}
}
</syntaxhighlight>
Grab some data and send it down the pipeline:
<syntaxhighlight 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 4,282 ⟶ 4,566:
$paragraphs | Out-WordWrap -Width 100
</syntaxhighlight>
{{Out}}
<pre>
Line 4,332 ⟶ 4,616:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<
word_wrap(String, Length, Wrapped):-
re_split("\\S+", String, Words),
Line 4,369 ⟶ 4,653:
test_word_wrap(60),
nl,
test_word_wrap(80).</
{{out}}
Line 4,393 ⟶ 4,677:
=={{header|PureBasic}}==
<
DataSection
Data.s "In olden times when wishing still helped one, there lived a king "+
Line 4,440 ⟶ 4,724:
Repeat : d$=Inkey() : Delay(50) : Until FindString("lr",d$,1,#PB_String_NoCase) : PrintN(d$+#CRLF$)
main(t$,lw) : Input()
</syntaxhighlight>
{{out}}
<pre>
Line 4,486 ⟶ 4,770:
=={{header|Python}}==
<
>>> help(textwrap.fill)
Help on function fill in module textwrap:
Line 4,525 ⟶ 4,809:
wrap(), tabs are expanded and other whitespace characters converted to space. See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> </
=={{header|Quackery}}==
<
a consuming love for cats and dedicates himself to the
protection of cats, you have only to accuse him of killing
Line 4,548 ⟶ 4,832:
55 wrap$ cr
75 wrap$ cr
say "-- William S. Burroughs, Ghost Of Chance, 1981" cr</
{{out}}
Line 4,590 ⟶ 4,874:
Use <code>strwrap()</code>:
<
> cat(paste(strwrap(x=c(x, "\n"), width=80), collapse="\n"))
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Line 4,603 ⟶ 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.</
=== Using the stringr tidyverse library ===
Another option, using <code>stringr::str_wrap</code>
<
> 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 4,617 ⟶ 4,901:
libero egestas mattis sit amet vitae augue. Nam tincidunt
congue enim, ut porta lorem lacinia consectetur.
</syntaxhighlight>
=={{header|Racket}}==
Using a library function:
<syntaxhighlight lang="racket">
#lang at-exp racket
(require scribble/text/wrap)
Line 4,636 ⟶ 4,920:
high and caught it, and this ball was her favorite plaything.})
(for-each displayln (wrap-line text 60))
</syntaxhighlight>
Explicit (and simple) implementation:
<
#lang racket
Line 4,662 ⟶ 4,946:
;;; Usage:
(wrap (string-split text) 70)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
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,680 ⟶ 4,964:
say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g);
say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g);</
=={{header|REXX}}==
===version 0===
This version was the original (of version 1) and has no error checking and only does left-margin justification.
<
parse arg iFID width . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID='LAWS.TXT' /*Not specified? Then use the default.*/
Line 4,702 ⟶ 4,986:
end /*m*/
if $\=='' then say $ /*handle any residual words (overflow).*/
/*stick a fork in it, we're all done. */</
'''output''' is the same as version 1 using the '''L'''eft option (the default).
Line 4,726 ⟶ 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.
<
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 4,767 ⟶ 5,051:
say $ /*display the line of words to terminal*/
_= x /*handle any word overflow. */
return /*go back and keep truckin'. */</
This REXX program makes use of '''LINESIZE''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
Line 5,047 ⟶ 5,331:
===version 2===
<
* 20.08.2013 Walter Pachl "my way"
* 23.08.2013 Walter Pachl changed to use lastpos bif
Line 5,074 ⟶ 5,358:
Call o s
Return
o:Return lineout(oid,arg(1))</
{{out}} for widths 72 and 9
<pre>
Line 5,101 ⟶ 5,385:
=={{header|Ring}}==
<
# Project : Word wrap
Line 5,132 ⟶ 5,416:
next
see line + nl + nl
</syntaxhighlight>
Output:
<pre>
Line 5,156 ⟶ 5,440:
=={{header|Ruby}}==
<
def wrap(width)
txt = gsub("\n", " ")
Line 5,186 ⟶ 5,470:
puts "." * w
puts text.wrap(w)
end</
{{out}}
Line 5,214 ⟶ 5,498:
Word Wrap style for different browsers.
This automatically adjusts the text if the browser window is stretched in any direction
<
"whose daughters were all beautiful, but the youngest was so beautiful ";_
"that the sun itself, which has seen so much, was astonished whenever ";_
Line 5,223 ⟶ 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>"</
output will adjust as you stretch the browser and maintain a 60 to 40 ratio of the width of the screen.
<pre>
Line 5,235 ⟶ 5,519:
</pre>
Without Browser
<
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
Line 5,257 ⟶ 5,541:
docOut$ = docOut$ + thisWord$
wend
print docOut$</
=={{header|Rust}}==
This is an implementation of the simple greedy algorithm.
<
pub struct LineComposer<I> {
words: I,
Line 5,358 ⟶ 5,642:
.for_each(|line| println!("{}", line));
}
</syntaxhighlight>
{{out}}
Line 5,374 ⟶ 5,658:
=={{header|Scala}}==
===Intuitive approach===
{{libheader|Scala}}<
object WordWrap extends App {
Line 5,417 ⟶ 5,701:
letsWrap(ewd)
letsWrap(ewd, 120)
} // 44 lines</
................................................................................
Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme.
Line 5,460 ⟶ 5,744:
The simple, greedy algorithm:
<
(import (scheme base)
(scheme write)
Line 5,500 ⟶ 5,784:
(show-para simple-word-wrap 50)
(show-para simple-word-wrap 60)
</syntaxhighlight>
{{out}}
Line 5,530 ⟶ 5,814:
=={{header|Seed7}}==
<
const func string: wrap (in string: aText, in integer: lineWidth) is func
Line 5,573 ⟶ 5,857:
writeln(wrap(frog, width));
end for;
end func;</
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 5,597 ⟶ 5,881:
=={{header|Sidef}}==
===Greedy word wrap===
<
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)
para.append(txt.substr(i, j-i))
i = j+1
}
return para.join("\n")
}
}
var text = 'aaa bb cc ddddd'
say text.wrap(6)
{{out}}
Line 5,624 ⟶ 5,908:
===Smart word wrap===
<
has width = 80
Line 5,650 ⟶ 5,934:
root << [
array.first(i+1).join(' '),
self.prepare_words(array.
]
Line 5,693 ⟶ 5,977:
self.combine([], path, { |combination|
var score = 0
combination.
score += (width - line.len -> sqr)
}
Line 5,707 ⟶ 5,991:
}
}
var sww = SmartWordWrap()
var words = %w(aaa bb cc ddddd)
var wrapped = sww.wrap(words, 6)
say wrapped
{{out}}
<pre>
Line 5,722 ⟶ 6,006:
=={{header|Standard ML}}==
<
let
fun appendLine (line, text) =
Line 5,736 ⟶ 6,020:
end
val () = (print o wordWrap 72 o TextIO.inputAll) TextIO.stdIn</
{{in}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
Line 5,750 ⟶ 6,034:
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.
<
proc wrapParagraph {n text} {
Line 5,778 ⟶ 6,099:
puts [wrapParagraph 80 $txt]
puts "[string repeat - 72]"
puts [wrapParagraph 72 $txt]</
{{out}}
<pre>--------------------------------------------------------------------------------
Line 5,803 ⟶ 6,124:
The text presentation program automatically provides word wrap:
<
=={{header|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 5,825 ⟶ 6,146:
wrappedtext=FORMAT(text,length,firstline,nextlines)
FILE "text" = wrappedtext
</syntaxhighlight>
{{out}}
<pre style='height:30ex;overflow:scroll'>
Line 5,850 ⟶ 6,171:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
column = 60
text = "In olden times when wishing still helped one, there lived a king " &_
Line 5,881 ⟶ 6,202:
End If
End Sub
</syntaxhighlight>
{{Out}}
Line 5,897 ⟶ 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}}
<
var words = text.split(" ")
var sb = words[0]
Line 5,932 ⟶ 6,317:
System.print(greedyWordWrap.call(text, 72))
System.print("\nGreedy algorithm - wrapped at 80:")
System.print(greedyWordWrap.call(text, 80))</
{{out}}
Line 5,951 ⟶ 6,336:
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
Line 5,959 ⟶ 6,407:
=={{header|Yabasic}}==
<
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 5,995 ⟶ 6,443:
next i
return n
end sub</
{{trans|Run BASIC}}
<
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 6,012 ⟶ 6,460:
close #f
void = system("explorer WordWrap.html")</
=={{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.
<
length=72, calcIndents=True){
sink:=Data();
Line 6,052 ⟶ 6,500:
}
sink
}</
<
{{out}}
<pre>
Line 6,065 ⟶ 6,513:
times ...
</pre>
<
.pump(String).println();</
{{out}}
<pre>
Line 6,074 ⟶ 6,522:
9: favorite plaything.
</pre>
<
{{out}}
<pre>
|