PICO-8 Text Editor with Effects, #12

Word wrap is finally working! :DDD I still need to define the behavior of words at the end of space-only lines, but the main use case is working perfectly.

Here’s the new word wrap function:

function _draw()
 local cx, cy = l_margin, t_margin
 local i=1
 local line_breaks={}
 local last_space=0
 local line_width=l_margin
 local width_since_space=0
 cls(7)

 -- find line breaks
 for k=1,#text do
  char = text[k]
  if char.sym == " " then
   last_space = k
   width_since_space = 0
  end
  if not char.control then
   line_width += char.width
   width_since_space += char.width
  else
   line_width=l_margin
  end
  if line_width >= r_margin then
   if last_space != 0 then
    add(line_breaks, last_space)
    line_width = l_margin + width_since_space
   else
    add(line_breaks, k - 1)
    line_width = l_margin
   end
   last_space = 0
  end
 end
 -- draw the text
 while i <= #text do
  c = text[i]
  if i == cr.x then
   rectfill(cx, cy, cx+c.width, cy+4, 8)
  end
  if not c.control then
   print(c.sym, cx, cy, c.c)
   cx += c.width
   if #line_breaks>0 and i==line_breaks[1] then
    cx = l_margin
    cy += line_spacing
    deli(line_breaks, 1)
   end
  else
   if c.sym == "r" then
    cx = l_margin
    cy += line_spacing
   end
  end
  i += 1
 end
 if cr.x > #text and cr.on then
  rectfill(cx, cy, cx+4, cy+4, 8)
 end
end

It loops through the text twice: once to find the line breaks and again to draw the characters. The first loop adds the characters’ widths until the current line width is greater than the right margin. Then it resets the line width and adds a line break at the last found space or the current index, depending on whether it found a space. The second loop just draws the text using the line breaks from the first loop. It’s not optimized or efficient, but at least it works.

Leave a comment

Your email address will not be published. Required fields are marked *


Your data is processed in accordance with my privacy policy. Comments are manually approved and may take a while to appear.