about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--Manual_tests.md21
-rw-r--r--README.md5
-rw-r--r--app.lua29
-rw-r--r--colorize.lua83
-rw-r--r--commands.lua100
-rw-r--r--edit.lua9
-rw-r--r--file.lua1
-rw-r--r--keychord.lua14
-rw-r--r--log.lua34
-rw-r--r--log_browser.lua316
-rw-r--r--main.lua367
-rw-r--r--run.lua182
-rw-r--r--run_tests.lua (renamed from main_tests.lua)0
-rw-r--r--search.lua20
-rw-r--r--source.lua358
-rw-r--r--source_edit.lua377
-rw-r--r--source_file.lua89
-rw-r--r--source_tests.lua77
-rw-r--r--source_text.lua1561
-rw-r--r--source_text_tests.lua1609
-rw-r--r--source_undo.lua110
-rw-r--r--text.lua5
22 files changed, 5164 insertions, 203 deletions
diff --git a/Manual_tests.md b/Manual_tests.md
index e258940..358ea8b 100644
--- a/Manual_tests.md
+++ b/Manual_tests.md
@@ -3,17 +3,28 @@ program before it ever runs. However, some things don't have tests yet, either
 because I don't know how to test them or because I've been lazy. I'll at least
 record those here.
 
-* Initializing settings:
-    - from previous session
-        - Filename as absolute path
-        - Filename as relative path
-    - from defaults
+Startup:
+    - terminal log shows unit tests running
+
+Initializing settings:
+    - delete app settings, start; window opens running the text editor
+    - quit while running the text editor, restart; window opens running the text editor in same position+dimensions
+    - quit while editing source (color; no drawings; no selection), restart; window opens editing source in same position+dimensions
+    - start out running the text editor, move window, press ctrl+e twice; window is running text editor in same position+dimensions
+    - start out editing source, move window, press ctrl+e twice; window is editing source in same position+dimensions
+    - no log file; switching to source works
+
+Code loading:
+* run love with directory; text editor runs
+* run love with zip file; text editor runs
 
 * How the screen looks. Our tests use a level of indirection to check text and
   graphics printed to screen, but not the precise pixels they translate to.
     - where exactly the cursor is drawn to highlight a given character
     - analogously, how a shape precisely looks as you draw it
 
+* start out running the text editor, press ctrl+e to edit source, make a change to the source, press ctrl+e twice to return to the source editor; the change should be preserved.
+
 ### Other compromises
 
 Lua is dynamically typed. Tests can't patch over lack of type-checking.
diff --git a/README.md b/README.md
index 880b507..8dfa137 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ While editing text:
 * `ctrl+z` to undo, `ctrl+y` to redo
 * `ctrl+=` to zoom in, `ctrl+-` to zoom out, `ctrl+0` to reset zoom
 * `alt+right`/`alt+left` to jump to the next/previous word, respectively
+* `ctrl+e` to modify the sources
 
 For shortcuts while editing drawings, consult the online help. Either:
 * hover on a drawing and hit `ctrl+h`, or
@@ -78,6 +79,10 @@ found anything amiss: http://akkartik.name/contact
 
 * No scrollbars yet. That stuff is hard.
 
+* There are some temporary limitations when editing sources:
+    - no line drawings
+    - no selecting text
+
 ## Mirrors and Forks
 
 Updates to lines.love can be downloaded from the following mirrors in addition
diff --git a/app.lua b/app.lua
index cac1303..2135fb0 100644
--- a/app.lua
+++ b/app.lua
@@ -1,4 +1,4 @@
--- main entrypoint for LÖVE
+-- love.run: main entrypoint function for LÖVE
 --
 -- Most apps can just use the default, but we need to override it to
 -- install a test harness.
@@ -11,13 +11,10 @@
 --
 -- Scroll below this function for more details.
 function love.run()
+  App.snapshot_love()
   -- Tests always run at the start.
-  App.run_tests()
-
+  App.run_tests_and_initialize()
 --?   print('==')
-  App.disable_tests()
-  App.initialize_globals()
-  App.initialize(love.arg.parseGameArguments(arg), arg)
 
   love.timer.step()
   local dt = 0
@@ -123,6 +120,26 @@ end
 
 App = {screen={}}
 
+-- save/restore various framework globals we care about -- only on very first load
+function App.snapshot_love()
+  if Love_snapshot then return end
+  Love_snapshot = {}
+  -- save the entire initial font; it doesn't seem reliably recreated using newFont
+  Love_snapshot.initial_font = love.graphics.getFont()
+end
+
+function App.undo_initialize()
+  love.graphics.setFont(Love_snapshot.initial_font)
+end
+
+function App.run_tests_and_initialize()
+  App.load()
+  App.run_tests()
+  App.disable_tests()
+  App.initialize_globals()
+  App.initialize(love.arg.parseGameArguments(arg), arg)
+end
+
 function App.initialize_for_test()
   App.screen.init({width=100, height=50})
   App.screen.contents = {}  -- clear screen
diff --git a/colorize.lua b/colorize.lua
new file mode 100644
index 0000000..c0d2117
--- /dev/null
+++ b/colorize.lua
@@ -0,0 +1,83 @@
+-- State transitions while colorizing a single line.
+-- Just for comments and strings.
+-- Limitation: each fragment gets a uniform color so we can only change color
+-- at word boundaries.
+Next_state = {
+  normal={
+    {prefix='--', target='comment'},
+    {prefix='"', target='dstring'},
+    {prefix="'", target='sstring'},
+  },
+  dstring={
+    {suffix='"', target='normal'},
+  },
+  sstring={
+    {suffix="'", target='normal'},
+  },
+  -- comments are a sink
+}
+
+Comments_color = {r=0, g=0, b=1}
+String_color = {r=0, g=0.5, b=0.5}
+Divider_color = {r=0.7, g=0.7, b=0.7}
+
+Colors = {
+  normal=Text_color,
+  comment=Comments_color,
+  sstring=String_color,
+  dstring=String_color
+}
+
+Current_state = 'normal'
+
+function initialize_color()
+--?   print('new line')
+  Current_state = 'normal'
+end
+
+function select_color(frag)
+--?   print('before', '^'..frag..'$', Current_state)
+  switch_color_based_on_prefix(frag)
+--?   print('using color', Current_state, Colors[Current_state])
+  App.color(Colors[Current_state])
+  switch_color_based_on_suffix(frag)
+--?   print('state after suffix', Current_state)
+end
+
+function switch_color_based_on_prefix(frag)
+  if Next_state[Current_state] == nil then
+    return
+  end
+  frag = rtrim(frag)
+  for _,edge in pairs(Next_state[Current_state]) do
+    if edge.prefix and find(frag, edge.prefix, nil, --[[plain]] true) == 1 then
+      Current_state = edge.target
+      break
+    end
+  end
+end
+
+function switch_color_based_on_suffix(frag)
+  if Next_state[Current_state] == nil then
+    return
+  end
+  frag = rtrim(frag)
+  for _,edge in pairs(Next_state[Current_state]) do
+    if edge.suffix and rfind(frag, edge.suffix, nil, --[[plain]] true) == #frag then
+      Current_state = edge.target
+      break
+    end
+  end
+end
+
+function trim(s)
+  return s:gsub('^%s+', ''):gsub('%s+$', '')
+end
+
+function ltrim(s)
+  return s:gsub('^%s+', '')
+end
+
+function rtrim(s)
+  return s:gsub('%s+$', '')
+end
diff --git a/commands.lua b/commands.lua
new file mode 100644
index 0000000..037205f
--- /dev/null
+++ b/commands.lua
@@ -0,0 +1,100 @@
+Menu_background_color = {r=0.6, g=0.8, b=0.6}
+Menu_border_color = {r=0.6, g=0.7, b=0.6}
+Menu_command_color = {r=0.2, g=0.2, b=0.2}
+Menu_highlight_color = {r=0.5, g=0.7, b=0.3}
+
+function source.draw_menu_bar()
+  if App.run_tests then return end  -- disable in tests
+  App.color(Menu_background_color)
+  love.graphics.rectangle('fill', 0,0, App.screen.width, Menu_status_bar_height)
+  App.color(Menu_border_color)
+  love.graphics.rectangle('line', 0,0, App.screen.width, Menu_status_bar_height)
+  App.color(Menu_command_color)
+  Menu_cursor = 5
+  if Show_file_navigator then
+    source.draw_file_navigator()
+    return
+  end
+  add_hotkey_to_menu('ctrl+e: run')
+  if Focus == 'edit' then
+    add_hotkey_to_menu('ctrl+g: switch file')
+    if Show_log_browser_side then
+      add_hotkey_to_menu('ctrl+l: hide log browser')
+    else
+      add_hotkey_to_menu('ctrl+l: show log browser')
+    end
+    if Editor_state.expanded then
+      add_hotkey_to_menu('ctrl+b: collapse debug prints')
+    else
+      add_hotkey_to_menu('ctrl+b: expand debug prints')
+    end
+    add_hotkey_to_menu('ctrl+d: create/edit debug print')
+    add_hotkey_to_menu('ctrl+f: find in file')
+    add_hotkey_to_menu('alt+left alt+right: prev/next word')
+  elseif Focus == 'log_browser' then
+    -- nothing yet
+  else
+    assert(false, 'unknown focus "'..Focus..'"')
+  end
+  add_hotkey_to_menu('ctrl+z ctrl+y: undo/redo')
+  add_hotkey_to_menu('ctrl+x ctrl+c ctrl+v: cut/copy/paste')
+  add_hotkey_to_menu('ctrl+= ctrl+- ctrl+0: zoom')
+end
+
+function add_hotkey_to_menu(s)
+  if Text_cache[s] == nil then
+    Text_cache[s] = App.newText(love.graphics.getFont(), s)
+  end
+  local width = App.width(Text_cache[s])
+  if Menu_cursor + width > App.screen.width - 5 then
+    return
+  end
+  App.color(Menu_command_color)
+  App.screen.draw(Text_cache[s], Menu_cursor,5)
+  Menu_cursor = Menu_cursor + width + 30
+end
+
+function source.draw_file_navigator()
+  for i,file in ipairs(File_navigation.candidates) do
+    if file == 'source' then
+      App.color(Menu_border_color)
+      love.graphics.line(Menu_cursor-10,2, Menu_cursor-10,Menu_status_bar_height-2)
+    end
+    add_file_to_menu(file, i == File_navigation.index)
+  end
+end
+
+function add_file_to_menu(s, cursor_highlight)
+  if Text_cache[s] == nil then
+    Text_cache[s] = App.newText(love.graphics.getFont(), s)
+  end
+  local width = App.width(Text_cache[s])
+  if Menu_cursor + width > App.screen.width - 5 then
+    return
+  end
+  if cursor_highlight then
+    App.color(Menu_highlight_color)
+    love.graphics.rectangle('fill', Menu_cursor-5,5-2, App.width(Text_cache[s])+5*2,Editor_state.line_height+2*2)
+  end
+  App.color(Menu_command_color)
+  App.screen.draw(Text_cache[s], Menu_cursor,5)
+  Menu_cursor = Menu_cursor + width + 30
+end
+
+function keychord_pressed_on_file_navigator(chord, key)
+  if chord == 'escape' then
+    Show_file_navigator = false
+  elseif chord == 'return' then
+    local candidate = guess_source(File_navigation.candidates[File_navigation.index]..'.lua')
+    source.switch_to_file(candidate)
+    Show_file_navigator = false
+  elseif chord == 'left' then
+    if File_navigation.index > 1 then
+      File_navigation.index = File_navigation.index-1
+    end
+  elseif chord == 'right' then
+    if File_navigation.index < #File_navigation.candidates then
+      File_navigation.index = File_navigation.index+1
+    end
+  end
+end
diff --git a/edit.lua b/edit.lua
index f5dc1f2..87cf6c2 100644
--- a/edit.lua
+++ b/edit.lua
@@ -20,15 +20,6 @@ Drawing_padding_height = Drawing_padding_top + Drawing_padding_bottom
 
 Same_point_distance = 4  -- pixel distance at which two points are considered the same
 
-utf8 = require 'utf8'
-
-require 'file'
-require 'text'
-require 'drawing'
-require 'geom'
-require 'help'
-require 'icons'
-
 edit = {}
 
 -- run in both tests and a real run
diff --git a/file.lua b/file.lua
index 6b36b0f..4e268a7 100644
--- a/file.lua
+++ b/file.lua
@@ -50,7 +50,6 @@ function save_to_disk(State)
   outfile:close()
 end
 
-json = require 'json'
 function load_drawing(infile_next_line)
   local drawing = {mode='drawing', h=256/2, points={}, shapes={}, pending={}}
   while true do
diff --git a/keychord.lua b/keychord.lua
index ba0a47c..7be57d2 100644
--- a/keychord.lua
+++ b/keychord.lua
@@ -56,9 +56,17 @@ end
 array = {}
 
 function array.find(arr, elem)
-  for i,x in ipairs(arr) do
-    if x == elem then
-      return i
+  if type(elem) == 'function' then
+    for i,x in ipairs(arr) do
+      if elem(x) then
+        return i
+      end
+    end
+  else
+    for i,x in ipairs(arr) do
+      if x == elem then
+        return i
+      end
     end
   end
   return nil
diff --git a/log.lua b/log.lua
new file mode 100644
index 0000000..f59449c
--- /dev/null
+++ b/log.lua
@@ -0,0 +1,34 @@
+function log(stack_frame_index, obj)
+	local info = debug.getinfo(stack_frame_index, 'Sl')
+	local msg
+	if type(obj) == 'string' then
+		msg = obj
+	else
+		msg = json.encode(obj)
+	end
+	love.filesystem.append('log', info.short_src..':'..info.currentline..': '..msg..'\n')
+end
+
+-- for section delimiters we'll use specific Unicode box characters
+function log_start(name, stack_frame_index)
+	if stack_frame_index == nil then
+		stack_frame_index = 3
+	end
+	log(stack_frame_index, '\u{250c} ' .. name)
+end
+function log_end(name, stack_frame_index)
+	if stack_frame_index == nil then
+		stack_frame_index = 3
+	end
+	log(stack_frame_index, '\u{2518} ' .. name)
+end
+
+function log_new(name, stack_frame_index)
+	if stack_frame_index == nil then
+		stack_frame_index = 4
+	end
+	log_end(name, stack_frame_index)
+	log_start(name, stack_frame_index)
+end
+
+-- vim:noexpandtab
diff --git a/log_browser.lua b/log_browser.lua
new file mode 100644
index 0000000..f65117f
--- /dev/null
+++ b/log_browser.lua
@@ -0,0 +1,316 @@
+-- environment for immutable logs
+-- optionally reads extensions for rendering some types from the source codebase that generated them
+--
+-- We won't care too much about long, wrapped lines. If they lines get too
+-- long to manage, you need a better, graphical rendering for them. Load
+-- functions to render them into the log_render namespace.
+
+function source.initialize_log_browser_side()
+  Log_browser_state = edit.initialize_state(Margin_top, Editor_state.right + Margin_right + Margin_left, (Editor_state.right+Margin_right)*2, Editor_state.font_height, Editor_state.line_height)
+  Log_browser_state.filename = 'log'
+  load_from_disk(Log_browser_state)  -- TODO: pay no attention to Fold
+  log_browser.parse(Log_browser_state)
+  Text.redraw_all(Log_browser_state)
+  Log_browser_state.screen_top1 = {line=1, pos=1}
+  Log_browser_state.cursor1 = {line=1, pos=nil}
+end
+
+Section_stack = {}
+Section_border_color = {r=0.7, g=0.7, b=0.7}
+Cursor_line_background_color = {r=0.7, g=0.7, b=0, a=0.1}
+
+Section_border_padding_horizontal = 30  -- TODO: adjust this based on font height (because we draw text vertically along the borders
+Section_border_padding_vertical = 15  -- TODO: adjust this based on font height
+
+log_browser = {}
+
+function log_browser.parse(State)
+  for _,line in ipairs(State.lines) do
+    if line.data ~= '' then
+      line.filename, line.line_number, line.data = line.data:match('%[string "([^:]*)"%]:([^:]*):%s*(.*)')
+      line.filename = guess_source(line.filename)
+      line.line_number = tonumber(line.line_number)
+      if line.data:sub(1,1) == '{' then
+        local data = json.decode(line.data)
+        if log_render[data.name] then
+          line.data = data
+        end
+        line.section_stack = table.shallowcopy(Section_stack)
+      elseif line.data:match('\u{250c}') then
+        line.section_stack = table.shallowcopy(Section_stack)  -- as it is at the beginning
+        local section_name = line.data:match('\u{250c}%s*(.*)')
+        table.insert(Section_stack, {name=section_name})
+        line.section_begin = true
+        line.section_name = section_name
+        line.data = nil
+      elseif line.data:match('\u{2518}') then
+        local section_name = line.data:match('\u{2518}%s*(.*)')
+        if array.find(Section_stack, function(x) return x.name == section_name end) then
+          while table.remove(Section_stack).name ~= section_name do
+            --
+          end
+          line.section_end = true
+          line.section_name = section_name
+          line.data = nil
+        end
+        line.section_stack = table.shallowcopy(Section_stack)
+      else
+        -- string
+        line.section_stack = table.shallowcopy(Section_stack)
+      end
+    else
+      line.section_stack = {}
+    end
+  end
+end
+
+function table.shallowcopy(x)
+  return {unpack(x)}
+end
+
+function guess_source(filename)
+  local possible_source = filename:gsub('%.lua$', '%.splua')
+  if file_exists(possible_source) then
+    return possible_source
+  else
+    return filename
+  end
+end
+
+function log_browser.draw(State)
+  assert(#State.lines == #State.line_cache)
+  local mouse_line_index = log_browser.line_index(State, App.mouse_x(), App.mouse_y())
+  local y = State.top
+  for line_index = State.screen_top1.line,#State.lines do
+    App.color(Text_color)
+    local line = State.lines[line_index]
+    if y + State.line_height > App.screen.height then break end
+    local height = State.line_height
+    if should_show(line) then
+      local xleft = render_stack_left_margin(State, line_index, line, y)
+      local xright = render_stack_right_margin(State, line_index, line, y)
+      if line.section_name then
+        App.color(Section_border_color)
+        local section_text = to_text(line.section_name)
+        if line.section_begin then
+          local sectiony = y+Section_border_padding_vertical
+          love.graphics.line(xleft,sectiony, xleft,y+State.line_height)
+          love.graphics.line(xright,sectiony, xright,y+State.line_height)
+          love.graphics.line(xleft,sectiony, xleft+50-2,sectiony)
+          love.graphics.draw(section_text, xleft+50,y)
+          love.graphics.line(xleft+50+App.width(section_text)+2,sectiony, xright,sectiony)
+        else assert(line.section_end)
+          local sectiony = y+State.line_height-Section_border_padding_vertical
+          love.graphics.line(xleft,y, xleft,sectiony)
+          love.graphics.line(xright,y, xright,sectiony)
+          love.graphics.line(xleft,sectiony, xleft+50-2,sectiony)
+          love.graphics.draw(section_text, xleft+50,y)
+          love.graphics.line(xleft+50+App.width(section_text)+2,sectiony, xright,sectiony)
+        end
+      else
+        if type(line.data) == 'string' then
+          local old_left, old_right = State.left,State.right
+          State.left,State.right = xleft,xright
+          y = Text.draw(State, line_index, y, --[[startpos]] 1)
+          State.left,State.right = old_left,old_right
+        else
+          height = log_render[line.data.name](line.data, xleft, y, xright-xleft)
+        end
+      end
+      if App.mouse_x() > Log_browser_state.left and line_index == mouse_line_index then
+        App.color(Cursor_line_background_color)
+        love.graphics.rectangle('fill', xleft,y, xright-xleft, height)
+      end
+      y = y + height
+    end
+  end
+end
+
+function render_stack_left_margin(State, line_index, line, y)
+  if line.section_stack == nil then
+    -- assertion message
+    for k,v in pairs(line) do
+      print(k)
+    end
+  end
+  App.color(Section_border_color)
+  for i=1,#line.section_stack do
+    local x = State.left + (i-1)*Section_border_padding_horizontal
+    love.graphics.line(x,y, x,y+log_browser.height(State, line_index))
+    if y < 30 then
+      love.graphics.print(line.section_stack[i].name, x+State.font_height+5, y+5, --[[vertically]] math.pi/2)
+    end
+    if y > App.screen.height-log_browser.height(State, line_index) then
+      love.graphics.print(line.section_stack[i].name, x+State.font_height+5, App.screen.height-App.width(to_text(line.section_stack[i].name))-5, --[[vertically]] math.pi/2)
+    end
+  end
+  return log_browser.left_margin(State, line)
+end
+
+function render_stack_right_margin(State, line_index, line, y)
+  App.color(Section_border_color)
+  for i=1,#line.section_stack do
+    local x = State.right - (i-1)*Section_border_padding_horizontal
+    love.graphics.line(x,y, x,y+log_browser.height(State, line_index))
+    if y < 30 then
+      love.graphics.print(line.section_stack[i].name, x, y+5, --[[vertically]] math.pi/2)
+    end
+    if y > App.screen.height-log_browser.height(State, line_index) then
+      love.graphics.print(line.section_stack[i].name, x, App.screen.height-App.width(to_text(line.section_stack[i].name))-5, --[[vertically]] math.pi/2)
+    end
+  end
+  return log_browser.right_margin(State, line)
+end
+
+function should_show(line)
+  -- Show a line if every single section it's in is expanded.
+  for i=1,#line.section_stack do
+    local section = line.section_stack[i]
+    if not section.expanded then
+      return false
+    end
+  end
+  return true
+end
+
+function log_browser.left_margin(State, line)
+  return State.left + #line.section_stack*Section_border_padding_horizontal
+end
+
+function log_browser.right_margin(State, line)
+  return State.right - #line.section_stack*Section_border_padding_horizontal
+end
+
+function log_browser.update(State, dt)
+end
+
+function log_browser.quit(State)
+end
+
+function log_browser.mouse_pressed(State, x,y, mouse_button)
+  local line_index = log_browser.line_index(State, x,y)
+  if line_index == nil then
+    -- below lower margin
+    return
+  end
+  -- leave some space to click without focusing
+  local line = State.lines[line_index]
+  local xleft = log_browser.left_margin(State, line)
+  local xright = log_browser.right_margin(State, line)
+  if x < xleft or x > xright then
+    return
+  end
+  -- if it's a section begin/end and the section is collapsed, expand it
+  -- TODO: how to collapse?
+  if line.section_begin or line.section_end then
+    -- HACK: get section reference from next/previous line
+    local new_section
+    if line.section_begin then
+      if line_index < #State.lines then
+        local next_section_stack = State.lines[line_index+1].section_stack
+        if next_section_stack then
+          new_section = next_section_stack[#next_section_stack]
+        end
+      end
+    elseif line.section_end then
+      if line_index > 1 then
+        local previous_section_stack = State.lines[line_index-1].section_stack
+        if previous_section_stack then
+          new_section = previous_section_stack[#previous_section_stack]
+        end
+      end
+    end
+    if new_section and new_section.expanded == nil then
+      new_section.expanded = true
+      return
+    end
+  end
+  -- open appropriate file in source side
+  if line.filename ~= Editor_state.filename then
+    source.switch_to_file(line.filename)
+  end
+  -- set cursor
+  Editor_state.cursor1 = {line=line.line_number, pos=1, posB=nil}
+  -- make sure it's visible
+  -- TODO: handle extremely long lines
+  Editor_state.screen_top1.line = math.max(0, Editor_state.cursor1.line-5)
+  -- show cursor
+  Focus = 'edit'
+  -- expand B side
+  Editor_state.expanded = true
+end
+
+function log_browser.line_index(State, mx,my)
+  -- duplicate some logic from log_browser.draw
+  local y = State.top
+  for line_index = State.screen_top1.line,#State.lines do
+    local line = State.lines[line_index]
+    if should_show(line) then
+      y = y + log_browser.height(State, line_index)
+      if my < y then
+        return line_index
+      end
+      if y > App.screen.height then break end
+    end
+  end
+end
+
+function log_browser.mouse_released(State, x,y, mouse_button)
+end
+
+function log_browser.textinput(State, t)
+end
+
+function log_browser.keychord_pressed(State, chord, key)
+  -- move
+  if chord == 'up' then
+    while State.screen_top1.line > 1 do
+      State.screen_top1.line = State.screen_top1.line-1
+      if should_show(State.lines[State.screen_top1.line]) then
+        break
+      end
+    end
+  elseif chord == 'down' then
+    while State.screen_top1.line < #State.lines do
+      State.screen_top1.line = State.screen_top1.line+1
+      if should_show(State.lines[State.screen_top1.line]) then
+        break
+      end
+    end
+  elseif chord == 'pageup' then
+    local y = 0
+    while State.screen_top1.line > 1 and y < App.screen.height - 100 do
+      State.screen_top1.line = State.screen_top1.line - 1
+      if should_show(State.lines[State.screen_top1.line]) then
+        y = y + log_browser.height(State, State.screen_top1.line)
+      end
+    end
+  elseif chord == 'pagedown' then
+    local y = 0
+    while State.screen_top1.line < #State.lines and y < App.screen.height - 100 do
+      if should_show(State.lines[State.screen_top1.line]) then
+        y = y + log_browser.height(State, State.screen_top1.line)
+      end
+      State.screen_top1.line = State.screen_top1.line + 1
+    end
+  end
+end
+
+function log_browser.height(State, line_index)
+  local line = State.lines[line_index]
+  if line.data == nil then
+    -- section header
+    return State.line_height
+  elseif type(line.data) == 'string' then
+    return State.line_height
+  else
+    if line.height == nil then
+--?       print('nil line height! rendering off screen to calculate')
+      line.height = log_render[line.data.name](line.data, State.left, App.screen.height, State.right-State.left)
+    end
+    return line.height
+  end
+end
+
+function log_browser.keyreleased(State, key, scancode)
+end
diff --git a/main.lua b/main.lua
index a41d93b..e3f1d93 100644
--- a/main.lua
+++ b/main.lua
@@ -1,217 +1,260 @@
-utf8 = require 'utf8'
-
-require 'app'
-require 'test'
+-- Entrypoint for the app. You can edit this file from within the app if
+-- you're careful.
 
-require 'keychord'
-require 'button'
+-- files that come with LÖVE; we can't edit those from within the app
+utf8 = require 'utf8'
 
-require 'main_tests'
+function load_file_from_source_or_save_directory(filename)
+  local contents = love.filesystem.read(filename)
+  local code, err = loadstring(contents, filename)
+  if code == nil then
+    error(err)
+  end
+  return code()
+end
 
--- delegate most business logic to a layer that can be reused by other projects
-require 'edit'
-Editor_state = {}
+json = load_file_from_source_or_save_directory('json.lua')
 
--- called both in tests and real run
-function App.initialize_globals()
-  -- tests currently mostly clear their own state
+load_file_from_source_or_save_directory('app.lua')
+load_file_from_source_or_save_directory('test.lua')
 
-  -- a few text objects we can avoid recomputing unless the font changes
-  Text_cache = {}
+load_file_from_source_or_save_directory('keychord.lua')
+load_file_from_source_or_save_directory('button.lua')
 
-  -- blinking cursor
-  Cursor_time = 0
-
-  -- for hysteresis in a few places
-  Last_resize_time = App.getTime()
-  Last_focus_time = App.getTime()  -- https://love2d.org/forums/viewtopic.php?p=249700
-end
-
--- called only for real run
-function App.initialize(arg)
-  love.keyboard.setTextInput(true)  -- bring up keyboard on touch screen
-  love.keyboard.setKeyRepeat(true)
-
-  love.graphics.setBackgroundColor(1,1,1)
+-- both sides require (different parts of) the logging framework
+load_file_from_source_or_save_directory('log.lua')
 
+-- but some files we want to only load sometimes
+function App.load()
   if love.filesystem.getInfo('config') then
-    load_settings()
-  else
-    initialize_default_settings()
-  end
-
-  if #arg > 0 then
-    Editor_state.filename = arg[1]
-    load_from_disk(Editor_state)
-    Text.redraw_all(Editor_state)
-    Editor_state.screen_top1 = {line=1, pos=1}
-    Editor_state.cursor1 = {line=1, pos=1}
-    edit.fixup_cursor(Editor_state)
-  else
-    load_from_disk(Editor_state)
-    Text.redraw_all(Editor_state)
-    if Editor_state.cursor1.line > #Editor_state.lines or Editor_state.lines[Editor_state.cursor1.line].mode ~= 'text' then
-      edit.fixup_cursor(Editor_state)
-    end
+    Settings = json.decode(love.filesystem.read('config'))
+    Current_app = Settings.current_app
   end
-  love.window.setTitle('lines.love - '..Editor_state.filename)
 
-  if #arg > 1 then
-    print('ignoring commandline args after '..arg[1])
+  if Current_app == nil then
+    Current_app = 'run'
   end
 
-  if rawget(_G, 'jit') then
-    jit.off()
-    jit.flush()
+  if Current_app == 'run' then
+    load_file_from_source_or_save_directory('file.lua')
+    load_file_from_source_or_save_directory('run.lua')
+      load_file_from_source_or_save_directory('edit.lua')
+      load_file_from_source_or_save_directory('text.lua')
+        load_file_from_source_or_save_directory('search.lua')
+        load_file_from_source_or_save_directory('select.lua')
+        load_file_from_source_or_save_directory('undo.lua')
+      load_file_from_source_or_save_directory('icons.lua')
+      load_file_from_source_or_save_directory('text_tests.lua')
+    load_file_from_source_or_save_directory('run_tests.lua')
+    load_file_from_source_or_save_directory('drawing.lua')
+      load_file_from_source_or_save_directory('geom.lua')
+      load_file_from_source_or_save_directory('help.lua')
+    load_file_from_source_or_save_directory('drawing_tests.lua')
+  else
+    load_file_from_source_or_save_directory('source_file.lua')
+    load_file_from_source_or_save_directory('source.lua')
+      load_file_from_source_or_save_directory('commands.lua')
+      load_file_from_source_or_save_directory('source_edit.lua')
+      load_file_from_source_or_save_directory('log_browser.lua')
+      load_file_from_source_or_save_directory('source_text.lua')
+        load_file_from_source_or_save_directory('search.lua')
+        load_file_from_source_or_save_directory('select.lua')
+        load_file_from_source_or_save_directory('source_undo.lua')
+        load_file_from_source_or_save_directory('colorize.lua')
+      load_file_from_source_or_save_directory('source_text_tests.lua')
+    load_file_from_source_or_save_directory('source_tests.lua')
   end
 end
 
-function load_settings()
-  local settings = json.decode(love.filesystem.read('config'))
-  love.graphics.setFont(love.graphics.newFont(settings.font_height))
-  -- maximize window to determine maximum allowable dimensions
-  App.screen.width, App.screen.height, App.screen.flags = love.window.getMode()
-  -- set up desired window dimensions
-  love.window.setPosition(settings.x, settings.y, settings.displayindex)
-  App.screen.flags.resizable = true
-  App.screen.flags.minwidth = math.min(App.screen.width, 200)
-  App.screen.flags.minheight = math.min(App.screen.width, 200)
-  App.screen.width, App.screen.height = settings.width, settings.height
-  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
-  Editor_state = edit.initialize_state(Margin_top, Margin_left, App.screen.width-Margin_right, settings.font_height, math.floor(settings.font_height*1.3))
-  Editor_state.filename = settings.filename
-  Editor_state.screen_top1 = settings.screen_top
-  Editor_state.cursor1 = settings.cursor
-end
+function App.initialize_globals()
+  if Current_app == 'run' then
+    run.initialize_globals()
+  elseif Current_app == 'source' then
+    source.initialize_globals()
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 
-function initialize_default_settings()
-  local font_height = 20
-  love.graphics.setFont(love.graphics.newFont(font_height))
-  local em = App.newText(love.graphics.getFont(), 'm')
-  initialize_window_geometry(App.width(em))
-  Editor_state = edit.initialize_state(Margin_top, Margin_left, App.screen.width-Margin_right)
-  Editor_state.font_height = font_height
-  Editor_state.line_height = math.floor(font_height*1.3)
-  Editor_state.em = em
+  -- for hysteresis in a few places
+  Last_focus_time = App.getTime()  -- https://love2d.org/forums/viewtopic.php?p=249700
+  Last_resize_time = App.getTime()
 end
 
-function initialize_window_geometry(em_width)
-  -- maximize window
-  love.window.setMode(0, 0)  -- maximize
-  App.screen.width, App.screen.height, App.screen.flags = love.window.getMode()
-  -- shrink height slightly to account for window decoration
-  App.screen.height = App.screen.height-100
-  App.screen.width = 40*em_width
-  App.screen.flags.resizable = true
-  App.screen.flags.minwidth = math.min(App.screen.width, 200)
-  App.screen.flags.minheight = math.min(App.screen.width, 200)
-  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+function App.initialize(arg)
+  if Current_app == 'run' then
+    run.initialize(arg)
+  elseif Current_app == 'source' then
+    source.initialize(arg)
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
+  love.window.setTitle('text.love - '..Current_app)
 end
 
-function App.resize(w, h)
---?   print(("Window resized to width: %d and height: %d."):format(w, h))
-  App.screen.width, App.screen.height = w, h
-  Text.redraw_all(Editor_state)
-  Editor_state.selection1 = {}  -- no support for shift drag while we're resizing
-  Editor_state.right = App.screen.width-Margin_right
-  Editor_state.width = Editor_state.right-Editor_state.left
-  Text.tweak_screen_top_and_cursor(Editor_state, Editor_state.left, Editor_state.right)
+function App.resize(w,h)
+  if Current_app == 'run' then
+    if run.resize then run.resize(w,h) end
+  elseif Current_app == 'source' then
+    if source.resize then source.resize(w,h) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
   Last_resize_time = App.getTime()
 end
 
 function App.filedropped(file)
-  -- first make sure to save edits on any existing file
-  if Editor_state.next_save then
-    save_to_disk(Editor_state)
-  end
-  -- clear the slate for the new file
-  App.initialize_globals()
-  Editor_state.filename = file:getFilename()
-  file:open('r')
-  Editor_state.lines = load_from_file(file)
-  file:close()
-  Text.redraw_all(Editor_state)
-  edit.fixup_cursor(Editor_state)
-  love.window.setTitle('lines.love - '..Editor_state.filename)
+  if Current_app == 'run' then
+    if run.filedropped then run.filedropped(file) end
+  elseif Current_app == 'source' then
+    if source.filedropped then source.filedropped(file) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
+  love.window.setTitle('text.love - '..Current_app)
+end
+
+function App.focus(in_focus)
+  if in_focus then
+    Last_focus_time = App.getTime()
+  end
+  if Current_app == 'run' then
+    if run.focus then run.focus(in_focus) end
+  elseif Current_app == 'source' then
+    if source.focus then source.focus(in_focus) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 end
 
 function App.draw()
-  edit.draw(Editor_state)
+  if Current_app == 'run' then
+    run.draw()
+  elseif Current_app == 'source' then
+    source.draw()
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 end
 
 function App.update(dt)
-  Cursor_time = Cursor_time + dt
   -- some hysteresis while resizing
   if App.getTime() < Last_resize_time + 0.1 then
     return
   end
-  edit.update(Editor_state, dt)
-end
-
-function love.quit()
-  edit.quit(Editor_state)
-  -- save some important settings
-  local x,y,displayindex = love.window.getPosition()
-  local filename = Editor_state.filename
-  if filename:sub(1,1) ~= '/' then
-    filename = love.filesystem.getWorkingDirectory()..'/'..filename  -- '/' should work even on Windows
-  end
-  local settings = {
-    x=x, y=y, displayindex=displayindex,
-    width=App.screen.width, height=App.screen.height,
-    font_height=Editor_state.font_height,
-    filename=filename,
-    screen_top=Editor_state.screen_top1, cursor=Editor_state.cursor1}
-  love.filesystem.write('config', json.encode(settings))
-end
-
-function App.mousepressed(x,y, mouse_button)
-  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
-  return edit.mouse_pressed(Editor_state, x,y, mouse_button)
-end
-
-function App.mousereleased(x,y, mouse_button)
-  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
-  return edit.mouse_released(Editor_state, x,y, mouse_button)
+  --
+  if Current_app == 'run' then
+    run.update(dt)
+  elseif Current_app == 'source' then
+    source.update(dt)
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 end
 
-function App.focus(in_focus)
-  if in_focus then
-    Last_focus_time = App.getTime()
+function App.keychord_pressed(chord, key)
+  -- ignore events for some time after window in focus (mostly alt-tab)
+  if App.getTime() < Last_focus_time + 0.01 then
+    return
+  end
+  --
+  if chord == 'C-e' then
+    -- carefully save settings
+    if Current_app == 'run' then
+      local source_settings = Settings.source
+      Settings = run.settings()
+      Settings.source = source_settings
+      if run.quit then run.quit() end
+      Current_app = 'source'
+    elseif Current_app == 'source' then
+      Settings.source = source.settings()
+      if source.quit then source.quit() end
+      Current_app = 'run'
+    else
+      assert(false, 'unknown app "'..Current_app..'"')
+    end
+    Settings.current_app = Current_app
+    love.filesystem.write('config', json.encode(Settings))
+    -- reboot
+    load_file_from_source_or_save_directory('main.lua')
+    App.undo_initialize()
+    App.run_tests_and_initialize()
+    return
+  end
+  if Current_app == 'run' then
+    if run.keychord_pressed then run.keychord_pressed(chord, key) end
+  elseif Current_app == 'source' then
+    if source.keychord_pressed then source.keychord_pressed(chord, key) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
   end
 end
 
 function App.textinput(t)
-  -- ignore events for some time after window in focus
+  -- ignore events for some time after window in focus (mostly alt-tab)
   if App.getTime() < Last_focus_time + 0.01 then
     return
   end
-  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
-  return edit.textinput(Editor_state, t)
+  --
+  if Current_app == 'run' then
+    if run.textinput then run.textinput(t) end
+  elseif Current_app == 'source' then
+    if source.textinput then source.textinput(t) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 end
 
-function App.keychord_pressed(chord, key)
-  -- ignore events for some time after window in focus
+function App.keyreleased(chord, key)
+  -- ignore events for some time after window in focus (mostly alt-tab)
   if App.getTime() < Last_focus_time + 0.01 then
     return
   end
-  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
-  return edit.keychord_pressed(Editor_state, chord, key)
+  --
+  if Current_app == 'run' then
+    if run.key_released then run.key_released(chord, key) end
+  elseif Current_app == 'source' then
+    if source.key_released then source.key_released(chord, key) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
 end
 
-function App.keyreleased(key, scancode)
-  -- ignore events for some time after window in focus
-  if App.getTime() < Last_focus_time + 0.01 then
-    return
+function App.mousepressed(x,y, mouse_button)
+--?   print('mouse press', x,y)
+  if Current_app == 'run' then
+    if run.mouse_pressed then run.mouse_pressed(x,y, mouse_button) end
+  elseif Current_app == 'source' then
+    if source.mouse_pressed then source.mouse_pressed(x,y, mouse_button) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
+  end
+end
+
+function App.mousereleased(x,y, mouse_button)
+  if Current_app == 'run' then
+    if run.mouse_released then run.mouse_released(x,y, mouse_button) end
+  elseif Current_app == 'source' then
+    if source.mouse_released then source.mouse_released(x,y, mouse_button) end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
   end
-  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
-  return edit.key_released(Editor_state, key, scancode)
 end
 
--- use this sparingly
-function to_text(s)
-  if Text_cache[s] == nil then
-    Text_cache[s] = App.newText(love.graphics.getFont(), s)
+function love.quit()
+  if Current_app == 'run' then
+    local source_settings = Settings.source
+    Settings = run.settings()
+    Settings.source = source_settings
+  else
+    Settings.source = source.settings()
+  end
+  Settings.current_app = Current_app
+  love.filesystem.write('config', json.encode(Settings))
+  if Current_app == 'run' then
+    if run.quit then run.quit() end
+  elseif Current_app == 'source' then
+    if source.quit then source.quit() end
+  else
+    assert(false, 'unknown app "'..Current_app..'"')
   end
-  return Text_cache[s]
 end
diff --git a/run.lua b/run.lua
new file mode 100644
index 0000000..bb64aa3
--- /dev/null
+++ b/run.lua
@@ -0,0 +1,182 @@
+run = {}
+
+Editor_state = {}
+
+-- called both in tests and real run
+function run.initialize_globals()
+  -- tests currently mostly clear their own state
+
+  -- a few text objects we can avoid recomputing unless the font changes
+  Text_cache = {}
+
+  -- blinking cursor
+  Cursor_time = 0
+end
+
+-- called only for real run
+function run.initialize(arg)
+  love.keyboard.setTextInput(true)  -- bring up keyboard on touch screen
+  love.keyboard.setKeyRepeat(true)
+
+  love.graphics.setBackgroundColor(1,1,1)
+
+  if Settings then
+    run.load_settings()
+  else
+    run.initialize_default_settings()
+  end
+
+  if #arg > 0 then
+    Editor_state.filename = arg[1]
+    load_from_disk(Editor_state)
+    Text.redraw_all(Editor_state)
+    Editor_state.screen_top1 = {line=1, pos=1}
+    Editor_state.cursor1 = {line=1, pos=1}
+    edit.fixup_cursor(Editor_state)
+  else
+    load_from_disk(Editor_state)
+    Text.redraw_all(Editor_state)
+    if Editor_state.cursor1.line > #Editor_state.lines or Editor_state.lines[Editor_state.cursor1.line].mode ~= 'text' then
+      edit.fixup_cursor(Editor_state)
+    end
+  end
+  love.window.setTitle('lines.love - '..Editor_state.filename)
+
+  if #arg > 1 then
+    print('ignoring commandline args after '..arg[1])
+  end
+
+  if rawget(_G, 'jit') then
+    jit.off()
+    jit.flush()
+  end
+end
+
+function run.load_settings()
+  love.graphics.setFont(love.graphics.newFont(Settings.font_height))
+  -- maximize window to determine maximum allowable dimensions
+  App.screen.width, App.screen.height, App.screen.flags = love.window.getMode()
+  -- set up desired window dimensions
+  love.window.setPosition(Settings.x, Settings.y, Settings.displayindex)
+  App.screen.flags.resizable = true
+  App.screen.flags.minwidth = math.min(App.screen.width, 200)
+  App.screen.flags.minheight = math.min(App.screen.width, 200)
+  App.screen.width, App.screen.height = Settings.width, Settings.height
+  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+  Editor_state = edit.initialize_state(Margin_top, Margin_left, App.screen.width-Margin_right, Settings.font_height, math.floor(Settings.font_height*1.3))
+  Editor_state.filename = Settings.filename
+  Editor_state.screen_top1 = Settings.screen_top
+  Editor_state.cursor1 = Settings.cursor
+end
+
+function run.initialize_default_settings()
+  local font_height = 20
+  love.graphics.setFont(love.graphics.newFont(font_height))
+  local em = App.newText(love.graphics.getFont(), 'm')
+  run.initialize_window_geometry(App.width(em))
+  Editor_state = edit.initialize_state(Margin_top, Margin_left, App.screen.width-Margin_right)
+  Editor_state.font_height = font_height
+  Editor_state.line_height = math.floor(font_height*1.3)
+  Editor_state.em = em
+  Settings = run.settings()
+end
+
+function run.initialize_window_geometry(em_width)
+  -- maximize window
+  love.window.setMode(0, 0)  -- maximize
+  App.screen.width, App.screen.height, App.screen.flags = love.window.getMode()
+  -- shrink height slightly to account for window decoration
+  App.screen.height = App.screen.height-100
+  App.screen.width = 40*em_width
+  App.screen.flags.resizable = true
+  App.screen.flags.minwidth = math.min(App.screen.width, 200)
+  App.screen.flags.minheight = math.min(App.screen.width, 200)
+  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+end
+
+function run.resize(w, h)
+--?   print(("Window resized to width: %d and height: %d."):format(w, h))
+  App.screen.width, App.screen.height = w, h
+  Text.redraw_all(Editor_state)
+  Editor_state.selection1 = {}  -- no support for shift drag while we're resizing
+  Editor_state.right = App.screen.width-Margin_right
+  Editor_state.width = Editor_state.right-Editor_state.left
+  Text.tweak_screen_top_and_cursor(Editor_state, Editor_state.left, Editor_state.right)
+end
+
+function run.filedropped(file)
+  -- first make sure to save edits on any existing file
+  if Editor_state.next_save then
+    save_to_disk(Editor_state)
+  end
+  -- clear the slate for the new file
+  App.initialize_globals()
+  Editor_state.filename = file:getFilename()
+  file:open('r')
+  Editor_state.lines = load_from_file(file)
+  file:close()
+  Text.redraw_all(Editor_state)
+  edit.fixup_cursor(Editor_state)
+  love.window.setTitle('lines.love - '..Editor_state.filename)
+end
+
+function run.draw()
+  edit.draw(Editor_state)
+end
+
+function run.update(dt)
+  Cursor_time = Cursor_time + dt
+  edit.update(Editor_state, dt)
+end
+
+function run.quit()
+  edit.quit(Editor_state)
+end
+
+function run.settings()
+  local x,y,displayindex = love.window.getPosition()
+  local filename = Editor_state.filename
+  if filename:sub(1,1) ~= '/' then
+    filename = love.filesystem.getWorkingDirectory()..'/'..filename  -- '/' should work even on Windows
+  end
+  return {
+    x=x, y=y, displayindex=displayindex,
+    width=App.screen.width, height=App.screen.height,
+    font_height=Editor_state.font_height,
+    filename=filename,
+    screen_top=Editor_state.screen_top1, cursor=Editor_state.cursor1
+  }
+end
+
+function run.mouse_pressed(x,y, mouse_button)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  return edit.mouse_pressed(Editor_state, x,y, mouse_button)
+end
+
+function run.mouse_released(x,y, mouse_button)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  return edit.mouse_released(Editor_state, x,y, mouse_button)
+end
+
+function run.textinput(t)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  return edit.textinput(Editor_state, t)
+end
+
+function run.keychord_pressed(chord, key)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  return edit.keychord_pressed(Editor_state, chord, key)
+end
+
+function run.key_released(key, scancode)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  return edit.key_released(Editor_state, key, scancode)
+end
+
+-- use this sparingly
+function to_text(s)
+  if Text_cache[s] == nil then
+    Text_cache[s] = App.newText(love.graphics.getFont(), s)
+  end
+  return Text_cache[s]
+end
diff --git a/main_tests.lua b/run_tests.lua
index 31605f0..31605f0 100644
--- a/main_tests.lua
+++ b/run_tests.lua
diff --git a/search.lua b/search.lua
index bd28d58..83545c9 100644
--- a/search.lua
+++ b/search.lua
@@ -30,8 +30,7 @@ function Text.search_next(State)
     for i=State.cursor1.line+1,#State.lines do
       pos = find(State.lines[i].data, State.search_term)
       if pos then
-        State.cursor1.line = i
-        State.cursor1.pos = pos
+        State.cursor1 = {line=i, pos=pos}
         break
       end
     end
@@ -41,8 +40,7 @@ function Text.search_next(State)
     for i=1,State.cursor1.line-1 do
       pos = find(State.lines[i].data, State.search_term)
       if pos then
-        State.cursor1.line = i
-        State.cursor1.pos = pos
+        State.cursor1 = {line=i, pos=pos}
         break
       end
     end
@@ -78,8 +76,7 @@ function Text.search_previous(State)
     for i=State.cursor1.line-1,1,-1 do
       pos = rfind(State.lines[i].data, State.search_term)
       if pos then
-        State.cursor1.line = i
-        State.cursor1.pos = pos
+        State.cursor1 = {line=i, pos=pos}
         break
       end
     end
@@ -89,8 +86,7 @@ function Text.search_previous(State)
     for i=#State.lines,State.cursor1.line+1,-1 do
       pos = rfind(State.lines[i].data, State.search_term)
       if pos then
-        State.cursor1.line = i
-        State.cursor1.pos = pos
+        State.cursor1 = {line=i, pos=pos}
         break
       end
     end
@@ -115,18 +111,18 @@ function Text.search_previous(State)
   end
 end
 
-function find(s, pat, i)
+function find(s, pat, i, plain)
   if s == nil then return end
-  return s:find(pat, i)
+  return s:find(pat, i, plain)
 end
 
-function rfind(s, pat, i)
+function rfind(s, pat, i, plain)
   if s == nil then return end
   local rs = s:reverse()
   local rpat = pat:reverse()
   if i == nil then i = #s end
   local ri = #s - i + 1
-  local rendpos = rs:find(rpat, ri)
+  local rendpos = rs:find(rpat, ri, plain)
   if rendpos == nil then return nil end
   local endpos = #s - rendpos + 1
   assert (endpos >= #pat)
diff --git a/source.lua b/source.lua
new file mode 100644
index 0000000..6f2b131
--- /dev/null
+++ b/source.lua
@@ -0,0 +1,358 @@
+source = {}
+
+Editor_state = {}
+
+-- called both in tests and real run
+function source.initialize_globals()
+  -- tests currently mostly clear their own state
+
+  Show_log_browser_side = false
+  Focus = 'edit'
+  Show_file_navigator = false
+  File_navigation = {
+    candidates = {
+      'run',
+      'run_tests',
+      'log',
+      'edit',
+      'text',
+      'search',
+      'select',
+      'undo',
+      'text_tests',
+      'file',
+      'source',
+      'source_tests',
+      'commands',
+      'log_browser',
+      'source_edit',
+      'source_text',
+      'source_undo',
+      'colorize',
+      'source_text_tests',
+      'source_file',
+      'main',
+      'button',
+      'keychord',
+      'app',
+      'test',
+      'json',
+    },
+    index = 1,
+  }
+
+  Menu_status_bar_height = nil  -- initialized below
+
+  -- a few text objects we can avoid recomputing unless the font changes
+  Text_cache = {}
+
+  -- blinking cursor
+  Cursor_time = 0
+end
+
+-- called only for real run
+function source.initialize()
+  love.keyboard.setTextInput(true)  -- bring up keyboard on touch screen
+  love.keyboard.setKeyRepeat(true)
+
+  love.graphics.setBackgroundColor(1,1,1)
+
+  if Settings and Settings.source then
+    source.load_settings()
+  else
+    source.initialize_default_settings()
+  end
+
+  source.initialize_edit_side{'run.lua'}
+  source.initialize_log_browser_side()
+
+  Menu_status_bar_height = 5 + Editor_state.line_height + 5
+  Editor_state.top = Editor_state.top + Menu_status_bar_height
+  Log_browser_state.top = Log_browser_state.top + Menu_status_bar_height
+end
+
+-- environment for a mutable file of bifolded text
+-- TODO: some initialization is also happening in load_settings/initialize_default_settings. Clean that up.
+function source.initialize_edit_side(arg)
+  if #arg > 0 then
+    Editor_state.filename = arg[1]
+    load_from_disk(Editor_state)
+    Text.redraw_all(Editor_state)
+    Editor_state.screen_top1 = {line=1, pos=1}
+    Editor_state.cursor1 = {line=1, pos=1}
+  else
+    load_from_disk(Editor_state)
+    Text.redraw_all(Editor_state)
+  end
+
+  if #arg > 1 then
+    print('ignoring commandline args after '..arg[1])
+  end
+
+  -- We currently start out with side B collapsed.
+  -- Other options:
+  --  * save all expanded state by line
+  --  * expand all if any location is in side B
+  if Editor_state.cursor1.line > #Editor_state.lines then
+    Editor_state.cursor1 = {line=1, pos=1}
+  end
+  if Editor_state.screen_top1.line > #Editor_state.lines then
+    Editor_state.screen_top1 = {line=1, pos=1}
+  end
+  edit.eradicate_locations_after_the_fold(Editor_state)
+
+  if rawget(_G, 'jit') then
+    jit.off()
+    jit.flush()
+  end
+end
+
+function source.load_settings()
+  local settings = Settings.source
+  love.graphics.setFont(love.graphics.newFont(settings.font_height))
+  -- maximize window to determine maximum allowable dimensions
+  love.window.setMode(0, 0)  -- maximize
+  Display_width, Display_height, App.screen.flags = love.window.getMode()
+  -- set up desired window dimensions
+  App.screen.flags.resizable = true
+  App.screen.flags.minwidth = math.min(Display_width, 200)
+  App.screen.flags.minheight = math.min(Display_height, 200)
+  App.screen.width, App.screen.height = settings.width, settings.height
+--?   print('setting window from settings:', App.screen.width, App.screen.height)
+  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+--?   print('loading source position', settings.x, settings.y, settings.displayindex)
+  source.set_window_position_from_settings(settings)
+  Show_log_browser_side = settings.show_log_browser_side
+  local right = App.screen.width - Margin_right
+  if Show_log_browser_side then
+    right = App.screen.width/2 - Margin_right
+  end
+  Editor_state = edit.initialize_state(Margin_top, Margin_left, right, settings.font_height, math.floor(settings.font_height*1.3))
+  Editor_state.filename = settings.filename
+  Editor_state.screen_top1 = settings.screen_top
+  Editor_state.cursor1 = settings.cursor
+end
+
+function source.set_window_position_from_settings(settings)
+  -- setPosition doesn't quite seem to do what is asked of it on Linux.
+  love.window.setPosition(settings.x, settings.y-37, settings.displayindex)
+end
+
+function source.initialize_default_settings()
+  local font_height = 20
+  love.graphics.setFont(love.graphics.newFont(font_height))
+  local em = App.newText(love.graphics.getFont(), 'm')
+  source.initialize_window_geometry(App.width(em))
+  Editor_state = edit.initialize_state(Margin_top, Margin_left, App.screen.width-Margin_right)
+  Editor_state.font_height = font_height
+  Editor_state.line_height = math.floor(font_height*1.3)
+  Editor_state.em = em
+end
+
+function source.initialize_window_geometry(em_width)
+  -- maximize window
+  love.window.setMode(0, 0)  -- maximize
+  Display_width, Display_height, App.screen.flags = love.window.getMode()
+  -- shrink height slightly to account for window decoration
+  App.screen.height = Display_height-100
+  App.screen.width = 40*em_width
+  App.screen.flags.resizable = true
+  App.screen.flags.minwidth = math.min(App.screen.width, 200)
+  App.screen.flags.minheight = math.min(App.screen.width, 200)
+  love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+  print('initializing source position')
+  if Settings == nil then Settings = {} end
+  if Settings.source == nil then Settings.source = {} end
+  Settings.source.x, Settings.source.y, Settings.source.displayindex = love.window.getPosition()
+end
+
+function source.resize(w, h)
+--?   print(("Window resized to width: %d and height: %d."):format(w, h))
+  App.screen.width, App.screen.height = w, h
+  Text.redraw_all(Editor_state)
+  Editor_state.selection1 = {}  -- no support for shift drag while we're resizing
+  if Show_log_browser_side then
+    Editor_state.right = App.screen.width/2 - Margin_right
+  else
+    Editor_state.right = App.screen.width-Margin_right
+  end
+  Log_browser_state.left = App.screen.width/2 + Margin_right
+  Log_browser_state.right = App.screen.width-Margin_right
+  Editor_state.width = Editor_state.right-Editor_state.left
+  Text.tweak_screen_top_and_cursor(Editor_state, Editor_state.left, Editor_state.right)
+--?   print('end resize')
+end
+
+function source.filedropped(file)
+  -- first make sure to save edits on any existing file
+  if Editor_state.next_save then
+    save_to_disk(Editor_state)
+  end
+  -- clear the slate for the new file
+  Editor_state.filename = file:getFilename()
+  file:open('r')
+  Editor_state.lines = load_from_file(file)
+  file:close()
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.cursor1 = {line=1, pos=1}
+end
+
+-- a copy of source.filedropped when given a filename
+function source.switch_to_file(filename)
+  -- first make sure to save edits on any existing file
+  if Editor_state.next_save then
+    save_to_disk(Editor_state)
+  end
+  -- clear the slate for the new file
+  Editor_state.filename = filename
+  load_from_disk(Editor_state)
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.cursor1 = {line=1, pos=1}
+end
+
+function source.draw()
+  source.draw_menu_bar()
+  edit.draw(Editor_state)
+  if Show_log_browser_side then
+    -- divider
+    App.color(Divider_color)
+    love.graphics.rectangle('fill', App.screen.width/2-1,Menu_status_bar_height, 3,App.screen.height)
+    --
+    log_browser.draw(Log_browser_state)
+  end
+end
+
+function source.update(dt)
+  Cursor_time = Cursor_time + dt
+  if App.mouse_x() < Editor_state.right then
+    edit.update(Editor_state, dt)
+  elseif Show_log_browser_side then
+    log_browser.update(Log_browser_state, dt)
+  end
+end
+
+function source.quit()
+  edit.quit(Editor_state)
+  log_browser.quit(Log_browser_state)
+  -- convert any bifold files here
+end
+
+function source.convert_bifold_text(infilename, outfilename)
+  local contents = love.filesystem.read(infilename)
+  contents = contents:gsub('\u{1e}', ';')
+  love.filesystem.write(outfilename, contents)
+end
+
+function source.settings()
+  if Current_app == 'source' then
+--?     print('reading source window position')
+    Settings.source.x, Settings.source.y, Settings.source.displayindex = love.window.getPosition()
+  end
+  local filename = Editor_state.filename
+  if filename:sub(1,1) ~= '/' then
+    filename = love.filesystem.getWorkingDirectory()..'/'..filename  -- '/' should work even on Windows
+  end
+--?   print('saving source settings', Settings.source.x, Settings.source.y, Settings.source.displayindex)
+  return {
+    x=Settings.source.x, y=Settings.source.y, displayindex=Settings.source.displayindex,
+    width=App.screen.width, height=App.screen.height,
+    font_height=Editor_state.font_height,
+    filename=filename,
+    screen_top=Editor_state.screen_top1, cursor=Editor_state.cursor1,
+    show_log_browser_side=Show_log_browser_side,
+    focus=Focus,
+  }
+end
+
+function source.mouse_pressed(x,y, mouse_button)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+--?   print('mouse click', x, y)
+--?   print(Editor_state.left, Editor_state.right)
+--?   print(Log_browser_state.left, Log_browser_state.right)
+  if Editor_state.left <= x and x < Editor_state.right then
+--?     print('click on edit side')
+    if Focus ~= 'edit' then
+      Focus = 'edit'
+    end
+    edit.mouse_pressed(Editor_state, x,y, mouse_button)
+  elseif Show_log_browser_side and Log_browser_state.left <= x and x < Log_browser_state.right then
+--?     print('click on log_browser side')
+    if Focus ~= 'log_browser' then
+      Focus = 'log_browser'
+    end
+    log_browser.mouse_pressed(Log_browser_state, x,y, mouse_button)
+    for _,line_cache in ipairs(Editor_state.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+  end
+end
+
+function source.mouse_released(x,y, mouse_button)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  if Focus == 'edit' then
+    return edit.mouse_released(Editor_state, x,y, mouse_button)
+  else
+    return log_browser.mouse_released(Log_browser_state, x,y, mouse_button)
+  end
+end
+
+function source.textinput(t)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  if Focus == 'edit' then
+    return edit.textinput(Editor_state, t)
+  else
+    return log_browser.textinput(Log_browser_state, t)
+  end
+end
+
+function source.keychord_pressed(chord, key)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+--?   print('source keychord')
+  if Show_file_navigator then
+    keychord_pressed_on_file_navigator(chord, key)
+    return
+  end
+  if chord == 'C-l' then
+--?     print('C-l')
+    Show_log_browser_side = not Show_log_browser_side
+    if Show_log_browser_side then
+      App.screen.width = Log_browser_state.right + Margin_right
+    else
+      App.screen.width = Editor_state.right + Margin_right
+    end
+--?     print('setting window:', App.screen.width, App.screen.height)
+    love.window.setMode(App.screen.width, App.screen.height, App.screen.flags)
+--?     print('done setting window')
+    -- try to restore position if possible
+    -- if the window gets wider the window manager may not respect this
+    source.set_window_position_from_settings(Settings.source)
+    return
+  end
+  if chord == 'C-g' then
+    Show_file_navigator = true
+    File_navigation.index = 1
+    return
+  end
+  if Focus == 'edit' then
+    return edit.keychord_pressed(Editor_state, chord, key)
+  else
+    return log_browser.keychord_pressed(Log_browser_state, chord, key)
+  end
+end
+
+function source.key_released(key, scancode)
+  Cursor_time = 0  -- ensure cursor is visible immediately after it moves
+  if Focus == 'edit' then
+    return edit.key_released(Editor_state, key, scancode)
+  else
+    return log_browser.keychord_pressed(Log_browser_state, chordkey, scancode)
+  end
+end
+
+-- use this sparingly
+function to_text(s)
+  if Text_cache[s] == nil then
+    Text_cache[s] = App.newText(love.graphics.getFont(), s)
+  end
+  return Text_cache[s]
+end
diff --git a/source_edit.lua b/source_edit.lua
new file mode 100644
index 0000000..d454467
--- /dev/null
+++ b/source_edit.lua
@@ -0,0 +1,377 @@
+-- some constants people might like to tweak
+Text_color = {r=0, g=0, b=0}
+Cursor_color = {r=1, g=0, b=0}
+Focus_stroke_color = {r=1, g=0, b=0}  -- what mouse is hovering over
+Highlight_color = {r=0.7, g=0.7, b=0.9}  -- selected text
+Fold_color = {r=0, g=0.6, b=0}
+Fold_background_color = {r=0, g=0.7, b=0}
+
+Margin_top = 15
+Margin_left = 25
+Margin_right = 25
+
+edit = {}
+
+-- run in both tests and a real run
+function edit.initialize_state(top, left, right, font_height, line_height)  -- currently always draws to bottom of screen
+  local result = {
+    -- a line of bifold text consists of an A side and an optional B side, each of which is a string
+    -- expanded: whether to show B side
+    lines = {{data='', dataB=nil, expanded=nil}},  -- array of lines
+
+    -- Lines can be too long to fit on screen, in which case they _wrap_ into
+    -- multiple _screen lines_.
+
+    -- rendering wrapped text lines needs some additional short-lived data per line:
+    --   startpos, the index of data the line starts rendering from, can only be >1 for topmost line on screen
+    --   starty, the y coord in pixels the line starts rendering from
+    --   fragments: snippets of rendered love.graphics.Text, guaranteed to not straddle screen lines
+    --   screen_line_starting_pos: optional array of grapheme indices if it wraps over more than one screen line
+    line_cache = {},
+
+    -- Given wrapping, any potential location for the text cursor can be described in two ways:
+    -- * schema 1: As a combination of line index and position within a line (in utf8 codepoint units)
+    -- * schema 2: As a combination of line index, screen line index within the line, and a position within the screen line.
+    -- Positions (and screen line indexes) can be in either the A or the B side.
+    --
+    -- Most of the time we'll only persist positions in schema 1, translating to
+    -- schema 2 when that's convenient.
+    --
+    -- Make sure these coordinates are never aliased, so that changing one causes
+    -- action at a distance.
+    screen_top1 = {line=1, pos=1, posB=nil},  -- position of start of screen line at top of screen
+    cursor1 = {line=1, pos=1, posB=nil},  -- position of cursor
+    screen_bottom1 = {line=1, pos=1, posB=nil},  -- position of start of screen line at bottom of screen
+
+    -- cursor coordinates in pixels
+    cursor_x = 0,
+    cursor_y = 0,
+
+    font_height = font_height,
+    line_height = line_height,
+    em = App.newText(love.graphics.getFont(), 'm'),  -- widest possible character width
+
+    top = top,
+    left = left,
+    right = right,
+    width = right-left,
+
+    filename = love.filesystem.getUserDirectory()..'/lines.txt',
+    next_save = nil,
+
+    -- undo
+    history = {},
+    next_history = 1,
+
+    -- search
+    search_term = nil,
+    search_text = nil,
+    search_backup = nil,  -- stuff to restore when cancelling search
+  }
+  return result
+end  -- App.initialize_state
+
+function edit.draw(State)
+  State.button_handlers = {}
+  App.color(Text_color)
+  assert(#State.lines == #State.line_cache)
+  if not Text.le1(State.screen_top1, State.cursor1) then
+    print(State.screen_top1.line, State.screen_top1.pos, State.screen_top1.posB, State.cursor1.line, State.cursor1.pos, State.cursor1.posB)
+    assert(false)
+  end
+  State.cursor_x = nil
+  State.cursor_y = nil
+  local y = State.top
+--?   print('== draw')
+  for line_index = State.screen_top1.line,#State.lines do
+    local line = State.lines[line_index]
+--?     print('draw:', y, line_index, line)
+    if y + State.line_height > App.screen.height then break end
+    State.screen_bottom1 = {line=line_index, pos=nil, posB=nil}
+--?     print('text.draw', y, line_index)
+    local startpos, startposB = 1, nil
+    if line_index == State.screen_top1.line then
+      if State.screen_top1.pos then
+        startpos = State.screen_top1.pos
+      else
+        startpos, startposB = nil, State.screen_top1.posB
+      end
+    end
+    y, State.screen_bottom1.pos, State.screen_bottom1.posB = Text.draw(State, line_index, y, startpos, startposB)
+    y = y + State.line_height
+--?     print('=> y', y)
+  end
+  if State.search_term then
+    Text.draw_search_bar(State)
+  end
+end
+
+function edit.update(State, dt)
+  if State.next_save and State.next_save < App.getTime() then
+    save_to_disk(State)
+    State.next_save = nil
+  end
+end
+
+function schedule_save(State)
+  if State.next_save == nil then
+    State.next_save = App.getTime() + 3  -- short enough that you're likely to still remember what you did
+  end
+end
+
+function edit.quit(State)
+  -- make sure to save before quitting
+  if State.next_save then
+    save_to_disk(State)
+  end
+end
+
+function edit.mouse_pressed(State, x,y, mouse_button)
+  if State.search_term then return end
+--?   print('press', State.selection1.line, State.selection1.pos)
+  if mouse_press_consumed_by_any_button_handler(State, x,y, mouse_button) then
+    -- press on a button and it returned 'true' to short-circuit
+    return
+  end
+
+  for line_index,line in ipairs(State.lines) do
+    if Text.in_line(State, line_index, x,y) then
+      local pos,posB = Text.to_pos_on_line(State, line_index, x, y)
+--?       print(x,y, 'setting cursor:', line_index, pos, posB)
+      State.cursor1 = {line=line_index, pos=pos, posB=posB}
+      break
+    end
+  end
+end
+
+function edit.mouse_released(State, x,y, mouse_button)
+end
+
+function edit.textinput(State, t)
+  for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+  if State.search_term then
+    State.search_term = State.search_term..t
+    State.search_text = nil
+    Text.search_next(State)
+  else
+    Text.textinput(State, t)
+  end
+  schedule_save(State)
+end
+
+function edit.keychord_pressed(State, chord, key)
+  if State.search_term then
+    if chord == 'escape' then
+      State.search_term = nil
+      State.search_text = nil
+      State.cursor1 = State.search_backup.cursor
+      State.screen_top1 = State.search_backup.screen_top
+      State.search_backup = nil
+      Text.redraw_all(State)  -- if we're scrolling, reclaim all fragments to avoid memory leaks
+    elseif chord == 'return' then
+      State.search_term = nil
+      State.search_text = nil
+      State.search_backup = nil
+    elseif chord == 'backspace' then
+      local len = utf8.len(State.search_term)
+      local byte_offset = Text.offset(State.search_term, len)
+      State.search_term = string.sub(State.search_term, 1, byte_offset-1)
+      State.search_text = nil
+    elseif chord == 'down' then
+      if State.cursor1.pos then
+        State.cursor1.pos = State.cursor1.pos+1
+      else
+        State.cursor1.posB = State.cursor1.posB+1
+      end
+      Text.search_next(State)
+    elseif chord == 'up' then
+      Text.search_previous(State)
+    end
+    return
+  elseif chord == 'C-f' then
+    State.search_term = ''
+    State.search_backup = {
+      cursor={line=State.cursor1.line, pos=State.cursor1.pos, posB=State.cursor1.posB},
+      screen_top={line=State.screen_top1.line, pos=State.screen_top1.pos, posB=State.screen_top1.posB},
+    }
+    assert(State.search_text == nil)
+  -- bifold text
+  elseif chord == 'C-b' then
+    State.expanded = not State.expanded
+    Text.redraw_all(State)
+    if not State.expanded then
+      for _,line in ipairs(State.lines) do
+        line.expanded = nil
+      end
+      edit.eradicate_locations_after_the_fold(State)
+    end
+  elseif chord == 'C-d' then
+    if State.cursor1.posB == nil then
+      local before = snapshot(State, State.cursor1.line)
+      if State.lines[State.cursor1.line].dataB == nil then
+        State.lines[State.cursor1.line].dataB = ''
+      end
+      State.lines[State.cursor1.line].expanded = true
+      State.cursor1.pos = nil
+      State.cursor1.posB = 1
+      if Text.cursor_out_of_screen(State) 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, State.cursor1.line)})
+    end
+  -- zoom
+  elseif chord == 'C-=' then
+    edit.update_font_settings(State, State.font_height+2)
+    Text.redraw_all(State)
+  elseif chord == 'C--' then
+    edit.update_font_settings(State, State.font_height-2)
+    Text.redraw_all(State)
+  elseif chord == 'C-0' then
+    edit.update_font_settings(State, 20)
+    Text.redraw_all(State)
+  -- undo
+  elseif chord == 'C-z' then
+    for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+    local event = undo_event(State)
+    if event then
+      local src = event.before
+      State.screen_top1 = deepcopy(src.screen_top)
+      State.cursor1 = deepcopy(src.cursor)
+      patch(State.lines, event.after, event.before)
+      patch_placeholders(State.line_cache, event.after, event.before)
+      -- if we're scrolling, reclaim all fragments to avoid memory leaks
+      Text.redraw_all(State)
+      schedule_save(State)
+    end
+  elseif chord == 'C-y' then
+    for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+    local event = redo_event(State)
+    if event then
+      local src = event.after
+      State.screen_top1 = deepcopy(src.screen_top)
+      State.cursor1 = deepcopy(src.cursor)
+      patch(State.lines, event.before, event.after)
+      -- if we're scrolling, reclaim all fragments to avoid memory leaks
+      Text.redraw_all(State)
+      schedule_save(State)
+    end
+  -- clipboard
+  elseif chord == 'C-c' then
+    local s = Text.selection(State)
+    if s then
+      App.setClipboardText(s)
+    end
+  elseif chord == 'C-x' then
+    for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+    local s = Text.cut_selection(State, State.left, State.right)
+    if s then
+      App.setClipboardText(s)
+    end
+    schedule_save(State)
+  elseif chord == 'C-v' then
+    for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+    -- We don't have a good sense of when to scroll, so we'll be conservative
+    -- and sometimes scroll when we didn't quite need to.
+    local before_line = State.cursor1.line
+    local before = snapshot(State, before_line)
+    local clipboard_data = App.getClipboardText()
+    for _,code in utf8.codes(clipboard_data) do
+      local c = utf8.char(code)
+      if c == '\n' then
+        Text.insert_return(State)
+      else
+        Text.insert_at_cursor(State, c)
+      end
+    end
+    if Text.cursor_out_of_screen(State) 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)})
+  -- dispatch to text
+  else
+    for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end  -- just in case we scroll
+    Text.keychord_pressed(State, chord)
+  end
+end
+
+function edit.eradicate_locations_after_the_fold(State)
+  -- eradicate side B from any locations we track
+  if State.cursor1.posB then
+    State.cursor1.posB = nil
+    State.cursor1.pos = utf8.len(State.lines[State.cursor1.line].data)
+    State.cursor1.pos = Text.pos_at_start_of_screen_line(State, State.cursor1)
+  end
+  if State.screen_top1.posB then
+    State.screen_top1.posB = nil
+    State.screen_top1.pos = utf8.len(State.lines[State.screen_top1.line].data)
+    State.screen_top1.pos = Text.pos_at_start_of_screen_line(State, State.screen_top1)
+  end
+end
+
+function edit.key_released(State, key, scancode)
+end
+
+function edit.update_font_settings(State, font_height)
+  State.font_height = font_height
+  love.graphics.setFont(love.graphics.newFont(Editor_state.font_height))
+  State.line_height = math.floor(font_height*1.3)
+  State.em = App.newText(love.graphics.getFont(), 'm')
+  Text_cache = {}
+end
+
+--== some methods for tests
+
+Test_margin_left = 25
+
+function edit.initialize_test_state()
+  -- if you change these values, tests will start failing
+  return edit.initialize_state(
+      15,  -- top margin
+      Test_margin_left,
+      App.screen.width,  -- right margin = 0
+      14,  -- font height assuming default LÖVE font
+      15)  -- line height
+end
+
+-- all textinput events are also keypresses
+-- TODO: handle chords of multiple keys
+function edit.run_after_textinput(State, t)
+  edit.keychord_pressed(State, t)
+  edit.textinput(State, t)
+  edit.key_released(State, t)
+  App.screen.contents = {}
+  edit.draw(State)
+end
+
+-- not all keys are textinput
+function edit.run_after_keychord(State, chord)
+  edit.keychord_pressed(State, chord)
+  edit.key_released(State, chord)
+  App.screen.contents = {}
+  edit.draw(State)
+end
+
+function edit.run_after_mouse_click(State, x,y, mouse_button)
+  App.fake_mouse_press(x,y, mouse_button)
+  edit.mouse_pressed(State, x,y, mouse_button)
+  App.fake_mouse_release(x,y, mouse_button)
+  edit.mouse_released(State, x,y, mouse_button)
+  App.screen.contents = {}
+  edit.draw(State)
+end
+
+function edit.run_after_mouse_press(State, x,y, mouse_button)
+  App.fake_mouse_press(x,y, mouse_button)
+  edit.mouse_pressed(State, x,y, mouse_button)
+  App.screen.contents = {}
+  edit.draw(State)
+end
+
+function edit.run_after_mouse_release(State, x,y, mouse_button)
+  App.fake_mouse_release(x,y, mouse_button)
+  edit.mouse_released(State, x,y, mouse_button)
+  App.screen.contents = {}
+  edit.draw(State)
+end
diff --git a/source_file.lua b/source_file.lua
new file mode 100644
index 0000000..978e949
--- /dev/null
+++ b/source_file.lua
@@ -0,0 +1,89 @@
+-- primitives for saving to file and loading from file
+
+Fold = '\x1e'  -- ASCII RS (record separator)
+
+function file_exists(filename)
+  local infile = App.open_for_reading(filename)
+  if infile then
+    infile:close()
+    return true
+  else
+    return false
+  end
+end
+
+function load_from_disk(State)
+  local infile = App.open_for_reading(State.filename)
+  State.lines = load_from_file(infile)
+  if infile then infile:close() end
+end
+
+function load_from_file(infile)
+  local result = {}
+  if infile then
+    local infile_next_line = infile:lines()  -- works with both Lua files and LÖVE Files (https://www.love2d.org/wiki/File)
+    while true do
+      local line = infile_next_line()
+      if line == nil then break end
+      local line_info = {}
+      if line:find(Fold) then
+        _, _, line_info.data, line_info.dataB = line:find('([^'..Fold..']*)'..Fold..'([^'..Fold..']*)')
+      else
+        line_info.data = line
+      end
+      table.insert(result, line_info)
+    end
+  end
+  if #result == 0 then
+    table.insert(result, {data=''})
+  end
+  return result
+end
+
+function save_to_disk(State)
+  local outfile = App.open_for_writing(State.filename)
+  if outfile == nil then
+    error('failed to write to "'..State.filename..'"')
+  end
+  for _,line in ipairs(State.lines) do
+    outfile:write(line.data)
+    if line.dataB and #line.dataB > 0 then
+      outfile:write(Fold)
+      outfile:write(line.dataB)
+    end
+    outfile:write('\n')
+  end
+  outfile:close()
+end
+
+function file_exists(filename)
+  local infile = App.open_for_reading(filename)
+  if infile then
+    infile:close()
+    return true
+  else
+    return false
+  end
+end
+
+-- for tests
+function load_array(a)
+  local result = {}
+  local next_line = ipairs(a)
+  local i,line,drawing = 0, ''
+  while true do
+    i,line = next_line(a, i)
+    if i == nil then break end
+    local line_info = {}
+    if line:find(Fold) then
+      _, _, line_info.data, line_info.dataB = line:find('([^'..Fold..']*)'..Fold..'([^'..Fold..']*)')
+    else
+      line_info.data = line
+    end
+    table.insert(result, line_info)
+  end
+  if #result == 0 then
+    table.insert(result, {data=''})
+  end
+  return result
+end
diff --git a/source_tests.lua b/source_tests.lua
new file mode 100644
index 0000000..dde4ec4
--- /dev/null
+++ b/source_tests.lua
@@ -0,0 +1,77 @@
+function test_resize_window()
+  io.write('\ntest_resize_window')
+  App.screen.init{width=300, height=300}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.filename = 'foo'
+  Log_browser_state = edit.initialize_test_state()
+  check_eq(App.screen.width, 300, 'F - test_resize_window/baseline/width')
+  check_eq(App.screen.height, 300, 'F - test_resize_window/baseline/height')
+  check_eq(Editor_state.left, Test_margin_left, 'F - test_resize_window/baseline/left_margin')
+  App.resize(200, 400)
+  check_eq(App.screen.width, 200, 'F - test_resize_window/width')
+  check_eq(App.screen.height, 400, 'F - test_resize_window/height')
+  check_eq(Editor_state.left, Test_margin_left, 'F - test_resize_window/left_margin')
+  -- ugly; right margin switches from 0 after resize
+  check_eq(Editor_state.right, 200-Margin_right, 'F - test_resize_window/right_margin')
+  check_eq(Editor_state.width, 200-Test_margin_left-Margin_right, 'F - test_resize_window/drawing_width')
+  -- TODO: how to make assertions about when App.update got past the early exit?
+end
+
+function test_drop_file()
+  io.write('\ntest_drop_file')
+  App.screen.init{width=Editor_state.left+300, height=300}
+  Editor_state = edit.initialize_test_state()
+  App.filesystem['foo'] = 'abc\ndef\nghi\n'
+  local fake_dropped_file = {
+    opened = false,
+    getFilename = function(self)
+                    return 'foo'
+                  end,
+    open = function(self)
+             self.opened = true
+           end,
+    lines = function(self)
+              assert(self.opened)
+              return App.filesystem['foo']:gmatch('[^\n]+')
+            end,
+    close = function(self)
+              self.opened = false
+            end,
+  }
+  App.filedropped(fake_dropped_file)
+  check_eq(#Editor_state.lines, 3, 'F - test_drop_file/#lines')
+  check_eq(Editor_state.lines[1].data, 'abc', 'F - test_drop_file/lines:1')
+  check_eq(Editor_state.lines[2].data, 'def', 'F - test_drop_file/lines:2')
+  check_eq(Editor_state.lines[3].data, 'ghi', 'F - test_drop_file/lines:3')
+  edit.draw(Editor_state)
+end
+
+function test_drop_file_saves_previous()
+  io.write('\ntest_drop_file_saves_previous')
+  App.screen.init{width=Editor_state.left+300, height=300}
+  -- initially editing a file called foo that hasn't been saved to filesystem yet
+  Editor_state.lines = load_array{'abc', 'def'}
+  Editor_state.filename = 'foo'
+  schedule_save(Editor_state)
+  -- now drag a new file bar from the filesystem
+  App.filesystem['bar'] = 'abc\ndef\nghi\n'
+  local fake_dropped_file = {
+    opened = false,
+    getFilename = function(self)
+                    return 'bar'
+                  end,
+    open = function(self)
+             self.opened = true
+           end,
+    lines = function(self)
+              assert(self.opened)
+              return App.filesystem['bar']:gmatch('[^\n]+')
+            end,
+    close = function(self)
+              self.opened = false
+            end,
+  }
+  App.filedropped(fake_dropped_file)
+  -- filesystem now contains a file called foo
+  check_eq(App.filesystem['foo'], 'abc\ndef\n', 'F - test_drop_file_saves_previous')
+end
diff --git a/source_text.lua b/source_text.lua
new file mode 100644
index 0000000..e491dac
--- /dev/null
+++ b/source_text.lua
@@ -0,0 +1,1561 @@
+-- text editor, particularly text drawing, horizontal wrap, vertical scrolling
+Text = {}
+AB_padding = 20  -- space in pixels between A side and B side
+
+-- draw a line starting from startpos to screen at y between State.left and State.right
+-- return the final y, and pos,posB of start of final screen line drawn
+function Text.draw(State, line_index, y, startpos, startposB)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+  line_cache.starty = y
+  line_cache.startpos = startpos
+  line_cache.startposB = startposB
+  -- draw A side
+  local overflows_screen, x, pos, screen_line_starting_pos
+  if startpos then
+    overflows_screen, x, y, pos, screen_line_starting_pos = Text.draw_wrapping_line(State, line_index, State.left, y, startpos)
+    if overflows_screen then
+      return y, screen_line_starting_pos
+    end
+    if Focus == 'edit' and State.cursor1.pos then
+      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
+    end
+  else
+    x = State.left
+  end
+  -- check for B side
+--?   if line_index == 8 then print('checking for B side') end
+  if line.dataB == nil then
+    assert(y)
+    assert(screen_line_starting_pos)
+--?     if line_index == 8 then print('return 1') end
+    return y, screen_line_starting_pos
+  end
+  if not State.expanded and not line.expanded then
+    assert(y)
+    assert(screen_line_starting_pos)
+--?     if line_index == 8 then print('return 2') end
+    button(State, 'expand', {x=x+AB_padding, y=y+2, w=App.width(State.em), h=State.line_height-4, color={1,1,1},
+      icon = function(button_params)
+               App.color(Fold_background_color)
+               love.graphics.rectangle('fill', button_params.x, button_params.y, App.width(State.em), State.line_height-4, 2,2)
+             end,
+      onpress1 = function()
+                   line.expanded = true
+                 end,
+    })
+    return y, screen_line_starting_pos
+  end
+  -- draw B side
+--?   if line_index == 8 then print('drawing B side') end
+  App.color(Fold_color)
+--?   if Foo then
+--?     print('draw:', State.lines[line_index].data, "=====", State.lines[line_index].dataB, 'starting from x', x+AB_padding)
+--?   end
+  if startposB then
+    overflows_screen, x, y, pos, screen_line_starting_pos = Text.draw_wrapping_lineB(State, line_index, x,y, startposB)
+  else
+    overflows_screen, x, y, pos, screen_line_starting_pos = Text.draw_wrapping_lineB(State, line_index, x+AB_padding,y, 1)
+  end
+  if overflows_screen then
+    return y, nil, screen_line_starting_pos
+  end
+--?   if line_index == 8 then print('a') end
+  if Focus == 'edit' and State.cursor1.posB then
+--?     if line_index == 8 then print('b') end
+    if State.search_term == nil then
+--?       if line_index == 8 then print('c', State.cursor1.line, State.cursor1.posB, line_index, pos) end
+      if line_index == State.cursor1.line and State.cursor1.posB == pos then
+        Text.draw_cursor(State, x, y)
+      end
+    end
+  end
+  return y, nil, screen_line_starting_pos
+end
+
+-- Given an array of fragments, draw the subset starting from pos to screen
+-- starting from (x,y).
+-- Return:
+--  - whether we got to bottom of screen before end of line
+--  - the final (x,y)
+--  - the final pos
+--  - starting pos of the final screen line drawn
+function Text.draw_wrapping_line(State, line_index, x,y, startpos)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+--?   print('== line', line_index, '^'..line.data..'$')
+  local screen_line_starting_pos = startpos
+  Text.compute_fragments(State, line_index)
+  local pos = 1
+  initialize_color()
+  for _, f in ipairs(line_cache.fragments) do
+    App.color(Text_color)
+    local frag, frag_text = f.data, f.text
+    select_color(frag)
+    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 --[[screen filled]] true, x,y, pos, screen_line_starting_pos
+        end
+        screen_line_starting_pos = pos
+        x = State.left
+      end
+      App.screen.draw(frag_text, x,y)
+      -- render cursor if necessary
+      if State.cursor1.pos and 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
+          elseif Focus == 'edit' then
+            Text.draw_cursor(State, x+Text.x(frag, State.cursor1.pos-pos+1), y)
+            App.color(Text_color)
+          end
+        end
+      end
+      x = x + frag_width
+    end
+    pos = pos + frag_len
+  end
+  return false, x,y, pos, screen_line_starting_pos
+end
+
+function Text.draw_wrapping_lineB(State, line_index, x,y, startpos)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+  local screen_line_starting_pos = startpos
+  Text.compute_fragmentsB(State, line_index, x)
+  local pos = 1
+  for _, f in ipairs(line_cache.fragmentsB) 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 --[[screen filled]] true, x,y, pos, screen_line_starting_pos
+        end
+        screen_line_starting_pos = pos
+        x = State.left
+      end
+      App.screen.draw(frag_text, x,y)
+      -- render cursor if necessary
+      if State.cursor1.posB and line_index == State.cursor1.line then
+        if pos <= State.cursor1.posB and pos + frag_len > State.cursor1.posB then
+          if State.search_term then
+            if State.lines[State.cursor1.line].dataB:sub(State.cursor1.posB, State.cursor1.posB+utf8.len(State.search_term)-1) == State.search_term then
+              local lo_px = Text.draw_highlight(State, line, x,y, pos, State.cursor1.posB, State.cursor1.posB+utf8.len(State.search_term))
+              App.color(Fold_color)
+              love.graphics.print(State.search_term, x+lo_px,y)
+            end
+          elseif Focus == 'edit' then
+            Text.draw_cursor(State, x+Text.x(frag, State.cursor1.posB-pos+1), y)
+            App.color(Fold_color)
+          end
+        end
+      end
+      x = x + frag_width
+    end
+    pos = pos + frag_len
+  end
+  return false, x,y, pos, 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)
+  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]
+  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]
+  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)..'; frag_width: '..tostring(frag_width)..'; '..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.populate_screen_line_starting_posB(State, line_index, x)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+  if line_cache.screen_line_starting_posB then
+    return
+  end
+  -- duplicate some logic from Text.draw
+  Text.compute_fragmentsB(State, line_index, x)
+  line_cache.screen_line_starting_posB = {1}
+  local pos = 1
+  for _, f in ipairs(line_cache.fragmentsB) 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_posB, pos)
+    end
+    x = x + frag_width
+    local frag_len = utf8.len(frag)
+    pos = pos + frag_len
+  end
+end
+
+function Text.compute_fragmentsB(State, line_index, x)
+--?   print('compute_fragmentsB', line_index, 'between', x, State.right)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+  if line_cache.fragmentsB then
+    return
+  end
+  line_cache.fragmentsB = {}
+  -- try to wrap at word boundaries
+  for frag in line.dataB: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.fragmentsB, {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.fragmentsB, {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)
+  end
+  record_undo_event(State, {before=before, after=snapshot(State, State.cursor1.line)})
+end
+
+function Text.insert_at_cursor(State, t)
+  if State.cursor1.pos then
+    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
+  else
+    assert(State.cursor1.posB)
+    local byte_offset = Text.offset(State.lines[State.cursor1.line].dataB, State.cursor1.posB)
+    State.lines[State.cursor1.line].dataB = string.sub(State.lines[State.cursor1.line].dataB, 1, byte_offset-1)..t..string.sub(State.lines[State.cursor1.line].dataB, byte_offset)
+    Text.clear_screen_line_cache(State, State.cursor1.line)
+    State.cursor1.posB = State.cursor1.posB+1
+  end
+end
+
+-- Don't handle any keys here that would trigger love.textinput above.
+function Text.keychord_pressed(State, chord)
+--?   print('chord', chord)
+  --== shortcuts that mutate text
+  if chord == 'return' then
+    local before_line = State.cursor1.line
+    local before = snapshot(State, before_line)
+    Text.insert_return(State)
+    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
+    local before
+    if State.cursor1.pos and 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.posB then
+      if State.cursor1.posB > 1 then
+        before = snapshot(State, State.cursor1.line)
+        local byte_start = utf8.offset(State.lines[State.cursor1.line].dataB, State.cursor1.posB-1)
+        local byte_end = utf8.offset(State.lines[State.cursor1.line].dataB, State.cursor1.posB)
+        if byte_start then
+          if byte_end then
+            State.lines[State.cursor1.line].dataB = string.sub(State.lines[State.cursor1.line].dataB, 1, byte_start-1)..string.sub(State.lines[State.cursor1.line].dataB, byte_end)
+          else
+            State.lines[State.cursor1.line].dataB = string.sub(State.lines[State.cursor1.line].dataB, 1, byte_start-1)
+          end
+          State.cursor1.posB = State.cursor1.posB-1
+        end
+      else
+        -- refuse to delete past beginning of side B
+      end
+    elseif State.cursor1.line > 1 then
+      before = snapshot(State, State.cursor1.line-1, State.cursor1.line)
+      -- 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)
+      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
+    local before
+    if State.cursor1.posB or 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 and 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.posB then
+      if State.cursor1.posB <= utf8.len(State.lines[State.cursor1.line].dataB) then
+        local byte_start = utf8.offset(State.lines[State.cursor1.line].dataB, State.cursor1.posB)
+        local byte_end = utf8.offset(State.lines[State.cursor1.line].dataB, State.cursor1.posB+1)
+        if byte_start then
+          if byte_end then
+            State.lines[State.cursor1.line].dataB = string.sub(State.lines[State.cursor1.line].dataB, 1, byte_start-1)..string.sub(State.lines[State.cursor1.line].dataB, byte_end)
+          else
+            State.lines[State.cursor1.line].dataB = string.sub(State.lines[State.cursor1.line].dataB, 1, byte_start-1)
+          end
+          -- no change to State.cursor1.pos
+        end
+      else
+        -- refuse to delete past end of side B
+      end
+    elseif State.cursor1.line < #State.lines then
+      -- join lines
+      State.lines[State.cursor1.line].data = State.lines[State.cursor1.line].data..State.lines[State.cursor1.line+1].data
+      -- delete side B on first line
+      State.lines[State.cursor1.line].dataB = State.lines[State.cursor1.line+1].dataB
+      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)
+  elseif chord == 'right' then
+    Text.right(State)
+  elseif chord == 'S-left' then
+    Text.left(State)
+  elseif chord == 'S-right' then
+    Text.right(State)
+  -- C- hotkeys reserved for drawings, so we'll use M-
+  elseif chord == 'M-left' then
+    Text.word_left(State)
+  elseif chord == 'M-right' then
+    Text.word_right(State)
+  elseif chord == 'M-S-left' then
+    Text.word_left(State)
+  elseif chord == 'M-S-right' then
+    Text.word_right(State)
+  elseif chord == 'home' then
+    Text.start_of_line(State)
+  elseif chord == 'end' then
+    Text.end_of_line(State)
+  elseif chord == 'S-home' then
+    Text.start_of_line(State)
+  elseif chord == 'S-end' then
+    Text.end_of_line(State)
+  elseif chord == 'up' then
+    Text.up(State)
+  elseif chord == 'down' then
+    Text.down(State)
+  elseif chord == 'S-up' then
+    Text.up(State)
+  elseif chord == 'S-down' then
+    Text.down(State)
+  elseif chord == 'pageup' then
+    Text.pageup(State)
+  elseif chord == 'pagedown' then
+    Text.pagedown(State)
+  elseif chord == 'S-pageup' then
+    Text.pageup(State)
+  elseif chord == 'S-pagedown' then
+    Text.pagedown(State)
+  end
+end
+
+function Text.insert_return(State)
+  if State.cursor1.pos then
+    -- when inserting a newline, move any B side to the new line
+    local byte_offset = Text.offset(State.lines[State.cursor1.line].data, State.cursor1.pos)
+    table.insert(State.lines, State.cursor1.line+1, {data=string.sub(State.lines[State.cursor1.line].data, byte_offset), dataB=State.lines[State.cursor1.line].dataB})
+    table.insert(State.line_cache, State.cursor1.line+1, {})
+    State.lines[State.cursor1.line].data = string.sub(State.lines[State.cursor1.line].data, 1, byte_offset-1)
+    State.lines[State.cursor1.line].dataB = nil
+    Text.clear_screen_line_cache(State, State.cursor1.line)
+    State.cursor1 = {line=State.cursor1.line+1, pos=1}
+  else
+    -- disable enter when cursor is on the B side
+  end
+end
+
+function Text.pageup(State)
+--?   print('pageup')
+  -- duplicate some logic from love.draw
+  local top2 = Text.to2(State, State.screen_top1)
+--?   print(App.screen.height)
+  local y = App.screen.height - State.line_height
+  while y >= State.top do
+--?     print(y, top2.line, top2.screen_line, top2.screen_pos)
+    if State.screen_top1.line == 1 and State.screen_top1.pos and State.screen_top1.pos == 1 then break end
+    y = y - State.line_height
+    top2 = Text.previous_screen_line(State, top2)
+  end
+  State.screen_top1 = Text.to1(State, top2)
+  State.cursor1 = {line=State.screen_top1.line, pos=State.screen_top1.pos, posB=State.screen_top1.posB}
+  Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary(State)
+--?   print(State.cursor1.line, State.cursor1.pos, State.screen_top1.line, State.screen_top1.pos)
+--?   print('pageup end')
+end
+
+function Text.pagedown(State)
+--?   print('pagedown')
+  local bot2 = Text.to2(State, State.screen_bottom1)
+  local new_top1 = Text.to1(State, bot2)
+  if Text.lt1(State.screen_top1, new_top1) then
+    State.screen_top1 = new_top1
+  else
+    State.screen_top1 = {line=State.screen_bottom1.line, pos=State.screen_bottom1.pos}
+  end
+--?   print('setting top to', State.screen_top1.line, State.screen_top1.pos)
+  State.cursor1 = {line=State.screen_top1.line, pos=State.screen_top1.pos, posB=State.screen_top1.posB}
+  Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary(State)
+--?   print('top now', State.screen_top1.line)
+  Text.redraw_all(State)  -- if we're scrolling, reclaim all fragments to avoid memory leaks
+--?   print('pagedown end')
+end
+
+function Text.up(State)
+  if State.cursor1.pos then
+    Text.upA(State)
+  else
+    Text.upB(State)
+  end
+end
+
+function Text.upA(State)
+--?   print('up', State.cursor1.line, State.cursor1.pos, State.screen_top1.line, State.screen_top1.pos)
+  local screen_line_starting_pos, screen_line_index = Text.pos_at_start_of_screen_line(State, State.cursor1)
+  if screen_line_starting_pos == 1 then
+--?     print('cursor is at first screen line of its line')
+    -- line is done; skip to previous text line
+    if State.cursor1.line > 1 then
+--?       print('found previous text line')
+      State.cursor1 = {line=State.cursor1.line-1, pos=nil}
+      Text.populate_screen_line_starting_pos(State, State.cursor1.line)
+      -- previous text line found, pick its final screen line
+--?       print('has multiple screen lines')
+      local screen_line_starting_pos = State.line_cache[State.cursor1.line].screen_line_starting_pos
+--?       print(#screen_line_starting_pos)
+      screen_line_starting_pos = screen_line_starting_pos[#screen_line_starting_pos]
+      local screen_line_starting_byte_offset = Text.offset(State.lines[State.cursor1.line].data, screen_line_starting_pos)
+      local s = string.sub(State.lines[State.cursor1.line].data, screen_line_starting_byte_offset)
+      State.cursor1.pos = screen_line_starting_pos + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+    end
+  else
+    -- move up one screen line in current line
+    assert(screen_line_index > 1)
+    local new_screen_line_starting_pos = State.line_cache[State.cursor1.line].screen_line_starting_pos[screen_line_index-1]
+    local new_screen_line_starting_byte_offset = Text.offset(State.lines[State.cursor1.line].data, new_screen_line_starting_pos)
+    local s = string.sub(State.lines[State.cursor1.line].data, new_screen_line_starting_byte_offset)
+    State.cursor1.pos = new_screen_line_starting_pos + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+--?     print('cursor pos is now '..tostring(State.cursor1.pos))
+  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.upB(State)
+  local line_cache = State.line_cache[State.cursor1.line]
+  local screen_line_starting_posB, screen_line_indexB = Text.pos_at_start_of_screen_lineB(State, State.cursor1)
+  assert(screen_line_indexB >= 1)
+  if screen_line_indexB == 1 then
+    -- move to A side of previous line
+    if State.cursor1.line > 1 then
+      State.cursor1.line = State.cursor1.line-1
+      State.cursor1.posB = nil
+      Text.populate_screen_line_starting_pos(State, State.cursor1.line)
+      local prev_line_cache = State.line_cache[State.cursor1.line]
+      local prev_screen_line_starting_pos = prev_line_cache.screen_line_starting_pos[#prev_line_cache.screen_line_starting_pos]
+      local prev_screen_line_starting_byte_offset = Text.offset(State.lines[State.cursor1.line].data, prev_screen_line_starting_pos)
+      local s = string.sub(State.lines[State.cursor1.line].data, prev_screen_line_starting_byte_offset)
+      State.cursor1.pos = prev_screen_line_starting_pos + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+    end
+  elseif screen_line_indexB == 2 then
+    -- all-B screen-line to potentially A+B screen-line
+    local xA = Margin_left + Text.screen_line_width(State, State.cursor1.line, #line_cache.screen_line_starting_pos) + AB_padding
+    if State.cursor_x < xA then
+      State.cursor1.posB = nil
+      Text.populate_screen_line_starting_pos(State, State.cursor1.line)
+      local new_screen_line_starting_pos = line_cache.screen_line_starting_pos[#line_cache.screen_line_starting_pos]
+      local new_screen_line_starting_byte_offset = Text.offset(State.lines[State.cursor1.line].data, new_screen_line_starting_pos)
+      local s = string.sub(State.lines[State.cursor1.line].data, new_screen_line_starting_byte_offset)
+      State.cursor1.pos = new_screen_line_starting_pos + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+    else
+      Text.populate_screen_line_starting_posB(State, State.cursor1.line)
+      local new_screen_line_starting_posB = line_cache.screen_line_starting_posB[screen_line_indexB-1]
+      local new_screen_line_starting_byte_offsetB = Text.offset(State.lines[State.cursor1.line].dataB, new_screen_line_starting_posB)
+      local s = string.sub(State.lines[State.cursor1.line].dataB, new_screen_line_starting_byte_offsetB)
+      State.cursor1.posB = new_screen_line_starting_posB + Text.nearest_cursor_pos(s, State.cursor_x-xA, State.left) - 1
+    end
+  else
+    assert(screen_line_indexB > 2)
+    -- all-B screen-line to all-B screen-line
+    Text.populate_screen_line_starting_posB(State, State.cursor1.line)
+    local new_screen_line_starting_posB = line_cache.screen_line_starting_posB[screen_line_indexB-1]
+    local new_screen_line_starting_byte_offsetB = Text.offset(State.lines[State.cursor1.line].dataB, new_screen_line_starting_posB)
+    local s = string.sub(State.lines[State.cursor1.line].dataB, new_screen_line_starting_byte_offsetB)
+    State.cursor1.posB = new_screen_line_starting_posB + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+  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
+
+-- cursor on final screen line (A or B side) => goes to next screen line on A side
+-- cursor on A side => move down one screen line (A side) in current line
+-- cursor on B side => move down one screen line (B side) in current line
+function Text.down(State)
+--?   print('down', State.cursor1.line, State.cursor1.pos, State.screen_top1.line, State.screen_top1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
+  if Text.cursor_at_final_screen_line(State) then
+    -- line is done, skip to next text line
+--?     print('cursor at final screen line of its line')
+    if State.cursor1.line < #State.lines then
+      State.cursor1 = {
+        line = State.cursor1.line+1,
+        pos = Text.nearest_cursor_pos(State.lines[State.cursor1.line+1].data, State.cursor_x, State.left)
+      }
+--?       print(State.cursor1.pos)
+    end
+    if State.cursor1.line > State.screen_bottom1.line then
+--?       print('screen top before:', State.screen_top1.line, State.screen_top1.pos)
+--?       print('scroll up preserving cursor')
+      Text.snap_cursor_to_bottom_of_screen(State)
+--?       print('screen top after:', State.screen_top1.line, State.screen_top1.pos)
+    end
+  elseif State.cursor1.pos then
+    -- move down one screen line (A side) in current line
+    local scroll_down = Text.le1(State.screen_bottom1, State.cursor1)
+--?     print('cursor is NOT at final screen line of its line')
+    local screen_line_starting_pos, screen_line_index = Text.pos_at_start_of_screen_line(State, State.cursor1)
+    Text.populate_screen_line_starting_pos(State, State.cursor1.line)
+    local new_screen_line_starting_pos = State.line_cache[State.cursor1.line].screen_line_starting_pos[screen_line_index+1]
+--?     print('switching pos of screen line at cursor from '..tostring(screen_line_starting_pos)..' to '..tostring(new_screen_line_starting_pos))
+    local new_screen_line_starting_byte_offset = Text.offset(State.lines[State.cursor1.line].data, new_screen_line_starting_pos)
+    local s = string.sub(State.lines[State.cursor1.line].data, new_screen_line_starting_byte_offset)
+    State.cursor1.pos = new_screen_line_starting_pos + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+--?     print('cursor pos is now', State.cursor1.line, State.cursor1.pos)
+    if scroll_down then
+--?       print('scroll up preserving cursor')
+      Text.snap_cursor_to_bottom_of_screen(State)
+--?       print('screen top after:', State.screen_top1.line, State.screen_top1.pos)
+    end
+  else
+    -- move down one screen line (B side) in current line
+    local scroll_down = false
+    if Text.le1(State.screen_bottom1, State.cursor1) then
+      scroll_down = true
+    end
+    local cursor_line = State.lines[State.cursor1.line]
+    local cursor_line_cache = State.line_cache[State.cursor1.line]
+    local cursor2 = Text.to2(State, State.cursor1)
+    assert(cursor2.screen_lineB < #cursor_line_cache.screen_line_starting_posB)
+    local screen_line_starting_posB, screen_line_indexB = Text.pos_at_start_of_screen_lineB(State, State.cursor1)
+    Text.populate_screen_line_starting_posB(State, State.cursor1.line)
+    local new_screen_line_starting_posB = cursor_line_cache.screen_line_starting_posB[screen_line_indexB+1]
+    local new_screen_line_starting_byte_offsetB = Text.offset(cursor_line.dataB, new_screen_line_starting_posB)
+    local s = string.sub(cursor_line.dataB, new_screen_line_starting_byte_offsetB)
+    State.cursor1.posB = new_screen_line_starting_posB + Text.nearest_cursor_pos(s, State.cursor_x, State.left) - 1
+    if scroll_down then
+      Text.snap_cursor_to_bottom_of_screen(State)
+    end
+  end
+--?   print('=>', State.cursor1.line, State.cursor1.pos, State.screen_top1.line, State.screen_top1.pos, State.screen_bottom1.line, State.screen_bottom1.pos)
+end
+
+function Text.start_of_line(State)
+  if State.cursor1.pos then
+    State.cursor1.pos = 1
+  else
+    State.cursor1.posB = 1
+  end
+  if Text.lt1(State.cursor1, State.screen_top1) then
+    State.screen_top1 = {line=State.cursor1.line, pos=1}  -- copy
+  end
+end
+
+function Text.end_of_line(State)
+  if State.cursor1.pos then
+    State.cursor1.pos = utf8.len(State.lines[State.cursor1.line].data) + 1
+  else
+    State.cursor1.posB = utf8.len(State.lines[State.cursor1.line].dataB) + 1
+  end
+  if Text.cursor_out_of_screen(State) then
+    Text.snap_cursor_to_bottom_of_screen(State)
+  end
+end
+
+function Text.word_left(State)
+  -- we can cross the fold, so check side A/B one level down
+  Text.skip_whitespace_left(State)
+  Text.left(State)
+  Text.skip_non_whitespace_left(State)
+end
+
+function Text.word_right(State)
+  -- we can cross the fold, so check side A/B one level down
+  Text.skip_whitespace_right(State)
+  Text.right(State)
+  Text.skip_non_whitespace_right(State)
+  if Text.cursor_out_of_screen(State) then
+    Text.snap_cursor_to_bottom_of_screen(State)
+  end
+end
+
+function Text.skip_whitespace_left(State)
+  if State.cursor1.pos then
+    Text.skip_whitespace_leftA(State)
+  else
+    Text.skip_whitespace_leftB(State)
+  end
+end
+
+function Text.skip_non_whitespace_left(State)
+  if State.cursor1.pos then
+    Text.skip_non_whitespace_leftA(State)
+  else
+    Text.skip_non_whitespace_leftB(State)
+  end
+end
+
+function Text.skip_whitespace_leftA(State)
+  while true do
+    if State.cursor1.pos == 1 then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].data, State.cursor1.pos-1, '%S') then
+      break
+    end
+    Text.left(State)
+  end
+end
+
+function Text.skip_whitespace_leftB(State)
+  while true do
+    if State.cursor1.posB == 1 then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].dataB, State.cursor1.posB-1, '%S') then
+      break
+    end
+    Text.left(State)
+  end
+end
+
+function Text.skip_non_whitespace_leftA(State)
+  while true do
+    if State.cursor1.pos == 1 then
+      break
+    end
+    assert(State.cursor1.pos > 1)
+    if Text.match(State.lines[State.cursor1.line].data, State.cursor1.pos-1, '%s') then
+      break
+    end
+    Text.left(State)
+  end
+end
+
+function Text.skip_non_whitespace_leftB(State)
+  while true do
+    if State.cursor1.posB == 1 then
+      break
+    end
+    assert(State.cursor1.posB > 1)
+    if Text.match(State.lines[State.cursor1.line].dataB, State.cursor1.posB-1, '%s') then
+      break
+    end
+    Text.left(State)
+  end
+end
+
+function Text.skip_whitespace_right(State)
+  if State.cursor1.pos then
+    Text.skip_whitespace_rightA(State)
+  else
+    Text.skip_whitespace_rightB(State)
+  end
+end
+
+function Text.skip_non_whitespace_right(State)
+  if State.cursor1.pos then
+    Text.skip_non_whitespace_rightA(State)
+  else
+    Text.skip_non_whitespace_rightB(State)
+  end
+end
+
+function Text.skip_whitespace_rightA(State)
+  while true do
+    if State.cursor1.pos > utf8.len(State.lines[State.cursor1.line].data) then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].data, State.cursor1.pos, '%S') then
+      break
+    end
+    Text.right_without_scroll(State)
+  end
+end
+
+function Text.skip_whitespace_rightB(State)
+  while true do
+    if State.cursor1.posB > utf8.len(State.lines[State.cursor1.line].dataB) then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].dataB, State.cursor1.posB, '%S') then
+      break
+    end
+    Text.right_without_scroll(State)
+  end
+end
+
+function Text.skip_non_whitespace_rightA(State)
+  while true do
+    if State.cursor1.pos > utf8.len(State.lines[State.cursor1.line].data) then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].data, State.cursor1.pos, '%s') then
+      break
+    end
+    Text.right_without_scroll(State)
+  end
+end
+
+function Text.skip_non_whitespace_rightB(State)
+  while true do
+    if State.cursor1.posB > utf8.len(State.lines[State.cursor1.line].dataB) then
+      break
+    end
+    if Text.match(State.lines[State.cursor1.line].dataB, State.cursor1.posB, '%s') then
+      break
+    end
+    Text.right_without_scroll(State)
+  end
+end
+
+function Text.match(s, pos, pat)
+  local start_offset = Text.offset(s, pos)
+  assert(start_offset)
+  local end_offset = Text.offset(s, pos+1)
+  assert(end_offset > start_offset)
+  local curr = s:sub(start_offset, end_offset-1)
+  return curr:match(pat)
+end
+
+function Text.left(State)
+  if State.cursor1.pos then
+    Text.leftA(State)
+  else
+    Text.leftB(State)
+  end
+end
+
+function Text.leftA(State)
+  if State.cursor1.pos > 1 then
+    State.cursor1.pos = State.cursor1.pos-1
+  elseif State.cursor1.line > 1 then
+    State.cursor1 = {
+      line = State.cursor1.line-1,
+      pos = utf8.len(State.lines[State.cursor1.line-1].data) + 1,
+    }
+  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.leftB(State)
+  if State.cursor1.posB > 1 then
+    State.cursor1.posB = State.cursor1.posB-1
+  else
+    -- overflow back into A side
+    State.cursor1.posB = nil
+    State.cursor1.pos = utf8.len(State.lines[State.cursor1.line].data) + 1
+  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)
+  if State.cursor1.pos then
+    Text.right_without_scrollA(State)
+  else
+    Text.right_without_scrollB(State)
+  end
+end
+
+function Text.right_without_scrollA(State)
+  if State.cursor1.pos <= utf8.len(State.lines[State.cursor1.line].data) then
+    State.cursor1.pos = State.cursor1.pos+1
+  elseif State.cursor1.line <= #State.lines-1 then
+    State.cursor1 = {line=State.cursor1.line+1, pos=1}
+  end
+end
+
+function Text.right_without_scrollB(State)
+  if State.cursor1.posB <= utf8.len(State.lines[State.cursor1.line].dataB) then
+    State.cursor1.posB = State.cursor1.posB+1
+  elseif State.cursor1.line <= #State.lines-1 then
+    -- overflow back into A side
+    State.cursor1 = {line=State.cursor1.line+1, pos=1}
+  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.pos_at_start_of_screen_lineB(State, loc1)
+  Text.populate_screen_line_starting_pos(State, loc1.line)
+  local line_cache = State.line_cache[loc1.line]
+  local x = Margin_left + Text.screen_line_width(State, loc1.line, #line_cache.screen_line_starting_pos) + AB_padding
+  Text.populate_screen_line_starting_posB(State, loc1.line, x)
+  for i=#line_cache.screen_line_starting_posB,1,-1 do
+    local sposB = line_cache.screen_line_starting_posB[i]
+    if sposB <= loc1.posB then
+      return sposB,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 line = State.lines[State.cursor1.line]
+  local screen_lines = State.line_cache[State.cursor1.line].screen_line_starting_pos
+--?   print(screen_lines[#screen_lines], State.cursor1.pos)
+  if (not State.expanded and not line.expanded) or
+      line.dataB == nil then
+    return screen_lines[#screen_lines] <= State.cursor1.pos
+  end
+  if State.cursor1.pos then
+    -- ignore B side
+    return screen_lines[#screen_lines] <= State.cursor1.pos
+  end
+  assert(State.cursor1.posB)
+  local line_cache = State.line_cache[State.cursor1.line]
+  local x = Margin_left + Text.screen_line_width(State, State.cursor1.line, #line_cache.screen_line_starting_pos) + AB_padding
+  Text.populate_screen_line_starting_posB(State, State.cursor1.line, x)
+  local screen_lines = State.line_cache[State.cursor1.line].screen_line_starting_posB
+  return screen_lines[#screen_lines] <= State.cursor1.posB
+end
+
+function Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary(State)
+  if State.top > 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)
+--?   print('to2:', State.cursor1.line, State.cursor1.pos, State.cursor1.posB)
+  local top2 = Text.to2(State, State.cursor1)
+--?   print('to2: =>', top2.line, top2.screen_line, top2.screen_pos, top2.screen_lineB, top2.screen_posB)
+  -- slide to start of screen line
+  if top2.screen_pos then
+    top2.screen_pos = 1
+  else
+    assert(top2.screen_posB)
+    top2.screen_posB = 1
+  end
+--?   print('snap', State.screen_top1.line, State.screen_top1.pos, State.screen_top1.posB, State.cursor1.line, State.cursor1.pos, State.cursor1.posB, State.screen_bottom1.line, State.screen_bottom1.pos, State.screen_bottom1.posB)
+--?   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:', State.lines[top2.line].data, top2.line, top2.screen_line, top2.screen_pos, top2.screen_lineB, top2.screen_posB)
+    if top2.line == 1 and top2.screen_line == 1 then break end
+    local h = State.line_height
+    if y - h < State.top then
+      break
+    end
+    y = y - h
+    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)
+--?   print('snap =>', State.screen_top1.line, State.screen_top1.pos, State.screen_top1.posB, State.cursor1.line, State.cursor1.pos, State.cursor1.posB, State.screen_bottom1.line, State.screen_bottom1.pos, State.screen_bottom1.posB)
+  Text.redraw_all(State)  -- if we're scrolling, reclaim all fragments to avoid memory leaks
+  Foo = true
+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
+  local num_screen_lines = 0
+  if line_cache.startpos then
+    Text.populate_screen_line_starting_pos(State, line_index)
+    num_screen_lines = num_screen_lines + #line_cache.screen_line_starting_pos - Text.screen_line_index(line_cache.screen_line_starting_pos, line_cache.startpos) + 1
+  end
+--?   print('#screenlines after A', num_screen_lines)
+  if line.dataB and (State.expanded or line.expanded) then
+    local x = Margin_left + Text.screen_line_width(State, line_index, #line_cache.screen_line_starting_pos) + AB_padding
+    Text.populate_screen_line_starting_posB(State, line_index, x)
+--?     print('B:', x, #line_cache.screen_line_starting_posB)
+    if line_cache.startposB then
+      num_screen_lines = num_screen_lines + #line_cache.screen_line_starting_posB - Text.screen_line_indexB(line_cache.screen_line_starting_posB, line_cache.startposB)  -- no +1; first screen line of B side overlaps with A side
+    else
+      num_screen_lines = num_screen_lines + #line_cache.screen_line_starting_posB - Text.screen_line_indexB(line_cache.screen_line_starting_posB, 1)  -- no +1; first screen line of B side overlaps with A side
+    end
+  end
+--?   print('#screenlines after B', num_screen_lines)
+  return y < line_cache.starty + State.line_height*num_screen_lines
+end
+
+-- convert mx,my in pixels to schema-1 coordinates
+-- returns: pos, posB
+-- scenarios:
+--   line without B side
+--   line with B side collapsed
+--   line with B side expanded
+--   line starting rendering in A side (startpos ~= nil)
+--   line starting rendering in B side (startposB ~= nil)
+--   my on final screen line of A side
+--     mx to right of A side with no B side
+--     mx to right of A side but left of B side
+--     mx to right of B side
+-- preconditions:
+--  startpos xor startposB
+--  expanded -> dataB
+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
+--?   print('click', line_index, my, 'with line starting at', y, #line_cache.screen_line_starting_pos)  -- , #line_cache.screen_line_starting_posB)
+  if line_cache.startpos then
+    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)
+        local screen_line_posA = Text.nearest_cursor_pos(s, mx, State.left)
+        if line.dataB == nil then
+          -- no B side
+          return screen_line_starting_pos + screen_line_posA - 1
+        end
+        if not State.expanded and not line.expanded then
+          -- B side is not expanded
+          return screen_line_starting_pos + screen_line_posA - 1
+        end
+        local lenA = utf8.len(s)
+        if screen_line_posA < lenA then
+          -- mx is within A side
+          return screen_line_starting_pos + screen_line_posA - 1
+        end
+        local max_xA = State.left+Text.x(s, lenA+1)
+        if mx < max_xA + AB_padding then
+          -- mx is in the space between A and B side
+          return screen_line_starting_pos + screen_line_posA - 1
+        end
+        mx = mx - max_xA - AB_padding
+        local screen_line_posB = Text.nearest_cursor_pos(line.dataB, mx, --[[no left margin]] 0)
+        return nil, screen_line_posB
+      end
+      y = nexty
+    end
+  end
+  -- look in screen lines composed entirely of the B side
+  assert(State.expanded or line.expanded)
+  local start_screen_line_indexB
+  if line_cache.startposB then
+    start_screen_line_indexB = Text.screen_line_indexB(line_cache.screen_line_starting_posB, line_cache.startposB)
+  else
+    start_screen_line_indexB = 2  -- skip the first line of side B, which we checked above
+  end
+  for screen_line_indexB = start_screen_line_indexB,#line_cache.screen_line_starting_posB do
+    local screen_line_starting_posB = line_cache.screen_line_starting_posB[screen_line_indexB]
+    local screen_line_starting_byte_offsetB = Text.offset(line.dataB, screen_line_starting_posB)
+--?     print('iter2', y, screen_line_indexB, screen_line_starting_posB, string.sub(line.dataB, screen_line_starting_byte_offsetB))
+    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.)
+--?       print('aa', mx, State.left, Text.screen_line_widthB(State, line_index, screen_line_indexB))
+      if screen_line_indexB < #line_cache.screen_line_starting_posB and mx > State.left + Text.screen_line_widthB(State, line_index, screen_line_indexB) then
+--?         print('past end of non-final line; return')
+        return nil, line_cache.screen_line_starting_posB[screen_line_indexB+1]-1
+      end
+      local s = string.sub(line.dataB, screen_line_starting_byte_offsetB)
+--?       print('return', mx, Text.nearest_cursor_pos(s, mx, State.left), '=>', screen_line_starting_posB + Text.nearest_cursor_pos(s, mx, State.left) - 1)
+      return nil, screen_line_starting_posB + 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_widthB(State, line_index, i)
+  local line = State.lines[line_index]
+  local line_cache = State.line_cache[line_index]
+  local start_posB = line_cache.screen_line_starting_posB[i]
+  local start_offsetB = Text.offset(line.dataB, start_posB)
+  local screen_line
+  if i < #line_cache.screen_line_starting_posB then
+--?     print('non-final', i)
+    local past_end_posB = line_cache.screen_line_starting_posB[i+1]
+    local past_end_offsetB = Text.offset(line.dataB, past_end_posB)
+--?     print('between', start_offsetB, past_end_offsetB)
+    screen_line = string.sub(line.dataB, start_offsetB, past_end_offsetB-1)
+  else
+--?     print('final', i)
+--?     print('after', start_offsetB)
+    screen_line = string.sub(line.dataB, start_offsetB)
+  end
+  local screen_line_text = App.newText(love.graphics.getFont(), screen_line)
+--?   local result = App.width(screen_line_text)
+--?   print('=>', result)
+--?   return result
+  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
+
+function Text.screen_line_indexB(screen_line_starting_posB, posB)
+  if posB == nil then
+    return 0
+  end
+  assert(screen_line_starting_posB)
+  for i = #screen_line_starting_posB,1,-1 do
+    if screen_line_starting_posB[i] <= posB 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 loc1.pos then
+    return Text.to2A(State, loc1)
+  else
+    return Text.to2B(State, loc1)
+  end
+end
+
+function Text.to2A(State, loc1)
+  local result = {line=loc1.line}
+  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.to2B(State, loc1)
+  local result = {line=loc1.line}
+  local line_cache = State.line_cache[loc1.line]
+  Text.populate_screen_line_starting_pos(State, loc1.line)
+  local x = Margin_left + Text.screen_line_width(State, loc1.line, #line_cache.screen_line_starting_pos) + AB_padding
+  Text.populate_screen_line_starting_posB(State, loc1.line, x)
+  for i=#line_cache.screen_line_starting_posB,1,-1 do
+    local sposB = line_cache.screen_line_starting_posB[i]
+    if sposB <= loc1.posB then
+      result.screen_lineB = i
+      result.screen_posB = loc1.posB - sposB + 1
+      break
+    end
+  end
+  assert(result.screen_posB)
+  return result
+end
+
+function Text.to1(State, loc2)
+  if loc2.screen_pos then
+    return Text.to1A(State, loc2)
+  else
+    return Text.to1B(State, loc2)
+  end
+end
+
+function Text.to1A(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.to1B(State, loc2)
+  local result = {line=loc2.line, posB=loc2.screen_posB}
+  if loc2.screen_lineB > 1 then
+    result.posB = State.line_cache[loc2.line].screen_line_starting_posB[loc2.screen_lineB] + loc2.screen_posB - 1
+  end
+  return result
+end
+
+function Text.lt1(a, b)
+  if a.line < b.line then
+    return true
+  end
+  if a.line > b.line then
+    return false
+  end
+  -- A side < B side
+  if a.pos and not b.pos then
+    return true
+  end
+  if not a.pos and b.pos then
+    return false
+  end
+  if a.pos then
+    return a.pos < b.pos
+  else
+    return a.posB < b.posB
+  end
+end
+
+function Text.le1(a, b)
+  return eq(a, b) or Text.lt1(a, b)
+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_pos then
+    return Text.previous_screen_lineA(State, loc2)
+  else
+    return Text.previous_screen_lineB(State, loc2)
+  end
+end
+
+function Text.previous_screen_lineA(State, loc2)
+  if loc2.screen_line > 1 then
+--?     print('a')
+    return {line=loc2.line, screen_line=loc2.screen_line-1, screen_pos=1}
+  elseif loc2.line == 1 then
+--?     print('b')
+    return loc2
+  else
+    Text.populate_screen_line_starting_pos(State, loc2.line-1)
+    if State.lines[loc2.line-1].dataB == nil or
+        (not State.expanded and not State.lines[loc2.line-1].expanded) then
+--?       print('c1', loc2.line-1, State.lines[loc2.line-1].data, '==', State.lines[loc2.line-1].dataB, State.line_cache[loc2.line-1].fragmentsB)
+      return {line=loc2.line-1, screen_line=#State.line_cache[loc2.line-1].screen_line_starting_pos, screen_pos=1}
+    end
+    -- try to switch to B
+    local prev_line_cache = State.line_cache[loc2.line-1]
+    local x = Margin_left + Text.screen_line_width(State, loc2.line-1, #prev_line_cache.screen_line_starting_pos) + AB_padding
+    Text.populate_screen_line_starting_posB(State, loc2.line-1, x)
+    local screen_line_starting_posB = State.line_cache[loc2.line-1].screen_line_starting_posB
+--?     print('c', loc2.line-1, State.lines[loc2.line-1].data, '==', State.lines[loc2.line-1].dataB, '==', #screen_line_starting_posB, 'starting from x', x)
+    if #screen_line_starting_posB > 1 then
+--?       print('c2')
+      return {line=loc2.line-1, screen_lineB=#State.line_cache[loc2.line-1].screen_line_starting_posB, screen_posB=1}
+    else
+--?       print('c3')
+      -- if there's only one screen line, assume it overlaps with A, so remain in A
+      return {line=loc2.line-1, screen_line=#State.line_cache[loc2.line-1].screen_line_starting_pos, screen_pos=1}
+    end
+  end
+end
+
+function Text.previous_screen_lineB(State, loc2)
+  if loc2.screen_lineB > 2 then  -- first screen line of B side overlaps with A side
+    return {line=loc2.line, screen_lineB=loc2.screen_lineB-1, screen_posB=1}
+  else
+    -- switch to A side
+    -- TODO: handle case where fold lands precisely at end of a new screen-line
+    return {line=loc2.line, screen_line=#State.line_cache[loc2.line].screen_line_starting_pos, screen_pos=1}
+  end
+end
+
+-- resize helper
+function Text.tweak_screen_top_and_cursor(State)
+  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')
+      local pos,posB = Text.to_pos_on_line(State, State.screen_bottom1.line, State.right-5, App.screen.height-5)
+      State.cursor1 = {line=State.screen_bottom1.line, pos=pos, posB=posB}
+    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].fragmentsB = nil
+  State.line_cache[line_index].screen_line_starting_pos = nil
+  State.line_cache[line_index].screen_line_starting_posB = nil
+end
+
+function trim(s)
+  return s:gsub('^%s+', ''):gsub('%s+$', '')
+end
+
+function ltrim(s)
+  return s:gsub('^%s+', '')
+end
+
+function rtrim(s)
+  return s:gsub('%s+$', '')
+end
diff --git a/source_text_tests.lua b/source_text_tests.lua
new file mode 100644
index 0000000..ecffb13
--- /dev/null
+++ b/source_text_tests.lua
@@ -0,0 +1,1609 @@
+-- major tests for text editing flows
+
+function test_initial_state()
+  io.write('\ntest_initial_state')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{}
+  Text.redraw_all(Editor_state)
+  edit.draw(Editor_state)
+  check_eq(#Editor_state.lines, 1, 'F - test_initial_state/#lines')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_initial_state/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_initial_state/cursor:pos')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_initial_state/screen_top:line')
+  check_eq(Editor_state.screen_top1.pos, 1, 'F - test_initial_state/screen_top:pos')
+end
+
+function test_backspace_from_start_of_final_line()
+  io.write('\ntest_backspace_from_start_of_final_line')
+  -- display final line of text with cursor at start of it
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def'}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.cursor1 = {line=2, pos=1}
+  Text.redraw_all(Editor_state)
+  -- backspace scrolls up
+  edit.run_after_keychord(Editor_state, 'backspace')
+  check_eq(#Editor_state.lines, 1, 'F - test_backspace_from_start_of_final_line/#lines')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_backspace_from_start_of_final_line/cursor')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_backspace_from_start_of_final_line/screen_top')
+end
+
+function test_insert_first_character()
+  io.write('\ntest_insert_first_character')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{}
+  Text.redraw_all(Editor_state)
+  edit.draw(Editor_state)
+  edit.run_after_textinput(Editor_state, 'a')
+  local y = Editor_state.top
+  App.screen.check(y, 'a', 'F - test_insert_first_character/screen:1')
+end
+
+function test_press_ctrl()
+  io.write('\ntest_press_ctrl')
+  -- press ctrl while the cursor is on text
+  App.screen.init{width=50, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{''}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.run_after_keychord(Editor_state, 'C-m')
+end
+
+function test_move_left()
+  io.write('\ntest_move_left')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'a'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=2}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'left')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_move_left')
+end
+
+function test_move_right()
+  io.write('\ntest_move_right')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'a'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'right')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_move_right')
+end
+
+function test_move_left_to_previous_line()
+  io.write('\ntest_move_left_to_previous_line')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'left')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_move_left_to_previous_line/line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_move_left_to_previous_line/pos')  -- past end of line
+end
+
+function test_move_right_to_next_line()
+  io.write('\ntest_move_right_to_next_line')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=4}  -- past end of line
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'right')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_move_right_to_next_line/line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_move_right_to_next_line/pos')
+end
+
+function test_move_to_start_of_word()
+  io.write('\ntest_move_to_start_of_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=3}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_move_to_start_of_word')
+end
+
+function test_move_to_start_of_previous_word()
+  io.write('\ntest_move_to_start_of_previous_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=4}  -- at the space between words
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_move_to_start_of_previous_word')
+end
+
+function test_skip_to_previous_word()
+  io.write('\ntest_skip_to_previous_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=5}  -- at the start of second word
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_skip_to_previous_word')
+end
+
+function test_skip_past_tab_to_previous_word()
+  io.write('\ntest_skip_past_tab_to_previous_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def\tghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=10}  -- within third word
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.pos, 9, 'F - test_skip_past_tab_to_previous_word')
+end
+
+function test_skip_multiple_spaces_to_previous_word()
+  io.write('\ntest_skip_multiple_spaces_to_previous_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc  def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=6}  -- at the start of second word
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_skip_multiple_spaces_to_previous_word')
+end
+
+function test_move_to_start_of_word_on_previous_line()
+  io.write('\ntest_move_to_start_of_word_on_previous_line')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def', 'ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-left')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_move_to_start_of_word_on_previous_line/line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_move_to_start_of_word_on_previous_line/pos')
+end
+
+function test_move_past_end_of_word()
+  io.write('\ntest_move_past_end_of_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-right')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_move_past_end_of_word')
+end
+
+function test_skip_to_next_word()
+  io.write('\ntest_skip_to_next_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=4}  -- at the space between words
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-right')
+  check_eq(Editor_state.cursor1.pos, 8, 'F - test_skip_to_next_word')
+end
+
+function test_skip_past_tab_to_next_word()
+  io.write('\ntest_skip_past_tab_to_next_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc\tdef'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}  -- at the space between words
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-right')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_skip_past_tab_to_next_word')
+end
+
+function test_skip_multiple_spaces_to_next_word()
+  io.write('\ntest_skip_multiple_spaces_to_next_word')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc  def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=4}  -- at the start of second word
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-right')
+  check_eq(Editor_state.cursor1.pos, 9, 'F - test_skip_multiple_spaces_to_next_word')
+end
+
+function test_move_past_end_of_word_on_next_line()
+  io.write('\ntest_move_past_end_of_word_on_next_line')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def', 'ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=8}
+  edit.draw(Editor_state)
+  edit.run_after_keychord(Editor_state, 'M-right')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_move_past_end_of_word_on_next_line/line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_move_past_end_of_word_on_next_line/pos')
+end
+
+function test_click_with_mouse()
+  io.write('\ntest_click_with_mouse')
+  -- display two lines with cursor on one of them
+  App.screen.init{width=50, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click on the other line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  -- cursor moves
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse/cursor:line')
+end
+
+function test_click_with_mouse_to_left_of_line()
+  io.write('\ntest_click_with_mouse_to_left_of_line')
+  -- display a line with the cursor in the middle
+  App.screen.init{width=50, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=3}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click to the left of the line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left-4,Editor_state.top+5, 1)
+  -- cursor moves to start of line
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse_to_left_of_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_click_with_mouse_to_left_of_line/cursor:pos')
+end
+
+function test_click_with_mouse_takes_margins_into_account()
+  io.write('\ntest_click_with_mouse_takes_margins_into_account')
+  -- display two lines with cursor on one of them
+  App.screen.init{width=100, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.left = 50  -- occupy only right side of screen
+  Editor_state.lines = load_array{'abc', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click on the other line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  -- cursor moves
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse_takes_margins_into_account/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_click_with_mouse_takes_margins_into_account/cursor:pos')
+end
+
+function test_click_with_mouse_on_empty_line()
+  io.write('\ntest_click_with_mouse_on_empty_line')
+  -- display two lines with the first one empty
+  App.screen.init{width=50, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click on the empty line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  -- cursor moves
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse_on_empty_line/cursor')
+end
+
+function test_draw_text()
+  io.write('\ntest_draw_text')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_draw_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_draw_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_draw_text/screen:3')
+end
+
+function test_draw_wrapping_text()
+  io.write('\ntest_draw_wrapping_text')
+  App.screen.init{width=50, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'defgh', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_draw_wrapping_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'de', 'F - test_draw_wrapping_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'fgh', 'F - test_draw_wrapping_text/screen:3')
+end
+
+function test_draw_word_wrapping_text()
+  io.write('\ntest_draw_word_wrapping_text')
+  App.screen.init{width=60, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc ', 'F - test_draw_word_wrapping_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def ', 'F - test_draw_word_wrapping_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_draw_word_wrapping_text/screen:3')
+end
+
+function test_click_with_mouse_on_wrapping_line()
+  io.write('\ntest_click_with_mouse_on_wrapping_line')
+  -- display two lines with cursor on one of them
+  App.screen.init{width=50, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def ghi jkl mno pqr stu'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=20}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click on the other line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  -- cursor moves
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse_on_wrapping_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_click_with_mouse_on_wrapping_line/cursor:pos')
+end
+
+function test_click_with_mouse_on_wrapping_line_takes_margins_into_account()
+  io.write('\ntest_click_with_mouse_on_wrapping_line_takes_margins_into_account')
+  -- display two lines with cursor on one of them
+  App.screen.init{width=100, height=80}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.left = 50  -- occupy only right side of screen
+  Editor_state.lines = load_array{'abc def ghi jkl mno pqr stu'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=20}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- click on the other line
+  edit.draw(Editor_state)
+  edit.run_after_mouse_click(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  -- cursor moves
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_with_mouse_on_wrapping_line_takes_margins_into_account/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_click_with_mouse_on_wrapping_line_takes_margins_into_account/cursor:pos')
+end
+
+function test_draw_text_wrapping_within_word()
+  -- arrange a screen line that needs to be split within a word
+  io.write('\ntest_draw_text_wrapping_within_word')
+  App.screen.init{width=60, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abcd e fghijk', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abcd ', 'F - test_draw_text_wrapping_within_word/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'e fgh', 'F - test_draw_text_wrapping_within_word/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ijk', 'F - test_draw_text_wrapping_within_word/screen:3')
+end
+
+function test_draw_wrapping_text_containing_non_ascii()
+  -- draw a long line containing non-ASCII
+  io.write('\ntest_draw_wrapping_text_containing_non_ascii')
+  App.screen.init{width=60, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'madam I’m adam', 'xyz'}  -- notice the non-ASCII apostrophe
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'mad', 'F - test_draw_wrapping_text_containing_non_ascii/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'am I', 'F - test_draw_wrapping_text_containing_non_ascii/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, '’m a', 'F - test_draw_wrapping_text_containing_non_ascii/screen:3')
+end
+
+function test_click_on_wrapping_line()
+  io.write('\ntest_click_on_wrapping_line')
+  -- display a wrapping line
+  App.screen.init{width=75, height=80}
+  Editor_state = edit.initialize_test_state()
+                               --  12345678901234
+  Editor_state.lines = load_array{"madam I'm adam"}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'madam ', 'F - test_click_on_wrapping_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, "I'm ad", 'F - test_click_on_wrapping_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  -- click past end of second screen line
+  edit.run_after_mouse_click(Editor_state, App.screen.width-2,y-2, 1)
+  -- cursor moves to end of screen line
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_on_wrapping_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 12, 'F - test_click_on_wrapping_line/cursor:pos')
+end
+
+function test_click_on_wrapping_line_rendered_from_partway_at_top_of_screen()
+  io.write('\ntest_click_on_wrapping_line_rendered_from_partway_at_top_of_screen')
+  -- display a wrapping line from its second screen line
+  App.screen.init{width=75, height=80}
+  Editor_state = edit.initialize_test_state()
+                               --  12345678901234
+  Editor_state.lines = load_array{"madam I'm adam"}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=8}
+  Editor_state.screen_top1 = {line=1, pos=7}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, "I'm ad", 'F - test_click_on_wrapping_line_rendered_from_partway_at_top_of_screen/baseline/screen:2')
+  y = y + Editor_state.line_height
+  -- click past end of second screen line
+  edit.run_after_mouse_click(Editor_state, App.screen.width-2,y-2, 1)
+  -- cursor moves to end of screen line
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_click_on_wrapping_line_rendered_from_partway_at_top_of_screen/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 12, 'F - test_click_on_wrapping_line_rendered_from_partway_at_top_of_screen/cursor:pos')
+end
+
+function test_click_past_end_of_wrapping_line()
+  io.write('\ntest_click_past_end_of_wrapping_line')
+  -- display a wrapping line
+  App.screen.init{width=75, height=80}
+  Editor_state = edit.initialize_test_state()
+                               --  12345678901234
+  Editor_state.lines = load_array{"madam I'm adam"}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'madam ', 'F - test_click_past_end_of_wrapping_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, "I'm ad", 'F - test_click_past_end_of_wrapping_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'am', 'F - test_click_past_end_of_wrapping_line/baseline/screen:3')
+  y = y + Editor_state.line_height
+  -- click past the end of it
+  edit.run_after_mouse_click(Editor_state, App.screen.width-2,y-2, 1)
+  -- cursor moves to end of line
+  check_eq(Editor_state.cursor1.pos, 15, 'F - test_click_past_end_of_wrapping_line/cursor')  -- one more than the number of UTF-8 code-points
+end
+
+function test_click_past_end_of_wrapping_line_containing_non_ascii()
+  io.write('\ntest_click_past_end_of_wrapping_line_containing_non_ascii')
+  -- display a wrapping line containing non-ASCII
+  App.screen.init{width=75, height=80}
+  Editor_state = edit.initialize_test_state()
+                               --  12345678901234
+  Editor_state.lines = load_array{'madam I’m adam'}  -- notice the non-ASCII apostrophe
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'madam ', 'F - test_click_past_end_of_wrapping_line_containing_non_ascii/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'I’m ad', 'F - test_click_past_end_of_wrapping_line_containing_non_ascii/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'am', 'F - test_click_past_end_of_wrapping_line_containing_non_ascii/baseline/screen:3')
+  y = y + Editor_state.line_height
+  -- click past the end of it
+  edit.run_after_mouse_click(Editor_state, App.screen.width-2,y-2, 1)
+  -- cursor moves to end of line
+  check_eq(Editor_state.cursor1.pos, 15, 'F - test_click_past_end_of_wrapping_line_containing_non_ascii/cursor')  -- one more than the number of UTF-8 code-points
+end
+
+function test_click_past_end_of_word_wrapping_line()
+  io.write('\ntest_click_past_end_of_word_wrapping_line')
+  -- display a long line wrapping at a word boundary on a screen of more realistic length
+  App.screen.init{width=160, height=80}
+  Editor_state = edit.initialize_test_state()
+                                -- 0        1         2
+                                -- 123456789012345678901
+  Editor_state.lines = load_array{'the quick brown fox jumped over the lazy dog'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'the quick brown fox ', 'F - test_click_past_end_of_word_wrapping_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  -- click past the end of the screen line
+  edit.run_after_mouse_click(Editor_state, App.screen.width-2,y-2, 1)
+  -- cursor moves to end of screen line
+  check_eq(Editor_state.cursor1.pos, 20, 'F - test_click_past_end_of_word_wrapping_line/cursor')
+end
+
+function test_edit_wrapping_text()
+  io.write('\ntest_edit_wrapping_text')
+  App.screen.init{width=50, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=4}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  edit.run_after_textinput(Editor_state, 'g')
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_edit_wrapping_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'de', 'F - test_edit_wrapping_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'fg', 'F - test_edit_wrapping_text/screen:3')
+end
+
+function test_insert_newline()
+  io.write('\ntest_insert_newline')
+  -- display a few lines
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=2}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_insert_newline/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_insert_newline/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_insert_newline/baseline/screen:3')
+  -- hitting the enter key splits the line
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_insert_newline/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_insert_newline/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_insert_newline/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'a', 'F - test_insert_newline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'bc', 'F - test_insert_newline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_insert_newline/screen:3')
+end
+
+function test_insert_newline_at_start_of_line()
+  io.write('\ntest_insert_newline_at_start_of_line')
+  -- display a line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- hitting the enter key splits the line
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_insert_newline_at_start_of_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_insert_newline_at_start_of_line/cursor:pos')
+  check_eq(Editor_state.lines[1].data, '', 'F - test_insert_newline_at_start_of_line/data:1')
+  check_eq(Editor_state.lines[2].data, 'abc', 'F - test_insert_newline_at_start_of_line/data:2')
+end
+
+function test_insert_from_clipboard()
+  io.write('\ntest_insert_from_clipboard')
+  -- display a few lines
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=2}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_insert_from_clipboard/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_insert_from_clipboard/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_insert_from_clipboard/baseline/screen:3')
+  -- paste some text including a newline, check that new line is created
+  App.clipboard = 'xy\nz'
+  edit.run_after_keychord(Editor_state, 'C-v')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_insert_from_clipboard/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_insert_from_clipboard/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_insert_from_clipboard/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'axy', 'F - test_insert_from_clipboard/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'zbc', 'F - test_insert_from_clipboard/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_insert_from_clipboard/screen:3')
+end
+
+function test_move_cursor_using_mouse()
+  io.write('\ntest_move_cursor_using_mouse')
+  App.screen.init{width=50, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)  -- populate line_cache.starty for each line Editor_state.line_cache
+  edit.run_after_mouse_press(Editor_state, Editor_state.left+8,Editor_state.top+5, 1)
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_move_cursor_using_mouse/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_move_cursor_using_mouse/cursor:pos')
+end
+
+function test_pagedown()
+  io.write('\ntest_pagedown')
+  App.screen.init{width=120, height=45}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- initially the first two lines are displayed
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_pagedown/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_pagedown/baseline/screen:2')
+  -- after pagedown the bottom line becomes the top
+  edit.run_after_keychord(Editor_state, 'pagedown')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_pagedown/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_pagedown/cursor')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_pagedown/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_pagedown/screen:2')
+end
+
+function test_pagedown_can_start_from_middle_of_long_wrapping_line()
+  io.write('\ntest_pagedown_can_start_from_middle_of_long_wrapping_line')
+  -- draw a few lines starting from a very long wrapping line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def ghi jkl mno pqr stu vwx yza bcd efg hij', 'XYZ'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=2}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/baseline/screen:3')
+  -- after pagedown we scroll down the very long wrapping line
+  edit.run_after_keychord(Editor_state, 'pagedown')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/screen_top:line')
+  check_eq(Editor_state.screen_top1.pos, 9, 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/screen_top:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'ghi ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno ', 'F - test_pagedown_can_start_from_middle_of_long_wrapping_line/screen:3')
+end
+
+function test_pagedown_never_moves_up()
+  io.write('\ntest_pagedown_never_moves_up')
+  -- draw the final screen line of a wrapping line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=9}
+  Editor_state.screen_top1 = {line=1, pos=9}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- pagedown makes no change
+  edit.run_after_keychord(Editor_state, 'pagedown')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_pagedown_never_moves_up/screen_top:line')
+  check_eq(Editor_state.screen_top1.pos, 9, 'F - test_pagedown_never_moves_up/screen_top:pos')
+end
+
+function test_down_arrow_moves_cursor()
+  io.write('\ntest_down_arrow_moves_cursor')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- initially the first three lines are displayed
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_down_arrow_moves_cursor/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_down_arrow_moves_cursor/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_down_arrow_moves_cursor/baseline/screen:3')
+  -- after hitting the down arrow, the cursor moves down by 1 line
+  edit.run_after_keychord(Editor_state, 'down')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_down_arrow_moves_cursor/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_down_arrow_moves_cursor/cursor')
+  -- the screen is unchanged
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_down_arrow_moves_cursor/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_down_arrow_moves_cursor/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_down_arrow_moves_cursor/screen:3')
+end
+
+function test_down_arrow_scrolls_down_by_one_line()
+  io.write('\ntest_down_arrow_scrolls_down_by_one_line')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_down_arrow_scrolls_down_by_one_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_down_arrow_scrolls_down_by_one_line/baseline/screen:3')
+  -- after hitting the down arrow the screen scrolls down by one line
+  edit.run_after_keychord(Editor_state, 'down')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_down_arrow_scrolls_down_by_one_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 4, 'F - test_down_arrow_scrolls_down_by_one_line/cursor')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_down_arrow_scrolls_down_by_one_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_down_arrow_scrolls_down_by_one_line/screen:3')
+end
+
+function test_down_arrow_scrolls_down_by_one_screen_line()
+  io.write('\ntest_down_arrow_scrolls_down_by_one_screen_line')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_down_arrow_scrolls_down_by_one_screen_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_screen_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_down_arrow_scrolls_down_by_one_screen_line/baseline/screen:3')  -- line wrapping includes trailing whitespace
+  -- after hitting the down arrow the screen scrolls down by one line
+  edit.run_after_keychord(Editor_state, 'down')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_down_arrow_scrolls_down_by_one_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_down_arrow_scrolls_down_by_one_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_down_arrow_scrolls_down_by_one_screen_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_down_arrow_scrolls_down_by_one_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_down_arrow_scrolls_down_by_one_screen_line/screen:3')
+end
+
+function test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word()
+  io.write('\ntest_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghijkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghij', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/baseline/screen:3')
+  -- after hitting the down arrow the screen scrolls down by one line
+  edit.run_after_keychord(Editor_state, 'down')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghij', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'kl', 'F - test_down_arrow_scrolls_down_by_one_screen_line_after_splitting_within_word/screen:3')
+end
+
+function test_page_down_followed_by_down_arrow_does_not_scroll_screen_up()
+  io.write('\ntest_page_down_followed_by_down_arrow_does_not_scroll_screen_up')
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghijkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghij', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline/screen:3')
+  -- after hitting pagedown the screen scrolls down to start of a long line
+  edit.run_after_keychord(Editor_state, 'pagedown')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline2/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline2/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/baseline2/cursor:pos')
+  -- after hitting down arrow the screen doesn't scroll down further, and certainly doesn't scroll up
+  edit.run_after_keychord(Editor_state, 'down')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'ghij', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'kl', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_page_down_followed_by_down_arrow_does_not_scroll_screen_up/screen:3')
+end
+
+function test_up_arrow_moves_cursor()
+  io.write('\ntest_up_arrow_moves_cursor')
+  -- display the first 3 lines with the cursor on the bottom line
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_up_arrow_moves_cursor/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_up_arrow_moves_cursor/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_moves_cursor/baseline/screen:3')
+  -- after hitting the up arrow the cursor moves up by 1 line
+  edit.run_after_keychord(Editor_state, 'up')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_up_arrow_moves_cursor/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_up_arrow_moves_cursor/cursor')
+  -- the screen is unchanged
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_up_arrow_moves_cursor/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_up_arrow_moves_cursor/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_moves_cursor/screen:3')
+end
+
+function test_up_arrow_scrolls_up_by_one_line()
+  io.write('\ntest_up_arrow_scrolls_up_by_one_line')
+  -- display the lines 2/3/4 with the cursor on line 2
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_up_arrow_scrolls_up_by_one_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_scrolls_up_by_one_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_up_arrow_scrolls_up_by_one_line/baseline/screen:3')
+  -- after hitting the up arrow the screen scrolls up by one line
+  edit.run_after_keychord(Editor_state, 'up')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_up_arrow_scrolls_up_by_one_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_up_arrow_scrolls_up_by_one_line/cursor')
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_up_arrow_scrolls_up_by_one_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_up_arrow_scrolls_up_by_one_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_scrolls_up_by_one_line/screen:3')
+end
+
+function test_up_arrow_scrolls_up_by_one_screen_line()
+  io.write('\ntest_up_arrow_scrolls_up_by_one_screen_line')
+  -- display lines starting from second screen line of a line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=6}
+  Editor_state.screen_top1 = {line=3, pos=5}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_up_arrow_scrolls_up_by_one_screen_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_up_arrow_scrolls_up_by_one_screen_line/baseline/screen:2')
+  -- after hitting the up arrow the screen scrolls up to first screen line
+  edit.run_after_keychord(Editor_state, 'up')
+  y = Editor_state.top
+  App.screen.check(y, 'ghi ', 'F - test_up_arrow_scrolls_up_by_one_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_up_arrow_scrolls_up_by_one_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_up_arrow_scrolls_up_by_one_screen_line/screen:3')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_up_arrow_scrolls_up_by_one_screen_line/screen_top')
+  check_eq(Editor_state.screen_top1.pos, 1, 'F - test_up_arrow_scrolls_up_by_one_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_up_arrow_scrolls_up_by_one_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_up_arrow_scrolls_up_by_one_screen_line/cursor:pos')
+end
+
+function test_up_arrow_scrolls_up_to_final_screen_line()
+  io.write('\ntest_up_arrow_scrolls_up_to_final_screen_line')
+  -- display lines starting just after a long line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def', 'ghi', 'jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_scrolls_up_to_final_screen_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_up_arrow_scrolls_up_to_final_screen_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_up_arrow_scrolls_up_to_final_screen_line/baseline/screen:3')
+  -- after hitting the up arrow the screen scrolls up to final screen line of previous line
+  edit.run_after_keychord(Editor_state, 'up')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_up_arrow_scrolls_up_to_final_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_scrolls_up_to_final_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_up_arrow_scrolls_up_to_final_screen_line/screen:3')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_up_arrow_scrolls_up_to_final_screen_line/screen_top')
+  check_eq(Editor_state.screen_top1.pos, 5, 'F - test_up_arrow_scrolls_up_to_final_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_up_arrow_scrolls_up_to_final_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_up_arrow_scrolls_up_to_final_screen_line/cursor:pos')
+end
+
+function test_up_arrow_scrolls_up_to_empty_line()
+  io.write('\ntest_up_arrow_scrolls_up_to_empty_line')
+  -- display a screenful of text with an empty line just above it outside the screen
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'', 'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_up_arrow_scrolls_up_to_empty_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_up_arrow_scrolls_up_to_empty_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_up_arrow_scrolls_up_to_empty_line/baseline/screen:3')
+  -- after hitting the up arrow the screen scrolls up by one line
+  edit.run_after_keychord(Editor_state, 'up')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_up_arrow_scrolls_up_to_empty_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_up_arrow_scrolls_up_to_empty_line/cursor')
+  y = Editor_state.top
+  -- empty first line
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'abc', 'F - test_up_arrow_scrolls_up_to_empty_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_up_arrow_scrolls_up_to_empty_line/screen:3')
+end
+
+function test_pageup()
+  io.write('\ntest_pageup')
+  App.screen.init{width=120, height=45}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- initially the last two lines are displayed
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_pageup/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_pageup/baseline/screen:2')
+  -- after pageup the cursor goes to first line
+  edit.run_after_keychord(Editor_state, 'pageup')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_pageup/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_pageup/cursor')
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_pageup/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_pageup/screen:2')
+end
+
+function test_pageup_scrolls_up_by_screen_line()
+  io.write('\ntest_pageup_scrolls_up_by_screen_line')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def', 'ghi', 'jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'ghi', 'F - test_pageup_scrolls_up_by_screen_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_pageup_scrolls_up_by_screen_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_pageup_scrolls_up_by_screen_line/baseline/screen:3')  -- line wrapping includes trailing whitespace
+  -- after hitting the page-up key the screen scrolls up to top
+  edit.run_after_keychord(Editor_state, 'pageup')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_pageup_scrolls_up_by_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_pageup_scrolls_up_by_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_pageup_scrolls_up_by_screen_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'abc ', 'F - test_pageup_scrolls_up_by_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_pageup_scrolls_up_by_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_pageup_scrolls_up_by_screen_line/screen:3')
+end
+
+function test_pageup_scrolls_up_from_middle_screen_line()
+  io.write('\ntest_pageup_scrolls_up_from_middle_screen_line')
+  -- display a few lines starting from the middle of a line (Editor_state.cursor1.pos > 1)
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=5}
+  Editor_state.screen_top1 = {line=2, pos=5}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_pageup_scrolls_up_from_middle_screen_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_pageup_scrolls_up_from_middle_screen_line/baseline/screen:3')  -- line wrapping includes trailing whitespace
+  -- after hitting the page-up key the screen scrolls up to top
+  edit.run_after_keychord(Editor_state, 'pageup')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_pageup_scrolls_up_from_middle_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_pageup_scrolls_up_from_middle_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_pageup_scrolls_up_from_middle_screen_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'abc ', 'F - test_pageup_scrolls_up_from_middle_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_pageup_scrolls_up_from_middle_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_pageup_scrolls_up_from_middle_screen_line/screen:3')
+end
+
+function test_enter_on_bottom_line_scrolls_down()
+  io.write('\ntest_enter_on_bottom_line_scrolls_down')
+  -- display a few lines with cursor on bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=2}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_enter_on_bottom_line_scrolls_down/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_enter_on_bottom_line_scrolls_down/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_enter_on_bottom_line_scrolls_down/baseline/screen:3')
+  -- after hitting the enter key the screen scrolls down
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_enter_on_bottom_line_scrolls_down/screen_top')
+  check_eq(Editor_state.cursor1.line, 4, 'F - test_enter_on_bottom_line_scrolls_down/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_enter_on_bottom_line_scrolls_down/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_enter_on_bottom_line_scrolls_down/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'g', 'F - test_enter_on_bottom_line_scrolls_down/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'hi', 'F - test_enter_on_bottom_line_scrolls_down/screen:3')
+end
+
+function test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom()
+  io.write('\ntest_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom')
+  -- display just the bottom line on screen
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=4, pos=2}
+  Editor_state.screen_top1 = {line=4, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/baseline/screen:1')
+  -- after hitting the enter key the screen does not scroll down
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.screen_top1.line, 4, 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/screen_top')
+  check_eq(Editor_state.cursor1.line, 5, 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'j', 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'kl', 'F - test_enter_on_final_line_avoids_scrolling_down_when_not_at_bottom/screen:2')
+end
+
+function test_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom()
+  io.write('\ntest_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom')
+  -- display just an empty bottom line on screen
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', ''}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- after hitting the inserting_text key the screen does not scroll down
+  edit.run_after_textinput(Editor_state, 'a')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom/screen_top')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 2, 'F - test_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom/cursor:pos')
+  local y = Editor_state.top
+  App.screen.check(y, 'a', 'F - test_inserting_text_on_final_line_avoids_scrolling_down_when_not_at_bottom/screen:1')
+end
+
+function test_typing_on_bottom_line_scrolls_down()
+  io.write('\ntest_typing_on_bottom_line_scrolls_down')
+  -- display a few lines with cursor on bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=4}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_typing_on_bottom_line_scrolls_down/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_typing_on_bottom_line_scrolls_down/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_typing_on_bottom_line_scrolls_down/baseline/screen:3')
+  -- after typing something the line wraps and the screen scrolls down
+  edit.run_after_textinput(Editor_state, 'j')
+  edit.run_after_textinput(Editor_state, 'k')
+  edit.run_after_textinput(Editor_state, 'l')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_typing_on_bottom_line_scrolls_down/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_typing_on_bottom_line_scrolls_down/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 7, 'F - test_typing_on_bottom_line_scrolls_down/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_typing_on_bottom_line_scrolls_down/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghij', 'F - test_typing_on_bottom_line_scrolls_down/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'kl', 'F - test_typing_on_bottom_line_scrolls_down/screen:3')
+end
+
+function test_left_arrow_scrolls_up_in_wrapped_line()
+  io.write('\ntest_left_arrow_scrolls_up_in_wrapped_line')
+  -- display lines starting from second screen line of a line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=3, pos=5}
+  Editor_state.screen_bottom1 = {}
+  -- cursor is at top of screen
+  Editor_state.cursor1 = {line=3, pos=5}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_left_arrow_scrolls_up_in_wrapped_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_left_arrow_scrolls_up_in_wrapped_line/baseline/screen:2')
+  -- after hitting the left arrow the screen scrolls up to first screen line
+  edit.run_after_keychord(Editor_state, 'left')
+  y = Editor_state.top
+  App.screen.check(y, 'ghi ', 'F - test_left_arrow_scrolls_up_in_wrapped_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_left_arrow_scrolls_up_in_wrapped_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_left_arrow_scrolls_up_in_wrapped_line/screen:3')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_left_arrow_scrolls_up_in_wrapped_line/screen_top')
+  check_eq(Editor_state.screen_top1.pos, 1, 'F - test_left_arrow_scrolls_up_in_wrapped_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_left_arrow_scrolls_up_in_wrapped_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_left_arrow_scrolls_up_in_wrapped_line/cursor:pos')
+end
+
+function test_right_arrow_scrolls_down_in_wrapped_line()
+  io.write('\ntest_right_arrow_scrolls_down_in_wrapped_line')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- cursor is at bottom right of screen
+  Editor_state.cursor1 = {line=3, pos=5}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_right_arrow_scrolls_down_in_wrapped_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_right_arrow_scrolls_down_in_wrapped_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_right_arrow_scrolls_down_in_wrapped_line/baseline/screen:3')  -- line wrapping includes trailing whitespace
+  -- after hitting the right arrow the screen scrolls down by one line
+  edit.run_after_keychord(Editor_state, 'right')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_right_arrow_scrolls_down_in_wrapped_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_right_arrow_scrolls_down_in_wrapped_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 6, 'F - test_right_arrow_scrolls_down_in_wrapped_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_right_arrow_scrolls_down_in_wrapped_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_right_arrow_scrolls_down_in_wrapped_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_right_arrow_scrolls_down_in_wrapped_line/screen:3')
+end
+
+function test_home_scrolls_up_in_wrapped_line()
+  io.write('\ntest_home_scrolls_up_in_wrapped_line')
+  -- display lines starting from second screen line of a line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=3, pos=5}
+  Editor_state.screen_bottom1 = {}
+  -- cursor is at top of screen
+  Editor_state.cursor1 = {line=3, pos=5}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_home_scrolls_up_in_wrapped_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_home_scrolls_up_in_wrapped_line/baseline/screen:2')
+  -- after hitting home the screen scrolls up to first screen line
+  edit.run_after_keychord(Editor_state, 'home')
+  y = Editor_state.top
+  App.screen.check(y, 'ghi ', 'F - test_home_scrolls_up_in_wrapped_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_home_scrolls_up_in_wrapped_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_home_scrolls_up_in_wrapped_line/screen:3')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_home_scrolls_up_in_wrapped_line/screen_top')
+  check_eq(Editor_state.screen_top1.pos, 1, 'F - test_home_scrolls_up_in_wrapped_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_home_scrolls_up_in_wrapped_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_home_scrolls_up_in_wrapped_line/cursor:pos')
+end
+
+function test_end_scrolls_down_in_wrapped_line()
+  io.write('\ntest_end_scrolls_down_in_wrapped_line')
+  -- display the first three lines with the cursor on the bottom line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- cursor is at bottom right of screen
+  Editor_state.cursor1 = {line=3, pos=5}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_end_scrolls_down_in_wrapped_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_end_scrolls_down_in_wrapped_line/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_end_scrolls_down_in_wrapped_line/baseline/screen:3')  -- line wrapping includes trailing whitespace
+  -- after hitting end the screen scrolls down by one line
+  edit.run_after_keychord(Editor_state, 'end')
+  check_eq(Editor_state.screen_top1.line, 2, 'F - test_end_scrolls_down_in_wrapped_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_end_scrolls_down_in_wrapped_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 8, 'F - test_end_scrolls_down_in_wrapped_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_end_scrolls_down_in_wrapped_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi ', 'F - test_end_scrolls_down_in_wrapped_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_end_scrolls_down_in_wrapped_line/screen:3')
+end
+
+function test_position_cursor_on_recently_edited_wrapping_line()
+  -- draw a line wrapping over 2 screen lines
+  io.write('\ntest_position_cursor_on_recently_edited_wrapping_line')
+  App.screen.init{width=100, height=200}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc def ghi jkl mno pqr ', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=25}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'abc def ghi ', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline1/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl mno pqr ', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline1/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'xyz', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline1/screen:3')
+  -- add to the line until it's wrapping over 3 screen lines
+  edit.run_after_textinput(Editor_state, 's')
+  edit.run_after_textinput(Editor_state, 't')
+  edit.run_after_textinput(Editor_state, 'u')
+  check_eq(Editor_state.cursor1.pos, 28, 'F - test_position_cursor_on_recently_edited_wrapping_line/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'abc def ghi ', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline2/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl mno pqr ', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline2/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'stu', 'F - test_position_cursor_on_recently_edited_wrapping_line/baseline2/screen:3')
+  -- try to move the cursor earlier in the third screen line by clicking the mouse
+  edit.run_after_mouse_press(Editor_state, Editor_state.left+8,Editor_state.top+Editor_state.line_height*2+5, 1)
+  -- cursor should move
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_position_cursor_on_recently_edited_wrapping_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 26, 'F - test_position_cursor_on_recently_edited_wrapping_line/cursor:pos')
+end
+
+function test_backspace_can_scroll_up()
+  io.write('\ntest_backspace_can_scroll_up')
+  -- display the lines 2/3/4 with the cursor on line 2
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'jkl'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  Editor_state.screen_top1 = {line=2, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'def', 'F - test_backspace_can_scroll_up/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_backspace_can_scroll_up/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_backspace_can_scroll_up/baseline/screen:3')
+  -- after hitting backspace the screen scrolls up by one line
+  edit.run_after_keychord(Editor_state, 'backspace')
+  check_eq(Editor_state.screen_top1.line, 1, 'F - test_backspace_can_scroll_up/screen_top')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_backspace_can_scroll_up/cursor')
+  y = Editor_state.top
+  App.screen.check(y, 'abcdef', 'F - test_backspace_can_scroll_up/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'ghi', 'F - test_backspace_can_scroll_up/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'jkl', 'F - test_backspace_can_scroll_up/screen:3')
+end
+
+function test_backspace_can_scroll_up_screen_line()
+  io.write('\ntest_backspace_can_scroll_up_screen_line')
+  -- display lines starting from second screen line of a line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi jkl', 'mno'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=3, pos=5}
+  Editor_state.screen_top1 = {line=3, pos=5}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  local y = Editor_state.top
+  App.screen.check(y, 'jkl', 'F - test_backspace_can_scroll_up_screen_line/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_backspace_can_scroll_up_screen_line/baseline/screen:2')
+  -- after hitting backspace the screen scrolls up by one screen line
+  edit.run_after_keychord(Editor_state, 'backspace')
+  y = Editor_state.top
+  App.screen.check(y, 'ghij', 'F - test_backspace_can_scroll_up_screen_line/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'kl', 'F - test_backspace_can_scroll_up_screen_line/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'mno', 'F - test_backspace_can_scroll_up_screen_line/screen:3')
+  check_eq(Editor_state.screen_top1.line, 3, 'F - test_backspace_can_scroll_up_screen_line/screen_top')
+  check_eq(Editor_state.screen_top1.pos, 1, 'F - test_backspace_can_scroll_up_screen_line/screen_top')
+  check_eq(Editor_state.cursor1.line, 3, 'F - test_backspace_can_scroll_up_screen_line/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_backspace_can_scroll_up_screen_line/cursor:pos')
+end
+
+function test_backspace_past_line_boundary()
+  io.write('\ntest_backspace_past_line_boundary')
+  -- position cursor at start of a (non-first) line
+  App.screen.init{width=Editor_state.left+30, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=1}
+  -- backspace joins with previous line
+  edit.run_after_keychord(Editor_state, 'backspace')
+  check_eq(Editor_state.lines[1].data, 'abcdef', "F - test_backspace_past_line_boundary")
+end
+
+function test_undo_insert_text()
+  io.write('\ntest_undo_insert_text')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=4}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- insert a character
+  edit.draw(Editor_state)
+  edit.run_after_textinput(Editor_state, 'g')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_undo_insert_text/baseline/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_undo_insert_text/baseline/cursor:pos')
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_undo_insert_text/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'defg', 'F - test_undo_insert_text/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'xyz', 'F - test_undo_insert_text/baseline/screen:3')
+  -- undo
+  edit.run_after_keychord(Editor_state, 'C-z')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_undo_insert_text/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_undo_insert_text/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_undo_insert_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_undo_insert_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'xyz', 'F - test_undo_insert_text/screen:3')
+end
+
+function test_undo_delete_text()
+  io.write('\ntest_undo_delete_text')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'defg', 'xyz'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=2, pos=5}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  -- delete a character
+  edit.run_after_keychord(Editor_state, 'backspace')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_undo_delete_text/baseline/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 4, 'F - test_undo_delete_text/baseline/cursor:pos')
+  local y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_undo_delete_text/baseline/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'def', 'F - test_undo_delete_text/baseline/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'xyz', 'F - test_undo_delete_text/baseline/screen:3')
+  -- undo
+--?   -- after undo, the backspaced key is selected
+  edit.run_after_keychord(Editor_state, 'C-z')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_undo_delete_text/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_undo_delete_text/cursor:pos')
+  y = Editor_state.top
+  App.screen.check(y, 'abc', 'F - test_undo_delete_text/screen:1')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'defg', 'F - test_undo_delete_text/screen:2')
+  y = y + Editor_state.line_height
+  App.screen.check(y, 'xyz', 'F - test_undo_delete_text/screen:3')
+end
+
+function test_search()
+  io.write('\ntest_search')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc', 'def', 'ghi', 'deg'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- search for a string
+  edit.run_after_keychord(Editor_state, 'C-f')
+  edit.run_after_textinput(Editor_state, 'd')
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.cursor1.line, 2, 'F - test_search/1/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_search/1/cursor:pos')
+  -- reset cursor
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  -- search for second occurrence
+  edit.run_after_keychord(Editor_state, 'C-f')
+  edit.run_after_textinput(Editor_state, 'de')
+  edit.run_after_keychord(Editor_state, 'down')
+  edit.run_after_keychord(Editor_state, 'return')
+  check_eq(Editor_state.cursor1.line, 4, 'F - test_search/2/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_search/2/cursor:pos')
+end
+
+function test_search_upwards()
+  io.write('\ntest_search_upwards')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc abd'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=2}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- search for a string
+  edit.run_after_keychord(Editor_state, 'C-f')
+  edit.run_after_textinput(Editor_state, 'a')
+  -- search for previous occurrence
+  edit.run_after_keychord(Editor_state, 'up')
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_search_upwards/2/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_search_upwards/2/cursor:pos')
+end
+
+function test_search_wrap()
+  io.write('\ntest_search_wrap')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=3}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- search for a string
+  edit.run_after_keychord(Editor_state, 'C-f')
+  edit.run_after_textinput(Editor_state, 'a')
+  edit.run_after_keychord(Editor_state, 'return')
+  -- cursor wraps
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_search_wrap/1/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 1, 'F - test_search_wrap/1/cursor:pos')
+end
+
+function test_search_wrap_upwards()
+  io.write('\ntest_search_wrap_upwards')
+  App.screen.init{width=120, height=60}
+  Editor_state = edit.initialize_test_state()
+  Editor_state.lines = load_array{'abc abd'}
+  Text.redraw_all(Editor_state)
+  Editor_state.cursor1 = {line=1, pos=1}
+  Editor_state.screen_top1 = {line=1, pos=1}
+  Editor_state.screen_bottom1 = {}
+  edit.draw(Editor_state)
+  -- search upwards for a string
+  edit.run_after_keychord(Editor_state, 'C-f')
+  edit.run_after_textinput(Editor_state, 'a')
+  edit.run_after_keychord(Editor_state, 'up')
+  -- cursor wraps
+  check_eq(Editor_state.cursor1.line, 1, 'F - test_search_wrap_upwards/1/cursor:line')
+  check_eq(Editor_state.cursor1.pos, 5, 'F - test_search_wrap_upwards/1/cursor:pos')
+end
diff --git a/source_undo.lua b/source_undo.lua
new file mode 100644
index 0000000..0aa6755
--- /dev/null
+++ b/source_undo.lua
@@ -0,0 +1,110 @@
+-- undo/redo by managing the sequence of events in the current session
+-- based on https://github.com/akkartik/mu1/blob/master/edit/012-editor-undo.mu
+
+-- Incredibly inefficient; we make a copy of lines on every single keystroke.
+-- The hope here is that we're either editing small files or just reading large files.
+-- TODO: highlight stuff inserted by any undo/redo operation
+-- TODO: coalesce multiple similar operations
+
+function record_undo_event(State, data)
+  State.history[State.next_history] = data
+  State.next_history = State.next_history+1
+  for i=State.next_history,#State.history do
+    State.history[i] = nil
+  end
+end
+
+function undo_event(State)
+  if State.next_history > 1 then
+--?     print('moving to history', State.next_history-1)
+    State.next_history = State.next_history-1
+    local result = State.history[State.next_history]
+    return result
+  end
+end
+
+function redo_event(State)
+  if State.next_history <= #State.history then
+--?     print('restoring history', State.next_history+1)
+    local result = State.history[State.next_history]
+    State.next_history = State.next_history+1
+    return result
+  end
+end
+
+-- Copy all relevant global state.
+-- Make copies of objects; the rest of the app may mutate them in place, but undo requires immutable histories.
+function snapshot(State, s,e)
+  -- Snapshot everything by default, but subset if requested.
+  assert(s)
+  if e == nil then
+    e = s
+  end
+  assert(#State.lines > 0)
+  if s < 1 then s = 1 end
+  if s > #State.lines then s = #State.lines end
+  if e < 1 then e = 1 end
+  if e > #State.lines then e = #State.lines end
+  -- compare with App.initialize_globals
+  local event = {
+    screen_top=deepcopy(State.screen_top1),
+    selection=deepcopy(State.selection1),
+    cursor=deepcopy(State.cursor1),
+    lines={},
+    start_line=s,
+    end_line=e,
+    -- no filename; undo history is cleared when filename changes
+  }
+  -- deep copy lines without cached stuff like text fragments
+  for i=s,e do
+    local line = State.lines[i]
+    table.insert(event.lines, {data=line.data, dataB=line.dataB})
+  end
+  return event
+end
+
+function patch(lines, from, to)
+--?   if #from.lines == 1 and #to.lines == 1 then
+--?     assert(from.start_line == from.end_line)
+--?     assert(to.start_line == to.end_line)
+--?     assert(from.start_line == to.start_line)
+--?     lines[from.start_line] = to.lines[1]
+--?     return
+--?   end
+  assert(from.start_line == to.start_line)
+  for i=from.end_line,from.start_line,-1 do
+    table.remove(lines, i)
+  end
+  assert(#to.lines == to.end_line-to.start_line+1)
+  for i=1,#to.lines do
+    table.insert(lines, to.start_line+i-1, to.lines[i])
+  end
+end
+
+function patch_placeholders(line_cache, from, to)
+  assert(from.start_line == to.start_line)
+  for i=from.end_line,from.start_line,-1 do
+    table.remove(line_cache, i)
+  end
+  assert(#to.lines == to.end_line-to.start_line+1)
+  for i=1,#to.lines do
+    table.insert(line_cache, to.start_line+i-1, {})
+  end
+end
+
+-- https://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value/26367080#26367080
+function deepcopy(obj, seen)
+  if type(obj) ~= 'table' then return obj end
+  if seen and seen[obj] then return seen[obj] end
+  local s = seen or {}
+  local result = setmetatable({}, getmetatable(obj))
+  s[obj] = result
+  for k,v in pairs(obj) do
+    result[deepcopy(k, s)] = deepcopy(v, s)
+  end
+  return result
+end
+
+function minmax(a, b)
+  return math.min(a,b), math.max(a,b)
+end
diff --git a/text.lua b/text.lua
index 2e3aa32..c2c633b 100644
--- a/text.lua
+++ b/text.lua
@@ -1,11 +1,6 @@
 -- 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)
<dickey@invisible-island.net> 1998-03-29 19:00:00 -0500 snapshot of project "lynx", label v2-8-1dev_5' href='/ingrix/lynx-snapshots/commit/WWW/Library/Implementation/HTFTP.c?id=af9be28bc2701ea448898282942bd5b957439f18'>af9be28b ^
e087f6d4
af9be28b ^
e087f6d4

c5fef0d4 ^
e087f6d4

af9be28b ^
e087f6d4

af9be28b ^


e087f6d4

af9be28b ^





e087f6d4
55ebd12c ^
e087f6d4

af9be28b ^
953d3d55 ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^



e087f6d4


af9be28b ^

e087f6d4




af9be28b ^
e087f6d4

af9be28b ^
e087f6d4
c5fef0d4 ^
e087f6d4


af9be28b ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^



e087f6d4


af9be28b ^

e087f6d4







af9be28b ^
e087f6d4


6bd78b38 ^
af9be28b ^



e087f6d4


af9be28b ^

e087f6d4







af9be28b ^
e087f6d4

6bd78b38 ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^


e087f6d4


af9be28b ^

e087f6d4







af9be28b ^
e087f6d4



af9be28b ^



e087f6d4

af9be28b ^


e087f6d4

af9be28b ^
c5fef0d4 ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^
e087f6d4
af9be28b ^
55ebd12c ^
e087f6d4

af9be28b ^
08fc6e5c ^
e087f6d4


e087f6d4











af9be28b ^


e087f6d4









af9be28b ^
e087f6d4

ab8b1f12 ^
af9be28b ^


e087f6d4
ab8b1f12 ^
1d80538b ^
ab8b1f12 ^


1d80538b ^
ab8b1f12 ^
1d80538b ^
e087f6d4

af9be28b ^
e087f6d4




e47cfd56 ^
55ebd12c ^
e087f6d4





af9be28b ^
e087f6d4
af9be28b ^
e087f6d4





e087f6d4
af9be28b ^


e087f6d4



af9be28b ^
e087f6d4
af9be28b ^

e087f6d4


















152e034b ^
e087f6d4



152e034b ^
e087f6d4





af9be28b ^
e087f6d4
af9be28b ^
e087f6d4


152e034b ^
e087f6d4










af9be28b ^
152e034b ^
e087f6d4



152e034b ^
af9be28b ^
e087f6d4




af9be28b ^
e087f6d4




152e034b ^
e087f6d4












af9be28b ^
e087f6d4



af9be28b ^
e087f6d4
af9be28b ^


e087f6d4








327b7c16 ^
e087f6d4
327b7c16 ^
e087f6d4













c3ec4181 ^
e087f6d4
c3ec4181 ^


e087f6d4


d3f9d547 ^
c3ec4181 ^

af9be28b ^

c3ec4181 ^

af9be28b ^
c3ec4181 ^

af9be28b ^




c3ec4181 ^

55ebd12c ^
e087f6d4


af9be28b ^


e087f6d4
af9be28b ^
e087f6d4
55ebd12c ^
e087f6d4






af9be28b ^
e087f6d4







55ebd12c ^
e087f6d4
af9be28b ^
c5fef0d4 ^
e087f6d4



a735f5ad ^
c5fef0d4 ^
e087f6d4


af9be28b ^
e087f6d4
af9be28b ^
e087f6d4






af9be28b ^
e087f6d4
327b7c16 ^
c5fef0d4 ^
e087f6d4

af9be28b ^
e087f6d4
af9be28b ^





c5fef0d4 ^
e087f6d4
af9be28b ^













c5fef0d4 ^
af9be28b ^











e087f6d4
327b7c16 ^
e087f6d4
c5fef0d4 ^
327b7c16 ^
e087f6d4
c5fef0d4 ^
e087f6d4
af9be28b ^
e087f6d4



152e034b ^
e087f6d4



c5fef0d4 ^
e087f6d4
af9be28b ^
d3f9d547 ^

e087f6d4


d3f9d547 ^

af9be28b ^
cbcc3a1e ^
c5fef0d4 ^
cbcc3a1e ^
e087f6d4





af9be28b ^
e087f6d4




a735f5ad ^
e087f6d4
af9be28b ^
e087f6d4
a735f5ad ^
e087f6d4

a735f5ad ^
e087f6d4

55ebd12c ^
e087f6d4
af9be28b ^
e087f6d4
55ebd12c ^

e087f6d4

















af9be28b ^
e087f6d4
af9be28b ^
e087f6d4


55ebd12c ^
e087f6d4








af9be28b ^
152e034b ^
e087f6d4






cbcc3a1e ^
e087f6d4




57bfc74f ^
cbcc3a1e ^

57bfc74f ^

4b034492 ^
57bfc74f ^



e087f6d4
af9be28b ^

0654c702 ^
e087f6d4


af9be28b ^
e087f6d4











327b7c16 ^
e087f6d4








1d80538b ^
e087f6d4


55ebd12c ^
e087f6d4







cbcc3a1e ^
e087f6d4






af9be28b ^



e087f6d4

55ebd12c ^
e087f6d4





d3f9d547 ^
0654c702 ^
d3f9d547 ^



af9be28b ^
e087f6d4


327b7c16 ^
e087f6d4
d3f9d547 ^
e087f6d4





953d3d55 ^
e087f6d4




152e034b ^
e087f6d4


327b7c16 ^
e087f6d4





55ebd12c ^
af9be28b ^


d3f9d547 ^
af9be28b ^


d3f9d547 ^

e087f6d4




152e034b ^
af9be28b ^
e087f6d4

d3f9d547 ^
e087f6d4


55ebd12c ^
d3f9d547 ^
e087f6d4


af9be28b ^
e087f6d4


af9be28b ^
55ebd12c ^
e087f6d4
55ebd12c ^
e087f6d4
af9be28b ^

e087f6d4
e087f6d4





af9be28b ^
e087f6d4



d3f9d547 ^
e087f6d4








af9be28b ^
e087f6d4

af9be28b ^
e087f6d4




















d3f9d547 ^

e087f6d4


d3f9d547 ^
e087f6d4




ab8b1f12 ^
e087f6d4

ab8b1f12 ^

e087f6d4
152e034b ^
e087f6d4
152e034b ^
e087f6d4

ab8b1f12 ^

e087f6d4
ab8b1f12 ^
e087f6d4
ab8b1f12 ^
e087f6d4
ab8b1f12 ^
e087f6d4




ab8b1f12 ^
af9be28b ^
c3ec4181 ^
e087f6d4

ab8b1f12 ^

af9be28b ^
ab8b1f12 ^
e087f6d4




af9be28b ^
ab8b1f12 ^
af9be28b ^
ab8b1f12 ^
1d80538b ^
ab8b1f12 ^
e087f6d4
1d80538b ^
e087f6d4

af9be28b ^
e087f6d4

1d80538b ^
e087f6d4
e4409c40 ^
e087f6d4



af9be28b ^




e087f6d4

af9be28b ^
e087f6d4




af9be28b ^
e087f6d4



af9be28b ^
e087f6d4


af9be28b ^
e087f6d4
08fc6e5c ^
e087f6d4

152e034b ^
e087f6d4

af9be28b ^
e087f6d4














af9be28b ^
e087f6d4



d3f9d547 ^
e087f6d4



af9be28b ^
e087f6d4



d3f9d547 ^
e087f6d4
d3f9d547 ^
e087f6d4


af9be28b ^
e087f6d4
d3f9d547 ^
e087f6d4
152e034b ^
e087f6d4
152e034b ^
af9be28b ^
e087f6d4
152e034b ^
e087f6d4
af9be28b ^
e087f6d4




152e034b ^


e087f6d4
af9be28b ^
e087f6d4





af9be28b ^

e087f6d4












d3f9d547 ^
af9be28b ^
e087f6d4


152e034b ^
e087f6d4


152e034b ^
e087f6d4
af9be28b ^
152e034b ^
e087f6d4
af9be28b ^
e087f6d4


af9be28b ^
e087f6d4





55ebd12c ^
e087f6d4
152e034b ^
e087f6d4

152e034b ^
e087f6d4

af9be28b ^
e087f6d4










af9be28b ^
e087f6d4


af9be28b ^
152e034b ^
af9be28b ^


e087f6d4


af9be28b ^



152e034b ^














e087f6d4
af9be28b ^
e087f6d4


af9be28b ^
e087f6d4





c3ec4181 ^
af9be28b ^

e087f6d4
152e034b ^
e087f6d4


af9be28b ^
e087f6d4







c3ec4181 ^
af9be28b ^
953d3d55 ^
e087f6d4
af9be28b ^
953d3d55 ^

152e034b ^

953d3d55 ^
152e034b ^
953d3d55 ^

e087f6d4
953d3d55 ^
152e034b ^



e087f6d4

af9be28b ^
e087f6d4





af9be28b ^

e087f6d4






af9be28b ^


e087f6d4

af9be28b ^
e087f6d4




152e034b ^
e087f6d4
af9be28b ^
e087f6d4







152e034b ^
e087f6d4
152e034b ^
e087f6d4


af9be28b ^
e087f6d4










af9be28b ^
152e034b ^
e087f6d4



152e034b ^
e087f6d4
152e034b ^
e087f6d4


af9be28b ^
e087f6d4
















af9be28b ^
e087f6d4






152e034b ^
e087f6d4
327b7c16 ^
e087f6d4



af9be28b ^
e087f6d4
152e034b ^
08fc6e5c ^
af9be28b ^
152e034b ^



e087f6d4



af9be28b ^
e087f6d4


af9be28b ^
e087f6d4
af9be28b ^
e087f6d4








af9be28b ^
e087f6d4










af9be28b ^
e087f6d4








af9be28b ^

e087f6d4


af9be28b ^
e087f6d4

af9be28b ^
e087f6d4
e087f6d4






1d80538b ^

af9be28b ^


1d80538b ^





e087f6d4
af9be28b ^
e087f6d4

55ebd12c ^
e087f6d4
1d80538b ^
e4409c40 ^
e087f6d4



af9be28b ^
e087f6d4



1d80538b ^
e4409c40 ^
e087f6d4







d3f9d547 ^
e087f6d4


0654c702 ^
e087f6d4


55ebd12c ^
e087f6d4
d3f9d547 ^
e087f6d4







af9be28b ^
e087f6d4






55ebd12c ^
e087f6d4
97d3287a ^







af9be28b ^



97d3287a ^


af9be28b ^

97d3287a ^


327b7c16 ^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293














                                                                             
                                                                      





                                                                         

                                                            






                                                                              
                                                                       

                                                                        
                                                                       
                                     


                                                                            






                                                                           

                                                                             








                                                                         
  




                                    
                                            
                                        
                                                                 
                                                     
 
                                                                           

                                                                      
  
 



                            
                    
 
                    
 
                                              










                                                                               
                            





                          





                                                



                          

                      
                    
 
                            
                                                                  
                                                                  
                                                                             








                                                          
                 


                                                       
                                                                     







                                                       


                             
                                           
                                                                


                         
                                  








                                           


                                                                           
                                                                               

                                            

                            




                            




                            
                            
                            
                            
 

                                                                          

                                                                           
                                                      

                 
                                                     


                       
                                                                          
                                                                          

                                                                       
     
                                                                            









                                                                               

                                     

 
                    






                                            




                                      
 
                          
 






                                                                         
                                              
  
                                                  

                                    
                           


                           


                                                                                
                                                        






                                                                            
                                                
 
                                         

                               
                                        
                         
                                                                            
                                      
                      

                                  

                                                           
                        
                                     


                                                                 
                                                                       






                                                               
 


                                                                         
                                                              

                                                                    
                                                                   
                 
                                                                 





                                                             
                                                                       








                                                            
                                 




                                                                  
                                          
                      
                  




                                                
                                      


                            
                                                 











                                       
                
                                                                       




                                             

                             
                                


                                                       
                                

                                                    
                                         













                                                              
                               

                            
                                                 
        
                                                  
 
                                                            
































                                                                          
                            
 
                                                                      
                                   
               
 
                   

                                                               
     
 
              
                                     



                                    
                                 




                                                                  
                                                                               







                                                 
                  

                                    



                                                                

                                                                                        


                                               
                 

                                                                          
                                                         
 
                                                      








                                                                          
                                                

                                                              
                                                                   

                      
                                  
 





                                                                                    
 
                             
                                                               
                                             
                                                                              

                                                             



                                          
 
                        
                                                                
                                     



                                                       
                                            
                                          
          






                                                                           





















                                                                        


                                                                          
   
                                 
                                   

                                    

                                          
          
                                              




                                            






                                                           

                                   





                                                               
               



                                         


                                                                     
                                                          



                                                                   
                     
               

                                              
                                                                 
                    

                                           
                                                                  

                   


                                                                   
                            
                                                            

                                         
                                                                

         




                                                  








                                                                     
                           







                                                                      


                                       

               
                       
                     

                           
                                   
 



                                        
                    
                                
      


                         

                  
                                           
          
                                    
                                      
         
                      

                            






                                                          


                     


                                                                          








                                                   
                                                       


                                                           
                             


                                          
                                     
 
              



                                                                       

                            
                                 
 
                                                        



                                                                          





                                                              

                                                                               
                                                
                                                                  


                                                         
                          


             
                      


                       
                                                                       
 







                                                                              
                                                 


                                                               
         
                              


                                
 




                                                        

     

                                                          



                                                                
                                                                     



                                                                
                                                          
 

                                                                    
                                             


                                  
     
                                                   
                                                   

                                                           
                                                    



                                                                       
             




                                                    
         

                                         



                                                           

                                                                         
                                                 


                                      
         





                                                                 
                                                                  




                                                                   
                                    


                                                                  
                  


                                                     
                                                          



                                                     
                                        

                    
                  





                                                                        
                                    






                                                          
                          
 
                                                                       
                       
         

                                   

                                       
                                                                       
                                                 


                                      
         



                      
                                              

                                                                         
                                                 


                                      
         


                      
                                                            

                                                                         
     
                                       

                               

                                                   
                                                   
                                             



                                                                     
                            
                                                                
 
                                                             
                                                             
                                      
                            
                                                             
 

                                                              
                            
                                                                               
 

                                                             
                            
                                                            

                                                                  

                                                               
                            
                                                            

                                                              
                                      
                                                             

                                                                              
                                      
                                                              
                                                 

                               


                                                                              
                                                                           
 



                                                                               
                                                                            
 
                                                                     

                                            
                                                                  



                                                                     
                                                                   
 
                                           
                                                                        


                                            
                                                                   
 
                 
                                         
                                                            
                                                 
                               


                                                                     
                                              








                                                                 
                                                  

                                                        
                                              

                           
                                                         












                                       


                                             
                                     
                                                                   

                       
                                                            
        
                      











                                                                            
                                             






                                                                    
                                              
                                                                   

 

                                                                      
 

                           
                                                 




                                                           
 
                       
                                                                 
 
                                                                       
 

                           

                                                                                

                 
                                                     
                                                                  








                                                      
                                             














                                                          
                                                                            




                                                   
                   




                                                                  
                                                           






                                                             
                                  
 

















                                                                          
 















                                                                 
                                             
                                      


                           
                                     
                          
 
                               
 

                                                             
                                                                      
                                                       





                                                                   








                                                  
                                           










                                                                      
                                      





























                                                                             
                     




                                                 
                                             




                                                   
                                              







                                                  


                          
                      
                                                 





                                                  


                                   





                             




                                                        

                                 
                          


                                                           
                     
















                                                   
                     


                    
                     









                                      
                     









                                      
                     









                                      
                     





                        
                                                                          

                                   
                             


















                                                             
                     
                      
                                                     

                       
                         













                                                                   
                                                             











                                     
                                                            

                                 
                             






                                   

                                                                          

                   
                                                    





                                                                         
                                                            

             
     

                              


                                           






                                                     

                                                            

                                       
                             

                                   

                        



                                                            
                                                            

                                    







                                                                      

                                          
            
                                                                                
                                                          

                                                                               
                    
             
                                                                  



                                             
                                              



                                            



                                            



                                                       
                   




                                   



                                           




                                                             
                             



                                        

                                               
 



                                     






















                                                                
                                             



                                        














                                                 

                                              


                                                       








                                                   


                      



                                                                




                                  

                                                                         

                                              
                             






                                             
                          
                 

                                    


                                           
                              





                                           

                                   



                                         
                                                               











                                                             
                                




                                                  

                                                      
                


                                                      






                                                                          



                                                                       




                                  

                                                                        
   
                 
                                              
                             







                                             
                          
                 

                                    



                                           
                                 

                                                

                                    













                                                             
                               

                    

                                    
     

                               

                                                     

                                    


                                                             
                                                                 

                                           
                                         





                                                  
                                
                                                
                    
                                                







                                                   
                                         

                                                                      
                                             






                                                                      

                                   



                                         
                                                               





                                           



                                                                       

                                  
                       


                           

                                                               

                                       
                             









                                             
                          
                 

                                    


                                           
                              



                                                         
               
                           
                 




                                                       
     
                              

                                                            
                                      
                                                           
                             
            

                            


                                              
                                                    

                       

                                      







                                                            

                                  








                                                         

                                  

















                                                              

                                             









                                                                      
                           





                                                       
                                                      
                                     
                                                     
                        
                                                     

                    
                                                     

                                                  
                                             









                                                                          



                                                                   



                           
                        

                                                                 
  
                                                                


                                          
                              







                              
                                                        

                                              






                                


                                
                          


                               
              
                                                    




                                                   
 

                                                                
              
                                
                         
                                                            
                                                                   
                      
                                                                          

                                                

                                       


                                                             
                                                

                                         

                                                          
                                                



                                       

                                                      
              

                                            

                                     
                                                                   
                                                          
                                         
                  
                                                                  
                                                                

                                            
                                                                         

                                                          
                  

                                             


                                                          

                                                             





                                      
 
                                             

                                                     
                                                  
                                            
              
                                                  
              
                  
 



                                                              


                                                   

                                          




                                     
                                                  

                                               
                                                                             
                                                   
                                                                   


                                                          
                                                  
              
                  
 



                                                                     


                                                          

                                          







                                                                
                                                  


                  
                 



                                                                     


                                                          

                                          







                                                                
                                                  

                  
                       
 
                        
           


                                                                 


                                                   

                                          







                                                                
                                                  



                  



                                                                  

                                                      


                                      

                                                             
                                    
                                                                   
                                                          
             
              
                                                  
              
                  
 

                
                                                                
                                                                  


                                                       











                                                                   


                                                             









                                                              
                                  

                            
                        


                                                                     
 
                          
                                                                  


                                               
                    
                                          
             

         
                                            




                       
                                            
                               





                                                            
                          
                                      
                                             





                                                                   
 


                                                                 



                                                      
                                                                
 

                                               


















                                                                               
                                                    



                                          
                                                    





                                                         
                              
                     
                 


                                                               
                                                    










                                                                        
                                              
                                                        



                                              
                                                        
                                               




                                                         
                              




                                                               
                                                    












                                                                        
                                                   



                                                      
                                                                
 


                                                                








                                                                      
                                                
           
                                       













                                                                          
                         
                           


                                                                             


                                 
                                                      

      

                                             

                                  
                          

      




                                                     

                                                                          
 


                                                                         


                                                          
            
                                                                              
                 
 






                                                                              
                                              







                                              
 
     
                                                                          
               



                                             
                                       
                                                                             


                                        
                                      
                                    
                                                          






                                              
                                     
               
                                                                          
                                    

                                                    
                                          
                                        





                                                              
                                                                                   
                                                                













                                                                                
                                             











                                                                          
                            
                                                                      
                     
                                       
                                                         
                        
                                                 
                 
             



                                                       
                                                                      



                                              
                                              
                                                       
                      

                                                    


                                                              

                                                         
                                                         
                    
                                                           
                                 





                           
                           




                                                             
                       
                                                
                                                            
                           
                       

                            
                       

         
                        
           
                                                                        
           

                                                 

















                                                                           
                                                  
                                       
                                  


                                      
                                                                   








                                                                 
                                                                       
                                        






                                                           
                      




                                  
 

                                           

                                                  
                                               



                           
                                                  

                                      
                                          


                                  
                      











                                                                           
                                                       








                                           
                             


                                                           
 







                                                                                
                                              






                                       



                                                                        

                          
 





                                                              
                                                                                
                                                     



                                           
             


                                                                  
                                                       
             
                                                  





                                     
                                        




                                                                    
                                        


                                                                 
                                                       





                                                                 
 


                                                    
                                                                        


                                       

                                                                 




                                 
                                                                      
                                                                       

                             
                                                                 


                                                                
 
                                                                     


                     
                                     


                       
                                                           
 
                         
  
     

                                                                           
                    





                                                                               
                                        



                                                                
                                                                                     








                                                             
                                                        

                                                      
                                            




















                                         

                                                      


                             
                                                       




                                                                  
                             

                            

                                                            
             
                                       
                                                         
                                              

                                                   

                                   
                                                      
                                                 
                                
                                                     
                         
                                   




                                          
                      
                           
             

                                   

                                                        
                                                     
                                                    




                                                                 
                                                   
                                            
                                                                   
                                
                                                                     
                               
                        
                                                                     

                    
                                                                 

                
                                                             
         
                                                     



                                                   




                                                                   

                                        
                                                        




                                                     
                                                   



                                                    
                                                  


                           
                                        
              
                                                           

                                             
                                              

                                                                
                                                         














                                                                
                                                



                                                                
                                                                                     



                                                    
                      



                                                  
                                                               
                                                   
                                                         


                                                     
                                             
                                       
                                                                    
                                
                                          
                                      
                                           
                                                            
                                          
                                                  
                                              
                                            




                                                                               


                                                               
                                              
                                            





                                                                               

                                                                            












                                                                     
                                                                        
                                    


                                             
                                              


                                                   
                                                  
                                              
                                            
                                                      
                                                  
                                                


                                                              
                                                                             





                                                 
                     
                                                         
                                          

                                        
                                              

                                          
                                                                            










                                                                            
                                                    


                                                                                
                                                                      
                                           


                                                                    


                                                             



                                                                














                                                                     
                                      
                                    


                                                                        
                                                                 





                                                                           
                                            

                                                                     
                                  
                                            


                                            
                                                                    







                                                                              
                                            
                              
                                                                              
                                   
                                                       

                                                   

                              
                                                            
 

                                                         
                               
                                                       



                                       

                                  
                                                                    





                                                             

                                       






                        


                                                                        

                                                              
                                                                   




                                                                 
                                                  
                                      
                                                







                                                                        
                                                
                    
                                                


                                            
                                                                    










                                                                              
                             
                                            



                                          
                                                        
                            
                                                        


                                                      
                                                                            
















                                                                           
                           






                                                                  
                                                  
                
                                                                     



                                                                              
                                          
 
                                        
                                                                    
                                  



                                                



                          
                                                            


                                      
                              
                
                               








                                       
                                                










                                                             
                                                            








                                                             

                                                                 


                                                        
                      

                                      
               
                






                                                                           

                                    


                                                                          





                                                                          
                                             
                                            

                                             
 
                                         
                                                                 
                                                             



                                                                     
                                                                        



                                               
                                                                     
                                                                 







                                                                     
                                                     


                                                                       
                                               


                                                             
 
                                    
                                                                 







                                                                         
                                                             






                                                        
     
                      







                                                          



                                                     


      

                                                   


                                

                               
/*			File Transfer Protocol (FTP) Client
**			for a WorldWideWeb browser
**			===================================
**
**	A cache of control connections is kept.
**
** Note: Port allocation
**
**	It is essential that the port is allocated by the system, rather
**	than chosen in rotation by us (POLL_PORTS), or the following
**	problem occurs.
**
**	It seems that an attempt by the server to connect to a port which has
**	been used recently by a listen on the same socket, or by another
**	socket this or another process causes a hangup of (almost exactly)
**	one minute.  Therefore, we have to use a rotating port number.
**	The problem remains that if the application is run twice in quick
**	succession, it will hang for what remains of a minute.
**
** Authors
**	TBL	Tim Berners-lee <timbl@info.cern.ch>
**	DD	Denis DeLaRoca 310 825-4580 <CSP1DWD@mvs.oac.ucla.edu>
**	LM	Lou Montulli <montulli@ukanaix.cc.ukans.edu>
**	FM	Foteos Macrides <macrides@sci.wfeb.edu>
** History:
**	 2 May 91	Written TBL, as a part of the WorldWideWeb project.
**	15 Jan 92	Bug fix: close() was used for NETCLOSE for control soc
**	10 Feb 92	Retry if cached connection times out or breaks
**	 8 Dec 92	Bug fix 921208 TBL after DD
**	17 Dec 92	Anon FTP password now just WWWuser@ suggested by DD
**			fails on princeton.edu!
**	27 Dec 93 (FM)	Fixed up so FTP now works with VMS hosts.  Path
**			must be Unix-style and cannot include the device
**			or top directory.
**	?? ??? ?? (LM)	Added code to prompt and send passwords for non
**			anonymous FTP
**	25 Mar 94 (LM)	Added code to recognize different ftp server types
**			and code to parse dates and sizes on most hosts.
**	27 Mar 93 (FM)	Added code for getting dates and sizes on VMS hosts.
**
** Options:
**	LISTEN		We listen, the other guy connects for data.
**			Otherwise, other way round, but problem finding our
**			internet address!
**
** Notes:
**			Portions Copyright 1994 Trustees of Dartmouth College
**			Code for recognizing different FTP servers and
**			parsing "ls -l" output taken from Macintosh Fetch
**			program with permission from Jim Matthews,
**			Dartmouth Software Development Team.
*/

/*
** If LISTEN is not defined, PASV is used instead of PORT, and not
** all FTP servers support PASV, so define it unless there is no
** alternative for your system.
*/
#ifndef NOPORT
#define LISTEN	 /* @@@@ Test LJM */
#endif /* !NOPORT */

/*
BUGS:	@@@	Limit connection cache size!
		Error reporting to user.
		400 & 500 errors are ack'ed by user with windows.
		Use configuration file for user names

**		Note for portability this version does not use select() and
**		so does not watch the control and data channels at the
**		same time.
*/

#ifdef DJGPP
#define u_long unsigned long
#endif

#include <HTUtils.h>

#include <HTAlert.h>

#include <HTFTP.h>	/* Implemented here */

/* this define should be in HTFont.h :( */
#define HT_NON_BREAK_SPACE ((char)1)   /* For now */

#define REPEAT_PORT	/* Give the port number for each file */
#define REPEAT_LISTEN	/* Close each listen socket and open a new one */

/* define POLL_PORTS		 If allocation does not work, poll ourselves.*/
#define LISTEN_BACKLOG 2	/* Number of pending connect requests (TCP)*/

#define FIRST_TCP_PORT	1024	/* Region to try for a listening port */
#define LAST_TCP_PORT	5999

#define LINE_LENGTH 256
#define COMMAND_LENGTH 256

#define INFINITY 512

#include <HTParse.h>
#include <HTTCP.h>
#include <HTAnchor.h>
#include <HTFile.h>	/* For HTFileFormat() */
#include <HTBTree.h>
#include <HTChunk.h>
#ifndef IPPORT_FTP
#define IPPORT_FTP	21
#endif /* !IPORT_FTP */

#include <LYUtils.h>
#include <LYStrings.h>
#include <LYLeaks.h>

typedef struct _connection {
    struct _connection *	next;	/* Link on list		*/
    u_long			addr;	/* IP address		*/
    int				socket; /* Socket number for communication */
    BOOL			binary; /* Binary mode? */
} connection;

#ifndef NIL
#define NIL 0
#endif /* !NIL */

/*		Hypertext object building machinery
*/
#include <HTML.h>

#define PUTC(c) (*targetClass.put_character)(target, c)
#define PUTS(s) (*targetClass.put_string)(target, s)
#define START(e) (*targetClass.start_element)(target, e, 0, 0, -1, 0)
#define END(e) (*targetClass.end_element)(target, e, 0)
#define FREE_TARGET (*targetClass._free)(target)
#define ABORT_TARGET (*targetClass._free)(target)
struct _HTStructured {
	CONST HTStructuredClass *	isa;
	/* ... */
};

/*	Global Variables
**	---------------------
*/
PUBLIC int HTfileSortMethod = FILE_BY_NAME;
#ifndef DISABLE_FTP /*This disables everything to end-of-file */
PRIVATE char ThisYear[8];
PRIVATE char LastYear[8];
PRIVATE int TheDate;
PRIVATE BOOLEAN HaveYears = FALSE;
#ifdef SOCKS
extern BOOLEAN socks_flag;
extern unsigned long socks_bind_remoteAddr;
#endif /* SOCKS */
extern char *personal_mail_address;

/*	Module-Wide Variables
**	---------------------
*/
PRIVATE connection * connections = NULL;/* Linked list of connections */
PRIVATE char response_text[LINE_LENGTH+1];/* Last response from ftp host */
PRIVATE connection * control = NULL;	/* Current connection */
PRIVATE int data_soc = -1;		/* Socket for data transfer =invalid */
PRIVATE char *user_entered_password = NULL;
PRIVATE char *last_username_and_host = NULL;

#define GENERIC_SERVER	   0
#define MACHTEN_SERVER	   1
#define UNIX_SERVER	   2
#define VMS_SERVER	   3
#define CMS_SERVER	   4
#define DCTS_SERVER	   5
#define TCPC_SERVER	   6
#define PETER_LEWIS_SERVER 7
#define NCSA_SERVER	   8
#define WINDOWS_NT_SERVER  9
#define MS_WINDOWS_SERVER 10
#define MSDOS_SERVER	  11
#define APPLESHARE_SERVER 12
#define NETPRESENZ_SERVER 13

PRIVATE int	server_type = GENERIC_SERVER;	/* the type of ftp host */
PRIVATE int	unsure_type = FALSE;		/* sure about the type? */
PRIVATE BOOLEAN use_list = FALSE;		/* use the LIST command? */

PRIVATE int	interrupted_in_next_data_char = FALSE;

#ifdef POLL_PORTS
PRIVATE unsigned short	port_number = FIRST_TCP_PORT;
#endif /* POLL_PORTS */

#ifdef LISTEN
PRIVATE int	master_socket = -1;	/* Listening socket = invalid	*/
PRIVATE char	port_command[255];	/* Command for setting the port */
PRIVATE fd_set	open_sockets;		/* Mask of active channels */
PRIVATE int	num_sockets;		/* Number of sockets to scan */
#else
PRIVATE unsigned short	passive_port;	/* Port server specified for data */
#endif /* LISTEN */


#define NEXT_CHAR HTGetCharacter()	/* Use function in HTFormat.c */

#define DATA_BUFFER_SIZE 2048
PRIVATE char data_buffer[DATA_BUFFER_SIZE];		/* Input data buffer */
PRIVATE char * data_read_pointer;
PRIVATE char * data_write_pointer;
#define NEXT_DATA_CHAR next_data_char()
PRIVATE int close_connection PARAMS((
	connection *	con));


#ifdef LY_FIND_LEAKS
/*
**  This function frees module globals. - FM
*/
PRIVATE void free_FTPGlobals NOARGS
{
    FREE(user_entered_password);
    FREE(last_username_and_host);
    if (control) {
	if (control->socket != -1)
	    close_connection(control);
	FREE(control);
    }
}
#endif /* LY_FIND_LEAKS */

/* PUBLIC						HTMake_VMS_name()
**		CONVERTS WWW name into a VMS name
** ON ENTRY:
**	nn		Node Name (optional)
**	fn		WWW file name
**
** ON EXIT:
**	returns		vms file specification
**
** Bug: Returns pointer to static -- non-reentrant
*/
PUBLIC char * HTMake_VMS_name ARGS2(
	CONST char *,	nn,
	CONST char *,	fn)
{

/*	We try converting the filename into Files-11 syntax.  That is, we assume
**	first that the file is, like us, on a VMS node.  We try remote
**	(or local) DECnet access.  Files-11, VMS, VAX and DECnet
**	are trademarks of Digital Equipment Corporation.
**	The node is assumed to be local if the hostname WITHOUT DOMAIN
**	matches the local one. @@@
*/
    static char vmsname[INFINITY];	/* returned */
    char * filename = (char*)malloc(strlen(fn)+1);
    char * nodename = (char*)malloc(strlen(nn)+2+1);	/* Copies to hack */
    char *second;		/* 2nd slash */
    char *last;			/* last slash */

    CONST char * hostname = HTHostName();

    if (!filename || !nodename)
	outofmem(__FILE__, "HTVMSname");
    strcpy(filename, fn);
    strcpy(nodename, "");	/* On same node?  Yes if node names match */
    if (strncmp(nn, "localhost", 9)) {
	CONST char *p;
	CONST char *q;
	for (p = hostname, q = nn;
	     *p && *p != '.' && *q && *q != '.'; p++, q++){
	    if (TOUPPER(*p) != TOUPPER(*q)) {
		char *r;
		strcpy(nodename, nn);
		r = strchr(nodename, '.');	/* Mismatch */
		if (r)
		    *r = '\0';			/* Chop domain */
		strcat(nodename, "::");		/* Try decnet anyway */
		break;
	    }
	}
    }

    second = strchr(filename+1, '/');		/* 2nd slash */
    last = strrchr(filename, '/');	/* last slash */

    if (!second) {				/* Only one slash */
	sprintf(vmsname, "%s%s", nodename, filename + 1);
    } else if (second == last) {		/* Exactly two slashes */
	*second = '\0';		/* Split filename from disk */
	sprintf(vmsname, "%s%s:%s", nodename, filename+1, second+1);
	*second = '/';	/* restore */
    } else {				/* More than two slashes */
	char * p;
	*second = '\0';		/* Split disk from directories */
	*last = '\0';		/* Split dir from filename */
	sprintf(vmsname, "%s%s:[%s]%s",
		nodename, filename+1, second+1, last+1);
	*second = *last = '/';	/* restore filename */
	for (p = strchr(vmsname, '['); *p!=']'; p++)
	    if (*p == '/')
		*p = '.';		/* Convert dir sep.  to dots */
    }
    FREE(nodename);
    FREE(filename);
    return vmsname;
}

/*	Procedure: Read a character from the data connection
**	----------------------------------------------------
*/
PRIVATE int next_data_char NOARGS
{
    int status;
    if (data_read_pointer >= data_write_pointer) {
	status = NETREAD(data_soc, data_buffer, DATA_BUFFER_SIZE);
      if (status == HT_INTERRUPTED)
	interrupted_in_next_data_char = 1;
      if (status <= 0)
	return -1;
      data_write_pointer = data_buffer + status;
      data_read_pointer = data_buffer;
    }
#ifdef NOT_ASCII
    {
	char c = *data_read_pointer++;
	return FROMASCII(c);
    }
#else
    return (unsigned char)(*data_read_pointer++);
#endif /* NOT_ASCII */
}


/*	Close an individual connection
**
*/
PRIVATE int close_connection ARGS1(
	connection *,	con)
{
    connection * scan;
    int status = NETCLOSE(con->socket);
    if (TRACE) {
	CTRACE(tfp, "HTFTP: Closing control socket %d\n", con->socket);
#ifdef UNIX
	if (status != 0)
	    perror("HTFTP:close_connection");
#endif
    }
    con->socket = -1;
    if (connections == con) {
	connections = con->next;
	return status;
    }
    for (scan = connections; scan; scan = scan->next) {
	if (scan->next == con) {
	    scan->next = con->next;	/* Unlink */
	    if (control == con)
		control = (connection*)0;
	    return status;
	} /*if */
    } /* for */
    return -1;		/* very strange -- was not on list. */
}

PRIVATE char *help_message_buffer = NULL;  /* global :( */

PRIVATE void init_help_message_cache NOARGS
{
    FREE(help_message_buffer);
}

PRIVATE void help_message_cache_add ARGS1(
	char *,		string)
{
    if (help_message_buffer)
	StrAllocCat(help_message_buffer, string);
    else
	StrAllocCopy(help_message_buffer, string);

    CTRACE(tfp,"Adding message to help cache: %s\n",string);
}

PRIVATE char *help_message_cache_non_empty NOARGS
{
  return(help_message_buffer);
}
PRIVATE char *help_message_cache_contents NOARGS
{
   return(help_message_buffer);
}

/*	Execute Command and get Response
**	--------------------------------
**
**	See the state machine illustrated in RFC959, p57. This implements
**	one command/reply sequence.  It also interprets lines which are to
**	be continued, which are marked with a "-" immediately after the
**	status code.
**
**	Continuation then goes on until a line with a matching reply code
**	an a space after it.
**
** On entry,
**	con	points to the connection which is established.
**	cmd	points to a command, or is NIL to just get the response.
**
**	The command is terminated with the CRLF pair.
**
** On exit,
**	returns:  The first digit of the reply type,
**		  or negative for communication failure.
*/
PRIVATE int response ARGS1(
	char *,		cmd)
{
    int result;				/* Three-digit decimal code */
    int continuation_response = -1;
    int status;

    if (!control) {
	CTRACE(tfp, "HTFTP: No control connection set up!!\n");
	return -99;
    }

    if (cmd) {
	CTRACE(tfp, "  Tx: %s", cmd);
#ifdef NOT_ASCII
	{
	    char * p;
	    for (p = cmd; *p; p++) {
		*p = TOASCII(*p);
	    }
	}
#endif /* NOT_ASCII */
	status = NETWRITE(control->socket, cmd, (int)strlen(cmd));
	if (status < 0) {
	    CTRACE(tfp, "HTFTP: Error %d sending command: closing socket %d\n",
			status, control->socket);
	    close_connection(control);
	    return status;
	}
    }

    do {
	char *p = response_text;
	for (;;) {
	    int ich = NEXT_CHAR;
	    if (((*p++ = ich) == LF)
			|| (p == &response_text[LINE_LENGTH])) {

		char continuation;

		if (interrupted_in_htgetcharacter) {
		    CTRACE (tfp, "HTFTP: Interrupted in HTGetCharacter, apparently.\n");
		    NETCLOSE (control->socket);
		    control->socket = -1;
		    return HT_INTERRUPTED;
		}

		*p = '\0';			/* Terminate the string */
		CTRACE(tfp, "    Rx: %s", response_text);

		/* Check for login or help messages */
		if (!strncmp(response_text,"230-",4) ||
		    !strncmp(response_text,"250-",4) ||
		    !strncmp(response_text,"220-",4))
		    help_message_cache_add(response_text+4);

		sscanf(response_text, "%d%c", &result, &continuation);
		if  (continuation_response == -1) {
			if (continuation == '-')  /* start continuation */
			    continuation_response = result;
		} else {	/* continuing */
			if (continuation_response == result &&
			    continuation == ' ')
			    continuation_response = -1; /* ended */
		}
		break;
	    } /* if end of line */

	    if (interrupted_in_htgetcharacter) {
		CTRACE (tfp, "HTFTP: Interrupted in HTGetCharacter, apparently.\n");
		NETCLOSE (control->socket);
		control->socket = -1;
		return HT_INTERRUPTED;
	    }

	    if (ich == EOF) {
		CTRACE(tfp, "Error on rx: closing socket %d\n",
			    control->socket);
		strcpy(response_text, "000 *** TCP read error on response\n");
		close_connection(control);
		return -1;	/* End of file on response */
	    }
	} /* Loop over characters */

    } while (continuation_response != -1);

    if (result == 421) {
	CTRACE(tfp, "HTFTP: They close so we close socket %d\n",
		    control->socket);
	close_connection(control);
	return -1;
    }
    if ((result == 255 && server_type == CMS_SERVER) &&
	(0 == strncasecomp(cmd, "CWD", 3) ||
	 0 == strcasecomp(cmd, "CDUP"))) {
	/*
	**  Alas, CMS returns 255 on failure to CWD to parent of root. - PG
	*/
	result = 555;
    }
    return result/100;
}

PRIVATE int send_cmd_1 ARGS1(char *, verb)
{
    char command[80];

    sprintf(command, "%.*s%c%c", (int) sizeof(command)-4, verb, CR, LF);
    return response (command);
}

PRIVATE int send_cmd_2 ARGS2(char *, verb, char *, param)
{
    char *command = 0;
    int status;

    HTSprintf0(&command, "%s %s%c%c", verb, param, CR, LF);
    status = response (command);
    FREE(command);

    return status;
}

#define send_cwd(path) send_cmd_2("CWD", path)

/*
 *  This function should try to set the macintosh server into binary mode.
 *  Some servers need an additional letter after the MACB command.
 */
PRIVATE int set_mac_binary ARGS1(
	int,		ServerType)
{
    /* try to set mac binary mode */
    if (ServerType == APPLESHARE_SERVER ||
	ServerType == NETPRESENZ_SERVER) {
	/*
	 *  Presumably E means "Enable".  - KW
	 */
	return(2 == response("MACB E\r\n"));
    } else {
	return(2 == response("MACB\r\n"));
    }
}

/* This function gets the current working directory to help
 * determine what kind of host it is
 */

PRIVATE void get_ftp_pwd ARGS2(
	int *,		ServerType,
	BOOLEAN *,	UseList)
{

    char *cp;
    /* get the working directory (to see what it looks like) */
    int status = response("PWD\r\n");
    if (status < 0) {
	return;
    } else {
	cp = strchr(response_text+5,'"');
	if (cp)
	    *cp = '\0';
	if (*ServerType == TCPC_SERVER) {
	    *ServerType = ((response_text[5] == '/') ?
					  NCSA_SERVER : TCPC_SERVER);
	    CTRACE(tfp, "HTFTP: Treating as %s server.\n",
			 ((*ServerType == NCSA_SERVER) ?
						 "NCSA" : "TCPC"));
	} else if (response_text[5] == '/') {
	    /* path names beginning with / imply Unix,
	     * right?
	     */
	    if (set_mac_binary(*ServerType)) {
		*ServerType = NCSA_SERVER;
		CTRACE(tfp, "HTFTP: Treating as NCSA server.\n");
	    } else {
		 *ServerType = UNIX_SERVER;
		 *UseList = TRUE;
		 CTRACE(tfp, "HTFTP: Treating as Unix server.\n");
	    }
	    return;
	} else if (response_text[strlen(response_text)-1] == ']') {
	    /* path names ending with ] imply VMS, right? */
	    *ServerType = VMS_SERVER;
	    *UseList = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as VMS server.\n");
	} else {
	    *ServerType = GENERIC_SERVER;
	    CTRACE(tfp, "HTFTP: Treating as Generic server.\n");
	}

	if ((*ServerType == NCSA_SERVER) ||
	    (*ServerType == TCPC_SERVER) ||
	    (*ServerType == PETER_LEWIS_SERVER) ||
	    (*ServerType == NETPRESENZ_SERVER))
	    set_mac_binary(*ServerType);
    }
}

/*	Get a valid connection to the host
**	----------------------------------
**
** On entry,
**	arg	points to the name of the host in a hypertext address
** On exit,
**	returns <0 if error
**		socket number if success
**
**	This routine takes care of managing timed-out connections, and
**	limiting the number of connections in use at any one time.
**
**	It ensures that all connections are logged in if they exist.
**	It ensures they have the port number transferred.
*/
PRIVATE int get_connection ARGS2(
	CONST char *,		arg,
	HTParentAnchor *,	anchor)
{
    int status;
    char * command = 0;
    connection * con;
    char * username = NULL;
    char * password = NULL;
    static BOOLEAN firstuse = TRUE;

    if (firstuse) {
	/*
	**  Set up freeing at exit. - FM
	*/
#ifdef LY_FIND_LEAKS
	atexit(free_FTPGlobals);
#endif
	firstuse = FALSE;
    }

    if (control) {
	/*
	**  Reuse this object - KW, DW & FM
	*/
	if (control->socket != -1) {
	    NETCLOSE(control->socket);
	}
	con = control;
	con->addr = 0;
	con->binary = FALSE;
    } else {
	/*
	**  Allocate and init control struct.
	*/
	con = (connection *)calloc(1, sizeof(connection));
	if (con == NULL)
	    outofmem(__FILE__, "get_connection");
    }
    con->socket = -1;

    if (!arg) return -1;		/* Bad if no name specified	*/
    if (!*arg) return -1;		/* Bad if name had zero length	*/

/* Get node name:
*/
    {
	char *p1 = HTParse(arg, "", PARSE_HOST);
	char *p2 = strrchr(p1, '@');	/* user? */
	char * pw = NULL;

	if (p2 != NULL) {
	    username = p1;
	    *p2 = '\0';			/* terminate */
	    p1 = p2+1;			/* point to host */
	    pw = strchr(username, ':');
	    if (pw != NULL) {
		*pw++ = '\0';
		password = HTUnEscape(pw);
	    }
	    if (*username)
		HTUnEscape(username);

	    /*
	     *	If the password doesn't exist then we are going to have
	     *	to ask the user for it.  The only problem is that we
	     *	don't want to ask for it every time, so we will store
	     *	away in a primitive fashion.
	     */
	    if (!password) {
		char *tmp = NULL;

		HTSprintf0(&tmp, "%s@%s", username, p1);
		/*
		 *  If the user@host is not equal to the last time through
		 *  or user_entered_password has no data then we need
		 *  to ask the user for the password.
		 */
		if (!last_username_and_host ||
		    strcmp(tmp, last_username_and_host) ||
		    !user_entered_password) {

		    StrAllocCopy(last_username_and_host, tmp);
		    HTSprintf0(&tmp, gettext("Enter password for user %s@%s:"),
				     username, p1);
		    FREE(user_entered_password);
		    user_entered_password = HTPromptPassword(tmp);

		} /* else we already know the password */
		password = user_entered_password;
		FREE(tmp);
	    }
	}

	if (!username)
	    FREE(p1);
    } /* scope of p1 */

    status = HTDoConnect (arg, "FTP", IPPORT_FTP, (int *)&con->socket);

    if (status < 0) {
	if (status == HT_INTERRUPTED) {
	    CTRACE (tfp, "HTFTP: Interrupted on connect\n");
	} else {
	    CTRACE(tfp, "HTFTP: Unable to connect to remote host for `%s'.\n",
			arg);
	}
	if (status == HT_INTERRUPTED) {
	    _HTProgress (CONNECTION_INTERRUPTED);
	    status = HT_NOT_LOADED;
	} else {
	    HTAlert(gettext("Unable to connect to FTP host."));
	}
	if (con->socket != -1)
	{
	  NETCLOSE(con->socket);
	}

	FREE(username);
	if (control == con)
	    control = NULL;
	FREE(con);
	return status;			/* Bad return */
    }

    CTRACE(tfp, "FTP connected, socket %d  control %ld\n",
		con->socket, (long)con);
    control = con;		/* Current control connection */

    /* Initialise buffering for control connection */
    HTInitInput(control->socket);
    init_help_message_cache();	/* Clear the login message buffer. */


/*	Now we log in		Look up username, prompt for pw.
*/
    status = response((char *)0);	/* Get greeting */

    if (status == HT_INTERRUPTED) {
	CTRACE (tfp, "HTFTP: Interrupted at beginning of login.\n");
	_HTProgress (CONNECTION_INTERRUPTED);
	NETCLOSE(control->socket);
	control->socket = -1;
	return HT_INTERRUPTED;
    }
    server_type = GENERIC_SERVER;	/* reset */
    if (status == 2) {		/* Send username */
	char *cp;		/* look at greeting text */

	/* don't gettext() this -- incoming text: */
	if (strlen(response_text) > 4) {
	    if ((cp = strstr(response_text, " awaits your command")) ||
		(cp = strstr(response_text, " ready."))) {
		*cp = '\0';
	    }
	    cp = response_text + 4;
	    if (!strncasecomp(cp, "NetPresenz", 10))
		server_type = NETPRESENZ_SERVER;
	} else {
	    cp = response_text;
	}
	StrAllocCopy(anchor->server, cp);

	status = send_cmd_2("USER", (username && *username)
			    ? username
			    : "anonymous");

	if (status == HT_INTERRUPTED) {
	    CTRACE (tfp, "HTFTP: Interrupted while sending username.\n");
	    _HTProgress (CONNECTION_INTERRUPTED);
	    NETCLOSE(control->socket);
	    control->socket = -1;
	    return HT_INTERRUPTED;
	}
    }
    if (status == 3) {		/* Send password */
	if (password) {
	    /*
	     * We have non-zero length password, so send it. - FM
	     */
	    HTSprintf0(&command, "PASS %s%c%c", password, CR, LF);
	} else {
	    /*
	     * Create and send a mail address as the password. - FM
	     */
	    char *user = NULL;
	    CONST char *host = NULL;
	    char * cp;

	    if (personal_mail_address && *personal_mail_address) {
		/*
		 * We have a non-zero length personal
		 * mail address, so use that. - FM
		 */
		StrAllocCopy(user, personal_mail_address);
		if ((cp=strchr(user, '@')) != NULL) {
		    *cp++ = '\0';
		    host = cp;
		} else {
		    host = HTHostName();
		}
	    } else {
		/*
		 * Use an environment variable and the host global. - FM
		 */
		if ((cp=getenv("USER")) != NULL)
		    StrAllocCopy(user, cp);
		else
		    StrAllocCopy(user, "WWWuser");
		host = HTHostName();
	    }

	    /*
	     * If host is not fully qualified, suppress it
	     * as ftp.uu.net prefers a blank to a bad name
	     */
	    if (!(host) || strchr(host, '.') == NULL)
		host = "";

	    HTSprintf0(&command, "PASS %s@%s%c%c", user, host, CR, LF);
	    FREE(user);
	}
	status = response(command);
	FREE(command);
	if (status == HT_INTERRUPTED) {
	    CTRACE (tfp,
		       "HTFTP: Interrupted while sending password.\n");
	    _HTProgress (CONNECTION_INTERRUPTED);
	    NETCLOSE(control->socket);
	    control->socket = -1;
	    return HT_INTERRUPTED;
	}
    }
    FREE(username);

    if (status == 3) {
	status = send_cmd_1("ACCT noaccount");
	if (status == HT_INTERRUPTED) {
	    CTRACE (tfp, "HTFTP: Interrupted while sending password.\n");
	    _HTProgress (CONNECTION_INTERRUPTED);
	    NETCLOSE(control->socket);
	    control->socket = -1;
	    return HT_INTERRUPTED;
	}

    }
    if (status != 2) {
	CTRACE(tfp, "HTFTP: Login fail: %s", response_text);
	/* if (control->socket > 0) close_connection(control->socket); */
	return -1;		/* Bad return */
    }
    CTRACE(tfp, "HTFTP: Logged in.\n");

    /** Check for host type **/
    if (server_type != NETPRESENZ_SERVER)
	server_type = GENERIC_SERVER;	/* reset */
    use_list = FALSE;			/* reset */
    if ((status=response("SYST\r\n")) == 2) {
	/* we got a line -- what kind of server are we talking to? */
	if (strncmp(response_text+4,
		    "UNIX Type: L8 MAC-OS MachTen", 28) == 0) {
	    server_type = MACHTEN_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as MachTen server.\n");

	} else if (strstr(response_text+4, "UNIX") != NULL ||
		   strstr(response_text+4, "Unix") != NULL) {
	    server_type = UNIX_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as Unix server.\n");

	} else if (strstr(response_text+4, "MSDOS") != NULL) {
	    server_type = MSDOS_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as MSDOS (Unix emulation) server.\n");

	} else if (strncmp(response_text+4, "VMS", 3) == 0) {
	    server_type = VMS_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as VMS server.\n");

	} else if ((strncmp(response_text+4, "VM/CMS", 6) == 0) ||
		   (strncmp(response_text+4, "VM ", 3) == 0)) {
	    server_type = CMS_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as CMS server.\n");

	} else if (strncmp(response_text+4, "DCTS", 4) == 0) {
	    server_type = DCTS_SERVER;
	    CTRACE(tfp, "HTFTP: Treating as DCTS server.\n");

	} else if (strstr(response_text+4, "MAC-OS TCP/Connect II") != NULL) {
	    server_type = TCPC_SERVER;
	    CTRACE(tfp, "HTFTP: Looks like a TCPC server.\n");
	    get_ftp_pwd(&server_type, &use_list);
	    unsure_type = TRUE;

	} else if (server_type == NETPRESENZ_SERVER) { /* already set above */
	    use_list = TRUE;
	    set_mac_binary(server_type);
	    CTRACE(tfp, "HTFTP: Treating as NetPresenz (MACOS) server.\n");

	} else if (strncmp(response_text+4, "MACOS Peter's Server", 20) == 0) {
	    server_type = PETER_LEWIS_SERVER;
	    use_list = TRUE;
	    set_mac_binary(server_type);
	    CTRACE(tfp, "HTFTP: Treating as Peter Lewis (MACOS) server.\n");

	} else if (strncmp(response_text+4, "Windows_NT", 10) == 0) {
	    server_type = WINDOWS_NT_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as Window_NT server.\n");

	} else if (strncmp(response_text+4, "MS Windows", 10) == 0) {
	    server_type = MS_WINDOWS_SERVER;
	    use_list = TRUE;
	    CTRACE(tfp, "HTFTP: Treating as MS Windows server.\n");

	} else if (strncmp(response_text+4,
			   "MACOS AppleShare IP FTP Server", 30) == 0) {
	    server_type = APPLESHARE_SERVER;
	    use_list = TRUE;
	    set_mac_binary(server_type);
	    CTRACE(tfp, "HTFTP: Treating as AppleShare server.\n");

	} else	{
	    server_type = GENERIC_SERVER;
	    CTRACE(tfp, "HTFTP: Ugh!  A Generic server.\n");
	    get_ftp_pwd(&server_type, &use_list);
	    unsure_type = TRUE;
	 }
    } else {
	/* SYST fails :(  try to get the type from the PWD command */
	 get_ftp_pwd(&server_type, &use_list);
    }

/*  Now we inform the server of the port number we will listen on
*/
#ifdef NOTREPEAT_PORT
    {
	int status = response(port_command);
	if (status != 2) {
	    if (control->socket)
		close_connection(control->socket);
	    return -status;		/* Bad return */
	}
	CTRACE(tfp, "HTFTP: Port defined.\n");
    }
#endif /* NOTREPEAT_PORT */
    return con->socket;			/* Good return */
}


#ifdef LISTEN

/*	Close Master (listening) socket
**	-------------------------------
**
**
*/
PRIVATE int close_master_socket NOARGS
{
    int status;

    if (master_socket != -1)
	FD_CLR(master_socket, &open_sockets);
    status = NETCLOSE(master_socket);
    CTRACE(tfp, "HTFTP: Closed master socket %d\n", master_socket);
    master_socket = -1;
    if (status < 0)
	return HTInetStatus(gettext("close master socket"));
    else
	return status;
}


/*	Open a master socket for listening on
**	-------------------------------------
**
**	When data is transferred, we open a port, and wait for the server to
**	connect with the data.
**
** On entry,
**	master_socket	Must be negative if not set up already.
** On exit,
**	Returns		socket number if good
**			less than zero if error.
**	master_socket	is socket number if good, else negative.
**	port_number	is valid if good.
*/
PRIVATE int get_listen_socket NOARGS
{
    struct sockaddr_in soc_address;	/* Binary network address */
    struct sockaddr_in* soc_in = &soc_address;
    int new_socket;			/* Will be master_socket */


    FD_ZERO(&open_sockets);	/* Clear our record of open sockets */
    num_sockets = 0;

#ifndef REPEAT_LISTEN
    if (master_socket >= 0)
	return master_socket;  /* Done already */
#endif /* !REPEAT_LISTEN */

/*  Create internet socket
*/
    new_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (new_socket < 0)
	return HTInetStatus(gettext("socket for master socket"));

    CTRACE(tfp, "HTFTP: Opened master socket number %d\n", new_socket);

/*  Search for a free port.
*/
    soc_in->sin_family = AF_INET;	    /* Family = internet, host order  */
    soc_in->sin_addr.s_addr = INADDR_ANY;   /* Any peer address */
#ifdef POLL_PORTS
    {
	unsigned short old_port_number = port_number;
	for (port_number = (old_port_number+1); ; port_number++) {
	    int status;
	    if (port_number > LAST_TCP_PORT)
		port_number = FIRST_TCP_PORT;
	    if (port_number == old_port_number) {
		return HTInetStatus("bind");
	    }
	    soc_address.sin_port = htons(port_number);
#ifdef SOCKS
	    if (socks_flag)
		if ((status=Rbind(new_socket,
			(struct sockaddr*)&soc_address,
			    /* Cast to generic sockaddr */
			sizeof(soc_address)
#ifndef SHORTENED_RBIND
			,socks_bind_remoteAddr
#endif /* !SHORTENED_RBIND */
						)) == 0)
		    break;
	    else
#endif /* SOCKS */
	    if ((status=bind(new_socket,
		    (struct sockaddr*)&soc_address,
			    /* Cast to generic sockaddr */
		    sizeof(soc_address))) == 0)
		break;
	    CTRACE(tfp, "TCP bind attempt to port %d yields %d, errno=%d\n",
		port_number, status, SOCKET_ERRNO);
	} /* for */
    }
#else
    {
	int status;
	int address_length = sizeof(soc_address);
#ifdef SOCKS
	if (socks_flag)
	    status = Rgetsockname(control->socket,
				  (struct sockaddr *)&soc_address,
				  (void *)&address_length);
	else
#endif /* SOCKS */
	status = getsockname(control->socket,
			     (struct sockaddr *)&soc_address,
			     (void *)&address_length);
	if (status<0) return HTInetStatus("getsockname");
	CTRACE(tfp, "HTFTP: This host is %s\n",
	    HTInetString(soc_in));

	soc_address.sin_port = 0;	/* Unspecified: please allocate */
#ifdef SOCKS
	if (socks_flag)
	    status=Rbind(new_socket,
			 (struct sockaddr*)&soc_address,
			 /* Cast to generic sockaddr */
			 sizeof(soc_address)
#ifndef SHORTENED_RBIND
			,socks_bind_remoteAddr
#endif /* !SHORTENED_RBIND */
						);
	else
#endif /* SOCKS */
	status=bind(new_socket,
		    (struct sockaddr*)&soc_address,
		    /* Cast to generic sockaddr */
		    sizeof(soc_address));
	if (status<0) return HTInetStatus("bind");

	address_length = sizeof(soc_address);
#ifdef SOCKS
	if (socks_flag)
	    status = Rgetsockname(new_socket,
				  (struct sockaddr*)&soc_address,
				  (void *)&address_length);
	else
#endif /* SOCKS */
	status = getsockname(new_socket,
			     (struct sockaddr*)&soc_address,
			     (void *)&address_length);
	if (status<0) return HTInetStatus("getsockname");
    }
#endif /* POLL_PORTS */

    CTRACE(tfp, "HTFTP: bound to port %d on %s\n",
		(int)ntohs(soc_in->sin_port),
		HTInetString(soc_in));

#ifdef REPEAT_LISTEN
    if (master_socket >= 0)
	(void) close_master_socket();
#endif /* REPEAD_LISTEN */

    master_socket = new_socket;

/*	Now we must find out who we are to tell the other guy
*/
    (void)HTHostName();		/* Make address valid - doesn't work*/
    sprintf(port_command, "PORT %d,%d,%d,%d,%d,%d%c%c",
		    (int)*((unsigned char *)(&soc_in->sin_addr)+0),
		    (int)*((unsigned char *)(&soc_in->sin_addr)+1),
		    (int)*((unsigned char *)(&soc_in->sin_addr)+2),
		    (int)*((unsigned char *)(&soc_in->sin_addr)+3),
		    (int)*((unsigned char *)(&soc_in->sin_port)+0),
		    (int)*((unsigned char *)(&soc_in->sin_port)+1),
		    CR, LF);


/*	Inform TCP that we will accept connections
*/
  {
    int status;
#ifdef SOCKS
    if (socks_flag)
	status = Rlisten(master_socket, 1);
    else
#endif /* SOCKS */
    status = listen(master_socket, 1);
    if (status < 0) {
	master_socket = -1;
	return HTInetStatus("listen");
    }
  }
    CTRACE(tfp, "TCP: Master socket(), bind() and listen() all OK\n");
    FD_SET(master_socket, &open_sockets);
    if ((master_socket+1) > num_sockets)
	num_sockets = master_socket+1;

    return master_socket;		/* Good */

} /* get_listen_socket */
#endif /* LISTEN */

PRIVATE char * months[12] = {
    "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
};

/*	Procedure: Set the current and last year strings and date integer
**	-----------------------------------------------------------------
**
**	Bug:
**		This code is for sorting listings by date, if that option
**		is selected in Lynx, and doesn't take into account time
**		zones or ensure resetting at midnight, so the sort may not
**		be perfect, but the actual date isn't changed in the display,
**		i.e., the date is still correct. - FM
*/
PRIVATE void set_years_and_date NOARGS
{
    char day[8], month[8], date[12];
    time_t NowTime;
    int i;

    NowTime = time(NULL);
    strncpy(day, (char *)ctime(&NowTime)+8, 2);
    day[2] = '\0';
    if (day[0] == ' ') {
	day[0] = '0';
    }
    strncpy(month, (char *)ctime(&NowTime)+4, 3);
    strncpy(month, (char *)ctime(&NowTime)+4, 3);
    month[3] = '\0';
    for (i = 0; i < 12; i++) {
	if (!strcasecomp(month, months[i])) {
	    break;
	}
    }
    i++;
    sprintf(month, "%s%d", (i < 10 ? "0" : ""), i);
    sprintf(date, "9999%.2s%.2s", month, day);
    TheDate = atoi(date);
    strcpy(ThisYear, (char *)ctime(&NowTime)+20);
    ThisYear[4] = '\0';
    sprintf(LastYear, "%d", (atoi(ThisYear) - 1));
    HaveYears = TRUE;
}

typedef struct _EntryInfo {
    char *	 filename;
    char *	 type;
    char *	 date;
    unsigned int size;
    BOOLEAN	 display;  /* show this entry? */
} EntryInfo;

PRIVATE void free_entryinfo_struct_contents ARGS1(
	EntryInfo *,	entry_info)
{
    if (entry_info) {
	FREE(entry_info->filename);
	FREE(entry_info->type);
	FREE(entry_info->date);
    }
   /* dont free the struct */
}

/*
 * is_ls_date() --
 *	Return TRUE if s points to a string of the form:
 *		"Sep  1  1990 " or
 *		"Sep 11 11:59 " or
 *		"Dec 12 1989  " or
 *		"FCv 23 1990  " ...
 */
PRIVATE BOOLEAN is_ls_date ARGS1(
	char *,		s)
{
    /* must start with three alpha characters */
    if (!isalpha(*s++) || !isalpha(*s++) || !isalpha(*s++))
	return FALSE;

    /* space or HT_NON_BREAK_SPACE */
    if (!(*s == ' ' || *s == HT_NON_BREAK_SPACE)) {
	s++;
	return FALSE;
    }
    s++;

    /* space or digit */
    if (!(*s == ' ' || isdigit(*s))) {
	s++;
	return FALSE;
    }
    s++;

    /* digit */
    if (!isdigit(*s++))
	return FALSE;

    /* space */
    if (*s++ != ' ')
	return FALSE;

    /* space or digit */
    if (!(*s == ' ' || isdigit(*s))) {
	s++;
	return FALSE;
    }
    s++;

    /* digit */
    if (!isdigit(*s++))
	return FALSE;

    /* colon or digit */
    if (!(*s == ':' || isdigit(*s))) {
	s++;
	return FALSE;
    }
    s++;

    /* digit */
    if (!isdigit(*s++))
	return FALSE;

    /* space or digit */
    if (!(*s == ' ' || isdigit(*s))) {
	s++;
	return FALSE;
    }
    s++;

    /* space */
    if (*s++ != ' ')
	return FALSE;

    return TRUE;
} /* is_ls_date() */

/*
 *  parse_eplf_line() --
 *	Extract the name, size, and date from an EPLF line. - 08-06-96 DJB
 */
PRIVATE void parse_eplf_line ARGS2(
	char *,		line,
	EntryInfo *,	info)
{
    char *cp = line;
    char ct[26];
    unsigned long size;
    time_t secs;
    static time_t base; /* time() value on this OS in 1970 */
    static int flagbase = 0;

    if (!flagbase) {
	struct tm t;
	t.tm_year = 70; t.tm_mon = 0; t.tm_mday = 0;
	t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0;
	t.tm_isdst = -1;
	base = mktime(&t); /* could return -1 */
	flagbase = 1;
    }

    while (*cp) {
	switch(*cp) {
	    case '\t':
		StrAllocCopy(info->filename, cp + 1);
		return;
	    case 's':
		size = 0;
		while (*(++cp) && (*cp != ','))
		    size = (size * 10) + (*cp - '0');
		info->size = size;
		break;
	    case 'm':
		secs = 0;
		while (*(++cp) && (*cp != ','))
		    secs = (secs * 10) + (*cp - '0');
		secs += base; /* assumes that time_t is #seconds */
		strcpy(ct, ctime(&secs));
		ct[24] = 0;
		StrAllocCopy(info->date, ct);
		break;
	    case '/':
		StrAllocCopy(info->type, ENTRY_IS_DIRECTORY);
	    default:
		while (*cp) {
		    if (*cp++ == ',')
		      break;
		}
		break;
	}
    }
} /* parse_eplf_line */

/*
 * parse_ls_line() --
 *	Extract the name, size, and date from an ls -l line.
 */
PRIVATE void parse_ls_line ARGS2(
	char *,		line,
	EntryInfo *,	entry_info)
{
    short  i, j;
    int    base=1;
    int    size_num=0;

    for (i = strlen(line) - 1;
	 (i > 13) && (!isspace(line[i]) || !is_ls_date(&line[i-12])); i--)
	; /* null body */
    line[i] = '\0';
    if (i > 13) {
	StrAllocCopy(entry_info->date, &line[i-12]);
	/* replace the 4th location with nbsp if it is a space or zero */
	if (entry_info->date[4] == ' ' || entry_info->date[4] == '0')
	    entry_info->date[4] = HT_NON_BREAK_SPACE;
	/* make sure year or time is flush right */
	if (entry_info->date[11] == ' ') {
	    for (j = 11; j > 6; j--) {
		entry_info->date[j] = entry_info->date[j-1];
	    }
	}
    }
    j = i - 14;
    while (isdigit(line[j])) {
	size_num += (line[j] - '0') * base;
	base *= 10;
	j--;
    }
    entry_info->size = size_num;
    StrAllocCopy(entry_info->filename, &line[i + 1]);
} /* parse_ls_line() */

/*
 * parse_vms_dir_entry()
 *	Format the name, date, and size from a VMS LIST line
 *	into the EntryInfo structure - FM
 */
PRIVATE void parse_vms_dir_entry ARGS2(
	char *,		line,
	EntryInfo *,	entry_info)
{
    int i, j;
    unsigned int ialloc;
    char *cp, *cpd, *cps, date[16], *sp = " ";

    /**  Get rid of blank lines, and information lines.  **/
    /**  Valid lines have the ';' version number token.  **/
    if (!strlen(line) || (cp = strchr(line, ';')) == NULL) {
	entry_info->display = FALSE;
	return;
    }

    /** Cut out file or directory name at VMS version number. **/
    *cp++ ='\0';
    StrAllocCopy(entry_info->filename,line);

    /** Cast VMS non-README file and directory names to lowercase. **/
    if (strstr(entry_info->filename, "READ") == NULL) {
	LYLowerCase(entry_info->filename);
	i = strlen(entry_info->filename);
    } else {
	i = ((strstr(entry_info->filename, "READ") - entry_info->filename) + 4);
	if (!strncmp(&entry_info->filename[i], "ME", 2)) {
	    i += 2;
	    while (entry_info->filename[i] && entry_info->filename[i] != '.') {
		i++;
	    }
	} else if (!strncmp(&entry_info->filename[i], ".ME", 3)) {
	    i = strlen(entry_info->filename);
	} else {
	    i = 0;
	}
	LYLowerCase(entry_info->filename + i);
    }

    /** Uppercase terminal .z's or _z's. **/
    if ((--i > 2) &&
	entry_info->filename[i] == 'z' &&
	(entry_info->filename[i-1] == '.' ||
	 entry_info->filename[i-1] == '_'))
	entry_info->filename[i] = 'Z';

    /** Convert any tabs in rest of line to spaces. **/
    cps = cp-1;
    while ((cps=strchr(cps+1, '\t')) != NULL)
	*cps = ' ';

    /** Collapse serial spaces. **/
    i = 0; j = 1;
    cps = cp;
    while (cps[j] != '\0') {
	if (cps[i] == ' ' && cps[j] == ' ')
	    j++;
	else
	    cps[++i] = cps[j++];
    }
    cps[++i] = '\0';

    /* Set the years and date, if we don't have them yet. **/
    if (!HaveYears) {
	set_years_and_date();
    }

    /** Track down the date. **/
    if ((cpd=strchr(cp, '-')) != NULL &&
	strlen(cpd) > 9 && isdigit(*(cpd-1)) &&
	isalpha(*(cpd+1)) && *(cpd+4) == '-') {

	/** Month **/
	*(cpd+4) = '\0';
	*(cpd+2) = TOLOWER(*(cpd+2));
	*(cpd+3) = TOLOWER(*(cpd+3));
	sprintf(date, "%s ", cpd+1);
	*(cpd+4) = '-';

	/** Day **/
	*cpd = '\0';
	if (isdigit(*(cpd-2)))
	    sprintf(date+4, "%s ", cpd-2);
	else
	    sprintf(date+4, "%c%s ", HT_NON_BREAK_SPACE, cpd-1);
	*cpd = '-';

	/** Time or Year **/
	if (!strncmp(ThisYear, cpd+5, 4) &&
	    strlen(cpd) > 15 && *(cpd+12) == ':') {
	    *(cpd+15) = '\0';
	    sprintf(date+7, "%s", cpd+10);
	    *(cpd+15) = ' ';
	} else {
	    *(cpd+9) = '\0';
	    sprintf(date+7, " %s", cpd+5);
	    *(cpd+9) = ' ';
	}

	StrAllocCopy(entry_info->date, date);
    }

    /** Track down the size **/
    if ((cpd=strchr(cp, '/')) != NULL) {
	/* Appears be in used/allocated format */
	cps = cpd;
	while (isdigit(*(cps-1)))
	    cps--;
	if (cps < cpd)
	    *cpd = '\0';
	entry_info->size = atoi(cps);
	cps = cpd+1;
	while (isdigit(*cps))
	    cps++;
	*cps = '\0';
	ialloc = atoi(cpd+1);
	/* Check if used is in blocks or bytes */
	if (entry_info->size <= ialloc)
	    entry_info->size *= 512;

    } else if ((cps=strtok(cp, sp)) != NULL) {
	/* We just initialized on the version number */
	/* Now let's hunt for a lone, size number    */
	while ((cps=strtok(NULL, sp)) != NULL) {
	    cpd = cps;
	    while (isdigit(*cpd))
		cpd++;
	    if (*cpd == '\0') {
		/* Assume it's blocks */
		entry_info->size = atoi(cps) * 512;
		break;
	    }
	}
    }

    /** Wrap it up **/
    CTRACE(tfp, "HTFTP: VMS filename: %s  date: %s  size: %d\n",
		entry_info->filename,
		entry_info->date ? entry_info->date : "",
		entry_info->size);
    return;
} /* parse_vms_dir_entry() */

/*
 * parse_ms_windows_dir_entry() --
 *	Format the name, date, and size from an MS_WINDOWS LIST line into
 *	the EntryInfo structure (assumes Chameleon NEWT format). - FM
 */
PRIVATE void parse_ms_windows_dir_entry ARGS2(
	char *,		line,
	EntryInfo *,	entry_info)
{
    char *cp = line;
    char *cps, *cpd, date[16];
    char *end = line + strlen(line);

    /**  Get rid of blank or junk lines.  **/
    cp = LYSkipBlanks(cp);
    if (!(*cp)) {
	entry_info->display = FALSE;
	return;
    }

    /** Cut out file or directory name. **/
    cps = LYSkipNonBlanks(cp);
    *cps++ ='\0';
    cpd = cps;
    StrAllocCopy(entry_info->filename, cp);

    /** Track down the size **/
    if (cps < end) {
	cps = LYSkipBlanks(cps);
	cpd = LYSkipNonBlanks(cps);
	*cpd++ = '\0';
	if (isdigit(*cps)) {
	    entry_info->size = atoi(cps);
	} else {
	    StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
	}
    } else {
	StrAllocCopy(entry_info->type, "");
    }

    /* Set the years and date, if we don't have them yet. **/
    if (!HaveYears) {
	set_years_and_date();
    }

    /** Track down the date. **/
    if (cpd < end) {
	cpd = LYSkipBlanks(cpd);
	if (strlen(cpd) > 17) {
	    *(cpd+6)  = '\0';  /* Month and Day */
	    *(cpd+11) = '\0';  /* Year */
	    *(cpd+17) = '\0';  /* Time */
	    if (strcmp(ThisYear, cpd+7))
		/* Not this year, so show the year */
		sprintf(date, "%s  %s", cpd, (cpd+7));
	    else
		/* Is this year, so show the time */
		sprintf(date, "%s %s", cpd, (cpd+12));
	    StrAllocCopy(entry_info->date, date);
	    if (entry_info->date[4] == ' '|| entry_info->date[4] == '0') {
		entry_info->date[4] = HT_NON_BREAK_SPACE;
	    }
	}
    }

    /** Wrap it up **/
    CTRACE(tfp, "HTFTP: MS Windows filename: %s  date: %s  size: %d\n",
		entry_info->filename,
		entry_info->date ? entry_info->date : "",
		entry_info->size);
    return;
} /* parse_ms_windows_dir_entry */

/*
 * parse_windows_nt_dir_entry() --
 *	Format the name, date, and size from a WINDOWS_NT LIST line into
 *	the EntryInfo structure (assumes Chameleon NEWT format). - FM
 */
#ifdef NOTDEFINED
PRIVATE void parse_windows_nt_dir_entry ARGS2(
	char *,		line,
	EntryInfo *,	entry_info)
{
    char *cp = line;
    char *cps, *cpd, date[16];
    char *end = line + strlen(line);
    int i;

    /**  Get rid of blank or junk lines.  **/
    cp = LYSkipBlanks(cp);
    if (!(*cp)) {
	entry_info->display = FALSE;
	return;
    }

    /** Cut out file or directory name. **/
    cpd = cp;
    cps = LYSkipNonBlanks(end-1);
    cp = (cps+1);
    if (!strcmp(cp, ".") || !strcmp(cp, "..")) {
	entry_info->display = FALSE;
	return;
    }
    StrAllocCopy(entry_info->filename, cp);
    if (cps < cpd)
	return;
    *cp = '\0';
    end = cp;

    /* Set the years and date, if we don't have them yet. **/
    if (!HaveYears) {
	set_years_and_date();
    }

    /** Cut out the date. **/
    cp = cps = cpd;
    cps = LYSkipNonBlanks(cps);
    *cps++ ='\0';
    if (cps > end) {
	entry_info->display = FALSE;
	return;
    }
    cps = LYSkipBlanks(cps);
    cpd = LYSkipNonBlanks(cps);
    *cps++ ='\0';
    if (cps > end || cpd == cps || strlen(cpd) < 7) {
	entry_info->display = FALSE;
	return;
    }
    if (strlen(cp) == 8 &&
	isdigit(*cp) && isdigit(*(cp+1)) && *(cp+2) == '-' &&
	isdigit(*(cp+3)) && isdigit(*(cp+4)) && *(cp+5) == '-') {
	*(cp+2)  = '\0';	/* Month */
	i = atoi(cp) - 1;
	*(cp+5) = '\0';		/* Day */
	sprintf(date, "%s %s", months[i], (cp+3));
	if (date[4] == '0')
	    date[4] = ' ';
	cp += 6;			/* Year */
	if (strcmp((ThisYear+2), cp)) {
	    /* Not this year, so show the year */
	    if (atoi(cp) < 70) {
		sprintf(&date[6], "  20%s", cp);
	    } else {
		sprintf(&date[6], "  19%s", cp);
	    }
	} else {
	    /* Is this year, so show the time */
	    *(cpd+2) = '\0';	/* Hour */
	    i = atoi(cpd);
	    if (*(cpd+5) == 'P' || *(cpd+5) == 'p')
		i += 12;
	    *(cpd+5) = '\0';
	    sprintf(&date[6], " %s%d:%s",
				     (i < 10 ? "0" : ""), i, (cpd+3));
	}
	StrAllocCopy(entry_info->date, date);
	if (entry_info->date[4] == ' '|| entry_info->date[4] == '0') {
	    entry_info->date[4] = HT_NON_BREAK_SPACE;
	}
    }

    /** Track down the size **/
    if (cps < end) {
	cps = LYSkipBlanks(cps);
	cpd = LYSkipNonBlanks(cps);
	*cpd = '\0';
	if (isdigit(*cps)) {
	    entry_info->size = atoi(cps);
	} else {
	    StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
	}
    } else {
	StrAllocCopy(entry_info->type, "");
    }

    /** Wrap it up **/
    CTRACE(tfp, "HTFTP: Windows NT filename: %s  date: %s  size: %d\n",
		entry_info->filename,
		entry_info->date ? entry_info->date : "",
		entry_info->size);
    return;
} /* parse_windows_nt_dir_entry */
#endif /* NOTDEFINED */

/*
 * parse_cms_dir_entry() --
 *	Format the name, date, and size from a VM/CMS line into
 *	the EntryInfo structure. - FM
 */
PRIVATE void parse_cms_dir_entry ARGS2(
	char *,		line,
	EntryInfo *,	entry_info)
{
    char *cp = line;
    char *cps, *cpd, date[16];
    char *end = line + strlen(line);
    int RecordLength = 0;
    int Records = 0;
    int i;

    /**  Get rid of blank or junk lines.  **/
    cp = LYSkipBlanks(cp);
    if (!(*cp)) {
	entry_info->display = FALSE;
	return;
    }

    /** Cut out file or directory name. **/
    cps = LYSkipNonBlanks(cp);
    *cps++ ='\0';
    StrAllocCopy(entry_info->filename, cp);
    if (strchr(entry_info->filename, '.') != NULL)
	/** If we already have a dot, we did an NLST. **/
	return;
    cp = LYSkipBlanks(cps);
    if (!(*cp)) {
	/** If we don't have more, we've misparsed. **/
	FREE(entry_info->filename);
	FREE(entry_info->type);
	entry_info->display = FALSE;
	return;
    }
    cps = LYSkipNonBlanks(cp);
    *cps++ ='\0';
    if ((0 == strcasecomp(cp, "DIR")) && (cp - line) > 17) {
	/** It's an SFS directory. **/
	StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
	entry_info->size = 0;
    } else {
	/** It's a file. **/
	cp--;
	*cp = '.';
	StrAllocCat(entry_info->filename, cp);

	/** Track down the VM/CMS RECFM or type. **/
	cp = cps;
	if (cp < end) {
	    cp = LYSkipBlanks(cp);
	    cps = LYSkipNonBlanks(cp);
	    *cps++ = '\0';
	    /** Check cp here, if it's relevant someday. **/
	}
    }

    /** Track down the record length or dash. **/
    cp = cps;
    if (cp < end) {
	cp = LYSkipBlanks(cp);
	cps = LYSkipNonBlanks(cp);
	*cps++ = '\0';
	if (isdigit(*cp)) {
	    RecordLength = atoi(cp);
	}
    }

    /** Track down the number of records or the dash. **/
    cp = cps;
    if (cps < end) {
	cp = LYSkipBlanks(cp);
	cps = LYSkipNonBlanks(cp);
	*cps++ = '\0';
	if (isdigit(*cp)) {
	    Records = atoi(cp);
	}
	if (Records > 0 && RecordLength > 0) {
	    /** Compute an approximate size. **/
	    entry_info->size = (Records * RecordLength);
	}
    }

    /** Set the years and date, if we don't have them yet. **/
    if (!HaveYears) {
	set_years_and_date();
    }

    /** Track down the date. **/
    cpd = cps;
    if (((cps < end) &&
	 (cps = strchr(cpd, ':')) != NULL) &&
	(cps < (end - 3) &&
	 isdigit(*(cps+1)) && isdigit(*(cps+2)) && *(cps+3) == ':')) {
	cps += 3;
	*cps = '\0';
	if ((cps - cpd) >= 14) {
	    cpd = (cps - 14);
	    *(cpd+2) = '\0';	/* Month */
	    *(cpd+5) = '\0';	/* Day */
	    *(cpd+8) = '\0';	/* Year */
	    cps -= 5;		/* Time */
	    if (*cpd == ' ')
		*cpd = '0';
	    i = atoi(cpd) - 1;
	    sprintf(date, "%s %s", months[i], (cpd+3));
	    if (date[4] == '0')
		date[4] = ' ';
	    cpd += 6;		/* Year */
	    if (strcmp((ThisYear+2), cpd)) {
		/* Not this year, so show the year. */
		if (atoi(cpd) < 70) {
		    sprintf(&date[6], "  20%s", cpd);
		} else {
		    sprintf(&date[6], "  19%s", cpd);
		}
	    } else {
		/* Is this year, so show the time. */
		*(cps+2) = '\0';	/* Hour */
		i = atoi(cps);
		sprintf(&date[6], " %s%d:%s",
				     (i < 10 ? "0" : ""), i, (cps+3));
	    }
	    StrAllocCopy(entry_info->date, date);
	    if (entry_info->date[4] == ' '|| entry_info->date[4] == '0') {
		entry_info->date[4] = HT_NON_BREAK_SPACE;
	    }
	}
    }

    /** Wrap it up. **/
    CTRACE(tfp, "HTFTP: VM/CMS filename: %s  date: %s  size: %d\n",
		entry_info->filename,
		entry_info->date ? entry_info->date : "",
		entry_info->size);
    return;
} /* parse_cms_dir_entry */

/*
 *     parse_dir_entry()
 *	Given a line of LIST/NLST output in entry, return results
 *	and a file/dir name in entry_info struct
 *
 *	If first is true, this is the first name in a directory.
 */

PRIVATE EntryInfo * parse_dir_entry ARGS2(
	char *,		entry,
	BOOLEAN *,	first)
{
    EntryInfo *entry_info;
    int  i;
    int  len;
    BOOLEAN remove_size=FALSE;
    char *cp;

    entry_info = (EntryInfo *)malloc(sizeof(EntryInfo));
    if (entry_info == NULL)
	outofmem(__FILE__, "parse_dir_entry");
    entry_info->filename = NULL;
    entry_info->type = NULL;
    entry_info->date = NULL;
    entry_info->size = 0;
    entry_info->display = TRUE;

    switch (server_type) {
	case UNIX_SERVER:
	case PETER_LEWIS_SERVER:
	case MACHTEN_SERVER:
	case MSDOS_SERVER:
	case WINDOWS_NT_SERVER:
	case APPLESHARE_SERVER:
	case NETPRESENZ_SERVER:
	    /*
	    **	Check for EPLF output (local times).
	    */
	    if (*entry == '+') {
		parse_eplf_line(entry, entry_info);
		break;
	    }

	    /*
	    **	Interpret and edit LIST output from Unix server.
	    */
	    len = strlen(entry);
	    if (*first) {
		/* don't gettext() this -- incoming text: */
		if (!strcmp(entry, "can not access directory .")) {
		    /*
		     *	Don't reset *first, nothing real will follow. - KW
		     */
		    entry_info->display = FALSE;
		    return(entry_info);
		}
		*first = FALSE;
		if (!strncmp(entry, "total ", 6) ||
		    strstr(entry, "not available") != NULL) {
		    entry_info->display = FALSE;
		    return(entry_info);
		} else if (unsure_type) {
		    /* this isn't really a unix server! */
		    server_type = GENERIC_SERVER;
		    entry_info->display = FALSE;
		    return(entry_info);
		}
	    }

	    /*
	    **	Check first character of ls -l output.
	    */
	    if (TOUPPER(entry[0]) == 'D')  {
		/*
		**  It's a directory.
		*/
		StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
		remove_size=TRUE; /* size is not useful */
	    } else if (entry[0] == 'l') {
		/*
		**  It's a symbolic link, does the user care about
		**  knowing if it is symbolic?	I think so since
		**  it might be a directory.
		*/
		StrAllocCopy(entry_info->type, gettext("Symbolic Link"));
		remove_size=TRUE; /* size is not useful */

		/*
		**  Strip off " -> pathname".
		*/
		for (i = len - 1; (i > 3) &&
				  (!isspace(entry[i]) ||
				   (entry[i-1] != '>')	||
				   (entry[i-2] != '-') ||
				   (entry[i-3] != ' ')); i--)
		    ; /* null body */
		if (i > 3) {
		    entry[i-3] = '\0';
		    len = i - 3;
		}
	    } /* link */

	    parse_ls_line(entry, entry_info);

	    if (!strcmp(entry_info->filename,"..") ||
		!strcmp(entry_info->filename,"."))
		entry_info->display = FALSE;
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;

	case VMS_SERVER:
	    /*
	    **	Interpret and edit LIST output from VMS server
	    **	and convert information lines to zero length.
	    */
	    parse_vms_dir_entry(entry, entry_info);

	    /*
	    **	Get rid of any junk lines.
	    */
	    if (!entry_info->display)
		return(entry_info);

	    /*
	    **	Trim off VMS directory extensions.
	    */
	    len = strlen(entry_info->filename);
	    if ((len > 4) && !strcmp(&entry_info->filename[len-4], ".dir")) {
		entry_info->filename[len-4] = '\0';
		StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
		remove_size=TRUE; /* size is not useful */
	    }
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;

	case MS_WINDOWS_SERVER:
	    /*
	    **	Interpret and edit LIST output from MS_WINDOWS server
	    **	and convert information lines to zero length.
	    */
	    parse_ms_windows_dir_entry(entry, entry_info);

	    /*
	    **	Get rid of any junk lines.
	    */
	    if (!entry_info->display)
		return(entry_info);
	    if (entry_info->type && *entry_info->type == '\0') {
		FREE(entry_info->type);
		return(entry_info);
	    }
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;

#ifdef NOTDEFINED
	case WINDOWS_NT_SERVER:
	    /*
	    **	Interpret and edit LIST output from MS_WINDOWS server
	    **	and convert information lines to zero length.
	    */
	    parse_windows_nt_dir_entry(entry, entry_info);

	    /*
	    **	Get rid of any junk lines.
	    */
	    if (!entry_info->display)
		return(entry_info);
	    if (entry_info->type && *entry_info->type == '\0') {
		FREE(entry_info->type);
		return(entry_info);
	    }
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;
#endif /* NOTDEFINED */

	case CMS_SERVER:
	  {
	    /*
	    **	Interpret and edit LIST output from VM/CMS server
	    **	and convert any information lines to zero length.
	    */
	    parse_cms_dir_entry(entry, entry_info);

	    /*
	    **	Get rid of any junk lines.
	    */
	    if (!entry_info->display)
		return(entry_info);
	    if (entry_info->type && *entry_info->type == '\0') {
		FREE(entry_info->type);
		return(entry_info);
	    }
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;
	  }

	case NCSA_SERVER:
	case TCPC_SERVER:
	    /*
	    **	Directories identified by trailing "/" characters.
	    */
	    StrAllocCopy(entry_info->filename, entry);
	    len = strlen(entry);
	    if (entry[len-1] == '/') {
		/*
		**  It's a dir, remove / and mark it as such.
		*/
		entry[len-1] = '\0';
		StrAllocCopy(entry_info->type, ENTRY_IS_DIRECTORY);
		remove_size=TRUE; /* size is not useful */
	    }
	    /*
	    **	Goto the bottom and get real type.
	    */
	    break;

	default:
	    /*
	    **	We can't tell if it is a directory since we only
	    **	did an NLST :(	List bad file types anyways?  NOT!
	    */
	    StrAllocCopy(entry_info->filename, entry);
	    return(entry_info); /* mostly empty info */

    } /* switch (server_type) */

    if (remove_size && entry_info->size) {
	entry_info->size = 0;
    }

    if (entry_info->filename && strlen(entry_info->filename) > 3) {
	if (((cp=strrchr(entry_info->filename, '.')) != NULL &&
	     0 == strncasecomp(cp, ".me", 3)) &&
	    (cp[3] == '\0' || cp[3] == ';')) {
	    /*
	    **	Don't treat this as application/x-Troff-me
	    **	if it's a Unix server but has the string
	    **	"read.me", or if it's not a Unix server. - FM
	    */
	    if ((server_type != UNIX_SERVER) ||
		(cp > (entry_info->filename + 3) &&
		 0 == strncasecomp((cp - 4), "read.me", 7))) {
		StrAllocCopy(entry_info->type, "text/plain");
	    }
	}
    }

    /*
    **	Get real types eventually.
    */
    if (!entry_info->type) {
	CONST char *cp2;
	HTFormat format;
	HTAtom * encoding;  /* @@ not used at all */
	format = HTFileFormat(entry_info->filename, &encoding, &cp2);

	if (cp2 == NULL) {
	    if (!strncmp(HTAtom_name(format), "application",11)) {
		cp2 = HTAtom_name(format) + 12;
		if (!strncmp(cp2,"x-",2))
		    cp2 += 2;
	    } else {
		cp2 = HTAtom_name(format);
	    }
	}

	StrAllocCopy(entry_info->type, cp2);
    }

    return(entry_info);
} /* parse_dir_entry */

PRIVATE int compare_EntryInfo_structs ARGS2(
	EntryInfo *,	entry1,
	EntryInfo *,	entry2)
{
    int i, status;
    char date1[16], date2[16], time1[8], time2[8], month[4];

    switch(HTfileSortMethod) {
	case FILE_BY_SIZE:
	    /* both equal or both 0 */
	    if (entry1->size == entry2->size)
		return(strcmp(entry1->filename, entry2->filename));
	    else
		if (entry1->size > entry2->size)
		    return(1);
		else
		    return(-1);

	case FILE_BY_TYPE:
	    if (entry1->type && entry2->type) {
		status = strcasecomp(entry1->type, entry2->type);
		if (status)
		    return(status);
		/* else fall to filename comparison */
	    }
	    return (strcmp(entry1->filename, entry2->filename));

	case FILE_BY_DATE:
	    if (entry1->date && entry2->date) {
		/*
		** Make sure we have the correct length. - FM
		*/
		if (strlen(entry1->date) != 12 || strlen(entry2->date) != 12) {
		    return(strcmp(entry1->filename, entry2->filename));
		}
		/*
		** Set the years and date,
		** if we don't have them yet.
		*/
		if (!HaveYears) {
		    set_years_and_date();
		}
		/*
		** Set up for sorting in reverse
		** chronological order. - FM
		*/
		if (entry1->date[9] == ':') {
		    strcpy(date1, "9999");
		    strcpy(time1, &entry1->date[7]);
		    if (time1[0] == ' ') {
			 time1[0] = '0';
		    }
		} else {
		    strcpy(date1, &entry1->date[8]);
		    strcpy(time1, "00:00");
		}
		strncpy(month, entry1->date, 3);
		month[3] = '\0';
		for (i = 0; i < 12; i++) {
		    if (!strcasecomp(month, months[i])) {
			break;
		    }
		}
		i++;
		sprintf(month, "%s%d", (i < 10 ? "0" : ""), i);
		strcat(date1, month);
		strncat(date1, &entry1->date[4], 2);
		date1[8] = '\0';
		if (date1[6] == ' ' || date1[6] == HT_NON_BREAK_SPACE) {
		    date1[6] = '0';
		}
		if (date1[0] == '9' && atoi(date1) > TheDate) {
		    for (i = 0; i < 4; i++) {
			date1[i] = LastYear[i];
		    }
		}
		strcat(date1, time1);
		    if (entry2->date[9] == ':') {
			strcpy(date2, "9999");
			strcpy(time2, &entry2->date[7]);
			if (time2[0] == ' ') {
			    time2[0] = '0';
			}
		    } else {
			strcpy(date2, &entry2->date[8]);
			strcpy(time2, "00:00");
		    }
		strncpy(month, entry2->date, 3);
		month[3] = '\0';
		for (i = 0; i < 12; i++) {
		    if (!strcasecomp(month, months[i])) {
			break;
		    }
		}
		i++;
		sprintf(month, "%s%d", (i < 10 ? "0" : ""), i);
		strcat(date2, month);
		strncat(date2, &entry2->date[4], 2);
		date2[8] = '\0';
		if (date2[6] == ' ' || date2[6] == HT_NON_BREAK_SPACE) {
		    date2[6] = '0';
		}
		if (date2[0] == '9' && atoi(date2) > TheDate) {
		    for (i = 0; i < 4; i++) {
			date2[i] = LastYear[i];
		    }
		}
		strcat(date2, time2);
		/*
		** Do the comparison. - FM
		*/
		status = strcasecomp(date2, date1);
		if (status)
		    return(status);
		/* else fall to filename comparison */
	    }
	    return (strcmp(entry1->filename, entry2->filename));

	case FILE_BY_NAME:
	default:
	    return (strcmp(entry1->filename, entry2->filename));
    }
}


/*	Read a directory into an hypertext object from the data socket
**	--------------------------------------------------------------
**
** On entry,
**	anchor		Parent anchor to link the this node to
**	address		Address of the directory
** On exit,
**	returns		HT_LOADED if OK
**			<0 if error.
*/
PRIVATE int read_directory ARGS4(
	HTParentAnchor *,	parent,
	CONST char *,		address,
	HTFormat,		format_out,
	HTStream *,		sink)
{
    int status;
    BOOLEAN WasInterrupted = FALSE;
    HTStructured* target = HTML_new(parent, format_out, sink);
    HTStructuredClass targetClass;
    char *filename = HTParse(address, "", PARSE_PATH + PARSE_PUNCTUATION);
    EntryInfo *entry_info;
    BOOLEAN first = TRUE;
    char string_buffer[64];
    char *lastpath = NULL;/* prefix for link, either "" (for root) or xxx  */
    BOOL need_parent_link = FALSE;
    BOOL tildeIsTop = FALSE;

    targetClass = *(target->isa);

    _HTProgress (gettext("Receiving FTP directory."));

    /*
    **	Check whether we always want the home
    **	directory treated as Welcome. - FM
    */
    if (server_type == VMS_SERVER)
	tildeIsTop = TRUE;

    /*
    **	This should always come back FALSE, since the
    **	flag is set only for local directory listings
    **	if LONG_LIST was defined on compilation, but
    **	we could someday set up an equivalent listing
    **	for Unix ftp servers. - FM
    */
    need_parent_link = HTDirTitles(target, (HTAnchor*)parent, tildeIsTop);

    data_read_pointer = data_write_pointer = data_buffer;

    if (*filename == '\0') {		  /* Empty filename: use root. */
	StrAllocCopy (lastpath, "/");
    } else if (!strcmp(filename,"/")) {   /* Root path. */
	StrAllocCopy (lastpath, "/foo/..");
    } else {
	char * p = strrchr(filename, '/');	     /* Find the lastslash. */
	char *cp;

	if (server_type == CMS_SERVER) {
	    StrAllocCopy(lastpath, filename); /* Use absolute path for CMS. */
	} else {
	    StrAllocCopy(lastpath, p+1);   /* Take slash off the beginning. */
	}
	if ((cp = strrchr(lastpath, ';')) != NULL) {   /* Trim type= param. */
	    if (!strncasecomp((cp+1), "type=", 5)) {
		if (TOUPPER(*(cp+6)) == 'D' ||
		    TOUPPER(*(cp+6)) == 'A' ||
		    TOUPPER(*(cp+6)) == 'I')
		    *cp = '\0';
	    }
	}
    }
    FREE (filename);


    {
	HTBTree * bt = HTBTree_new((HTComparer)compare_EntryInfo_structs);
	int ic;
	HTChunk * chunk = HTChunkCreate(128);
	int BytesReceived = 0;
	int BytesReported = 0;
	char NumBytes[64];
	PUTC('\n');  /* prettier LJM */
	for (ic = 0; ic != EOF;) {	/* For each entry in the directory */
	    HTChunkClear(chunk);

	    if (HTCheckForInterrupt()) {
		WasInterrupted = TRUE;
		if (BytesReceived) {
		    goto unload_btree;	/* unload btree */
		} else {
		    ABORT_TARGET;
		    HTBTreeAndObject_free(bt);
		    return HT_INTERRUPTED;
		}
	    }

	    /*	 read directory entry
	     */
	    for (;;) {			/* Read in one line as filename */
		ic = NEXT_DATA_CHAR;
AgainForMultiNet:
		if (interrupted_in_next_data_char) {
		    WasInterrupted = TRUE;
		    if (BytesReceived) {
			goto unload_btree;  /* unload btree */
		    } else {
			ABORT_TARGET;
			HTBTreeAndObject_free(bt);
			return HT_INTERRUPTED;
		    }
		} else if ((char)ic == CR || (char)ic == LF) {    /* Terminator? */
		    if (chunk->size != 0) {  /* got some text */
			/* Deal with MultiNet's wrapping of long lines */
			if (server_type == VMS_SERVER) {
			/* Deal with MultiNet's wrapping of long lines - F.M. */
			    if (data_read_pointer < data_write_pointer &&
				*(data_read_pointer+1) == ' ')
				data_read_pointer++;
			    else if (data_read_pointer >= data_write_pointer) {
				status = NETREAD(data_soc, data_buffer,
						 DATA_BUFFER_SIZE);
				if (status == HT_INTERRUPTED) {
				    interrupted_in_next_data_char = 1;
				    goto AgainForMultiNet;
				}
				if (status <= 0) {
				    ic = EOF;
				    break;
				}
				data_write_pointer = data_buffer + status;
				data_read_pointer = data_buffer;
				if (*data_read_pointer == ' ')
				    data_read_pointer++;
				else
				    break;
			    }
			    else
				break;
			}
			else
			    break;	/* finish getting one entry */
		    }
		} else if (ic == EOF) {
		    break;		/* End of file */
		} else {
		    HTChunkPutc(chunk, (char)ic);
		}
	    }
	    HTChunkTerminate(chunk);

	    BytesReceived += chunk->size;
	    if (BytesReceived > BytesReported + 1024) {
		sprintf(NumBytes, TRANSFERRED_X_BYTES, BytesReceived);
		HTProgress(NumBytes);
		BytesReported = BytesReceived;
	    }

	    if (ic == EOF && chunk->size == 1)
	    /* 1 means empty: includes terminating 0 */
		break;
	    CTRACE(tfp, "HTFTP: Line in %s is %s\n",
			lastpath, chunk->data);

	    entry_info = parse_dir_entry(chunk->data, &first);
	    if (entry_info->display) {
		CTRACE(tfp, "Adding file to BTree: %s\n",
			    entry_info->filename);
		HTBTree_add(bt, (EntryInfo *)entry_info);
	    } else {
		free_entryinfo_struct_contents(entry_info);
		FREE(entry_info);
	    }

	}  /* next entry */

unload_btree:

	HTChunkFree(chunk);

	/* print out the handy help message if it exits :) */
	if (help_message_cache_non_empty()) {
	    START(HTML_PRE);
	    START(HTML_HR);
	    PUTC('\n');
	    PUTS(help_message_cache_contents());
	    init_help_message_cache();	/* to free memory */
	    START(HTML_HR);
	    PUTC('\n');
	} else {
	    START(HTML_PRE);
	    PUTC('\n');
	}

	/* Put up header
	 */
	/* PUTS("    Date	 Type		  Size	   Filename\n");
	 */

	/* Run through tree printing out in order
	 */
	{
	    HTBTElement * ele;
	    int i;
	    for (ele = HTBTree_next(bt, NULL);
		 ele != NULL;
		 ele = HTBTree_next(bt, ele)) {
		entry_info = (EntryInfo *)HTBTree_object(ele);

		if (entry_info->date) {
		    PUTS(entry_info->date);
		    PUTS("  ");
		} else {
		    PUTS("     * ");
		}

		if (entry_info->type) {
		    for (i = 0; entry_info->type[i] != '\0' && i < 15; i++)
			PUTC(entry_info->type[i]);
		    for (; i < 17; i++)
			PUTC(' ');
		}

		/* start the anchor */
		HTDirEntry(target, lastpath, entry_info->filename);
		PUTS(entry_info->filename);
		END(HTML_A);

		if (entry_info->size) {
		    if (entry_info->size < 1024)
			sprintf(string_buffer, "  %d bytes",
					       entry_info->size);
		    else
			sprintf(string_buffer, "  %dKb",
						entry_info->size/1024);
		    PUTS(string_buffer);
		}

		PUTC('\n'); /* end of this entry */

		free_entryinfo_struct_contents(entry_info);
	    }
	}
	END(HTML_PRE);
	FREE_TARGET;
	HTBTreeAndObject_free(bt);
    }

    FREE(lastpath);

    if (server_type == APPLESHARE_SERVER ||
	server_type == NETPRESENZ_SERVER) {
	/*
	 *  Without closing the data socket first,
	 *  the response(NIL) below hangs. - KW
	 */
	NETCLOSE(data_soc);
    }

    if (WasInterrupted || HTCheckForInterrupt()) {
	if (server_type != CMS_SERVER)
	    response(NIL);
	_HTProgress(TRANSFER_INTERRUPTED);
	return HT_LOADED;
    }
    if (server_type != CMS_SERVER)
	response(NIL);
    return HT_LOADED;
#ifdef NOTDEFINED
    return response(NIL) == 2 ? HT_LOADED : -1;
#endif /* NOTDEFINED */
}

/*	Retrieve File from Server
**	-------------------------
**
** On entry,
**	name		WWW address of a file: document, including hostname
** On exit,
**	returns		Socket number for file if good.
**			<0 if bad.
*/
PUBLIC int HTFTPLoad ARGS4(
	CONST char *,		name,
	HTParentAnchor *,	anchor,
	HTFormat,		format_out,
	HTStream *,		sink)
{
    BOOL isDirectory = NO;
    HTAtom * encoding = NULL;
    int status;
    int retry;			/* How many times tried? */
    HTFormat format;


    /* set use_list to NOT since we don't know what kind of server
     * this is yet.  And set the type to GENERIC
     */
    use_list = FALSE;
    server_type = GENERIC_SERVER;

    for (retry = 0; retry < 2; retry++) { /* For timed out/broken connections */
	status = get_connection(name, anchor);
	if (status < 0)
	    return status;

#ifdef LISTEN
	status = get_listen_socket();
	if (status < 0) {
	    NETCLOSE (control->socket);
	    control->socket = -1;
	    close_master_socket ();
	    /* HT_INTERRUPTED would fall through, if we could interrupt
	       somehow in the middle of it, which we currently can't. */
	    return status;
	}

#ifdef REPEAT_PORT
/*	Inform the server of the port number we will listen on
*/
	{
	    status = response(port_command);
	    if (status == HT_INTERRUPTED) {
		CTRACE (tfp, "HTFTP: Interrupted in response (port_command)\n");
		_HTProgress (CONNECTION_INTERRUPTED);
		NETCLOSE (control->socket);
		control->socket = -1;
		close_master_socket ();
		return HT_INTERRUPTED;
	    }
	    if (status != 2) {		/* Could have timed out */
		if (status < 0)
		    continue;		/* try again - net error*/
		return -status;		/* bad reply */
	    }
	    CTRACE(tfp, "HTFTP: Port defined.\n");
	}
#endif /* REPEAT_PORT */
#else	/* Use PASV */
/*	Tell the server to be passive
*/
	{
	    char command[LINE_LENGTH+1];
	    char *p;
	    int reply, h0, h1, h2, h3, p0, p1;	/* Parts of reply */
	    int status;
	    data_soc = status;

	    status = send_cmd_1("PASV");
	    if (status != 2) {
		if (status < 0)
		    continue;		/* retry or Bad return */
		return -status;		/* bad reply */
	    }
	    for (p = response_text; *p && *p != ','; p++)
		; /* null body */

	    while (--p > response_text && '0' <= *p && *p <= '9')
		; /* null body */

	   status = sscanf(p+1, "%d,%d,%d,%d,%d,%d",
		   &h0, &h1, &h2, &h3, &p0, &p1);
	   if (status < 4) {
	       fprintf(tfp, "HTFTP: PASV reply has no inet address!\n");
	       return -99;
	   }
	   passive_port = (p0<<8) + p1;
	   CTRACE(tfp, "HTFTP: Server is listening on port %d\n",
			passive_port);


/*	Open connection for data:
*/
	    sprintf(command,
		    "ftp://%d.%d.%d.%d:%d/",h0,h1,h2,h3,passive_port);
	    status = HTDoConnect(name, "FTP", passive_port, &data_soc);

	    if (status < 0) {
		(void) HTInetStatus(gettext("connect for data"));
		NETCLOSE(data_soc);
		return status;			/* Bad return */
	    }

	    CTRACE(tfp, "FTP data connected, socket %d\n", data_soc);
	}
#endif /* use PASV */
	status = 0;
	break;	/* No more retries */

    } /* for retries */
    if (status < 0)
	return status;		/* Failed with this code */

/*	Ask for the file:
*/
    {
	char *filename = HTParse(name, "", PARSE_PATH + PARSE_PUNCTUATION);
	char *fname = filename; /** Save for subsequent free() **/
	BOOL binary;
	char *type = NULL;
	char *cp;

	if (server_type == CMS_SERVER) {
	    /** If the unescaped path has a %2f, reject it as illegal. - FM **/
	    if (((cp = strstr(filename, "%2")) != NULL) &&
		TOUPPER(cp[2]) == 'F') {
		FREE(fname);
		init_help_message_cache();  /* to free memory */
		NETCLOSE(control->socket);
		control->socket = -1;
		CTRACE(tfp, "HTFTP: Rejecting path due to illegal escaped slash.\n");
		return -1;
	    }
	}

	if (!*filename) {
	    StrAllocCopy(filename, "/");
	    type = "D";
	} else if ((type = strrchr(filename, ';')) != NULL) {
	    /*
	    **	Check and trim the type= parameter. - FM
	    */
	    if (!strncasecomp((type+1), "type=", 5)) {
		switch(TOUPPER(*(type+6))) {
		case 'D':
		    *type = '\0';
		    type = "D";
		    break;
		case 'A':
		    *type = '\0';
		    type = "A";
		    break;
		case 'I':
		    *type = '\0';
		    type = "I";
		    break;
		default:
		    type = "";
		    break;
		}
		if (!*filename) {
		    *filename = '/';
		    *(filename+1) = '\0';
		}
	    }
	    if (*type != '\0') {
		CTRACE(tfp, "HTFTP: type=%s\n", type);
	    }
	}
	HTUnEscape(filename);
	CTRACE(tfp, "HTFTP: UnEscaped %s\n", filename);
	if (filename[1] == '~') {
	    /*
	    ** Check if translation of HOME as tilde is supported,
	    ** and adjust filename if so. - FM
	    */
	    char *cp2 = NULL;
	    char *fn = NULL;

	    if ((cp2 = strchr((filename+1), '/')) != NULL) {
		*cp2 = '\0';
	    }
	    status = send_cmd_1("PWD");
	    if (status == 2 && response_text[5] == '/') {
		status = send_cwd(filename+1);
		if (status == 2) {
		    StrAllocCopy(fn, (filename+1));
		    if (cp2) {
			*cp2 = '/';
			if (fn[strlen(fn)-1] != '/') {
			    StrAllocCat(fn, cp2);
			} else {
			    StrAllocCat(fn, (cp2+1));
			}
			cp2 = NULL;
		    }
		    FREE(fname);
		    fname = filename = fn;
		}
	    }
	    if (cp2) {
		*cp2 = '/';
	    }
	}
	if (strlen(filename) > 3) {
	    char *cp2;
	    if (((cp2=strrchr(filename, '.')) != NULL &&
		 0 == strncasecomp(cp2, ".me", 3)) &&
		(cp2[3] == '\0' || cp2[3] == ';')) {
		/*
		**  Don't treat this as application/x-Troff-me
		**  if it's a Unix server but has the string
		**  "read.me", or if it's not a Unix server. - FM
		*/
		if ((server_type != UNIX_SERVER) ||
		    (cp2 > (filename + 3) &&
		     0 == strncasecomp((cp2 - 4), "read.me", 7))) {
		    *cp2 = '\0';
		    format = HTFileFormat(filename, &encoding, NULL);
		    *cp2 = '.';
		} else {
		    format = HTFileFormat(filename, &encoding, NULL);
		}
	    } else {
		format = HTFileFormat(filename, &encoding, NULL);
	    }
	} else {
	    format = HTFileFormat(filename, &encoding, NULL);
	}
	format = HTCharsetFormat(format, anchor, -1);
	binary = (encoding != HTAtom_for("8bit") &&
		  encoding != HTAtom_for("7bit"));
	if (!binary &&
	    /*
	    **	Force binary if we're in source, download or dump
	    **	mode and this is not a VM/CMS server, so we don't
	    **	get CRLF instead of LF (or CR) for newlines in text
	    **	files.	Can't do this for VM/CMS or we'll get
	    **	raw EBCDIC.  - FM
	    */
	    (format_out == WWW_SOURCE ||
	     format_out == HTAtom_for("www/download") ||
	     format_out == HTAtom_for("www/dump")) &&
	    (server_type != CMS_SERVER))
	    binary = TRUE;
	if (!binary && type && *type == 'I') {
	    /*
	    **	Force binary if we had ;type=I - FM
	    */
	    binary = TRUE;
	} else if (binary && type && *type == 'A') {
	    /*
	    **	Force ASCII if we had ;type=A - FM
	    */
	    binary = FALSE;
	}
	if (binary != control->binary) {
	    /*
	    **	Act on our setting if not already set. - FM
	    */
	    char * mode = binary ? "I" : "A";
	    status = send_cmd_2("TYPE", mode);
	    if (status != 2) {
		init_help_message_cache();  /* to free memory */
		return ((status < 0) ? status : -status);
	    }
	    control->binary = binary;
	}
	switch (server_type) {
	/*
	**  Handle what for Lynx are special case servers, e.g.,
	**  for which we respect RFC 1738, or which have known
	**  conflicts in suffix mappings. - FM
	*/
	case VMS_SERVER:
	  {
	    char *cp1, *cp2;
	    BOOL included_device = FALSE;
	    /** Accept only Unix-style filename **/
	    if (strchr(filename, ':') != NULL ||
		strchr(filename, '[') != NULL) {
		FREE(fname);
		init_help_message_cache();  /* to free memory */
		NETCLOSE(control->socket);
		control->socket = -1;
		CTRACE(tfp, "HTFTP: Rejecting path due to non-Unix-style syntax.\n");
		return -1;
	    }
	    /** Handle any unescaped "/%2F" path **/
	    if (!strncmp(filename, "//", 2)) {
		int i;
		included_device = TRUE;
		for (i = 0; filename[(i+1)]; i++)
		    filename[i] = filename[(i+1)];
		filename[i] = '\0';
		CTRACE(tfp, "HTFTP: Trimmed '%s'\n", filename);
		cp = HTMake_VMS_name("", filename);
		CTRACE(tfp, "HTFTP: VMSized '%s'\n", cp);
		if ((cp1=strrchr(cp, ']')) != NULL) {
		    cp1++;
		    for (i = 0; cp1[i]; i++)
			filename[i] = cp1[i];
		    filename[i] = '\0';
		    CTRACE(tfp, "HTFTP: Filename '%s'\n", filename);
		    *cp1 = '\0';
		    status = send_cwd(cp);
		    if (status != 2) {
			char *dotslash = 0;
			if ((cp1=strchr(cp, '[')) != NULL) {
			    *cp1++ = '\0';
			    status = send_cwd(cp);
			    if (status != 2) {
				FREE(fname);
				init_help_message_cache(); /* to free memory */
				NETCLOSE(control->socket);
				control->socket = -1;
				return ((status < 0) ? status : -status);
			    }
			    HTSprintf0(&dotslash, "[.%s", cp1);
			    status = send_cwd(dotslash);
			    FREE(dotslash);
			    if (status != 2) {
				FREE(fname);
				init_help_message_cache(); /* to free memory */
				NETCLOSE(control->socket);
				control->socket = -1;
				return ((status < 0) ? status : -status);
			    }
			} else {
			    FREE(fname);
			    init_help_message_cache();	/* to free memory */
			    NETCLOSE(control->socket);
			    control->socket = -1;
			    return ((status < 0) ? status : -status);
			}
		    }
		} else if ((cp1=strchr(cp, ':')) != NULL &&
			   strchr(cp, '[') == NULL &&
			   strchr(cp, ']') == NULL) {
		    cp1++;
		    if (*cp1 != '\0') {
			for (i = 0; cp1[i]; i++)
			    filename[i] = cp1[i];
			filename[i] = '\0';
			CTRACE(tfp, "HTFTP: Filename '%s'\n", filename);
			*cp1 = '\0';
			strcat(cp, "[");
			strcat(cp, filename);
			strcat(cp, "]");
			status = send_cwd(cp);
			if (status != 2) {
			    *cp1 = '\0';
			    strcat(cp, "[000000]");
			    status = send_cwd(cp);
			    if (status != 2) {
				*cp1 = '\0';
				status = send_cwd(cp);
				if (status != 2) {
				    FREE(fname);
				    init_help_message_cache();
				    NETCLOSE(control->socket);
				    control->socket = -1;
				    return ((status < 0) ? status : -status);
				}
			    }
			} else {
			    strcpy(cp, "000000");
			    filename = cp;
			}
		    }
		} else if (0==strcmp(cp, (filename+1))) {
		    status = send_cwd(cp);
		    if (status != 2) {
			strcat(cp, ":");
			status = send_cwd(cp);
			if (status != 2) {
			    FREE(fname);
			    init_help_message_cache();	/* to free memory */
			    NETCLOSE(control->socket);
			    control->socket = -1;
			    return ((status < 0) ? status : -status);
			}
		    }
		    strcpy(cp, "000000");
		    filename = cp;
		}
	    }
	    /** Trim trailing slash if filename is not the top directory **/
	    if (strlen(filename) > 1 && filename[strlen(filename)-1] == '/')
		filename[strlen(filename)-1] = '\0';

#ifdef MAINTAIN_CONNECTION /* Don't need this if always new connection - F.M. */
	    if (!included_device) {
		/** Get the current default VMS device:[directory] **/
		status = send_cmd_1("PWD");
		if (status != 2) {
		    FREE(fname);
		    init_help_message_cache();	/* to free memory */
		    NETCLOSE(control->socket);
		    control->socket = -1;
		    return ((status < 0) ? status : -status);
		}
		/** Go to the VMS account's top directory **/
		if ((cp=strchr(response_text, '[')) != NULL &&
		    (cp1=strrchr(response_text, ']')) != NULL) {
		    char *tmp = 0;
		    unsigned len = 4;

		    StrAllocCopy(tmp, cp);
		    if ((cp2=strchr(cp, '.')) != NULL && cp2 < cp1) {
			len += (cp2 - cp);
		    } else {
			len += (cp1 - cp);
		    }
		    tmp[len] = 0;
		    StrAllocCat(tmp, "]");

		    status = send_cwd(tmp);
		    FREE(tmp);

		    if (status != 2) {
			FREE(fname);
			init_help_message_cache();  /* to free memory */
			NETCLOSE(control->socket);
			control->socket = -1;
			return ((status < 0) ? status : -status);
		    }
		}
	    }
#endif /* MAINTAIN_CONNECTION */

	    /** If we want the VMS account's top directory, list it now **/
	    if (!(strcmp(filename, "/~")) ||
		(included_device && 0==strcmp(filename, "000000")) ||
		(strlen(filename) == 1 && *filename == '/')) {
		isDirectory = YES;
		status = send_cmd_1("LIST");
		FREE(fname);
		if (status != 1) {
		    /* Action not started */
		    init_help_message_cache();	/* to free memory */
		    NETCLOSE(control->socket);
		    control->socket = -1;
		    return ((status < 0) ? status : -status);
		}
		/** Big goto! **/
		goto listen;
	    }
	    /** Otherwise, go to appropriate directory and doctor filename **/
	    if (!strncmp(filename, "/~", 2))
		filename += 2;
	    CTRACE(tfp, "check '%s' to translate x/y/ to [.x.y]\n", filename);
	    if (!included_device &&
		(cp = strchr(filename, '/')) != NULL &&
		(cp1 = strrchr(cp, '/')) != NULL &&
		(cp1 - cp) > 1) {
		char *tmp = 0;

		HTSprintf0(&tmp, "[.%.*s]", cp1-cp-1, cp+1);

		CTRACE(tfp, "change path '%s'\n", tmp);
		while ((cp2 = strrchr(tmp, '/')) != NULL)
		    *cp2 = '.';
		CTRACE(tfp, "...to  path '%s'\n", tmp);

		status = send_cwd(tmp);
		FREE(tmp);

		if (status != 2) {
		    FREE(fname);
		    init_help_message_cache();	/* to free memory */
		    NETCLOSE(control->socket);
		    control->socket = -1;
		    return ((status < 0) ? status : -status);
		}
		filename = cp1+1;
	    } else {
		if (!included_device) {
		    filename += 1;
		}
	    }
	    break;
	  }
	case CMS_SERVER:
	  {
	    /*
	    **	If we want the CMS account's top directory, or a base
	    **	SFS or anonymous directory path (i.e., without a slash),
	    **	list it now. FM
	    */
	    if ((strlen(filename) == 1 && *filename == '/') ||
		((0 == strncasecomp((filename+1), "vmsysu:", 7)) &&
		 (cp = strchr((filename+1), '.')) != NULL &&
		 strchr(cp, '/') == NULL) ||
		(0 == strncasecomp(filename+1, "anonymou.", 9) &&
		 strchr(filename+1, '/') == NULL)) {
		if (filename[1] != '\0') {
		    status = send_cwd(filename+1);
		    if (status != 2) {
			/* Action not started */
			init_help_message_cache();  /* to free memory */
			NETCLOSE(control->socket);
			control->socket = -1;
			return ((status < 0) ? status : -status);
		    }
		}
		isDirectory = YES;
		if (use_list)
		    status = send_cmd_1("LIST");
		else
		    status = send_cmd_1("NLST");
		FREE(fname);
		if (status != 1) {
		    /* Action not started */
		    init_help_message_cache();	/* to free memory */
		    NETCLOSE(control->socket);
		    control->socket = -1;
		    return ((status < 0) ? status : -status);
		}
		/** Big goto! **/
		goto listen;
	    }
	    filename++;

	    /** Otherwise, go to appropriate directory and adjust filename **/
	    while ((cp = strchr(filename, '/')) != NULL) {
		*cp++ = '\0';
		status = send_cwd(filename);
		if (status == 2) {
		    if (*cp == '\0') {
			isDirectory = YES;
			if (use_list)
			    status = send_cmd_1("LIST");
			else
			    status = send_cmd_1("NLST");
			FREE(fname);
			if (status != 1) {
			    /** Action not started **/
			    init_help_message_cache();	/* to free memory */
			    NETCLOSE(control->socket);
			    control->socket = -1;
			    return ((status < 0) ? status : -status);
			}
			/** Clear any messages from the login directory **/
			init_help_message_cache();
			/** Big goto! **/
			goto listen;
		    }
		    filename = cp;
		}
	    }
	    break;
	  }
	default:
	    /** Shift for any unescaped "/%2F" path **/
	    if (!strncmp(filename, "//", 2))
		filename++;
	    break;
	}
	/*
	**  Act on a file or listing request, or try to figure out
	**  which we're dealing with if we don't know yet. - FM
	*/
	if (!(type) || (type && *type != 'D')) {
	    status = send_cmd_2("RETR", filename);
	} else {
	    status = 5;		/* Failed status set as flag. - FM */
	}
	if (status != 1) {	/* Failed : try to CWD to it */
	    /** Clear any login messages if this isn't the login directory **/
	    if (strcmp(filename, "/"))
		init_help_message_cache();

	    status = send_cwd(filename);
	    if (status == 2) {	/* Succeeded : let's NAME LIST it */
		isDirectory = YES;
		if (use_list)
		    status = send_cmd_1("LIST");
		else
		    status = send_cmd_1("NLST");
	    }
	}
	FREE(fname);
	if (status != 1) {
	    init_help_message_cache();	/* to free memory */
	    NETCLOSE(control->socket);
	    control->socket = -1;
	    if (status < 0)
		return status;
	    else
		return -status;
	}
    }

listen:
#ifdef LISTEN
/*	Wait for the connection
*/
    {
	struct sockaddr_in soc_address;
	int	soc_addrlen=sizeof(soc_address);
#ifdef SOCKS
	if (socks_flag)
	    status = Raccept(master_socket,
			     (struct sockaddr *)&soc_address,
			     (void *)&soc_addrlen);
	else
#endif /* SOCKS */
	status = accept(master_socket,
			(struct sockaddr *)&soc_address,
			(void *)&soc_addrlen);
	if (status < 0) {
	    init_help_message_cache();	/* to free memory */
	    return HTInetStatus("accept");
	}
	CTRACE(tfp, "TCP: Accepted new socket %d\n", status);
	data_soc = status;
    }
#else
/* @@ */
#endif /* LISTEN */
    if (isDirectory) {
	status = read_directory (anchor, name, format_out, sink);
	NETCLOSE(data_soc);
	NETCLOSE(control->socket);
	control->socket = -1;
	init_help_message_cache();  /* to free memory */
	return status;
      /* returns HT_LOADED or error */
    } else {
	int rv;
	int len;
	char *FileName = HTParse(name, "", PARSE_PATH + PARSE_PUNCTUATION);

	/** Clear any login messages **/
	init_help_message_cache();

	/** Fake a Content-Encoding for compressed files. - FM **/
	HTUnEscape(FileName);
	if (!IsUnityEnc(encoding)) {
	    /*
	     *	We already know from the call to HTFileFormat above that
	     *	this is a compressed file, no need to look at the filename
	     *	again. - kw
	     */
	    StrAllocCopy(anchor->content_type, format->name);
	    StrAllocCopy(anchor->content_encoding, HTAtom_name(encoding));
	    format = HTAtom_for("www/compressed");

	} else if ((len = strlen(FileName)) > 2) {
	    if ((FileName[len - 1] == 'Z') &&
		(FileName[len - 2] == '.' ||
		 FileName[len - 2] == '-' ||
		 FileName[len - 2] == '_')) {

		FileName[len - 2] = '\0';
		format = HTFileFormat(FileName, &encoding, NULL);
		format = HTCharsetFormat(format, anchor, -1);
		StrAllocCopy(anchor->content_type, format->name);
		StrAllocCopy(anchor->content_encoding, "x-compress");
		format = HTAtom_for("www/compressed");
	    } else if ((len > 3) &&
		       !strcasecomp((char *)&FileName[len - 2], "gz")) {
		if (FileName[len - 3] == '.' ||
		    FileName[len - 3] == '-' ||
		    FileName[len - 3] == '_') {
		    FileName[len - 3] = '\0';
		    format = HTFileFormat(FileName, &encoding, NULL);
		    format = HTCharsetFormat(format, anchor, -1);
		    StrAllocCopy(anchor->content_type, format->name);
		    StrAllocCopy(anchor->content_encoding, "x-gzip");
		    format = HTAtom_for("www/compressed");
		}
	    }
	}
	FREE(FileName);

	_HTProgress (gettext("Receiving FTP file."));
	rv = HTParseSocket(format, format_out, anchor, data_soc, sink);

	if (rv == HT_INTERRUPTED)
	     _HTProgress(TRANSFER_INTERRUPTED);

	HTInitInput(control->socket);
	/* Reset buffering to control connection DD 921208 */

	status = NETCLOSE(data_soc);
	CTRACE(tfp, "HTFTP: Closing data socket %d\n", data_soc);
	if (status < 0 && rv != HT_INTERRUPTED && rv != -1) {
	    (void) HTInetStatus("close");	/* Comment only */
	    data_soc = -1;			/* invalidate it */
	} else {
	    data_soc = -1;			/* invalidate it */
	    status = response(NIL);		/* Pick up final reply */
	    if (status != 2 && rv != HT_INTERRUPTED && rv != -1) {
		init_help_message_cache();  /* to free memory */
		return HTLoadError(sink, 500, response_text);
	    }
	}

	NETCLOSE(control->socket);
	control->socket = -1;
	init_help_message_cache();  /* to free memory */
	return HT_LOADED;
    }
} /* open_file_read */

/*
**  This function frees any user entered password, so that
**  it must be entered again for a future request. - FM
*/
PUBLIC void HTClearFTPPassword NOARGS
{
    /*
    **	Need code to check cached documents from
    **	non-anonymous ftp accounts and do something
    **	to ensure that they no longer can be accessed
    **	without a new retrieval. - FM
    */

    /*
    **	Now free the current user entered password,
    **	if any. - FM
    */
    FREE(user_entered_password);
}

#endif /* ifndef DISABLE_FTP */