BASIC line editor: cursor keys, Home/End, Delete, and Right to recall a line

Typing a line number and pressing Right brings that program line up to
edit. Left/Right move, Home/End (Ctrl-A/Ctrl-E) jump, typing inserts,
Backspace and Delete remove, Enter takes the whole line; long lines wrap.
To fit the ROM, the date code is smaller and SDCC gets more allocator
effort; build.sh now fails if the code runs past 8000h. basic/test-edit.py
checks the editor in the emulator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-30 07:37:28 -08:00
1 parent 073db68754
commit eb72d85834
8 files changed
+6473 -6227

No files matched your search

+4 -2
View File
@@ -183,8 +183,10 @@ RUN
``` ```
Type numbered lines to store a program, or a statement without a number to run Type numbered lines to store a program, or a statement without a number to run
it at once (`PRINT 2^10`). Ctrl-C stops a running program; Backspace and Ctrl-U it at once (`PRINT 2^10`). Ctrl-C stops a running program. The line being
edit the line being typed. typed can be edited with the cursor keys, Home, End, Backspace, Delete and
Ctrl-U; type a line number and press Right to bring that program line up to
edit.
- **Commands**: `RUN [line]`, `LIST [a][-b]`, `NEW` (also `SCRATCH`). - **Commands**: `RUN [line]`, `LIST [a][-b]`, `NEW` (also `SCRATCH`).
- **Files in flash**: `SAVE "NAME"`, `LOAD "NAME"`, `RUN "NAME"`, `DIR`, - **Files in flash**: `SAVE "NAME"`, `LOAD "NAME"`, `RUN "NAME"`, `DIR`,
BIN
View File
Binary file not shown.
+144 -46
View File
@@ -352,24 +352,21 @@ static u8 month_len(u16 y, u8 m) { return mdays[m - 1] + (m == 2 && leap(y)); }
/* "YYYY-MM-DD HH:MM" (or with ":SS" when sec is set) for t; "" when t is 0. */ /* "YYYY-MM-DD HH:MM" (or with ":SS" when sec is set) for t; "" when t is 0. */
static void fmt_date(u32 t, char *out, u8 sec) static void fmt_date(u32 t, char *out, u8 sec)
{ {
u16 y = 2000, days = t / 86400UL; static const char sep[] = "-- ::";
u8 m = 1, i; u16 y = 2000, days, mins;
u32 r = t % 86400UL; u8 m = 1, i, v[6];
u16 v[6];
if (!t) { *out = 0; return; } if (!t) { *out = 0; return; }
days = t / 86400UL;
mins = (u16)(t % 86400UL / 60);
while (days >= 365 + leap(y)) days -= 365 + leap(y++); while (days >= 365 + leap(y)) days -= 365 + leap(y++);
while (days >= month_len(y, m)) days -= month_len(y, m++); while (days >= month_len(y, m)) days -= month_len(y, m++);
v[0] = y; v[1] = m; v[2] = days + 1; v[0] = y - 2000; v[1] = m; v[2] = days + 1;
v[3] = r / 3600; v[4] = r / 60 % 60; v[5] = r % 60; v[3] = mins / 60; v[4] = mins % 60; v[5] = t % 60;
for (i = 0; i < (sec ? 6 : 5); i++) { *out++ = '2'; *out++ = '0';
if (i == 0) { for (i = 0; i < 5 + sec; i++) {
*out++ = '0' + y / 1000; *out++ = '0' + y / 100 % 10; if (i) *out++ = sep[i - 1];
} *out++ = '0' + v[i] / 10;
*out++ = '0' + v[i] / 10 % 10;
*out++ = '0' + v[i] % 10; *out++ = '0' + v[i] % 10;
if (i < 2) *out++ = '-';
else if (i == 2) *out++ = ' ';
else if (i < (sec ? 5 : 4)) *out++ = ':';
} }
*out = 0; *out = 0;
} }
@@ -388,29 +385,26 @@ static u16 date_field(const char **p, u8 n, u16 lo, u16 hi)
/* Set the clock from "YYYY-MM-DD[ HH:MM[:SS]]". */ /* Set the clock from "YYYY-MM-DD[ HH:MM[:SS]]". */
static void set_date(const char *s) static void set_date(const char *s)
{ {
u16 y, m, d, hh = 0, mm = 0, ss = 0, i; static const char sep[] = "-- ::";
static const u8 hi[] = { 99, 12, 31, 23, 59, 59 };
u8 v[6], i;
u32 days; u32 days;
y = date_field(&s, 4, 2000, 2099); memset(v, 0, sizeof v);
if (*s++ != '-') error(E_FUNC); if (*s++ != '2' || *s++ != '0') error(E_FUNC);
m = date_field(&s, 2, 1, 12); for (i = 0; i < 6; i++) {
if (*s++ != '-') error(E_FUNC); if (i) {
d = date_field(&s, 2, 1, month_len(y, m)); if (!*s && (i == 3 || i == 5)) break;
if (*s) { if (*s++ != sep[i - 1]) error(E_FUNC);
if (*s++ != ' ') error(E_FUNC);
hh = date_field(&s, 2, 0, 23);
if (*s++ != ':') error(E_FUNC);
mm = date_field(&s, 2, 0, 59);
if (*s) {
if (*s++ != ':') error(E_FUNC);
ss = date_field(&s, 2, 0, 59);
} }
if (*s) error(E_FUNC); v[i] = date_field(&s, 2, i == 1 || i == 2,
i == 2 ? month_len(2000 + v[0], v[1]) : hi[i]);
} }
days = d - 1; if (*s) error(E_FUNC);
for (i = 2000; i < y; i++) days += 365 + leap(i); days = v[2] - 1;
for (i = 1; i < m; i++) days += month_len(y, i); for (i = 0; i < v[0]; i++) days += 365 + leap(2000 + i);
for (i = 1; i < v[1]; i++) days += month_len(2000 + v[0], i);
clk_ms = millis(); clk_ms = millis();
clk_sec = days * 86400UL + hh * 3600UL + mm * 60 + ss; clk_sec = days * 86400UL + (u16)(v[3] * 60 + v[4]) * 60UL + v[5];
if (!clk_sec) clk_sec = 1; if (!clk_sec) clk_sec = 1;
} }
@@ -1042,27 +1036,131 @@ static void check_break(void)
if (c >= 0) held = c; if (c >= 0) held = c;
} }
/* Read a line with echo and simple editing; returns 0 on Ctrl-C. */ /* ------------------------------------------------------------ line editor
The line being typed is linebuf[0..ed_n) with the cursor at ed_cur. Left
and Right move, Home and End (or Ctrl-A, Ctrl-E) jump, typing inserts,
Backspace and Delete take out, Ctrl-U clears. Right at the end of a line
that is only a line number brings that program line in to edit. The screen
is kept up to date with cursor moves only, so a line may wrap: ed_sc is the
column it starts in, ED_W the screen width, ed_row the screen row (from the
line's first) the terminal's cursor is on and ed_at the place it is at. */
#define ED_W 80
static void esc_num(u8 n);
static u8 ed_sc, ed_row, ed_at, ed_pend, ed_n, ed_cur;
static void ed_csi(u8 n, char f)
{
out_c(27); out_c('['); esc_num(n); out_c(f);
}
/* Put the terminal's cursor at place i of the line. */
static void ed_go(u8 i)
{
u16 p = ed_sc + i;
u8 r = p / ED_W, c = p % ED_W;
if (i == ed_at && !ed_pend) return;
out_c('\r');
if (r < ed_row) ed_csi(ed_row - r, 'A');
for (; ed_row < r; ed_row++) out_c('\n');
if (c) ed_csi(c, 'C');
ed_row = r; ed_at = i; ed_pend = 0;
}
/* Write the line from place i on, blank `gone` cells after it, then put the
cursor back. */
static void ed_show(u8 i, u8 gone)
{
u8 k = i;
ed_go(i);
for (; k < ed_n; k++) out_c(linebuf[k]);
for (; gone; gone--, k++) out_c(' ');
if (k > i) {
ed_row = (ed_sc + k - 1) / ED_W;
ed_at = k;
ed_pend = (ed_sc + k) % ED_W == 0;
}
ed_go(ed_cur);
}
static void ed_put(char c)
{
if (ed_n < 250) linebuf[ed_n++] = c;
}
/* Right at the end of a bare line number: bring that line in. */
static u8 ed_recall(void)
{
u8 i = 0;
u16 v = 0;
u8 *p;
while (i < ed_n && linebuf[i] == ' ') i++;
if (i == ed_n) return 0;
for (; i < ed_n; i++) {
if (!is_digit(linebuf[i])) return 0;
v = v * 10 + linebuf[i] - '0';
}
p = find_line(v);
if (!*p || line_no(p) != v) return 0;
i = ed_n;
ed_n = 0;
list_to(p, ed_put);
ed_cur = ed_n;
ed_show(0, ed_n < i ? i - ed_n : 0);
return 1;
}
/* Read a line with echo and editing; returns 0 on Ctrl-C. */
static u8 read_line(void) static u8 read_line(void)
{ {
u8 n = 0, c; u8 c, k;
ed_sc = col % 80;
ed_row = ed_at = ed_pend = ed_n = ed_cur = 0;
for (;;) { for (;;) {
c = getkey(); c = getkey();
if (c == '\r' || c == '\n') { newline(); linebuf[n] = 0; return 1; } if (c == '\r' || c == '\n') {
if (c == 3) { puts_("^C"); newline(); return 0; } ed_cur = ed_n; ed_go(ed_n);
if (c == 27) { /* drop cursor-key escape sequences */ newline(); linebuf[ed_n] = 0; return 1;
}
if (c == 3) { ed_cur = ed_n; ed_go(ed_n); puts_("^C"); newline(); return 0; }
if (c == 27) { /* cursor and editing keys */
c = getkey(); c = getkey();
k = 0;
if (c == '[' || c == 'O') if (c == '[' || c == 'O')
do c = getkey(); while (c < 0x40 || c > 0x7E); do { c = getkey(); if (is_digit(c)) k = c; } while (c < 0x40 || c > 0x7E);
if (c == '~') c = k == '1' ? 'H' : k == '4' ? 'F' : k == '3' ? 'P' : 0;
if (c == 'C') {
if (ed_cur < ed_n) ed_cur++;
else ed_recall();
} else if (c == 'D') { if (ed_cur) ed_cur--; }
else if (c == 'H') ed_cur = 0;
else if (c == 'F') ed_cur = ed_n;
else if (c == 'P' && ed_cur < ed_n) {
memmove(linebuf + ed_cur, linebuf + ed_cur + 1, ed_n - ed_cur - 1);
ed_n--;
ed_show(ed_cur, 1);
}
ed_go(ed_cur);
continue; continue;
} }
if (c == 8 || c == 127) { if (c == 1) { ed_cur = 0; ed_go(0); }
if (n) { n--; putch('\b'); putch(' '); putch('\b'); } else if (c == 5) { ed_cur = ed_n; ed_go(ed_n); }
} else if (c == 21) { /* Ctrl-U */ else if (c == 8 || c == 127) {
while (n) { n--; putch('\b'); putch(' '); putch('\b'); } if (ed_cur) {
} else if (c >= ' ' && c < 127 && n < 250) { ed_cur--;
linebuf[n++] = c; memmove(linebuf + ed_cur, linebuf + ed_cur + 1, ed_n - ed_cur - 1);
putch(c); ed_n--;
ed_show(ed_cur, 1);
}
} else if (c == 21) { /* Ctrl-U */
k = ed_n;
ed_n = ed_cur = 0;
ed_show(0, k);
} else if (c >= ' ' && c < 127 && ed_n < 250) {
memmove(linebuf + ed_cur + 1, linebuf + ed_cur, ed_n - ed_cur);
linebuf[ed_cur++] = c;
ed_n++;
ed_show(ed_cur - 1, 0);
} }
} }
} }
+6175 -6175
View File
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -4,6 +4,12 @@ set -e
cd "$(dirname "$0")" cd "$(dirname "$0")"
mkdir -p out mkdir -p out
sdasz80 -plosgff out/crt0.rel crt0.s sdasz80 -plosgff out/crt0.rel crt0.s
sdcc -mz80 --opt-code-speed --max-allocs-per-node 20000 --std-sdcc11 -c -o out/basic.rel basic.c sdcc -mz80 --opt-code-speed --max-allocs-per-node 100000 --std-sdcc11 -c -o out/basic.rel basic.c
sdcc -mz80 --no-std-crt0 --code-loc 0x0080 --data-loc 0x8000 -o out/basic.ihx out/crt0.rel out/basic.rel sdcc -mz80 --no-std-crt0 --code-loc 0x0080 --data-loc 0x8000 -o out/basic.ihx out/crt0.rel out/basic.rel
python3 ../tools/ihx2mem.py out/basic.ihx basic.bin basic.mem python3 ../tools/ihx2mem.py out/basic.ihx basic.bin basic.mem
# the code must end below 8000h, where BASIC's data starts
end=$(awk '$2 == "s__GSFINAL" {print $1}' out/basic.map)
if [ $((16#$end)) -gt $((0x8000)) ]; then
echo "BASIC is too big: its code runs to $end, past 8000h" >&2
exit 1
fi
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Try BASIC's line editor in tools/z80emu.py, with the screen kept by pyte.
python3 test-edit.py
Types lines the way the keyboard sends them (cursor keys as ESC [ C and so
on), checks what the screen shows while a line is edited, and checks the
program LIST prints afterwards. Needs pyte.
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "tools"))
from boardemu import Board # noqa: E402
RIGHT, LEFT, HOME, END, DEL = b"\x1b[C", b"\x1b[D", b"\x1b[1~", b"\x1b[4~", b"\x1b[3~"
BS, CTRL_U, CR = b"\x7f", b"\x15", b"\r"
class Basic(Board):
def __init__(self):
mem = bytearray(open(os.path.join(HERE, "basic.bin"), "rb").read())
mem += bytes(65536 - len(mem))
super().__init__(mem, start=0)
self.pc = 0
self.m[0] = mem[0]
self.idle = 0
def io_in(self, port):
if port & 0xFF == 0 and not self.keys_in:
self.idle += 1
return super().io_in(port)
def io_out(self, port, v):
self.idle = 0 # printing reads the status port too
super().io_out(port, v)
def type(self, keys):
"""Send keys one at a time and run until BASIC waits for the next."""
for k in [keys[i:i + 1] for i in range(len(keys))]:
self.keys_in += k
self.idle = 0
while self.idle < 50:
self.step()
def main():
b = Basic()
errors = 0
def check(what, ok):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
errors += not ok
def screen():
return b.screen_text()
def lines():
return "\n".join(l.rstrip() for l in screen().display)
def row(r):
return screen().display[r].rstrip()
def cur():
s = screen()
return s.cursor.y, s.cursor.x
b.type(b"")
b.type(b'10 PRINT "HELLO"' + CR + b"20 GOTO 10" + CR)
y = cur()[0]
b.type(b"10" + RIGHT)
check("right after 10 brings line 10 in", row(y) == '10 PRINT "HELLO"' and cur() == (y, 16))
b.type(LEFT * 6) # cursor onto the H
check("left moves the cursor back", cur() == (y, 10))
b.type(b"BIG ")
check("typing inserts in the middle", row(y) == '10 PRINT "BIG HELLO"' and cur() == (y, 14))
b.type(HOME + RIGHT * 3 + DEL * 6)
check("Home and Delete", row(y) == '10 "BIG HELLO"' and cur() == (y, 3))
b.type(b"PRINT " + END + BS + b'!"')
check("End and Backspace", row(y) == '10 PRINT "BIG HELLO!"')
b.type(CR + b"LIST" + CR)
lst = lines()
check("the edited line is stored", '10 PRINT "BIG HELLO!"\n20 GOTO 10' in lst)
b.type(b"99" + RIGHT)
y = cur()[0]
check("right after a missing line number does nothing", row(y) == "99" and cur() == (y, 2))
b.type(CTRL_U)
check("Ctrl-U clears the line", row(y) == "" and cur() == (y, 0))
b.type(b"20" + RIGHT + HOME + DEL * 2 + b"30" + CR)
b.type(b"LIST" + CR)
lst = lines()
check("a recalled line can be stored as a copy", "20 GOTO 10\n30 GOTO 10" in lst)
# a line that wraps onto three screen rows
text = "REM " + "".join(chr(65 + i % 26) for i in range(170))
b.type(b"40 " + text.encode() + CR)
b.type(b"40" + RIGHT)
y, x = cur()
full = "40 " + text
y0 = y - (len(full) // 80)
shown = "".join(screen().display[y0 + i] for i in range(3))
check("a long line comes in over three rows", shown.rstrip() == full and (y, x) == (y0 + len(full) // 80, len(full) % 80))
b.type(HOME + RIGHT * 79)
check("right walks across a row end", cur() == (y0, 79))
b.type(RIGHT)
check("and onto the next row", cur() == (y0 + 1, 0))
b.type(b"*" + LEFT * 2 + DEL)
full = full[:79] + "*" + full[80:]
shown = "".join(screen().display[y0 + i] for i in range(3))
check("inserting and deleting across rows redraws them", shown.rstrip() == full and cur() == (y0, 79))
b.type(CR + b"LIST 40" + CR)
check("the long line is stored", full in "".join(screen().display))
b.type(b"NEW" + CR + b'INPUT A$: PRINT "GOT ";A$' + CR)
b.type(b"ABD" + LEFT + b"C" + CR)
check("INPUT uses the editor too", "GOT ABCD" in lines())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()
+19 -3
View File
@@ -44,17 +44,33 @@ RUN
``` ```
- **Ctrl-C** stops a running program. - **Ctrl-C** stops a running program.
- **Backspace** (or Delete) rubs out the last character. - **Left** and **Right** move the cursor along the line; **Home** and **End**
(or Ctrl-A and Ctrl-E) jump to its start and end. What you type goes in at
the cursor.
- **Backspace** rubs out the character before the cursor, **Delete** the one
under it.
- **Ctrl-U** erases the whole line. - **Ctrl-U** erases the whole line.
- Cursor keys are ignored. - **Enter** takes the whole line, wherever the cursor is.
Lines can be up to 250 characters. Lower case is accepted and turned into upper Lines can be up to 250 characters. Lower case is accepted and turned into upper
case, except inside quotes. case, except inside quotes.
### Editing a program ### Editing a program
- To replace a line, type it again with the same number. - To change a line, type its number and press **Right**: the line comes up
as `LIST` would show it, with the cursor at the end, ready to edit. Move
back with Left or Home, fix it, and press Enter. If there is no such line,
Right does nothing.
- To copy a line, bring it up the same way and change its number.
- To replace a line, you can also type it again with the same number.
- To delete a line, type its number alone. - To delete a line, type its number alone.
```
10 PRINT "HELO"
10→ the line comes back: 10 PRINT "HELO"
←←←L Enter now it is 10 PRINT "HELLO"
```
- Lines are kept in number order whatever order you type them in. Number in - Lines are kept in number order whatever order you type them in. Number in
tens (10, 20, 30…) to leave room for later additions. tens (10, 20, 30…) to leave room for later additions.
- Changing the program clears all variables. - Changing the program clears all variables.
Binary file not shown.