use markdown syntax for images
[teliva.git] / toot-toot.tlv
blob528b1b194f6a562e49864319a1503c1cfeb3f03a
1 # .tlv file generated by https://github.com/akkartik/teliva
2 # You may edit it if you are careful; however, you may see cryptic errors if you
3 # violate Teliva's assumptions.
5 # .tlv files are representations of Teliva programs. Teliva programs consist of
6 # sequences of definitions. Each definition is a table of key/value pairs. Keys
7 # and values are both strings.
9 # Lines in .tlv files always follow exactly one of the following forms:
10 # - comment lines at the top of the file starting with '#' at column 0
11 # - beginnings of definitions starting with '- ' at column 0, followed by a
12 #   key/value pair
13 # - key/value pairs consisting of '  ' at column 0, containing either a
14 #   spaceless value on the same line, or a multi-line value
15 # - multiline values indented by more than 2 spaces, starting with a '>'
17 # If these constraints are violated, Teliva may unceremoniously crash. Please
18 # report bugs at http://akkartik.name/contact
19 - __teliva_timestamp: original
20   str_helpers:
21     >-- some string helpers from http://lua-users.org/wiki/StringIndexing
22     >
23     >-- index characters using []
24     >getmetatable('').__index = function(str,i)
25     >  if type(i) == 'number' then
26     >    return str:sub(i,i)
27     >  else
28     >    return string[i]
29     >  end
30     >end
31     >
32     >-- ranges using (), selected bytes using {}
33     >getmetatable('').__call = function(str,i,j)
34     >  if type(i)~='table' then
35     >    return str:sub(i,j)
36     >  else
37     >    local t={}
38     >    for k,v in ipairs(i) do
39     >      t[k]=str:sub(v,v)
40     >    end
41     >    return table.concat(t)
42     >  end
43     >end
44     >
45     >-- iterate over an ordered sequence
46     >function q(x)
47     >  if type(x) == 'string' then
48     >    return x:gmatch('.')
49     >  else
50     >    return ipairs(x)
51     >  end
52     >end
53     >
54     >-- insert within string
55     >function string.insert(str1, str2, pos)
56     >  return str1:sub(1,pos)..str2..str1:sub(pos+1)
57     >end
58     >
59     >function string.remove(s, pos)
60     >  return s:sub(1,pos-1)..s:sub(pos+1)
61     >end
62     >
63     >function string.pos(s, sub)
64     >  return string.find(s, sub, 1, true)  -- plain=true to disable regular expressions
65     >end
66     >
67     >-- TODO: backport utf-8 support from Lua 5.3
68 - __teliva_timestamp: original
69   debugy:
70     >debugy = 5
71 - __teliva_timestamp: original
72   dbg:
73     >-- helper for debug by print; overlay debug information towards the right
74     >-- reset debugy every time you refresh screen
75     >function dbg(window, s)
76     >  local oldy = 0
77     >  local oldx = 0
78     >  oldy, oldx = window:getyx()
79     >  window:mvaddstr(debugy, 60, s)
80     >  debugy = debugy+1
81     >  window:mvaddstr(oldy, oldx, '')
82     >end
83 - __teliva_timestamp: original
84   check:
85     >function check(x, msg)
86     >  if x then
87     >    Window:addch('.')
88     >  else
89     >    print('F - '..msg)
90     >    print('  '..str(x)..' is false/nil')
91     >    teliva_num_test_failures = teliva_num_test_failures + 1
92     >    -- overlay first test failure on editors
93     >    if teliva_first_failure == nil then
94     >      teliva_first_failure = msg
95     >    end
96     >  end
97     >end
98 - __teliva_timestamp: original
99   check_eq:
100     >function check_eq(x, expected, msg)
101     >  if eq(x, expected) then
102     >    Window:addch('.')
103     >  else
104     >    print('F - '..msg)
105     >    print('  expected '..str(expected)..' but got '..str(x))
106     >    teliva_num_test_failures = teliva_num_test_failures + 1
107     >    -- overlay first test failure on editors
108     >    if teliva_first_failure == nil then
109     >      teliva_first_failure = msg
110     >    end
111     >  end
112     >end
113 - __teliva_timestamp: original
114   eq:
115     >function eq(a, b)
116     >  if type(a) ~= type(b) then return false end
117     >  if type(a) == 'table' then
118     >    if #a ~= #b then return false end
119     >    for k, v in pairs(a) do
120     >      if b[k] ~= v then
121     >        return false
122     >      end
123     >    end
124     >    for k, v in pairs(b) do
125     >      if a[k] ~= v then
126     >        return false
127     >      end
128     >    end
129     >    return true
130     >  end
131     >  return a == b
132     >end
133 - __teliva_timestamp: original
134   str:
135     >-- smarter tostring
136     >-- slow; used only for debugging
137     >function str(x)
138     >  if type(x) == 'table' then
139     >    local result = ''
140     >    result = result..#x..'{'
141     >    for k, v in pairs(x) do
142     >      result = result..str(k)..'='..str(v)..', '
143     >    end
144     >    result = result..'}'
145     >    return result
146     >  elseif type(x) == 'string' then
147     >    return '"'..x..'"'
148     >  end
149     >  return tostring(x)
150     >end
151 - __teliva_timestamp: original
152   find_index:
153     >function find_index(arr, x)
154     >  for n, y in ipairs(arr) do
155     >    if x == y then
156     >      return n
157     >    end
158     >  end
159     >end
160 - __teliva_timestamp: original
161   trim:
162     >function trim(s)
163     >  return s:gsub('^%s*', ''):gsub('%s*$', '')
164     >end
165 - __teliva_timestamp: original
166   split:
167     >function split(s, d)
168     >  result = {}
169     >  for match in (s..d):gmatch("(.-)"..d) do
170     >    table.insert(result, match);
171     >  end
172     >  return result
173     >end
174 - __teliva_timestamp: original
175   map:
176     >-- only for arrays
177     >function map(l, f)
178     >  result = {}
179     >  for _, x in ipairs(l) do
180     >    table.insert(result, f(x))
181     >  end
182     >  return result
183     >end
184 - __teliva_timestamp: original
185   reduce:
186     >-- only for arrays
187     >function reduce(l, f, init)
188     >  result = init
189     >  for _, x in ipairs(l) do
190     >    result = f(result, x)
191     >  end
192     >  return result
193     >end
194 - __teliva_timestamp: original
195   filter:
196     >function filter(h, f)
197     >  result = {}
198     >  for k, v in pairs(h) do
199     >    if f(k, v) then
200     >      result[k] = v
201     >    end
202     >  end
203     >  return result
204     >end
205 - __teliva_timestamp: original
206   ifilter:
207     >-- only for arrays
208     >function ifilter(l, f)
209     >  result = {}
210     >  for _, x in ipairs(l) do
211     >    if f(x) then
212     >      table.insert(result, x)
213     >    end
214     >  end
215     >  return result
216     >end
217 - __teliva_timestamp: original
218   sort_letters:
219     >function sort_letters(s)
220     >  tmp = {}
221     >  for i=1,#s do
222     >    table.insert(tmp, s[i])
223     >  end
224     >  table.sort(tmp)
225     >  local result = ''
226     >  for _, c in pairs(tmp) do
227     >    result = result..c
228     >  end
229     >  return result
230     >end
231     >
232     >function test_sort_letters(s)
233     >  check_eq(sort_letters(''), '', 'test_sort_letters: empty')
234     >  check_eq(sort_letters('ba'), 'ab', 'test_sort_letters: non-empty')
235     >  check_eq(sort_letters('abba'), 'aabb', 'test_sort_letters: duplicates')
236     >end
237 - __teliva_timestamp: original
238   count_letters:
239     >-- TODO: handle unicode
240     >function count_letters(s)
241     >  local result = {}
242     >  for i=1,s:len() do
243     >    local c = s[i]
244     >    if result[c] == nil then
245     >      result[c] = 1
246     >    else
247     >      result[c] = result[c] + 1
248     >    end
249     >  end
250     >  return result
251     >end
252 - __teliva_timestamp: original
253   count:
254     >-- turn an array of elements into a map from elements to their frequency
255     >-- analogous to count_letters for non-strings
256     >function count(a)
257     >  local result = {}
258     >  for i, v in ipairs(a) do
259     >    if result[v] == nil then
260     >      result[v] = 1
261     >    else
262     >      result[v] = result[v] + 1
263     >    end
264     >  end
265     >  return result
266     >end
267 - __teliva_timestamp: original
268   union:
269     >function union(a, b)
270     >  for k, v in pairs(b) do
271     >    a[k] = v
272     >  end
273     >  return a
274     >end
275 - __teliva_timestamp: original
276   subtract:
277     >-- set subtraction
278     >function subtract(a, b)
279     >  for k, v in pairs(b) do
280     >    a[k] = nil
281     >  end
282     >  return a
283     >end
284 - __teliva_timestamp: original
285   all:
286     >-- universal quantifier on sets
287     >function all(s, f)
288     >  for k, v in pairs(s) do
289     >    if not f(k, v) then
290     >      return false
291     >    end
292     >  end
293     >  return true
294     >end
295 - __teliva_timestamp: original
296   to_array:
297     >-- turn a set into an array
298     >-- drops values
299     >function to_array(h)
300     >  local result = {}
301     >  for k, _ in pairs(h) do
302     >    table.insert(result, k)
303     >  end
304     >  return result
305     >end
306 - __teliva_timestamp: original
307   append:
308     >-- concatenate list 'elems' into 'l', modifying 'l' in the process
309     >function append(l, elems)
310     >  for i=1,#elems do
311     >    table.insert(l, elems[i])
312     >  end
313     >end
314 - __teliva_timestamp: original
315   prepend:
316     >-- concatenate list 'elems' into the start of 'l', modifying 'l' in the process
317     >function prepend(l, elems)
318     >  for i=1,#elems do
319     >    table.insert(l, i, elems[i])
320     >  end
321     >end
322 - __teliva_timestamp: original
323   all_but:
324     >function all_but(x, idx)
325     >  if type(x) == 'table' then
326     >    local result = {}
327     >    for i, elem in ipairs(x) do
328     >      if i ~= idx then
329     >        table.insert(result,elem)
330     >      end
331     >    end
332     >    return result
333     >  elseif type(x) == 'string' then
334     >    if idx < 1 then return x:sub(1) end
335     >    return x:sub(1, idx-1) .. x:sub(idx+1)
336     >  else
337     >    error('all_but: unsupported type '..type(x))
338     >  end
339     >end
340     >
341     >function test_all_but()
342     >  check_eq(all_but('', 0), '', 'all_but: empty')
343     >  check_eq(all_but('abc', 0), 'abc', 'all_but: invalid low index')
344     >  check_eq(all_but('abc', 4), 'abc', 'all_but: invalid high index')
345     >  check_eq(all_but('abc', 1), 'bc', 'all_but: first index')
346     >  check_eq(all_but('abc', 3), 'ab', 'all_but: final index')
347     >  check_eq(all_but('abc', 2), 'ac', 'all_but: middle index')
348     >end
349 - __teliva_timestamp: original
350   set:
351     >function set(l)
352     >  local result = {}
353     >  for i, elem in ipairs(l) do
354     >    result[elem] = true
355     >  end
356     >  return result
357     >end
358 - __teliva_timestamp: original
359   set_eq:
360     >function set_eq(l1, l2)
361     >  return eq(set(l1), set(l2))
362     >end
363     >
364     >function test_set_eq()
365     >  check(set_eq({1}, {1}), 'set_eq: identical')
366     >  check(not set_eq({1, 2}, {1, 3}), 'set_eq: different')
367     >  check(set_eq({1, 2}, {2, 1}), 'set_eq: order')
368     >  check(set_eq({1, 2, 2}, {2, 1}), 'set_eq: duplicates')
369     >end
370 - __teliva_timestamp: original
371   clear:
372     >function clear(lines)
373     >  while #lines > 0 do
374     >    table.remove(lines)
375     >  end
376     >end
377 - __teliva_timestamp: original
378   zap:
379     >function zap(target, src)
380     >  clear(target)
381     >  append(target, src)
382     >end
383 - __teliva_timestamp: original
384   mfactorial:
385     >-- memoized version of factorial
386     >-- doesn't memoize recursive calls, but may be good enough
387     >mfactorial = memo1(factorial)
388 - __teliva_timestamp: original
389   factorial:
390     >function factorial(n)
391     >  local result = 1
392     >  for i=1,n do
393     >    result = result*i
394     >  end
395     >  return result
396     >end
397 - __teliva_timestamp: original
398   memo1:
399     >-- a higher-order function that takes a function of a single arg
400     >-- (that never returns nil)
401     >-- and returns a memoized version of it
402     >function memo1(f)
403     >  local memo = {}
404     >  return function(x)
405     >    if memo[x] == nil then
406     >      memo[x] = f(x)
407     >    end
408     >    return memo[x]
409     >  end
410     >end
411     >
412     >-- mfactorial doesn't seem noticeably faster
413     >function test_memo1()
414     >  for i=0,30 do
415     >    check_eq(mfactorial(i), factorial(i), 'memo1 over factorial: '..str(i))
416     >  end
417     >end
418 - __teliva_timestamp: original
419   num_permutations:
420     >-- number of permutations of n distinct objects, taken r at a time
421     >function num_permutations(n, r)
422     >  return factorial(n)/factorial(n-r)
423     >end
424     >
425     >-- mfactorial doesn't seem noticeably faster
426     >function test_memo1()
427     >  for i=0,30 do
428     >    for j=0,i do
429     >      check_eq(num_permutations(i, j), mfactorial(i)/mfactorial(i-j), 'num_permutations memoizes: '..str(i)..'P'..str(j))
430     >    end
431     >  end
432     >end
433 - __teliva_timestamp: original
434   menu:
435     >-- To show app-specific hotkeys in the menu bar, add hotkey/command
436     >-- arrays of strings to the menu array.
437     >menu = {
438     >  {'^k', 'clear'},
439     >  {'^w', 'write prose to file "toot" (edit hotkey does NOT save)'},
440     >}
441 - __teliva_timestamp: original
442   Window:
443     >Window = curses.stdscr()
444     >curses.curs_set(0)  -- we'll simulate our own cursor
445 - __teliva_timestamp: original
446   main:
447     >function main()
448     >  init_colors()
449     >
450     >  while true do
451     >    render(Window)
452     >    update(Window)
453     >  end
454     >end
455 - __teliva_timestamp: original
456   init_colors:
457     >function init_colors()
458     >  for i=0,7 do
459     >    curses.init_pair(i, i, -1)
460     >  end
461     >  curses.init_pair(8, 7, 0)
462     >  curses.init_pair(9, 7, 1)
463     >  curses.init_pair(10, 7, 2)
464     >  curses.init_pair(11, 7, 3)
465     >  curses.init_pair(12, 7, 4)
466     >  curses.init_pair(13, 7, 5)
467     >  curses.init_pair(14, 7, 6)
468     >  curses.init_pair(15, -1, 15)
469     >end
470 - __teliva_timestamp: original
471   prose:
472     >prose = ''
473 - __teliva_timestamp: original
474   cursor:
475     >cursor = 1
476 - __teliva_timestamp: original
477   render:
478     >function render(window)
479     >  window:clear()
480     >  debugy = 5
481     >  local toots = split(prose, '\n\n===\n\n')
482     >  pos = 1
483     >  for i, toot in ipairs(toots) do
484     >    if i > 1 then
485     >      pos = render_delimiter(window, '\n\n===\n\n', pos, cursor)
486     >    end
487     >    pos = render_text(window, toot, pos, cursor)
488     >    print('')
489     >    window:attron(curses.A_BOLD)
490     >    window:addstr(toot:len())
491     >    window:attroff(curses.A_BOLD)
492     >  end
493     >  window:refresh()
494     >end
495 - __teliva_timestamp: original
496   render_delimiter:
497     >function render_delimiter(window, s, pos, cursor)
498     >  local newpos = pos
499     >  for i=1,s:len() do
500     >    if newpos == cursor and i ~= 1 then
501     >      if s[i] == '\n' then
502     >        -- newline at cursor = render extra space in reverse video before jumping to new line
503     >        window:attron(curses.A_REVERSE)
504     >        window:addch(' ')
505     >        window:attroff(curses.A_REVERSE)
506     >        window:addstr(s[i])
507     >      else
508     >        -- most characters at cursor = render in reverse video
509     >        window:attron(curses.A_REVERSE)
510     >        window:addstr(s[i])
511     >        window:attroff(curses.A_REVERSE)
512     >      end
513     >    else
514     >      window:addstr(s[i])
515     >    end
516     >    newpos = newpos+1
517     >  end
518     >  return newpos
519     >end
520 - __teliva_timestamp: original
521   render_text:
522     >-- https://gankra.github.io/blah/text-hates-you
523     >-- https://lord.io/text-editing-hates-you-too
524     >
525     >-- manual tests:
526     >--   cursor on some character
527     >--   cursor on (within) '\n\n===\n\n' delimiter (delimiter is hardcoded; things may break if you change it)
528     >--   cursor at end of each line
529     >--   render digits
530     >
531     >-- positions serve two purposes:
532     >--   character to index into prose
533     >--   cursor-printing
534     >
535     >-- sequence of stories
536     >--   focus on rendering a single piece of text, first get that rock-solid
537     >--   split prose into toots, manage transitions between toots in response to cursor movements
538     >--   cursor movement: left/right vs up/down
539     >
540     >-- what is the ideal representation?
541     >--   prose + cursor has issues in multi-toot context. when to display cursor?
542     >function render_text(window, s, pos, cursor)
543     >  local newpos = pos
544     >--?   dbg(window, '--')
545     >  for i=1,s:len() do
546     >--?     dbg(window, tostring(newpos)..' '..tostring(string.byte(s[i])))
547     >    if newpos == cursor then
548     >--?       dbg(window, 'cursor: '..tostring(cursor))
549     >      if s[i] == '\n' then
550     >        -- newline at cursor = render extra space in reverse video before jumping to new line
551     >        window:attron(curses.A_REVERSE)
552     >        window:addch(' ')
553     >        window:attroff(curses.A_REVERSE)
554     >        window:addstr(s[i])
555     >      else
556     >        -- most characters at cursor = render in reverse video
557     >        window:attron(curses.A_REVERSE)
558     >        window:addstr(s[i])
559     >        window:attroff(curses.A_REVERSE)
560     >      end
561     >    else
562     >      window:addstr(s[i])
563     >    end
564     >    newpos = newpos+1
565     >  end
566     >  if newpos == cursor then
567     >    window:attron(curses.A_REVERSE)
568     >    window:addch(' ')
569     >    window:attroff(curses.A_REVERSE)
570     >  end
571     >  return newpos
572     >end
573 - __teliva_timestamp: original
574   update:
575     >function update(window)
576     >  local key = window:getch()
577     >  local h, w = window:getmaxyx()
578     >  if key == curses.KEY_LEFT then
579     >    if cursor > 1 then
580     >      cursor = cursor-1
581     >    end
582     >  elseif key == curses.KEY_RIGHT then
583     >    if cursor <= #prose then
584     >      cursor = cursor+1
585     >    end
586     >  elseif key == curses.KEY_DOWN then
587     >    cursor = cursor_down(prose, cursor, w)
588     >  elseif key == curses.KEY_UP then
589     >    cursor = cursor_up(prose, cursor, w)
590     >  elseif key == curses.KEY_BACKSPACE or key == 8 or key == 127 then  -- ctrl-h, ctrl-?, delete
591     >    if cursor > 1 then
592     >      cursor = cursor-1
593     >      prose = prose:remove(cursor)
594     >    end
595     >  elseif key == 11 then  -- ctrl-k
596     >    prose = ''
597     >    cursor = 1
598     >  elseif key == 23 then  -- ctrl-w
599     >    local out = io.open('toot', 'w')
600     >    if out ~= nil then
601     >      out:write(prose, '\n')
602     >      out:close()
603     >    end
604     >  elseif key == 10 or (key >= 32 and key < 127) then
605     >    prose = prose:insert(string.char(key), cursor-1)
606     >    cursor = cursor+1
607     >  end
608     >end
609 - __teliva_timestamp: original
610   cursor_down:
611     >function cursor_down(s, old_idx, width)
612     >  local max = string.len(s)
613     >  local i = 1
614     >  -- compute oldcol, the screen column of old_idx
615     >  local oldcol = 0
616     >  local col = 0
617     >  while true do
618     >    if i > max then
619     >      -- abnormal old_idx
620     >      return old_idx
621     >    end
622     >    if i == old_idx then
623     >      oldcol = col
624     >      break
625     >    end
626     >    if s[i] == '\n' then
627     >      col = 0
628     >    else
629     >      col = col+1
630     >    end
631     >    i = i+1
632     >  end
633     >  -- skip rest of line
634     >  while true do
635     >    if i > max then
636     >      -- current line is at bottom
637     >      if col >= width then
638     >        return i
639     >      end
640     >      return old_idx
641     >    end
642     >    if s[i] == '\n' then
643     >      break
644     >    end
645     >    if i - old_idx >= width then
646     >      return i
647     >    end
648     >    col = col+1
649     >    i = i+1
650     >  end
651     >  -- compute index at same column on next line
652     >  -- i is at a newline
653     >  i = i+1
654     >  col = 0
655     >  while true do
656     >    if i > max then
657     >      -- next line is at bottom and is too short; position at end of it
658     >      return i
659     >    end
660     >    if s[i] == '\n' then
661     >      -- next line is too short; position at end of it
662     >      return i
663     >    end
664     >    if col == oldcol then
665     >      return i
666     >    end
667     >    col = col+1
668     >    i = i+1
669     >  end
670     >end
671     >
672     >function test_cursor_down()
673     >  -- lines that don't wrap
674     >  check_eq(cursor_down('abc\ndef', 1, 5), 5, 'cursor_down: non-bottom line first char')
675     >  check_eq(cursor_down('abc\ndef', 2, 5), 6, 'cursor_down: non-bottom line mid char')
676     >  check_eq(cursor_down('abc\ndef', 3, 5), 7, 'cursor_down: non-bottom line final char')
677     >  check_eq(cursor_down('abc\ndef', 4, 5), 8, 'cursor_down: non-bottom line end')
678     >  check_eq(cursor_down('abc\ndef', 5, 5), 5, 'cursor_down: bottom line first char')
679     >  check_eq(cursor_down('abc\ndef', 6, 5), 6, 'cursor_down: bottom line mid char')
680     >  check_eq(cursor_down('abc\ndef', 7, 5), 7, 'cursor_down: bottom line final char')
681     >  check_eq(cursor_down('abc\n\ndef', 2, 5), 5, 'cursor_down: to shorter line')
682     >
683     >  -- within a single wrapping line
684     >  --   |abcde|  <-- wrap, no newline
685     >  --   |fgh  |
686     >  check_eq(cursor_down('abcdefgh', 1, 5), 6, 'cursor_down from wrapping line: first char')
687     >  check_eq(cursor_down('abcdefgh', 2, 5), 7, 'cursor_down from wrapping line: mid char')
688     >  check_eq(cursor_down('abcdefgh', 5, 5), 9, 'cursor_down from wrapping line: to shorter line')
689     >
690     >  -- within a single very long wrapping line
691     >  --   |abcde|  <-- wrap, no newline
692     >  --   |fghij|  <-- wrap, no newline
693     >  --   |klm  |
694     >  check_eq(cursor_down('abcdefghijklm', 1, 5), 6, 'cursor_down within wrapping line: first char')
695     >  check_eq(cursor_down('abcdefghijklm', 2, 5), 7, 'cursor_down within wrapping line: mid char')
696     >  check_eq(cursor_down('abcdefghijklm', 5, 5), 10, 'cursor_down within wrapping line: final char')
697     >end
698 - __teliva_timestamp: original
699   cursor_up:
700     >function cursor_up(s, old_idx, width)
701     >  local max = string.len(s)
702     >  local i = 1
703     >  -- compute oldcol, the screen column of old_idx
704     >  local oldcol = 0
705     >  local col = 0
706     >  local newline_before_current_line = 0
707     >  while true do
708     >    if i > max or i == old_idx then
709     >      oldcol = col
710     >      break
711     >    end
712     >    if s[i] == '\n' then
713     >      col = 0
714     >      newline_before_current_line = i
715     >    else
716     >      col = col+1
717     >      if col == width then
718     >        col = 0
719     >      end
720     >    end
721     >    i = i+1
722     >  end
723     >  -- find previous newline
724     >  i = i-col-1
725     >  if old_idx - newline_before_current_line > width then
726     >    -- we're in a wrapped line
727     >    return old_idx - width
728     >  end
729     >  -- scan back to start of previous line
730     >  if s[i] == '\n' then
731     >    i = i-1
732     >  end
733     >  while true do
734     >    if i < 1 then
735     >      -- current line is at top
736     >      break
737     >    end
738     >    if s[i] == '\n' then
739     >      break
740     >    end
741     >    i = i-1
742     >  end
743     >  -- i is at a newline
744     >  i = i+1
745     >  -- skip whole screen lines within previous line
746     >  while newline_before_current_line - i > width do
747     >    i = i + width
748     >  end
749     >  -- compute index at same column on previous screen line
750     >  col = 0
751     >  while true do
752     >    if i > max then
753     >      -- next line is at bottom and is too short; position at end of it
754     >      return i
755     >    end
756     >    if s[i] == '\n' then
757     >      -- next line is too short; position at end of it
758     >      return i
759     >    end
760     >    if col == oldcol then
761     >      return i
762     >    end
763     >    col = col+1
764     >    i = i+1
765     >  end
766     >end
767     >
768     >function test_cursor_up()
769     >  -- lines that don't wrap
770     >  check_eq(cursor_up('abc\ndef', 1, 5), 1, 'cursor_up: top line first char')
771     >  check_eq(cursor_up('abc\ndef', 2, 5), 2, 'cursor_up: top line mid char')
772     >  check_eq(cursor_up('abc\ndef', 3, 5), 3, 'cursor_up: top line final char')
773     >  check_eq(cursor_up('abc\ndef', 4, 5), 4, 'cursor_up: top line end')
774     >  check_eq(cursor_up('abc\ndef', 5, 5), 1, 'cursor_up: non-top line first char')
775     >  check_eq(cursor_up('abc\ndef', 6, 5), 2, 'cursor_up: non-top line mid char')
776     >  check_eq(cursor_up('abc\ndef', 7, 5), 3, 'cursor_up: non-top line final char')
777     >  check_eq(cursor_up('abc\ndef\n', 8, 5), 4, 'cursor_up: non-top line end')
778     >  check_eq(cursor_up('ab\ndef\n', 7, 5), 3, 'cursor_up: to shorter line')
779     >
780     >  -- within a single wrapping line
781     >  --   |abcde|  <-- wrap, no newline
782     >  --   |fgh  |
783     >  check_eq(cursor_up('abcdefgh', 6, 5), 1, 'cursor_up from wrapping line: first char')
784     >  check_eq(cursor_up('abcdefgh', 7, 5), 2, 'cursor_up from wrapping line: mid char')
785     >  check_eq(cursor_up('abcdefgh', 8, 5), 3, 'cursor_up from wrapping line: final char')
786     >  check_eq(cursor_up('abcdefgh', 9, 5), 4, 'cursor_up from wrapping line: wrapped line end')
787     >
788     >  -- within a single very long wrapping line
789     >  --   |abcde|  <-- wrap, no newline
790     >  --   |fghij|  <-- wrap, no newline
791     >  --   |klm  |
792     >  check_eq(cursor_up('abcdefghijklm', 11, 5), 6, 'cursor_up within wrapping line: first char')
793     >  check_eq(cursor_up('abcdefghijklm', 12, 5), 7, 'cursor_up within wrapping line: mid char')
794     >  check_eq(cursor_up('abcdefghijklm', 13, 5), 8, 'cursor_up within wrapping line: final char')
795     >  check_eq(cursor_up('abcdefghijklm', 14, 5), 9, 'cursor_up within wrapping line: wrapped line end')
796     >
797     >  -- from below to (the bottom of) a wrapping line
798     >  --   |abcde|  <-- wrap, no newline
799     >  --   |fg   |
800     >  --   |hij  |
801     >  check_eq(cursor_up('abcdefg\nhij', 9, 5), 6, 'cursor_up to wrapping line: first char')
802     >  check_eq(cursor_up('abcdefg\nhij', 10, 5), 7, 'cursor_up to wrapping line: mid char')
803     >  check_eq(cursor_up('abcdefg\nhij', 11, 5), 8, 'cursor_up to wrapping line: final char')
804     >  check_eq(cursor_up('abcdefg\nhij', 12, 5), 8, 'cursor_up to wrapping line: to shorter line')
805     >end
806 - __teliva_timestamp:
807     >Thu Feb 17 19:52:30 2022
808   doc:blurb:
809     >A tiny editor (no scrolling) for composing a series of toots or tweets. Always shows character counts for current state of prose.
810     >
811     >Typing '===' on its own lines, surrounded by empty lines, partitions prose and gives all segments independent character counts. Good for threads (tweetstorms).
812 - __teliva_timestamp:
813     >Fri Mar 11 09:45:27 2022
814   first_toot:
815     >first_toot = 1
816 - __teliva_timestamp:
817     >Fri Mar 11 11:47:34 2022
818   update:
819     >function update(window)
820     >  local key = window:getch()
821     >  local h, w = window:getmaxyx()
822     >  if key == curses.KEY_LEFT then
823     >    if cursor > 1 then
824     >      cursor = cursor-1
825     >    end
826     >  elseif key == curses.KEY_RIGHT then
827     >    if cursor <= #prose then
828     >      cursor = cursor+1
829     >    end
830     >  elseif key == curses.KEY_DOWN then
831     >    cursor = cursor_down(prose, cursor, w)
832     >  elseif key == curses.KEY_UP then
833     >    cursor = cursor_up(prose, cursor, w)
834     >  elseif key == curses.KEY_BACKSPACE or key == 8 or key == 127 then  -- ctrl-h, ctrl-?, delete
835     >    if cursor > 1 then
836     >      cursor = cursor-1
837     >      prose = prose:remove(cursor)
838     >    end
839     >  elseif key == 6 then  -- ctrl-f
840     >    first_toot = first_toot+1
841     >  elseif key == 2 then  -- ctrl-b
842     >    if first_toot > 1 then
843     >      first_toot = first_toot-1
844     >    end
845     >  elseif key == 11 then  -- ctrl-k
846     >    prose = ''
847     >    cursor = 1
848     >  elseif key == 23 then  -- ctrl-w
849     >    local out = io.open('toot', 'w')
850     >    if out ~= nil then
851     >      out:write(prose, '\n')
852     >      out:close()
853     >    end
854     >  elseif key == 10 or (key >= 32 and key < 127) then
855     >    prose = prose:insert(string.char(key), cursor-1)
856     >    cursor = cursor+1
857     >  end
858     >end
859 - __teliva_timestamp:
860     >Fri Mar 11 11:48:43 2022
861   menu:
862     >-- To show app-specific hotkeys in the menu bar, add hotkey/command
863     >-- arrays of strings to the menu array.
864     >menu = {
865     >  {'^w', 'write to "toot"'},
866     >  {'^f|^b', 'scroll'},
867     >  {'^k', 'clear'},
868     >}
869 - __teliva_timestamp:
870     >Sat Mar 12 08:48:44 2022
871   render:
872     >function render(window)
873     >  window:clear()
874     >  debugy = 5
875     >  local toots = split(prose, '\n\n===\n\n')
876     >  pos = 1
877     >  for i, toot in ipairs(toots) do
878     >--?     dbg(window, "render: "..i.." pos "..pos.." cursor "..cursor)
879     >    if i > 1 then
880     >      pos = render_delimiter(window, '\n\n===\n\n', pos, cursor)
881     >--?       dbg(window, "delim: "..pos.." cursor "..cursor)
882     >    end
883     >    if i <= first_toot then
884     >      window:clear()
885     >    end
886     >    pos = render_text(window, toot, pos, cursor)
887     >    print('')
888     >--?     dbg(window, "text: "..pos.." cursor "..cursor)
889     >    window:attron(curses.A_BOLD)
890     >    window:addstr(toot:len())
891     >    window:attroff(curses.A_BOLD)
892     >  end
893     >  window:refresh()
894     >end
895 - __teliva_timestamp:
896     >Sat Mar 12 08:57:41 2022
897   doc:blurb:
898     >A tiny editor (no scrolling) for composing a series of toots or tweets.
899     >Always shows character counts for current state of prose.
900     >
901     >Typing '===' on its own lines, surrounded by empty lines, partitions prose and gives all segments independent character counts. Good for threads (tweetstorms).
902 - __teliva_timestamp:
903     >Sat Mar 12 08:59:52 2022
904   __teliva_note:
905     >hacky scrolling support
906     >
907     >Since I started out rendering a toot at a time and tracking the position
908     >as I rendered each toot, the easiest way to build this was to scroll a
909     >toot at a time, always render each toot and just decide when to stop
910     >clearing the screen. This way I don't mess with the position computation
911     >logic which is carefully synced between render and cursor_up/cursor_down.
912     >
913     >But there may be a more elegant approach if I was building the current state
914     >from scratch.
915   doc:blurb:
916     >A tiny editor for composing a short series of toots or tweets. Always shows character counts for current state of prose.
917     >
918     >Typing '===' on its own lines, surrounded by empty lines, partitions prose and gives all segments independent character counts. Good for threads (tweetstorms).
919     >
920     >Scrolling support is rudimentary. Keys to scroll are independent of cursor movement, so cursor can move off the screen and confusingly 'get lost'.
921 - __teliva_timestamp:
922     >Wed Mar 30 21:33:17 2022
923   update:
924     >function update(window)
925     >  local key = window:getch()
926     >  local h, w = window:getmaxyx()
927     >  if key == curses.KEY_LEFT then
928     >    if cursor > 1 then
929     >      cursor = cursor-1
930     >    end
931     >  elseif key == curses.KEY_RIGHT then
932     >    if cursor <= #prose then
933     >      cursor = cursor+1
934     >    end
935     >  elseif key == curses.KEY_DOWN then
936     >    cursor = cursor_down(prose, cursor, w)
937     >  elseif key == curses.KEY_UP then
938     >    cursor = cursor_up(prose, cursor, w)
939     >  elseif key == curses.KEY_BACKSPACE or key == 8 or key == 127 then  -- ctrl-h, ctrl-?, delete
940     >    if cursor > 1 then
941     >      cursor = cursor-1
942     >      prose = prose:remove(cursor)
943     >    end
944     >  elseif key == 6 then  -- ctrl-f
945     >    first_toot = first_toot+1
946     >  elseif key == 2 then  -- ctrl-b
947     >    if first_toot > 1 then
948     >      first_toot = first_toot-1
949     >    end
950     >  elseif key == 23 then  -- ctrl-w
951     >    local out = io.open('toot', 'w')
952     >    if out ~= nil then
953     >      out:write(prose, '\n')
954     >      out:close()
955     >    end
956     >  elseif key == 10 or (key >= 32 and key < 127) then
957     >    prose = prose:insert(string.char(key), cursor-1)
958     >    cursor = cursor+1
959     >  end
960     >end
961 - __teliva_timestamp:
962     >Wed Mar 30 21:33:44 2022
963   __teliva_note:
964     >Get rid of the ctrl-k shortcut. Makes it too easy to lose data. To clear the page just quit and restart.
965   menu:
966     >-- To show app-specific hotkeys in the menu bar, add hotkey/command
967     >-- arrays of strings to the menu array.
968     >menu = {
969     >  {'^w', 'write to "toot"'},
970     >  {'^f|^b', 'scroll'},
971     >}
972 - __teliva_timestamp:
973     >Thu Mar 31 08:42:19 2022
974   update:
975     >function update(window)
976     >  local key = window:getch()
977     >  local h, w = window:getmaxyx()
978     >  if key == curses.KEY_LEFT then
979     >    if cursor > 1 then
980     >      cursor = cursor-1
981     >    end
982     >  elseif key == curses.KEY_RIGHT then
983     >    if cursor <= #prose then
984     >      cursor = cursor+1
985     >    end
986     >  elseif key == curses.KEY_DOWN then
987     >    cursor = cursor_down(prose, cursor, w)
988     >  elseif key == curses.KEY_UP then
989     >    cursor = cursor_up(prose, cursor, w)
990     >  elseif key == curses.KEY_BACKSPACE or key == 8 or key == 127 then  -- ctrl-h, ctrl-?, delete
991     >    if cursor > 1 then
992     >      cursor = cursor-1
993     >      prose = prose:remove(cursor)
994     >    end
995     >  elseif key == 6 then  -- ctrl-f
996     >    first_toot = first_toot+1
997     >  elseif key == 2 then  -- ctrl-b
998     >    if first_toot > 1 then
999     >      first_toot = first_toot-1
1000     >    end
1001     >  elseif key == 23 then  -- ctrl-w
1002     >    local out = io.open(next_toot(), 'w')
1003     >    if out ~= nil then
1004     >      out:write(prose, '\n')
1005     >      out:close()
1006     >    end
1007     >  elseif key == 10 or (key >= 32 and key < 127) then
1008     >    prose = prose:insert(string.char(key), cursor-1)
1009     >    cursor = cursor+1
1010     >  end
1011     >end
1012 - __teliva_timestamp:
1013     >Thu Mar 31 08:44:19 2022
1014   next_toot:
1015     >-- pick the first filename starting with 'toot' that doesn't exist yet
1016     >function next_toot()
1017     >  if not file_exists('toot') then return 'toot' end
1018     >  local idx = 1
1019     >  while true do
1020     >    local curr = 'toot'..str(idx)
1021     >    if not file_exists(curr) then
1022     >      return curr
1023     >    end
1024     >    idx = idx+1
1025     >  end
1026     >end
1027 - __teliva_timestamp:
1028     >Thu Mar 31 08:46:27 2022
1029   file_exists:
1030     >function file_exists(filename)
1031     >  local f = io.open(filename, 'r')
1032     >  return f ~= nil
1033     >end