izapplebasic

package module
v0.0.0-...-426efd0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: GPL-3.0 Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

izapplebasic

Applesoft and Integer BASIC on modern hardware. It runs the unmodified Apple II ROMs on the iz6502 emulated CPU and intercepts the monitor calls to use the modern computer interfaces, in the spirit of bbz.

The project is a Go library with the emulation core, package izapplebasic at the root, and two frontends in cmd: the command line izapplebasic and the izapplebasic-telegram bot. All the filesystem access happens on the frontends.

go install github.com/ivanizag/izapplebasic/cmd/...@latest

Command line usage

izapplebasic
]10 FOR I=1 TO 5
]20 PRINT I, I*I
]30 NEXT
]RUN
1               1
2               4
3               9
4               16
5               25

Both ROMs are embedded in the binary, Applesoft is the default and -language integer boots the other one:

izapplebasic -language integer
>10 FOR I=1 TO 5
>20 PRINT I, I*I
>30 NEXT I
>RUN
1  1
2  4
3  9
4  16
5  25

Another ROM image can be used with the -rom argument, 12 KB from 0xd000 or 8 KB from 0xe000. It is booted through the reset vector, as the Apple II+ one.

Options:

  • -language <name>: BASIC to boot, applesoft or integer (default: applesoft)
  • -rom <file>: filename of another ROM (default: embedded)
  • -home: clear the host screen on HOME (default: HOME is ignored)
  • -c: trace the CPU execution
  • -m: trace the intercepted monitor calls excluding char output
  • -M: trace the intercepted monitor calls including char output
  • -s: trace the accesses to the softswitches at 0xc0xx
  • -l: do not convert the input to uppercase
  • -r: disable the readline like input with history
  • -load <file>: load the emulation state from a file on startup
  • -tape <name>: name of the cassette tape inserted on startup (default: default)

How it works

The emulated machine is an Apple II with 48 KB of RAM and nothing in the slots. With the Apple II+ ROM, on reset the autostart monitor finds no bootable card and falls back to Applesoft BASIC. The Apple II ROM has the original monitor, which has no autostart and stops on the * prompt: the run loop takes over at MON (0xff65), where the reset code has set up the screen and the I/O vectors but has not printed anything yet, and enters Integer BASIC on its cold start (0xe000).

Both ROMs share the same monitor entry points for console I/O, they are patched with an RTS and intercepted when the program counter reaches them:

  • COUT1 (0xfdf0): char output
  • KEYIN (0xfd1b): char input, used by Applesoft GET and by the Integer BASIC direct mode, which reads its prompt key by key instead of calling GETLN
  • GETLN1 (0xfd6f): line input, used by the Applesoft direct mode prompt and by INPUT. The prompt printing entry points GETLNZ and GETLN are real ROM code running on the intercepted COUT.
  • HOME (0xfc58): clear the screen, on the command line ignored unless -home is given
  • WRITE and READ (0xfecd, 0xfefd): the cassette tape

On a real Apple II the screen is random access: Applesoft moves the cursor for HTAB and the comma print zones just by changing CH (0x24). The output here is a stream, so the interception tracks the host column and pads with spaces when CH jumps forward.

The intercepted output is also mirrored to the text page memory at 0x0400, respecting the text window, so the screen snapshots show the session as a real Apple II would.

Meta commands

Lines starting with / are processed by the frontend, they never reach the emulated machine. On the command line, press tab after the / to see them all:

  • /help: list the meta commands
  • /quit: exit
  • /reset [applesoft|integer]: reboot the machine, losing everything not saved. Without an argument it stays on the BASIC in use, with one it switches: /reset integer reboots into Integer BASIC.
  • /save [filename] and /load [filename]: save the emulation state, CPU, RAM, video mode and which BASIC was running, and load it back, even on another session. A state saved on one BASIC brings its ROM along on the load. The state can also be loaded on startup with the -load argument.
  • /export [filename.bas]: save the program in memory as a text file, laid out as LIST prints it. The keywords come from the token name table of the ROM itself, so a ROM given with -rom brings its own. Applesoft only for now, the Integer BASIC program format is not decoded yet.
  • /screenshot [filename.png]: save a PNG image of the emulated screen, rendered with the izapple2 screen module. The video mode softswitches (0xc050-0xc057) are tracked, so GR and HGR graphics, mixed modes and page 2 are rendered as they would show on the real screen.
  • /tape [name], /tapes [folder] and /rewind [block]: manage the emulated cassette deck, see below.
  • /!<command>: run a command on the host and show its output, like /!ls or /!cat program.bas. The rest of the line goes to a shell as it is, so the pipes, the globs and the quoting work. Only on the command line frontend, the telegram bot has no way to reach it.

The cassette

The monitor tape routines, WRITE (0xfecd) and READ (0xfefd), are intercepted too, so SAVE, LOAD, STORE, RECALL and SHLOAD work. Each monitor call is one checksummed record on a real tape, here one block stored as the file tape-NAME-nn.tape with the raw bytes. Reads and writes happen at the current tape position and advance it, /tape name inserts another tape rewound to block 0 and /rewind [block] moves the position. /tapes lists the tapes recorded on the current folder, or on the one given, with the number of blocks of each:

]/tapes
tapes in .:
  adventure (2 blocks)
  default (4 blocks, inserted)

Integer BASIC SAVE and LOAD go through the same monitor routines. An Applesoft SAVE writes two blocks, the length header and the program:

]/tape adventure
tape adventure inserted and rewound
]10 PRINT "YOU ARE IN A MAZE"
]SAVE
]/rewind
tape adventure at block 0
]LOAD
]RUN
YOU ARE IN A MAZE

The tape operations are silent as on the real machine, the -m trace shows the blocks being read and written. Reading past the last block or a block recorded with a different size shows the monitor ERR, as a bad tape would.

Frontends

  • Command line: readline like input with history recall on the up and down arrows, saved in .izapplebasichistory. Tab completes the meta commands and their arguments: on a / it lists the commands, after the space it offers the BASICs of /reset, the tapes of the drive for /tape and the files or folders of the host for the rest. On a prefix it completes as far as it is unambiguous and a second tab shows the candidates. Falls back to plain stdin/stdout when the input is piped or with -r, without the editing or the completion.
  • Telegram: running at https://t.me/a2basic_bot. See below to host your own bot

The frontends implement the Console interface of the core package, including their own meta commands: the telegram bot has no way to name files on the host.

Telegram bot

izapplebasic-telegram -token <bot token>

The token comes from @BotFather, by argument or in the TELEGRAM_TOKEN environment variable. The bot connects to Telegram with long polling, no webhook or open port is needed.

Every user gets a persistent Apple II, running Applesoft until /reset integer switches it: on each message the state is loaded from a file, the lines of the message are executed and the state is saved back. Multiline messages work, a whole program can be pasted at once. A program waiting on INPUT or GET takes the next message as the answer. Programs running longer than the per message budget are stopped with the control-C break.

Text replies are monospace. When a command draws GR or HGR graphics a snapshot of the screen is attached.

The bot has its own meta commands, registered on Telegram so they are suggested when typing /:

  • /help: list the commands
  • /screenshot: show an image of the emulated screen
  • /reset [applesoft|integer]: reboot the machine, losing everything not saved. Without an argument it stays on the BASIC in use, with one it switches: /reset integer reboots into Integer BASIC. The choice persists between messages.
  • /save [name], /load [name], /list and /delete [name]: manage named states, stored on the folder of the user, up to 30 per user
  • /tape [name], /rewind [block] and /deletetape <name>: the cassette deck for the BASIC SAVE and LOAD, stored on the folder of the user, up to 30 blocks per user. The inserted tape and its position persist between messages.

Each user has a directory under -data (default telegram-data) with the current state, the named saved states and a log of the interaction.

To deploy with docker compose, from cmd/izapplebasic-telegram: put the token in a .env file (TELEGRAM_TOKEN=...), create the telegram-data directory owned by uid 1000, and run docker compose up -d.

Limitations

  • Line based input: the keystroke reads take a whole line and serve it key by key, so Applesoft GET waits for the enter key. The meta commands are processed on the line boundary.
  • The graphics are only visible through /screenshot, there is no live graphics display. No disk.
  • Control-C breaks the running BASIC program as on a real Apple II, press it twice in fast succession to quit.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExportNotSupported = errors.New("the program can only be exported from Applesoft BASIC")

ErrExportNotSupported is returned for a BASIC whose stored program format is not decoded yet.

Functions

This section is empty.

Types

type Console

type Console interface {
	// ReadLine returns a full line of input, without the final CR.
	// The second value is true when there is no more input (EOF).
	// The line is echoed by the frontend: it is read by a ROM call
	// that does not print what it reads.
	ReadLine(prompt string) (string, bool)

	/*
		ReadKeys returns a line of input to be delivered to the
		machine one keystroke at a time, as Integer BASIC reads its
		direct mode and Applesoft reads a GET.

		Same as ReadLine, except that the frontend must not echo the
		line: the machine prints the keys itself as it reads them.
	*/
	ReadKeys(prompt string) (string, bool)

	// Write sends text to the user.
	Write(string)

	// Clear clears the screen, if the frontend supports it.
	Clear()

	// MetaCommand gives the frontend the chance to process an input
	// line as one of its meta commands, returning true when the
	// line was consumed and must not reach the emulated machine.
	MetaCommand(line string) bool

	// TapeWrite stores one block on the tape.
	TapeWrite(data []uint8)

	// TapeRead returns the next block of the tape, or nil when
	// there is no tape or no more blocks. The requested size is a
	// hint for the frontend, the caller deals with mismatches.
	TapeRead(requested int) []uint8
}

Console is the interface implemented by the frontends. The emulation core uses it for all the input and output intercepted from the monitor ROM calls. The core does not touch the host filesystem: anything involving files lives on the frontends.

type Environment

type Environment struct {

	// Uppercase converts the input to uppercase, as the Apple II+
	// keyboard would
	Uppercase bool

	// TraceMonitor dumps the intercepted monitor calls, and
	// TraceMonitorIO also the char output ones
	TraceMonitor   bool
	TraceMonitorIO bool

	// MaxCycles stops the emulation after this many cycles, 0 for
	// no limit
	MaxCycles uint64

	// BreakCycles injects a control-C when reached, to break BASIC
	// programs running for too long. 0 for no limit.
	BreakCycles uint64
	// contains filtered or unexported fields
}

Environment is an Apple II running Applesoft or Integer BASIC with the console I/O intercepted.

func NewEnvironment

func NewEnvironment(rom []uint8) (*Environment, error)

NewEnvironment builds the machine with the given ROM, or the embedded Apple II+ ROM when nil. A ROM given here is booted as the Apple II+ one, through the reset vector. The console has to be set with SetConsole before calling Run.

func NewEnvironmentWithLanguage

func NewEnvironmentWithLanguage(language Language) (*Environment, error)

NewEnvironmentWithLanguage builds the machine with the embedded ROM of the given BASIC.

func (*Environment) Break

func (env *Environment) Break()

Break presents a control-C keypress to the emulated machine, to break a running BASIC program. Safe to call from any goroutine.

func (*Environment) ClearGraphicsDirty

func (env *Environment) ClearGraphicsDirty()

func (*Environment) Cycles

func (env *Environment) Cycles() uint64

Cycles returns the CPU cycles executed so far.

func (*Environment) ExportProgram

func (env *Environment) ExportProgram() (string, error)

ExportProgram returns the BASIC program in memory as text, laid out as LIST prints it.

func (*Environment) GraphicsDirty

func (env *Environment) GraphicsDirty() bool

GraphicsDirty reports if the emulated code drew graphics since the last call to ClearGraphicsDirty.

func (*Environment) Language

func (env *Environment) Language() Language

Language returns the BASIC in ROM.

func (*Environment) LoadState

func (env *Environment) LoadState(r io.Reader) error

func (*Environment) Reset

func (env *Environment) Reset()

Reset takes the machine back to a cold boot: the RAM is cleared and the CPU restarts on the reset vector. The BASIC in ROM is kept, use ResetWithLanguage to change it.

func (*Environment) ResetWithLanguage

func (env *Environment) ResetWithLanguage(language Language) error

ResetWithLanguage swaps the ROM for the one of the given BASIC and does a cold boot on it.

func (*Environment) Run

func (env *Environment) Run()

Run is the main emulation loop. It executes instructions and intercepts the monitor calls, until there is no more input or Stop is called.

func (*Environment) SaveState

func (env *Environment) SaveState(w io.Writer) error

func (*Environment) SetConsole

func (env *Environment) SetConsole(con Console)

SetConsole attaches the frontend.

func (*Environment) SetTraceCPU

func (env *Environment) SetTraceCPU(trace bool)

SetTraceCPU dumps the CPU execution operations.

func (*Environment) SetTraceIO

func (env *Environment) SetTraceIO(trace bool)

SetTraceIO dumps the accesses to the softswitches at 0xc0xx.

func (*Environment) Snapshot

func (env *Environment) Snapshot() image.Image

Snapshot renders the emulated screen with the pixels widened to compensate the vertical stretch of the CRT line separation, as izapple2 does when saving to a file.

func (*Environment) Stop

func (env *Environment) Stop()

Stop makes Run return at the next instruction.

func (*Environment) VideoModeName

func (env *Environment) VideoModeName() string

VideoModeName describes the active video mode, like "TEXT40COL" or "HGR-MIX40".

type Language

type Language uint8

Language is the BASIC in ROM.

const (
	LanguageApplesoft Language = 0
	LanguageInteger   Language = 1
)

func ParseLanguage

func ParseLanguage(name string) (Language, bool)

ParseLanguage resolves the name of a BASIC as the frontends take it from the user, on the command line or on a meta command.

func (Language) Name

func (l Language) Name() string

Name returns the name of the BASIC, to show to the user.

Directories

Path Synopsis
cmd
izapplebasic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL