> Really, write a stored procedure that accepts (text, line_length) and
> returns SETOF text. You could even add hyphenation for the appropriate
> language if you go that route. For the latter it's probably best to write
> it in C so you can link hyphenation libraries to your code.
>
> Another approach that may be viable is to use windowing functions, but I'm
> not so sure it's possible to have a window that is being defined by the
> data it's running over (eg. a window defined by the length of an
> accumulated line of text).
Implementations from http://sqlserverpedia.com/wiki/Word_Wrap_a_String
and from http://docstore.mik.ua/orelly/oracle/prog2/ch11_02.htm#AUTOID-10508
paragraph 11.2.2 did not work in Postgres.
I created method below. Is this best code for this ?
Andrus.
CREATE OR REPLACE FUNCTION wordwrap(line text, linelen integer)
RETURNS SETOF text as $$
DECLARE
words text[] := string_to_array(line,' ');
i integer;
res text:='';
BEGIN
if trim(line)='' then
return next '';
return;
end if;
for i IN 1 .. array_upper(words,1) LOOP
if length(res)+length(words[i]) > linelen THEN
return next res;
res := '';
END IF ;
if res<>'' then
res := res || ' ';
end if;
res := res || words[i];
end loop;
return next res;
END
$$ LANGUAGE plpgsql;