1 -- random code from http://lua-users.org/wiki/TextJustification
2 -- easy queue implementation ------------------------------------------
11 function q_insert(q, s)
17 return q.first >= q.last
31 return q.last - q.first
34 function q_length(q, f)
35 local l, i = 0, q.first
43 -- line creation routines ------------------------------------------
45 -- justifies one line to fit into MAX columns
47 local blanks = MAX - q_length(q)
48 local skips = q_card(q) - 1
49 local line = q_remove(q)
50 local quotient = floor(blanks/skips)
51 local reminder = blanks/skips - quotient
54 error = error + reminder
57 line = line .. strrep(" ", quotient+1)
59 line = line .. strrep(" ", quotient)
61 line = line .. q_remove(q)
67 -- join all words with one space between them
69 local line = q_remove(q)
70 while not q_empty(q) do
71 line = line .. " " .. q_remove(q)
76 -- main program -----------------------------------------------------
78 -- tries to get MAX from command-line
79 if not arg or getn(arg) < 1 then
82 MAX = tonumber(arg[1])
83 if not MAX or MAX < 0 then
88 -- collects all text from stdin
92 _, n = gsub(line, "(%S+)", function (s) q_insert(%text, s) end)
101 word = q_remove(text)
105 if not q_empty(line) then
106 write(catenate(line), "\n\n")
111 elseif size + strlen(word) > MAX then
112 write(justify(line), "\n")
117 size = size + strlen(word) + 1
119 word = q_remove(text)
121 write(catenate(line), "\n")