Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,4 @@
---
category:
- Text processing
from: http://rosettacode.org/wiki/Word_wrap

View file

@ -0,0 +1,24 @@
Even today, with proportional fonts and complex layouts, there are still [[Template:Lines_too_long|cases]] where you need to wrap text at a specified column.
;Basic task:
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 [http://en.wikipedia.org/wiki/Word_wrap#Minimum_length minimum length greedy algorithm from Wikipedia.]
Show your routine working on a sample of text at two different wrap columns.
;Extra credit:
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,29 @@
F word_wrap(text, line_width)
V words = text.split_py()
I words.empty
R
V wrapped = words[0]
V space_left = line_width - wrapped.len
L(word) words[1..]
I word.len + 1 > space_left
wrapped = "\n"word
space_left = line_width - word.len
E
wrapped = word
space_left -= 1 + word.len
R wrapped
V frog =
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.
L(width) (72, 80)
print(Wrapped at width":\n"word_wrap(frog, width))
print()

View file

@ -0,0 +1,223 @@
* Word wrap 29/01/2017
WORDWRAP CSECT
USING WORDWRAP,R13
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
MVC S2,=CL96' ' s2=''
SR R0,R0
STH R0,LENS2 lens2=0
LA R8,1 i=1
LOOPI CH R8,=AL2(NTS) do i=1 to hbound(ts)
BH ELOOPI --
LH R4,LENS2
LTR R4,R4 if lens2=0
BNZ IFLENS2 then
LR R1,R8 i
MH R1,=H'48'
LA R14,TS-48(R1)
MVC S(48),0(R14) s=ts(i)
MVC S+48(48),=CL48' '
LA R12,L'TS jmax=length(ts)
B EIFLENS2 else
IFLENS2 MVC S,=CL96' ' s=''
LA R6,S @s
LH R7,LENS2
LA R4,S2 @s2
LH R5,LENS2
MVCL R6,R4 substr(s,1,lens2)=substr(s2,1,lens2)
LH R2,LENS2
LA R2,1(R2) lens2+1
LR R1,R8 i
MH R1,=H'48'
LA R14,TS-48(R1) @ts(i)
LA R15,S-1
AR R15,R2
MVC 0(48,R15),0(R14) substr(s,lens2+1,48)=ts(i)
LA R12,L'S jmax=length(s)
EIFLENS2 MVI OKS2,X'01' oks2=true
WHILEOK CLI OKS2,X'01' do while(oks2)
BNE EWHILEOK --
LR R9,R12 j=jmax /*loop1*/
LOOPJ1 CH R9,=H'1' do j=jmax to 1 by -1
BL ELOOPJ1 --
LA R14,S-1 @s-1
AR R14,R9 j
MVC CJ(1),0(R14) cj=substr(s,j,1)
CLI CJ,C' ' if cj^=' '
BNE ELOOPJ1 then leave j
BCTR R9,0 j=j-1
B LOOPJ1 end do j
ELOOPJ1 STH R9,LENS lens=j {length of s}
MVI OKJ,X'00' okj=false /*loop2*/
LH R11,W js=w
LH R4,W
CH R4,LENS if w>lens
BNH IFWLENS
LH R11,LENS js=lens
IFWLENS LR R9,R11 j=js
LOOPJ2 CH R9,=H'1' do j=js to 1 by -1
BL ELOOPJ2 --
LA R14,S-1 @s-1
AR R14,R9 +j
MVC CJ(1),0(R14) cj=substr(s,j,1)
CLI CJ,C' ' if cj=' '
BNE ITERJ2 then
MVI OKJ,X'01' okj=true
B ELOOPJ2 leave j
ITERJ2 BCTR R9,0 j=j-1
B LOOPJ2 end do j
ELOOPJ2 CLI OKJ,X'00' if ^okj
BNE ELOOPK
MVI OKK,X'00' okk=false /*loop3*/
LH R10,W k=w
LOOPK CH R10,LENS do k=w to lens
BH ELOOPK --
LA R14,S-1 @s-1
AR R14,R10 +k
MVC CK(1),0(R14) ck=substr(s,k,1)
CLI CK,C' ' if ck=' '
BNE ITERK then
MVI OKK,X'01' okk=true
B ELOOPK leave k
ITERK LA R10,1(R10) k=k+1
B LOOPK end do k
ELOOPK MVC S2,=CL96' ' s2=' '
SR R0,R0
STH R0,LENS2 lens2=0
MVI CAS,X'01' cas=true
LH R1,LENS
CH R1,W lens<w
BL IFLENSLW
MVI CAS,X'00' cas=false
IFLENSLW CLI CAS,X'00' if ^cas
BNE IFNOTCAS then
CLI OKJ,X'01' if okj
BNE NOKJ then
STH R9,LENS1 lens1=j
LH R2,LENS
SR R2,R9 -j
LA R2,1(R2)
STH R2,LENS2 lens2=lens-j+1
LA R6,S1
LR R7,R9 j
LA R4,S
LR R5,R7
MVCL R6,R4 s1=substr(s,1,j)
LH R4,LENS2
LTR R4,R4 if lens2>0
BNP ELJLENS2 then
LA R6,S2
LH R7,LENS2
LA R4,S(R9) @s(j+1)
LR R5,R7
MVCL R6,R4 s2=substr(s,j+1,lens2)
B EFJLENS2
ELJLENS2 SR R0,R0 else
STH R0,LENS2 lens2=0
EFJLENS2 B IFNOTCAS
NOKJ CLI OKK,X'01' else if okk
BNE NOTOKK
STH R10,LENS1 lens1=k
LH R2,LENS
SR R2,R10 -k
LA R2,1(R2)
STH R2,LENS2 lens2=lens-k+1
LA R6,S1
LR R7,R10 k
LA R4,S
LR R5,R7
MVCL R6,R4 s1=substr(s,1,k)
LH R4,LENS2
LTR R4,R4 if lens2>0
BNP ELKLENS2 then
LA R6,S2
LH R7,LENS2
LA R4,S(R10) @s(k+1)
LR R5,R7
MVCL R6,R4 s2=substr(s,k+1,lens2)
B EFKLENS2 else
ELKLENS2 SR R0,R0
STH R0,LENS2 lens2=0
EFKLENS2 B IFNOTCAS else
NOTOKK LH R0,LENS
STH R0,LENS1 lens1=lens
MVC S1,S s1=s
IFNOTCAS CLI CAS,X'01' if cas
BNE ELCAS then
LH R7,LENS
LA R7,1(R7)
LA R6,S2
LA R4,S
LR R5,R7
MVCL R6,R4 s2=substr(s,1,lens+1)
LH R2,LENS
LA R2,1(R2)
STH R2,LENS2 lens2=lens+1
B EFCAS else
ELCAS LA R6,PG
LA R7,L'PG
LA R4,S1
LH R5,LENS1
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s1,1,lens1)
XPRNT PG,L'PG put skip list(pg)
EFCAS MVI OKS2,X'00' oks2=false
LH R4,LENS2
CH R4,W if lens2>w
BNH EFWLENS2 then
MVI OKS2,X'01' oks2=true
LH R0,LENS2
STH R0,LENS lens=lens2
MVC S,S2 s=s2
EFWLENS2 B WHILEOK end while
EWHILEOK LA R8,1(R8) i=i+1
B LOOPI end do i
ELOOPI LH R4,LENS2
LTR R4,R4 if lens2^=0
BZ EFLENS2N then
LA R6,PG
LA R7,L'PG
LA R4,S2
LH R5,LENS2
ICM R5,B'1000',=C' ' padding
MVCL R6,R4 pg=substr(s2,1,lens2)
XPRNT PG,L'PG put skip list(pg)
EFLENS2N L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
TS DC CL48'In olden times when wishing still helped one,'
DC CL48'there lived a king whose daughters were all,'
DC CL48'beautiful, but the youngest was so beautiful'
DC CL48'that the sun itself, which has seen so much,'
DC CL48'was astonished whenever it shone in her face.'
DC CL48'Close by the king''s castle lay a great dark'
DC CL48'forest, and under an old lime tree in the'
DC CL48'forest was a well, and when the day was very'
DC CL48'warm, the king''s child went out into the forest'
DC CL48'and sat down by the side of the cool fountain,'
DC CL48'and when she was bored she took a golden ball,'
DC CL48'and threw it up on high and caught it, and this'
DC CL48'ball was her favorite plaything.'
TSE DC 0C
NTS EQU (TSE-TS)/L'TS
W DC H'36' <-- input width 12<=w<=80
LENS DS H
S DS CL96
LENS1 DS H
S1 DS CL96
LENS2 DS H
S2 DS CL96
OKJ DS X
OKK DS X
OKS2 DS X
CAS DS X
CJ DS CL1
CK DS CL1
PG DS CL80
YREGS
END WORDWRAP

View file

@ -0,0 +1,40 @@
function wordwrap_paragraph(p)
{
if ( length(p) < 1 ) return
split(p, words)
spaceLeft = lineWidth
line = words[1]
delete words[1]
for (i = 1; i <= length(words); i++) {
word = words[i]
if ( (length(word) + 1) > spaceLeft ) {
print line
line = word
spaceLeft = lineWidth - length(word)
} else {
spaceLeft -= length(word) + 1
line = line " " word
}
}
print line
}
BEGIN {
lineWidth = width
par = ""
}
/^[ \t]*$/ {
wordwrap_paragraph(par)
par = ""
}
!/^[ \t]*$/ {
par = par " " $0
}
END {
wordwrap_paragraph(par)
}

View file

@ -0,0 +1,100 @@
CHAR ARRAY text(1000)
CARD length
PROC AppendText(CHAR ARRAY part)
BYTE i
FOR i=1 TO part(0)
DO
text(length)=part(i)
length==+1
OD
RETURN
INT FUNC GetPosForWrap(BYTE lineLen INT start)
INT pos
pos=start+lineLen
IF pos>=length THEN
RETURN (length-1)
FI
WHILE pos>start AND text(pos)#32
DO
pos==-1
OD
IF pos=start THEN
pos=start+lineLen
ELSE
pos==-1
FI
RETURN (pos)
PROC PrintTextWrapped(BYTE lineLen)
INT i,pos
BYTE wrap,screenWidth=[40]
i=0
WHILE i<length
DO
pos=GetPosForWrap(lineLen,i)
IF pos-i=screenWidth-1 OR pos=length-1 THEN
wrap=0
ELSE
wrap=1
FI
WHILE i<=pos
DO
Put(text(i))
i==+1
OD
WHILE i<length AND text(i)=32
DO
i==+1
OD
IF wrap THEN
PutE()
FI
OD
RETURN
PROC Test(BYTE lineLen)
BYTE CH=$02FC
Put(125) ;clear screen
PrintF("Line length=%B%E%E",lineLen)
PrintTextWrapped(lineLen)
PrintF("%E%EPress any key to continue...")
DO UNTIL CH#$FF OD
CH=$FF
RETURN
PROC Main()
BYTE LMARGIN=$52,old
length=0
AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ")
AppendText("Maecenas varius sapien vel purus hendrerit vehicula. ")
AppendText("Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. ")
AppendText("Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. ")
AppendText("Proin blandit lacus vitae nibh tincidunt cursus. ")
AppendText("Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. ")
AppendText("Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. ")
AppendText("Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. ")
AppendText("Nam vel tortor nisi. Sed eget porta tortor. ")
AppendText("Aliquam suscipit lacus vel odio faucibus tempor. ")
AppendText("Sed ipsum est, condimentum eget eleifend ac, ultricies non dui.")
old=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Test(40)
Test(30)
Test(20)
LMARGIN=old ;restore left margin on the screen
RETURN

View file

@ -0,0 +1,18 @@
generic
with procedure Put_Line(Line: String);
package Word_Wrap is
type Basic(Length_Of_Output_Line: Positive) is tagged private;
procedure Push_Word(State: in out Basic; Word: String);
procedure New_Paragraph(State: in out Basic);
procedure Finish(State: in out Basic);
private
type Basic(Length_Of_Output_Line: Positive) is tagged record
Line: String(1 .. Length_Of_Output_Line);
Size: Natural := 0; -- Line(1 .. Size) is relevant
Top_Of_Paragraph: Boolean := True;
end record;
end Word_Wrap;

View file

@ -0,0 +1,36 @@
package body Word_Wrap is
procedure Push_Word(State: in out Basic; Word: String) is
begin
if Word'Length + State.Size >= State.Length_Of_Output_Line then
Put_Line(State.Line(1 .. State.Size));
State.Line(1 .. Word'Length) := Word; -- may raise CE if Word too long
State.Size := Word'Length;
elsif State.Size > 0 then
State.Line(State.Size+1 .. State.Size+1+Word'Length) := ' ' & Word;
State.Size := State.Size + 1 + Word'Length;
else
State.Line(1 .. Word'Length) := Word;
State.Size := Word'Length;
end if;
State.Top_Of_Paragraph := False;
end Push_Word;
procedure New_Paragraph(State: in out Basic) is
begin
Finish(State);
if not State.Top_Of_Paragraph then
Put_Line("");
State.Top_Of_Paragraph := True;
end if;
end New_Paragraph;
procedure Finish(State: in out Basic) is
begin
if State.Size > 0 then
Put_Line(State.Line(1 .. State.Size));
State.Size := 0;
end if;
end Finish;
end Word_Wrap;

View file

@ -0,0 +1,62 @@
with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line;
procedure Wrap is
use Ada.Strings.Unbounded;
Line: Unbounded_String;
Word: Unbounded_String;
function "+"(S: String) return Unbounded_String renames To_Unbounded_String;
function "-"(U: Unbounded_String) return String renames To_String;
package IO renames Ada.Text_IO;
procedure Split(S: Unbounded_String; First, Rest: out Unbounded_String) is
function Skip_Leading_Spaces(S: String) return String is
begin
if S="" then return "";
elsif S(S'First) = ' ' then return S(S'First+1 .. S'Last);
else return S;
end if;
end Skip_Leading_Spaces;
Str: String := Skip_Leading_Spaces(-S);
I: Positive := Str'First;
J: Natural;
begin
-- read nonspaces for First output param
J := I-1;
while J < Str'Last and then Str(J+1) /= ' ' loop
J := J + 1;
end loop;
First := + Str(I .. J);
-- write output param Rest
Rest := + Skip_Leading_Spaces(Str(J+1 .. Str'Last));
end Split;
procedure Print(S: String) is
begin
IO.Put_Line(S);
end Print;
package WW is new Word_Wrap(Print);
Wrapper: WW.Basic(Integer'Value(Ada.Command_Line.Argument(1)));
begin
while not IO.End_Of_File loop
Line := +IO.Get_Line;
if Line = +"" then
Wrapper.New_Paragraph;
Line := +IO.Get_Line;
end if;
while Line /= +"" loop
Split(Line, First => Word, Rest => Line);
Wrapper.Push_Word(-Word);
end loop;
end loop;
Wrapper.Finish;
end Wrap;

View file

@ -0,0 +1,34 @@
on wrapParagraph(para, lineWidth)
if (para is "") then return para
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {space, tab} -- Doesn't include character id 160 (NO-BREAK SPACE).
script o
property wrds : para's text items -- Space- or tab-delimited chunks.
end script
set spaceWidth to (count space) -- ;-)
set spaceLeft to lineWidth
set theLines to {}
set i to 1
repeat with j from 1 to (count o's wrds)
set wordWidth to (count item j of o's wrds)
if (wordWidth + spaceWidth > spaceLeft) then
set end of theLines to text 1 thru (-1 - wordWidth) of (text from text item i to text item j of para)
set i to j
set spaceLeft to lineWidth - wordWidth
else
set spaceLeft to spaceLeft - (wordWidth + spaceWidth)
end if
end repeat
set end of theLines to text from text item i to end of para
set AppleScript's text item delimiters to character id 8232 -- U+2028 (LINE SEPARATOR).
set output to theLines as text
set AppleScript's text item delimiters to astid
return output
end wrapParagraph
local para
set para to "If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia."
return wrapParagraph(para, 70) & (linefeed & linefeed) & wrapParagraph(para, 40)

View file

@ -0,0 +1,9 @@
"If there is a way to do this that is built-in, trivial, or provided
in a standard library, show that. Otherwise implement the minimum
length greedy algorithm from Wikipedia.
If there is a way to do this that is
built-in, trivial, or provided in a
standard library, show that. Otherwise
implement the minimum length greedy
algorithm from Wikipedia."

View file

@ -0,0 +1,32 @@
on wrapParagraph(para, lineWidth)
set theLines to {}
set spaceTab to space & tab
set len to (count para)
set i to 1
repeat until (i > len)
set j to i + lineWidth - 1
if (j < len) then
repeat with j from j to i by -1
if (character j of para is in spaceTab) then exit repeat
end repeat
-- The "greedy" algorithm keeps words which are longer than or
-- the same length as the line width intact. Do the same here.
if (j = i) then
repeat with j from (i + lineWidth) to len
if (character j of para is in spaceTab) then exit repeat
end repeat
end if
else
set j to len
end if
set end of theLines to text i thru j of para
set i to j + 1
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to character id 8232 -- U+2028 (LINE SEPARATOR).
set output to theLines as text
set AppleScript's text item delimiters to astid
return output
end wrapParagraph

View file

@ -0,0 +1,16 @@
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on wrapParagraph(para, lineWidth)
if (para is "") then return para
set str to current application's class "NSMutableString"'s stringWithString:(para)
-- Replace each run of up to (lineWidth - 1) characters followed by a space or a tab,
-- or by the end of the paragraph, with itself and a LINE SEPARATOR character.
tell str to replaceOccurrencesOfString:(".{1," & (lineWidth - 1) & "}(?:[ \\t]|\\Z)") withString:("$0" & character id 8232) ¬
options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})
-- Remove the LINE SEPARATOR inserted at the end.
tell str to replaceOccurrencesOfString:(character id 8232) withString:("") ¬
options:(0) range:({(its |length|()) - 2, 2})
return str as text
end wrapParagraph

View file

@ -0,0 +1,5 @@
txt: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."
print wordwrap txt
print ""
print wordwrap.at:45 txt

View file

@ -0,0 +1,9 @@
MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80)
return
WrapText(Text, LineLength) {
StringReplace, Text, Text, `r`n, %A_Space%, All
while (p := RegExMatch(Text, "(.{1," LineLength "})(\s|\R+|$)", Match, p ? p + StrLen(Match) : 1))
Result .= Match1 ((Match2 = A_Space || Match2 = A_Tab) ? "`n" : Match2)
return, Result
}

View file

@ -0,0 +1,13 @@
paragraph$ = "In olden times when wishing still helped one," \
" there lived a king whose daughters were all beautiful, but" \
" the youngest was so beautiful that the sun itself, which has" \
" 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."
PRINT ALIGN$(paragraph$, 72, 0)
PRINT ALIGN$(paragraph$, 90, 0)

View file

@ -0,0 +1,40 @@
@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!"
rem call the function (the second parameter is the line width)
call :wrap "%input%" 40
echo(
call :wrap "%input%" 70
pause>nul
exit /b 0
:: The procedure
:wrap
set "line="
set "tmp_str=%~1"
set /a "width=%2", "width-=1"
:proc_loop
rem check if we are done already
if "%tmp_str%"=="" (
setlocal enabledelayedexpansion
if defined line echo(!line!
endlocal & goto :EOF
)
rem not yet done, so take a word and process it
for /f "tokens=1,* delims= " %%A in ("%tmp_str%") do (
set "word=%%A"
set "tmp_str=%%B"
setlocal enabledelayedexpansion
if "!line!"=="" (set "testline=!word!") else (set "testline=!line! !word!")
if "!testline:~%width%,1!" == "" (
set "line=!testline!"
) else (
echo(!line!
set "line=!word!"
)
)
endlocal & set "line=%line%"
goto proc_loop

View file

@ -0,0 +1,29 @@
( str
$ ( "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
& ( wrap
= txt length line output q rem
. !arg:(?txt.?length)
& :?output
& whl
' ( @( str$!txt
: ?line
(" " %?lastword [?q " " ?rem&!q:~<!length)
)
& !lastword " " !rem:?txt
& !output !line \n:?output
)
& str$(!output !txt)
)
& out$(str$("72 columns:\n" wrap$(!Text.72)))
& out$(str$("\n80 columns:\n" wrap$(!Text.80)))
);

View file

@ -0,0 +1,44 @@
#include <iostream>
#include <sstream>
#include <string>
const char *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."
};
std::string wrap(const char *text, size_t line_length = 72)
{
std::istringstream words(text);
std::ostringstream wrapped;
std::string word;
if (words >> word) {
wrapped << word;
size_t space_left = line_length - word.length();
while (words >> word) {
if (space_left < word.length() + 1) {
wrapped << '\n' << word;
space_left = line_length - word.length();
} else {
wrapped << ' ' << word;
space_left -= word.length() + 1;
}
}
}
return wrapped.str();
}
int main()
{
std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}

View file

@ -0,0 +1,64 @@
namespace RosettaCode.WordWrap
{
using System;
using System.Collections.Generic;
internal static class Program
{
private const string LoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.";
private static void Main()
{
foreach (var lineWidth in new[] { 72, 80 })
{
Console.WriteLine(new string('-', lineWidth));
Console.WriteLine(Wrap(LoremIpsum, lineWidth));
}
}
private static string Wrap(string text, int lineWidth)
{
return string.Join(string.Empty,
Wrap(
text.Split(new char[0],
StringSplitOptions
.RemoveEmptyEntries),
lineWidth));
}
private static IEnumerable<string> Wrap(IEnumerable<string> words,
int lineWidth)
{
var currentWidth = 0;
foreach (var word in words)
{
if (currentWidth != 0)
{
if (currentWidth + word.Length < lineWidth)
{
currentWidth++;
yield return " ";
}
else
{
currentWidth = 0;
yield return Environment.NewLine;
}
}
currentWidth += word.Length;
yield return word;
}
}
}
}

View file

@ -0,0 +1,179 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* nonsensical hyphens to make greedy wrapping method look bad */
const char *string = "In olden times when wishing still helped one, there lived a king "
"whose daughters were all beautiful, but the youngest was so beautiful "
"that the sun itself, which has seen so much, was astonished whenever "
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "
"forest, and under an old lime-tree in the forest was a well, and when "
"the day was very warm, the king's child went out into the forest and "
"sat down by the side of the cool-fountain, and when she was bored she "
"took a golden ball, and threw it up on high and caught it, and this "
"ball was her favorite plaything.";
/* Each but the last of wrapped lines comes with some penalty as the square
of the diff between line length and desired line length. If the line
is longer than desired length, the penalty is multiplied by 100. This
pretty much prohibits the wrapping routine from going over right margin.
If is ok to exceed the margin just a little, something like 20 or 40 will
do.
Knuth uses a per-paragraph penalty for line-breaking in TeX, which is--
unlike what I have here--probably bug-free.
*/
#define PENALTY_LONG 100
#define PENALTY_SHORT 1
typedef struct word_t {
const char *s;
int len;
} *word;
word make_word_list(const char *s, int *n)
{
int max_n = 0;
word words = 0;
*n = 0;
while (1) {
while (*s && isspace(*s)) s++;
if (!*s) break;
if (*n >= max_n) {
if (!(max_n *= 2)) max_n = 2;
words = realloc(words, max_n * sizeof(*words));
}
words[*n].s = s;
while (*s && !isspace(*s)) s++;
words[*n].len = s - words[*n].s;
(*n) ++;
}
return words;
}
int greedy_wrap(word words, int count, int cols, int *breaks)
{
int score = 0, line, i, j, d;
i = j = line = 0;
while (1) {
if (i == count) {
breaks[j++] = i;
break;
}
if (!line) {
line = words[i++].len;
continue;
}
if (line + words[i].len < cols) {
line += words[i++].len + 1;
continue;
}
breaks[j++] = i;
if (i < count) {
d = cols - line;
if (d > 0) score += PENALTY_SHORT * d * d;
else if (d < 0) score += PENALTY_LONG * d * d;
}
line = 0;
}
breaks[j++] = 0;
return score;
}
/* tries to make right margin more even; pretty sure there's an off-by-one bug
here somewhere */
int balanced_wrap(word words, int count, int cols, int *breaks)
{
int *best = malloc(sizeof(int) * (count + 1));
/* do a greedy wrap to have some baseline score to work with, else
we'll end up with O(2^N) behavior */
int best_score = greedy_wrap(words, count, cols, breaks);
void test_wrap(int line_no, int start, int score) {
int line = 0, current_score = -1, d;
while (start <= count) {
if (line) line ++;
line += words[start++].len;
d = cols - line;
if (start < count || d < 0) {
if (d > 0)
current_score = score + PENALTY_SHORT * d * d;
else
current_score = score + PENALTY_LONG * d * d;
} else {
current_score = score;
}
if (current_score >= best_score) {
if (d <= 0) return;
continue;
}
best[line_no] = start;
test_wrap(line_no + 1, start, current_score);
}
if (current_score >= 0 && current_score < best_score) {
best_score = current_score;
memcpy(breaks, best, sizeof(int) * (line_no));
}
}
test_wrap(0, 0, 0);
free(best);
return best_score;
}
void show_wrap(word list, int count, int *breaks)
{
int i, j;
for (i = j = 0; i < count && breaks[i]; i++) {
while (j < breaks[i]) {
printf("%.*s", list[j].len, list[j].s);
if (j < breaks[i] - 1)
putchar(' ');
j++;
}
if (breaks[i]) putchar('\n');
}
}
int main(void)
{
int len, score, cols;
word list = make_word_list(string, &len);
int *breaks = malloc(sizeof(int) * (len + 1));
cols = 80;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
cols = 32;
score = greedy_wrap(list, len, cols, breaks);
printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
score = balanced_wrap(list, len, cols, breaks);
printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score);
show_wrap(list, len, breaks);
return 0;
}

View file

@ -0,0 +1,48 @@
#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);
}

View file

@ -0,0 +1,13 @@
;; Wrap line naive version
(defn wrap-line [size text]
(loop [left size line [] lines []
words (clojure.string/split text #"\s+")]
(if-let [word (first words)]
(let [wlen (count word)
spacing (if (== left size) "" " ")
alen (+ (count spacing) wlen)]
(if (<= alen left)
(recur (- left alen) (conj line spacing word) lines (next words))
(recur (- size wlen) [word] (conj lines (apply str line)) (next words))))
(when (seq line)
(conj lines (apply str line))))))

View file

@ -0,0 +1,4 @@
;; Wrap line base on regular expression
(defn wrap-line [size text]
(re-seq (re-pattern (str ".{1," size "}\\s|.{1," size "}"))
(clojure.string/replace text #"\n" " ")))

View file

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

View file

@ -0,0 +1,12 @@
(def text "In olden times when wishing still helped one, there lived
a king whose daughters were all beautiful, but the youngest was so
beautiful that the sun itself, which has seen so much, was astonished
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.")
(doseq [line (wrap-line 72 text)]
(println line))

View file

@ -0,0 +1,39 @@
10 rem word wrap - commodore basic
20 rem rosetta code
30 s$="":co=40:gosub 200
35 print chr$(147);chr$(14)
40 print "The current string is:"
41 print chr$(18);s$;chr$(146)
42 print:print "Enter a string, blank to keep previous,"
43 print "or type 'sample' to use a preset"len(z$)" character string."
44 print:input s$:if s$="sample" then s$=z$
45 print:print "enter column limit, 10-80 [";co;"{left}]";:input co
46 if co<12 or co>80 then goto 45
50 print chr$(147);"Wrapping on column";co;"results as:"
55 gosub 400
60 print
65 print r$
70 print
80 input "Again (y/n)";yn$
90 if yn$="y" then goto 35
100 end
200 rem set up sample string
205 data "Lorem Ipsum is typically a corrupted version of 'De finibus "
210 data "bonorum et malorum', a first-century BC text by the Roman statesman "
215 data "and philosopher Cicero, with words altered, added, and removed to "
220 data "make it nonsensical, improper Latin."
225 data "zzz"
230 z$=""
235 read tp$:if tp$<>"zzz" then z$=z$+tp$:goto 235
240 return
400 rem word-wrap string
401 tp$=s$:as$=""
405 if len(tp$)<=co then goto 440
410 for i=0 to co-1:c$=mid$(tp$,co-i,1)
420 if c$<>" " and c$<>"-" then next i
425 ad$=chr$(13):if c$="-" then ad$="-"+chr$(13)
430 as$=as$+left$(tp$,co-1-i)+ad$:tp$=mid$(tp$,co-i+1,len(tp$)):i=0
435 goto 405
440 as$=as$+tp$
450 r$=as$
460 return

View file

@ -0,0 +1,13 @@
;; Greedy wrap line
(defun greedy-wrap (str width)
(setq str (concatenate 'string str " ")) ; add sentinel
(do* ((len (length str))
(lines nil)
(begin-curr-line 0)
(prev-space 0 pos-space)
(pos-space (position #\Space str) (when (< (1+ prev-space) len) (position #\Space str :start (1+ prev-space)))) )
((null pos-space) (progn (push (subseq str begin-curr-line (1- len)) lines) (nreverse lines)) )
(when (> (- pos-space begin-curr-line) width)
(push (subseq str begin-curr-line prev-space) lines)
(setq begin-curr-line (1+ prev-space)) )))

View file

@ -0,0 +1,16 @@
void main() {
immutable 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.";
import std.stdio, std.string;
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}

View file

@ -0,0 +1,35 @@
import std.algorithm;
string wrap(in string text, in int lineWidth) {
auto words = text.splitter;
if (words.empty) return null;
string wrapped = words.front;
words.popFront();
int spaceLeft = lineWidth - wrapped.length;
foreach (word; words)
if (word.length + 1 > spaceLeft) {
wrapped ~= "\n" ~ word;
spaceLeft = lineWidth - word.length;
} else {
wrapped ~= " " ~ word;
spaceLeft -= 1 + word.length;
}
return wrapped;
}
void main() {
immutable 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.";
import std.stdio;
foreach (width; [72, 80])
writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width));
}

View file

@ -0,0 +1,80 @@
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;

View file

@ -0,0 +1,40 @@
let loremIpsum = <[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.]>
func wrap(text, lineWidth) {
String.Concat(values: wrapWords(text.Split('\s', '\r', '\n'), lineWidth))
}
and wrapWords(words, lineWidth) {
var currentWidth = 0
for word in words {
if currentWidth != 0 {
if currentWidth + word.Length() < lineWidth {
currentWidth += 1
yield " "
} else {
currentWidth = 0
yield "\n"
}
}
currentWidth += word.Length()
yield word
}
}
and printWrap(at) {
print("Wrap at \(at):")
print(wrap(loremIpsum, at))
print()
}
printWrap(at: 72)
printWrap(at: 80)

View file

@ -0,0 +1,34 @@
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.

View file

@ -0,0 +1,50 @@
import extensions;
import system'routines;
import extensions'text;
string 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.";
extension wrapOp
{
wrap(int lineWidth)
{
int currentWidth := 0;
^ TokenEnumerator
.new(self)
.selectBy:(word)
{
currentWidth += word.Length;
if (currentWidth > lineWidth)
{
currentWidth := word.Length + 1;
^ newLine + word + " "
}
else
{
currentWidth += 1;
^ word + " "
}
}
.summarize(new StringWriter())
}
}
public program()
{
console.printLine(new StringWriter("-", 72));
console.printLine(text.wrap(72));
console.printLine(new StringWriter("-", 80));
console.printLine(text.wrap(80));
}

View file

@ -0,0 +1,27 @@
defmodule Word_wrap do
def paragraph( string, max_line_length ) do
[word | rest] = String.split( string, ~r/\s+/, trim: true )
lines_assemble( rest, max_line_length, String.length(word), word, [] )
|> Enum.join( "\n" )
end
defp lines_assemble( [], _, _, line, acc ), do: [line | acc] |> Enum.reverse
defp lines_assemble( [word | rest], max, line_length, line, acc ) do
if line_length + 1 + String.length(word) > max do
lines_assemble( rest, max, String.length(word), word, [line | acc] )
else
lines_assemble( rest, max, line_length + 1 + String.length(word), line <> " " <> word, acc )
end
end
end
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.
"""
Enum.each([72, 80], fn len ->
IO.puts String.duplicate("-", len)
IO.puts Word_wrap.paragraph(text, len)
end)

View file

@ -0,0 +1,21 @@
-module( word_wrap ).
-export( [paragraph/2, task/0] ).
paragraph( String, Max_line_length ) ->
Lines = lines( string:tokens(String, " "), Max_line_length ),
string:join( Lines, "\n" ).
task() ->
Paragraph = "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.",
io:fwrite( "~s~n~n", [paragraph(Paragraph, 72)] ),
io:fwrite( "~s~n~n", [paragraph(Paragraph, 80)] ).
lines( [Word | T], Max_line_length ) ->
{Max_line_length, _Length, Last_line, Lines} = lists:foldl( fun lines_assemble/2, {Max_line_length, erlang:length(Word), Word, []}, T ),
lists:reverse( [Last_line | Lines] ).
lines_assemble( Word, {Max, Line_length, Line, Acc} ) when erlang:length(Word) + Line_length > Max -> {Max, erlang:length(Word), Word, [Line | Acc]};
lines_assemble( Word, {Max, Line_length, Line, Acc} ) -> {Max, Line_length + 1 + erlang:length(Word), Line ++ " " ++ Word, Acc}.

View file

@ -0,0 +1,40 @@
open System
let LoremIpsum = "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh."
let Wrap words lineWidth =
let rec loop words currentWidth = seq {
match (words : string list) with
| word :: rest ->
let (stuff, pos) =
if currentWidth > 0 then
if currentWidth + word.Length < lineWidth then
(" ", (currentWidth + 1))
else
("\n", 0)
else ("", 0)
yield stuff + word
yield! loop rest (pos + word.Length)
| _ -> ()
}
loop words 0
[<EntryPoint>]
let main argv =
for n in [72; 80] do
printfn "%s" (String('-', n))
let l = Seq.toList (LoremIpsum.Split((null:char[]), StringSplitOptions.RemoveEmptyEntries))
Wrap l n |> Seq.iter (printf "%s")
printfn ""
0

View file

@ -0,0 +1,12 @@
USE: wrap.strings
IN: scratchpad "Most languages in widespread use today are applicative languages
: the central construct in the language is some form of function call, where a f
unction is applied to a set of parameters, where each parameter is itself the re
sult of a function call, the name of a variable, or a constant. In stack languag
es, a function call is made by simply writing the name of the function; the para
meters are implicit, and they have to already be on the stack when the call is m
ade. The result of the function call (if any) is then left on the stack after th
e function returns, for the next function to consume, and so on. Because functio
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

View file

@ -0,0 +1,26 @@
\ wrap text
\ usage: gforth wrap.f in.txt 72
0. argc @ 1- arg >number 2drop drop constant maxLine
: .wrapped ( buf len -- )
begin
dup maxLine >
while
over maxLine
begin 1- 2dup + c@ bl = until
dup 1+ >r
begin 1- 2dup + c@ bl <> until
1+ type cr
r> /string
repeat type cr ;
: strip-nl ( buf len -- )
bounds do
i c@ 10 = if bl i c! then
loop ;
argc @ 2 - arg slurp-file
2dup strip-nl
.wrapped
bye

View file

@ -0,0 +1,5 @@
CHARACTER*12345 TEXT
...
DO I = 0,120
WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
END DO

View file

@ -0,0 +1,125 @@
MODULE RIVERRUN !Schemes for re-flowing wads of text to a specified line length.
INTEGER BL,BLIMIT,BM !Fingers for the scratchpad.
PARAMETER (BLIMIT = 222) !This should be enough for normal widths.
CHARACTER*(BLIMIT) BUMF !The scratchpad, accumulating text.
INTEGER OUTBUMF !Output unit number.
DATA OUTBUMF/0/ !Thus detect inadequate initialisation.
PRIVATE BL,BLIMIT,BM !These names are not so unusual
PRIVATE BUMF,OUTBUMF !That no other routine will use them.
CONTAINS
INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank.
Concocted yet again by R.N.McLean (whom God preserve) December MM.
Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!
Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces.
Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.
Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.
Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone.
Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only.
Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!
Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.
CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back.
INTEGER L !The length of the bumf.
L = LEN(TEXT) !So, what is it?
1 IF (L.LE.0) GO TO 2 !Are we there yet?
IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also.
L = L - 1 !Step back one.
GO TO 1 !And try again.
2 LSTNB = L !The last non-blank, possibly zero.
RETURN !Unsafe to use LSTNB as a variable.
END FUNCTION LSTNB !Compilers can bungle it.
SUBROUTINE STARTFLOW(OUT,WIDTH) !Preparation.
INTEGER OUT !Output device.
INTEGER WIDTH !Width limit.
OUTBUMF = OUT !Save these
BM = WIDTH !So that they don't have to be specified every time.
IF (BM.GT.BLIMIT) STOP "Too wide!" !Alas, can't show the values BLIMIT and WIDTH.
BL = 0 !No text already waiting in BUMF
END SUBROUTINE STARTFLOW!Simple enough.
SUBROUTINE FLOW(TEXT) !Add to the ongoing BUMF.
CHARACTER*(*) TEXT !The text to append.
INTEGER TL !Its last non-blank.
INTEGER T1,T2 !Fingers to TEXT.
INTEGER L !A length.
IF (OUTBUMF.LT.0) STOP "Call STARTFLOW first!" !Paranoia.
TL = LSTNB(TEXT) !No trailing spaces, please.
IF (TL.LE.0) THEN !A blank (or null) line?
CALL FLUSH !Thus end the paragraph.
RETURN !Perhaps more text will follow, later.
END IF !Curse the (possible) full evaluation of .OR. expressions!
IF (TEXT(1:1).LE." ") CALL FLUSH !This can't be checked above in case LEN(TEXT) = 0.
Chunks of TEXT are to be appended to BUMF.
T1 = 1 !Start at the start, blank or not.
10 IF (BL.GT.0) THEN !If there is text waiting in BUMF,
BL = BL + 1 !Then this latest text is to be appended
BUMF(BL:BL) = " " !After one space.
END IF !So much for the join.
Consider the amount of text to be placed, TEXT(T1:TL)
L = TL - T1 + 1 !Length of text to be placed.
IF (BM - BL .GE. L) THEN !Sufficient space available?
BUMF(BL + 1:BM + L) = TEXT(T1:TL) !Yes. Copy all the remaining text.
BL = BL + L !Advance the finger.
IF (BL .GE. BM - 1) CALL FLUSH !If there is no space for an addendum.
RETURN !Done.
END IF !Otherwise, there is an overhang.
Calculate the available space up to the end of a line. BUMF(BL + 1:BM)
L = BM - BL !The number of characters available in BUMF.
T2 = T1 + L !Finger the first character beyond the take.
IF (TEXT(T2:T2) .LE. " ") GO TO 12 !A splitter character? Happy chance!
T2 = T2 - 1 !Thus the last character of TEXT that could be placed in BUMF.
11 IF (TEXT(T2:T2) .GT. " ") THEN !Are we looking at a space yet?
T2 = T2 - 1 !No. step back one.
IF (T2 .GT. T1) GO TO 11 !And try again, if possible.
IF (L .LE. 6) THEN !No splitter found. For short appendage space,
CALL FLUSH !Starting a new line gives more scope.
GO TO 10 !At the cost of spaces at the end.
END IF !But splitting words is unsavoury too.
T2 = T1 + L - 1 !Alas, no split found.
END IF !So the end-of-line will force a split.
L = T2 - T1 + 1 !The length I settle on.
12 BUMF(BL + 1:BL + L) = TEXT(T1:T1 + L - 1) !I could add a hyphen at the arbitrary chop...
BL = BL + L !The last placed.
CALL FLUSH !The line being full.
Consider what the flushed line didn't take. TEXT(T1 + L:TL)
T1 = T1 + L !Advance to fresh grist.
13 IF (T1.GT.TL) RETURN !Perhaps there is no more. No compound testing, alas.
IF (TEXT(T1:T1).LE." ") THEN !Does a space follow a line split?
T1 = T1 + 1 !Yes. It would appear as a leading space in the output.
GO TO 13 !But the line split stands in for all that.
END IF !So, speed past all such.
IF (T1.LE.TL) GO TO 10!Does anything remain?
RETURN !Nope.
CONTAINS !A convenience.
SUBROUTINE FLUSH !Save on repetition.
IF (BL.GT.0) WRITE (OUTBUMF,"(A)") BUMF(1:BL) !Roll the bumf, if any.
BL = 0 !And be ready for more.
END SUBROUTINE FLUSH !Thus avoid the verbosity of repeated begin ... end blocks.
END SUBROUTINE FLOW !Invoke with one large blob, or, pieces.
END MODULE RIVERRUN !Flush the tail end with a null text.
PROGRAM TEST
USE RIVERRUN
INTEGER MSG,IN
CHARACTER*222 BUMF
MSG = 6
IN = 10
CALL STARTFLOW(MSG,36)
CALL FLOW("Fifteen men on a dead man's chest!")
CALL FLOW(" Yo ho ho and a bottle of rum!")
CALL FLOW("Drink and the devil have done for the rest!")
CALL FLOW(" Yo ho ho and a bottle of rum!")
CALL FLOW("")
WRITE (MSG,*)
Chew into my source file for a second example.
OPEN (IN,FILE="TextFlow.for",ACTION = "READ")
1 READ (IN,2) BUMF
2 FORMAT (A)
IF (BUMF(1:1).NE."C") GO TO 1 !No comment block yet.
CALL STARTFLOW(MSG,66) !Found it!
3 CALL FLOW(BUMF) !Roll its text.
READ (IN,2) BUMF !Grab another line.
IF (BUMF(1:1).EQ."C") GO TO 3 !And if a comment, append.
CALL FLOW("")
CLOSE (IN)
END

View file

@ -0,0 +1,49 @@
Dim Shared As String texto, dividido()
texto = "In olden times when wishing still helped one, there lived a king " &_
"whose daughters were all beautiful, but the youngest was so beautiful "&_
"that the sun itself, which has seen so much, was astonished whenever "&_
"it shone-in-her-face. Close-by-the-king's castle lay a great dark "&_
"forest, and under an old lime-tree in the forest was a well, and when "&_
"the day was very warm, the king's child went out into the forest and "&_
"sat down by the side of the cool-fountain, and when she was bored she "&_
"took a golden ball, and threw it up on high and caught it, and this "&_
"ball was her favorite plaything."
Sub Split(splitArray() As String, subject As String, delimitador As String = " ")
Dim As Integer esteDelim, sgteDelim, toks
Dim As String tok
Redim splitArray(toks)
Do While Strptr(subject)
sgteDelim = Instr(esteDelim + 1, subject, delimitador)
splitArray(toks) = Mid(subject, esteDelim + 1, sgteDelim - esteDelim - 1)
If sgteDelim = FALSE Then Exit Do
toks += 1
Redim Preserve splitArray(toks)
esteDelim = sgteDelim
Loop
End Sub
Sub WordWrap(s As String, n As Integer)
Split(dividido(),s," ")
Dim As String fila = ""
For i As Integer = 0 To Ubound(dividido)
If Len(fila) = 0 Then
fila = fila & dividido(i)
Elseif Len(fila & " " & dividido(i)) <= n Then
fila = fila & " " & dividido(i)
Else
Print fila
fila = dividido(i)
End If
Next i
If Len(fila) > 0 Then Print dividido(Ubound(dividido))
End Sub
Print "Ajustado a 72:"
WordWrap(texto,72)
Print !"\nAjustado a 80:"
WordWrap(texto,80)
Sleep

View file

@ -0,0 +1,43 @@
package main
import (
"fmt"
"strings"
)
func wrap(text string, lineWidth int) (wrapped string) {
words := strings.Fields(text)
if len(words) == 0 {
return
}
wrapped = words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return
}
var 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.`
func main() {
fmt.Println("wrapped at 80:")
fmt.Println(wrap(frog, 80))
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
}

View file

@ -0,0 +1,13 @@
def wordWrap(text, length = 80) {
def sb = new StringBuilder()
def line = ''
text.split(/\s/).each { word ->
if (line.size() + word.size() > length) {
sb.append(line.trim()).append('\n')
line = ''
}
line += " $word"
}
sb.append(line.trim()).toString()
}

View file

@ -0,0 +1,13 @@
def text = """\
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished 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.""".stripIndent().split('\n').join(' ')
println wordWrap(text)
println wordWrap(text, 120)

View file

@ -0,0 +1,6 @@
String wordWrap(str, width=80) {
str.tokenize(' ').inject([[]]) { rows, word ->
if (rows.last().join(' ').length() + word.length() <= width) rows.last() << word else rows << [word]
rows
}.collect { it.join(' ') }.join('\n')
}

View file

@ -0,0 +1,8 @@
import groovy.transform.TailRecursive
import static java.lang.Math.min
@TailRecursive
String wordWrap(str, w, i=w, b=''<<'', len=str.length()-1, x=0) {
b.setCharAt(x = (b << str[b.length()..i]).lastIndexOf(' '), '\n' as char)
b.length()+w >= len ? b << str[i..-1] : wordWrap(str, w, min(x+w+1, len), b, len, 0)
}

View file

@ -0,0 +1,2 @@
def a = new StringBuilder()
def a = '' << ''

View file

@ -0,0 +1,25 @@
ss =
concat
[ "In olden times when wishing still helped one, there lived a king"
, "whose daughters were all beautiful, but the youngest was so beautiful"
, "that the sun itself, which has seen so much, was astonished whenever"
, "it shone in her face. Close by the king's castle lay a great dark"
, "forest, and under an old lime-tree in the forest was a well, and when"
, "the day was very warm, the king's child went out into the forest and"
, "sat down by the side of the cool fountain, and when she was bored she"
, "took a golden ball, and threw it up on high and caught it, and this"
, "ball was her favorite plaything."
]
wordwrap maxlen = wrap_ 0 . words
where
wrap_ _ [] = "\n"
wrap_ pos (w:ws)
-- at line start: put down the word no matter what
| pos == 0 = w ++ wrap_ (pos + lw) ws
| pos + lw + 1 > maxlen = '\n' : wrap_ 0 (w : ws)
| otherwise = ' ' : w ++ wrap_ (pos + lw + 1) ws
where
lw = length w
main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss]

View file

@ -0,0 +1,39 @@
import Data.List (inits, tail, tails)
wWrap :: Int -> String -> String
wWrap n =
unlines
. map unwords
. wWrap'' n
. words
. concat
. lines
wWrap'' :: Int -> [String] -> [[String]]
wWrap'' _ [] = []
wWrap'' n ss =
(\(a, b) -> a : wWrap'' n b) $
last . filter ((<= n) . length . unwords . fst) $
zip (inits ss) (tails ss)
main :: IO ()
main =
putStrLn $
wWrap 80 $
concat
[ "In olden times when wishing still helped one,",
" there lived a king whose daughters were all",
" beautiful, but the youngest was so beautiful",
" that the sun itself, which has seen so much,",
" was astonished whenever, it shone in her",
" face. Close by the king's castle lay a great",
" dark forest, and under an old lime-tree in",
" the forest was a well, and when the day was",
" very warm, the king's child went out into the",
" forest and sat down by the side of the cool",
" fountain, and when she was bored she took a",
" golden ball, and threw it up on high and",
" caught it, and this ball was her favorite",
" plaything."
]

View file

@ -0,0 +1,18 @@
100 TEXT 80
110 CALL WRITE(12,68,0)
120 PRINT :CALL WRITE(10,70,1)
130 DEF WRITE(LEFTMARGIN,RIGHTMARGIN,JUSTIFIED)
140 STRING S$*254
150 RESTORE
160 PRINT TAB(LEFTMARGIN);CHR$(243);
170 PRINT TAB(RIGHTMARGIN-1);CHR$(251)
180 DO
190 READ IF MISSING EXIT DO:S$
200 PRINT S$;
210 LOOP
220 IF JUSTIFIED THEN PRINT CHR$(248) ! <- Extra credit :-)
230 PRINT
240 END DEF
250 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. "
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."

View file

@ -0,0 +1,21 @@
procedure main(A)
ll := integer(A[1]) | 72
wordWrap(&input, ll)
end
procedure wordWrap(f, ll)
every (sep := "", s := "", w := words(f)) do
if w == "\n" then write(1(.s, s := sep := ""),"\n")
else if (*s + *w) >= ll then write(1(.s, s := w, sep := " "))
else (s ||:= .sep||("\n" ~== w), sep := " ")
if *s > 0 then write(s)
end
procedure words(f)
static wc
initial wc := &cset -- ' \t' # Loose definition of a 'word'...
while l := !f do {
l ? while tab(upto(wc)) do suspend tab(many(wc))\1
if *trim(l) = 0 then suspend "\n" # Paragraph boundary
}
end

View file

@ -0,0 +1,4 @@
ww =: 75&$: : wrap
wrap =: (] turn edges) ,&' '
turn =: LF"_`]`[}
edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2

View file

@ -0,0 +1,16 @@
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
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.
20 ww GA NB. Specify different length
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.

View file

@ -0,0 +1,43 @@
package rosettacode;
import java.util.StringTokenizer;
public class WordWrap
{
int defaultLineWidth=80;
int defaultSpaceWidth=1;
void minNumLinesWrap(String text)
{
minNumLinesWrap(text,defaultLineWidth);
}
void minNumLinesWrap(String text,int LineWidth)
{
StringTokenizer st=new StringTokenizer(text);
int SpaceLeft=LineWidth;
int SpaceWidth=defaultSpaceWidth;
while(st.hasMoreTokens())
{
String word=st.nextToken();
if((word.length()+SpaceWidth)>SpaceLeft)
{
System.out.print("\n"+word+" ");
SpaceLeft=LineWidth-word.length();
}
else
{
System.out.print(word+" ");
SpaceLeft-=(word.length()+SpaceWidth);
}
}
}
public static void main(String[] args)
{
WordWrap now=new WordWrap();
String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
System.out.println("DEFAULT:");
now.minNumLinesWrap(wodehouse);
System.out.println("\n\nLINEWIDTH=120");
now.minNumLinesWrap(wodehouse,120);
}
}

View file

@ -0,0 +1,12 @@
function wrap (text, limit) {
if (text.length > limit) {
// find the last space within limit
var edge = text.slice(0, limit).lastIndexOf(' ');
if (edge > 0) {
var line = text.slice(0, edge);
var remainder = text.slice(edge + 1);
return line + '\n' + wrap(remainder, limit);
}
}
return text;
}

View file

@ -0,0 +1 @@
console.log(wrap(text, 80));

View file

@ -0,0 +1 @@
console.log(wrap(text, 42));

View file

@ -0,0 +1,23 @@
(function (width) {
'use strict';
function wrapByRegex(n, s) {
return s.match(
RegExp('.{1,' + n + '}(\\s|$)', 'g')
)
.join('\n');
}
return wrapByRegex(width,
'Even today, with proportional fonts and compl\
ex layouts, there are still cases where you ne\
ed to wrap text at a specified column. The bas\
ic task is to wrap a paragraph of text in a si\
mple way in your language. If there is a way t\
o do this that is built-in, trivial, or provid\
ed in a standard library, show that. Otherwise\
implement the minimum length greedy algorithm\
from Wikipedia.'
)
})(60);

View file

@ -0,0 +1,56 @@
/**
* [wordwrap description]
* @param {[type]} text [description]
* @param {Number} width [description]
* @param {String} br [description]
* @param {Boolean} cut [description]
* @return {[type]} [description]
*/
function wordwrap(text, width = 80, br = '\n', cut = false) {
// Приводим к uint
// 0..2^32-1 либо 0..2^64-1
width >>>= 0;
// Длина текста меньше или равна максимальной
if (0 === width || text.length <= width) {
return text;
}
// Разбиваем текст на строки
return text.split('\n').map(line => {
if (line.length <= width) {
return line;
}
// Разбиваем строку на слова
let words = line.split(' ');
// Если требуется, то обрезаем длинные слова
if (cut) {
let temp = [];
for (const word of words) {
if (word.length > width) {
let i = 0;
const length = word.length;
while (i < length) {
temp.push(word.slice(i, Math.min(i + width, length)));
i += width;
}
} else {
temp.push(word);
}
}
words = temp;
}
// console.log(words);
// Собираем новую строку
let wrapped = words.shift();
let spaceLeft = width - wrapped.length;
for (const word of words) {
if (word.length + 1 > spaceLeft) {
wrapped += br + word;
spaceLeft = width - word.length;
} else {
wrapped += ' ' + word;
spaceLeft -= 1 + word.length;
}
}
return wrapped;
}).join('\n'); // Объединяем элементы массива по LF
}

View file

@ -0,0 +1 @@
console.log(wordwrap("The quick brown fox jumped over the lazy dog.", 20, "<br />\n"));

View file

@ -0,0 +1,14 @@
# Simple greedy algorithm.
# Note: very long words are not truncated.
# input: a string
# output: an array of strings
def wrap_text(width):
reduce splits("\\s+") as $word
([""];
.[length-1] as $current
| ($word|length) as $wl
| (if $current == "" then 0 else 1 end) as $pad
| if $wl + $pad + ($current|length) <= width
then .[-1] += ($pad * " ") + $word
else . + [ $word]
end );

View file

@ -0,0 +1 @@
"aaa bb cc ddddd" | wrap_text(6)[] # wikipedia example

View file

@ -0,0 +1 @@
"aaa bb cc ddddd" | wrap_text(5)[]

View file

@ -0,0 +1,3 @@
советских военных судов и самолетов была отмечена в Японском море после появления там двух американских авианосцев. Не
менее 100 советских самолетов поднялись в воздух, когдаамериканские
авианосцы "Уинсон" и "Мидуэй" приблизились на 50 миль к Владивостоку.

View file

@ -0,0 +1,8 @@
$ jq -M -R -s -r -f Word_wrap.jq Russian.txt
советских военных судов и самолетов была
отмечена в Японском море после появления
там двух американских авианосцев. Не
менее 100 советских самолетов поднялись
в воздух, когдаамериканские авианосцы
"Уинсон" и "Мидуэй" приблизились на 50
миль к Владивостоку.

View file

@ -0,0 +1,12 @@
using TextWrap
text = """Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour."""
println("# Wrapped at 80 chars")
print_wrapped(text, width=80)
println("\n\n# Wrapped at 70 chars")
print_wrapped(text, width=70)

View file

@ -0,0 +1,28 @@
:wordwrap %long !long
%ps 0 !ps
split
len [ drop
pop swap len $ps + !ps
$ps $long > [ len !ps nl ] if
print " " print
$ps 1 + !ps
] for
drop
;
"tlhIngan Hol jatlhwI', pIvan. ghomuv! nItebHa' mu'ghomvam wIchenmoHlaH. boQchugh Hoch, mu'ghom Dun mojlaH.
tlhIngan maH! Qapla'! DaH tlhIngan Hol mu'ghom'a' Dalegh. qawHaqvam chenmoHlu'DI' 'oHvaD wIqIpe'DIya ponglu'.
'ach jInmolvamvaD Saghbe'law' tlhIngan Hol, DIS 2005 'oH mevmoHlu'. 'ach DIS 2006 jar wa'maHcha'DIch Wikia jInmolDaq vIHta'.
Hov lengvaD chenmoHlu' tlhIngan Hol'e' 'ej DaH 'oH ghojtaH ghot law'. Qapbej Holvam wIcha'meH, qawHaqvam chenmoHlu'.
taHjaj wo', taHjaj Hol! Sov qawHaq tlhab 'oH 'ej ghItlhmey DIqonmeH tlhIngan Hol wIlo'. ghItlhmey chenmoHlaH 'ej choHlaH tlhIngan Hol
jatlhlaHbogh Hoch ghotpu''e'. wej tIn Sov qawHaqvam, 'ach ghurlI' 'e' wItul. DaH 229 ghItlhmey ngaS.
vay' Daghel DaneHchugh qoj vay' Dachup DaneHchugh, vaj tachDaq maghom."
dup
72 wordwrap nl nl
100 wordwrap nl nl
"End " input

View file

@ -0,0 +1,37 @@
// version 1.1.3
val 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."
fun greedyWordwrap(text: String, lineWidth: Int): String {
val words = text.split(' ')
val sb = StringBuilder(words[0])
var spaceLeft = lineWidth - words[0].length
for (word in words.drop(1)) {
val len = word.length
if (len + 1 > spaceLeft) {
sb.append("\n").append(word)
spaceLeft = lineWidth - len
}
else {
sb.append(" ").append(word)
spaceLeft -= (len + 1)
}
}
return sb.toString()
}
fun main(args: Array<String>) {
println("Greedy algorithm - wrapped at 72:")
println(greedyWordwrap(text, 72))
println("\nGreedy algorithm - wrapped at 80:")
println(greedyWordwrap(text, 80))
}

View file

@ -0,0 +1,25 @@
(defun wrap-text (text)
(wrap-text text 78))
(defun wrap-text (text max-len)
(string:join
(make-wrapped-lines
(string:tokens text " ") max-len)
"\n"))
(defun make-wrapped-lines
(((cons word rest) max-len)
(let ((`#(,_ ,_ ,last-line ,lines) (assemble-lines max-len word rest)))
(lists:reverse (cons last-line lines)))))
(defun assemble-lines (max-len word rest)
(lists:foldl
#'assemble-line/2
`#(,max-len ,(length word) ,word ())
rest))
(defun assemble-line
((word `#(,max ,line-len ,line ,acc)) (when (> (+ (length word) line-len) max))
`#(,max ,(length word) ,word ,(cons line acc)))
((word `#(,max ,line-len ,line ,acc))
`#(,max ,(+ line-len 1 (length word)) ,(++ line " " word) ,acc)))

View file

@ -0,0 +1,9 @@
(defun make-regex-str (max-len)
(++ "(.{1," (integer_to_list max-len) "}|\\S{"
(integer_to_list (+ max-len 1)) ",})(?:\\s[^\\S\\r\\n]*|\\Z)"))
(defun wrap-text (text max-len)
(let ((find-patt (make-regex-str max-len))
(replace-patt "\\1\\\n"))
(re:replace text find-patt replace-patt
'(global #(return list)))))

View file

@ -0,0 +1,4 @@
> (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))

View file

@ -0,0 +1 @@
> (io:format (wrap-text text 50))

View file

@ -0,0 +1,3 @@
{def text
Personne na 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 quil 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 jusquau quarantième parallèle sud ! (Lîle mystérieuse / Jules Verne)}
-> text

View file

@ -0,0 +1,16 @@
{def wrap1
{lambda {:n}
pre {@ style="width::npx; // the line width in pixels
white-space:pre-wrap; "}}} // the word-wrap rule
-> wrap1
{{wrap1 500} {text}}
->
Personne na 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
quil 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 jusquau
quarantième parallèle sud ! (Lîle mystérieuse / Jules Verne)

View file

@ -0,0 +1,39 @@
{def wrap2 // the function's name
{def wrap2.r // recursive "loop"
{lambda {:linewidth :a1 :spaceleft :a2}
{if {A.empty? :a1} // it's the end so ...
then {A.toS :a2} // ... return the sentence
else {let { {:linewidth :linewidth} // local variables
{:spaceleft :spaceleft} // lambdatalk has no closure
{:a1 :a1} // so we recall outers values
{:a2 :a2} // ... manually
{:word {A.first :a1}} // get the first word
{:length {W.length {A.first :a1}}} // compute its length
} {wrap2.r // do it again with
:linewidth // the linewidth unchanged
{A.rest :a1} // the rest of array
{if {> {+ :length 1} :spaceleft} // if ...
then {- :linewidth :length} // then update spaceleft and
{A.addlast! {br}:word :a2} // push a breakline and the word
else {- :spaceleft {+ :length 1}} // else update spaceleft and
{A.addlast! :word :a2}} }}}}} // push the word
{lambda {:linewidth :text} // a function with 2 arguments
{wrap2.r :linewidth // call the recursive "loop"
{A.rest {A.new :text}} // the input as an array minus first word
{- :linewidth {W.length {S.get 0 :text}}} // compute spaceleft
{A.new {S.get 0 :text}}}}} // the output as an array plus first word
-> wrap2
{wrap2 70 {text}} ->
Personne na 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 quil 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
jusquau quarantième parallèle sud ! (Lîle mystérieuse /
Jules Verne)

View file

@ -0,0 +1,29 @@
LAMBDATALK.DICT['jswrap'] = function() {
var wrap = function(text, limit) {
if (text.length > limit) {
var edge = text.slice(0, limit).lastIndexOf(' ');
if (edge > 0) {
var line = text.slice(0, edge);
var remainder = text.slice(edge + 1);
return line + '\n' + wrap(remainder, limit);
}
}
return text;
};
var args = arguments[0].trim().split(" ");
var limit = parseInt(args.shift());
var text = args.join(" ");
return wrap(text,limit);
};
{jswrap 60 {text}} ->
Personne na 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 quil 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 jusquau quarantième parallèle sud ! (Lîle
mystérieuse / Jules Verne)

View file

@ -0,0 +1,14 @@
define wordwrap(
text::string,
row_length::integer = 75
) => {
return regexp(`(?is)(.{1,` + #row_length + `})(?:$|\W)+`, '$1<br />\n', #text, true) -> replaceall
}
local(text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat ornare lectus, dignissim iaculis libero consequat sed. Proin quis magna in arcu sagittis consequat sed ac risus. Ut a pharetra dui. Phasellus molestie, mauris eget scelerisque laoreet, diam dolor vulputate nulla, in porta sem sem sit amet lacus.')
wordwrap(#text, 40)
'<hr />'
wordwrap(#text)
'<hr />'
wordwrap(#text, 90)

View file

@ -0,0 +1,42 @@
-- in some movie script
----------------------------------------
-- Wraps specified text into lines of specified width (in px), returns lines as list of strings
-- @param {string} str
-- @param {integer} pixelWidth
-- @param {propList} [style]
-- @return {list}
----------------------------------------
on hardWrapText (str, pixelWidth, style)
if voidP(style) then style = [:]
lines = []
-- create a new field member
m = new(#field)
m.text = str
m.rect = rect(0,0,pixelWidth,0)
-- assign style props (if not specified, defaults are used)
repeat with i = 1 to style.count
m.setProp(style.getPropAt(i), style[i])
end repeat
-- create an invisible temporary sprite
s = channel(1).makeScriptedSprite(m)
s.loc = point(0,0)
s.visible = false
_movie.updateStage()
-- get the wrapped lines
charPos = 0
repeat with y = 0 to s.height-1
n = s.pointToChar(point(pixelWidth-1, y))
if n<>charPos then
lines.add(str.char[charPos+1..n])
charPos = n
end if
end repeat
channel(1).removeScriptedSprite()
return lines
end

View file

@ -0,0 +1,12 @@
str = "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed "&\
"eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim "&\
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi "&\
"consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu "&\
"fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in "&\
"culpa qui officia deserunt mollit anim id est laborum."
lines = hardWrapText(str, 320, [#font: "Arial", #fontSize:24])
repeat with l in lines
put l
end repeat

View file

@ -0,0 +1,45 @@
function splittokens(s)
local res = {}
for w in s:gmatch("%S+") do
res[#res+1] = w
end
return res
end
function textwrap(text, linewidth)
if not linewidth then
linewidth = 75
end
local spaceleft = linewidth
local res = {}
local line = {}
for _, word in ipairs(splittokens(text)) do
if #word + 1 > spaceleft then
table.insert(res, table.concat(line, ' '))
line = {word}
spaceleft = linewidth - #word
else
table.insert(line, word)
spaceleft = spaceleft - (#word + 1)
end
end
table.insert(res, table.concat(line, ' '))
return table.concat(res, '\n')
end
local example1 = [[
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.
]]
print(textwrap(example1))
print()
print(textwrap(example1, 60))

View file

@ -0,0 +1,81 @@
Module Checkit {
\\ leading space from begin of paragraph stay as is
a$={ 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.
}
const crlf$=chr$(13)+chr$(10)
a$=replace$(crlf$, " ", a$)+crlf$
const justify=0
const flushright=1
const centered=2
const flushleft=3
\\ set layer font
Font "Tahoma"
Form 80, 50
Print "Font:";Fontname$
Print "Font size:";Mode;"pt"
Print "Bold:";Bold
Print "Italic:";Italic
\\ set left margin for Report
Cursor 10, 8 ' pos 10 row 8 (11 9 - it is 0 based)
m=Italic
Italic 1
Report centered, trim$(A$), Width-10-10
Italic m
Print @(0,79),"Press any key";
wait$=key$
Refresh 5000
charwidth=scale.x div width
For i=2000 to scale.x-charwidth step 150
\\ clear screen with 14pt fonts
Mode 12.75
\\ by default use justify, word wrap
Report a$, i
\\ we can calculate only using a negative parameter
Report a$, i, -10000
k=ReportLines
\\ print any line in differnet color
Dim a(2)
a(0)=11, 15 ' 0 to 15 are vb6 colors, we can use html colors #aabbcc, #ff2211
For j=1 to k {
Pen a(j mod 2) {
Report a$, i, 1 line j
}
}
Refresh 5000
wait$=key$
Next i
Report a$, scale.x/2, -1000
k=ReportLines
Document Doc$
Report a$, scale.x/2, k as Doc$
\\ Print document without expanding spaces
Print $(4), ' 4=proportional printing using columns, on line online, word wrap, expand to fit in columns
For i=1 to k {
Print "*";Paragraph$(Doc$, i);"*"
}
Print $(0), ' restore to non proportional printing
For i=1 to k {
Print i, size.x(Paragraph$(Doc$, i), Fontname$, Mode), size.y(Paragraph$(Doc$, i), Fontname$, Mode)
}
\\ scale.x unit in twips
Report a$, scale.x/2
\\ width unit in characters
Report a$, width/2
Print @(width div 2),
Report flushright, a$, width/2
Cursor 0, Row
I=Italic
Double
Italic 1
Report centered, a$
Italic I
Double
Normal
}
Checkit

View file

@ -0,0 +1,27 @@
string="In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything.";
wordWrap[textWidth_,spaceWidth_,string_]:=Module[{start,spaceLeft,masterString},
spaceLeft=textWidth;
start=1;
masterString={};
Do[
If[i+1>Length@StringSplit@string
,
p=StringSplit[string][[start;;i]];
AppendTo[masterString,{StringJoin@@Riffle[p,StringJoin@ConstantArray[" ",spaceWidth]]}]
,
If[StringLength[StringSplit@string][[i+1]]+spaceWidth>spaceLeft
,
spaceLeft=textWidth-StringLength[StringSplit@string][[i]];
start=i;
AppendTo[masterString,{StringJoin@@Riffle[p,StringJoin@ConstantArray[" ",spaceWidth]]}]
,
spaceLeft-=StringLength[StringSplit@string][[i]];
spaceLeft-=spaceWidth;
p=StringSplit[string][[start;;i]]
]
]
,
{i,1,Length@StringSplit@string}
];
StringJoin@@Riffle[masterString,"\n"]
];

View file

@ -0,0 +1,2 @@
wordWrap[72, 1, string]
wordWrap[80, 1, string]

View file

@ -0,0 +1,16 @@
str = "one two three four five six seven eight nine ten eleven!"
width = 15
words = str.split
pos = 0
line = ""
for word in words
pos = pos + word.len + 1
if pos <= width then
line = line + word + " "
else
print line[:-1]
line = word + " "
pos = word.len
end if
end for
print line[:-1]

View file

@ -0,0 +1,76 @@
/* NetRexx */
options replace format comments java crossref symbols
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
@see http://en.wikipedia.org/wiki/Word_wrap#Minimum_length
SpaceLeft := LineWidth
for each Word in Text
if (Width(Word) + SpaceWidth) > SpaceLeft
insert line break before Word in Text
SpaceLeft := LineWidth - Width(Word)
else
SpaceLeft := SpaceLeft - (Width(Word) + SpaceWidth)
*/
method wordWrap(text, lineWidth = 80) public static
if lineWidth > 0 then do
NL = '\n'
SP = ' '
wrapped = ''
spaceWidth = SP.length()
spaceLeft = lineWidth
loop w_ = 1 to text.words()
nextWord = text.word(w_)
if (nextWord.length() + spaceWidth) > spaceLeft then do
wrapped = wrapped || NL || nextWord
spaceLeft = lineWidth - nextWord.length()
end
else do
wrapped = wrapped || SP || nextWord
spaceLeft = spaceLeft - (nextWord.length() + spaceWidth)
end
end w_
end
else do
wrapped = text
end
return wrapped.strip() -- clean w/s from front & back
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
parse arg lineLen .
if lineLen = '' then lineLen = 80
text = getText()
wrappedLines = wordWrap(text, lineLen)
say 'Wrapping text at' lineLen 'characters'
say ('....+....|'.copies((lineLen + 9) % 10)).left(lineLen)
say wrappedLines
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getText() public static
-- ....+....|....+....|....+....|....+....|....+....|....+....|
speech01 = -
'She should have died hereafter;' -
'There would have been a time for such a word.' -
'Tomorrow, and tomorrow, and tomorrow,' -
'Creeps in this petty pace from day to day,' -
'To the last syllable of recorded time;' -
'And all our yesterdays have lighted fools' -
'The way to dusty death. Out, out, brief candle!' -
'Life''s but a walking shadow, a poor player' -
'That struts and frets his hour upon the stage' -
'And then is heard no more. It is a tale' -
'Told by an idiot, full of sound and fury' -
'Signifying nothing.' -
'' -
'—-Macbeth (Act 5, Scene 5, lines 17-28)' -
''
return speech01

View file

@ -0,0 +1,28 @@
/* NetRexx ************************************************************
* 23.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
options replace format comments java crossref symbols
runSample(arg)
method runSample(arg) public static
s='She should have died hereafter;' -
'There would have been a time for such a word.' -
'Tomorrow, and tomorrow, and tomorrow, and so on'
w=72
Say s.length
loop while s>' '
Loop i=w+1 to 1 by -1
If s.substr(i,1)='' Then
Leave
End
If i=0 Then
p=s.pos(' ')
Else
p=i
say s.left(p)
s=s.substr(p+1)
End
If s>'' Then
say s
return

View file

@ -0,0 +1,6 @@
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."
echo txt.wrapWords()
echo ""
echo txt.wrapWords(45)

View file

@ -0,0 +1,33 @@
#load "str.cma"
let txt = "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."
let () =
let line_width = int_of_string Sys.argv.(1) in
let words = Str.split (Str.regexp "[ \n]+") txt in
let buf = Buffer.create 10 in
let _ =
List.fold_left (fun (width, sep) word ->
let wlen = String.length word in
let len = width + wlen + 1 in
if len > line_width then
begin
Buffer.add_char buf '\n';
Buffer.add_string buf word;
(wlen, " ")
end else begin
Buffer.add_string buf sep;
Buffer.add_string buf word;
(len, " ")
end
) (0, "") words
in
print_endline (Buffer.contents buf)

View file

@ -0,0 +1,35 @@
(define (get-one-word start)
(let loop ((chars #null) (end start))
(let ((char (car end)))
(if (has? (list #\space #\newline) char)
(values (reverse chars) (force (cdr end)))
(loop (cons char chars) (force (cdr end)))))))
(define (get-all-words string)
(let loop ((words #null) (start (str-iter string)))
(let* ((word next (get-one-word start)))
(if (null? next)
(reverse words)
(loop (cons (runes->string word) words) next)))))
(define (get-one-line words n)
(let loop ((line #null) (words words) (i 0))
(let*((word (car words))
(len (string-length word)))
(if (null? (cdr words))
(values (reverse (cons word line)) #null)
(if (> (+ i len) n 1)
(values (reverse line) words)
(loop (cons word line) (cdr words) (+ i len 1)))))))
(define (get-all-lines words n)
(let loop ((lines #null) (words words))
(let* ((line words (get-one-line words n)))
(if (null? words)
(reverse (cons line lines))
(loop (cons line lines) words)))))
(define (hyphenation width string)
(let*((words (get-all-words string))
(lines (get-all-lines words width)))
lines))

View file

@ -0,0 +1,26 @@
wrap(s,len)={
my(t="",cur);
s=Vec(s);
for(i=1,#s,
if(s[i]==" ",
if(cur>#t,
print1(" "t);
cur-=#t+1
,
print1("\n"t);
cur=len-#t
);
t=""
,
t=concat(t,s[i])
)
);
if(cur>#t,
print1(" "t)
,
print1("\n"t)
)
};
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)

View file

@ -0,0 +1,30 @@
<?php
$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day
So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life
Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;
// remove preexisting line breaks
$text = str_replace( PHP_EOL, " " , $text );
echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;

View file

@ -0,0 +1,32 @@
*process source attributes xref or(!);
ww: proc Options(main);
/*********************************************************************
* 21.08-2013 Walter Pachl derived from REXX version 2
*********************************************************************/
Dcl in record input;
Dcl out record output;
On Endfile(in) z=' ';
Dcl z char(32767) Var;
Dcl s char(32767) Var Init('');
dcl o Char(200) Var;
Dcl (i,w,p) Bin Fixed(31) Init(0);
w=72;
Read File(in) Into(z);
s=z;
Do Until(s='');
Do i=w+1 to 1 by -1;
If substr(s,i,1)='' Then Leave;
End;
If i=0 Then
p=index(s,' ');
Else
p=i;
o=left(s,p);
Write file(out) From(o);
s=substr(s,p+1);
If length(s)<200 Then Do;
Read File(in) Into(z);
s=s!!z;
End;
End;
End;

View file

@ -0,0 +1,18 @@
my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
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.";
$s =~ s/\b\s+/ /g;
$s =~ s/\s*$/\n\n/;
my $_ = $s;
s/\s*(.{1,66})\s/$1\n/g, print;
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print;

View file

@ -0,0 +1,27 @@
(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
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."""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">word_wrap</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">maxwidth</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">words</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxwidth</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">word</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">line</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">word</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</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>
<!--

View file

@ -0,0 +1,25 @@
include ..\Utilitys.pmt
72 var long
0 >ps
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh."
split
len for drop
pop swap len ps> + >ps
tps long > if ps> drop len >ps nl endif
print " " print
ps> 1 + >ps
endfor
drop ps> drop

View file

@ -0,0 +1,34 @@
import util.
go =>
text(1,Text),
foreach(LineWidth in [60,80])
println(lineWidth=LineWidth),
println(wrap(Text,LineWidth)),
nl
end,
nl.
wrap(Text,LineWidth) = Wrapped =>
Words = Text.split(),
Wrapped = Words[1],
SpaceLeft = LineWidth - Wrapped.len,
foreach(Word in Words.tail)
WordLen = Word.length,
if (WordLen + 1) > SpaceLeft then
Wrapped := Wrapped ++ "\n" ++ Word,
SpaceLeft := LineWidth - WordLen
else
Wrapped := Wrapped ++ " " ++ Word,
SpaceLeft := SpaceLeft - WordLen - 1
end
end.
text(1,"Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.").

View file

@ -0,0 +1,6 @@
: (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog")))
The quick
brown fox
jumps over
the lazy dog
-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog"

View file

@ -0,0 +1,29 @@
function wrap{
$divide=$args[0] -split " "
$width=$args[1]
$spaceleft=$width
foreach($word in $divide){
if($word.length+1 -gt $spaceleft){
$output+="`n$word "
$spaceleft=$width-($word.length+1)
} else {
$output+="$word "
$spaceleft-=$word.length+1
}
}
return "$output`n"
}
### The Main Thing...
$paragraph="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."
"`nLine width:30`n"
wrap $paragraph 30
"========================================================="
"Line width:100`n"
wrap $paragraph 100
### End script

View file

@ -0,0 +1,52 @@
function Out-WordWrap
{
[CmdletBinding()]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[string]
$Text,
[Parameter(Mandatory=$false,
Position=1)]
[ValidateRange(16,160)]
[int]
$Width = 80
)
Begin
{
function New-WordWrap ([string]$Text, [int]$Width)
{
[string[]]$words = $Text.Split()
[string]$output = ""
[int]$remaining = $Width
foreach ($word in $words)
{
if($word.Length + 1 -gt $remaining)
{
$output += "`n$word "
$remaining = $Width - ($word.Length + 1)
}
else
{
$output += "$word "
$remaining -= $word.Length + 1
}
}
return "$output`n"
}
}
Process
{
foreach ($paragraph in $Text)
{
New-WordWrap -Text $paragraph -Width $Width
}
}
}

Some files were not shown because too many files have changed in this diff Show more