about summary refs log blame commit diff stats
path: root/020run.cc
blob: 60a5c1161f8b7babaa36f84da28252fdc249c171 (plain) (tree)
ac0e9db5 pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
-- text editor, particularly text drawing, horizontal wrap, vertical scrolling
Text = {}

require 'search'
require 'select'
require 'undo'
require 'text_tests'

-- draw a line starting from startpos to screen at y between State.left and State.right
-- return the final y, and position of start of final screen line drawn
function Text.draw(State, line_index, y, startpos)
  App.color(Text_color)
  local line = State.lines[line_index]
  local line_cache = State.line_cache[line_index]
  line_cache.starty = y
  line_cache.startpos = startpos
  -- wrap long lines
  local x = State.left
  local pos = 1
  local screen_line_starting_pos = startpos
  Text.compute_fragments(State, line_index)
  for _, f in ipairs(line_cache.fragments) do
    local frag, frag_text = f.data, f.text
    local frag_len = utf8.len(frag)
--?     print('text.draw:', frag, 'at', line_index,pos, 'after', x,y)
    if pos < startpos then
      -- render nothing
--?       print('skipping', frag)
    else
      -- render fragment
      local frag_width = App.width(frag_text)
      if x + frag_width > State.right then
        assert(x > State.left)  -- no overfull lines
        y = y + State.line_height
        if y + State.line_height > App.screen.height then
          return y, screen_line_starting_pos
        end
        screen_line_starting_pos = pos
        x = State.left
      end
      if State.selection1.line then
        local lo, hi = Text.clip_selection(State, line_index, pos, pos+frag_len)
        Text.draw_highlight(State, line, x,y, pos, lo,hi)
      end
      App.screen.draw(frag_text, x,y)
      -- render cursor if necessary
      if line_index == State.cursor1.line then
        if pos <= State.cursor1.pos and pos + frag_len > State.cursor1.pos then
          if State.search_term then
            if State.lines[State.cursor1.line].data:sub(State.cursor1.pos, State.cursor1.pos+utf8.len(State.search_term)-1) == State.search_term then
              local lo_px = Text.draw_highlight(State, line, x,y, pos, State.cursor1.pos, State.cursor1.pos+utf8.len(State.search_term))
              App.color(Text_color)
              love.graphics.print(State.search_term, x+lo_px,y)
            end
          else
            Text.draw_cursor(State, x+Text.x(frag, State.cursor1.pos-pos+1), y)
          end
        end
      end
      x = x + frag_width
    end
    pos = pos + frag_len
  end
  if State.search_term == nil then
    if line_index == State.cursor1.line and State.cursor1.pos == pos then
      Text.draw_cursor(State, x, y)
    end
  end
  return y, screen_line_starting_pos
end

function Text.draw_cursor(State, x, y)
  -- blink every 0.5s
  if math.floor(Cursor_time*2)%2 == 0 then
    App.color(Cursor_color)
    love.graphics.rectangle('fill', x,y, 3,State.line_height)
    App.color(Text_color)
  end
  State.cursor_x = x
  State.cursor_y = y+State.line_height
end

function Text.populate_screen_line_starting_pos(State, line_index)
  local line = State.lines[line_index]
  if line.mode ~= 'text' then return end
  local line_cache = State.line_cache[line_index]
  if line_cache.screen_line_starting_pos then
    return
  end
  -- duplicate some logic from Text.draw
  Text.compute_fragments(State, line_index)
  line_cache.screen_line_starting_pos = {1}
  local x = State.left
  local pos = 1
  for _, f in ipairs(line_cache.fragments) do
    local frag, frag_text = f.data, f.text
    -- render fragment
    local frag_width = App.width(frag_text)
    if x + frag_width > State.right then
      x = State.left
      table.insert(line_cache.screen_line_starting_pos, pos)
    end
    x = x + frag_width
    local frag_len = utf8.len(frag)
    pos = pos + frag_len
  end
end

function Text.compute_fragments(State, line_index)
--?   print('compute_fragments', line_index, 'between', State.left, State.right)
  local line = State.lines[line_index]
  if line.mode ~= 'text' then return end
  local line_cache = State.line_cache[line_index]
  if line_cache.fragments then
    return
  end
  line_cache.fragments = {}
  local x = State.left
  -- try to wrap at word boundaries
  for frag in line.data:gmatch('%S*%s*') do
    local frag_text = App.newText(love.graphics.getFont(), frag)
    local frag_width = App.width(frag_text)
--?     print('x: '..tostring(x)..'; '..tostring(State.right-x)..'px to go')
    while x + frag_width > State.right do
--?       print(('checking whether to split fragment ^%s$ of width %d when rendering from %d'):format(frag, frag_width, x))
      if (x-State.left) < 0.8 * (State.right-State.left) then
--?         print('splitting')
        -- long word; chop it at some letter
        -- We're not going to reimplement TeX here.
        local bpos = Text.nearest_pos_less_than(frag, State.right - x)
--?         print('bpos', bpos)
        if bpos == 0 then break end  -- avoid infinite loop when window is too narrow
        local boffset = Text.offset(frag, bpos+1)  -- byte _after_ bpos
--?         print('space for '..tostring(bpos)..' graphemes, '..tostring(boffset-1)..' bytes')
        local frag1 = string.sub(frag, 1, boffset-1)
        local frag1_text = App.newText(love.graphics.getFont(), frag1)
        local frag1_width = App.width(frag1_text)
--?         print('extracting ^'..frag1..'$ of width '..tostring(frag1_width)..'px')
        assert(x + frag1_width <= State.right)
        table.insert(line_cache.fragments, {data=frag1, text=frag1_text})
        frag = string.sub(frag, boffset)
        frag_text = App.newText(love.graphics.getFont(), frag)
        frag_width = App.width(frag_text)
      end
      x = State.left  -- new line
    end
    if #frag > 0 then
--?       print('inserting ^'..frag..'$ of width '..tostring(frag_width)..'px')
      table.insert(line_cache.fragments, {data=frag, text=frag_text})
    end
    x = x + frag_width
  end
end

function Text.textinput(State, t)
  if App.mouse_down(1) then return end
  if App.ctrl_down() or App.alt_down() or App.cmd_down() then return end
  local before = snapshot(State, State.cursor1.line)
--?   print(State.screen_top1.line, State.screen_top1.pos, State.cursor1.line, State.cursor1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
  Text.insert_at_cursor(State, t)
  if State.cursor_y > App.screen.height - State.line_height then
    Text.populate_screen_line_starting_pos(State, State.cursor1.line)
    Text.snap_cursor_to_bottom_of_screen(State, State.left, State.right)
--?     print('=>', State.screen_top1.line, State.screen_top1.pos, State.cursor1.line, State.cursor1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
  end
  record_undo_event(State, {before=before, after=snapshot(State, State.cursor1.line)})
end

function Text.insert_at_cursor(State, t)
  local byte_offset = Text.offset(State.lines[State.cursor1.line].data, State.cursor1.pos)
  State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_offset-1)..t..string.sub(State.lines[State.cursor1.line].data, byte_offset)
  Text.clear_screen_line_cache(State, State.cursor1.line)
  State.cursor1.pos = State.cursor1.pos+1
end

-- Don't handle any keys here that would trigger love.textinput above.
function Text.keychord_pressed(State, chord)
--?   print('chord', chord, State.selection1.line, State.selection1.pos)
  --== shortcuts that mutate text
  if chord == 'return' then
    local before_line = State.cursor1.line
    local before = snapshot(State, before_line)
    Text.insert_return(State)
    State.selection1 = {}
    if State.cursor_y > App.screen.height - State.line_height then
      Text.snap_cursor_to_bottom_of_screen(State, State.left, State.right)
    end
    schedule_save(State)
    record_undo_event(State, {before=before, after=snapshot(State, before_line, State.cursor1.line)})
  elseif chord == 'tab' then
    local before = snapshot(State, State.cursor1.line)
--?     print(State.screen_top1.line, State.screen_top1.pos, State.cursor1.line, State.cursor1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
    Text.insert_at_cursor(State, '\t')
    if State.cursor_y > App.screen.height - State.line_height then
      Text.populate_screen_line_starting_pos(State, State.cursor1.line)
      Text.snap_cursor_to_bottom_of_screen(State, State.left, State.right)
--?       print('=>', State.screen_top1.line, State.screen_top1.pos, State.cursor1.line, State.cursor1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
    end
    schedule_save(State)
    record_undo_event(State, {before=before, after=snapshot(State, State.cursor1.line)})
  elseif chord == 'backspace' then
    if State.selection1.line then
      Text.delete_selection(State, State.left, State.right)
      schedule_save(State)
      return
    end
    local before
    if State.cursor1.pos > 1 then
      before = snapshot(State, State.cursor1.line)
      local byte_start = utf8.offset(State.lines[State.cursor1.line].data, State.cursor1.pos-1)
      local byte_end = utf8.offset(State.lines[State.cursor1.line].data, State.cursor1.pos)
      if byte_start then
        if byte_end then
          State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_start-1)..string.sub(State.lines[State.cursor1.line].data, byte_end)
        else
          State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_start-1)
        end
        State.cursor1.pos = State.cursor1.pos-1
      end
    elseif State.cursor1.line > 1 then
      before = snapshot(State, State.cursor1.line-1, State.cursor1.line)
      if State.lines[State.cursor1.line-1].mode == 'drawing' then
        table.remove(State.lines, State.cursor1.line-1)
        table.remove(State.line_cache, State.cursor1.line-1)
      else
        -- join lines
        State.cursor1.pos = utf8.len(State.lines[State.cursor1.line-1].data)+1
        State.lines[State.cursor1.line-1].data = State.lines[State.cursor1.line-1].data..State.lines[State.cursor1.line].data
        table.remove(State.lines, State.cursor1.line)
        table.remove(State.line_cache, State.cursor1.line)
      end
      State.cursor1.line = State.cursor1.line-1
    end
    if State.screen_top1.line > #State.lines then
      Text.populate_screen_line_starting_pos(State, #State.lines)
      local line_cache = State.line_cache[#State.line_cache]
      State.screen_top1 = {line=#State.lines, pos=line_cache.screen_line_starting_pos[#line_cache.screen_line_starting_pos]}
    elseif Text.lt1(State.cursor1, State.screen_top1) then
      local top2 = Text.to2(State, State.screen_top1)
      top2 = Text.previous_screen_line(State, top2, State.left, State.right)
      State.screen_top1 = Text.to1(State, top2)
      Text.redraw_all(State)  -- if we're scrolling, reclaim all fragments to avoid memory leaks
    end
    Text.clear_screen_line_cache(State, State.cursor1.line)
    assert(Text.le1(State.screen_top1, State.cursor1))
    schedule_save(State)
    record_undo_event(State, {before=before, after=snapshot(State, State.cursor1.line)})
  elseif chord == 'delete' then
    if State.selection1.line then
      Text.delete_selection(State, State.left, State.right)
      schedule_save(State)
      return
    end
    local before
    if State.cursor1.pos <= utf8.len(State.lines[State.cursor1.line].data) then
      before = snapshot(State, State.cursor1.line)
    else
      before = snapshot(State, State.cursor1.line, State.cursor1.line+1)
    end
    if State.cursor1.pos <= utf8.len(State.lines[State.cursor1.line].data) then
      local byte_start = utf8.offset(State.lines[State.cursor1.line].data, State.cursor1.pos)
      local byte_end = utf8.offset(State.lines[State.cursor1.line].data, State.cursor1.pos+1)
      if byte_start then
        if byte_end then
          State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_start-1)..string.sub(State.lines[State.cursor1.line].data, byte_end)
        else
          State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_start-1)
        end
        -- no change to State.cursor1.pos
      end
    elseif State.cursor1.line < #State.lines then
      if State.lines[State.cursor1.line+1].mode == 'text' then
        -- join lines
        State.lines[State.cursor1.line].data = State.lines[State.cursor1.line].data..State.lines[State.cursor1.line+1].data
      end
      table.remove(State.lines, State.cursor1.line+1)
      table.remove(State.line_cache, State.cursor1.line+1)
    end
    Text.clear_screen_line_cache(State, State.cursor1.line)
    schedule_save(State)
    record_undo_event(State, {before=before, after=snapshot(State, State.cursor1.line)})
  --== shortcuts that move the cursor
  elseif chord == 'left' then
    Text.left(State)
    State.selection1 = {}
  elseif chord == 'right' then
    Text.right(State)
    State.selection1 = {}
  elseif chord == 'S-left' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.left(State)
  elseif chord == 'S-right' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.right(State)
  -- C- hotkeys reserved for drawings, so we'll use M-
  elseif chord == 'M-left' then
    Text.word_left(State)
    State.selection1 = {}
  elseif chord == 'M-right' then
    Text.word_right(State)
    State.selection1 = {}
  elseif chord == 'M-S-left' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.word_left(State)
  elseif chord == 'M-S-right' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.word_right(State)
  elseif chord == 'home' then
    Text.start_of_line(State)
    State.selection1 = {}
  elseif chord == 'end' then
    Text.end_of_line(State)
    State.selection1 = {}
  elseif chord == 'S-home' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.start_of_line(State)
  elseif chord == 'S-end' then
    if State.selection1.line == nil then
      State.selection1 = {line=State.cursor1.line, pos=State.cursor1.pos}
    end
    Text.end_of_line(State)
  elseif chord == 'up'pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
//: Phase 3: Start running a loaded and transformed recipe.
//:
//: So far we've seen recipes as lists of instructions, and instructions point
//: at other recipes. To kick things off mu needs to know how to run certain
//: 'primitive' recipes. That will then give the ability to run recipes
//: containing these primitives.
//:
//: This layer defines a skeleton with just two primitive recipes: IDLE which
//: does nothing, and COPY, which can copy numbers from one memory location to
//: another. Later layers will add more primitives.

:(scenario copy_literal)
recipe main [
  1:number <- copy 23:literal
]
+run: 1:number <- copy 23:literal
+mem: storing 23 in location 1

:(scenario copy)
recipe main [
  1:number <- copy 23:literal
  2:number <- copy 1:number
]
+run: 2:number <- copy 1:number
+mem: location 1 is 23
+mem: storing 23 in location 2

:(scenario copy_multiple)
recipe main [
  1:number, 2:number <- copy 23:literal, 24:literal
]
+mem: storing 23 in location 1
+mem: storing 24 in location 2

:(before "End Types")
// Book-keeping while running a recipe.
//: Later layers will change this.
struct routine {
  recipe_ordinal running_recipe;
  long long int running_step_index;
  routine(recipe_ordinal r) :running_recipe(r), running_step_index(0) {}
  bool completed() const;
};

:(before "End Globals")
routine* Current_routine = NULL;

:(code)
void run(recipe_ordinal r) {
  routine rr(r);
  Current_routine = &rr;
  run_current_routine();
}

void run_current_routine()
{  // curly on a separate line, because later layers will modify header
//?   cerr << "AAA 6\n"; //? 3
  while (!Current_routine->completed())  // later layers will modify condition
  {
//?     cerr << "AAA 7: " << current_step_index() << '\n'; //? 1
    // Running One Instruction
    if (current_instruction().is_label) { ++current_step_index(); continue; }
    trace(Initial_callstack_depth+Callstack_depth, "run") << current_instruction().to_string();
    assert(Memory[0] == 0);
    // Read all ingredients from memory.
    // Each ingredient loads a vector of values rather than a single value; mu
    // permits operating on reagents spanning multiple locations.
    vector<vector<double> > ingredients;
    for (long long int i = 0; i < SIZE(current_instruction().ingredients); ++i) {
      ingredients.push_back(read_memory(current_instruction().ingredients.at(i)));
    }
    // Instructions below will write to 'products'.
    vector<vector<double> > products;
//?     cerr << "AAA 8: " << current_instruction().operation << " ^" << Recipe[current_instruction().operation].name << "$\n"; //? 1
//?     cerr << "% " << current_recipe_name() << "/" << current_step_index() << ": " << Memory[1013] << ' ' << Memory[1014] << '\n'; //? 1
    switch (current_instruction().operation) {
      // Primitive Recipe Implementations
      case COPY: {
//?         if (!ingredients.empty()) cerr << current_instruction().ingredients.at(0).to_string() << ' ' << ingredients.at(0).at(0) << '\n'; //? 1
        copy(ingredients.begin(), ingredients.end(), inserter(products, products.begin()));
        break;
      }
      // End Primitive Recipe Implementations
      default: {
        cout << "not a primitive op: " << current_instruction().operation << '\n';
      }
    }
    if (SIZE(products) < SIZE(current_instruction().products))
      raise << "failed to write to all products! " << current_instruction().to_string();
    for (long long int i = 0; i < SIZE(current_instruction().products); ++i) {
      write_memory(current_instruction().products.at(i), products.at(i));
    }
    // End of Instruction
    ++current_step_index();
  }
//?   cerr << "AAA 9\n"; //? 2
  stop_running_current_routine:;
}

//: Some helpers.
//: We'll need to override these later as we change the definition of routine.
//: Important that they return referrences into the routine.

inline long long int& current_step_index() {
  return Current_routine->running_step_index;
}

inline const string& current_recipe_name() {
  return Recipe[Current_routine->running_recipe].name;
}

inline const instruction& current_instruction() {
  return Recipe[Current_routine->running_recipe].steps.at(Current_routine->running_step_index);
}

inline bool routine::completed() const {
  return running_step_index >= SIZE(Recipe[running_recipe].steps);
}

:(before "End Commandline Parsing")
// Loading Commandline Files
if (argc > 1) {
  for (int i = 1; i < argc; ++i) {
    load_permanently(argv[i]);
  }
}

:(before "End Main")
if (!Run_tests) {
  setup();
//?   Trace_file = "interactive"; //? 1
  START_TRACING_UNTIL_END_OF_SCOPE;
//?   Trace_stream->dump_layer = "all"; //? 2
  transform_all();
  recipe_ordinal r = Recipe_ordinal[string("main")];
//?   Trace_stream->dump_layer = "all"; //? 1
  if (r) run(r);
//?   dump_memory(); //? 1
  teardown();
}

:(code)
void load_permanently(string filename) {
  ifstream fin(filename.c_str());
  fin.peek();
//?   cerr << "AAA: " << filename << ' ' << static_cast<bool>(fin) << ' ' << fin.fail() << '\n'; //? 1
//?   return; //? 1
  if (!fin) {
    raise << "no such file " << filename << '\n';
    return;
  }
  fin >> std::noskipws;
  load(fin);
  transform_all();
  fin.close();
  // freeze everything so it doesn't get cleared by tests
  recently_added_recipes.clear();
  // End load_permanently.
}

//:: On startup, load everything in core.mu
:(before "End Load Recipes")
load_permanently("core.mu");

:(code)
// helper for tests
void run(string form) {
//?   cerr << "AAA 2\n"; //? 2
//?   cerr << form << '\n'; //? 1
  vector<recipe_ordinal> tmp = load(form);
  if (tmp.empty()) return;
  transform_all();
//?   cerr << "AAA 3\n"; //? 2
  run(tmp.front());
//?   cerr << "YYY\n"; //? 2
}

//:: Reading from memory, writing to memory.

vector<double> read_memory(reagent x) {
//?   cout << "read_memory: " << x.to_string() << '\n'; //? 2
  vector<double> result;
  if (is_literal(x)) {
    result.push_back(x.value);
    return result;
  }
  long long int base = x.value;
  long long int size = size_of(x);
  for (long long int offset = 0; offset < size; ++offset) {
    double val = Memory[base+offset];
    trace(Primitive_recipe_depth, "mem") << "location " << base+offset << " is " << val;
    result.push_back(val);
  }
  return result;
}

void write_memory(reagent x, vector<double> data) {
  if (is_dummy(x)) return;
  if (is_literal(x)) return;
  long long int base = x.value;
  if (size_mismatch(x, data)) {
    raise << current_recipe_name() << ": size mismatch in storing to " << x.to_string() << " at " << current_instruction().to_string() << '\n' << die();
  }
  for (long long int offset = 0; offset < SIZE(data); ++offset) {
    trace(Primitive_recipe_depth, "mem") << "storing " << data.at(offset) << " in location " << base+offset;
    Memory[base+offset] = data.at(offset);
  }
}

:(code)
long long int size_of(const reagent& r) {
  return size_of(r.types);
}
long long int size_of(const vector<type_ordinal>& types) {
  // End size_of(types) Cases
  return 1;
}

bool size_mismatch(const reagent& x, const vector<double>& data) {
//?   if (size_of(x) != SIZE(data)) cerr << size_of(x) << " vs " << SIZE(data) << '\n'; //? 2
  return size_of(x) != SIZE(data);
}

bool is_dummy(const reagent& x) {
  return x.name == "_";
}

bool is_literal(const reagent& r) {
  return SIZE(r.types) == 1 && r.types.at(0) == 0;
}

:(scenario run_label)
recipe main [
  +foo
  1:number <- copy 23:literal
  2:number <- copy 1:number
]
+run: 1:number <- copy 23:literal
+run: 2:number <- copy 1:number
-run: +foo

:(scenario run_dummy)
recipe main [
  _ <- copy 0:literal
]
+run: _ <- copy 0:literal

:(scenario run_literal)
recipe main [
  0:literal/screen <- copy 0:literal
]
-mem: storing 0 in location 0
class="o">= new_cursor_line State.cursor1.pos = utf8.len(State.lines[State.cursor1.line].data) + 1 break end end end if Text.lt1(State.cursor1, State.screen_top1) then local top2 = Text.to2(State, State.screen_top1) top2 = Text.previous_screen_line(State, top2) State.screen_top1 = Text.to1(State, top2) end end function Text.right(State) Text.right_without_scroll(State) if Text.cursor_out_of_screen(State) then Text.snap_cursor_to_bottom_of_screen(State) end end function Text.right_without_scroll(State) assert(State.lines[State.cursor1.line].mode == 'text') if State.cursor1.pos <= utf8.len(State.lines[State.cursor1.line].data) then State.cursor1.pos = State.cursor1.pos+1 else local new_cursor_line = State.cursor1.line while new_cursor_line <= #State.lines-1 do new_cursor_line = new_cursor_line+1 if State.lines[new_cursor_line].mode == 'text' then State.cursor1.line = new_cursor_line State.cursor1.pos = 1 break end end end end function Text.pos_at_start_of_screen_line(State, loc1) Text.populate_screen_line_starting_pos(State, loc1.line) local line_cache = State.line_cache[loc1.line] for i=#line_cache.screen_line_starting_pos,1,-1 do local spos = line_cache.screen_line_starting_pos[i] if spos <= loc1.pos then return spos,i end end assert(false) end function Text.cursor_at_final_screen_line(State) Text.populate_screen_line_starting_pos(State, State.cursor1.line) local screen_lines = State.line_cache[State.cursor1.line].screen_line_starting_pos --? print(screen_lines[#screen_lines], State.cursor1.pos) return screen_lines[#screen_lines] <= State.cursor1.pos end function Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary(State) local y = State.top while State.cursor1.line <= #State.lines do if State.lines[State.cursor1.line].mode == 'text' then break end --? print('cursor skips', State.cursor1.line) y = y + Drawing_padding_height + Drawing.pixels(State.lines[State.cursor1.line].h, State.width) State.cursor1.line = State.cursor1.line + 1 end -- hack: insert a text line at bottom of file if necessary if State.cursor1.line > #State.lines then assert(State.cursor1.line == #State.lines+1) table.insert(State.lines, {mode='text', data=''}) table.insert(State.line_cache, {}) end --? print(y, App.screen.height, App.screen.height-State.line_height) if y > App.screen.height - State.line_height then --? print('scroll up') Text.snap_cursor_to_bottom_of_screen(State) end end -- should never modify State.cursor1 function Text.snap_cursor_to_bottom_of_screen(State) local top2 = Text.to2(State, State.cursor1) top2.screen_pos = 1 -- start of screen line --? print('cursor pos '..tostring(State.cursor1.pos)..' is on the #'..tostring(top2.screen_line)..' screen line down') local y = App.screen.height - State.line_height -- duplicate some logic from love.draw while true do --? print(y, 'top2:', top2.line, top2.screen_line, top2.screen_pos) if top2.line == 1 and top2.screen_line == 1 then break end if top2.screen_line > 1 or State.lines[top2.line-1].mode == 'text' then local h = State.line_height if y - h < State.top then break end y = y - h else assert(top2.line > 1) assert(State.lines[top2.line-1].mode == 'drawing') -- We currently can't draw partial drawings, so either skip it entirely -- or not at all. local h = Drawing_padding_height + Drawing.pixels(State.lines[top2.line-1].h, State.width) if y - h < State.top then break end --? print('skipping drawing of height', h) y = y - h end top2 = Text.previous_screen_line(State, top2) end --? print('top2 finally:', top2.line, top2.screen_line, top2.screen_pos) State.screen_top1 = Text.to1(State, top2) --? print('top1 finally:', State.screen_top1.line, State.screen_top1.pos) Text.redraw_all(State) -- if we're scrolling, reclaim all fragments to avoid memory leaks end function Text.in_line(State, line_index, x,y) local line = State.lines[line_index] local line_cache = State.line_cache[line_index] if line_cache.starty == nil then return false end -- outside current page if y < line_cache.starty then return false end Text.populate_screen_line_starting_pos(State, line_index) return y < line_cache.starty + State.line_height*(#line_cache.screen_line_starting_pos - Text.screen_line_index(line_cache.screen_line_starting_pos, line_cache.startpos) + 1) end -- convert mx,my in pixels to schema-1 coordinates function Text.to_pos_on_line(State, line_index, mx, my) local line = State.lines[line_index] local line_cache = State.line_cache[line_index] assert(my >= line_cache.starty) -- duplicate some logic from Text.draw local y = line_cache.starty local start_screen_line_index = Text.screen_line_index(line_cache.screen_line_starting_pos, line_cache.startpos) for screen_line_index = start_screen_line_index,#line_cache.screen_line_starting_pos do local screen_line_starting_pos = line_cache.screen_line_starting_pos[screen_line_index] local screen_line_starting_byte_offset = Text.offset(line.data, screen_line_starting_pos) --? print('iter', y, screen_line_index, screen_line_starting_pos, string.sub(line.data, screen_line_starting_byte_offset)) local nexty = y + State.line_height if my < nexty then -- On all wrapped screen lines but the final one, clicks past end of -- line position cursor on final character of screen line. -- (The final screen line positions past end of screen line as always.) if screen_line_index < #line_cache.screen_line_starting_pos and mx > State.left + Text.screen_line_width(State, line_index, screen_line_index) then --? print('past end of non-final line; return') return line_cache.screen_line_starting_pos[screen_line_index+1]-1 end local s = string.sub(line.data, screen_line_starting_byte_offset) --? print('return', mx, Text.nearest_cursor_pos(s, mx, State.left), '=>', screen_line_starting_pos + Text.nearest_cursor_pos(s, mx, State.left) - 1) return screen_line_starting_pos + Text.nearest_cursor_pos(s, mx, State.left) - 1 end y = nexty end assert(false) end function Text.screen_line_width(State, line_index, i) local line = State.lines[line_index] local line_cache = State.line_cache[line_index] local start_pos = line_cache.screen_line_starting_pos[i] local start_offset = Text.offset(line.data, start_pos) local screen_line if i < #line_cache.screen_line_starting_pos then local past_end_pos = line_cache.screen_line_starting_pos[i+1] local past_end_offset = Text.offset(line.data, past_end_pos) screen_line = string.sub(line.data, start_offset, past_end_offset-1) else screen_line = string.sub(line.data, start_pos) end local screen_line_text = App.newText(love.graphics.getFont(), screen_line) return App.width(screen_line_text) end function Text.screen_line_index(screen_line_starting_pos, pos) for i = #screen_line_starting_pos,1,-1 do if screen_line_starting_pos[i] <= pos then return i end end end -- convert x pixel coordinate to pos -- oblivious to wrapping -- result: 1 to len+1 function Text.nearest_cursor_pos(line, x, left) if x < left then return 1 end local len = utf8.len(line) local max_x = left+Text.x(line, len+1) if x > max_x then return len+1 end local leftpos, rightpos = 1, len+1 --? print('-- nearest', x) while true do --? print('nearest', x, '^'..line..'$', leftpos, rightpos) if leftpos == rightpos then return leftpos end local curr = math.floor((leftpos+rightpos)/2) local currxmin = left+Text.x(line, curr) local currxmax = left+Text.x(line, curr+1) --? print('nearest', x, leftpos, rightpos, curr, currxmin, currxmax) if currxmin <= x and x < currxmax then if x-currxmin < currxmax-x then return curr else return curr+1 end end if leftpos >= rightpos-1 then return rightpos end if currxmin > x then rightpos = curr else leftpos = curr end end assert(false) end -- return the nearest index of line (in utf8 code points) which lies entirely -- within x pixels of the left margin -- result: 0 to len+1 function Text.nearest_pos_less_than(line, x) --? print('', '-- nearest_pos_less_than', line, x) local len = utf8.len(line) local max_x = Text.x_after(line, len) if x > max_x then return len+1 end local left, right = 0, len+1 while true do local curr = math.floor((left+right)/2) local currxmin = Text.x_after(line, curr+1) local currxmax = Text.x_after(line, curr+2) --? print('', x, left, right, curr, currxmin, currxmax) if currxmin <= x and x < currxmax then return curr end if left >= right-1 then return left end if currxmin > x then right = curr else left = curr end end assert(false) end function Text.x_after(s, pos) local offset = Text.offset(s, math.min(pos+1, #s+1)) local s_before = s:sub(1, offset-1) --? print('^'..s_before..'$') local text_before = App.newText(love.graphics.getFont(), s_before) return App.width(text_before) end function Text.x(s, pos) local offset = Text.offset(s, pos) local s_before = s:sub(1, offset-1) local text_before = App.newText(love.graphics.getFont(), s_before) return App.width(text_before) end function Text.to2(State, loc1) if State.lines[loc1.line].mode == 'drawing' then return {line=loc1.line, screen_line=1, screen_pos=1} end local result = {line=loc1.line, screen_line=1} local line_cache = State.line_cache[loc1.line] Text.populate_screen_line_starting_pos(State, loc1.line) for i=#line_cache.screen_line_starting_pos,1,-1 do local spos = line_cache.screen_line_starting_pos[i] if spos <= loc1.pos then result.screen_line = i result.screen_pos = loc1.pos - spos + 1 break end end assert(result.screen_pos) return result end function Text.to1(State, loc2) local result = {line=loc2.line, pos=loc2.screen_pos} if loc2.screen_line > 1 then result.pos = State.line_cache[loc2.line].screen_line_starting_pos[loc2.screen_line] + loc2.screen_pos - 1 end return result end function Text.eq1(a, b) return a.line == b.line and a.pos == b.pos end function Text.lt1(a, b) if a.line < b.line then return true end if a.line > b.line then return false end return a.pos < b.pos end function Text.le1(a, b) if a.line < b.line then return true end if a.line > b.line then return false end return a.pos <= b.pos end function Text.offset(s, pos1) if pos1 == 1 then return 1 end local result = utf8.offset(s, pos1) if result == nil then print(pos1, #s, s) end assert(result) return result end function Text.previous_screen_line(State, loc2) if loc2.screen_line > 1 then return {line=loc2.line, screen_line=loc2.screen_line-1, screen_pos=1} elseif loc2.line == 1 then return loc2 elseif State.lines[loc2.line-1].mode == 'drawing' then return {line=loc2.line-1, screen_line=1, screen_pos=1} else local l = State.lines[loc2.line-1] Text.populate_screen_line_starting_pos(State, loc2.line-1) return {line=loc2.line-1, screen_line=#State.line_cache[loc2.line-1].screen_line_starting_pos, screen_pos=1} end end -- resize helper function Text.tweak_screen_top_and_cursor(State) --? print('a', State.selection1.line) if State.screen_top1.pos == 1 then return end Text.populate_screen_line_starting_pos(State, State.screen_top1.line) local line = State.lines[State.screen_top1.line] local line_cache = State.line_cache[State.screen_top1.line] for i=2,#line_cache.screen_line_starting_pos do local pos = line_cache.screen_line_starting_pos[i] if pos == State.screen_top1.pos then break end if pos > State.screen_top1.pos then -- make sure screen top is at start of a screen line local prev = line_cache.screen_line_starting_pos[i-1] if State.screen_top1.pos - prev < pos - State.screen_top1.pos then State.screen_top1.pos = prev else State.screen_top1.pos = pos end break end end -- make sure cursor is on screen if Text.lt1(State.cursor1, State.screen_top1) then State.cursor1 = {line=State.screen_top1.line, pos=State.screen_top1.pos} elseif State.cursor1.line >= State.screen_bottom1.line then --? print('too low') if Text.cursor_out_of_screen(State) then --? print('tweak') State.cursor1 = { line=State.screen_bottom1.line, pos=Text.to_pos_on_line(State, State.screen_bottom1.line, State.right-5, App.screen.height-5), } end end end -- slightly expensive since it redraws the screen function Text.cursor_out_of_screen(State) App.draw() return State.cursor_y == nil -- this approach is cheaper and almost works, except on the final screen -- where file ends above bottom of screen --? local botpos = Text.pos_at_start_of_screen_line(State, State.cursor1) --? local botline1 = {line=State.cursor1.line, pos=botpos} --? return Text.lt1(State.screen_bottom1, botline1) end function Text.redraw_all(State) --? print('clearing fragments') State.line_cache = {} for i=1,#State.lines do State.line_cache[i] = {} end end function Text.clear_screen_line_cache(State, line_index) State.line_cache[line_index].fragments = nil State.line_cache[line_index].screen_line_starting_pos = nil end