SyncTERM is a terminal program written specifically for connecting to Bulleten Board Systems (BBSs). Despite the name, SyncTERM is in no way Synchronet specific, it just happens to share a large portion of code with the rest of the Synchronet project, and live in the same git repository.
Getting Support
If you need help with SyncTERM, the best places are:
- IRC
-
Connect to irc.synchro.net and find Deuce in #Synchronet. Ask your question, then idle. I can take hours to respond. Do not give up, this is the quickest way to get a response.
- SourceForge
-
The official SyncTERM project page has a bug tracker and other features that will email me and provide tracking for issues that are filed.
-
I am usually fairly responsive to emails sent to me at shurd@sasktel.net. Please describe your issue as clearly as possible.
- Dove-Net
-
While I no longer read Dove-Net regularly, many other users can often help with support issues. Ask questions in the Hardware/Software Help sub. If your local BBS does not carry Dove-Net, you can telnet to vert.synchro.net and leave messages there.
Throughout this document, I will mention things which are not supported. These are things which I don’t normally test, and are unlikely to work at any given time. If you ask for support on one of these issues, I may help out, or I may not. It doesn’t bother me if you ask for help on these things, but if you continue to ask for help after I refuse, it will make it less likely I’ll work on it in the future.
History
I started writing SyncTERM in June of 2004. There weren’t any good BBS clients available for FreeBSD at the time, so I started writing one. Initially, it was RLogin only and no file transfer support existed or was planned. since RLogin supports auto-login with user ID and password on Synchronet systems, and RLogin is a much simpler protocol than telnet, no telnet support was planned. Digital Man (authour of Synchronet) added telnet and ZModem support a year later, and SyncTERM became a generally usable BBS client. New features continued to be added slowly over the years.
Getting SyncTERM
Releases of SyncTERM are available on the SourceForge project page. Nightly builds and source bundles are also available at the SyncTERM website for the more adventurous.
Compiling SyncTERM from Source
SyncTERM is a standalone CMake project. It requires CMake 3.22 or later and a C17 compiler. Windows builds support both MSVC and MinGW; POSIX builds include FreeBSD, Linux, macOS, Haiku, and other sufficiently capable POSIX-like systems.
Dependencies
libjxl is an optional but strongly
recommended dependency. It provides JPEG XL graphics support; without it,
the only generally available image-transfer representation is uncompressed
PPM. CMake’s ST_PIXEL_IMAGE_JXL setting accepts AUTO, ON, or OFF;
AUTO enables the decoder when usable libjxl decode and CMS headers are
available, while ON makes those headers mandatory. The resulting binary
loads libjxl and libjxl_cms at run time and reports support only when the
complete decoder is available. libjxl_threads is loaded opportunistically;
its absence merely selects single-threaded decoding.
Encrypted BBS lists and TLS use either Botan 3.13 or newer or OpenSSL 3.0 or
newer. CMake prefers a usable Botan installation and then OpenSSL when
CRYPTO_BACKEND is left unset. A build without either provider is possible,
but encryption and TLS-dependent features are unavailable. The provider can
be selected explicitly with -DCRYPTO_BACKEND=Botan,
-DCRYPTO_BACKEND=OpenSSL, or -DCRYPTO_BACKEND=none.
The graphical console uses the native backend where one is available: X11 or
Wayland on POSIX desktops, Quartz on macOS, and GDI on Windows. X11 requires
the Xlib, Xutil, and XKB development interfaces; XRender, XRandR, and Xinerama
are used when available. Wayland requires the Wayland client and xkbcommon
development interfaces, wayland-scanner, and the core, xdg-shell, and
viewporter protocol descriptions. SDL 2 remains an optional fallback and is
particularly useful on Haiku, but is no longer the primary graphical backend
on platforms with a native implementation. ANSI, ncurses, and the native
Windows console provide non-bitmap output modes.
In ANSI and ncurses modes, a fixed-size BBS screen is centred within a
larger host terminal, with a blue surround. Resizing the host recentres the
screen without changing the selected BBS screen size. LeftJustify=true
in the configuration’s [SyncTERM] section selects left alignment and a
black surround; vertical alignment remains centred. A host terminal smaller
than the BBS screen displays its upper-left portion.
Audio output can use the native CoreAudio or WASAPI backend, or the optional PortAudio, PipeWire, PulseAudio, ALSA, OSS, and SDL backends. CMake enables the usable choices it detects; most non-system backends are loaded at run time, but their development headers are required when building them.
Configure and build out of the source tree, then run the tests:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
With a single-configuration generator, the executable is
build/bin/syncterm. Multi-configuration generators place it under the
selected configuration directory.
CMake detects the console, audio, cryptography, and other optional
facilities available on the target. Most optional backend controls use
AUTO, ON, or OFF: AUTO enables a backend when its complete build
requirements are present, ON requires it and makes configuration fail
when it is unavailable, and OFF excludes it. The principal controls are
ST_CONSOLE_X11, ST_CONSOLE_WAYLAND, and ST_CONSOLE_SDL for graphical
console backends, the ST_AUDIO_* family for audio backends, and
CRYPTO_BACKEND (unset for automatic selection, or Botan, OpenSSL, or
none) for cryptography.
For example:
cmake -S . -B build -DST_CONSOLE_WAYLAND=ON -DST_CONSOLE_SDL=OFF
SYNCTERM_ENABLE_UNIFONT is enabled by default. It includes SyncTERM Unicode,
a modified GNU Unifont-derived font with an UNSCII overlay, distributed under
the SIL Open Font License 1.1. Configure with
-DSYNCTERM_ENABLE_UNIFONT=OFF to omit that data. Original SyncTERM material
remains under the two-clause BSD license. The font copyright notices and full
license are available under SyncTERM Settings > Licenses and in
src/fonts/unifont/LICENSE.OFL-1.1; see LICENSE and src/fonts/unifont/UPSTREAM.md.
All builds also include SyncTERM Emoji, rasterized from monochrome Noto Emoji
for 8x8, 8x14, and 8x16 cells under SIL OFL 1.1. This covers skin-tone and
joined sequences supported by the source font, as well as individual emoji,
flags, keycaps, and presentation selectors. The attribution and full license
are available in SyncTERM Settings > Licenses and src/fonts/builtin/LICENSE.NOTO-EMOJI.
Running SyncTERM
SyncTERM supports command-line options to control behaviour. Option letters
are case-insensitive, except for the standalone -T and -v actions
described below. Values for -i and -l must be attached to their letters
(for example, -isf and -l43). Paths for -b, -n, and -w may be
attached (for example, -b/path/to/list) or supplied as the next argument.
- -6
-
Specifying -6 forces SyncTERM to use IPv6 addresses when possible.
- -4
-
Specifying -4 forces SyncTERM to use IPv4 addresses when possible.
- -B/path/to/bbs/list.lst
-
Loads the user BBS list from the specified file instead of the default.
- -C
-
Changes the default to no status line.
- -H
-
Use SSH mode when connecting.
- -I(A[U|C]|C|F|I|G[W|F]|Q[W|F]|S[W|F]|W|X[W|F]|Y[W|F])
-
Selects the output mode. Not all modes are available in all builds or on all platforms;
-?lists the modes compiled into the current build. Legal values are:- A or AU
-
UTF-8 ANSI output mode. This mode outputs ANSI control sequences and UTF-8 text to stdout.
Ais an alias forAU. - AC
-
CP437 ANSI output mode. This emits CP437 bytes instead of UTF-8.
- C
-
Curses output mode. For use in *nix terminals.
- F
-
Curses with forced IBM character set. Limited usefulness.
- G[WF]
-
Windows GDI output mode. Uses the Win32 API directly, and is the default for Windows. Additionally, a 'W' or 'F' can be specified to force windowed or full-screen mode respectively.
- I
-
Curses in ASCII mode.
- S[WF]
-
SDL window output mode. Uses the SDL library for output. Additionally, a 'W' or 'F' can be specified to force windowed or full-screen mode respectively.
- W
-
Windows console mode. Windows only mode which uses the system console APIs for output.
- Q[WF]
-
Quartz output mode. macOS only mode which uses the native AppKit/Core Graphics framework for drawing. The default on macOS. Additionally, a 'W' or 'F' can be specified to force windowed or full-screen mode respectively.
- X[WF]
-
X11 output mode. UNIX only mode which directly uses the X11 libraries for drawing. Additionally, a 'W' or 'F' can be specified to force windowed or full-screen mode respectively.
- Y[WF]
-
Wayland output mode. UNIX only mode which uses the native Wayland protocol for drawing. The default where supported. Additionally, a 'W' or 'F' can be specified to force windowed or full-screen mode respectively.
Refer to the Output Modes section for more details.
- -L##
-
Specifies the number of lines on the "screen". Supported values are: 14, 21, 25 (default), 28, 30, 43, 50, and 60. An unsupported value is reported as a command-line error.
- -N/path/to/config.ini
-
Loads the configuration from the specified file instead of the default.
- -Q
-
Quiet mode, doesn’t show popups by default.
- -R
-
Use RLogin mode when connecting.
- -T
-
Use Telnet mode when connecting. If an upper-case -T is the only argument passed to SyncTERM however, SyncTERM will output a terminfo entry on stdout then exit. See Installing Terminfo Entry for more details.
- -S
-
Use "safe" mode. This mode attempts to restrict the ability of the user to modify the local drive contents. This has not been exhaustively audited, and should therefore not be trusted.
- -v
-
This option is case-sensitive. When it is the only argument, causes SyncTERM to output its version on stdout and exit.
- -?, --help
-
Shows command-line help, including output mode descriptions and URL examples, then exits.
- -W/path/to/script.wren
-
Loads the named Wren script in addition to the built-in and user auto-load scripts on every connect. The script is interpreted as its own filename-derived module after all other scripts have loaded, so its
importstatements resolve against the full surface. Compile and runtime errors during the load are written to standard error.
After the options, a full URI, hostname, or dialing directory entry may be specified. Supported URI schemes are: rlogin://, ssh://, telnet://, raw://, mqtts://, ws+telnet://, and wss+telnet://.
The WebSocket schemes carry binary Telnet data. They default to port 80
and 443 respectively. Include the server’s port when it differs from the
default. A path and query are passed to the HTTP server as entered,
including percent escapes, for example
wss+telnet://bbs.example.org/wss?mode=ansi. With no path, SyncTERM requests
/. WSS uses the TelnetS TLS settings and requires a TLS provider. Plain
WS also works in builds without a provider, where it uses the C library
PRNG and does not meet the WebSocket requirement for unpredictable masks.
mqtts:// connects to a Synchronet BBS’s internal MQTT broker as a
sysop-spy client. It always uses TLS-PSK on port 8883 (no plaintext
mqtt:// form is accepted) — the user portion of the URL becomes the
PSK identity, the password portion becomes the PSK secret, and a
prompt for the system password appears at connect time if the matching
dialing-directory entry doesn’t carry one. After authentication,
SyncTERM auto-discovers the BBSID from a retained broker topic, lists
the active nodes, and lets you pick which one to attach to. See
SBBS MQTT Spy under Connection Types.
If there is an entry matching the URI, hostname, or entry name, the settings will be loaded from the BBS list, then modified per the command-line arguments.
Advanced Keyboard Controls
The console layer directly implements some advanced keyboard controls. While these are not available in all output modes, they are available everywhere and not just in the menus or in the connected state.
- Keyboard Controls
-
- Alt+→
-
Snap the window size to the next smaller integer zoom level
- Alt+←
-
Snap the window size to the next larger smaller integer zoom level
- Alt+Return
-
Toggle fullscreen mode
- Alt+Home
-
Centre window on the screen
- Alt+drag
-
Hold Alt and drag the window with the left mouse button to move it on the desktop. Available in the Wayland output mode when the compositor does not provide server-side decorations (i.e. there is no title bar to drag).
In addition, you can directly enter characters either by their "codepage" value or their unicode value. A "codepage" value is an 8-bit value that indicates a character in the current codepage (such as the default CP437).
To enter a codepage value, ensure NumLock is on, and hold down an Alt key, then enter the decimal value on the numeric keypad. Do not enter leading zeros, as that would indicate a unicode value. Once the value is entered, release the Alt key.
A unicode value is the Unicode codepoint number. On a UTF-8 connection,
any valid Unicode character can be entered. On a codepage connection,
characters from any Unicode plane can be entered when they map to the
current codepage. On a UTF-8 connection and in the menus, entries without
a leading zero also use their Unicode value; for example, Alt+255
and Alt+0255 both enter ÿ. On a CP437 connection,
Alt+130 and Alt+0233 both enter é.
To enter a unicode value, ensure NumLock is on, and hold down an Alt key, press the 0 key on the numeric keypad, then enter the decimal value on the numeric keypad. Once the value is entered, release the Alt key.
This requires an input backend that receives physical key presses and releases. In curses and ANSI modes, character composition is handled by the host terminal. Native macOS keypads are numeric without a NumLock setting. Entries without a leading zero must be between 1 and 255; Unicode entries must be nonzero valid Unicode scalar values. Out-of-range entries are ignored. Another key press or loss of focus cancels a partial entry.
Emoji Picker
Press Alt+P in a local text field or on a UTF-8 connection to insert an emoji. ANSI and ncurses modes also provide Ctrl+P in local text fields. While viewing a connected terminal, Ctrl+P is sent to the remote system; use the Online Menu’s Insert Emoji… entry if Alt+P is unavailable. The connected picker is available only on UTF-8 connections. Local fields in menus reached through Alt+E still support it on codepage connections.
Type to filter by localized name or CLDR search keywords. The highlighted emoji’s localized name appears below the grid. Language preferences come from Windows/macOS UI settings or the POSIX locale environment; regional and script fallbacks follow CLDR. Missing translations fall back to English, and English names and keywords are always searchable. All data is bundled for offline use. Use the arrow keys to browse, F2 or Variants for gender and skin-tone variants, and Return or a click to insert. Escape returns from variants or cancels. The picker includes only emoji supported by the bundled fonts; joined sequences are inserted together and never truncated to fit a field. Opening it without a focused field does not copy to the clipboard. The mouse wheel scrolls the grid without changing the selected emoji. Keyboard navigation brings the selection back into view.
The 32 most recently used exact variants appear first and are saved as numbered
UTF-8 strings in the [RecentEmoji] section of syncterm.ini. Safe mode keeps
recents only for the current session. A failure to save recents is reported in
the Wren console and does not undo a successful insertion.
The User Interface
The following is the general behaviour of SyncTERM menus.
- Mouse controls
-
- Right-click
-
Same as pressing ESC (ie: exit menu).
- Left-click
-
Select an item in a menu.
If there is a blank line at the end of the menu, you can select it to insert a new item.
Menus have a standard set of mouse controls. If you click outside of a menu, that menu is usually closed, but in some cases, it may simply become inactive. At the top of each menu is a block which is used to close the menu. If there is help for the menu, there is also a ? button to bring up the help.
If there are more options than fit in the window, there is a scrollbar on the right side.
- Left-Drag
-
Select and copy a region (the copy is made when the button is released).
- Middle-click
-
Paste from PRIMARY selection or clipboard.
- Keyboard Controls
-
- Return
-
Select the currently highlighted option. If there is a blank line at the end of the menu, you can select it to insert a new item.
- Escape
-
Exit the current menu.
- Backspace
-
An alias for Escape.
- Ctrl+C
-
An alias for Escape.
- Home
-
Jump to the beginning of the menu
- ↑
-
Move to the previous item in the list
- Page Up
-
Jump up in the menu by one screen.
- Page Down
-
Jump down in the menu by one screen.
- End
-
Jump to the end of the menu
- ↓
-
Move to the next item in the list.
- F1
-
Help
- F2
-
Edit
- F5
-
Copy
- Ctrl+Insert
-
An alias for F5
- Shift+Delete
-
Cut
- F6
-
Paste
- Shift+Insert
-
An alias for F6
- Insert
-
Inserts a new item.
- +
-
An alias for Insert
- Delete
-
Delete item at current location
- -
-
An alias for Delete
- Any letter or number
-
Jumps to the next item that has that character earliest in it’s name.
- Ctrl+F
-
Find text in options
- Ctrl+G
-
Repeat last find
The File Browser
SyncTERM uses a shared file browser whenever a file or directory must be picked — for example when uploading a file (Alt+U), loading a font (Alt+F), or naming a capture file (Alt+C).
The browser shows three rows of content inside its window:
- Directory and File panes
-
Two side-by-side lists. The left pane contains subdirectories plus a
..entry (except at the filesystem root), and the right pane contains files that match the current mask. Directories are always listed regardless of the mask. - Info pane
-
A two-line area below the lists. The first line shows the full name of the item currently highlighted in whichever list has focus; the second line shows its size (or the word
directory) and last-modified timestamp. In the multi-file picker it also shows[selected]when the highlighted file is already tagged. - Mask and Path fields
-
The mask filters the file list (for example
*.bin). The path field always shows the current location. When the caller permits typing a path, e.g. Upload, it also lets you type a directory or filename directly. Long paths are shown from the end so the deepest directory stays visible.
The footer holds an OK (or Select) button and a Cancel button.
In the multi-file picker there is also a Review button.
- Keyboard Controls
-
- Tab / Shift+Tab
-
Move focus forward or backward between the panes, Mask, the editable Path field (when enabled), and the footer buttons.
- ← / →
-
Between the directory and file panes these move focus left or right. In the path and mask fields they move the edit cursor. Between the footer buttons they move focus between buttons.
- ↑ / ↓
-
In the lists they move the highlight. In the path and mask fields they move focus to the previous or next field.
- Return
-
In a list: open the directory, or commit the highlighted file (or toggle its selection in multi-pick). On a footer button: activate that button.
- Space
-
In the multi-file picker’s file list, toggles the highlighted file’s selection.
- Ctrl+A
-
Multi-file picker only — tags every file currently shown in the file pane. Does not descend into subdirectories. Safe to press repeatedly; files already tagged stay tagged.
- Ctrl+Return
-
Activate
OK/Selectfrom anywhere in the dialog, regardless of which field currently has focus. - F2
-
Multi-file picker only — opens the Review pop-up listing every tagged file. Inside the pop-up, Delete or Return or a left click removes the highlighted or clicked item, and Escape closes the pop-up.
- Escape
-
Cancel the browser.
- Mouse Controls
-
Clicking a list item in the currently-focused pane commits it immediately (or toggles it in multi-pick). Clicking a list item in an unfocused pane just moves focus and the highlight there — click again to commit. Clicking in the mask or path field places the edit cursor at that position. Clicking a footer button both focuses it and activates it.
The multi-file picker’s status line shows F2 Review while the dialog
is open. It returns the full path of every tagged file at once, so
you can queue uploads from several directories in a single pass.
The Dialing Directory
This is the default startup screen if no BBS is specified on the command-line. At the top is the program name and version, a build date, the current output mode, and the current date and time.
With version numbers, trailing letters indicate pre-release versions. 'a' indicates an alpha build which will have known bugs and/or incomplete features. 'b' indicates a beta build which indicates there are expected to be no known bugs, but it has not received testing. "rcX" is a release candidate where X is a number. These indicate that after some period (usually one to two weeks) of no newly reported bugs, a release will be made.
The output mode is important to make note of when reporting issues, since many bugs only impact one or two output modes. It’s after the build date.
The bottom-most line contains help on the current menu, indicating what options are available in the most recent menu.
There are three areas the user can interact with in the dialing directory. The Directory menu, the SyncTERM Settings menu, and the comment line.
The comment line is directly above the help line at the bottom, and allows a per-BBS comment to be entered.
The Directory
This menu lists all the entries in the two dialing directory files. If you move the bar over one and press <Enter>, it will connect you to the highlighted system as configured in the entry.
In addition to the standard controls, this menu also has some extra keyboard shortcuts.
- Ctrl+`
-
Open the Wren console in graphical and native-console output modes.
- Ctrl+Q
-
Open the Wren console in ANSI and Curses output modes. This binding applies to the dialing directory; while connected, Ctrl+Q retains its disconnect function and the console is available from the Ctrl+S Online Menu.
- Ctrl+D
-
Quick-connect to a URL
- Ctrl+E
-
Edit the selected entry (Alias for F2)
- Ctrl+S
- < / >
-
Cycle through sort profiles (previous / next). The current profile name is shown in the directory title bar.
- Alt+B
-
View the scrollback of the last session
- Tab
-
Move to the comment field for the current entry, or the settings menu if there is no current entry.
- Back Tab (Shift+Tab)
-
Move to SyncTERM Settings.
To add a new entry, go to the bottom of the list (by pressing end) and select the blank entry at the bottom. A window will pop up asking for the Name of the entry. This name must not already exist in the personal dialing directory.
Next you will be prompted for the protocol to use. Options include:
- RLogin
-
Uses the historic RFC1282 RLogin protocol, including its urgent-data controls for flow mode, received-output flushing, and window-size reporting. This is an obsolete, unencrypted protocol that can allow auto-login, and is 8-bit clean (unlike telnet). It is very simple. Instead of the local username, the users password is sent.
- RLogin Reversed
-
Some RLogin servers that support password auto-login have reversed the remote and local username fields. This allows connecting to these servers.
- Telnet
-
Uses the historic and highly complex telnet protocol. This is an obsolete, unencrypted protocol and is not 8-bit clean and predates TCP/IP. It has been the source of many security vulnerabilities over the fifty years or so it has existed. Historically, it has been the most common way to connect to a remote system as a terminal, so is widely supported.
- Raw
-
A raw 8-bit clean TCP connection. This is often what retro BBSs actually support when they say they support telnet.
- SSH
-
The Secure Shell v2 protocol. This is the modern replacement for both telnet and rlogin, and is widely supported. This is encrypted and performs user and server authentication as part of the protocol instead of inline. SyncTERM supports authenticating with both a password and a public key.
- SSH (no auth)
-
The SSH protocol, but will not send a password or public key. Used for auto-login systems where the user name by itself is sufficient.
- Modem
-
SyncTERM can directly control a modem for making outgoing calls.
- Serial
-
Direct communication with a serial port.
- 3-wire
-
Serial, but with only transmit and receive. In this mode, there is no way to detect if the remote has hung up and RTS/CTS hardware flow control is unavailable. XON/XOFF software flow control can still be used; without it, bytes can easily be lost. This is primarily used for communicating with embedded hardware, and not BBSs.
- Shell
-
Runs a shell in the terminal.
- MBBS GHost
- TelnetS
-
Telnet over TLS. All the drawbacks of the telnet protocol, but at least it’s encrypted. By default, SyncTERM authenticates the server using the public Web PKI. An entry can instead authenticate using one explicitly trusted certificate, or a TLS 1.3 or TLS 1.2 pre-shared key. Web-PKI trust and the explicitly trusted certificate are alternatives; their trust stores are never combined. After a certificate-authenticated connection, SyncTERM remembers the negotiated TLS version. A later downgrade requires user approval before any Telnet data is exchanged.
- Telnet over WebSocket and Telnet over Secure WebSocket
-
Binary Telnet over WebSocket. Set the server’s hostname and port, then set WebSocket Path and Query if the server uses a route other than
/. The secure variant uses the TLS settings described for TelnetS. - SBBS MQTT Spy
-
A sysop-spy connection to a Synchronet BBS’s internal MQTT broker. Subscribes to a node’s published terminal output, and (optionally) publishes locally typed keystrokes back as injected node input. Authentication is TLS-PSK on port 8883 — the entry’s User and Password are the PSK identity and secret, and the System Password is the broker’s MQTT-level password. When connecting, the BBSID is auto-discovered from the broker’s retained
sbbs/{BBSID}topic and the node number is chosen from a list of currently-active nodes. SyncTERM’s terminal emulator does not auto-respond to host queries (DSR, DECRQM, etc.) on this connection type so the real client driving the node still owns the query/response handshake. Also reachable from the command line asmqtts://user:pass@host.
Finally, you will be promted for the "address". This is the DNS addres, IP address, serial port, or command to connect to. If the connection will be made over the network, and the name is a valid hostname, it will be auto-filled in this field. To overwrite it, simply start typeing. A network address may include a TCP port after a single colon. The port must be a decimal number from 1 through 65535; invalid port input is shown again for correction.
Once these three pieces of information are entered, the entry is created and you are returned to the Directory. To further modify the settings, you can press F2 to enter the Edit Directory Entry menu.
Edit Directory Entry
In this menu, you can modify all the connection settings for an entry. The exact contents of this menu will vary a bit by connection type, but most of the options are the same or silimar.
- Ctrl+S
-
Edit the Explicit Sort Value.
- [ / ]
-
Navigate to the previous/next entry in the directory without returning to the directory listing. This also works in Font Management and Sort Profile field editors.
- Name
-
The name of the entry.
- Phone Number (Modem only)
-
The phone number to dial.
- Device Name (Serial and 3-wire only)
-
The device name to open.
- Command (Shell only)
-
The command to run (usually a shell such as /bin/sh)
- Address
-
IP address or host name
- Connection Type
-
Protocol to use. See [protocols]. When you change the protocol, the port number value will be updated as well.
- Flow Control (Modem, Serial, and 3-wire)
-
The type of flow control to use. RTS/CTS, XON/XOFF, Both, or None. For 3-wire connections, only XON/XOFF or None can take effect; any RTS/CTS component is ignored.
- Stop Bits (Modem, Serial, and 3-wire)
-
The number of stop bits to use.
- Data Bits (Modem, Serial, and 3-wire)
-
The number of data bits to use.
- Parity (Modem, Serial, and 3-wire)
-
The parity setting to use. Options are None, Even, Odd, Mark, and Space.
- TCP Port
-
The TCP port to connect to.
- SSH Username (SSH no auth only)
-
The username to send for the SSH protocol. Some BBSs have everyone log in to SSH with the same username, then log into the BBS with their name. This allows setting the first username.
- BBS Username (SSH no auth only)
-
The username to send when Alt+L is entered.
- BBS Password (SSH no auth only)
-
The password to send on Alt+L.
- Username
-
The user name to send. Used by SSH, RLogin, and GHost. For other protocols, send when Alt+L is pressed.
- Password
-
The password to send.
- GHost Program (GHost)
-
The program name to send to the remote.
- System Password
-
An additional password that can be sent after the first Alt+L using successive Alt+Ls.
- Binmode Broken (Telnet, TelnetS, and WebSocket Telnet)
-
Telnet binary mode is broken on the remote system, do not enable it when connecting. This option is to work around a bug in CTRL-C checking in older Synchronet versions.
- Defer Negotiate (Telnet, TelnetS, and WebSocket Telnet)
-
Some systems have a mailer or other program running on the initial connection, and will either disconnect or just ignore telnet negotiations at the start of the session. When this option is enabled, SyncTERM will wait until it receives a telnet command from the remote before starting telnet negotiation.
- WebSocket Path and Query (WS and WSS Telnet)
-
Enter the absolute path, optionally followed by a query. An empty field selects the server root. The port stays in the Port field.
- Trust Web PKI (TelnetS and WSS Telnet)
-
Verify the server name and certificate using the operating system’s public CA roots. This is enabled by default. Enabling it clears the Trusted Certificate setting. If certificate verification fails, SyncTERM allows the presented chain to be inspected. Any certificate in that chain may be saved beside the SyncTERM configuration file and trusted for that connection only. Installed filenames are derived from the dialing-directory entry name; a numeric parenthesized suffix is added rather than replacing an existing file.
- Trusted Certificate (TelnetS and WSS Telnet)
-
Select a PEM certificate to trust only for this connection. It may be a CA certificate or the specific server certificate. The server name is also verified. Setting this disables Web-PKI trust; the two trust sources are not additive. Press Delete on this menu item to clear the path.
- TLS Client Certificate / TLS Client Key (TelnetS and WSS Telnet)
-
Select a PEM client certificate or chain and its matching unencrypted PEM private key. Both fields must be set together. A per-entry pair overrides the global pair; leave both empty to use the global client certificate. Press Delete on either menu item to clear that path.
- TLS PSK Identity / TLS PSK (Text) (TelnetS and WSS Telnet)
-
The identity and literal text shared secret for PSK authentication. SyncTERM does not decode the secret as hexadecimal or Base64; for example,
deadbeefis sent as eight ASCII bytes. Both fields must be set together. PSK mode is certificate-free, so the server trust and client-certificate settings do not apply to that connection. The secret is protected at rest only when dialing-directory encryption is enabled. - TLS PSK Version (TelnetS and WSS Telnet)
-
The exact TLS version used for PSK authentication. TLS 1.3 is the default. TLS 1.2 must be selected explicitly for a compatible server and should use a separately provisioned secret. SyncTERM does not retry the PSK using another TLS version. TLS 1.3 PSKs use SHA-256 as their provisioned hash. Both versions require an ephemeral PSK key exchange.
- Screen Mode
-
Selects the format of the window when connected. A mode specifies the number of columns, the number of rows, the aspect ratio, and the font size. Some modes such as the Commodore, Atari, Prestel, and BBC Micro modes will also change the selected font. If the current font is a mode-specific one (such as C64 or Atari), Changing from that mode to a standard one will change the font to Codepage 437 English. A few of the modes will result in different terminal emulation than the ANSI-BBS described in the CTerm documentation. These are:
- C64, C128 (40col), and C128 (80col)
-
These modes use PETSCII controls and do not support ANSI-BBS.
- Atari, Atari XEP80
-
These modes use ATASCII controls and do not support ANSI-BBS.
- Prestel, BBC Micro Mode 7
-
These modes use Videotex controls. There are subtle differences between them, but the most obvious differnces are the Prestel mode doesn’t scroll and Return will send # instead of a carriage return.
- Atari ST 40x25, Atari ST 80x25, and Atari ST 80x25 Mono
-
These modes use the Atari ST VT52 emulation and do not support ANSI-BBS.
Protocol syntax, control characters, keyboard bytes and compatibility limits are described in the emulation manuals.
For Custom, open Custom Screen Mode in the entry editor to set the columns, rows, font height and display aspect ratio for this BBS. The editor starts with the values from Program Settings. Save Mode stores all five values together. Use Program Settings makes the entry follow the program values again. Selecting another screen mode retains the saved geometry. New Connection Defaults can supply a saved mode for new entries. For RIPv3, this editor is available even when Custom is absent from the screen-mode choices. A saved mode with square pixels makes Custom available.
See Current Screen Mode and Custom Screen Mode for additional information.
- Terminal Type
-
Sets the value send by protocols that support sending this as a string. Currently, Telnet, RLogin, SSH, and Shell. When this value is empty (displays as "<Automatic>"), it is chosen based on the screen mode as one of
syncterm,PETSCII,ATASCII,Prestel,Beeb7, orAtariST+VT52. - Hide Status Line
-
Indicates that the "status line" at the bottom of the window when connected should not be displayed. This allows for an extra line of text from the remote to be shown.
- Download Path
-
The location to save downloaded files.
- Upload Path
-
The location to start at when browsing for files to upload.
- Log Configuration
-
This brings up a sub-menu to control a debug log. There are four options in this sub-menu:
- Log Filename
-
If this is not blank, specifies the file to write the log data to. When this is blank, disable logging.
- File Transfer Log Level
-
May be one of None, Alerts, Critical Errors, Errors, Warnings, Notices, Normal, or Debug.
- Protocol Log Level
-
Chosen from the same list as above. Controls connection diagnostics for all supported connection types, including native TLS-provider tracing for TelnetS and MQTT. Logs contain protocol, setup, lifecycle, and error metadata as appropriate, but not terminal traffic, credentials, phone numbers, shell commands, MQTT topics, or message payloads. The global default is Errors when neither the new ProtocolLogLevel nor legacy TelnetLogLevel setting is present.
- Append Log File
-
If set you Yes, the log file retains old information and will keep growing. If set to No, the log file is emptied for each new connection.
- Comm Rate (Modem, Serial, and 3-wire)
-
Specifies the speed to open the serial port at.
- Fake Comm Rate (network connections)
-
Specifies the character pacing display speed for network connections. This controls the simulated baud rate shown in the status line and the character output pacing.
- ANSI Music
-
There are three options in this sub-menu.
- ESC [ | only
-
With this setting, ANSI music is fully compliant with the standards (ECMA-48, ANSI, etc), but almost no software works with this.
- BANSI Style
-
Supports both the SyncTERM (CSI |) and BananaCom (CSI N) ANSI music styles. Support is still very rare, but slightly more common than the first.
- All ANSI Music Enabled
-
In addition to the previous two, also supports CSI M for ANSI music. This is by far the most common sequence used by software that supports ANSI music. Unfortunately, this prevents the ANSI Delete Line sequence from working correctly.
- Address Family
-
Selected IP address family for network connections.
- As per DNS
-
Connects only to the system resolver’s preferred address, which may be IPv4 or IPv6. This is the default; no other address is tried if it fails.
- IPv4 only
-
Connects only to the resolver’s preferred IPv4 address.
- IPv6 only
-
Connects only to the resolver’s preferred IPv6 address.
- Happy Eyeballs
-
Allows both IPv4 and IPv6. Starts with the resolver’s preferred family, alternates families, and staggers additional connection attempts by 250 ms while earlier attempts are pending. Uses the first successful connection and closes the others. Extra connections can allocate BBS nodes or activate serial bridges, so this mode must be selected explicitly.
- Font
-
Choses a font (and by implication, a codepage) for the connection. Custom fonts are also listed in this menu.
- Hide Popups
-
Do not show status and progress popups.
- RIP
-
Selects the version for Remote Imaging Protocol ("RIP"). RIP allows graphics and mouse usage, and was used by doors and BBSs starting in the early 90s. The RIP support in SyncTERM is not complete, and may not be compatible with other terminals. RIPv1 is the one most commonly used by old BBS software, and it requires that the Screen Mode be set to an EGA mode. RIPv3 is an updated version that is not backward compatible, but can be used in any mode.
- Force LCF Mode
-
This setting will force the DEC terminal "Last Column Flag" mode to always be enabled. This mode is almost always used in modern terminal emulators, which are almost all VT-102 emulators at least. LCF controls the wrapping behaviour when the cursor is on the last column of a line. The specific rules used are complex and not implemented the same in all terminal emulators even today.
- Yellow is Yellow
-
By default, SyncTERM displays low-intensity yellow as brown. This originated in the IBM CGA monitors, and was carried forward to EGA and even most VGA modes. Some digital monitors that were CGA compatible did not have the brown hack. While the vast majority of software will assume that low-intensity yellow should be brown, this allows strict standard compliance.
- SFTP Public Key
-
For SSH connections, SyncTERM can open another SSH channel and write the public key to .ssh/authorized_keys on the remote, which will enable authentication using the private key on at least OpenSSH and new versions of Synchronet. This option requires SFTP support from the remote side, and may cause connection stability issues if SFTP is not available or does not work correctly.
- Edit Palette
-
This opens a menu allowing you to cusomize the palette for the entry. If the default palette has fewer than 16 colours, you can add additional palette entries. When you select a colour, you can enter the red, green, and blue values separately, and the resulting colour is shown when possible.
If there are fewer than sixteen entries in the list, the list will be repeated to fill all 16 palette slots. This allows for example, the use 16 colour Amiga VT-52 mode.
Managing Sort Profiles
SyncTERM supports named sort profiles that control the order entries appear in the Directory. Press < or > in the directory listing to cycle through profiles. The current profile name is shown in the title bar.
Four default profiles are provided: Name, Last Connected, Most Called, and Date Added. You can manage profiles by pressing Ctrl+S to open the Sort Profiles manager.
In the Sort Profiles manager:
- Enter
-
Edit the sort fields for the selected profile. In the sort field editor, press Insert to add a field, Delete to remove one, and Enter to toggle between normal and reversed order.
- F2
-
Rename the selected profile (max 19 characters, must be unique). Names use printable US-ASCII, cannot begin or end with whitespace, cannot contain
=or:, and cannot begin with;or[. - Insert
-
Create a new profile.
- Delete
-
Delete the selected profile. Deleting the last profile reloads the defaults.
- F5 / Ctrl+Insert
-
Copy a profile to the clipboard.
- Shift+Delete
-
Cut a profile (remove and place on clipboard).
- F6 / Shift+Insert
-
Paste the clipboard at the current position. If the name already exists, you will be prompted for a new unique name.
Sort profiles are stored in the [SortProfiles] section of the
SyncTERM INI file.
The Explicit Sort Value exists to manually control the position of entries in the list, and can be accessed using Ctrl+S in the Edit Directory Entry menu.
Viewing the Scrollback
After a remote disconnect, Alt+B (Cmd+B on macOS) opens the completed session’s scrollback from the Disconnected notice. Escape returns to that notice; Enter leaves it and F1 opens session details. When the connection had a status bar, its row stays blank and red while viewing scrollback. With the status bar disabled, scrollback uses the full terminal height, including the bottom row. Without a status bar, the terminal scrolls once to make room for the notice. Opening scrollback restores the screen from before that scroll, apart from the scrollback indicators. The notice is local UI rather than saved terminal output, and terminal dimensions are preserved. Hide Popups omits the notice.
If a BBS changes video modes, each saved line keeps its original width. For example, switching an Atari ST session from 80 to 40 columns saves the outgoing terminal page. Use the left and right arrows to reach the rest of a wider line. Bitmap displays retain the original font dimensions and graphics. The same controls work after disconnecting.
Drag to copy text in reading order. Hold Alt while starting a drag to copy a rectangle. In mixed-width history, holding the pointer at an edge scrolls the view while the start of the selection stays anchored.
When viewing the scrollback, the following keys are supported:
- ↑
-
Move up one line
- J
-
Move up one line
- ↓
-
Move down on line
- K
-
Move down one line
- Page Up
-
Move up one screen
- H
-
Move up one screen
- Page Down
-
Move down on screen
- L
-
Move down one screen
- Escape
-
Exit scrollback mode
SyncTERM Settings
The SyncTERM Settings menu has the following options:
- Web Lists
-
Add web lists which SyncTERM will synchronize with an http:// or https:// URI at each program startup. Web lists are added as system lists, which means credentials and paths will come from the Default Connection Settings, and they will be copied into your personal list if you use or modify them. Note that the web client will only do GET requests, and only supports status codes of 200 (OK) and 304 (Not Modified). Specifically, it does not support any redirection. Web-list names use printable US-ASCII, cannot begin or end with whitespace, cannot contain
=or:, and cannot begin with;or[. - Default Connection Settings
-
Set the default values for a new directory entry. See Edit Directory Entry for details on these options.
- Current Screen Mode
-
Changes the current screen mode. For directory entries where the screen mode is "Current", will be used during the connection. This setting is not saved across program restarts. To change the startup screen mode, see SyncTERM Settings → Program Settings → Startup Screen Mode.
- Font Management
-
Allows setting up custom font files.
- Program Settings
-
Allows changing settings that are preserved across reboots. Refer to the Program Settings section for details.
- Themes
-
Lists the built-in Classic Theme and
.initheme files from the user theme directory. Moving the highlight previews a valid theme. Enter selects and saves it; Escape restores the previously selected theme. Invalid files may be highlighted to display their error but cannot be selected. SeeThemes.adocfor the file format. - File Locations
-
Shows the paths to the various files and directories that SyncTERM will access. The Global RIP Directory is a read-only fallback for RIPv3 files. Place shared assets there to make them available across BBSes. RIPv3 commands can write and delete files in the connected BBS’s RIP cache.
- Build Options
-
Shows which components SyncTERM was built to support, including the compiled console and audio backends. The Fonts section lists Unifont (SyncTERM Unicode), UNSCII, Noto Emoji, and Noto Color Emoji. Unifont is optional; the other fonts are always included. Font license details are available under Licenses. A checked component may still require a runtime library, display server, or audio device.
The build also supplies a loadable libretro core. On Windows, syncterm.dll
is both that core and the application library used by the thin syncterm.com
console and syncterm.exe graphical launchers. Keep all three files together.
On Unix, the ordinary executable is accompanied by syncterm_libretro.so
(syncterm_libretro.dylib on macOS).
The core can start without content or open a .lst BBS list. When the frontend
provides a save directory, SyncTERM keeps its configuration, lists, scripts,
keys, downloads, and cache under a syncterm subdirectory there. Keyboard,
mouse/pointer input, video, and stereo audio use the frontend. Unloading joins
the application worker and closes connections without exiting the frontend.
- Licenses
-
Displays bundled software and font copyright notices and full license texts. Select a component, then use the arrows, Page Up/Down, Home, or End to read its notice. Escape returns to the component list. The notices are embedded in the executable and are available offline, including in safe mode and from the connected settings menu.
- List Encryption
-
Allows you to encrypt or decrypt the BBS list. Choose the encryption type you want or change the password, etc.
Current Screen Mode
This temporarily sets the screen mode. A screen mode defines the number of rows and columns in the window, which font size to use (8x8, 8x14, or 8x16), and the aspect ratio to scale pixels to. The majority of these modes are based on historical analog hardware modes, so most of them do not use square pixels. The main exceptions are LCD80x25, which is an 80x25 mode that uses square pixels and the 8x16 font, and VGA80x25, which is an 80x25 mode that uses square pixels, the 8x16 font, and performs the VGA column expansion to use 9 pixel wide cells. For further details, see Text Modes in the console-library chapter.
Font Management
The Font Management menu allows you to add and remove fonts. Each font has a unique, printable US-ASCII name and at least one file for 8x8, 8x14, 8x16, or 12x20 fonts. The font format is the one used by "DOS fonts". You can insert and delete items using the normal menu commands.
Program Settings
- Controller Mapping
-
The action pad is the four-button diamond. Action pad south is its lowest button. Select a BBS input and press the physical button you want to use. Its name appears beside the BBS input. To start with a physical control, choose Press a control to assign, move it, and pick what it should send. Browse physical controls lets you select it by name. To map a directional hat, select D-pad up and push up, then repeat for the other directions. Diagonals press both mapped buttons. For an analog trigger, select its axis row. For a digital trigger, select its button row. Select an assigned input to preview it, replace or clear it, or invert an axis. F1 opens help. Assignments are saved as you make them, except in safe mode, where they apply only in memory.
- Confirm Program Exit
-
Asks if you are sure you want to quit when pressing ESC or right-clicking in the main SyncTERM screen.
- Prompt To Save
-
If enabled, when SyncTERM is started with a URI that is not in a dialing directory, asks if you want to add the entry to the directory.
- Startup Screen Mode
-
The screen mode that is used when SyncTERM starts.
- Video Output Mode
-
The method of displaying SyncTERM output. The options will vary by OS, compile-time options, and installed libraries. See the -I option to SyncTERM for details on the various modes.
- Default Cursor Style
-
The cursor style used by default. Options are "Default (set by video mode)", "Blinking Underline", "Solid Underline", "Blinking Block", and "Solid Block". The remote system may override this using DECSCUSR.
- Audio Output Mode
-
Allows disabling different output methods. SyncTERM attempts to use them in the order listed in the menu, and the first one to succeed is used going forward.
- MIDI
-
Enables or disables each compiled MIDI method independently of PCM output. There are no SyncTERM routing, instrument or SoundFont settings. On POSIX, ALSA uses ALSA_OUTPUT_PORTS (comma-separated destinations) and is skipped when it is unset. macOS uses its built-in DLS synth; Windows uses the normal MIDI mapper. FluidSynth reads the user’s FluidSynth configuration, then its default bank if no bank was loaded. libADLMIDI uses its embedded bank. ANSI music automatically uses the first usable enabled method, falling back to classic tones. Quiet mode suppresses both MIDI and PCM. Build Options has a separate MIDI section reporting compiled methods and their linkage.
- Scrollback Buffer Lines
-
The maximum number of lines to keep in the scrollback. Once this number is reached, the oldest lines are removed to make room for new lines.
- Modem/Comm Device
-
The device name for the Modem device. For UNIX-like systems, this will be something like "/dev/ttyd0". For Windows, this will be "COM1" to "COM9". If it’s COM10 or higher, it needs to be specified as "\\.\COM10".
- Modem/Comm Rate
-
Specifies the speed to communicate with the modem at. If set to 0, the speed is not set by SyncTERM, and the default is used.
- Modem Init String
-
The string to send to the modem when the device is first opened to prepare it to be used.
- Modem Dial String
-
A string that is sent immediately before the phone number to cause the modem to dial.
- List Path
-
The path to load the personal dialing directory from.
- TERM For Shell
-
The value that the TERM variable is set to for shell type connections.
- TLS Client Certificate / TLS Client Key
-
Select the default PEM client certificate or chain and matching unencrypted PEM private key presented by TelnetS connections. Both fields must be set together. An entry with its own client-certificate pair overrides these global values. Press Delete on either menu item to clear that path.
- Scaling
-
Blocky scales pixels to rectangles. Pointy uses 45° angles. External uses the window backend’s scaler. OpenGL uploads the terminal bitmap at its native resolution and scales it to the window using the selected OpenGL scaler.
- OpenGL scaler
-
Choose SyncTERM Blocky, Pointy, Nearest, or browse for a RetroArch Slang preset (
.slangp). Install each pack in a folder under the SyncTERM data directory’sscalers/directory (normally~/.local/share/syncterm/scalers/on XDG systems). Preserve directory names and relative paths. For example, CRT Royale usescrt/crt-royale.slangp, masks and pass sources incrt/shaders/crt-royale/, blur passes inblurs/shaders/royale/, and headers ininclude/. Select the preset in Program Settings after choosing OpenGL. Custom presets require librashader. If a saved preset cannot load at startup, SyncTERM keeps the preference and uses its built-in scaler. - Invert Mouse Wheel
-
Toggles the direction the mouse wheel moves.
- Key Derivation Iterations
-
This specifies the number of iterations to derive a key from a password. The higher this value, the more difficult brute forcing is, but the longer it takes to read the BBS list.
- Classic Theme Colours
-
Allows changing the six colours used by the built-in Classic Theme. These settings apply to the menu, file picker, and connected Wren interfaces while Classic Theme is selected. File themes do not inherit these colour settings.
- Custom Screen Mode
-
Allows defining the Rows, Columns, Font Size, and Aspect Ratio of the "Custom" screen mode for the directory display and for BBS entries that use Program Settings.
Connected State
When you are connected to a system, there are a number of controls available that are not sent to the remote.
Hyperlinks
SyncTERM supports OSC 8 hyperlinks. When a BBS sends text with an embedded hyperlink, clicking on the linked text will open the URL in your default browser. When the BBS has mouse capture enabled, use Ctrl+Click instead. Hovering over a hyperlinked region displays the URL in the status bar.
Even without OSC 8 markup, Ctrl+Click on plain-text URLs
(starting with http://, https://, ftp://, ftps://, or
www.) will detect and open the URL directly. This also works
in the scrollback viewer.
In an RIPv3 session, clicking a field or activating its hotkey can also open a link. If the BBS requests a URL directly or on hover, SyncTERM shows the destination and asks before opening it. Cancel is selected by default. In safe mode or for an unsupported scheme, the dialog offers to copy the URL.
On platforms where opening a browser is not possible, the URL is copied to the clipboard instead.
Selecting and Copying Text
Left-drag across the terminal to select a region. The copy is made
when the button is released. By default the selection is stream-
shaped: it flows from the starting cell to the ending cell across
line wraps, trailing spaces are trimmed on each row, and rows are
separated by \r\n on Windows or \n on other platforms.
Hold Alt when you press the left mouse button to select a rectangular region instead. The Alt state is sampled once, at the start of the drag, and held for the duration of the drag; pressing or releasing Alt mid-drag does not change the selection shape. Each row of the rectangle is copied as its own line, with trailing spaces trimmed.
If the remote system has mouse capture enabled, use Alt+O to take the mouse back from the remote so that you can select text.
In the DOS Shell and DOS door terminals, the guest starts with mouse control. Press Alt+O (Cmd+O on macOS) to take the mouse back and drag to copy from a DOS text screen. Press the shortcut again to return it to DOS.
Press Alt+B (Cmd+B on macOS) to view scrollback for the current DOS run. Use the arrow keys or mouse wheel to scroll by line, PgUp and PgDn by page, and Home and End to jump to either end. Drag to copy and press Esc to return. The guest and its connection continue running while you read. The Scrollback Buffer Lines setting limits how many rows each DOS run keeps after they scroll off the screen. Copy supports the extended characters in code pages 437, 850, 865, 1131, and 1251. Other code pages use the Unicode replacement character for bytes above ASCII.
For Curses and ANSI modes, only two controls are avilable, and they are not available in other modes. This is because these two modes don’t have access to keys that could not potentially be sent to the remote. To help avoid conflict with remote systems, the XON (Ctrl+Q) and XOFF (Ctrl+S) codes that are used for software flow control are used.
- Ctrl+Q
-
Disconnects from the current session.
- Ctrl+S
-
Brings up the Online Menu (see below)
For all other modes, the ALT key is used for SyncTERM commands, and the following combinations are supported:
- Shift+Insert
-
Pastes the current PRIMARY selection or clipboard contents to the remote.
- Alt+B
-
View scrollback (See "Viewing The Scrollback")
- Alt+C
-
Capture Control. Allows starting and stopping capturing the session to a file. Useful for stealing ANSIs and debugging emulation issues.
- Alt+D
-
Begins a download from the remote system.
- Alt+E
-
Brings up the Dialing Directory
- Alt+F
-
Allows selecting a different font. In some output modes, the selected font will change text that is already on the screen. In most modes however, only newly displayed text will be in the new font.
- Alt+F5
-
Requests a screen refresh on an RIPv3 connection when the BBS has provided a refresh expression. The action is inactive while a scene header has locked input.
- Alt+H
-
Hangup and return to the main menu.
- Alt+L
-
Send auto-login information. For protocols that allow auto- login, only the system password is sent. For all others, the username is sent followed by a carriage return, then the password followed by a CR, then the system password followed by the CR. If any of these are not configured for the current entry, neither them, nor the CR are sent for that item.
- Alt+M
-
Changes the currently supported "ANSI" Music prefix.
- Alt+O
-
Toggles remote mouse support. With the remote capturing mouse events, it can be difficult to select text to copy. Alt+O allows taking the mouse away from the remote.
- Alt+U
-
Upload a file (or files) to the remote. Prompts first for a protocol, then for the file(s) to send.
ZMODEMandYMODEMeach offer aBatchvariant that brings up the multi-file picker so you can queue files from several directories and transfer them in a single session. The other choices (XMODEM-1K,XMODEM-128,ASCII,Raw) transfer a single file. - Alt+X
-
Disconnect and exit SyncTERM. Does not return to the main menu.
- Alt+Z
-
Brings up the Online Menu (see below)
- Alt+↑
-
Selects the next fastest character pacing speed. If the fastest speed is currently selected, disables character pacing. If pacing is currently disabled, selects the slowest pacing speed.
- Alt+↓
-
Selects the next slowest character pacing speed. If the slowest speed is currently selected, disables character pacing. If pacing is currently disabled, selects the fastest pacing speed.
Online Menu
Allows menu-based selection of some of the above options, as well as some less-common operations that don’t have a keyboard shortcut.
- Scrollback
-
Same as Alt+B
- Insert Emoji…
-
Opens the emoji picker on UTF-8 connections. Same as Alt+P.
- Disconnect
-
Same as Alt+H
- Send Login
-
Same as Alt+L
- Upload
-
Same as Alt+U
- Download
-
Same as Alt+D
- Change Output Rate
-
Allows selecting a specific character pacing to use.
- Change Log Level
-
Temporarily changes the file transfer log level
- Capture Control
-
Same as Alt+C
- ANSI Music Control
-
Same as Alt+M
- Wren Console
-
Opens the Wren console. In ANSI and Curses modes, both Ctrl+Q and Ctrl+S close the console and return to the connected session.
- Font Setup
-
Same as Alt+F
- Toggle Doorway Mode
-
Turns on or off Doorway mode without the host specifying it. Can be used to recover from broken remote software.
- Toggle Remote Mouse
-
Same as Alt+O
- Enable Thieves' Guild / Disable Thieves' Guild
-
Available in the three Atari ST screen modes. Enable it before entering the Thieves' Guild door. When the door prints "Reading the Scrolls…", SyncTERM identifies itself, shows the animated Atari title and plays its two startup sounds while the door loads. The next output from the door restores the text screen automatically. During play, SyncTERM uses the built-in artwork, sounds and local menus. Press Return when the door asks. Leaving a graphical scene restores the previous text screen. The option starts disabled on each connection.
- Toggle Operation Overkill ][ Mode
-
Cycles through off, OOTerm, OOTerm1, and OOTerm2 modes. Can be used to recover from broken remote software.
- Exit
-
Same as Alt+X
- Edit Dialing Directory
-
Same as Alt+E
Techical Details
The following sections delve deeper into technical details, and should not be required for normal use.
Persistant State
SyncTERM will preserve a very small amount of state when exited normally and restore it when the program is restarted. At present, this state is limited to the scaling factor applied to the window. The scaling factor is a floating-point value that indicates the largest value which both the width and height can be multiplied by and still fit inside the current window size. If you manually resize the window only making it wider for example, the additional width will not be saved as the height will control the size the next time SyncTERM is started.
This state is only saved under two specific circumstances. Either the current text mode at exit is the same as the configured Startup Screen Mode, or the Startup Screen Mode is "Current" and the current text mode is "80x25". In all other cases (such as after the Current Screen Mode is changed), it will not be saved. Also, it’s only saved when the program exits normally. In the case of a crash, the setting will not be updated.
Installing Terminfo Entry
When using *nix software through SyncTERM either locally via the shell protocol, or remotely via SSH or as a door on a BBS, it helps immensely if the remote has a terminfo entry for SyncTERM installed. To install the terminfo entry, follow the following steps:
-
Write the terminfo entry to a file
syncterm -T > syncterm.terminfo -
Compile the entry and install it
tic -sx syncterm.terminfo
By default, it is only installed for the current user.
Once the terminfo entries are installed, you can use them by setting the
TERM environment variable to syncterm. In Bourne shells, this is
usually accomplished with the command export TERM=syncterm.
MBBS GHost
"GHost" in SyncTERM refers to the "Galacticomm Host Program" (called Ghost) that was included in Major BBS and Worldgroup (MBBS/WG) that allowed a Sysop to connect another (DOS-based) PC to the BBS by use of a null modem cable. This was a way for a MBBS/WG Sysop to offer DOS doors, something that wasn’t normally possible.
The functions of the Ghost software itself are beyond the scope of SyncTERM, and you should consult the MBBS/WG Ghost documentation for operation details. However, broadly speaking, it worked like this:
1) MBBS/WG would send a signal down the null modem cable to alert the DOS PC (running Ghost) that it wanted to run a door. 2) Using a simple protocol, MBBS/WG would transmit information required to run the door (username, time remaining, whether ANSI-BBS graphics were supported, etc) to Ghost. 3) Ghost would then launch the door in DOS, using a batch file to call Ghost back once the door exited to wait for the next request.
While few people are connecting DOS-based PC’s to anything by null modem cables anymore, the Ghost protocol (as offered in SyncTERM) is still useful because it’s a way to run DOS doors inside a virtual machine and expose them outside of that virtual machine. The idea being that the VM would configure a serial port as some kind of network passthrough, so when SyncTERM connects, it’s passed through to the VM and then Ghost.
One use case for this is to offer DOS doors in environments where it would normally be difficult or impossible. For example, a UNIX user could run SyncTERM on a remote system in curses mode, where it would then connect to a VM and launch a DOS door via Ghost. This would all be presented to the end UNIX user in a seamless way, so all they would see is the door startup.
The Ghost protocol consists of a single line starting with 'MBBS:', terminated with \r\n, and contains five parameters:
MBBS: PROGRAM PROTOCOL 'USER' TIME GR
You don’t need to worry about sending this since SyncTERM will format it for you based on the SyncTERM configuration options. But it is helpful to understand how various SyncTERM options will translate to the Ghost protocol parameters:
PROGRAM: The name of the DOS door/software to ask the Ghost side to run. Configured in SyncTERM in the 'GHost Program' field of a directory entry, or after the final slash in a ghost:// style URL. For example: ghost://user@203.0.113.64/program
PROTOCOL: Always set to 2. Not configurable in SyncTERM.
USER: Username of the person connecting. Configured in SyncTERM in the 'username' field of a directory entry, or before the '@' in a ghost:// style URL. For example: ghost://user@203.0.113.64/program
TIME: Amount of time the user has remaining. Always set to 999. Not configurable in SyncTERM.
GR: Set to GR (for "GRaphics", meaning ANSI-BBS support) or NG (for "No Graphics"). Always set to GR. Not configurable in SyncTERM.
SyncTERM Wren Scripting Manual
SyncTERM embeds Wren in three isolated scripting hosts. A persistent trusted VM owns the main menu, a second persistent VM owns the file picker, and every connection gets a fresh restricted VM which is torn down at disconnect. Connected scripts hook into keyboard, mouse, inbound bytes, outbound bytes, status text, and a periodic timer; menu scripts implement the dialing directory and settings UI; and picker scripts implement the local-file consent interface. Each host exposes a different set of capabilities.
This document is the reference for that scripting layer: how scripts are discovered, how the embedded scripts can be overridden, and the complete add-on object model.
Why Wren
Wren is a small, class-based, dynamically typed scripting language. Three properties make it a good fit for SyncTERM:
-
It compiles to bytecode in-process; no separate toolchain or external interpreter is required.
-
The VM is a few thousand lines of plain C with no external dependencies, vendored under
wren_vm/. -
The host program controls every binding the script can reach. No filesystem, networking, or process primitives leak in by default.
The full upstream language reference lives at https://wren.io/. This manual covers only the SyncTERM additions.
Quick Start
The minimal "hello world" hook prints a message to the SyncTERM Wren console the first time you press F1 while connected:
import "syncterm" for Hook, Key
Hook.onKey { |k|
if (k == Key.f1) {
System.print("hello from wren!")
return true // consume the keystroke
}
return false // pass through to SyncTERM
}
Save this as hello.wren in the SyncTERM scripts directory (see
Script Loading), connect to any BBS, and press F1. In a graphical
or native-console backend, open the console with Ctrl+`. In ANSI or
ncurses mode, press Ctrl+S and choose Wren Console from the Online Menu.
Wren Language Reference
A compact reference for the Wren syntax SyncTERM scripts use. Full
upstream documentation at https://wren.io/. Key facts up front:
Wren is single-threaded and cooperative (concurrency via fibers, no
threads); whitespace-significant (newline terminates statements; no
; token); class-based with single inheritance; dynamically typed.
Comments
// Line comment.
/* Block comment, /* nested */ blocks ok. */
Literals
|
Booleans. |
|
The single null value. |
|
Numbers. All numeric values are 64-bit floats; |
|
String literal. Escapes: |
|
String interpolation: |
|
List literal. |
|
Map literal. |
|
Closed Range (1, 2, 3, 4, 5 — includes 5). |
|
Half-open Range (1, 2, 3, 4 — excludes 5). |
Statement Termination
Newlines separate statements. There is no ; token at all. Two
statements on one line is a compile error. This trips up developers
coming from C / JS / Python regularly.
var x = 1 // ok
var x = 1 ; var y = 2 // ERROR: Invalid character ';'
Two consequences of the same rule:
-
Ternaries can’t span lines.
cond ? a : bmust be on one line — the then-branch terminates at a newline before the:. -
elseafter a newline-endedifbody is a syntax error.if (c) bodywhose body sits on the same line as theifends at the newline; anelseon the next line is orphaned. Either brace each branch (soelsefollows}) or put the whole chain on one line.
if (a == "x") foo() else bar() // single-line, ok
if (a == "x") { // braced, ok
foo()
} else {
bar()
}
if (a == "x") foo() // ERROR: 'else' is orphaned
else bar()
Strings and %
The Wren lexer treats % inside a "…" string as the start of an
interpolation %(expr). A % not followed by ( is a lex error —
not a literal %. To put a literal percent sign in a string, escape
it as \%:
"100%" // ERROR: Expect '(' after '%'.
"100\%" // ok — four bytes: 1, 0, 0, %
"got %(x)" // ok — interpolation, inserts x.toString
Every literal % needs a leading \. The pair \% is its own
escape — \\% does not work, because \\ consumes the slash on
its own and leaves a bare %; spell that as \\\%.
Variables
var x = 1 // declare and initialize
x = 2 // reassign
Block-scoped (everything between { and }). Shadowing in inner
scopes is allowed. Top-level var at module scope is a module-level
binding (importable from other modules). Declaration is required
before use; there is no auto-vivification.
Operators
Arithmetic: + - * / % (modulo follows the dividend’s sign), unary
- and +. Comparison: < ⇐ > >= == !=. Logical: && || ! —
short-circuit, return one of their operands (not coerced to Bool).
Bitwise: & | ^ << >> ~ — operate on integers (Wren truncates to
32-bit for the bitwise op). Range: .. and .... Conditional:
cond ? a : b (one line). Type test: obj is Class.
The .. / ... operators bind tighter than method calls, so write
(0...list.count) not 0...list.count when chaining.
Control Flow
if (cond) {
...
} else if (cond2) {
...
} else {
...
}
while (cond) {
...
}
for (item in iterable) {
...
}
break // exit innermost loop
continue // next iteration
return v // return from method/function
for (x in seq) {} works on anything implementing iterate(prev)
and iteratorValue(iter) — Lists, Maps (yields MapEntry objects), Strings
(yields codepoint substrings), Ranges, and your own classes.
Functions and Closures
Wren has no top-level function keyword. Functions are closures
created with Fn.new:
var add = Fn.new {|a, b| a + b }
var n = add.call(3, 4) // 7
var greet = Fn.new {
System.print("hi")
}
greet.call()
Block syntax { … } after a method name passes a closure as the
last argument:
list.map {|x| x * 2 } // map(_) takes a Fn
Single-line { expr } returns expr implicitly; multi-line bodies
return null unless an explicit return is hit. This applies
uniformly to Fn.new, Fiber.new, getters, methods, and operator
overloads. The inverse is also true: { return expr } on a single
line is a compile error — single-line bodies are expression-mode,
and return is a statement.
foo() { 42 } // ok — implicit return
foo() { // multi-line — last expression NOT returned
var x = 1
x + 1 // discarded; foo() returns null
}
foo() { // ok — explicit return
var x = 1
return x + 1
}
foo() { return 42 } // ERROR: single-line, return not allowed
Classes
Single inheritance, no abstract classes, no interfaces. All fields are private to the declaring class (see "Field scope" below).
class Animal {
construct new(name) {
_name = name
}
name { _name } // getter
name=(s) { _name = s } // setter
speak() { // method
System.print("%(_name) makes a sound")
}
static kingdom { "Animalia" } // static getter
static spawn(n) { Animal.new(n) } // static method
// Operators: + - * / % - (prefix) ! < > <= >= == [_] [_]=(_)
+(other) { _name + other.name }
}
class Dog is Animal {
construct new(name, breed) {
super(name) // call super constructor
_breed = breed
}
speak() { // override
System.print("%(name) barks")
}
describe() {
super.speak() // call super method
System.print("It's a %(_breed)")
}
}
Field scope
Field references (_name, __static) resolve against the class
currently being compiled, not the inheritance chain. A subclass'
_x is a brand-new slot, not the parent’s _x. Cross class
boundaries via getters/setters:
class Widget {
construct new() { _surface = null }
surface { _surface } // expose to subclasses
}
class Pane is Widget {
paint() {
var s = surface // ok — uses getter
var t = _surface // BUG: brand-new field, null
}
}
Symptom of getting it wrong: Null does not implement 'X(,)'
errors from subclass methods reading "the parent’s" field.
Naming
-
_name— instance field. Only legal inside a class body; the parser rejects it elsewhere. -
__name— static field. Same scoping rule. -
name_(trailing underscore) — convention for "class-private" methods. Not enforced by the language; a strong project hint.
Foreign methods and classes
foreign declarations bind to host C code:
class Codepage {
foreign static encodes_(s) // host-implemented static
foreign instance_method(arg) // host-implemented instance
}
foreign class Cell { // host owns instance allocation
foreign ch
foreign ch=(s)
}
A class needs foreign class only when the host allocates instance
data; a plain class with foreign static methods is fine for
namespace-style bindings (see Codepage, Hook).
Type checks
obj is Class returns true if Class is in the object’s class
chain. Compiles to obj.is(Class). You can override is, but
you cannot delegate to the default via super.is(c) — is is a
reserved keyword and super. requires an identifier after it.
Override only if the foreign genuinely implements every method of
the claimed class.
Fibers
Fibers are first-class coroutines. Wren is single-threaded and
cooperative; concurrency comes from yielding fibers, not threads.
There is no await, no Promise, no scheduler — the fiber handle IS
the resumption token.
var f = Fiber.new {
System.print("a")
Fiber.yield() // suspend; control returns to .call() caller
System.print("b")
}
f.call() // prints "a", returns when fiber yields
f.call() // prints "b", fiber finishes
// .yield(v) returns v from the .call() that resumed the fiber:
var g = Fiber.new {
while (true) {
var x = Fiber.yield(42) // yield 42, get next call's arg as x
System.print(x)
}
}
g.call() // returns 42
g.call("hi") // prints "hi", returns 42
g.call("yo") // prints "yo", returns 42
// .try() catches abort:
var h = Fiber.new { Fiber.abort("boom") }
var err = h.try() // err == "boom"; h.error == "boom"
Fiber.yield(v) transfers to the immediate .call() caller — a
child fiber yielding inside a hook body returns control to the hook
body, NOT up to the dispatcher. This is what makes
Fiber.new { … }.call() from inside a hook safe.
For host-driven async: a foreign method captures Fiber.current
from a slot and returns; the host arranges to call .call(_) on
the captured handle later. See Modal Input for the
canonical example.
Modules and Imports
import "module" // load module, no symbols imported
import "module" for Name // import a single symbol
import "module" for A, B, C // multiple
import "module" for Name as Alias // rename on import
Module names are strings; the host resolves them. In SyncTERM, modules are
looked up first in the root user script directory, then in the active event’s
user script directory, and finally in the matching embedded scripts. A user
file myhelper.wren in the script directory is importable as
import "myhelper" and overrides an embedded module with the same name.
Common Pitfalls
A checklist of mistakes that catch every new Wren author at least once. Most are consequences of rules above; this section gives them a single place to look up.
-
Semicolons. Wren has no
;. Every separator is a newline. -
Multi-line bodies don’t auto-return. Use explicit
return. -
Single-line
{ return x }is a syntax error. Dropreturn. -
Ternaries on one line only. Split via
if/elseor pre-compute. -
elsemust follow}on the same line, or chain on one line. -
Every literal
%in a string needs\%. Bare%starts interpolation. See Strings and%. -
Subclass
_fieldis NOT the parent’s. Use getters/setters. -
String.countis codepoints;s[i]ands[a...b]are bytes. Mixing them silently truncates UTF-8 strings. For byte iteration uses.bytes.count. -
String
<>⇐>=are not defined.list.sort()on strings aborts; pass an explicit byte-wise comparator. -
Wren modulo follows the dividend’s sign.
-1 % 5is-1, not4. For positive-modulo, write((x % n) + n) % n. -
foreign classis for instance allocation only. Use plainclasswithforeign staticfor namespace bindings. -
No
async/await/ scheduler. Use fibers andFiber.yield.
Wren Standard Library
The built-in classes Wren provides without any host bindings. These
are always available, no import needed. Many are mixin-aware via
the Sequence protocol, so iteration and transformation methods
work on Lists, Maps, Ranges, Strings, and your own classes that
implement iterate / iteratorValue.
System
Static-only namespace for I/O and timing.
|
Print a blank line. |
|
Print |
|
Print each item in |
|
Print |
|
Like |
|
Process CPU time reported by C |
|
Note
|
In SyncTERM, System.print / System.write are routed to the
Wren console log buffer (visible via the Wren Console pane), not to
the process’s stdout. Use Host.print(s) when you need
output to reach the launching shell. Compile errors, reported runtime errors and
stack traces go to both the Wren console and the process’s stderr.
|
Object
Root of every class hierarchy. Every value responds to:
|
Identity by default; classes can override. |
|
Negation of |
|
Hash code, integer. |
|
Type check; same as |
|
Default returns |
|
Returns the object’s class. |
|
Boolean negation. Falsy values are |
Class
The class of all classes. Useful properties:
|
String name of the class. |
|
Parent class, or |
|
The class name. |
Bool
true and false. Has toString (returns "true" / "false")
and the standard ! && || operators (the latter two short-
circuit and return one of the operands, not a coerced Bool).
Null
The single value null. !null is true; everything else
(null.toString, null == null) does what you’d expect.
Num
All numeric values are 64-bit floats. No separate integer type; the language calls something an "integer" when it has no fractional part. Mathematical method-style helpers:
|
π. |
|
+∞. |
|
Max / min finite double. |
|
Range of exact-integer doubles (±2⁵³−1). |
|
Absolute value. |
|
Round-modes. |
|
Square root. |
|
Trig (radians). |
|
Inverse trig. |
|
atan2(self, x). |
|
Natural log, log base 2, eˣ. |
|
nᵖ. |
|
Pairwise min / max. |
|
Clamp into |
|
Fractional part. |
|
-1 / 0 / +1. |
|
Predicates. |
|
Decimal string. |
|
Bitwise (truncated to 32-bit). |
|
Bit shifts (also 32-bit). |
Native integer limits
Native integer quantities exposed as Numbers use the inclusive exact range
Num.minSafeInteger through Num.maxSafeInteger
(−9,007,199,254,740,991 through 9,007,199,254,740,991). Unsigned quantities,
including file sizes, byte counts and offsets, start at zero. Fractions,
NaN, infinity and values outside the range abort before native work starts;
representable values above this range, including 2^53 itself, are rejected.
Counts must also fit the host’s size_t, and narrower protocol or API limits
still apply. SFTP v3 read counts and set-mtime values are bounded by
4,294,967,295. An offset may exceed 32 bits even on a 32-bit host.
Formatting helpers such as Format.bytes deliberately accept estimates and
retain their documented rounding/saturation rules.
Native results are checked before conversion. File.size, File.offset
and File.mtime return FileError with IOErr.outOfRange and errno zero
when the native result cannot be represented. SFTP stat/directory operations
complete with a non-transient SFTPError (IO_ERROR_OUT_OF_RANGE) if any
size or timestamp is outside the range; they never return rounded or partial
metadata. Other integer getters, including profile timestamps, picker
metadata, transfer byte counts and log sequence numbers, abort on overflow.
Continuous measurements such as elapsed fractional seconds remain Numbers.
The persistent transfer queue applies the same bounds to saved sizes, resume offsets, timestamps and IDs. It preserves an invalid queue for inspection and refuses to run it. Job IDs reserve the largest safe integer as the exhausted next-ID value, preventing rounded or reused IDs.
String
Immutable byte string with UTF-8-aware operations. Strings can contain
malformed UTF-8 and embedded NULs. For well-formed UTF-8, s.count counts
Unicode scalars, while s[i], ranges, and s.codePoints[i] use byte offsets.
Use s.bytes for bytes and s.codePoints.toList or s.toList for scalar-ordinal
indexing. Unicode scalars are not grapheme clusters; Text.graphemes supplies
that separate operation.
|
Scalar count for valid UTF-8; does not validate the string. |
|
True iff |
|
A |
|
A |
|
Codepoint substring starting at byte index |
|
Visit byte offsets in the range, expanding complete scalars at lead bytes. Negative indices count from the end. |
|
Concatenation. |
|
Byte index of first match, or |
|
Byte index of match at-or-after |
|
Substring presence. |
|
Prefix check. |
|
Suffix check. |
|
All non-overlapping occurrences. |
|
List of substrings, separator removed. |
|
Strip whitespace. |
|
Strip any chars in the supplied string. |
|
|
|
The string itself. |
|
Single-byte string. |
|
Encode a codepoint as UTF-8 string. |
The codePoints view’s subscript still takes a byte offset; only materializing
it into a List changes the index unit. A subscript into a continuation byte
returns a raw byte String, while codePoints[i] returns -1 there. Ranges are
neither raw byte slices nor scalar-ordinal slices: "é"[0…1] returns the
whole two-byte character, while "é"[1…2] returns "".
No implicit NFC normalization occurs. "é" and "e\u0301" are different
Strings, with scalar counts 1 and 2. A one-byte invalid String can also have
count == 1, so text-taking native bindings must validate UTF-8 using the
explicit byte length rather than a String count or C strlen.
List
Mutable, ordered, dynamic-length, heterogeneous.
|
Empty list. |
|
Pre-fill |
|
Literal. |
|
Length. |
|
True iff empty. |
|
Access / replace; negatives count from the end. |
|
Slice (returns a new List). |
|
Append. |
|
Append every item of |
|
Insert |
|
Remove and return the first occurrence; returns |
|
Remove and return element at |
|
Empty the list. |
|
Index of first match, or |
|
Membership. |
|
In-place sort with |
|
In-place sort with a custom comparator. |
|
In-place swap. |
|
Sequence protocol. |
|
|
Map
Mutable hash map. Keys may be any hashable value (Num, String,
Bool, Null, Range, or Class — not List, Map, or arbitrary
instance). Iteration yields MapEntry objects with key and value
properties; use m.keys when only keys are wanted.
|
Empty map. |
|
Literal. |
|
Number of pairs. |
|
Empty? |
|
Access / set. Missing key returns |
|
Distinguishes "missing" from "value is null". |
|
Remove and return the old value (or |
|
Empty the map. |
|
|
|
Sequence protocol; iterating yields |
|
|
Range
Created via the .. (inclusive) and ... (exclusive-end) operators on
Nums. Lazy — values are produced on iteration.
|
Lower bound. |
|
Upper bound. |
|
Bounds normalised regardless of direction. |
|
True for |
|
Number of values. |
|
Iterate. |
Reverse ranges are valid: 5..0 walks 5, 4, 3, 2, 1, 0, while 5...0
excludes the ending zero.
Sequence (mixin)
The base "iterable" protocol. Sequence itself isn’t usually
instantiated; List, Map, Range, String, and your own classes that
implement iterate(prev) and iteratorValue(iter) inherit its
methods. Most are lazy where it makes sense.
|
True iff |
|
True iff any item passes. |
|
Membership via |
|
Eager count. |
|
Items where |
|
Apply |
|
True iff |
|
Concatenate all items' |
|
…with |
|
Lazy mapped sequence. |
|
Lazy filtered sequence. |
|
Lazy. |
|
Fold from first item. |
|
Fold from |
|
Materialise into a List. |
Fiber
First-class coroutines.
|
Create a paused fiber whose body is the closure. |
|
The fiber currently running. |
|
Resume |
|
Like call, but does not record this fiber as the resumer; cannot be returned to via |
|
Resume |
|
Like |
|
True after the body returns or aborts. |
|
The abort message if |
|
Suspend; control returns to the most recent |
|
…passing |
|
Raise |
A yield ends the current call/try boundary. To catch an error after a later
resume, use try() for that resume too. Fiber.suspend() returns to the host
while retaining the ordinary caller chain; transfer and transferError
retain their standard Wren behavior.
Host UI/resource wrappers drive their own callback fibers with ordinary
try() calls on each resume. Native completions are delivered to those
registered drivers; direct Fiber calls are not redirected. This is a host
callback policy, not an extension to Wren’s Fiber primitives.
Fn
A callable closure. Fn.new { … } is the only constructor.
|
Build from a closure literal. |
|
Invoke with no args. |
|
Invoke with args (up to 16). |
|
Declared parameter count. |
Script Loading
Script Directory
User scripts live in a per-platform directory. SyncTERM creates the directory on first launch if it doesn’t already exist.
| Platform | Scripts directory |
|---|---|
Linux / *BSD |
|
macOS |
|
Windows |
|
Haiku |
|
The directory has two roles, distinguished by where files live within it:
| Path | Role |
|---|---|
|
Importable module. Loaded when something imports it via
|
|
Auto-loaded entry script. Runs at the moment the framework fires
|
Files anywhere else under scripts/ (e.g. user-organised
subdirectories of pure library code) are reached only via import —
the framework owns scripts/auto/ and ignores everything else for
auto-load and per-connection selection purposes.
Module Names
Each script becomes its own Wren module, named after the file
basename without the .wren extension and without any directory
prefix. myscript.wren becomes module myscript, whether it’s at
scripts/myscript.wren or scripts/auto/connected/myscript.wren.
Module names are how scripts cross-reference each other:
import "myscript" for SomeClass
Module names are also how the embedded-script override mechanism works (see below).
Embedded Scripts
SyncTERM ships with a small set of scripts compiled into the binary.
They are not stored as files; the build system runs wren_embed_gen
at compile time, infers each script’s role from its source path
(library vs auto-load, and which event for auto-load), and folds the
sources into a C string table linked alongside wren_host.c.
The currently embedded scripts are:
| Module | Role | Purpose |
|---|---|---|
|
library |
Foundational module: foreign-class declarations and Wren-side
helpers ( |
|
library / menu only |
Trusted main-menu data model: transactional BBS-list loading and editable DirectoryEntry records, program settings, web lists, and custom-font configuration. The connected loader rejects this module. |
|
library / picker only |
Request-scoped file-picker interface. It exposes directory listings, path resolution, metadata, and completion methods, but no file-open capability. Menu and connected scripts cannot import it. |
|
reserved library / picker only |
Host-controlled picker entry and recovery surface. SyncTERM always interprets its embedded copy before loading picker overrides. |
|
auto / picker |
Split-pane file and directory browser. It implements single-file,
directory, save, and cross-directory multi-file selection and exports
|
|
auto / connected |
Connected-session Ctrl+` hook for graphical and native-console
backends. ANSI and ncurses sessions reach the shared |
|
library |
Wren REPL UI shared by the connected and menu VMs. Each invocation reads the log belonging to its current VM. |
|
auto / connected |
Alt+L send-login handler. Sends username, password, and sysop password from the directory entry, with the right send-order rules per connection type. |
|
auto / connected |
Default |
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
|
|
auto / connected |
Default |
|
auto / menu |
The persistent Wren main-menu controller. It loads the menu BBS
model, prompts for an encrypted-directory password when necessary,
and presents the classic dialing directory: the directory and
SyncTERM Settings lists remain visible together, the active list uses
the configured Classic Theme palette, and the selected entry’s comment and
list commands occupy the bottom two rows. The host calls
|
|
auto / menu |
Internal controller used by C connection and startup code for trusted
alerts, confirmations, prompts, choices, and progress overlays. An
override must preserve the |
The syncterm module is loaded on demand the first time something
imports it. Its top level obtains host-created Cache and Download
objects where that VM has them. The auto-load embeds run when their
owning VM is created: once per application for menu and picker, and
once per BBS session for connected.
Built-in main interfaces
Main Interface selects Classic or Retro: in Classic it is under Program
Settings, and in Retro it is on Settings → Program. Classic remains
the default when MainUI is absent or unrecognized. The accepted choice is
stored as MainUI=Classic or MainUI=Retro under [SyncTERM] and takes effect
when Settings closes, without restarting or reconnecting. It selects
both the offline directory and the existing edit-only connected directory.
Custom main_menu script overrides retain precedence over this built-in choice.
The legacy MainUI=DOS spelling remains readable; saves use MainUI=Retro.
The layout and selected colour theme are independent.
Retro opens on a full-width calling table. Its fixed 45-cell Name column fits
the longest legal name under the 30-scalar / 60-byte UTF-8 limits, including
wide characters. Address uses the remaining space; Port, Type, Term/Graphics,
Encoding, Calls, and Last Call appear as space permits. At 80 columns the table
shows Name, Address, Port, and Type. Narrow screens pan the table with Left/Right
instead of shrinking or truncating the Name column. Term/Graphics describes the
saved emulation and enabled graphics, such as ANSI/RIP1, ANSI/RIP3,
ANSI/Sky1.3, ANSI/Sky3.1, VT52/IGS, or ANSI/BIG; it does not report
live protocol negotiation or use the advertised TERM string as an emulator name.
The last-call date uses local time. Long text is clipped on grapheme boundaries.
Up/Down and paging keys select entries; type-to-search and Ctrl-F/Ctrl-G retain
the usual list behavior, with Retro Find also matching connection columns. Enter
connects offline and edits while connected. F2 edits, Insert adds, Delete
removes, F5/F6 copy/paste, Ctrl-S manages sorting, and </> cycle sort profiles.
A single mouse click selects a directory row; double-click activates it.
The selected entry’s comment is centred below the table, above the clickable
bottom command bar, with the same full-line styling and long-text clipping as
Classic. Entries without comments leave that line blank. F4 opens
the separate Settings screen. Tab moves between the directory and command bar;
Left/Right choose a focused command and Enter runs it. Escape exits the directory
or returns to the existing session.
Opening, resizing, or switching the directory does not resize the remote terminal.
Retro Settings opens one tabbed book with five categories on one row at 80 columns: Program (general behavior and audio/MIDI), Connections (new-entry defaults, modem, security, shell and TLS), Appearance (colours, themes, fonts and display), Files (list path, web lists and file locations), and About (read-only build capabilities and licenses). Regular settings edit directly in the book. Resource editors return to the tab that opened them; Escape from a child returns one level. Pending book edits survive child editors, including theme selection. Build information stays inside About instead of opening another menu. Resource managers and the defaults editor retain their own acceptance rules; the book’s Save/Cancel controls apply to its program-settings draft.
Resource list selectors, sorting and Wren scripts use full-page framed lists with bottom command hints. At 80 columns or wider, a separate scrollable information panel shows help or preview details. Narrow screens retain F1 help. Tab moves between the list and Back. Escape or Back returns to the owning tab or screen. Classic retains its compact menus.
Retro entry settings and New Connection Defaults use separate full-page forms.
They share the Settings book’s tab and field controls. Entry settings have three tabs on one row at 80 columns:
Connection (including login and security), Terminal (including scripts and
palette), and Files & Notes (paths, logging, and comment). New Connection
Defaults uses the same grouping without the per-entry comment, naming its last
tab Files. The active category stays highlighted and bracketed in the
top tab row while keyboard focus moves through its fields. Click a tab or use
Ctrl-PageUp/PageDown to change categories.
Tab/Shift-Tab move between three control groups: the tab bar, form fields, and
Save/Cancel. Entering the tab bar focuses the current page. Home/End jump to
the first/last tab. Arrow keys move within each group; Left/Right stay on the
same row, and Up/Down stay in the same field column. Text editors retain cursor
movement; at either end, Left/Right can cross to an adjacent field column.
tab.selected styles the current page independently of tab.focused for
keyboard focus; tab.selected.focused styles the combined state. Brackets
mark the current tab and > marks keyboard focus, including when colours match.
Labels sit beside their controls; text and number editors retain shaded,
bracketed rectangles when unfocused. Text boxes fit their field limits, numeric
boxes fit their minimum/maximum representation, and enum boxes fit their longest
choice, all capped by the available column width. Manage actions are compact
buttons sized to their labels; read-only facts are not editable boxes.
Enum fields have a down-arrow marker and open an attached dropdown with Enter,
Space, Alt-Down, or a click. The list opens below the field, or above when space
is limited. It expands to show all choices or fill the available height on that
side; a scrollbar appears only when the choices still do not fit.
Arrows, paging keys, Home/End, and typing navigate
choices. Enter or a click accepts; Tab accepts and moves to the next control group.
Escape or an outside click cancels without changing the draft. Resizing keeps
the list attached, or closes it if the field moves out of view. Opening a
dropdown retains the form’s active colours.
Wide screens balance fields across two columns. PageUp/PageDown and the
Previous/Next controls beside the tabs reach overflow fields within the current
category on small screens. F1 opens
contextual help. Specialized palette, script, font,
and file selectors remain available. Edits stay in a private draft across page
changes and resizing. Save/F10 accepts the complete draft; Cancel/Escape asks
before discarding changed drafts. A failed save retains the form and its draft
for retry. In safe mode, allowed program changes use Apply without persistence;
existing directory write restrictions still apply. Existing native partial-effect
errors, such as a saved configuration followed by a runtime-application failure,
are reported without claiming that completed effects were rolled back.
Classic retains its two-pane layout, field-list editors, immediate application of accepted program fields, and existing Escape/save conventions.
Overriding Embedded Scripts
A user script whose basename and role match an embedded module
overrides the embedded one. The shared REPL implementation can be
replaced with
~/.local/share/syncterm/scripts/wren_console.wren; all three VMs import
that library when their built-in menu, connected, or picker entry point opens
the console. Replacing
scripts/auto/connected/console.wren changes only the connected
graphical/native-console Ctrl+` hook. Replacing
scripts/auto/menu/main_menu.wren changes
the menu key binding along with the rest of the main-menu controller.
Replacing scripts/auto/picker/file_picker.wren changes the picker
implementation but not its reserved recovery surface.
The check is an exact match on the bare module name within the same
script role. A root console.wren is a library module distinct from
the connected auto-load module, while a root wren_console.wren
replaces the shared library. Case matters: Wren_Console.wren is a
different module from wren_console.wren.
To opt out of an embedded auto-load script entirely, drop a stub override into the matching directory:
// ~/.local/share/syncterm/scripts/auto/connected/connected.wren
// Disable the default Alt+L handler.
The override is loaded but registers no hook, so Alt+L silently does nothing.
Load Order
-
scripts/auto/<event>/is enumerated for files with the exact lowercase.wrensuffix. -
Each embedded script tagged with the firing event runs, unless its module name appears in the user-script set.
-
Each user script in
scripts/auto/<event>/runs as its own filename-derived module in case-sensitive byte order. This phase runs the user override omitted from the preceding embedded phase. A module already loaded through an earlier import is skipped. -
For
connected, root modules selected by the active personal directory entry run in their stored order. A module already loaded by an earlier script or import is skipped because Wren modules execute only once per VM. -
A command-line
-Wscript runs last in the connected VM.
import statements (whether from a script’s top-level or inside its
body) resolve through the lookup chain for the current VM:
-
scripts/<name>.wren— importable root module. -
scripts/auto/<event>/<name>.wren— where<event>ismenu,connected, orpicker; this catches imports of auto-load modules which have not run yet. -
The embedded table — built-in fallback by module name.
The foundational syncterm module lazily loads the first time
anything imports it; subsequent imports hit Wren’s module cache.
The menu host attempts every menu auto-load module and refuses to start a
partly initialized menu if any of them cannot be read or interpreted. Picker
implementation modules are optional: their errors are logged while the
embedded picker bootstrap and recovery surface remain available. A missing
FilePicker class enters recovery when the picker is invoked.
Per-Connection Scripts
A personal directory entry may contain an ordered WrenScripts INI value:
[Example BBS]
WrenScripts = session_logger,custom_keys
Each value names scripts/<name>.wren; do not include a path or extension.
Names contain only ASCII letters, digits, and underscore, are at most 255
bytes, and are case-sensitive Wren module names. The menu does not offer a
module already present in the entry, and the host removes exact duplicates
assigned through the menu API. syncterm_menu, syncterm_picker, and
picker_bootstrap are reserved and cannot be selected.
The editor catalog is rebuilt from root user-script files with the exact
lowercase .wren suffix on each request, in case-sensitive byte order. It
does not include modules embedded in the executable. Files with invalid
module names and the three reserved names above are omitted.
The entry editor’s Wren Scripts row opens the ordered-list editor. Select the
blank final row or press Insert to add a root module; Delete removes one.
Enter tags the selected module, Up and Down move it, and Enter places it.
Escape while moving restores its original position. A configured module
whose file is no longer present remains visible as [Missing] so opening and
saving the entry does not silently discard it.
Only personal named entries load this field. Defaults, installed system entries, web-list entries, and quick-connect records cannot activate scripts. At connection time, an unreadable configured module is reported in the connected VM log and error indicator, and loading continues with the next configured module.
A script’s top-level code runs once in the VM which owns its event. Top-level code commonly registers hooks or creates the long-lived menu controller; persistent state should be stored on classes (static fields).
The built-in main_menu module is also the host entry-point contract.
An override must export class MainMenu with these static methods:
-
prepare()loads the directory, performs any password interaction, and returns a Bool indicating whether the model is ready. -
run(currentName, connected)presents the directory.currentNameis a String ornull. Whenconnectedis false, return a current DirectoryEntry or Profile to start that connection ornullto exit. Connected invocations are edit-only; their return value is ignored. -
offerSave(source, name)receives a detached Profile and a separate suggested entry name after an unsaved quick-connect or command-line connection ends, including a return to the directory via Alt-H, and returns whether it was saved. The host callsprepare()first, then copies the C record into menu storage; no connection-owned pointer or foreign value is passed into Wren.
Additional trusted auto/menu scripts can extend the shipped controller
without replacing it:
import "syncterm" for Mod
import "main_menu" for MainMenu
MainMenu.registerCommand(121, Mod.command, "Alt-Y", "Open an offline planner",
Fn.new {|app, connected| Planner.show(app) })
registerCommand(key, modifiers, keyName, description, callback) replaces an earlier
extension on the same key/modifier pair or appends a new one. The overload
without modifiers uses zero. Registration happens during
menu-VM startup, before MainMenu.run builds its controller. The callback
receives the running App and the connected-directory Bool, is suppressed
while another modal is open, and its key name and description are appended to
the directory help.
When the built-in module is loaded, it paints the main-menu background and
title bar immediately. Startup alerts and progress panes therefore appear
over initialized menu chrome before MainMenu.run() constructs the
interactive directory.
The host validates and copies a record returned by run while the menu
VM is still selected, so the Wren foreign object itself never crosses
into the connected VM.
For an independently packaged frontend using this override contract, see Modern UI. Its directory/settings scripts are installed into the user script directory and are not embedded in SyncTERM.
The shipped controller binds Ctrl+` to the menu VM’s REPL in graphical
and native-console backends, and Ctrl+Q in ANSI and ncurses modes. A
CP437 ‼ in the top-right corner reports unread output from that VM: yellow
for print output and red for errors. Synchronous key and mouse handlers
run through an error boundary; an abort is added to the menu VM’s log,
the indicator is refreshed, and the main menu continues running. This
boundary does not hide layout or painting failures, which still abort
MainMenu.run rather than repeatedly failing during every redraw.
The Classic controller defines the following main-menu interaction contract. The Retro presentation shares its directory operations and host entry point, with the navigation and draft-editing differences described in Built-in main interfaces. After a connection or failed connection attempt, the offline directory restores its selected entry and viewport rather than returning to the first row. The selection follows the entry’s name across reloads and sort changes; if that entry disappeared, the previous row is retained and clamped to the new list. Connected-directory editing keeps a separate bookmark and does not overwrite the offline return position. Viewports are clamped when the list or screen size changes so the selected row remains visible.
Tab from the directory enters the selected entry’s comment field, then advances to the
simultaneously visible settings pane; Backtab traverses the same path in
reverse. Left and Right move directly between the directory and settings.
The first completed left click in an inactive pane transfers focus without
activating a row; a second click activates the row. A wheel event moves the
active list regardless of which pane is under the pointer. A completed left
click on the main-screen background transfers focus to the other pane.
Enter connects (or edits while connected) from the directory and invokes one
settings action from the settings pane. F2/Ctrl-E, Insert, Delete, F5/F6,
Ctrl-S, </>, Ctrl-D, and Alt-B invoke their documented commands. F2 does
nothing on the blank append row; Ctrl-E invokes the row’s add operation. The
comment row is also clickable for direct editing. An override may present the
model differently while preserving the host entry-point and ownership contracts.
The comment is edited only in the main screen’s footer. It is not a field in the full directory-entry editor. F1 and Ctrl-Z in the footer display the directory help. Operation-specific alerts and confirmations display the context help for the operation which opened them.
The footer advertises edit, copy, paste, insert, and delete only while the directory pane owns focus. The SyncTERM Settings pane advertises only Help and Exit, matching the operations available from that pane. While a comment is being edited, the footer shows the hints for the pane that opened it.
Lists which support appending provide a selectable blank final row.
Activating the blank row or pressing Insert invokes the same add operation.
The shipped directory, sort-profile, sort-field, web-list, custom-font, and
short-palette editors expose both forms; the palette row is omitted once all
sixteen colors are present. + aliases Insert, while - and ASCII DEL alias
Delete. Ctrl-Insert aliases F5 Copy, Shift-Insert aliases F6 Paste, and
Shift-Delete invokes Cut where that operation is available. Backspace and a
right click alias Escape after the focused widget declines the event. Delete
and the editor-specific copy, paste, rename, and cut keys are direct list
commands.
Adding a directory entry prompts for its name, connection type, and address,
then writes it immediately and returns to the directory. A single :port
suffix is accepted for network addresses. F2 or Ctrl-E opens the full entry
editor. Editing a read-only entry first offers to create a personal entry
with the same name. F5/F6 prompts for a new name when pasting a personal
entry; pasting a copied read-only entry uses the copied name.
The specialized editors provide direct menu operations. Enter on a sort
profile opens its field list, and Enter on a sort field reverses that
field; [ and ] move between profiles without returning to the profile
list. Enter on a web list edits its URI. Font details are a flat Name plus
four cell-size paths, and selecting a path opens the picker directly.
The encryption screen has distinct Change Password, algorithm, and Decrypt
operations; changing algorithms reuses the password already held by the
host. Palette editing uses a combined RGB, HSV, and hexadecimal colour
picker. The RGB ramps accept exact decimal entry, every ramp supports
keyboard and mouse adjustment, and the contrast grid selects the
foreground/background pair shown in the sample. % restores the mode
default; Enter accepts the colour and Escape cancels it.
In safe mode, accepted default-entry and web-list changes update the in-memory model but are not written to configuration files. Encryption conversions are no-ops; Change Password presents its password prompt before returning.
When an action rebuilds a repeating editor’s list, the editor retains the
same row and viewport position. This applies to entry logging and palettes,
sort profiles and fields, program settings and their nested lists, web lists,
and font management.
Directory editing commands apply only while the directory pane owns focus.
Directory, pasted-entry, command-line-save, sort-profile, and web-list name
prompts repeat after an invalid or duplicate name. Entry-editor prompts
distinguish empty, reserved, and duplicate names. Directory add and
command-line-save prompts treat an empty edit as cancellation while still
distinguishing reserved and duplicate names; an entry creation failure is
reported separately. Sort-profile field navigation returns to the last
profile visited. New entries are inserted according to the active sort
profile after their connection details are accepted. Quick Connect limits
the directory address field to 64 characters. Current Screen Mode and
Startup Screen Mode use distinct dialog titles and context help.
When PromptSave is enabled, every unsaved quick-connect or command-line
session offers to save its complete entry after disconnect. Accepted SSH
host keys remain in the temporary profile until that entry is saved; host-key
verification updates only existing personal entries and preserves their
list encryption.
Directory password and system-password rows are obscured in the editor
list, but selecting one uses ordinary text editing so the existing value can
be inspected and corrected. Personal-directory encryption prompts are
masked.
Rate choices select the first supported rate at or above a configured value,
or Current when no supported rate is high enough.
An OS window-close request sets a sticky process-exit latch. It does not ask
the main menu or connected session for confirmation. An App unwinds nested
widgets through their normal Escape path one modal frame at a time, allowing
each Wren call to return and run its normal cleanup. A widget explicitly
marked atExit remains interactive; the command-line directory-entry save
workflow uses this for its confirmation, prompts, errors, and editor.
Accepted Classic Theme colour changes rebuild the active theme immediately
while Classic Theme is selected. A selected file theme is unaffected.
Renaming a persisted entry also renames its per-entry cache directory after
the directory file is written successfully.
Font Management treats an empty name as cancellation when adding a record.
Otherwise, it accepts the entered name and the file returned by the picker as
the record values. It reports a full custom-font table before prompting for
another name. The preformatted File Locations and Build Options viewers use
the titles File Locations and Build Options. Their maximum dimensions are
78 by 21 and 60 by 21 cells respectively, capped to preserve the standard
modal margins and complete drop shadow. Their Markdown content defines the
label emphasis, indentation, and section layout rendered by the shared Help
viewer.
Palette Insert is exposed only while the palette has room for another color,
and Delete is exposed only while a color can be deleted. Sort-profile Paste
is exposed only after Copy or Cut has supplied a clipboard profile. Font
Details and the outer Font Management list both support Insert, Delete, and
the blank add row.
Adding a web list skips its initial fetch when no cache path is available but
records the configuration; explicit refresh reports the missing cache.
Left and Right move directly between the directory and settings panes.
Leaving the comment field by mouse, pane navigation, or application exit
commits the accepted edit before focus moves. The entry editor reselects its
highlighted field after [ and ] move between entries. Program Settings
summarizes enabled audio backends, and entry rows distinguish automatic
terminal types, unset passwords, and nonzero communication rates.
Web-list edits update the in-memory configuration immediately and are written
when the Web Lists screen closes.
Saving an existing directory entry does not change its Added timestamp.
Clearing the Terminal Type field writes the empty override, so a subsequent
directory reload uses automatic terminal-type selection. In the palette
component editor, % resets all three components of the selected colour from
the mode palette without moving focus to another field.
Creating or copying a personal entry with the same name as a read-only entry
replaces that row immediately. The model stores the read-only entry beneath
the personal override. Deleting the override exposes the read-only entry;
renaming and saving the personal entry exposes the read-only entry under its
own name.
Adding an entry may create such an override. Pasting a copied personal entry
instead requires a name unique across all currently visible entries.
The inactive directory comment is centered across its line. While the
directory pane has focus, its selection supplies the OS window title; while
the settings pane has focus, the title is the bare SyncTERM version. Editing
a comment leaves the title from the pane where editing began until focus moves
again. The active editor is left-aligned within the middle
screen width - 4 cells.
Its existing value initially appears selected in the text-input lightbar, so
typing or deleting replaces the complete comment. Cursor movement or mouse
positioning leaves the value unchanged and switches to the normal menu colors
for ordinary editing. Leaving the editor immediately centers the inactive
row, even when its value was unchanged.
The shipped menu keeps context help beside the Wren screen that owns each
control. Directory, sort-profile, entry-editor, settings, web-list, font,
and encryption panes assign Markdown helpText to their panes and nested
dialogs. F1 therefore resolves to the general screen description from the
list and to field-specific help while a choice or prompt is open. Menu
overrides should use the normal Help Markdown contract described under
Help viewer. Help content must be Markdown; legacy help-buffer
markup is unsupported.
The shipped editors distinguish accepting an edit from writing its backing file. A confirmed entry field immediately updates the entry-backed Profile view, and a confirmed program setting is immediately applied to the running settings. Their files are written when the owning entry or Program Settings editor closes. Font changes stay in the font model until Font Management closes. Sort-profile operations update the working profile model, which is written when Sort Profiles closes; profile cycling from the main directory writes immediately. None of these screens exposes the persistence boundary as a selectable Save or Cancel row.
Escape from a nested prompt or choice cancels only that nested operation. Escape from an owning editor closes it without rolling back accepted edits. An owning menu stays on the modal stack and is rendered behind a nested prompt, picker, viewer, or submenu until that child is dismissed.
Headless Tests
The CMake test suite drives menu and picker VMs against headless consoles and isolated temporary data trees. After building a configured tree, run the Wren tests with:
ctest --test-dir build --output-on-failure -R '^(wren_|st_wren_)'
The wren_host test covers the shared host bindings. The wren_* tests run
the menu, picker, and individual UI-script suites through the same embedded
module loader used by the application. The current tree does not provide a
standalone source-tree connected-VM script runner.
VM Lifetimes and Trust Boundaries
SyncTERM deliberately uses three Wren VMs. They do not share Wren objects, handles, modules, globals, hooks, timers, result queues, or foreign objects.
The persistent menu and picker VMs each own a logical console. A VM’s normal UI and its REPL share that console rather than copying the screen into a separate REPL console. Their cells, fonts, palette, cursor, dimensions, and pending input remain independent while one physical display switches synchronously between them. Work on the inactive console remains off-screen until it is selected. The connected terminal still uses the existing screen-ownership path pending its migration to the same display model.
-
The menu VM is created once after conio and configuration are initialized. It owns
scripts/auto/menu/, survives connections, is parked while the connected screen is active, and is destroyed at application shutdown. It can edit the BBS list and settings and can request a picker operation. -
A fresh connected VM is created by
wren_host_init(bbs)for each BBS session and freed bywren_host_shutdown()on every exit path. It ownsscripts/auto/connected/. Module statics, hooks, timers, claims, and queued results do not survive disconnect. -
The picker VM is created once after the menu VM, owns
scripts/auto/picker/, and remains parked except while a picker request is active. It cannot importsyncterm_menu, inspect BBS records, change settings, establish connections, or open files. Its request object exposes only directory listings, path resolution and metadata, and one-shot completion methods.
The remote system is considered hostile. A remotely supplied script
may know the active entry’s username, password, and system password;
those values are already meaningful to that remote. It must not gain
the authority to enumerate or edit other BBS entries, change global
settings, start another connection, or mint arbitrary local-file
access. Consequently syncterm_menu is not merely omitted from the
connected documentation: the connected loader explicitly rejects it,
and menu foreign objects cannot cross the VM boundary.
Menu auto-script overrides are trusted application code, not a sandbox for
downloaded scripts. In addition to directory and settings mutation, the
menu VM can invoke picker-mediated local-file operations, open URLs from the
completed session’s scrollback, and update trusted application chrome. Do
not install a remotely supplied script under scripts/auto/menu/; remote or
otherwise untrusted session automation belongs in the per-connection VM and
receives only that VM’s capabilities.
Connected scripts intentionally retain Input.ungetKey,
Input.ungetMouse, physical-key synthesis, and the other synthetic
input bindings. User scripts need them to automate the current remote
session. Isolation is provided by the VM and transition barriers, not
by removing those session-local controls.
At every ownership transition (connect, disconnect, entry to or return
from the menu through Alt+E, and entry to or return from the picker), the
host establishes a new input epoch. It discards pending conio keyboard
and mouse pushback and rejects late input-shaped results tagged with an
older epoch. Input claims remain parked in the VM that owns them and
cannot run while another VM owns the screen. This prevents a connected
script from placing synthetic input in
ungetkey() / ungetmouse() just before the trusted menu or picker
takes control. The same barrier protects the connected VM when control
returns from a trusted UI. Physical-key production is suspended while
the menu owns input, restored when returning to a live connection, and
disabled with its held-key state cleared when the connection ends.
The picker VM is the local-file consent broker. Neither its caller nor
the picker script receives arbitrary pathname-open authority. A
single-file or multi-file completion is converted by C into read-only
File handles. A save completion explicitly reports create or
overwrite consent; C converts it into a one-shot write-only grant without
retesting the pathname. These rights remain attached to the foreign
File handle as documented in Write consent.
The request object is invalidated as soon as the picker returns, so it
cannot retain listing or completion authority between calls.
Picker overrides under scripts/auto/picker/ are trusted local
application code, but the picker VM still receives only the capabilities
needed by the browser. The host always interprets the embedded
picker_bootstrap first. A picker implementation compile or runtime
failure therefore enters a recovery screen instead of terminating
SyncTERM: Ctrl+` opens the picker VM’s REPL, Escape cancels the
request, and Key.quit exits the application. The normal picker shows
that VM’s unread or error indicator at the top right and uses the same
Ctrl+` binding. Only failure to initialize the VM or reserved
bootstrap disables picker operations.
C-owned startup and connection flows also render their dialogs through the persistent menu VM. These calls do not expose a dialog capability to connected scripts. Blocking alerts, confirmations, prompts, and choices save and restore the current screen and establish input barriers both before and after the dialog, so synthetic connected-session input cannot answer a trusted question. Progress overlays deliberately do not clear or claim input: connection setup continues polling conio so the user can abort a stalled operation. Clearing progress restores the exact screen, palette, fonts, video flags, and cursor state saved when the first update was shown.
The embedded menu_host_ui module exports class MenuHostUI with static
methods alert(title, message), alertWithHelp(title, message, helpText),
help(title, body), confirm(title, message),
prompt(title, message, initial, maxLen, masked),
choice(title, message, options, current),
ripChoice(title, message, options, hotkeys, required), status(title, lines), and
statusClear(), plus disconnected(title, details) for the post-session
bottom-row notice. That notice keeps the completed terminal visible until
Enter, with F1 opening session details and the final protocol log. Alt-B
(Cmd-B on macOS) opens that session’s scrollback; Escape returns to the
notice. If the connection had a status bar, its row stays blank in the
disconnected style outside the viewer’s content area. With the status bar
disabled, the viewer uses the full terminal height, including the bottom row.
Without a status bar, the terminal scrolls once to make room for the notice.
History is saved before that scroll, so opening scrollback reconstructs the
completed screen apart from its scrollback indicators. Terminal dimensions
and status layout are preserved, and the notice does not enter saved history.
hidePopups and local hangup/exit skip the notice. This is a host-controller
ABI rather than a public menu script API: application C code holds the call
handles and invokes it.
ripChoice is the C-owned RIP pick-list bridge: hotkeys are Unicode scalar
values (zero disables one), and required lists ignore Escape and outside clicks.
Closing the application still unwinds the dialog and restores its saved screen.
The progress pane fits the wider of its title and status rows, capped to the
standard screen margins. The pane itself is centered, but all status rows
share one padded left edge so preformatted columns remain aligned between
rows. Text wraps within that common content width on narrower screens.
Menu auto-script overrides are trusted and may replace its presentation,
but must keep those signatures and return Bool, String/null, and
numeric choice indexes as appropriate or host dialogs fail closed.
Every reconnect rebuilds the connected VM from scratch. Connected
scripts needing cross-session state must persist it through an
authorized Cache / Download file or picker token. Menu scripts can
keep ordinary Wren state for the application lifetime, but durable
changes still require the explicit model save methods.
Console entries, cached entry handles, REPL state, and unread markers belong to one VM. Opening the menu through Alt+E therefore shows the menu VM’s log, not output produced by the parked connected VM, and no console object or handle crosses the trust boundary.
The owner thread is captured at init; dispatchers called from any
other thread (background SFTP and SSH writes invoke conn_send from
worker threads) short-circuit to pass-through. Scripts run on the
foreground thread only.
Importing the API
Shared host bindings live in module syncterm. Every script imports
the classes it needs:
import "syncterm" for Screen, Input, Conn, Hook, Key
An import does not grant all methods declared by that module. The host resolves known shared declarations so UI libraries can load in each VM. Calling a known capability owned by another VM aborts with "this capability is not available in this VM". Unknown foreign method declarations fail immediately during module loading, identifying the module, class, and signature. Constructing an unknown foreign class aborts with a missing-allocator error; the host never supplies an unrelated native payload. Namespace classes use ordinary Wren classes with foreign static methods. Menu-only data APIs are imported separately:
import "syncterm_menu" for Menu, DirectoryEntry, Settings, MenuFont, MenuError, BBSLoadDiagnostic, BBSListSource, MenuEncryption, MenuFontSlot
Cache is injected into the syncterm module from C as a
module-level Directory object — there is no Wren-callable
constructor. Import it like any other binding:
import "syncterm" for Cache
Hook Events
Hooks are registered as Wren callables (block, function, or method
reference). Each call site walks its hook list in registration
order; the first hook returning true consumes the event and stops
dispatch. Returning false, returning a non-Bool, or throwing
passes through to the next hook and ultimately to SyncTERM’s default
handling.
Every registration returns a HookHandle (or null if the per-event
limit is hit) — see HookHandle. Save it if the script needs to
remove the hook later or read its metrics; toss it if not.
Hooks must run synchronously
Every hook fire is wrapped in a child fiber via Hook.dispatch_.
For C1-contract hooks (see Two return contracts) the dispatcher needs
the hook’s return value before it can decide what to do next; a hook
that yields up to the dispatcher would strand it with no value to
act on. C2-contract hooks ignore returns, but yielding still
breaks the dispatch chain.
If a hook callback yields its own fiber directly (for example by awaiting an operation directly inside that callback), the dispatch wrapper detects the yield and logs:
hook handler must not yield directly; wrap parking work in
Fiber.new { ... }.call()
The hook is then treated as if it returned a non-Bool — the input
passes through to the next hook and to SyncTERM’s default handling.
A Fiber.abort from the hook is caught the same way: logged with a
stack trace, treated as passthrough.
A hook that needs to wait on async results has two options that keep the hook itself synchronous. The first wraps the work in a child fiber and `.call()`s it from the hook body:
Hook.onKey { |k|
if (k == Key.f2) {
Fiber.new { runModalBrowser() }.call()
return true
}
return false
}
.call() runs the child fiber synchronously until it yields (e.g.
on an SFTP op or a Fiber.yield() waiting for a Wake.post).
The child’s yield returns to the hook body — the immediate
.call() caller — not up to the dispatcher. The hook still
returns its Bool; the child resumes later via the framework’s
result-queue drain.
The second option is to observe the operation with .then(fn), whose
callback runs when the result arrives. The hook returns
synchronously without ever yielding; the callback fiber is invoked
later by the drainer:
Hook.onKey { |k|
if (k == Key.f2) {
SFTP.realpath(".").then(Fn.new {|r|
// handle r …
})
return true
}
return false
}
Two return contracts
Every hook callback follows one of exactly two return-value contracts. Knowing which contract a hook uses tells you what (if anything) your return value does.
| Contract | Behaviour |
|---|---|
|
|
|
The return value is ignored entirely. These hooks fire as a
side-effect notification; the event continues regardless. A |
onKey, onPhysicalKey, and onMouse use C1 but have no meaningful
interpretation for String returns (a key event, a
PhysicalKeyEvent, or a MouseEvent isn’t a byte stream), so a String
return from those is silently treated as passthrough. Use onWire for
wire-byte replacement, or onInput for Unicode text replacement.
| Method | Argument | Contract |
|---|---|---|
|
|
C1 |
|
Filtered by logical key and modifier mask; the short form uses zero
modifiers. Caps Lock and Num Lock are ignored. Other modifier bits must
match exactly. The callback receives a complete |
C1 |
|
|
C1. String replacements are NFC-normalized semantic UTF-8 text, capped at 256 bytes. Invalid UTF-8 or an oversized replacement logs an error and passes through the original scalar. |
|
Filtered: |
C1 |
|
|
C1. A returned String contributes its exact bytes to the parser, without revisiting wire hooks. Replacements are capped at 256 bytes; an oversized replacement logs an error and passes through the original byte. |
|
Filtered: |
C1 |
|
Receives mapped controller value changes before graphics and CTerm. The
Map has numeric |
C1 |
|
|
C1 |
|
Filtered: |
C1 |
|
|
C2. An "honor |
|
Same as |
C2 |
|
|
C1 |
|
Filtered: |
C1 |
|
|
C2 |
|
Fires once when the SSH shell channel closes but the session is still alive (e.g. SFTP transfers may still be in flight). Typical use: pop a status / queue UI so the user can watch transfers finish, or signal a worker to wind down. See Session for owned lifetime leases that keep auxiliary work running after shell EOF. |
C2 |
|
Fires at the end of the disconnect path, after the main loop has fully exited but before the BBS / Wren VM tear down. SFTP is no longer available at this point (sftpc_finish has already run); use this for final local-state flushes (queue persistence, log close, etc.). |
C2 |
Filtered variants share the same per-event registration array as the unfiltered forms, so dispatch order = registration order regardless of which form was used.
Hook.onWire fires on post-transport bytes before RIPscrip or CTerm
classifies controls and text. It is the explicit byte-oriented hook
for wire protocols; a returned String remains raw bytes. The default
Hook.onInput and streaming match hooks are Unicode-facing: they see
decoded text independent of whether the remote uses UTF-8 or a legacy
codepage. Their replacements stay in the semantic text path rather
than being re-encoded as if they had arrived from the remote.
Sequence parameters and opaque protocol payloads bypass these Unicode hooks.
onMatch retains control markers such as ESC; use onWire to inspect entire
protocol sequences, and onMatchClean to match text across them.
Hooks run in registration order; the first one that returns Bool true
(drop) or a String (replace) wins, and later hooks don’t see that unit.
An onWire replacement is emitted before the next received byte,
without recursively invoking the wire-hook chain.
Hook.every fires from the main-loop deadline check just before the
sleep call. If the loop stalls long enough that more than one
interval has elapsed, the deadline jumps forward to "now" rather
than firing repeatedly to catch up.
The status bar is a separate dispatch path — see Status.
A single render callable (rather than a hook chain) builds the row
into a Surface the host hands it.
Streaming regex hooks
Hook.onMatch(pattern, fn) registers a regex against the decoded
UTF-8 input stream. Each decoded byte is fed to a streaming Pike VM (Russ
Cox’s NFA simulation, vendored under re1/); when a match completes,
fn is called with a Wren List:
Hook.onMatch("login:") { |m|
Conn.sendText("user\r")
return false
}
Hook.onMatch("user (joe|jane|bob)") { |m|
// m[0] = "user joe", m[1] = "joe"
System.print("hi %(m[1])")
return false
}
m[0] is the matched substring; m[1..] are the user-pattern’s
capture groups in registration order. Both onMatch and
onMatchClean are passthrough-only: the callback’s return value is
ignored, and the matched text always reaches the terminal. Matching
completes only after preceding bytes have passed through cterm, so these
hooks cannot drop a complete matched span. Use the scalar-granular
Hook.onInput hook when input must be dropped before reaching cterm.
Hook.onMatchClean(pattern, fn) omits ESC markers from CTerm’s decoded text
stream. CTerm already withholds sequence bodies and opaque payloads from
Unicode hooks. The matcher does not run a second escape parser, so an escape
cannot leave it waiting for bytes which CTerm has already consumed. UTF-8 and
legacy-codepage text use the same matching path, including sequences and
Unicode characters split across receive buffers.
Grammar
RE1 implements a deliberately minimal regex dialect. These are all of the supported metacharacters:
| Construct | Meaning |
|---|---|
literal byte |
matches itself. Backslash has no special meaning —
|
|
any byte (including NUL — the streaming VM does not treat NUL as end-of-input) |
|
capturing group |
|
non-capturing group |
|
alternation |
|
greedy: zero-or-more, one-or-more, optional |
|
lazy (non-greedy) variants |
Notably not supported (will be parsed as literal characters or syntax errors):
Patterns are anchored at the current buffer start. "Match
anywhere in the stream" is achieved by the dispatcher: when the VM
returns IMPOSSIBLE (no thread can ever complete from the current
buffer head), the oldest byte is dropped and the survivors are
re-fed. In practice this means a pattern like "hello" matches the
substring "hello" wherever it appears in the stream.
This trick requires that the pattern can produce IMPOSSIBLE — i.e.,
the first byte either advances the NFA or kills every thread.
Patterns whose leading construct can match without consuming a byte
keep threads alive on every input forever, the buffer fills, and
matches start being silently dropped. Hook.onMatch therefore
rejects patterns whose leading construct is *, +, or ? at
registration time with Fiber.abort:
| Allowed (1-byte anchor) | Rejected (variable-width leading) |
|---|---|
|
|
|
|
|
|
|
|
If you want a quantifier inside the pattern, anchor it with a fixed
prefix: bbs (.) ` rather than `(.) bbs.
Match semantics
Pike VM has a leftmost-first-completing tie-breaking rule: as soon
as any thread reaches a Match opcode, the match commits and
remaining threads in the current step are discarded. In a streaming
context this means open-ended quantifiers fire as soon as the
shortest acceptable prefix is seen — a* matches the empty string
at the first byte, a+ matches the first 'a' and stops.
For greedy-feeling behavior, terminate variable-length sub-patterns
with a literal that follows them: user (.) ` (capture text up
to a space) instead of bare `user (.). Newlines must be encoded
as literal \n bytes in the Wren string (“\n” in the source code,
which Wren resolves to a single 0x0A byte).
Limits
-
Buffer is capped at 4 KB per hook. When a partial match grows past the cap, the oldest half is dropped and the VM restarts — patterns that demand more than 4 KB of context will silently miss.
-
Up to 9 capture groups (RE1’s
MAXSUB = 20minus the whole-match pair). -
Pattern compile errors (bad syntax, internal asserts) surface as
Fiber.abortat the registration site, with the RE1 error text attached. The exception trace points at the offendingHook.onMatchcall.
HookHandle
Every successful Hook.on* and Hook.every registration returns a
HookHandle. The class has no Wren-callable constructor, so a
script can’t fabricate one to remove arbitrary hooks — only its
own.
import "syncterm" for Hook
var h = Hook.onKey { |k|
if (k == 0x4200) { // F8
System.print("F8 pressed")
return true
}
return false
}
// ...later...
h.remove() // no further dispatch
| Member | Meaning |
|---|---|
|
Remove the hook from future dispatch. Safe to call from inside its
own callback; in-flight dispatch finishes before resources are reclaimed.
Returns |
|
Number of times the host has invoked this hook. Counts every
|
|
Cumulative wall-clock seconds spent inside |
|
Smallest / largest single invocation time in seconds. Both read
back as |
HookHandle.remove() is safe from inside the hook’s own callback.
The callable handle is released immediately and subsequent dispatches
skip the removed entry. Outside dispatch, the host unlinks removed entries
and frees their regex resources before registration, on the next pump, or
when a host interpretation returns. The metrics remain alive until the
script also drops the HookHandle and its foreign finalizer runs.
Dropping a handle alone leaves an active hook registered.
Metric getters on a removed handle keep working until the script
drops the handle.
Modal Input
The conventional Input.next() / Input.next(ms) / Input.poll()
primitives all return promptly; while a script is calling them in a
loop the doterm() main loop is blocked, and inbound server bytes
queue up in the socket buffer until the script returns.
For modal dialogs that should not block the main loop while the
script idles between events, use Input.pushClaim(fn). The
foreign installs fn as the current claim on a stack of input
claims; whenever a key or mouse event arrives, the C-side
dispatcher walks the stack head-first (newest first) and invokes
the first claim whose owning fiber is still alive. The claim’s
return value is a Bool — true consumes the event (no other claim
or hook sees it), false passes it through to the next claim down
and ultimately to the registered Hook.onKey / Hook.onMouse
chain.
import "syncterm" for Input, Key, Wake, Screen, CTerm
var saved = Screen.save()
CTerm.suspended = true
var me = Fiber.current
var claim
claim = Input.pushClaim(Fn.new {|ev|
// Decide consume / passthrough synchronously here — handlers
// run from the C dispatch frame and must not yield. Anything
// we want to *do* with the event is dispatched by waking the
// worker fiber via Wake.post; the worker yields/resumes on
// its own schedule.
Wake.post(me, ev)
return true
})
while (true) {
var ev = Fiber.yield()
if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
Screen.window.print("got: %(ev)\n")
}
claim.pop()
Screen.restore(saved)
CTerm.suspended = false
The claim is a per-fiber slot: pushing twice from the same fiber
replaces the existing claim in place (preserving stack position).
Pushing from a different fiber adds a new entry on top, which
becomes the foreground. Auto-prune at dispatch time drops claims
whose owning fiber is isDone (so a script that aborts mid-claim
doesn’t leave a dead handler installed). The returned
ClaimHandle is the explicit way to remove the
claim; pop() is idempotent.
CTerm.suspended is independent of the claim mechanism — any
script can set it to claim the screen, and remote bytes pile up in
the conn buffer behind it. When the TCP receive window fills, the
remote sees its send() calls block or EAGAIN. Clearing the
flag releases the backpressure and the buffered bytes drain
through cterm normally.
The claim handler runs from the C dispatch frame via the same
Hook.dispatch_ wrapper that protects regular hooks (see "Hooks
must run synchronously" above) — so a yield inside the handler is
caught and treated as not-consumed, and the input falls through to
the next claim or hook chain. Heavy work belongs in a separate
fiber that the handler wakes via Wake.post.
A hook callback can install its own claim and let it persist past the hook return — perfect for "F2 opens a modal that captures input until Esc":
Hook.onKey(Key.f2) { |k|
var worker
worker = Fiber.new {
var claim = Input.pushClaim(Fn.new {|ev|
Wake.post(worker, ev)
return true
})
while (true) {
var ev = Fiber.yield()
if (ev is KeyEvent && ev.matches(Key.escape, 0)) break
// ...
}
claim.pop()
}
worker.call()
return true
}
For more elaborate UIs, the App class (see App) wraps
this pattern and provides synchronous claim decisions based on its
own state (modal stack, focused widget, mouse hit-test) plus a
runChild helper that lets handler code yield safely on async
work without breaking the App’s event loop.
Built-in REPL
The immediate-mode REPL belongs to the VM which owns the current screen.
In graphical and native-console backends, Ctrl+` opens it from the main
menu or a connected session. In ANSI and ncurses modes, Ctrl+Q opens it
from the main menu; while connected, press Ctrl+S and select Wren Console
from the Online Menu. The shared UI is implemented in
scripts/wren_console.wren and can be overridden with
~/.local/share/syncterm/scripts/wren_console.wren. The connected
entry point is scripts/auto/connected/console.wren; the persistent menu
binds its backend-appropriate key in scripts/auto/menu/main_menu.wren.
While the connected console is open the doterm() main loop is suspended. Connection bytes accumulate in the socket buffer but aren’t drained until you exit the console. This is acceptable for a development tool; not appropriate for "watch a slow BBS scroll" use cases. The menu already uses a synchronous event loop, so opening its console does not change its event-pumping model. When the menu was entered through Alt+E, the connection is already parked for the entire menu visit.
When physical-key reporting is active, the console drains and ignores
PhysicalKeyEvent press/release edges; editing commands use the corresponding
translated KeyEvent. This keeps host key state synchronized without sending
console keystrokes to the connected application.
The editor stores cursor positions as UTF-8 byte offsets for Wren string
slicing, but Left, Right, Backspace, Delete, and Ctrl+W move only across
complete Unicode codepoints. The displayed cursor column follows the glyph
width selected by Screen.textWidth() and eight-column tab stops. Editing is
codepoint-based: grapheme-cluster navigation and Unicode word-breaking are not
performed. Display boundaries normalize text to NFC and measure complete
extended grapheme clusters.
The REPL evaluates input through REPL.eval(module, src). The
input is pre-classified by inspecting its leading non-whitespace
token: source that begins with a Wren statement keyword (var,
class, import, return, break, continue, if, while,
for) is compiled as a statement; everything else is compiled as
an expression. Successful expressions print their result quoted
with C-style escapes (so "7" the string and 7 the number are
visibly distinct); statements print nothing.
Variables and class declarations persist across submissions inside the active module:
> var x = 1 + 2
> x * 10
30
> class Foo { static greet { "hi" } }
> Foo.greet
"hi"
REPL Commands
| Command | Action |
|---|---|
|
Print commands, editing keys, history navigation, scrollback navigation, and exit keys. |
|
Switch the eval target to |
|
List every Wren module currently loaded into the VM, alphabetically
sorted. Includes |
|
Close the REPL and return to the connected session or main menu. |
Modules can plug in their own /<command> entries via
WrenConsole.register(name, help, fn):
import "wren_console" for WrenConsole
WrenConsole.register("greet", "say hello [<name>]") { |args|
if (args == "") {
System.print("hello!")
} else {
System.print("hello, %(args)!")
}
}
The handler is called with the raw argument string — everything
after the command name and its first separating space, or "" if
none. Re-registering an existing name overwrites the previous
binding. Names can’t contain spaces (the dispatcher splits on the
first one). The dispatch wraps the handler in Fiber.new {}.try()
so a runtime abort surfaces as a logged error instead of tearing
the console out from under itself. /? lists every registered
command with its help text alongside the built-ins.
WrenConsole.unregister(name) drops a registration (idempotent —
no-op if not registered); WrenConsole.commands returns the sorted
list of currently-registered names for tooling.
REPL Key Bindings
| Key | Action |
|---|---|
Left / Right |
Move the cursor within the current input line. |
Home / End |
Jump to start / end of the current input line. |
Backspace |
Delete the character before the cursor. |
Delete |
Delete the character at the cursor. |
Up / Down (live mode) |
Walk command history. If the line currently has typed text, that text becomes a prefix anchor — only history entries starting with it are visited. |
PgUp / PgDn |
Page through the scrollback log buffer. PgUp from live mode pins the current top of view; PgDn returns to live once you’ve scrolled past the tail. |
Up / Down (scrollback mode) |
Single-row scroll. Down past the tail rejoins live mode. |
Enter (blank or whitespace-only) |
Advance to a fresh prompt row without evaluating. |
Ctrl+W |
Backward kill-word, ending at the cursor (the tail past the cursor is preserved). |
Ctrl+L |
Clear the screen and the in-memory log. Returns to live mode. |
Middle-click |
Paste from the system clipboard at the cursor. Valid Unicode text and Tab are inserted. CR, LF, and CRLF each delimit one submitted line. Other C0, DEL, and C1 controls, malformed UTF-8, and non-scalar encodings are discarded without discarding valid text around them. |
Alt+drag |
Hand off to the existing select-and-copy gesture. |
Ctrl+` (graphical/native-console) / Ctrl+Q or Ctrl+S (ANSI/ncurses) |
Close the REPL and return to the owning screen. |
Esc / |
Close the REPL in every backend. |
Object Model
The remainder of this document is a reference for every foreign
class exposed in the syncterm module.
A note on toString: every class with an explicit toString method
returns it strictly for human-readable debug output — the format
that System.print(value) and string interpolation "%(value)"
emit when no other rendering is appropriate. The exact string is
not part of the API contract; it may change between SyncTERM
versions to add or remove fields, reformat, etc. Scripts that need
specific data should call the named property accessors (cell.ch,
event.key, surface.width) — never parse toString output.
Without an explicit toString a foreign would print as something
like [instance of Cell], which is uniformly less useful than even
a minimal Cell(0x41 attr=0x07); that’s the only motivation for
having these methods at all.
Error / ScriptError
Error is the polymorphic base for every recoverable-failure value
type the API hands back: SFTPError,
FileError, WONError,
ConnError, TransferError,
CTermError, ScreenError,
FontError, menu-only
MenuError, plus any user-defined
ScriptError subclass. Lets a script catch any of
them with one check:
import "syncterm" for Error
var v = something_that_might_fail()
if (v is Error) {
System.print("failed: %(v)") // toString includes the type
return
}
// proceed with the typed result
Every concrete Error subclass guarantees the contract:
| Member | Description |
|---|---|
|
Numeric error code from the type’s enum
(e.g. |
|
Human-readable diagnostic, may be |
|
Format with the subclass name as prefix. |
Type-specific extras (FileError.errno, WONError.offset,
ConnError.partial, FontError.nativeCode, MenuError.nativeCode, SFTPError.serverStatus,
SFTPError.isTransient) live on the subclass.
Error itself is empty by design: foreign subclasses (FileError
etc.) need the parent to be field-free or Wren rejects the
inheritance at module-load time (the
numFields == -1 && superclass→numFields > 0 check at
wren_vm.c:559-563).
ScriptError
Concrete Wren-side base for script-defined error types. Use this when a script wants to surface its own typed error without writing C bindings:
import "syncterm" for ScriptError
class ConfigError is ScriptError {}
if (something_bad) {
return ConfigError.new(42, "missing required field 'host'")
}
ScriptError provides the same code / message / toString
getters every foreign Error subclass exposes, so callers see uniform
behaviour from is Error and the field accesses regardless of
whether the value came from C or Wren. The default toString uses
the runtime class name ("ConfigError(42): missing required field
'host'"); subclasses may override for a different format.
| Member | Description |
|---|---|
|
Construct. |
|
The integer passed to the constructor. |
|
The string passed to the constructor. |
|
|
Screen
Drawing/state queries return their documented successful value or a
ScreenError. Drawing/state actions return null on success
or ScreenError; test for Error before using a returned value. These operations
are available in the menu, picker and connected VMs, each using its own console.
Read/write access to the terminal display surface. Screen itself
exposes whole-screen and absolute-coordinate operations; per-window
operations live under Screen.window.
| Member | Description |
|---|---|
|
|
|
Save the entire screen contents. Returns a host-created |
|
Restore a previously saved |
|
Run |
|
Read a rectangle of cells (1-based, inclusive). Returns a
|
|
Blit a |
|
Compose synchronous cell, pixel, and cursor updates in one presentation batch. Returns the callback result; nesting is supported, yielding is not. See Pixel screen operations for error and cleanup behavior. |
|
Internal raster size as |
|
Character-cell size as |
|
Capture a 0-based raster rectangle as a |
|
Set one 0-based raster pixel to a native pixel color. |
|
Draw a |
|
Read or set the active text attribute byte. |
|
Hyperlink ID attached to subsequent window writes. |
Screen.supports, Screen.font, Screen.palette, Screen.cursor,
Screen.videoFlags, Screen.color, and Screen.window are getters
that return the helper class so the script can call its static
members.
ScreenError
Immutable ScreenError is Error values expose code, message and toString,
with no public constructor or setters. code preserves the actual portable
native result, including unrecognized integers. Existing binding-owned rejected
regions, unavailable pixel capabilities and capture-storage allocation failures
use IOErr.outOfRange, IOErr.notSupported and IOErr.outOfMemory respectively;
these are binding diagnoses rather than fabricated native results. The owned
message identifies the failed operation/check. Errors hold no console, session,
input or borrowed native resources and remain valid across later calls and GC.
Native operations may change logical state before presentation fails. A returned error therefore does not imply rollback or permit automatic replay. Success reports native acceptance, not completion of a later asynchronous presentation. Restoring a screen snapshot synchronizes its saved Wren font slots whenever native state was applied, including a later presentation failure. Rejected restores leave them unchanged. Snapshots retain their existing owner, geometry and lifetime limits.
Screen.update, Screen.modalRun, CustomCursor.preserve and
VideoFlags.preserve return acquisition/cleanup ScreenError values. Failed
acquisition does not run the callback. Required cleanup is attempted after entry;
a callback’s returned Error takes precedence over cleanup failure, and callback
aborts propagate unchanged. Otherwise cleanup failure replaces the normal callback
result. Update callbacks still cannot yield; modal/preserve callbacks retain their
existing cooperative-yield, Operation and shutdown cleanup behavior. Finalizers
remain native cleanup boundaries and cannot return errors to an absent caller.
Live setters were replaced with explicit methods without aliases. Local staged cursor/flag setters and local offscreen-object APIs are unchanged. The bundled UI checks drawing results, propagates unhandled errors through its existing fiber handling and attempts independent restoration. Unsupported decorative title and pointer operations are skipped; URL-open failure still falls back to copying, with success announced only after copying succeeds. No clipboard protocol or VM authority changed.
Screen.supports
Read-only capability flags (Bool or ScreenError) reflecting what the current
display backend (SDL, X11, Win32, etc.) can do. Unsupported capabilities return
false; failure to acquire the native capability state returns ScreenError.
Scripts that adapt
their output to the backend should branch on these.
| Flag | True when the backend can… |
|---|---|
|
Replace the bitmap font in any slot at runtime. |
|
Select a registered alternate font with the source blink bit. |
|
Select a registered alternate font with the source bright bit. |
|
Render at least sixteen indexed colours, so the source blink bit can also select a bright background. |
|
Mutate the active palette at runtime. |
|
Address individual pixels (pixel-aware backends only — needed for RIP, SIXEL, SkyPix). |
|
Render a non-default cursor shape. |
|
Switch fonts via the SyncTERM font-selection UI. |
|
Set the OS window title. |
|
Advertise native clipboard text read/write support. |
|
Advertise native URL-opening support. |
|
Set the OS window’s class / icon name (X11). |
|
Set the OS window’s icon image. |
|
Address palette indices beyond 16. |
|
Use nearest-neighbour scaling for the pixel-doubled display. |
|
Defer scaling to the OS / window manager. |
|
Inhibit the OS window close button while a BBS session is active. |
The clipboard and URL flags mirror the native capability bits for the current VM’s console, including in menu, picker and connected VMs. They describe advertised backend support, not permission to use an operation or a guarantee that it will succeed. Reading them does not access the clipboard or open a URL.
Screen.window
Operations scoped to the active text window. Cursor position,
character output, line edits, and clearing all act inside the
window’s rectangle. Coordinates are window-relative (1, 1 is the
top-left of the window, not the screen). Invalid bounds, out-of-window
positions and invalid character values remain programmer errors. Native console
failures return ScreenError; an error can follow partial drawing or a committed
state change and does not promise rollback.
| Member | Description |
|---|---|
|
|
|
|
|
Write one character at the cursor. |
|
Write a string at the cursor. |
|
Clear the window with the current attribute. |
|
Clear from cursor to end of line. |
|
Line editing inside the window. |
Screen.font
Per-slot font management. Five slots (0..4) match SyncTERM’s font slot model.
Screen.font[i] reads the font index in slot i. Screen.font[i] = n
selects font n for slot i; assigning slot 0 also resets the
normal slot 1, matching the legacy default-font operation. Slots 1 through 4
are respectively normal, source-bright, source-blink, and source-bright plus
source-blink. VideoFlags.altChars and blinkAltChars enable the two
selectors. Selection happens when text is written, and the resolved internal
font identifier is retained in the cell. Clear, line insertion/deletion, and
scroll operations likewise resolve the font for the blank cells they create.
Later flag or slot changes do not reinterpret existing cells, and
Screen.putRect preserves the already-resolved fonts in its Surface. Use the
Font class (see Font) for the named built-in indices.
Screen.palette
24-bit-RGB palette as 0xRRGGBB integers.
Screen.palette[i] reads an RGB value or returns ScreenError.
Screen.palette.set(i, c) writes an entry and returns null or ScreenError.
Both retain the existing script index range, 0 through 255.
The first 16 entries are the legacy-attribute palette. Read each entry through the indexed API and write it through set.
|
Note
|
term.c, cterm.c, and ripper.c all do their own palette
manipulations. Concurrent edits from a script and from the terminal
code may not compose cleanly.
|
Screen.cursor — CustomCursor
Cursor geometry: scanline range, blink rate, visibility.
The class supports two usage modes:
-
Static (live state): static getters read the cursor and explicit static methods update it immediately.
Screen.cursor.setBlink(false)hides the blink on the next refresh. Each live setter method under the hood does a full read-modify-write of the renderer’s cell cursor state — so a single static write IS atomic for that one field, but a chain of static writes is NOT atomic across fields. The renderer can paint between them, briefly showing intermediate states. For multi-field changes, use the instance path. -
Instance (staged edit):
CustomCursor.new()(orCustomCursor.current) snapshots the current values. Modify the instance’s properties locally, thenapply()to commit as one locked state change regardless of how many fields changed.
CustomCursor.preserve(fn) is a convenience for the common
"snapshot, change, restore" pattern: snapshots the live cursor,
runs fn in a scoped child fiber, then re-applies the snapshot. It returns
fn’s result and restores state before propagating a callback error. Nested
calls, cooperative yields, Operation awaits, and VM shutdown have the same
cleanup semantics as `Screen.modalRun.
Static getters and instance properties: startLine, endLine, range,
blink, visible. Live writes use setStartLine(n), setEndLine(n),
setRange(n), setBlink(b) and setVisible(b), returning null or
ScreenError. Instance setters edit only the local snapshot; apply() returns
null or ScreenError. new(), current and the preset getters return a
snapshot or ScreenError, with no fabricated defaults after a failed read.
Pre-defined snapshots:
| Snapshot | Equivalent legacy code |
|---|---|
|
Mode-default cursor shape (legacy code 2). |
|
Solid block cursor (legacy code 1). |
|
Hidden cursor (legacy code 0). |
A CustomCursor.current snapshot also retains a terminal-owned pixel cursor
opaquely, so applying an unchanged snapshot or using CustomCursor.preserve
restores it. Editing a cursor field or applying a preset selects the ordinary
cell cursor. SkyPix’s native cursor position/colour/timer is owned by the
terminal; it is not a bitmap drawing operation and is excluded from pixel
captures and scrollback rasters.
Screen.videoFlags — VideoFlags
Boolean video-output flags, with the same static-vs-instance pattern
as CustomCursor — including the chained-static-writes
non-atomicity caveat and the VideoFlags.preserve(fn) snapshot
helper. Static reads return Bool or ScreenError; static writes use
setAltChars(b), setNoBright(b), setBgBright(b), setBlinkAltChars(b),
setNoBlink(b) and setLineGraphicsExpand(b), returning null or
ScreenError. new() and current return a snapshot or ScreenError;
instance setters remain local and apply() returns null or ScreenError.
expand remains read-only.
| Property | Meaning |
|---|---|
|
Let source attribute bit 3 select font slot 2 instead of slot 1 (and slot 4 instead of slot 3 when bit 7 also selects a font). |
|
Prevent source attribute bit 3 from selecting a bright foreground palette entry. This does not change the independent bold style flag or the source bit’s use as an alternate-font selector. |
|
Treat the high-intensity bit on the background nibble as a bright background. Its blink and alternate-font meanings remain independently controlled. |
|
Let source attribute bit 7 select font slot 3 instead of slot 1 (or slot 4 when bit 3 also selects a font). |
|
Prevent source attribute bit 7 from blinking. The same bit may still select a bright background or alternate font. |
|
Read-only. True when the backend is using
a cell one pixel wider than its font. The
extra column is blank unless
|
|
Apply the right-edge duplication to box-
drawing glyph indices in the 0xC0..0xDF range
when |
Screen.color — Color
Build and inspect 24-bit RGB values. Returned values are raw
0xRRGGBB without the high RGB-mode bit; the bit is added when
writing into a Cell field via fgRgb= / bgRgb=.
| Method | Description |
|---|---|
|
Pack three 8-bit components into a uint32. |
|
Decode an attribute byte into |
|
Map 24-bit RGB foreground and background colours to the nearest legacy
text attribute byte in that same active palette. Matching uses YCoCg
distance; bright foreground or background candidates are included only
when the current video flags give those attribute bits a colour meaning.
Returns |
Pixel graphics
The pixel API exposes ciolib’s internal raster directly in the connected,
menu, and picker VMs. Raster coordinates are 0-based and refer to the
unscaled video-mode surface, not operating-system window coordinates. User
display scaling does not change these coordinates. Screen.pixelSize
includes any raster rows that do not belong to a complete text cell.
Pixel buffers, masks, and blit descriptors are foreign objects owned by the VM that created them. Their native allocations are released by Wren’s garbage collector. They cannot be passed between SyncTERM’s isolated VMs.
PixelColor
Pixel buffers retain ciolib’s native colour words. A native word is either a
palette index in 0..65535 or a 24-bit RGB value tagged with
CIOLIB_COLOR_RGB. A plain 0xRRGGBB number is therefore not necessarily a
native RGB colour; construct it with PixelColor.rgb before placing it in a
buffer.
| Member | Description |
|---|---|
|
Tag a raw |
|
Construct a native palette colour. |
|
Return |
|
Return raw |
|
Return the index for a palette colour, or |
|
Return raw |
All methods reject fractional, negative, out-of-range, or malformed native colour values by aborting the calling fiber.
PixelBuffer
PixelBuffer is a row-major Sequence of native colour words. Linear index
i is (y * width) + x. Ordinary reads, writes, fills, and blits operate on
the native array directly.
| Member | Description |
|---|---|
|
Allocate a buffer, initially palette index 0 or |
|
Dimensions and total pixel count. |
|
Read or write one row-major native colour word. |
|
Read or write one 0-based buffer coordinate. |
|
Fill the primary plane. |
|
Copy the buffer and both blink-phase planes. Returns |
|
Composite another PixelBuffer into this buffer, using PixelBlit and an optional PixelMask. Returns null on success or PixelError. Available in all three VMs independently of Screen.supports.pixels. |
|
Import packed RGB bytes in |
|
Export the primary plane as packed RGB bytes. Palette words are resolved through the active palette. |
|
Inspect the optional alternate blink-phase plane. |
|
Read or set a pixel’s Boolean blink rate. False selects slow blink. The first true bit allocates a packed rate mask and, if needed, an alternate plane initialized from the primary colours. Clearing the alternate plane releases the mask. Edits to individual colours preserve the pixel’s chosen rate. |
|
Create or update the alternate plane. Its first creation copies the complete primary plane before applying the requested change. |
|
Export the alternate plane as packed RGB, or return |
|
Remove the explicit alternate plane. Native drawing then uses the primary plane for both blink phases. |
|
Decode the first P3 or P6 PPM image. Values use PPM’s BT.709 transfer function and are converted to 8-bit sRGB; maximum values through 65535 are accepted. |
|
Decode JPEG XL. Returns |
|
|
Decoder source may be a binary Wren String or a readable, consent-bounded
File. A File is mapped and decoded directly; SyncTERM does not
first copy its contents into a Wren string. Decoded images contain only a
primary plane.
Capture and clone preserve the primary and alternate colours and the packed blink-rate mask. RGB24 export is a conversion and resolves palette references at export time; use native indexing when palette identity must survive a round trip.
Buffer blits use the existing descriptor’s source rectangle, signed destination origin, mask origin, flips and independent integer scaling. Zero source extents mean the remainder, resolved on each call without changing the descriptor. The destination is clipped; masks control transparency and there is no alpha blending. Native palette words and tagged RGB values are copied without palette resolution. Source, mask and descriptor remain unchanged, except that a self-blit also changes its source because source and destination are the same object.
The two colour planes and the optional blink-rate bits are preserved. A source alternate plane causes the destination to acquire one, initially copying its whole primary plane; unpainted pixels keep those values. Without a source alternate plane, primary pixels supply both destination phases. Native plane creation happens before clipping/mask drawing, so a blit that paints no pixels can still create a plane or fail its allocation. Overlapping self-blits snapshot the source colours and rate bits before drawing. Distinct-buffer blits allocate missing alternate or rate storage as needed. No screen, file or network operation is performed, and no arguments are retained after the synchronous call.
Wrong argument types abort the calling fiber. The masked overload requires a PixelMask; use the two-argument overload rather than null for an unmasked blit. Invalid source/mask regions, including empty source regions, return PixelError with IOErr.outOfRange. An empty destination returns the native IOErr.invalidArgument. Native allocation/validation failures preserve their actual code. Returned errors leave destination pixels and plane ownership unchanged.
PixelError
Immutable PixelError is Error values expose code, message and toString,
with no public constructor or setters. code retains the actual native integer
status, including unrecognized values; binding-rejected source/mask regions use
IOErr.outOfRange. The owned message identifies the operation and reason. Errors
retain no buffer, mask, descriptor or console resources and survive later calls
and garbage collection independently. This result type applies to PixelBuffer.blit;
other existing pixel operations retain their documented result contracts.
PixelMask
PixelMask is a row-major Sequence of Bool values. A true bit draws its
source pixel; a false bit leaves the destination unchanged.
| Member | Description |
|---|---|
|
Allocate a false-filled mask, or initialize every bit to |
|
Import continuous row-major packed bits, most-significant bit first. The
string length must be |
|
Decode a P1 or P4 PBM from a binary |
|
Dimensions and linear Boolean access. |
|
0-based coordinate access and bulk fill. |
|
Export continuous row-major packed bits, most-significant bit first. |
PixelBlit
PixelBlit is a reusable mutable descriptor. PixelBlit.new() selects the
whole source, destination (0, 0), scale (1, 1), mask origin (0, 0), and
no mirroring.
| Member | Description |
|---|---|
|
0-based source origin. Values must be non-negative integers. |
|
Source extent. Zero means the remainder of that source dimension, evaluated when the descriptor is used. |
|
Signed 0-based destination origin. Negative values request clipping at the left or top edge. |
|
Positive integer nearest-neighbour scale factors. |
|
0-based mask origin. The mask region has the same unscaled extent as the source region. |
|
Mirror the selected source and corresponding mask region before scaling. |
Descriptor setters reject wrong types, fractional values, out-of-range coordinates, and zero scale by aborting the calling fiber. Reusing a descriptor does not retain a source, mask, or destination reference.
Pixel screen operations
Screen.update(fn) composes synchronous cell, pixel, and cursor changes as
one presentation batch. The callback runs immediately, may nest another
Screen.update, and returns its result. Ordinary presentation, including
blink and expose repaint events, waits until the outermost update ends.
The batch closes before a callback error is propagated; yielding from the
callback is rejected and also closes it. This groups drawing; it does not
roll back changes on error. Do not wait for input, open a modal, switch
screen modes, or run an event loop inside the callback. Native code that
explicitly forces a presentation can still bypass batching.
Use this when text cells provide a graphical UI’s metadata and base glyphs,
with pixel operations completing its appearance. Screen.readPixels can
inspect the composed raster inside the batch without presenting it.
Screen.readPixels(x, y, width, height) captures a positive-sized rectangle
and returns a new PixelBuffer. Passing force=true first requests a full
refresh from text vmem before capture; use the default false when capturing
pixel changes that have already been drawn. Capture returns ScreenError for an unsupported backend
(IOErr.notSupported), an out-of-screen rectangle (IOErr.outOfRange), or
allocation failure (IOErr.outOfMemory).
Screen.setPixel(x, y, color) and both Screen.blitPixels overloads return
null on success or ScreenError. A blit validates the source and optional mask regions, clips the scaled
destination to the screen, and returns null without drawing when the entire
destination is off-screen. Scaling is nearest-neighbour and independent in
X and Y. If the source has no alternate plane, its primary pixels are used
for both destination blink phases. Masks are the transparency mechanism;
there is no alpha blending.
Blitting uses the supplied native buffers directly and provisions missing rate storage as needed. Keep decoded or constructed buffers and descriptors for repeated sprite draws rather than rebuilding RGB strings. Capture, decode, clone, RGB24 conversion, and first alternate-plane creation do allocate.
var sprite = PixelBuffer.fromPpm(ppmBytes)
var mask = PixelMask.fromPbm(pbmBytes)
var blit = PixelBlit.new()
blit.destinationX = 40
blit.destinationY = 24
blit.scaleX = 2
blit.scaleY = 2
blit.flipX = true
if (sprite != null && Screen.supports.pixels) {
Screen.blitPixels(sprite, mask, blit)
}
Invalid argument types, fractional or out-of-range integers, invalid native
colours, malformed packed lengths, and invalid descriptor fields abort the
calling fiber. Constructors also abort on allocation failure because Wren
foreign constructors cannot return null; offscreen factories, decoders and clone return null for recoverable
allocation or decoding failure. Screen capture returns ScreenError.
The alternate-plane mutators leave the buffer unchanged and abort the calling
fiber if the plane’s first allocation fails.
Input
Unified blocking and nonblocking reader for keyboard and mouse events.
| Member | Description |
|---|---|
|
Block until the next event; return |
|
Wait up to |
|
Return immediately with the next pending event, or |
|
Push an exact copy of a |
|
Synthesize a physical key edge. |
|
Hand off to SyncTERM’s full-screen drag-select gesture. This uses the
current screen dimensions and does not depend on a connected terminal.
In a live RIP3 connection, selection uses the selected text window’s grid,
font and pixel origin. Suspended terminal UI continues to use its own screen.
The default is line selection; |
|
Show or hide the mouse cursor; return |
|
Read or set the bitmask of |
|
Single-event toggles for the same mask. |
|
Push |
Once a process-close request has been read, Input.next(), Input.next(ms),
and Input.poll() continue returning Key.quit until SyncTERM exits. UI code
should use App, which reserves the event for call-stack unwinding and
supports the explicit Widget.atExit exception.
For posting a synthetic resume to a parked fiber (the wake
mechanism that Hook.onInput-style callbacks use to nudge a UI
fiber), see Wake.
Claims and wakes are stored independently for each VM. The persistent menu
and picker currently use the synchronous Input.next path; the
connected-session owner loop is responsible for invoking claim dispatch and
draining wakes. Registering a claim alone does not create a background pump.
KeyEvent
Carries committed Unicode text, a logical named key, a numeric keypad byte,
or a DoorWay scan. These meanings remain distinct. Display font selection
never determines input text; connection encoding is applied only when an event
is forwarded through CTerm.sendKey.
| Member | Description |
|---|---|
|
Construct a named |
|
Construct from exactly one strictly valid UTF-8 scalar. NUL and non-BMP scalars are supported. Empty strings, malformed bytes, and multiple scalars are rejected. No NFC normalization or grapheme segmentation occurs. |
|
Construct an explicit numeric keypad byte, from 0 through 255. |
|
Construct a DoorWay scan with an explicit enhanced-key flag. |
|
Unicode scalar for committed text, a named |
|
Full event-time |
|
Original committed Unicode scalar, or |
|
Exact UTF-8 committed scalar, or |
|
Explicit numeric keypad byte, or |
|
DoorWay scan and Bool flag, or |
|
Compare logical key and modifiers, ignoring Caps Lock and Num Lock only. |
Alt+Keypad entry without a leading zero remains a raw byte in every Wren VM. Leading-zero Unicode entry produces committed Unicode text. The terminal resolves raw bytes using its active remote encoding; Wren UI code must not reinterpret them through the selected display font.
Wren Strings can contain arbitrary bytes. count counts decoded scalars in
valid UTF-8, while integer String and codePoints subscripts use byte offsets.
Neither count == 1 nor text[0] validates a Unicode scalar. The native text
constructor validates the entire byte sequence, including embedded NUL.
Input.unget preserves the full event and its native source type. Forwarding
through CTerm.sendKey uses that source, including text, modifiers, raw bytes,
physical edges and DoorWay scans; it does not re-enter key hooks.
PhysicalKeyEvent
Represents one physical key press or release edge using the same evdev key
code namespace as CTerm’s physical-key reporting protocol. Returned by
Input.next() / Input.poll(), passed to Input.pushClaim handlers, and
passed to Hook.onPhysicalKey callbacks.
Physical events remain separate from logical keys and committed text. The
host does not synthesize a second logical event from a physical press. A
backend may subsequently deliver a translated key or committed text; scripts
must choose the appropriate stream for a shortcut rather than bind both.
Repeated presses retain repeat; releases remain explicit physical events.
| Member | Description |
|---|---|
|
Construct a synthetic physical-key edge. |
|
evdev key code number. |
|
|
|
Event-time modifier mask: Shift=1, Control=2, Alt=4, GUI=8, Caps Lock=16, and Num Lock=32. |
|
|
MouseEvent
Represents one normalized SyncTERM mouse event. Returned by
Input.next() / Input.poll(), passed to Input.pushClaim
handlers, and passed to Hook.onMouse callbacks — every mouse
surface uses this same shape.
| Member | Description |
|---|---|
|
Construct from raw fields. Five overloads dispatched by arity.
Omitted |
|
Construct a fully explicit synthetic event including internal raster coordinates. This is a named factory rather than a sixth overloaded constructor so pixel and cell coordinates cannot be confused by arity. |
|
The fully explicit factory, including signed wheel-axis values. |
|
Mouse event type code. |
|
Snapshot of the button-state bitmask at the moment the event
fired (the |
|
Event-time keyboard modifier mask, using the same bits as
|
|
Click-down coordinates (1-based). |
|
Release coordinates (1-based). |
|
Click-down coordinates in the 0-based internal raster. Native backends that
cannot report pixel positions use |
|
Release coordinates in the 0-based internal raster, with the same |
|
Signed native wheel magnitude. A vertical event has |
Mouse event constants
Mouse.button1* through Mouse.button5* identify left, middle, right, X1,
and X2 events. Each family occupies nine stable values in the order Press,
Release, Click, double/triple/quadruple Click, DragStart, DragMove, and DragEnd.
Native translation currently produces Press, Release, Click, DragStart,
DragMove, and DragEnd; multi-click values remain available to synthetic input.
Mouse.wheelUp, wheelDown, wheelLeft, and wheelRight are values 46
through 49. The older wheel*Press and wheel*Click names remain aliases.
ClaimHandle
Returned from Input.pushClaim. Drop the claim by calling
pop().
| Member | Description |
|---|---|
|
Remove the claim entry from the stack. Idempotent — stale handles (after a same-fiber re-push bumped the entry’s id, or after another path popped it, or after the foreign finalizer ran) no-op silently. The C-side foreign finalizer also pops on GC, so a forgotten handle still cleans up — but explicit pop is cheaper and more predictable. |
Wake
Owner-thread fiber-resume primitive. Wake.post(fiber, value) queues a
synthetic resume of fiber, delivering value as the return of
its next Fiber.yield(). It is held in that VM’s FIFO and delivered by the
owning host’s next explicit wake drain — never in the middle of the current
foreign call. It may be called while executing that VM on its owner thread
(hooks, claim handlers, and worker fibers). value may be any Wren
object — the deliverer pins it as a WrenHandle until delivery,
then loads it into the fiber’s resumed-value slot. Multiple posts
queue up; each becomes one resumption in arrival order.
| Method | Description |
|---|---|
|
Queue a resume. Returns immediately; the wake is dispatched on
the next main-loop drain. Convention: pass a discriminated value
the fiber’s main-loop demuxer can recognise (a foreign
|
Key
Named key identifiers occupy 0x110000..0x11ffff, above the Unicode scalar
range. They identify keys independently of modifiers. Committed text uses
its Unicode scalar directly; for example, U+0100 and Key.up are distinct.
Key.quit is a separate sticky host shutdown marker at 0x120000.
Available names are escape, enter, backspace, tab, delChar, up,
down, left, right, insert, delete, home, end, pageUp,
pageDown, and f1 through f12. delChar represents a native ASCII DEL
key, separately from the dedicated Delete key. Modified keys use the same
identifier plus an explicit modifier mask; for example,
event.matches(Key.tab, Mod.shift) tests Shift-Tab.
Mod
Modifier constants are shift=1, control=2, alt=4, gui=8,
capsLock=16, and numLock=32. command selects GUI on macOS and Alt
elsewhere for bundled application command policy. Event masks retain the
actual modifiers reported by the backend. Applications should match the full
mask they intend; Caps Lock and Num Lock may be ignored for shortcuts.
Clipboard
| Member | Description |
|---|---|
|
Read the system clipboard as an NFC string, or return |
|
Write a string to the system clipboard; return |
Codepage
Enum-style class identifying a character-set encoding. Returned by
Font.codepage and Font.codepageOf(i) to tell scripts which
legacy character encoding a selected font uses. Cells expose Unicode text;
these values describe explicit conversions at a legacy byte boundary.
Codepage.encodes_(s) accepts exactly one Unicode codepoint and reports
whether the codepage of the selected primary font (Screen.font[0]) can
encode it. It returns false when that font is unavailable. It does not consult the process locale.
Codepage.encodeByte(codepage, scalar) explicitly encodes one Unicode scalar
using the chosen legacy codepage. The scalar is an integer Number from 0 through
0x10FFFF, excluding surrogates (0xD800 through 0xDFFF), rather than a String.
Return a byte Number from 0 through 255, or null when that scalar is unmappable.
Native aliases choose the first mapping in the legacy table. There is no
normalization, replacement character or dependency on the selected font,
connection encoding or locale. For example,
Codepage.encodeByte(Codepage.cp1251, 0x0410) returns 0xC0.
Wrong types, nonfinite/fractional Numbers, invalid codepages and invalid scalars
abort the calling Fiber.
Codepage.decodeByte(codepage, byte) explicitly decodes one legacy display
byte to a Unicode String. The codepage must be one of the constants below
and the byte an integer from 0 through 255. It uses graphical character
meanings for control positions: CP437 byte 1 becomes ☺, byte 0xB3
becomes │, and byte 0 remains NUL. Invalid arguments abort the calling
fiber. The result is independent of the selected font, connection encoding,
locale, and output mode. For example, a CP437 character picker can assign
cell.ch = Codepage.decodeByte(Codepage.cp437, value).
Codepage.decodeByte(codepage, byte, graphicControls) adds a strict Bool choice
of native decoding mode. true matches the two-argument display form; false
selects semantic control meanings. For CP437, byte 1 then returns U+0001 rather
than ☺, byte 0x7F returns DEL rather than ⌂, and byte 0x7C returns |
rather than ¦. The native tables determine the remaining mappings; byte 0
can return a one-byte NUL String. Invalid arguments abort the calling Fiber.
Encoding and decoding are not promised to be inverse operations for every table.
Codepage.brokenVertical(codepage) returns the native compatibility Bool for a
valid Codepage constant. It describes the broken-bar display glyph at byte
0x7C, not gaps in box-drawing lines. A _b suffix identifies an explicit
broken-vertical variant; some other codepages, including CP437, also have the
flag. A false flag does not imply that an arbitrary loaded raster has an
unbroken bar. Invalid arguments abort the calling Fiber.
These conversion and metadata methods are synchronous and available in all three VMs. They retain no inputs and grant no file or terminal authority.
| Constant | Index | Description |
|---|---|---|
|
0 |
IBM PC code page 437 — English plus box-drawing. The default for traditional ANSI BBSes. |
|
1 |
Windows-1251 — Cyrillic (Russian, Bulgarian, Ukrainian, etc.) in a "swiss" font variant. |
|
2 |
Windows-1251 with the broken-vertical glyph variant. |
|
3 |
KOI8-R — Russian Cyrillic. Common on 1990s Russian Linux/Unix systems. |
|
4 |
ISO-8859-2 (Latin-2) — Central European (Polish, Czech, Hungarian, …). |
|
5 |
ISO-8859-4 (Latin-4) — Northern European / older Baltic. 9-bit-mapped wide-glyph variant. |
|
6 |
CP866 — Russian DOS, "(c)" modified variant. |
|
7 |
ISO-8859-9 (Latin-5) — Turkish. |
|
8 |
ISO-8859-8 — Hebrew. |
|
9 |
KOI8-U — Ukrainian Cyrillic. |
|
10 |
ISO-8859-15 (Latin-9) — Western European with the Euro sign. |
|
11 |
ISO-8859-5 — Latin/Cyrillic. |
|
12 |
CP850 — Multilingual Latin-1 (DOS Western European). |
|
13 |
CP850 with the broken-vertical glyph variant. |
|
14 |
CP865 — Nordic DOS (Danish, Norwegian). |
|
15 |
CP865 with the broken-vertical glyph variant. |
|
16 |
ISO-8859-7 — Greek. |
|
17 |
ISO-8859-1 (Latin-1) — Western European, classic Unix default. |
|
18 |
CP866 — Russian DOS, second modified variant. |
|
19 |
CP866-U — Ukrainian variant. |
|
20 |
CP1131 — Belarusian DOS. |
|
21 |
ARMSCII-8 — Armenian. |
|
22 |
HAIK-8 — older Armenian set; used with the ARMSCII-8 screen map. |
|
23 |
ATASCII — Atari 8-bit native character set. |
|
24 |
PETSCII (uppercase/graphics mode) — Commodore 64/128 default. |
|
25 |
PETSCII (lowercase/shifted mode) — Commodore 64/128 after a Shift+Commodore key. |
|
26 |
UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal. |
|
27 |
Prestel separated mosaics — block mosaics with gaps between cells. |
|
28 |
Atari ST GEM character set. |
Cell
Wraps one st_console_cell: its resolved drawable glyph/font, colours, source
attributes, flags, and hyperlink. Read a Surface through Screen.readRect,
edit its cells, and blit it back through Screen.putRect.
The three-argument Surface.cellAt(x, y, cell) overload can retarget
the same Cell object to successive cells of a Surface. This changes
what storage that object refers to; it does not copy cell contents.
| Member | Description |
|---|---|
|
Construct an empty cell. |
|
Character as one NFC extended grapheme cluster. Assignment accepts exactly
one valid cluster, normalizes it to NFC, then resolves one drawable glyph in
the selected font and Unicode fallback font. An unsupported cluster is one
missing glyph, including emoji modifier sequences that do not use ZWJ.
+
Unlike ordinary text output and |
|
Font catalog selector at the Wren boundary. The selected and actual glyph font identifiers are retained separately in stored cells. Assignment resolves the current Unicode text in the new font and its fallback. Cell creation, character assignment, and font changes perform no legacy byte conversion. |
|
Legacy attribute byte (foreground in low nibble, background in
high nibble, plus source bright/blink bits). Setting it marks both
colours as legacy-derived. The active |
|
Source attribute bit 3. This is distinct from the |
|
Blink bit. |
|
Selects the fast cadence when |
|
Draws a one-pixel foreground line across the centre row of an odd-height cell or the lower middle row of an even-height cell. |
|
Draws a foreground line across the top pixel row of the cell. |
|
Draws the bottom pixel row and the row two pixels above it when present. Enabling either underline style replaces the other. |
|
Read/write Boolean drawing styles. Single underline spans the inked rows of the font’s underscore; bold thickens the glyph; reverse exchanges foreground/background when drawn; conceal hides the glyph unless its retained reveal flag is set. Bold is independent of the source-bright attribute. All style setters require Bool; wrong types abort rather than being ignored. |
|
Read or replace the drawing styles together using |
|
Read-only Booleans reporting retained SAA5050/teletext presentation state: serial-attribute mode, double height, reveal concealed content, and separated mosaics. These are observations, not independent serial-attribute controls. |
|
Read-only retained seven-bit source control as a Number, or null when none is recorded. Changing serial attributes requires editing the source stream and reconstructing the affected line or screen; Cell does not provide that operation. |
|
Read-only. |
|
Foreground / background palette indices. |
|
Foreground / background as 24-bit RGB. Setters change only the selected colour channel and its legacy-derived marker; source bright/blink and all other cell state remain intact. |
|
Hyperlink ID attached to this cell. |
|
Structural equality of every content field. This is not a |
c |
c.eqContent(template) }`).
+
Returns |
CellStyle
Named masks for Cell.styleFlags, available in all script VMs. bright is
0x400000, blink is 2, underline is 0x10000, bold is 0x20000,
reverse is 0x40000, conceal is 4, fastBlink is 0x2000000, strikethrough is 0x4000000, doubleUnderline is 0x100000, and overline is 0x200000.
all is their union (0x6770006).
These native bit values fit Wren’s ordinary bitwise operators. Renderer state,
serial attributes and pixel-graphics ownership are excluded from this mask.
cell.bold = true
cell.styleFlags = CellStyle.bold | CellStyle.underline
Surface
A width × height grid of Cells backed by a contiguous
st_console_cell buffer. Surface is Sequence, so the linear [i]
subscript, count, and the standard sequence helpers (each,
where, map, all, any, reduce, join, take, skip,
toList, …) all work — handy for "tell me where any 'X' lives"
without switching to 2D indexing. Linear order is row-major:
buf[y * width + x].
Screen.readRect returns a Surface sized to the requested rect, with optional
pixel strips for rows containing graphics. Captured strips retain RGB colours
and both blink phases; plain-text rows allocate no pixel storage. Rectangle
copies, including clipped and overlapping self-copies, preserve those strips.
Glyph edits and text fills replace the affected cells' raster content; style
edits do not recolour captured pixels. Screen.putRect restores cells and
pixel-marked regions in one presentation batch, so UI overlays remain visible. The
UI library uses Surfaces as per-widget backbuffers and composites
them into a screen-sized backbuffer Surface that’s blitted once
per frame.
| Member | Description |
|---|---|
|
Allocate a fresh Surface of the given size. Cells start as spaces using the current screen style. |
|
Dimensions in cells. |
|
|
|
Linear-indexed read of the cell at offset |
|
2D-indexed |
|
Retarget an existing |
|
Sequence protocol — yields each cell linearly in row-major order
(the cell at |
|
Sequence-of-Sequence view, outer-by-y. |
|
Sequence-of-Sequence view, outer-by-x. |
|
Detect an ASCII HTTP, HTTPS, FTP, FTPS, or bare |
|
Paste a source Surface into this Surface at |
|
Bulk-fill the intersection of |
|
Debug-only string form, e.g. |
Scrollback
Read-only logical access to the active cterm scrollback ring. The ring stays
in its native wrapped representation: these methods do not append rows,
rotate storage, or change CTerm.scrollbackStart / scrollbackPos.
SkyPix pixel scrolling can leave an unfinished strip between complete rows
and the live screen. Reads compose it into rows aligned at the live boundary,
within the configured capacity. A change of geometry finishes the strip in its original grid. Any padding precedes that run of rows.
Pixel colours and both phases were captured when they left the screen, so a
later palette change does not recolour the pending strip. Row copies do not
flush it. Aligned cell text is preserved; a fractional row view carries pixels
with blank cell metadata rather than stale text at the wrong position.
| Member | Description |
|---|---|
|
Current projection width in cells, or zero when no ring exists. |
|
Number of retained logical history rows, or zero when no ring exists. |
|
Return |
|
Return an owned, one-row Surface at its original width, with font, glyph,
hyperlink and available bitmap data. The indexes match |
|
Copy whole logical history rows, oldest-first, into an owned
|
Font
A "font" in SyncTERM is one of 257 indexed slots, each a complete
glyph table for a particular character set or display style. Slots
0–45 ship with built-in fonts, covering the codepages enumerated by
Codepage plus several Amiga and 8-bit display styles.
Slots 46+ hold configured or remotely supplied fonts. Font.count
reports the current catalog extent; use Font.available(i) to determine
whether a catalog slot has a bitmap for the active cell dimensions.
Application UI uses system CP437, independently of the connection’s font.
Font.cp437English remains the system font for Wren drawing even when SkyPix
or a remote command replaces terminal slot zero. The status bar, online menu,
file picker and transfer dialogs use it; built-in/loaded theme snapshots resolve
explicit font choices to system CP437. SkyPix keeps the screen mode’s system
cell grid independent of the Amiga strike: at 640x200 UI uses 8x8 CP437 even
with Diamond 20. The console scales a system strike only when the chosen
screen-mode cell dimensions have no exact system strike. Text
backends retain Unicode presentation and use their external terminal’s font.
The Font class itself only exposes named constants for the most
useful slots; every slot is reachable numerically through
Screen.font[i] regardless. The full built-in table follows.
| Named constant | Index | Slot description |
|---|---|---|
|
0 |
Codepage 437 English (default). |
1 |
Codepage 1251 Cyrillic, "swiss" variant. |
|
2 |
Russian KOI8-R. |
|
3 |
ISO-8859-2 Central European. |
|
4 |
ISO-8859-4 Baltic wide (VGA 9-bit mapped). |
|
5 |
Codepage 866 (c) Russian. |
|
6 |
ISO-8859-9 Turkish. |
|
7 |
HAIK-8 (used with the ARMSCII-8 screen map). |
|
8 |
ISO-8859-8 Hebrew. |
|
9 |
Ukrainian KOI8-U. |
|
10 |
ISO-8859-15 West European, "thin" variant. |
|
11 |
ISO-8859-4 Baltic (VGA 9-bit mapped). |
|
12 |
Russian KOI8-R, alternate (b) variant. |
|
13 |
ISO-8859-4 Baltic wide. |
|
14 |
ISO-8859-5 Cyrillic. |
|
15 |
ARMSCII-8 (Armenian). |
|
16 |
ISO-8859-15 West European. |
|
17 |
Codepage 850 Multilingual Latin I, "thin". |
|
18 |
Codepage 850 Multilingual Latin I. |
|
19 |
Codepage 865 Norwegian, "thin". |
|
20 |
Codepage 1251 Cyrillic. |
|
21 |
ISO-8859-7 Greek. |
|
22 |
Russian KOI8-R, alternate (c) variant. |
|
23 |
ISO-8859-4 Baltic. |
|
24 |
ISO-8859-1 West European. |
|
25 |
Codepage 866 Russian. |
|
26 |
Codepage 437 English, "thin" variant. |
|
27 |
Codepage 866 (b) Russian. |
|
28 |
Codepage 865 Norwegian. |
|
29 |
Ukrainian CP866-U. |
|
30 |
ISO-8859-1 West European, "thin". |
|
31 |
Codepage 1131 Belarusian, "swiss". |
|
|
32 |
Commodore 64 (uppercase / graphics). |
|
33 |
Commodore 64 (lowercase / shifted). |
|
34 |
Commodore 128 (uppercase / graphics). |
|
35 |
Commodore 128 (lowercase / shifted). |
|
36 |
Atari 8-bit. |
|
37 |
P0T NOoDLE — Amiga BBS classic. |
|
38 |
mO’sOul — Amiga BBS classic. |
|
39 |
MicroKnight Plus — Amiga. |
|
40 |
Topaz Plus — Amiga. |
|
41 |
MicroKnight — Amiga. |
|
42 |
Topaz — Amiga Workbench font. |
|
43 |
Prestel — UK Viewdata mosaic. |
|
44 |
Atari ST GEM. |
|
45 |
RIPterm — RIP graphics terminal font. |
The "thin" variants are the same character set rendered with thinner strokes in the VGA BIOS style. A "swiss" variant uses a Helvetica-style sans rendering. An "(a)" / "(b)" / "(c)" annotation distinguishes bundled font variants that use the same codepage encoding.
| Method | Description |
|---|---|
|
Human-readable font name for slot |
|
Current catalog extent. |
|
|
|
Native static broken-vertical compatibility flag of a built-in selector (0 through 45). Available in all three VMs, even if its bitmap is unavailable. This describes the bundled catalog entry independently of configured, downloaded or session raster replacements; it does not inspect a live font. Custom selectors, wrong types and nonfinite/fractional/out-of-range Numbers abort the calling Fiber. |
|
Actual mapping of the font selected in |
|
Actual mapping of the font selected in script-output
slot |
|
Actual mapping of the registered catalog
selector (0 through 255), or |
|
Register a 256-glyph bitmap using the terminal’s current
|
|
Register with an explicit |
Both load forms return the allocated selector (46 through 255), a FileError
for a file access/read failure, or a FontError. Loading requires
an active terminal and ScreenSupports.loadableFonts. It reads an actual
readable File grant belonging to the calling VM; path Strings are rejected.
Revoked/stale read authority returns FileError with IOErr.permissionDenied.
Loading neither selects the font nor changes the File’s stream position, consumes
its grant, or saves settings. The bitmap remains usable after the File is closed
or collected. Failed loads publish no catalog entry. Configured selectors and
selectors occupied by downloaded font variants are reserved.
The default mapping is captured at load time from CTerm.codepage; it does not
follow Screen.font, the process locale, or later terminal encoding changes.
The explicit overload accepts the serialized Codepage enum, not a text label
or UTF-8 encoding sentinel. An unsupported mapping is a font failure. Font files
contain raw bitmap bytes, never normalized text. Their dimensions must match the
current console cell, with exactly 256 glyphs.
var selector = Font.load(file, Codepage.cp1251)
if (selector is Error) return selector
CTerm.font[0] = selector
FontError
FontError is Error reports font failures separately from file failures. It has
read-only code, nativeCode, message, and toString properties and no public
constructor. nativeCode preserves the underlying portable native I/O status,
or zero when no native operation failed. Its diagnostic starts with FontError.
| FontErr value | Code | Meaning |
|---|---|---|
|
1 |
No active terminal or the backend cannot load/select fonts. |
|
2 |
The bitmap size or dimensions are invalid. |
|
3 |
No bitmap mapping is available for the codepage. |
|
4 |
No free custom selector remains. |
|
5 |
The requested selector has no available registration. |
|
6 |
Another native font/registration operation failed. |
Wrong types, inexact/out-of-range numbers, invalid codepage enums, invalid assignment indices, and invalid masks are programmer errors and abort the calling Fiber. Recoverable load failures are returned as Error values.
Hyperlinks
Typed-ID lookup table over the application-lifetime hyperlink registry. It
is available to the menu and connected VMs, but not the file-picker VM.
Despite the
[id] / containsKey(id) shape, this is not a Map — there is no
keys / values / count / iteration. IDs flow into a script from
add() returns or from Cell.hyperlinkId on cells under the cursor;
scripts can’t enumerate the ID space. IDs range from 1 through 65535 and zero
means no hyperlink. IDs attached to live console cells, Wren Cell/Surface
storage, terminal scrollback, or retained session history remain stable. If
the registry fills, IDs not reachable from those roots may be reclaimed and
reused. Consequently, scripts should resolve or attach an ID promptly rather
than treating a detached number as permanent application-lifetime storage.
| Member | Description |
|---|---|
|
URI string for |
|
|
|
Allocate a hyperlink ID for |
|
Parameter string for |
To attach hyperlinks to text, allocate an ID and assign it to
Screen.hyperlinkId before writing through Screen.window.print.
Console
Read-only access to the current VM’s always-on print/error log buffer. The buffer has 1024 entries of up to 8 KB each; older entries are evicted in FIFO order. Sequence numbers are monotonic across the VM’s lifetime, including across eviction, so an incremental "show only entries newer than X" reader works correctly even after the ring has wrapped.
| Member | Description |
|---|---|
|
Number of valid entries currently in the ring. |
|
Monotonic count of entries ever written. Survives |
|
Entry with monotonic sequence |
|
Drop all entries. |
|
Snapshot the current |
|
Wren iteration protocol — works in |
|
|
e |
e[1] == LogSource.runtimeError
}.toList
----
+
|
LogSource
Enum values for the source field on Console entries.
-
LogSource.print(0) — scriptSystem.print. -
LogSource.compileError(1) — Wren compile diagnostic. -
LogSource.runtimeError(2) — Wren runtime error message. -
LogSource.stackFrame(3) — one frame of a runtime-error stack trace.
REPL
Primitive for the immediate-mode REPL. Most scripts will not use
this directly; the embedded wren_console script wraps it.
| Method | Description |
|---|---|
|
Compile and run |
|
As above, in |
|
|
|
List of every module name currently loaded in the VM (including
|
The [value] wrapper for expressions distinguishes "this was a
statement" from "this was an expression whose value is `null`".
Runtime errors propagate normally. Wrap the call in
Fiber.new {}.try() to catch them.
Session
Session.current is the stable VM-scoped view of the connected session, or
null in menu/picker VMs and during session teardown. Session lifetime holds
belong to independent SessionLease objects, separately from terminal state.
| Member | Description |
|---|---|
|
Stable read-only Profile snapshot of the connection configuration. Its
|
|
Captured connection name. |
|
Captured directory ID and |
|
Captured entry timestamps and connection count. These are metadata, not editable Profile fields. |
|
Run an installed DOS door terminal on the active connection. Use an absolute
|
|
Acquire a lease that keeps the session pumping after shell EOF while its owner has auxiliary work. A lease cannot release another owner’s hold. Native pending SFTP requests also keep their work alive independently. |
|
Run |
|
Number of live script leases; excludes native pending requests. |
|
Release this hold. Returns |
|
Whether this lease has been released explicitly, by GC, or during shutdown. |
Install door terminals and their data files under the SyncTERM data
directory’s dosbox-x subdirectory. Connected DOS sessions mount it
read-only as S:. Configure clients that save settings there from
Settings > DOS Shell. Any graphics profile can launch a local terminal on
a bitmap display when libdosbox is available and safe mode is off.
To enable automatic launch for a particular BBS, manually copy the
corresponding add-on from the source tree (addons/lod_gterm.wren or
addons/pit_terminal.wren) into the SyncTERM data directory’s scripts/
subdirectory, then select it for that personal dialing entry.
For Land of Devastation 5.11, install GTERM and its data files in
dosbox-x/LOD and set WrenScripts = lod_gterm in the personal dialing
entry’s INI section. The script starts GTERM on the stock welcome line so
it can answer the door’s version probe (5C 47 45 08) on COM1. If the
welcome line is absent, the first probe starts GTERM. Press Enter at the
main or wasteland menu to have the door probe again. Ctrl-Esc returns to
SyncTERM, and later menu probes leave it there until the next welcome or
reconnection.
To start GTERM manually, enter these lines in the connected Wren Console.
var door = Session.current
door.runDos("S:\\LOD\\GTERM.EXE", "COM 1 BAUD 9600")
For The PIT! 4.17, extract the terminal archive
PIT417_T.ZIP into
dosbox-x/PIT417 so it contains PTERM.EXE, its configuration and its
data files. Set WrenScripts = pit_terminal in the personal dialing
entry’s INI section to enable the add-on.
It watches for the door’s graphics terminal invitation and launches PTERM
on COM1 at the session baud rate. Press any key at PTERM’s startup screen
to connect to the door. To start it manually, use
door.runDos("S:\\PIT417\\PTERM.EXE", "1 9600").
While DOS owns COM1, SyncTERM pauses terminal parsing. Unread bytes remain
available when the terminal resumes. A wire or input hook runs during byte
dispatch and cannot take ownership there. A pending script send, wire lease
or file transfer can also return IOErr.busy.
Leases are host-created and have no public constructor. Keep the lease reachable while it is needed; collecting an abandoned lease releases its hold. Explicit disconnect and actual connection loss still end the session. The bundled SFTP queue owns a lease while it has runnable work; the public-key installer uses a scoped lease. Neither client controls the other’s lifetime.
Conn
Connection-level send and receive.
| Member | Description |
|---|---|
|
Queue Unicode text using the session’s wire encoding and transport
processing (including Telnet IAC escaping or MQTT framing). Returns an
|
|
Queue the String’s exact bytes, including malformed UTF-8, NUL and CR/LF, applying transport framing (Telnet IAC and NVT CR escaping, MQTT framing). No Unicode conversion, text newline folding or local XON/XOFF interpretation occurs. Returns an Operation with the text send completion contract. |
|
Close the connection. |
|
Request a session end. Sets a flag that doterm() picks up at the
top of its next iteration, runs the (UI-free) cleanup
(cterm shutdown, conn close, mouse/cursor restore), then either
returns to the main menu ( |
|
Paste from the system clipboard onto the wire — codepage-aware, bracketed-paste-aware. No-op when the clipboard is empty. This is the operation bound to Shift+Insert by the default key hooks. |
|
Invoke |
|
Bool — is the link up? |
|
Monotonic seconds since the connection provider reached the active
connected state, clamped to |
|
|
|
A String snapshot of the current application’s session log, including
protocol, CTerm, and transfer messages accepted by their respective log
levels. It is independent of the optional log filename and contains only
this connection’s diagnostics. The application retains up to 1 MiB of
recent records, discarding whole old lines when needed. An empty log is
|
|
Bytes in the transport output ring that have not gone out yet. This does not include the unsent storage owned by pending send Operations. |
Owned terminal-channel I/O
Session.current.claimWire() returns a WireLease, or a ConnError when
another owner, native transfer, transfer reservation, pending script send or
active terminal input callback prevents acquisition. Await earlier sends before
claiming. This is terminal-channel input after transport decoding, not access
to encrypted network packets. Native terminal display and output, key forwarding
and other script sends pause while it is owned. UI dispatch continues.
CTerm.suspended is independent and retains its previous value.
| Member | Description |
|---|---|
|
Number of available bytes in FIFO order: returned transfer input, unread terminal read-ahead, then the connection queue. |
|
Consume up to 65536 bytes; nonempty String on data,
|
|
Same results and limits without consumption or capture. |
|
Framed binary payload Operation, as for Conn.sendBytes. |
|
Deliberately bypass transport framing and text conversion. Use only for a protocol that requires such bytes; MQTT payloads require sendBytes. |
|
Idempotent Bool; cancel pending owned sends and return unread input to terminal processing in order. Already queued output stays queued. |
|
Bool. |
|
Call |
Send failure, drained EOF, read failure, GC and VM/session teardown release the lease. An input capture failure can consume bytes before reporting its error. A pending send retains its owner until completion or cancellation. A released lease returns ConnError for input and failed Operations for output; claim a new lease for later work. A live lease alone does not keep a disconnected session alive; use Session.hold when auxiliary work must finish after EOF. The old unowned Conn receive/peek/pending and sendRaw entry points are removed.
ConnError
Conn.sendText and Conn.sendBytes own the remaining output and retry queue
pressure internally. Requests run in FIFO order within the VM. At most 64
pending requests and 1 MiB of owned encoded storage (including terminators)
are allowed; an individual input must be smaller than 1 MiB. Oversized or
excess requests complete immediately with ConnErr.queueFull and send
nothing. Text is submitted in complete encoded scalar units. Other terminal
writers may run between those units; await completion before sending a key
or starting a protocol that must follow the text.
Cancellation discards the unsent remainder and completes with the usual
OperationError. Bytes already queued cannot be recalled. Dropping an
Operation handle does not cancel its send. Shutdown cancels pending sends.
File-transfer ownership rejects new or pending sends with ConnErr.busy.
A WireLease rejects sends from Conn; use the lease for protocol output.
Recoverable connection failures complete the Operation with ConnError:
| Member | Description |
|---|---|
|
|
|
Bool: some of this request was accepted before the failure. This is diagnostic, not an input offset. Do not resend a whole request after a partial failure unless duplication is acceptable. |
|
Human-readable diagnostic. |
|
|
ConnErr constants:
| Constant | Code | When emitted |
|---|---|---|
|
1 |
The connection is down. |
|
2 |
The transport rejected the remaining output. |
|
3 |
The script request/storage limit was reached. |
|
4 |
Malformed UTF-8 or text unrepresentable in the session’s codepage. No output from this request was queued. |
|
5 |
A wire lease or file transfer owns or has reserved the connection. |
var error = Conn.sendText("café").await()
if (error == null) {
CTerm.sendKey(KeyEvent.new(Key.enter))
} else {
System.print(error)
}
As with other Operations, a hook with a synchronous return contract must
start a child Fiber to await completion; an App handler uses app.runChild.
Capture
Streaming-log control for the active session. The Wren-side
CaptureMenu in scripts/auto/connected/capture_menu.wren implements
the user-facing Alt+C flow with these primitives. All methods are
no-ops when no terminal is active.
| Method | Description |
|---|---|
|
Bool — true while a streaming log is open (regardless of pause state). |
|
Bool — true when the active log has been paused via
|
|
Open a streaming log to the path authorized by |
|
Close the active log. No-op when not capturing. Idempotent. |
|
Set the PAUSED bit on the active log. No-op when not capturing or already paused. |
|
Clear the PAUSED bit. No-op when not capturing. |
Use CTerm.saveScreenshot for a one-shot binary screen
snapshot with optional SAUCE metadata. Screen snapshots are terminal
state rather than streaming logs and therefore are not part of
Capture.
CTerm
The active terminal’s state and local operations. Most state properties are
read-only. Useful from Hook.onInput and Status.callable for emulation-aware
logic. Terminal operations are available in the connected VM.
For RIP3, these properties and local operations address the selected virtual
text window. Its cursor and dimensions are independent of the main Screen
canvas, which retains the entry’s configured video mode. CTerm.write and
CTerm.reset present their local changes inside that window.
| Group | Members |
|---|---|
Cursor (1-based, on the terminal) |
|
Origin (1-based, on the host screen) |
|
Geometry |
|
Color state |
|
Fonts |
|
Scrollback |
|
Mode flags |
|
Screenshot |
|
Mouse state |
|
Throttle |
|
Bitfield snapshots |
|
CTerm.font[i] is a live, writable view of terminal font assignments. Indices
0 through 9 correspond to SGR 10 through 19. All ten start with the configured
default font. In the primary rendition, positions 0 through 3 also supply the
normal, source-bright, source-blink, and bright-plus-blink fonts.
Reading returns a selector; writing changes only that assignment. This is
independent of the five Screen.font slots for script drawing.
CTerm.setFont(selector, mask) changes all requested assignments together.
CTermFontMask.normal is 1, .bright is 2, .blink is 4, .brightBlink is 8,
and .all is 1023. Use 1 << i for an individual position. Combine bits with
|; zero and unknown bits are invalid.
Selection requires an available registration and a capable backend. It finishes
pending output before committing; failed selection leaves every assignment
unchanged. Existing cells retain their resolved fonts. Selection does not change
the video flags which enable source-bright/blink font selection.
The method returns null on success or FontError on an operational failure.
An indexed write raises that same FontError through ordinary Fiber abort,
so failed assignment statements cannot silently discard a returned error.
Assignment expressions can capture setter results in standard Wren; this
particular indexed setter deliberately aborts on failure. Catch it with a
Fiber’s .try() when recovery is needed. The terminal assignment interface is
connected-VM-only. The old CTerm.altFont and detached CTerm.altFonts List
are removed without aliases. The shipped picker still changes only the normal
assignment when selecting an existing font; loading only registers a new font.
| Action | Description |
|---|---|
|
Render strict UTF-8/NFC text directly through the native semantic-input path,
independently of the wire encoding. Returns |
|
Forward a |
|
Bool. Reports whether the active RIP3 or DDO F/X scene has locked keyboard input. A shortcut that submits terminal data directly can check this before sending. |
|
Enable or disable the Thieves' Guild front end for the current Atari ST
session. Pass a Bool. The method returns null on success or a |
|
Locally arm the Musicomm receiver and read whether it still owns received
bytes (including startup/end drains). Start returns null on success or
|
|
Invoke the direct native terminal reset synchronously. Returns null on native success or CTermError with the exact native failure code. Requires the connected VM’s assigned terminal, independently of whether the network is still connected. Menu/picker and missing-terminal calls abort without invoking reset. + The native operation finishes pending input, resets parser/mode and cursor settings, and rebuilds enabled RIP state, including reloading its persisted variables. Finishing a buffered RIP command can invoke its existing host prompt or other callback before reset proceeds. This is distinct from feeding a reset escape sequence through CTerm.write. The binding adds no screen/history clear, resize, encoding change, reconnect, wire claim or suspension change. Existing native generated-response suppression under WireLease/transfer ownership remains in force; local reset does not create a new busy/network failure policy. + Failure may follow pending-output processing or partial reset, including a partially rebuilt RIP engine. It provides no rollback or automatic retry and does not guarantee that the terminal remains usable. The operation retains no arguments or native resources. |
|
Read or write the wire-pump suspend flag. When set true, the main
loop stops draining bytes from the conn buffer. Bytes pile up in the
conn buffer; the TCP receive window eventually fills and the remote
sees its |
|
Read or toggle the session gate for forwarding mouse events to the
remote tracking protocol. Changes take effect immediately; local UI
subscriptions remain controlled by |
|
Read-only effective native mouse protocol: BIG reports mode |
|
Read-only Bool; true while DECSET 1016 is the active SGR pixel-position reporting mode. False for IGS, SkyPix and an active BIG pointer. SkyPix controller reports use their own pixel-coordinate format even if an ANSI mouse mode was requested. |
|
Read or write the cterm doorway-mode flag. When true, the input pump passes most keys through verbatim instead of decoding them; used by door programs that want raw scancodes. |
|
Read or write the Operation Overkill ][ terminal mode
( |
|
Current network character-pacing rate in BPS. |
|
Walk |
CTermError
An immutable Error returned by write, sendKey and reset above. There is no
public constructor. It owns scalar diagnostics and message storage, retains no
input String, terminal or session, and remains usable through later calls and GC
within its VM.
| Member | Description |
|---|---|
|
Exact native I/O integer, comparable to |
|
Nonempty human-readable operation/reason diagnostic. |
|
Write errors only: native consumed count in the normalized
UTF-8 input; |
|
Key errors only: the native acceptance Bool, including local-only
actions; |
|
Includes |
Wrong types, invalid event objects, malformed UTF-8 and missing required native terminal/session state remain programmer errors raised through ordinary Fiber abort. An impossible native consumed count, or native success with incomplete consumption, also aborts as a native contract violation; no I/O status is invented. Native output policy is unchanged: key errors can reflect retained output failures, and disconnect suppression permits auxiliary work to continue. These values provide no rollback, automatic retry or network-delivery guarantee.
var result = CTerm.sendKey(KeyEvent.new(Key.enter))
if (result is CTermError) Fiber.abort(result)
// result is now the native acceptance Bool.
ExtAttr
Snapshot of cterm’s extended-attribute bitfield. All members are read-only Booleans reflecting the corresponding terminal mode.
| Member | Description |
|---|---|
|
DECAWM — characters past the right margin wrap to the next line. |
|
IRM — graphic characters shift text to the right when inserted. |
|
DECOM — cursor coordinates are relative to the active scroll region rather than the screen. |
|
SIXEL scroll: when a SIXEL image extends past the bottom of the screen, scroll the screen up to make room. When clear, the image is clipped at the bottom row. |
|
DECLRMM — left/right margin mode enables horizontal scroll regions. |
|
DEC mode 2004 — pasted text is bracketed by ESC[200~ / ESC[201~ markers. |
|
DECBKM — Backarrow key sends BS (0x08) instead of DEL (0x7F). |
|
Prestel mosaic graphics character set is active. |
|
Current row is rendered double-height. |
|
Concealed (hidden) text mode. |
|
Separated mosaics — gaps between mosaic blocks. |
|
Hold-graphics mode — control codes render as the most recently emitted mosaic glyph rather than blanking. |
|
DECKPAM — numeric keypad sends application keypad codes instead of digits. |
LastColumnFlag
Snapshot of cterm’s last-column-flag state. Used by emulations that distinguish "cursor at the right margin" from "cursor wrapped to next line" (the so-called phantom-column).
| Member | Description |
|---|---|
|
Bool — the flag is currently set: the cursor sits at the right margin awaiting the next character to wrap it. Cleared by any cursor-positioning sequence. |
|
Bool — last-column-flag tracking is enabled at all. Some emulations disable it. |
|
Bool — tracking is forced on regardless of the
underlying mode (set by SyncTERM’s emulation-bridge
code or the BBS list’s |
StatusDisplay
Referenced by CTerm.statusDisplay. VT320 DECSSDT (Select Status
Display Type) values: which status line, if any, the bottom row is
acting as.
| Constant | Code | Description |
|---|---|---|
|
0 |
No status line — the bottom row is part of the main display area. |
|
1 |
Indicator status line — terminal-managed diagnostic line (e.g. "INSERT", connection state). The host can’t write to it. |
|
2 |
Host-writable status line — the bottom row is a separate addressable region the BBS can direct writes to via DECSASD. |
Profiles
Profile in syncterm is the shared connection-configuration contract in all
VMs. DirectoryEntry.profile and Menu.defaults are views into the working
menu model. Session.current.profile is a cached, read-only snapshot of the
configuration captured for this connection. profile.copy() returns an
independently owned editable value, without a directory identity or statistics.
Quick-connect configurations are independently owned values too; later quick
connections and menu reloads do not overwrite or invalidate them.
readOnly identifies system/web views and session snapshots. Their setters
abort. All other Profile fields below have getters and setters, except the
derived display string connTypeName. Profiles have no rename/save/delete,
entry IDs, statistics, or cache authority. Use Menu.copy(profile, name) to
create an entry; selecting a Profile starts a transient connection without
updating another entry’s statistics.
| Group | Fields |
|---|---|
Address |
|
Network |
|
Auth |
|
Presentation |
|
Files and logging |
|
Serial and protocol |
|
Scripts |
|
Connection strings, credentials, paths, and comments use the normal strict
UTF-8/NFC text boundary without NUL, with field-specific size limits.
tlsPsk is literal text, without
hexadecimal or Base64 decoding. sshFingerprint is an exact byte String of
length 0, 20 or 32; use .bytes.count for its length. palette and
wrenScripts return fresh Lists; their lengths replace the old redundant
size getters. Invalid assignments leave existing values intact.
profile.customScreenMode returns null when Custom follows Program Settings,
or a fresh List in the order [columns, rows, fontHeight, aspectWidth, aspectHeight].
Assign a complete List to store an override, or null to clear it. Columns and
rows accept integers from 1 through 255, font height from 1 through 64, and
each aspect component from 1 through INT_MAX. The matching optional BBS-list
key uses comma-separated integers, for example CustomScreenMode=96,32,8,3,1.
An incomplete or malformed tuple inherits the program mode. A saved profile
retains its override when another screen mode is selected.
Configured profile.encoding uses the profile encoding catalog and remains
unchanged when terminal decoding changes. CTerm.encoding reports the live
TerminalEncoding.utf8 (0) or TerminalEncoding.codepage (1);
CTerm.codepage reports the live Codepage value. Session.current.name,
entryId, entrySource, added, lastConnected and calls describe the
session’s captured identity and connection statistics. Conn.elapsedSeconds
is live elapsed time. The former BBS classes and static namespace are removed.
Menu BBS Model
The menu VM imports Menu, DirectoryEntry, and MenuError from
syncterm_menu. Menu owns a C-side transactional view of the
personal, installed system, and web-cache BBS lists. It is not
available in a connected VM.
| Method | Description |
|---|---|
|
Load all lists and replace the current model only after the complete
load succeeds. |
|
Return a fresh List of immutable BBSLoadDiagnostic snapshots from the current installed list, in native order; empty without a loaded model. Reading does not reload files or change the model. See BBS load diagnostics. |
|
Parse a String using SyncTERM’s normal URL rules and return an owned editable
Profile, or null for an unusable address. It remains valid across further
quick connections and reloads. It can be returned from MainMenu.run; use
Menu.copy(profile, name) to create a directory entry.
The |
|
Return a detached |
|
Number of rows in the most recently completed session, including its saved terminal page, subject to the configured capacity. |
|
Read one detached row or its original geometry, using the same coordinates
and return types as |
|
Select the completed session’s text mode, restore its mode-specific fonts
and palette, and draw the terminal background. Returns |
|
Restore the original menu geometry after preparing detached history; returns null or ScreenError. It is idempotent and leaves an enclosing disconnected session’s mode bracket intact. The shipped viewer pairs this with preparation through its cleanup scope. |
|
Return whether the completed session’s terminal layout reserves a status row. The shipped viewer uses the full screen height for Page Up/Page Down and this value to recover the terminal height used by H/L. |
|
Open a detected plain-text URL with the configured local URL handler.
Returns whether it opened, or |
|
Resolve an ID from the shared hyperlink registry and open HTTP, HTTPS, FTP,
or FTPS URIs with the configured local URL handler. Scheme matching is
locale-independent and case-insensitive. Returns |
|
Select the link pointer when |
|
Return the classic header text, combining the SyncTERM version and active conio output-backend description. This is display data and does not change the OS window title. |
|
Return the current local time in the classic 24-character
|
|
Return the current Unix timestamp as a Num. Trusted offline applications
can use it to initialize date-oriented widgets without a connected Session
or |
|
Set the OS window title to the classic name/call-count/last-connected
summary for a current DirectoryEntry or Profile. Passing |
|
Set SyncTERM’s process exit latch after trusted menu code has completed any required work. This is available for explicit menu commands; OS window-close requests set the same latch in the host. |
|
Return a new List of host-created DirectoryEntry views in current sort order. The records themselves remain C-owned. |
|
Return whether the combined personal and read-only directory has room for another personal entry. |
|
Return a fresh List of valid root script-module names available for
per-entry connected loading. The list is rebuilt from user
|
|
Maximum byte length of the comma-separated |
|
Return the mutable defaults Profile view, or null before loading. Scripts are configured per entry: root-section WrenScripts is ignored, defaults expose an empty script list, and assigning scripts to defaults aborts. The defaults editor omits scripts. New entries start without scripts; entries without their own WrenScripts stay empty when edited. |
|
Bool indicating unsaved default configuration changes. |
|
Persist the working defaults to the root section. Returns null/MenuError; safe mode returns IOErr.readOnly. Profiles have no persistence methods. |
|
Test whether a new personal entry name is valid and unused by another
personal entry. Names are 1..30 Unicode scalars and at most 60 UTF-8 bytes;
identity uses Unicode canonical caseless matching. The reserved
|
|
Create an unsaved personal entry from |
|
Create an unsaved personal copy of |
|
Reapply the configured BBS-list sort profiles. Returns null/MenuError. |
|
Return fresh |
|
Return fresh |
|
Zero-based index of the active profile. |
|
Select a profile in memory, apply its order, and re-sort the loaded directory. Returns null/MenuError; invalid indices abort before the native call. |
|
Insert a profile. Names are 1..19 Unicode scalars, at most 38 UTF-8 bytes,
and canonically caseless-unique. They cannot contain controls, leading or
trailing Unicode whitespace, |
|
Replace a profile’s name and field order. Updating the active profile also re-sorts the loaded directory. Returns null/MenuError; invalid arguments and duplicate names abort. |
|
Delete a profile and re-sort with the resulting active profile. Deleting the last profile restores the built-in profiles. Returns null/MenuError. |
|
Write the working profiles, active profile, and current order to
|
The shipped offline viewer saves the menu screen, calls
prepareOfflineScrollback(), captures the resulting background, and restores
the saved mode, fonts, palette, video flags, cursor, mouse subscriptions, and
screen when it closes. It starts at the newest screen. Up/J and Down/K move
one line, Page Up/Page Down move by the physical screen height, H/L move by
the terminal content height, the mouse wheel moves one line, F1 opens the
Markdown help, and Escape returns to the directory. Clicking opens OSC 8 or
detected plain-text URLs, hovering shows an OSC 8 URL in the status row, and
button-one drag copies text in reading order. Alt at button press selects a
rectangle. In mixed geometry the viewer shows the hovered URL in its title row.
Horizontal arrows pan, and holding a dragged pointer at the viewport edge
continues scrolling. Both selection modes use each row’s original columns.
In v2, MenuReadStatus and Menu.statusMessage are removed without aliases, including obsolete migration status values. Successful loads can still contain warnings about skipped sources or sections, or truncated entry names. The bundled menu opens a scrollable Directory Warnings summary when any warning comes from a personal or shared list. Up/Down scroll one line, PgUp/PgDown scroll a page, and Home/End jump to the top/bottom. Enter continues and Escape closes the dialog. Once dismissed, an unchanged warning summary does not reopen during subsequent loads in the same menu VM, including returns after disconnect. A changed summary can reopen it; a successful load without an automatic warning clears the remembered summary. Warnings remain available through Menu.loadDiagnostics on every load. Warnings exclusively from web lists do not open the dialog automatically, but remain in the diagnostics and appear alongside other warnings when the dialog opens. Dismissal continues with usable entries; missing optional files remain silent. A diagnostic retrieval failure still opens the dialog every time as warnings unavailable, without treating the successful load as failed. Password cancellation and fatal load errors retain their existing prompts and error dialogs, even when all retained warnings are from web lists. There are no automatic retries.
A DirectoryEntry owns name, searchKey, source, sourceName, shadowed, id, added,
connected (persisted LastConnected timestamp), lastCallText, calls, readOnly, dirty,
profile and cache. Only sortOrder has a property setter. rename(name),
save() and delete() return null/MenuError; toString returns its name.
id survives sorting, rename, save and unrelated model edits. An unsaved draft
has -1 until its first successful save. IDs are local to a load and are not
serialized. Native ownership also distinguishes replaced records independently
of their names, addresses or numeric IDs.
lastCallText formats the persisted last-connected timestamp as a local-time
YYYY-MM-DD date, Never for zero, or Unknown if it cannot be represented.
It performs no I/O and follows the entry handle’s ordinary lifetime.
source preserves the native list source using BBSListSource.personal (0),
shared (1), webSystem (2), or webNamed (3). sourceName returns null for
personal entries, the shared-list path, "System List" for the system web list,
or the configured named web-list name. Source names are validated as UTF-8 and
normalized to NFC on access. A conversion failure returns MenuError with the
actual status in code and nativeCode; it does not change the loaded model.
Reading other fields does not construct a source-name String or Profile snapshot.
New and copied personal entries have personal provenance and no source name.
shadowed returns a read-only DirectoryEntry view of the next lower-priority
record retained by the native or working directory model, or null. Traverse only
the records actually retained; this does not enumerate every list containing
that name or change native precedence. Its profile is a read-only view,
cache is null, setters abort and rename/save/delete return read-only MenuError.
Explicit Menu.copy() and profile.copy() use the ordinary copy rules.
The view creates no file authority and remains excluded from Menu.entries.
Hidden entry/profile views follow normal directory lifetimes: sorting and unrelated edits preserve them, a successful load replaces them, and a failed load preserves them. Restoring a hidden record to the visible list invalidates its old hidden view; an old visible view does not revive when that record is restored. Captured Strings and detached Profile copies remain independent.
The former directory classification getter entry.type is removed. It now
inherits Wren’s standard Object.type, returning the DirectoryEntry class.
Use entry.source for provenance and entry.readOnly for editability.
BBSListType and Session.entrySource still represent the native profile’s
separate personal/system classification; no Profile.source getter is exposed.
searchKey retains the NFD full-default-casefold form of the name. The shipped
list uses it as a cheap search prefilter and verifies grapheme boundaries.
Configuration lives on entry.profile; its setters share the working record
and mark the entry dirty. Saving persists those edits and an in-memory rename
together. Deleting a persisted entry updates disk before removing the record;
deleting an unsaved draft only discards that draft. System/web views reject
configuration setters; rename/save/delete return MenuError with IOErr.readOnly. Menu.copy produces a
personal editable entry. Safe mode permits working edits but rejects persistence.
entry.cache is a Directory for a saved personal entry, created through the
normal cache resolver. It returns null for unsaved/system/web entries and a
FileError on native failure. Before a pending rename is saved it refers to the
persisted name’s cache. Saving the rename uses the native cache move policy.
Previously issued cache grants and their descendants become stale at that
point, on removal/replacement, and on reload. They cannot access a later entry
at the same name/path. An already open File retains its stream and can always
be closed; path-based operations still require a current grant. Displayed
paths confer no new authority. This adds no arbitrary filesystem constructor.
The shipped entry editor invokes those setters, including rename(),
after each nested field editor accepts a changed value. It calls
save() for a dirty entry when the entry editor closes.
The Wren Scripts editor applies additions, deletions, and completed moves to
the working Profile immediately; save() writes them as the comma-separated
WrenScripts value in that entry’s INI section.
The fingerprint has no direct editor row; the shipped F5/F6 clipboard carries
it through the draft so copying an entry preserves an accepted SSH host key.
TLS certificate/key and PSK identity/secret pairs can be edited one field at a time. The editor validates complete pairs before saving and remains open when a pair is incomplete. C-backed text fields also enforce their UTF-8 byte limits before invoking a setter.
Download Path and Upload Path remain direct entry rows. Log Configuration opens Log Filename, File Transfer Log Level, Protocol Log Level, CTerm Log Level, and Append Log File. Accepted values still update the working Profile before the logging submenu closes.
The persisted INI name is ProtocolLogLevel. During the pre-release
rename, a missing ProtocolLogLevel falls back to the legacy
TelnetLogLevel value; saving the entry writes the new name and removes
the old one. When neither global key exists, the default protocol log
level is Error.
CTermLogLevel is saved independently for each entry and connection default;
its default is Error. CTerm diagnostics share the configured LogFile and
append setting, with a CTerm source prefix. Warning includes detected
unsupported or invalid sequences, rejected parameters, and malformed UTF-8.
Debug also reports final missing grapheme clusters (.noglyph) with their
Unicode code points, selected console font identifier, and screen position.
An exact match supplied by compatible font zero is not a missing glyph.
A successful full load invalidates entry/default views and cache grants from the replaced model. A failed load preserves them. Creating/deleting unrelated entries, sorting and saving preserve existing identities. Deleted or shadowed entries become stale; restoring a shadowed system record does not revive an old view of it. Detached Profile values and session snapshots remain valid.
BBS load diagnostics
Menu.loadDiagnostics creates snapshots only when requested. BBSLoadDiagnostic is menu-only, host-created, and immutable, with no public constructor or setters:
| Property | Description |
|---|---|
source |
BBSListSource.personal (0), shared (1), webSystem (2), or webNamed (3), preserving native source values. This is distinct from BBSListType. |
sourceName |
Nullable source identifier: null for the personal list, the shared list path, "System List", or the configured named web-list name. |
sectionName |
The original section name for a skipped or truncated entry, or null for a source-level failure. |
error |
A fresh MenuError with the native portable diagnostic status in both code and nativeCode, and a readable reason. Constructed only on access. |
Snapshots own their names and scalar data, survive reloads and garbage collection, and retain no borrowed list pointers, secrets or filesystem authority. Their names are strict UTF-8/NFC host text. Allocation or text-conversion failures raise MenuError through ordinary Fiber abort; they do not alter the loaded model. The returned List is independently mutable; its records are immutable. Diagnostics come from the installed native list, including its existing rebuild behavior, not from a failed replacement candidate. Entry provenance and shadowed records are separate from these warnings.
Overlong entry names are loaded using the longest valid prefix within 30 Unicode scalars and 60 UTF-8 bytes, preserving complete UTF-8 scalars and removing trailing whitespace at the cutoff. Their diagnostic has IOErr.nameTooLong and retains the full original section name. Values are read from that original section; the shortened name determines entry identity and the usual duplicate/priority rules. Editing or deleting a personal entry still addresses its original section. Malformed or otherwise invalid names retain the existing rejection policy.
import "syncterm_menu" for Menu
var failure = Menu.load(null)
if (failure != null) {
System.print(failure.message)
} else {
for (item in Menu.loadDiagnostics) {
System.print("%(item.sourceName): %(item.error.message)")
}
}
Menu operation results
In v2, BBS and Settings mutation actions return null on success or a host-created,
immutable MenuError. Creators (Menu.create, copy, createFromProfile, createFont) return their
object or MenuError. This covers entry rename/save/delete, defaults/encryption/sort,
Settings apply/save/reload, font/web/sort collection actions, Menu.load, and
theme operations described below.
Predicates retain their own contracts. There are no Boolean compatibility forms.
| Member | Description |
|---|---|
|
Portable IOErr reason, or null when the called C API supplies no portable reason. Classify by the API’s contract, never by the raw integer alone. |
|
Actual integer C failure, or null for Boolean/pointer failures and host-only policy rejection. ThemeDocument.save retains its separate native ThemeSaveErr enum here with code null. Generic -1 from older collection APIs is retained here with code null; it is not classified as IOErr.invalidArgument. |
|
Owned operation-specific diagnostic; portable failures include their reason. |
|
Diagnostic prefixed by `MenuError: `. |
MenuError has no public constructor or setters, retains no borrowed native data, secrets or resource authority, and remains usable after reloads and collection. It is available only in the trusted menu VM and inherits the ordinary Error base. Existing invalid-argument and stale-handle aborts remain. Native mutation failures in property setters raise MenuError through ordinary Fiber abort.
Native C APIs, call order and partial effects are preserved. A list KDF rewrite may succeed before a Settings save fails. Collection edits may precede a later native failure, and installed settings may precede a runtime application failure. Messages identify completed earlier steps where known. Once settings are installed, generation/dirty transitions still occur even if applying a runtime option fails. There is no rollback or transaction-state API. Inspect current models as needed; no automatic retry is performed. Optional cache housekeeping remains outside primary BBS mutation success. Safe-mode blocked operations return IOErr.readOnly, including saveSortProfiles, which formerly reported a successful no-op.
var error = entry.save()
if (error != null) System.print(error.message)
Saving detached menu drafts
The Retro editors use the existing Profile.copy() to keep profile changes out
of the working directory until Save. The following menu-only additions accept
an owned, editable, detached Profile; passing another foreign type or a borrowed
profile view aborts. They do not consume the supplied Profile.
| Operation | Result and behavior |
|---|---|
|
Update an existing personal entry and persist it, returning null/MenuError.
Preserve entry identity, provenance, call statistics, and other entries.
|
|
Persist a new personal entry and return its DirectoryEntry or MenuError. Reset call statistics using the same rules as Menu.copy; normal name, capacity, and shadowing rules apply. A failed creation leaves no unsaved entry. |
|
Persist replacement new-connection defaults, returning null/MenuError. The existing zero-argument overload still saves the mutable working defaults. |
Preparation and persistence are serialized on the menu thread. No application callback observes a partially prepared record. Failure restores the working record and preserves its views; success publishes the replacement and reapplies sorting. Existing native write-error and secondary-cache semantics remain: a failed write can partially modify the file, and cache maintenance is separate from primary mutation success. These operations do not create a general-purpose transaction or filesystem rollback facility. Safe mode returns IOErr.readOnly.
Menu Program Settings
Menu.settings returns a C-owned Settings snapshot. Property
setters validate the assigned value, change only that snapshot, and set
dirty. apply() applies the snapshot to the running program without
writing syncterm.ini. Values copied from the running settings are not
revalidated, so values accepted by older versions pass through unchanged.
reload() discards changes not yet applied and repopulates the same handle
from the current running settings. It does not reread syncterm.ini, including
when another process has edited that file. The native raw global reload is
intentionally not exposed: it replaces configuration data and the merge baseline
without coordinating runtime fonts, themes, audio or layout. There is no full
application disk-reload method.
dirty specifically means that the snapshot differs from the running
settings. A successful apply() clears it. It does not indicate
whether those running settings have subsequently been written to
syncterm.ini; code which separates apply() from save() must track
that persistence obligation itself.
save() preserves unrelated INI sections, writes the existing
syncterm.ini keys, and applies the settings which have immediate effects.
These include scrollback capacity, scaling, mouse-wheel direction, audio
backends, custom-mode dimensions, cursor style, and the Classic Theme
colours used when the built-in theme is active. It returns
MenuError when preparation, encrypted-list rewriting, INI persistence, or runtime
application fails; success is null. A failure before installation does not apply
an unapplied snapshot; settings already
accepted through apply() remain active. Changing the KDF work factor may
rewrite an encrypted BBS list during apply(). Saving syncterm.ini is
disabled in safe mode: save() returns MenuError with IOErr.readOnly before applying the snapshot,
and the snapshot remains dirty.
The allowed audio-backend mask changes immediately. Backend selection occurs when the process first opens its audio engine; changing an already-open backend requires restarting SyncTERM. Startup screen and video output preferences also take effect on the next startup. In safe mode, applying a KDF change which would rewrite an encrypted directory returns IOErr.readOnly without changing the directory or installed settings.
Installing a snapshot during apply() or save() advances the settings generation,
even if a later runtime application step fails.
The object which performed the operation remains valid and clean, but
any other outstanding Settings handles become stale and abort when
used. Reacquire a snapshot from Menu.settings after another component
applies or saves settings.
The Classic Program Settings editor calls apply() after each accepted
setting and calls save() once when the editor closes. Thus settings
with immediate effects change at field-confirmation time while the INI
write remains grouped at the Program Settings screen-exit boundary.
If the write fails, the screen remains open so saving can be retried.
promptSave controls the save offer for a temporary URL connection when the
application exits. The offer is suppressed in safe mode, when that entry has
hidePopups set, and for entries already saved in the directory.
The Classic editor keeps Classic Theme Colours and Custom Screen Mode as nested groups instead
of flattening their fields into Program Settings. A connected invocation
omits Custom Screen Mode. The connected settings list also omits Current
Screen Mode and List Encryption; List Encryption is omitted in every mode
when Menu.encryptionAvailable is false.
| Property | Meaning |
|---|---|
|
Bool, defaults to true. Enables local Atari ST keyboard clicks independently
of the terminal bell and remote sound effects. The Program Settings row
toggles on selection and applies immediately, including during a connection.
Persists as |
|
Built-in main interface: 0 is Classic (default), 1 is Retro. Other assignments
abort. |
|
Bool program options. |
|
Modem strings and the terminal name exported to local shell
connections. The shipped editor accepts 1024 bytes for the device,
1023 bytes for either modem command, and 30 bytes for |
|
Stored personal-list path or URI. The host resolves it to the active
local or cached list path after a successful apply or save. The shipped
editor limits it to |
|
Catalog-backed display, backend, and audio selections. |
|
OpenGL scaler selection when |
|
Scrollback capacity is 1 through |
|
Stored transfer completion acknowledgement preferences in seconds, from
0 through |
|
The effective scrypt cost exponent for encryption rewrites; accepted
range is 8 through 20. Unsupported older persisted specifications report
the effective default of 15. This is policy, not the loaded file’s KDF;
use |
|
Custom text-mode geometry. Rows are 14..255, columns are 40..255,
font height is exactly 8, 14, or 16, and both aspect values are
1 through |
|
Palette indexes used to construct the built-in Classic Theme.
Frame, text, and lightbar foreground use |
The six values are persisted under [ClassicTheme]. On load, each
missing key falls back independently to the same key under the former
[UIFC] section, so a partial new section does not discard old
preferences. The next successful Program Settings save writes all six
[ClassicTheme] values and removes [UIFC]. A failed save leaves the
existing file unchanged.
Program Settings includes an Amiga Fonts manager. User-installed families live
under fonts/amiga/ beside the active syncterm.ini; the 11 bundled families
(39 strikes) are compiled into SyncTERM and are not copied there. The per-BBS SkyPix Font
choice stores Profile.amigaFont (family name, default Pearl.font) and
Profile.amigaFontSize (exact strike height, 1..65535, default 8). Initial
selection tries an exact installed name/height, an exact bundled strike, then
Pearl 8; it does not stretch a neighbouring size. Reset restores that configured
initial strike. Unavailable remote font requests also fall back to it. A selected font remains valid
if its installed package is subsequently replaced or removed. Catalog queries
and management are menu-only; connected scripts cannot import this interface.
The host supplies display catalogs rather than requiring scripts to duplicate platform-dependent enum tables:
| Menu member | Result |
|---|---|
|
Ordered |
|
Screen-mode picker rows with square pixels. Current uses the live console
geometry. Pass a profile or draft’s five-value Custom geometry to filter
Custom for that entry. The getter and a |
|
Ordered |
|
Lists of display names indexed by the corresponding numeric setting. |
|
Lists of |
|
The former returns compatible |
|
Fresh List of immutable |
|
Open the local Amiga |
|
Remove the installed portion of the current family snapshot; return null or MenuError. Bundled fonts cannot be removed. A snapshot retained across another install/remove operation must be reacquired before removal. |
|
Return the built-in default port for a connection-type value. RLogin uses 513, Telnet 23, SSH 22, MBBS GHOST 65535, Telnet TLS 992, and MQTT 8883. Types without an inherent network port return zero. |
|
Open the named serial device and return its supported rates as
|
|
Return the |
|
Return |
|
Build-dependent List of |
|
Build-dependent List of |
|
Build-dependent List of |
|
Bool. True in the persistent menu VM when the static libdosbox emulator can run on the current bitmap display and safe mode is off. |
|
Open an interactive DOS prompt in the local menu. Returns an integer status after the guest exits and the menu display is restored. Zero indicates success. See the DOS drive mappings. |
|
List of |
|
List of |
|
Build-specific |
|
Bool indicating whether this build exposes personal-list encryption. |
|
Foreground and background color-name Lists, including their final
|
|
Current SyncTERM screen-mode enum value. |
|
Apply a concrete screen mode immediately and restore the configured
default cursor. |
|
Map containing |
Controller mapping in syncterm_menu
Menu.controllers lists attached devices as [localId, label] pairs. An empty
list means zero devices and null means no provider. Menu.controllerFields(id)
returns one row per physical control in HID descriptor order or XUSB provider order, containing its
label, binding index (−1 if unassigned), inversion flag and current preview
value (null if unknown). Each physical hat also has four button fields appended
after the descriptor fields, one per cardinal direction. A diagonal presses
both adjacent directions. Libretro devices expose no editable fields.
Menu.controllerTargets(id, field) lists compatible targets as
[bindingIndex, label, kind]. Use field −1 for all targets. Kinds 0, 1, 2
and 3 denote button, centered axis, one-way axis and hat respectively.
Menu.controllerHatButton(id, field, direction) returns the button field
for a cardinal direction of a hat, or −1 for a non-hat, diagonal or neutral.
Menu.armController(id) starts identification using the current baseline.
Menu.armController(id, target) captures only fields assignable to that
target. Pass −1 to capture any control.
Menu.controllerMotion(id) returns [field, value], with field −1 until a
new actuation. Hat preview and captured values are clockwise directions
0..7 from up, with −1 for neutral.
Menu.bindController(id, field, target, inverted) applies a binding. Target
−1 clears it. Assigning an occupied target moves it to the selected field.
The method returns true on success, null if the device disconnected, or a
MenuError if saving failed. Safe mode applies the mapping in memory.
Menu Themes
Theme storage and file syntax are documented in Themes.adoc.
Menu.themes refreshes the C-owned catalog and returns a List of rows in the form
[filename, name, author, description, version, error], or MenuError if refresh
fails. Native failure preserves the previous catalog; already returned rows remain
usable. The built-in
Classic Theme has an empty filename. Optional metadata is null when
absent. An invalid or missing theme has an error String and cannot be
selected, but remains available for display in the browser.
Menu.selectedThemeFile returns the committed filename, or an empty String
when Classic or a cloud package is selected. Menu.selectedThemePackage
returns the committed repository/id, or an empty String for Classic and
local files. Menu.previewTheme(filename) installs a temporary
process-wide preview and returns null/MenuError without changing the committed
selection. Menu.cancelThemePreview() restores the
committed theme. Both operations advance Host.themeGeneration when they
change the active snapshot.
Menu.selectTheme(filename) validates the catalog entry, writes
[SyncTERM] ThemeFile, and commits the preview as one operation. Selecting
Classic removes the key. It returns null/MenuError. In safe mode the running selection changes but the INI file is not
written. A successful selection advances both the theme and settings
generations, so scripts should reacquire outstanding Settings snapshots.
Selection failure preserves its original native reason and existing restoration
attempts; messages describe failed restoration if detected. No new rollback or
unchanged-file guarantee is made.
Menu.deleteTheme(filename) removes a local theme file and returns null/MenuError. Deleting the selected file first commits and saves Classic
Theme. If deleting the file then fails, Classic remains selected and saved
while MenuError reports the deletion failure and the completed Classic selection/save.
Menu.refreshCloudThemes() refreshes the official manifest, updates cached
packages whose SHA-256 changed. It returns null for clean native success, a
String for native success with a warning, or MenuError for native failure. A
warning may accompany a usable cached manifest. The binding does not invent a
numeric reason for warning text whose underlying status C has already discarded.
Menu.cloudThemes returns a fresh List of read-only CloudThemeEntry live
views in the menu VM. They have no public constructor, setters or positional
indexing. Local Menu.themes rows keep their existing interface.
The native catalog is initialized from the cached manifest during startup,
without fetching the manifest or packages. Downloaded packages are therefore
available before opening Online Themes. Missing or invalid optional catalog
metadata does not prevent restoring the previously selected cached theme.
| Property | Meaning |
|---|---|
|
Native package identity and descriptive metadata. Optional fields are null when absent. |
|
The source URI from the manifest, or null when unavailable. |
|
The expected SHA-256 hexadecimal manifest text, preserving its spelling and case. It is not a freshly computed cached-file digest. Null when unavailable. |
|
Live native cache-state Bools; reading them does not inspect files or download. |
|
Native catalog diagnostic text, or null. It does not manufacture a numeric status for a diagnostic whose underlying native reason is unavailable. |
Text fields create Wren Strings only on access, validating UTF-8 and normalizing
to NFC. A conversion failure returns MenuError with the actual status in code
and nativeCode. This also applies to reading the diagnostic text in error.
A selected package absent from the manifest can have null sourceUri and
expectedSha256. Metadata views retain no borrowed strings or parsed-theme
pointers and grant no file or network authority.
Successful replacement of the native cloud catalog makes old views stale, including refreshes returning a warning. A failed refresh before replacement preserves them. Stale field reads abort; reacquire through Menu.cloudThemes. In-place cache, selection and deletion updates remain visible without replacing the view. Changes to the displayed theme alone do not invalidate catalog views. Captured Strings remain independent after updates or replacement. Property reads perform no downloads, cache checks or file reads.
Menu.previewCloudTheme(package) previews a validated cached package and
returns null/MenuError. Menu.cacheCloudTheme(package) downloads
and validates a package without selecting it. Menu.selectCloudTheme(package)
does the same as needed, writes [SyncTERM] ThemePackage, removes
ThemeFile, and commits the selection. Menu.copyCloudTheme(package)
returns an unsaved ThemeDocument populated from the cached package, or MenuError.
Caching and selecting return null/MenuError. These
catalog and document operations are menu-VM capabilities; the cache location
is never exposed as general filesystem authority.
Menu.deleteCloudTheme(package) removes a cached package so it appears in
Online Themes again, returning null/MenuError. Deleting the
selected package first commits and saves Classic Theme. If deleting the cache
file then fails, Classic remains selected and saved; MenuError describes that
completed step and preserves the deletion failure. Both deletion operations are unavailable in safe mode.
The shipped Themes browser combines Menu.themes with cached entries from
Menu.cloudThemes, using distinct identities for Classic, local files, and
packages when tracking its selection. Its Online Themes browser displays
only Menu.cloudThemes entries whose cached member is false. Downloading a
package therefore moves it from the online-only browser to the main Themes
browser. Both browsers publish the highlighted row’s description through
the main menu’s comment callback and reserve the comment row when sizing
their shadowed panes.
Menu.newThemeDocument() returns a new C-owned ThemeDocument containing a
minimal sparse overlay on the compiled default, or MenuError on native failure. Its filename is empty and
it is dirty until saved. Menu.openThemeDocument(filename) accepts the
nonempty basename of a file accepted by the current theme loader, returning
ThemeDocument/MenuError. Empty names and invalid arguments abort the Fiber.
Menu.copyCloudTheme likewise returns ThemeDocument/MenuError. These constructors
and all document methods are menu-VM capabilities; documents cannot be
created or passed into the connected or picker VMs.
ThemeDocument.metadata(field) and setMetadata(field, value) use field IDs
0 Name, 1 Author, 2 Description, and 3 Version. The optional fields return
null when absent; setting an optional field to an empty String removes it.
Name cannot be empty. Metadata/style/glyph mutation and import return
null/MenuError with the portable native reason, replacing error Strings in v2.
Existing type/range/enum validation aborts remain; native semantic failures are
recoverable values.
ThemeDocument.styles returns rows
[role, builtin, present, font, legacyAttr, foreground, background].
present is a bit mask for fields 0 Font, 1 LegacyAttr, 2 Foreground, and
3 Background. setStyle(role, field, mode, value) uses mode 0 to remove the
file value and restore the compiled default, mode 1 to write inherit, and
mode 2 to write the supplied numeric value. addStyle(role) creates a
custom role with inherited fields. removeStyle(role) removes only a custom
role.
ThemeDocument.glyphs returns rows
[name, builtin, present, cp437, ascii, codepoint]. Its present bits are
0 CP437, 1 ASCII, and 2 Codepoint. setGlyph(name, field, mode, value)
accepts modes 0 Default and 2 Explicit; mode 1 is not meaningful for glyphs.
addGlyph(name, ascii) creates a custom glyph with its required ASCII value;
the other representations can then be set explicitly. removeGlyph(name)
removes a custom glyph.
ThemeDocument.themeData returns a fresh Wren theme-data snapshot for the
draft. Theme.fromData(data) decodes such a snapshot without changing the
process-wide selected theme. dirty, canUndo, and canRedo report the
document state; undo() and redo() return whether they changed it.
importTheme(filename) replaces all style and glyph sections from an
installed theme as one history entry while retaining the document filename
and metadata. It preserves custom definitions and unknown content rather
than limiting the import to the built-in registry.
ThemeDocument.save(filename, force) persists only, returning null/MenuError
instead of the former [code, error] pair. A null filename saves to the current
basename. Native save failures use code == null and their distinct enum in
nativeCode; they are not portable IOErr values. The named ThemeSaveErr constants
preserve the native enum: ok=0, invalid=1, conflict=2, exists=3, readOnly=4 and io=5.
Success is null. Host safe-mode rejection uses IOErr.readOnly with nativeCode null,
rather than inventing a native call/result. A true force permits overwriting after
conflict or exists; it bypasses neither validation nor safe mode.
Save preserves untouched source text, writes through the destination without replacing its filesystem entry, and clears editing history after successful write and close. Symbolic/hard links retain their relationship; write/close failure can leave partial contents. Saving does not change the active theme or its generation.
ThemeDocument.activate() installs an independent native copy of the document’s
resolved in-memory theme and returns null/MenuError. It requires a clean, saved
document matching the manager’s committed local theme under the existing platform
filename identity rules. Unsaved, dirty, differently selected, Classic and cloud
selections return IOErr.invalidArgument. Allocation failure leaves the active theme,
preview and generation unchanged. Success clears temporary preview and advances
Host.themeGeneration once; selection, Settings generation, document history and
files are unchanged. Activation performs no filesystem I/O, including when the
backing file has been removed or edited externally, and is allowed in safe mode.
Later document edits or collection do not modify the installed copy. Native APIs
continue to own manager/document lifetime; no new script resource owner is created.
The editor confirms replacement only for conflict/exists, then saves with explicit force if accepted. After saving it activates only a matching selected local theme, using the native identity guard rather than Wren filename case assumptions. Failure to activate is reported as saved-but-not-activated; the document stays clean and persistence is treated as complete. There is no automatic resave or activation retry.
var failure = document.save(null, false)
if (failure != null) {
System.print(failure.message)
} else {
var activation = document.activate()
if (activation != null) System.print(activation.message)
}
The shipped menu_theme_editor module keeps the document rows as the editing
source of truth and builds a separate Theme.fromData(document.themeData)
snapshot for each draft refresh. Its cascade inspector distinguishes file
values, explicit inheritance, compiled defaults, compiled inheritance, and
absent roles for every field. The interactive widget preview reports the
theme role associated with its focused control and can return that role to
the exhaustive atlas. Glyph values are chosen as raw bytes from 16-column
CP437 and printable-ASCII grids rather than entered as decimal integers.
These operations remain menu-VM-only because they retain and modify a
ThemeDocument.
Menu List Encryption
Menu.encryptionInfo returns a fresh, read-only ListEncryptionInfo
snapshot of the personal list in memory, or null if no list model is loaded.
Plaintext is a snapshot with format == ListEncryptionFormat.plain,
algorithm == MenuEncryption.none, keyBits == 0, and kdf == ListEncryptionKdf.none.
It is distinct from an absent model. This getter performs no I/O or rewrite.
Snapshots have no public constructor or setters. They copy scalar metadata, retain no secrets or borrowed pointers, and remain usable and unchanged after reloads, encryption changes and failed operations. Invalid native metadata, including integers outside Wren’s exact Number range, aborts the calling Fiber. These classes and Menu operations are available only in the menu VM.
| Snapshot property | Result |
|---|---|
|
|
|
A |
|
Key length in bits, or zero for plaintext. |
|
|
|
|
|
Actual PBKDF2 iteration count; otherwise |
|
Actual scrypt cost exponent (N = 2^costLog2); otherwise |
|
Actual scrypt parameter r; otherwise |
|
Actual scrypt parameter p; otherwise |
|
Native recommendation Bool; reading it performs no rewrite. |
MenuEncryption defines none (0), tripleDes (1), idea (2), cast (3),
rc2 (4), rc4 (5), aes (6), and chacha20 (7). Legacy cipher values
identify loaded files; they do not enable legacy writes. The former
Menu.encryptionAlgorithm, Menu.encryptionKeySize, and Menu.encryptionName
getters are removed in v2. Use one snapshot for consistent reporting:
var info = Menu.encryptionInfo
if (info != null) System.print(info.name)
The shipped encryption dialog shows Change Password only when encryption is available and the loaded combination is writable: AES-128, AES-256, or ChaCha20. Unsupported loaded combinations (including AES-192) retain explicit conversion and decryption choices. SyncTERM reads the file metadata; users do not need to parse or enter headers.
Menu.setEncryption(algorithm, keySize, password) rewrites the current
personal list and returns null/MenuError. AES accepts 128- or 256-bit keys;
ChaCha20 accepts zero to select its fixed 256-bit key (explicit 256 is also
accepted), and unencrypted lists use key size zero. The current kdfShift
is used when encrypting, changing algorithms, or changing a password.
password may
be null to reuse the password already held by the host. Enabling
encryption fails if neither source supplies a non-empty password. A
successful rewrite updates the current algorithm, key size, and held
password; a failure leaves them unchanged. The operation is disabled
in safe mode, where it returns IOErr.readOnly without rewriting the list or changing
the algorithm, key size, or held password.
Menu Web Lists
Menu.webLists returns a fresh List of [name, uri] rows. Names must contain
1..50 Unicode scalars and at most 100 UTF-8 bytes, be canonically
caseless-unique, and have no controls, leading or trailing Unicode whitespace,
or =/:, and cannot begin with ; or [. System List is reserved.
Indexes refer to the order shown by that returned List. Menu.webListsDirty
reports whether the in-memory list has unpersisted edits.
| Method | Description |
|---|---|
|
Fetch the URI into the web-list cache and insert the in-memory entry.
Returns |
|
Change an in-memory entry’s URI. Returns null/MenuError. It does not refresh the cached list. |
|
Remove an in-memory entry. Returns null/MenuError. |
|
Persist the in-memory entries to the |
|
Fetch the current URI into the cache without changing configuration.
Returns |
In safe mode, add, update, and delete still update the running configuration,
and add still performs its initial fetch. saveWebLists() returns IOErr.readOnly
without writing syncterm.ini, so those changes last only for the current
process. Refresh remains permitted. No web-list method exposes its cache
pathname as a file capability.
Menu Custom Fonts
Each menu host owns a custom-font draft separate from the loaded console font
slots and from unrelated program settings. Menu.fonts returns a fresh List
of MenuFont handles. Menu.fontsDirty reports whether that draft has unsaved
edits.
| Method | Description |
|---|---|
|
Return whether another custom-font record can be added. This includes the available custom slots and safe mode. |
|
Insert a blank custom font at |
|
Merge only the draft’s |
|
Activate the installed custom-font configuration using the existing native loader. Returns null/MenuError. Failure preserves previous live mappings. Native missing/unsupported bitmap skip rules are unchanged. The bundled editor saves first, then activates, and reports activation failure without resaving. |
|
Discard unsaved font edits and reread only the |
|
Read/write the display and INI-section name using the same nonempty,
INI-safe and case-insensitively unique rules as |
|
Configured pathname String for display, or |
|
Assign a path from a live, read-authorized |
|
Clear one configured size and return null/MenuError. |
|
Remove the record from the in-memory model and return null/MenuError. Call
|
MenuFontSlot values and their picker masks are:
| Constant | Code | Bytes | Typical mask |
|---|---|---|---|
|
0 |
2048 |
|
|
1 |
3584 |
|
|
2 |
4096 |
|
|
3 |
10240 |
|
Create and delete advance the font-model generation, invalidating all
previously obtained MenuFont handles. Rename, file assignment,
clear, and save preserve handles. Font mutation, activation and persistence return IOErr.readOnly
in safe mode; reload remains available because it only reads
the existing configuration.
Menu BBS Constants
Profile properties use the following numeric constants in both menu and connected VMs. Prefer the catalogs returned by Menu when constructing a user-facing choice list.
ConnType
| Constant | Code | Description |
|---|---|---|
|
0 |
Unset / not yet decided. |
|
1 |
RLogin (TCP/513) — classic BBS auth-on-connect protocol. |
|
2 |
RLogin with the handshake byte order reversed (some servers). |
|
3 |
Telnet (TCP/23) — IAC negotiation in NVT mode. |
|
4 |
Raw TCP — no protocol layer; bytes pass straight through. |
|
5 |
SSH-2 — encrypted with password / key authentication. |
|
6 |
SSH-2 with the "none" authentication method (anonymous). |
|
7 |
Phone modem dial-out via AT commands. |
|
8 |
Direct serial port. |
|
9 |
Serial without RTS/CTS hardware flow control. |
|
10 |
Local subprocess (shell command). |
|
11 |
MajorBBS / Worldgroup "GHost" client interface. |
|
12 |
Telnet over TLS (TCP/992). |
|
13 |
Synchronet node terminal stream over MQTT 5/TLS. |
|
14 |
Binary Telnet over WebSocket (TCP/80). |
|
15 |
Binary Telnet over WebSocket with TLS (TCP/443). |
Emulation
| Constant | Code | Description |
|---|---|---|
|
0 |
ANSI-BBS — ANSI X3.64 / VT-style escape sequences with PC-style color attributes. The default. |
|
1 |
Commodore 64 / 128 PETSCII control codes. |
|
2 |
Atari 8-bit ATASCII control codes. |
|
3 |
UK Prestel / Viewdata teletext — block mosaic graphics, double-height, conceal. |
|
4 |
BBC Micro Mode 7 teletext. |
|
5 |
Atari ST GEM VT-52 emulation. |
BBSListType
| Constant | Code | Description |
|---|---|---|
|
0 |
User-edited entry from the user’s BBS list. |
|
1 |
Entry from a shared, system-web or named-web list. Read-only in its source directory. |
TLSVersion
| Constant | Code | Description |
|---|---|---|
|
0 |
No authenticated TLS version has been recorded. |
|
1 |
TLS 1.2. |
|
2 |
TLS 1.3. |
ScreenMode
Standard modes encode their dimensions in the name (e.g. c80x25 =
80 columns × 25 rows). Codes are stable enum values.
| Constant | Code | Description |
|---|---|---|
|
0 |
"Don’t change" — keep the current mode. |
|
1 |
80×25 (CGA / VGA standard). |
|
2 |
80×25 with LCD-style cell aspect (SyncTERM-specific). |
|
3 |
80×28 (extended VGA). |
|
4 |
80×30 (extended VGA). |
|
5 |
80×43 (EGA-extended). |
|
6 |
80×50 (VGA 8-pixel-tall cell). |
|
7 |
80×60 (extended VGA). |
|
8 |
132×37 (Super VGA). |
|
9 |
132×52 (Super VGA). |
|
10 |
132×25. |
|
11 |
132×28. |
|
12 |
132×30. |
|
13 |
132×34. |
|
14 |
132×43. |
|
15 |
132×50. |
|
16 |
132×60. |
|
17 |
Commodore 64 (40×25 PETSCII). |
|
18 |
Commodore 128 (40-column mode). |
|
19 |
Commodore 128 (80-column mode). |
|
20 |
Atari 8-bit native (40×24 ATASCII). |
|
21 |
Atari 8-bit with XEP80 80-column expansion box. |
|
22 |
Custom dimensions configured per-BBS. |
|
32 |
CGA 80x25, 640x200 with an 8x8 cell and 4:3 display aspect. |
|
23 |
EGA 80×25 with hardware-accurate pixel aspect (8×14 cell). |
|
24 |
VGA 80×25 with hardware-accurate pixel aspect (8×16 cell). |
|
25 |
Prestel teletext (40×24). |
|
26 |
BBC Micro Mode 7 (40×25 teletext). |
|
27 |
Atari ST 40×25 (low-res color). |
|
28 |
Atari ST 80×25 (medium-res color). |
|
29 |
Atari ST 80×25 monochrome (high-res). |
|
30 |
Amiga 640×200 pixel canvas, displayed at 4:3. |
|
31 |
Amiga 640×400 pixel canvas, displayed at 4:3. |
AddressFamily
| Constant | Code | Description |
|---|---|---|
|
0 |
As per DNS (default): connect only to the system resolver’s preferred address, IPv4 or IPv6. |
|
1 |
Connect only to the preferred IPv4 address. |
|
2 |
Connect only to the preferred IPv6 address. |
|
3 |
Race IPv4 and IPv6 addresses with attempts staggered by 250 ms. Use the first successful connection and close the others. Extra connections can allocate BBS nodes or activate serial bridges; this mode is opt-in. |
MusicMode
Controls how SyncTERM interprets ANSI music sequences (CSI … character).
| Constant | Code | Description |
|---|---|---|
|
0 |
SyncTERM’s strict mode — only the CSI MNML sequence triggers music; less-anchored sequences are passed through as text. The default. |
|
1 |
BANSI-style — older BBS music parsing rules. |
|
2 |
Most permissive — all forms accepted. |
GraphicsMode
| Constant | Code | Description |
|---|---|---|
|
0 |
Remote graphics disabled for this connection. |
|
1 |
RIPscrip v1.54 compatibility mode. |
|
2 |
SyncTERM’s "idealized" RIP v3 — bug-fixed and extended; not bug-compatible with v1.54. |
|
3 |
Practical SkyPix dialect, with Kickstart 1.3 rendering. |
|
4 |
Practical SkyPix dialect, with Kickstart 3.1 rendering. |
|
5 |
IGS 2.21 Atari ST graphics; see coverage. |
|
6 |
BIG 1.03 terminal graphics; see current coverage. |
|
7 |
DDO F/X 2.0. See current coverage. |
Selecting IGS presets Atari ST 40x25 (320x200), Atari ST encoding and font.
The ST 80x25 colour and monochrome modes are also available. UTF-8 can be
selected while retaining ST glyphs. IGS and RIP enter the same pre-ANSI
receive stage; ordinary bytes continue to the selected base emulation.
Profile.graphics stores the entry’s initial engine. CTerm.graphicsMode
reports the engine active on the connection, including changes negotiated
with the graphics APCs in the terminal protocol reference.
Selecting BIG presets ScreenMode.ega80x25 (640x350), CP437 and the original
IBM console font. ScreenMode.cga80x25 (640x200) and ScreenMode.c80x30
(640x480) are also supported initial profiles; UTF-8 retains the CP437 glyph
mapping. An unsupported or Current profile starts in EGA without rewriting
the saved profile. BIG mode installation selects the exact 8x8, 8x14 or 8x16
ROM bank. A different console font/codepage or unsupported screen choice in
the editor switches back to ordinary emulation. BIG shares the same pre-ANSI
receive insertion as IGS/RIP. All45 BIG command entries have native integration;
the coverage ledger records verification and the native protocol adaptations.
Both SkyPix variants use
the practical protocol recorded in SkyPix conformance,
Pearl 8 by default, measured native-glyph wrapping and 50 Hz delays including
short delays. Command 17 selects eight/sixteen colours; brush palettes apply
on first blit and promote depth when required. Kickstart differences concern
ellipse arithmetic and per-character proportional-glyph overhang. Selecting SkyPix initially presets
ScreenMode.amiga640x200 (4:3) and Latin-1. ScreenMode.amiga640x400 is also
available at 4:3, with an 80×50 system grid of 8×8 cells. Native Amiga font
strikes retain their pixel dimensions in either mode; the 400-line canvas
provides more vertical space. Screen Mode selects the pixel canvas,
Encoding selects the wire encoding, and Font selects an installed or bundled
Amiga family/height for initial text and reset. These choices remain editable.
The system cell grid comes from the screen mode, independently of the native
Amiga text metrics; graphics clip to the drawable area. The optional status row
uses the last system-cell row inside the selected mode; resolution and aspect
ratio remain unchanged. Ordinary Profile.font remains available
for other graphics modes. Classic Amiga fonts are byte-indexed and carry no
charset tag; codepage connections use that codepage’s glyph positions, and
UTF-8 text uses Latin-1 glyph mapping. C1 positions may contain glyphs even when
a selected terminal decoding mode interprets those bytes as controls.
CTerm.skypix reports the selected graphics engine, rather than inferring it
from a remote command. RIP sessions do not interpret SkyPix commands.
SkyPix command-16 transfers accept IFF brushes (type 1), IFF sound (type 2),
FutureSound samples (type 3), and general files (type 20). All use CRC XMODEM
and the active BBS’s shared SkyPix cache subdirectory, matching SkyTERM’s
single BRU: destination. Completed files are reused; partial or invalid
brush downloads are discarded. Types 2, 3 and 20 preserve cached bytes, including
XMODEM padding, without replacing the current brush. Type 3 also loads the
sample after receipt or on a cache hit; an unsuccessful load leaves the file
cached and retains the previous sound. Type 2 has no IFF sound decoder.
They do not use RIP asset framing. Gadget command
22 retains the definition in slot 1–20 and draws its foreground rectangle;
clicks still report raw controller-1 pixel coordinates. Controller-2 menu reports
and local execution of stored gadget commands remain unsupported. See
SkyPix conformance for the precise supported subset.
Type-3 samples contain a big-endian unsigned 32-bit PCM-byte count and unsigned 16-bit rate, followed by signed 8-bit mono PCM. The declared payload must be present, positive, and no larger than 4 MiB; the rate must be nonzero. Odd lengths are accepted and trailing bytes are ignored. Command 9 uses only its loop count and plays the entire sample. Zero deliberately means one play; the originals instead wait indefinitely for continuous playback.
SkyPix uses the shared effects stream (logical channel 1), independently of
channel-0 music, with its existing gain/pan. A custom incremental linear
converter uses the originals' 16-bit period (3579545 / rate) & 65535 and
converts its effective rate to 44100-Hz stereo. It does not emulate analog
filters or artificial gaps at Amiga device-write boundaries. Remote parsing
waits for playback and backend latency while local UI continues. Synchronous
connected/menu/picker input waits service pending audio without consuming remote
input or extending the requested input deadline. Reset/EOF
cancel playback; reset/destruction release the loaded sample. Disabled or
unavailable audio skips playback and the wait. There is no new script audio API.
Parity
| Constant | Code | Description |
|---|---|---|
|
0 |
No parity bit (8N1 framing). |
|
1 |
Even parity bit. |
|
2 |
Odd parity bit. |
FlowControl
Constants for the numeric Profile.flowControl setting.
| Constant | Code | Description |
|---|---|---|
|
0 |
RTS/CTS hardware flow control. |
|
1 |
XON/XOFF software flow control. |
|
2 |
Hardware and software flow control. |
|
3 |
No flow control. |
LogLevel
Standard syslog severity values (RFC 5424). emergency is the most
severe; debug is the least.
| Constant | Code | Description |
|---|---|---|
|
0 |
System is unusable. |
|
1 |
Action must be taken immediately. |
|
2 |
Critical condition. |
|
3 |
Error condition. |
|
4 |
Warning condition. |
|
5 |
Normal but significant. |
|
6 |
Informational. |
|
7 |
Debug-level diagnostic. |
Host
Module-private bridge for state the host owns but Wren shouldn’t
be able to construct directly. The members below are foreigns;
the Cache / Download module-level vars (see below) are
pre-bound from these at module load.
| Member | Description |
|---|---|
|
Monotonic process-wide generation for the active theme. Preview, cancellation, and committed selection changes advance it. |
|
Return fresh immutable-by-ownership snapshots of the active theme and
compiled fallback respectively. Each result is |
|
Returns a fresh |
|
Returns a fresh |
|
The BBS’s configured |
|
User-consent escape hatch for "upload from anywhere": invokes the
isolated picker VM and returns a |
|
The same consent picker with a caller-supplied title String. The title changes only the picker presentation and grants no additional file authority. |
|
Multi-select counterpart of |
|
Save-mode picker with path entry and overwrite confirmation. The user
can pick an existing file or type a new filename. The picker reports
create, overwrite, or append consent explicitly, and the caller does not
stat the path again. The two-argument form offers overwrite for existing
files. Pass |
|
Re-construct a |
|
Status-bar transfer-indicator arrows (CP437 ↑ / ↓, painted by the
default Status render at the row’s right edge).
Generic — any Wren script that knows it’s transferring something
can light them; the canonical user is the SFTP queue’s worker
fibers, but a Zmodem / HTTP fetcher / etc. could too. Pure
Wren-side state on the |
|
|
|
|
|
|
|
Display name of the modifier key that produces Alt keycodes on
this platform. |
|
Write |
|
Full path of the Wren script supplied via the |
|
Wren-console activity since the user last visited the REPL.
|
|
ANSI music mode display strings and help blurb, returned as a
fresh |
|
Throttled-output ladder. |
|
Transfer log threshold ( |
|
|
|
Highest valid OOII mode value ( |
|
Suspend terminal byte consumption and enter the persistent trusted menu VM over a saved copy of the connected screen. The connected VM is parked, no Wren or foreign object crosses between VMs, and trusted input barriers discard queued synthetic keyboard and mouse input in both directions. On return, the host restores the terminal screen, title, scrollback configuration, and prior suspension state. This is the default Alt+E path. |
|
The first locally-configured SSH public key, as a Map
|
FilePickerOptions
Public option bits for Host.pickFile and Host.pickFiles. The
numeric assignments are stable so scripts may combine or persist them.
| Member | Value | Meaning |
|---|---|---|
|
0 |
No optional behavior. |
|
1 |
Display the mask but do not let the user edit or replace it. |
|
2 |
Match file and directory masks case-sensitively. |
|
4 |
Sort entry names case-sensitively. |
|
8 |
Select a directory rather than a file. |
|
16 |
Reject a typed path which does not exist. |
|
32 |
Reject a typed filename which does not exist. |
|
64 |
Include hidden entries in directory listings. |
|
256 |
Allow the always-visible Path field to receive focus and accept a
typed directory or filename. Single-file pickers which permit a new
path (neither |
|
512 |
Ask before accepting an existing destination. |
|
1024 |
Ask before accepting a destination which does not exist. |
|
2048 |
Save picker only. When an existing destination is selected, offer Append alongside Overwrite and Cancel. |
allowEntry, confirmOverwrite, confirmCreate, and allowAppend are
invalid with Host.pickFiles. Host.pickSavePath(initialDir, mask)
supplies its save-mode options itself. Its three-argument overload
accepts save-picker option bits; currently only allowAppend is
meaningful there.
Cache
Module-level Directory injected from C (pre-bound from
Host.cacheDirectory), pointing at SyncTERM’s per-user cache
directory (SYNCTERM_PATH_CACHE). Use this for script-private
state that should survive restarts.
The visible syncterm-cache-name.txt file in each BBS cache records its entry
name. It is reserved for SyncTERM and excluded from script cache grants and
APC/RIP cache operations. Hash collisions use numbered directory suffixes; scripts
receive the directory matching the stored name automatically.
Cache.list returns a Map keyed by entry name; values are File
objects for regular files and Directory objects for subdirectories.
That’s the read-side handle factory — a script reads existing cache
content by indexing into Cache.list, and creates new content with
Cache.create(name):
import "syncterm" for Cache, FileError
var entries = Cache.list
if (entries is FileError) Fiber.abort(entries)
var f = entries["greetings.txt"]
var firstRun = f == null
if (firstRun) f = Cache.create("greetings.txt")
if (f is FileError) Fiber.abort(f)
var opened = f.open()
if (opened is FileError) Fiber.abort(opened)
var result = firstRun ? f.write("Hello, world!") : f.read()
var closed = f.close()
if (result is FileError) Fiber.abort(result)
if (closed is FileError) Fiber.abort(closed)
if (!firstRun) System.print(result)
// Subdirectories appear in the same map. Walk into them by chaining
// `.list` lookups:
// Cache.list["RIP"] → Directory for /RIP
// Cache.list["RIP"].list["icons.dat"] → File inside /RIP
There is no Wren-callable factory for Directory — Cache,
Download, and Cache.list[someSubdir] (and the analogous
Download.list[…]) are the only paths to one.
Download is a module-level Directory binding pre-bound from
Host.downloadDir at import time. It is null when the
configured DownloadPath is empty, set to the user’s $HOME,
or doesn’t exist as a directory on disk; scripts MUST null-check
before use. Its relaxed-name predicate is what makes typical
SFTP filenames ("file with spaces.zip", "doc-v1.0.tar.gz")
usable as local paths in transfer queues.
There is intentionally no Upload counterpart. All uploads must
go through Host.pickFile / Host.pickFiles, which mint a
per-file consent token tied to the file’s content hash. The
script then enqueues uploads by token (File.token); the worker
re-opens the source via Host.openLocalFile(token). Use
Host.uploadPath to feed the configured UploadPath to the
picker as initialDir.
Filesystem results
Local and remote filesystem APIs use these result conventions. Remote methods return an Operation; the table describes its completed value.
| Operation | Result |
|---|---|
Create/open a resource |
The requested resource object or an Error. Local |
Mutation or close |
|
|
A nonempty byte String, including a successful short read; |
Zero-byte read |
|
Zero-byte |
|
|
Complete file bytes from offset zero, including |
|
|
|
A line String (including |
|
Bool for presence/absence; |
Every filesystem error inherits from Error. Check result is Error when
either domain is possible, or the concrete class when inspecting its native
details. Invalid arguments, invalid names, missing rights and operations on
closed/closing streams abort the calling fiber before native I/O. Repeated
close is allowed. Property setters return the assigned Number on success or
FileError on a recoverable failure; their result can be captured explicitly.
Byte data is never UTF-8-validated or normalized. Local/remote path names and picker strings use the normal host text boundary: valid UTF-8 normalized to NFC, without NUL. This does not change Wren’s String semantics.
Directory
Opaque handle containing a directory pathname grant. The grant applies to the pathname, not to a particular filesystem object that occupied it when the handle was created.
| Method | Description |
|---|---|
|
|
|
A Map keyed by entry name; values are |
|
Atomically create a new zero-byte file named |
|
Atomically create a new subdirectory named |
|
Remove the entry named |
|
Atomically replace a regular file with the complete byte String. The
host writes and closes an exclusive sibling temporary file before the
rename, so any write or close failure leaves the prior file unchanged.
Returns |
Pathname grants
File and Directory foreign objects retain an absolute pathname and the
operations granted for that pathname. They are not filesystem snapshots and
do not preserve the identity of a particular file or directory. A closed
handle therefore addresses the current entry at its pathname. Removing,
replacing, or recreating that entry does not revoke the grant, whether the
change came through Directory.delete or from outside SyncTERM.
Operations validate the state they require. An unavailable pathname returns
FileError with the native reason (IOErr.notFound, notDirectory,
permissionDenied, etc.); it does not revoke the grant. A recreated directory
or file can be used through the same grant. File.path, File.token, and
Directory.toString report stored metadata without filesystem access.
File.close() is also independent of pathname availability.
Open files are exempt
A File whose stream is currently open (between File.open() and
File.close()) performs stream operations on that opened stream and bypasses
the closed-path existence check. This matches platform reality:
-
On Unix, an open file descriptor remains valid after the path is unlinked; reads and writes continue to work, and the inode is freed only when the last reference closes.
-
On Windows, deleting a file that’s currently open fails at the OS layer, so the situation never arises.
After File.close(), a later open resolves the pathname again and may open a
replacement file. Properties implemented as pathname operations, including
mtime and digest(algorithm), continue to resolve the pathname even while a
stream is open. Stored metadata properties do not access the filesystem.
Filename Policies
Directories below Cache use the strict portable cache-name policy:
-
Length 1..64 bytes.
-
Characters from
[A-Za-z0-9._-]only. -
Must not begin with
.or-. -
Must not end with
.. -
Must not contain
... -
Must not match a Windows reserved device name (
CON,PRN,AUX,NUL,COM1..COM9,LPT1..LPT9), case-insensitively and with or without an extension.
Directories below Download use the relaxed safe-leaf policy. Names are
1..255 bytes, must not be . or .., and may not contain a path separator,
NUL, an ASCII control byte, DEL, or a Windows reserved device basename.
Spaces, leading dots or dashes, trailing dots, parentheses, and non-ASCII
bytes are otherwise accepted. Descendant directories inherit their root’s
policy. Invalid names abort every directory method before filesystem access.
Names are validated as UTF-8 and normalized to NFC before the name policy
checks and filesystem access.
File
Every File carries rights assigned by the host when it is created:
-
Files reached through
CacheorDownloadare read/write. -
Files returned by
Host.pickFile/Host.pickFiles, or reconstructed byHost.openLocalFile, are read-only.open()usesrb; write methods andmtime=()abort the fiber. Read-consuming bindings such asScreen.loadFont()accept these Files. -
Files returned by
Host.pickSavePathare one-shot write-only grants. Read methods, hashes, and read-consuming bindings reject them. See Write consent.
Permissions apply to the stored pathname, not to a particular file object at
that pathname. The foreign handle retains those permissions so a script
cannot substitute a different pathname. Passing a File to another binding
does not broaden its authority.
| Method | Description |
|---|---|
|
Open the file using the mode authorized by its host-assigned rights.
Sandbox Files use |
|
Close the stream; returns |
|
Read up to |
|
Same results at an absolute offset; restore the current offset even after a successful short read or EOF. Zero count performs no seek. |
|
Read file bytes from offset 0, returning |
|
Write the byte String at the current or given offset. Returns |
|
Replace file contents with |
|
Resize an open writable file to an exact nonnegative integer byte length;
see Native integer limits. Shrinking discards the tail; extending fills
the added bytes with zero. Preserve the current offset, even beyond the new
EOF. Synchronizes buffered input/output first, so later reads cannot return
discarded bytes and buffered writes cannot regrow the truncated tail.
Zero and unchanged lengths still perform the native operation.
Returns |
|
Read from the current offset to the first LF (0x0A) or EOF and
return the bytes read with LF and its optional preceding CR removed.
An unterminated trailing CR is preserved. Advances the
offset past the LF on a hit, or to EOF if none was found. Returns
|
|
Write |
|
Current read/write position. Nonnegative exact integer; see Native integer limits. |
|
Length in bytes, subject to Native integer limits. Flushes this stream’s buffered writes before querying native metadata; flush failure is a FileError. |
|
Signed POSIX seconds within Native integer limits. The setter uses
the native filesystem API by path, requires write rights, and works on open and closed
handles. Pending output is flushed first. A filesystem which ignores or
rounds a timestamp returns |
|
|
|
Opaque consent token for picker-sourced |
|
Hash the complete file using a |
A closed File whose pathname is unavailable returns a
FileError with the native reason, such as IOErr.notFound from the
existence check, whether the entry was deleted through Directory.delete or
outside SyncTERM. The pathname grant remains valid. If a regular file is
later created at the same pathname, the original File can open it.
Write consent
Files minted by Host.pickSavePath carry a
write-only consent — a single-shot grant to open the user-picked path
exactly once, in a specific mode determined at pick time:
| Picker outcome | open() mode |
|---|---|
Path didn’t exist at pick time |
|
Path existed and the user confirmed overwrite |
|
Path existed and the user selected append |
|
The consent is consumed by the first successful open(). After
the matching close(), every subsequent open() / writeBytes /
write / writeLine / etc. aborts the fiber with "write consent
already used". Re-pick the path to write again.
The grant never includes read authority. read, readBytes,
readLine, digest(algorithm), and bindings which consume a readable File
reject a save-picker File, both before and while it is open.
File.token is null on write-consent Files: persisting a write
consent across sessions would defeat the single-shot rule. The
existing token mechanism is exclusively for read consent (the
Host.pickFiles / openLocalFile upload-resume flow).
Other bindings consume write consent on the caller’s behalf:
-
Host.pickSavePathmints the consent. -
Capture.start(file, raw)— opens for streaming-log output and transfers the FILE pointer into `cterm’s logfile. -
CTerm.saveScreenshot(file, withSauce)— writes the screen as IBM-CGA / BinaryText with optional SAUCE block.
After any of these calls the File is inert — calling open() on it
yourself is no longer valid.
FileError
FileError represents a recoverable local filesystem failure, following
Filesystem results. Its portable code describes the native reason rather
than the operation which happened to fail. Existing targets, missing paths,
permissions, full storage and native range failures remain distinguishable.
The fixed-purpose Emoji.recordUse operation also returns FileError for failure to
persist recents; its session update has already occurred and its errno is zero.
| Member | Description |
|---|---|
|
Stable negative native |
|
Captured C errno when available; zero for native APIs without errno
or a synthesized failure. Interpret |
|
Operation-specific diagnostic text, or |
|
Numeric code and diagnostic, plus errno when present. |
IOErr exposes all shared native I/O reasons in every script VM. In v2 it
replaces FileErr without an alias; FileError remains the filesystem error type:
| Constant | Code |
|---|---|
|
-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 |
Success is null, never a zero-code error. EOF is a read result, never a
FileError. Programmer errors (wrong types, invalid names/counts/offsets,
missing rights, unopened streams, opening an already-open stream) abort;
check the input contract rather than treating them as recoverable I/O.
The binding manages C update-stream direction changes and buffered writes. Scripts may mix reads/writes without inserting C-specific seeks or flushes. The current offset remains a logical stream position; metadata queries that need pending output flush it and report any failure normally.
Picker consent tokens
Wren scripts must not synthesize File foreigns from arbitrary
paths — that’s the whole point of the Cache / Download
sandboxed roots and the relaxed-name predicate. The escape
hatch is Host.pickFile / Host.pickFiles, where the isolated
picker interaction is the user’s signal of consent.
To let queued picker-sourced uploads survive a disconnect, the
picker mints a capability token at consent time: an
HMAC-SHA256 binding of the absolute path and the file’s SHA-256,
signed by a per-installation key stored in the user’s encrypted
syncterm.lst. Wren can store the token freely (it’s opaque
bytes — exposed via File.token and accepted by
Host.openLocalFile); only the C side can mint or verify one.
The file-content hash routes through DeuceSSH’s
hardware-accelerated digest backend (Intel SHA-NI / ARM crypto
extensions, via OpenSSL or Botan) when the build has it, so
signing/verifying a multi-GB picked file stays in the
sub-second range on commodity hardware. WITHOUT_DEUCESSH
builds fall back to xpdev’s pure-C SHA-256 (src/hash/sha256.c)
— correct, just slower on huge files; signing key generation
in that build seeds from /dev/urandom (or time/PID) via
xp_random rather than the SSH backend’s CSPRNG.
At resume time, Host.openLocalFile(token) verifies:
-
The HMAC matches (token wasn’t tampered with; signing key hasn’t rotated).
-
The file at the encoded path still exists.
-
The file’s current SHA-256 still matches the SHA-256 captured at consent time.
Any failure returns null; the queued upload should be marked
failed and the user prompted to re-pick. The content hash
binding is deliberate: if the file’s content has changed since
consent, the original consent doesn’t authorize uploading the
new content.
The signing key is loaded only from the user’s personal BBS list
(USER_BBSLIST) — never from shared/system or web-fetched
lists. This stops a malicious shared list from injecting a
known key and forging tokens against the local install. Key
rotation is manual: remove the WrenPickerHmacKey line from
syncterm.lst; SyncTERM regenerates on next launch. All
in-flight picker tokens become invalid.
Host.pickFile / Host.pickFiles continue to work even when
the signing key is unavailable (e.g. an unencrypted list, OOM
during generation) — the returned File`s have `null .token,
so picker uploads in such sessions don’t persist across
reconnects but otherwise behave normally.
Hook
The dispatcher registry. See Hook Events for the contract on each method, and HookHandle for the return type.
Hook.onKey(fn), Hook.onPhysicalKey(fn), Hook.onInput(fn),
Hook.onMouse(fn), Hook.every(ms, fn),
plus the filtered variants Hook.onKey(key, modifiers, fn), Hook.onInput(byte,
fn), Hook.onPhysicalKey(evdev, fn), Hook.onMouse(event, fn), and
Hook.onMatch(pattern, fn).
Each call returns a HookHandle.
Status
Wren-driven status bar. The host invokes a single render callable
on every status-bar update with a width×1 Surface that has been
pre-filled to the default attribute (yellow on blue, spaces). The
callable mutates cells in place and returns; its return value is
ignored.
In RIPv3, the supplied cells use the active RIP text-window font after a text-window font change. Other emulations retain the local status font.
import "syncterm" for Status, Surface, Screen, Session, CTerm
Status.callable = Fn.new { |surf|
if (!Status.enabled) return
var s = "%(Session.current.name) | %(Session.current.profile.connTypeName) | %(Session.current.profile.bpsRate) bps"
var x = 1
for (ch in s) {
var columns = Screen.textWidth(ch, surf[0].font)
if (columns == 0) continue
if (x + columns > surf.width) break
surf[x].ch = ch
x = x + columns
}
}
In a connected terminal, a left click on an OSC 8 hyperlink activates its actual destination. Ctrl+click also detects plain-text URLs and remains a local action when the BBS has enabled mouse reporting; ordinary clicks then continue to the BBS. A locally activated gesture is consumed through release or drag end so it cannot open twice or send an unmatched mouse release. Opening uses the desktop URL handler for HTTP, HTTPS, FTP, and FTPS. Other schemes, unavailable handlers, and safe mode copy the URI to the clipboard and show a notice unless popups are hidden. These actions are attached to user input and do not grant connected scripts a URL-launch API.
The default implementation lives at
scripts/auto/connected/status_default.wren. It uses the layout
name (flags) │ ConnType │ speed │ HH:MM:SS │ ALT-Z menu with
right-pinned indicators for mouse mode (M) and SFTP transfers
(arrows). To override it, place a same-named file in the auto-load
directory, or set Status.callable = … from any later script. The
host releases the previous handle when the callable changes.
| Member | Description |
|---|---|
|
The currently installed render |
|
Install (or clear) the render callable. |
|
Optional no-argument callable returning a complete human-readable status
String. SyncTERM snapshots it when the disconnect notice appears and
shows it in the F1 details popup, so fields omitted by narrow visual
layouts remain available. Set it to |
|
The OSC 8 hyperlink destination under the last unclaimed mouse position,
or |
|
|
The recycled Surface is reallocated only when the terminal width
changes, so per-frame allocation churn stays out of the hot path.
Out-of-bounds writes (surf[i] for i >= surf.width) throw —
treat surf.width as authoritative and clip your own loops.
Transfer
Session-owned bridge between the Wren transfer UI and C protocol workers.
upload(), uploadBatch() and download() return null after starting a worker,
or TransferError if startup fails. The terminal owner continues pumping protocol input while
TransferApp renders progress and handles cancellation on a child fiber.
Workers never call Wren or CTerm. Only one in-band transfer can own a
session’s stream at a time; SFTP uses its separate SSH channel.
import "syncterm" for Transfer
import "transfer_app" for TransferApp
Fiber.new {
var error = Transfer.beginSession("fake")
if (error != null) Fiber.abort(error)
TransferApp.new("Transfer demo").run()
var result = Transfer.result
Transfer.endSession()
if (result != null) System.print(result)
}.call()
The built-in upload/download flows are available through Alt-U, Alt-D and the
online menu. ZMODEM auto-start watches the incoming bytes for Ctrl-X followed by
B00 (download) or B01 (upload). Each byte reaches normal terminal processing
as it arrives. The transfer engine checks the complete header CRC. Downloads use the configured download directory;
unsafe roots and existing non-file destinations are rejected. If the configured
directory is unavailable, the connected UI shows a notice with the Download Path
setting to change. The detector checks the directory on each request and groups
retries less than 30 seconds apart into one notice. Existing files
can be overwritten, skipped, or renamed. ZMODEM resumes a partial file only
after checking its prefix CRC against the sender.
For a DDO F/X entry, a completed ZMODEM download batch installs recognized
$LI$ command packages in that BBS’s DDOFX cache before the session resumes.
Installation errors go to the transfer log. Ordinary downloads retain their
chosen destination.
RIP block-transfer commands use that BBS’s RIP cache subdirectory instead of
the download directory. RIP 1.54 display-only and active dynamic modes render validated
blocks as they arrive, using status-row progress so a modal restore cannot erase the
scene. RIPv3 displays successfully received scenes and images after the transfer
returns, using the active RIP3 style and parser. A failed RIPv3 receive
removes the incomplete destination. Earlier completed files in the batch
retain their own completion results. Host-requested uploads always
require confirmation and read regular files in the BBS cache. RIP 1.54 accepts
one filename per upload. RIPv3 batch uploads can name several files. RIP
transfers use the same cancellation, completion and log APIs as manual transfers.
| Member | Description |
|---|---|
|
Start the synthetic 100-KiB |
|
Latch an abort if the worker hasn’t already finished, join the
thread, and clear session state. Idempotent — safe to call after
a natural completion. Returns |
|
Drain the log ring under mutex; return a |
|
Read the "tick state changed" flag under the mailbox mutex. |
|
Return |
|
|
|
Read-only completion result: |
|
Latch an abort flag the worker polls between protocol steps.
Returns |
|
Read the abort flag without modifying it. |
|
Whether a session owns a transfer and its direction. |
|
Start one file using |
|
Start a List of readable |
|
Start |
|
Pending worker decision: 0 for none, 1 for an existing file, 2 for an XMODEM filename when a YMODEM receive falls back to XMODEM. |
|
Answer a pending decision with 0 (overwrite/accept filename), 1 (skip), or 2 (rename). The worker waits on a condition variable while the owner continues pumping. Abort and disconnect also wake that wait. |
All startup methods return null or TransferError; they do not wait for
completion. Wrong argument types, malformed UTF-8, embedded NUL in protocol tokens
or required download filenames, unsupported protocol/direction, invalid handshake
bytes and invalid upload grants abort as programmer misuse. Host text normalizes
to NFC; raw file bytes do not. Native filename validation remains authoritative.
Runtime restrictions and download roots are unchanged: real transfers require a
permitted connected session, and safe mode blocks them. The internal RIP-upload
acceptance method also returns null/TransferError; no pending request is misuse.
The bundled progress App derives its success convenience property from the
completion result, retains its local aborted property and displays the actual
failure message or cancellation. Inline flows capture the result before cleanup.
Startup failures display once and do not enter the progress UI. Existing cleanup
and partial-file behavior remain; an error is not a guarantee of rollback or a
safe offset from which to retry automatically. The detailed transfer log remains
separate from the result.
TransferError
An immutable Error value, available with Transfer in each VM. It owns its
diagnostic and retains no worker or session pointer. There is no public constructor.
| Member | Description |
|---|---|
|
The exact native portable I/O integer; compare with |
|
Nonempty human-readable startup or completion diagnostic. Detailed per-file/protocol diagnostics remain in the transfer log. |
|
Includes |
Platform
OS identification and preferred UI languages. No shell execution, stdio, or process model is exposed.
| Method | Description |
|---|---|
|
OS identifier as a String. Returns |
|
Fresh, nonempty List of unique language-tag Strings in preference order,
such as |
Digest
Stateless synchronous hashing, available in menu, picker and connected VMs.
Digest.hash consumes bytes already in a Wren String; File.digest separately
uses a native file mapping and requires a readable File grant. Byte hashing
provides no filesystem authority.
| Algorithm constant | Native value / output bytes |
|---|---|
|
1 / 32 |
|
2 / 48 |
|
3 / 64 |
|
4 / 16 |
|
5 / 20 |
Digest.size(algorithm) returns the output byte length even when the selected
provider cannot compute that algorithm. It is not an availability query.
Digest.hash(algorithm, bytes) returns the raw digest bytes as a String or a
DigestError. Every input byte participates, including NUL and malformed UTF-8;
no text validation or normalization occurs. Canonically equivalent Unicode
spellings can therefore have different hashes. Compare raw results directly,
and use .bytes.count for their lengths.
import "syncterm" for Digest, Error
var hash = Digest.hash(Digest.sha256, "abc")
if (hash is Error) Fiber.abort(hash)
System.print(hash.bytes.count) // 32
Wrong input types, fractional/nonfinite numbers and unknown algorithm constants
abort the fiber before hashing or file effects. Byte-String input must also fit
the Wren C byte API’s signed-int length range; this limit does not constrain
native mapped-file input. Known algorithms whose native
operation fails return DigestError; no availability preflight or automatic
retry is performed. Builds with provider none support MD5 and SHA-256. SHA-1,
SHA-384 and SHA-512 return the native disabled status in those builds. External
providers can also fail according to their native policy; those failures are
not relabelled as disabled.
DigestError
Host-created, immutable Error subclass with read-only code, message, and
toString. code is the exact nonzero native digest status, including an
unrecognized future status. message identifies Digest.hash or File.digest
and describes the native reason; toString also includes the code. Success
returns bytes, never a zero-code error. DigestErr.failed (-1) names the generic
native failure; DigestErr.disabled (-5) names disabled digest support.
File.digest retains FileError for pathname, flush and mapping failures, and
returns DigestError for failures from the native hashing operation. Check the
common Error base if either is relevant. A pending-write flush can succeed
before hashing fails; no partial digest is returned. Input is borrowed only for
the synchronous native call, mappings are released before return, and returned
Strings and errors remain valid through later calls and garbage collection.
Text
Locale-independent Unicode 18 comparison helpers. All inputs are normalized to NFC at the Wren host boundary. Caseless matching uses full default Unicode case folding with canonical equivalence; ordering uses the non-ignorable DUCET collation table and an identical tie-break for deterministic results.
| Method | Description |
|---|---|
|
Return a List of NFC extended grapheme cluster Strings using the shared Unicode text engine. Used by UI drawing so joined emoji resolve as one glyph. |
|
Return the UTF-8 byte count after NFC normalization. Use this when checking input against byte limits on C-backed text fields. |
|
Return the NFD full-default-casefold key used by caseless equality. This is useful for retained search prefilters; use the matching methods below to verify a candidate when grapheme-cluster boundaries matter. |
|
Canonical caseless equality. |
|
Caseless prefix matching at extended grapheme-cluster boundaries. |
|
Caseless substring matching at extended grapheme-cluster boundaries. |
|
Return a negative number, zero, or a positive number using Unicode 18 DUCET ordering. The Boolean selects tertiary (case-sensitive) rather than secondary (case-insensitive) strength. |
Timer
Timers are connected-session operations. Timer.after(ms) returns an
Operation that completes with null after the delay. The delay
must be an integer from 0 through 4294967295 milliseconds. Invalid arguments,
allocation failure, and exceeding the 32 pending timers per VM abort the
calling fiber. Cancellation removes the timer immediately and frees its slot.
A zero delay completes on the next owner-loop pump, never inside after.
Timer.now returns monotonic seconds as a Num; only differences between
readings are meaningful. For recurring callbacks, use Hook.every(ms, fn).
import "syncterm" for Timer
var delay = Timer.after(250)
var result = delay.await()
// result is null, or OperationError if another owner cancelled the delay
Format
Number-to-string helpers for human-readable display. Both methods auto-pick a unit based on the magnitude of the input and use one decimal of precision; negative inputs are clamped to zero.
| Method | Description |
|---|---|
|
Format |
|
Format |
Combined idiom — display a transfer rate and ETA:
import "syncterm" for Format, Timer
var startedAt = Timer.now
var startBytes = job.done
// ... later ...
var elapsed = Timer.now - startedAt
var moved = job.done - startBytes
if (elapsed > 0) {
System.print("%(Format.bytes(moved / elapsed))/s")
var remain = job.total - job.done
if (remain > 0) {
System.print("ETA %(Format.duration(remain / (moved / elapsed)))")
}
}
SFTP
SSH-channel side-band file transfer. Each operation queues work on the
connection-owned SFTP worker and returns an Operation.
Both immediate and deferred recoverable failures are SFTPError result
values; .await() obtains the result in either case. Arguments of the wrong
type abort the calling fiber before work is submitted. Up to 256 provider
requests may be outstanding; a full queue returns a completed operation with
an SFTPError rather than accepting unbounded work.
| Method | Description |
|---|---|
|
Lazily open and negotiate the SSH SFTP subsystem. Completes with |
|
|
|
The remote |
|
|
|
Resolve |
|
Stat a remote path. Completes with |
|
Open a directory cursor. Completes with |
|
Open a file with explicit rights. Completes with |
|
Mutation ops. Each completes with |
|
Set both atime and mtime of |
|
Fetch the server’s long description for |
FileFlag
OR-able bitmask constants for SFTP.open’s flags argument; each
matches the corresponding `SSH_FXF_* wire constant.
| Constant | Wire value |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
SFTPEntry
One entry from RemoteDirectory.readEntries.
| Member | Description |
|---|---|
|
Filename relative to the parent directory. |
|
Server-formatted long name (when the
|
|
A fresh, immutable |
|
|
|
|
|
SHA-1 / MD5 digest bytes from |
SFTPStat
Result of SFTP.stat, or the metadata returned by SFTPEntry.stat. All members
are read-only; there is no public constructor. Size and timestamps follow
Native integer limits; mode, UID and GID retain their unsigned 32-bit values.
Attributes omitted by the server retain the native API’s zero defaults.
entry.stat constructs its native metadata copy only when accessed. Each access
returns a new object holding the metadata from the directory listing, without
issuing a request or refreshing it. The copy survives directory closure, entry
collection and later responses. It grants no remote-resource authority.
For current metadata, explicitly await SFTP.stat(path) instead.
In v2, SFTPEntry.size and SFTPEntry.mtime are removed. Use entry.stat.size
and entry.stat.mtime, or capture var metadata = entry.stat once when reading
several fields. Inexact size or timestamps in any listing entry fail the entire
listing Operation with a non-transient SFTPError.
| Member | Description |
|---|---|
|
File size in bytes. |
|
Modification time, POSIX seconds. |
|
Access time, POSIX seconds. |
|
SFTP-wire permission bits (Unix-style on POSIX servers). |
|
Owner user ID. |
|
Owner group ID. |
RemoteFile and RemoteDirectory
These host-created objects own a remote resource in one connected VM. They have no public constructor and cannot be used in another session. The SFTP namespace owns path operations; resource operations belong to these objects.
| Member | Description |
|---|---|
|
Read at an absolute offset. Returns an Operation completing with a nonempty
byte String, |
|
Write a byte String at an absolute offset; Operation completes with |
|
Append a byte String using the server’s current end of file. Requires an open with write and append flags; no misleading offset argument is accepted. The same native write-size limit and zero-byte result apply. |
|
The rights and append mode granted by the successful open. |
|
Read the next directory batch. Operation completes with |
|
Returns an Operation completing with |
|
Explicit resource state. Reads/writes after close starts abort. Cancelling a close Operation does not revoke the submitted native close: the object remains closing until the provider reply establishes success or failure. |
|
Run |
Pending native operations retain their receiver, even after cancellation, until their replies are drained. Collecting an abandoned open resource submits a best-effort close and tracks its reply as auxiliary work. GC is a fallback; use an explicit close or scope when completion matters. VM shutdown cancels pending work, marks every resource closed and releases ownership without resuming parked user callbacks. Shutdown cleanup never waits on the network. The browser and public-key installer use scopes; the parallel transfer queue awaits its workers before closing each resource explicitly.
var file = SFTP.open(path, FileFlag.read).await()
if (file is SFTPError) return file
return file.use(Fn.new {|source| source.readBytes(4096, 0).await() })
SFTPError
Returned in place of the typed result on any failure. Two error
layers — distinguish via code:
| Member | Description |
|---|---|
|
|
|
|
|
Human-readable diagnostic text accumulated by the
library (may be |
|
|
The toString override produces "SFTPError: <name>: <message>"
for System.print / interpolation; useful for log-line debug.
Persistent transfer queue
The shipped sftp_queue module runs one cooperative worker fiber per
direction. Jobs have stable numeric IDs; the browser and queue UI retain
selection and cancel the intended job by ID even when status sorting changes.
Duplicate pending jobs with the same direction and remote path reuse the
existing job.
Each claimed interval is filled completely, including when a successful remote or local read returns fewer bytes than requested. Parallel interval completion advances a persisted resume point only across the contiguous prefix of the file, so data beyond a gap is never treated as durable progress. Downloads stat the remote before resuming and restart from zero when its size or mtime changed. Uploads revalidate the picker consent token and fail when the local source changed; a compatible remote partial resumes from the saved frontier.
The queue stores only queued and active work in
Cache/sftp_queue.won. Schema version 2 records the next stable job ID,
source identity, cancellation request, and contiguous resume point. Version
1 documents are imported conservatively with resume set to zero. Malformed
or unsupported documents make the queue unavailable without rewriting the
file. Every mutation uses Directory.replace, so a failed persistence write
leaves the previous complete document in place and makes the live queue fatal
rather than continuing with state that cannot survive disconnect.
Ordinary transfer failures retain partial data for diagnosis or a later
explicit retry. A user cancellation removes the local download partial or
remote upload partial before publishing cancelled; a transient transport
failure suspends the queue and preserves that cleanup request for the next
connected VM. Local and remote close failures affect the final job status.
Best-effort mtime updates do not turn an otherwise complete transfer into a
failure.
Async Ops
SFTP, timers, and connection sends return an owned Operation for each
request. No caller supplies a target fiber, and immediate errors follow the same result contract
as asynchronous completion. Operations have object identity, so overlapping
requests remain distinguishable even when their result types are identical.
| Member | Description |
|---|---|
|
Bool indicating completion, including cancellation. |
|
Bool indicating explicit or abandoned-owner cancellation. |
|
Completed value or typed |
|
Obtain the result, parking only when necessary. Multiple fibers may await the same operation; each receives the same retained result. |
|
Run |
|
Return true on cancellation, false if already complete. The
result becomes an |
var left = SFTP.stat("/a")
var right = SFTP.stat("/b")
var a = left.await()
var b = right.await()
// Either provider reply may arrive first; identity selects the right result.
SFTP.realpath(".").then(Fn.new {|result|
if (result is Error) System.print(result.message)
else System.print(result)
})
Await registers the calling fiber with that specific operation. The owner
loop delivers an operation notification to resume it. Unrelated Wake.post
messages remain queued in arrival order until the operation wait completes;
they cannot substitute for the result. Use .await() rather than a raw
Fiber.yield() when waiting for an operation. A direct await in an App
handler postpones that handler’s UI events; App.runChild keeps dispatching
those events while its child waits.
Pending native work retains its operation even if the script drops the handle. Dropping a handle alone does not cancel the request. Dead or aborted awaiters are pruned at the next pump; when the last awaiting owner dies, its pending operation is cancelled. Completed result storage is released when its operation is collected. VM shutdown cancels pending operations before running disconnect hooks, then releases all roots and waiters without resuming asynchronous script code after teardown.
Timer cancellation removes the native timer. SFTP cancellation abandons the script’s interest in the reply; the provider may already have performed a remote side effect, and cancellation does not roll it back. Late replies are discarded, and late open results receive a best-effort close. A cancelled request ID continues counting toward the provider limit until its reply is drained. Explicitly close successful SFTP handles when finished.
OperationError inherits Error and exposes code, message, and toString.
Programming errors, including an invalid private await target or non-Fn
callback, abort the calling fiber rather than becoming result values.
WON
The Wren Object Notation — round-trip serialisation between Wren values
and a textual literal format. Output is a strict subset of valid Wren
syntax (and therefore also pasteable into Wren source). Deserialisation
runs a hardened C parser, not eval, so feeding untrusted text to
WON.deserialize cannot execute code.
Supported types:
| Type | Notes |
|---|---|
|
|
|
|
|
|
|
quoted with Wren-style escapes; |
|
|
|
|
|
coerced to |
|
any other |
Values of any other type abort serialisation in strict mode and are
silently omitted (or replaced with null at the top level) in lossy
mode. Cyclic Lists / Maps abort in both modes.
| Member | Description |
|---|---|
|
Strict compact form. |
|
Strict pretty-printed form. |
|
Compact form that silently omits unsupported items from Lists and Maps;
a top-level unsupported value becomes |
|
Pretty-printed lossy form. |
|
Parse |
WONError
Returned IN PLACE of the parsed value when WON.deserialize fails.
The script demuxes via is WONError. Mirrors the
SFTPError / FileError /
ConnError shape.
| Member | Description |
|---|---|
|
|
|
Byte offset where the error was detected. Useful for flagging a position in the input. |
|
Human-readable diagnostic, may be |
|
|
WONErr constants:
| Constant | Code | When emitted |
|---|---|---|
|
0 |
Sentinel; never appears on a returned WONError. |
|
1 |
Expected token / unexpected character / malformed number. |
|
2 |
Unterminated string, premature end of input. |
|
3 |
Malformed |
|
4 |
A |
|
5 |
Nesting exceeded the parser’s recursion budget (256 levels). |
|
6 |
A complete value was followed by more (non-whitespace) data. |
OOM during parsing aborts the fiber (no recoverable path — the
parser can’t allocate a WONError to return either).
import "syncterm" for WON
var data = {
"name": "syncterm",
"items": [1, 2, [3, 4]],
"flags": {"verbose": true, "depth": 7},
}
System.print(WON.serialize(data))
// {"name":"syncterm","items":[1,2,[3,4]],"flags":{"verbose":true,"depth":7}}
System.print(WON.serialize(data, " "))
// {
// "name": "syncterm",
// "items": [
// 1,
// 2,
// [
// 3,
// 4
// ]
// ],
// "flags": {
// "verbose": true,
// "depth": 7
// }
// }
var roundTripped = WON.deserialize(WON.serialize(data))
System.print(roundTripped["flags"]["depth"]) // 7
// Lossy mode skips unsupported entries instead of aborting.
var mixed = [1, Fiber.new {}, 2, Fiber.new {}, 3]
System.print(WON.serializeLossy(mixed)) // [1,2,3]
Built-in UI Library
SyncTERM ships a pure-Wren widget library on top of the
Modal Input primitive. It reuses mutable Cell views while
drawing into Surfaces, avoiding a new Wren object for every cell. Drawing
still uses foreign cell and text-width methods. The library composites
through a screen-sized backbuffer and applies a final Screen.putRect per
frame, so the whole thing runs without flicker even on slow remote BBSes. The
visual style follows SyncTERM’s classic conventions: cyan-on-blue dialog frames,
yellow titles, lightbar selection, drop shadows on modals, and a
distinct cyan inactive palette for any pane that’s currently behind
a modal.
A minimal session looks like:
import "ui" for App, Pane, ListView, Alert, Rect
import "syncterm" for Screen
var snap = Screen.save()
var app = App.new()
var size = Screen.size
var pane = Pane.new()
pane.bounds = Rect.new(2, 2, size[0] - 2, size[1] - 2)
pane.title = "Pick one"
pane.focused = true
pane.onClose = Fn.new { app.quit() }
app.root.add(pane)
var list = ListView.new()
var ib = pane.innerBounds
list.bounds = Rect.new(ib.x, ib.y, ib.w, ib.h)
list.items = ["alpha", "beta", "gamma"]
list.onSelect = Fn.new {|i, item| Alert.show(app, "Picked: %(item)") }
pane.add(list)
app.runSync()
Screen.restore(snap)
App.run() and App.runSync() differ in how they pump events.
run() parks a fiber on Fiber.yield() between events — claim
handler posts each accepted event via Wake.post, the result
queue resumes the fiber. Inbound bytes flow normally,
Hook.every and Timer.after keep firing. runSync() blocks
the VM on Input.next() instead; use it from contexts where
doterm can’t dispatch back into the App, e.g. the Wren console
(whose REPL itself runs inside a Hook.onKey).
runSync() dispatches each key or mouse event in a child fiber. A
runtime abort from a synchronous handler therefore does not unwind the
App’s event loop. By default the App writes the error and trace to the
current VM’s console log; set app.onError = Fn.new {|failedFiber| … }
to replace that reporting. Layout and painting remain outside this
boundary so a deterministic redraw failure is not retried forever. Modal
frames pushed by a failed event are discarded before error reporting, so an
orphaned dialog cannot consume the next Escape or Backspace. A modal that
the handler dismissed before aborting remains dismissed.
Key.quit is reserved for the host’s sticky process-close request. App
claims it before ordinary widget or global-keymap dispatch. With a modal
open, the App sends that modal an Escape for normal cleanup and then removes
it if it did not close itself; subsequent pump iterations unwind the
remaining Wren call stack. With no modal, the App stops. A widget whose
atExit property is true is the explicit exception: it remains interactive
while the quit latch is set, and modals it opens inherit atExit. Use this
only for work that must finish or be decided during shutdown, such as a save
confirmation. The connected-session host handles a real process-close
request before dispatching to the connected VM, so remotely supplied scripts
cannot use atExit to delay termination.
Importing
Every public class is exported from individual ui_*.wren modules
and re-exported from the convenience aggregator ui:
import "ui" for App, Pane, ListView, TextInput, SelectOnFocusInput, Button,
Checkbox, RadioGroup, SpinBox, DatePicker, CalendarDate,
MenuBar, StatusBar,
Form, Alert, Confirm, Prompt, Find, Help, PopStatus,
Painter, Style, Theme, Glyphs,
Widget, Container, Rect
If you only need a couple of classes, the per-topic modules cut
load cost: import "ui_pane" for Pane, import "ui_popup" for
Confirm, etc. They’re listed in UI Modules.
App
App is the root of a UI session. It owns:
-
root— aContainerthat hosts the foreground widget tree. -
a modal stack — synchronous dialogs push themselves onto it via
app.modal(widget), which blocks until the widget pops itself (typically from its owndismissWith_(value)helper). -
a global keymap —
app.bind(key, modifiers, fn)registers a hotkey that fires when no widget consumes the key. The overload without modifiers uses zero;unbindandbindingaccept the same optional mask. F1 is bound by default toshowHelp. -
a Theme initialized from
Theme.current, which decodes the C-owned active theme and refreshes its per-VM cache whenHost.themeGenerationchanges. The menu, picker, and connected VMs therefore use the same selected theme. Assignapp.themeonly when the App intentionally needs a different per-App theme. Assignment invalidates the complete root, transient-status, and modal widget trees so every mounted widget repaints on the next draw. -
a single run-fiber that pumps the event loop.
run()pushes an input claim (see Modal Input) whose handler decides synchronously, from App state alone, whether each event is "for the App" — modal up consumes everything; with a focused widget, keys are claimed and mouse events are claimed when they hit the visible widget tree (or start a drag, which the App owns for rectangular select); otherwise the event falls through to lower claims and then to registeredHook.onKey/Hook.onMouse. Claimed events are delivered to the run-fiber viaWake.post; the nextdrainOnce_iteration picks them up and dispatches into the widget tree. -
a backbuffer
Surfacesized to the term area (Screen.sizeminus one row whenCTerm.statusDisplay > 0, so the App’s blit doesn’t overwrite the SyncTERM status bar) and a one-shot screen capture (Screen.readRect) used as the backdrop behind everything. Areas not covered by widgets show that capture rather than a styled fill.
Methods of interest:
-
run()/runSync()— enter the event loop in a cleanup scope. Mouse subscriptions, cursor shape and position, and text attributes are restored after normal return, a callback error, or VM shutdown. The input claim and timers are released andrunningbecomes false. Re-entering an active App is an error; a stopped App can run again.tickMs=schedules a periodiconTick_callback (overridable; no-op by default). Only one tick timer is pending at a time; input and external posts do not accumulate additional timers.runSync()contains runtime errors raised by key and mouse handlers as described above. Errors from layout, painting, ticks, or an error reporter propagate after cleanup, retaining the original error object. -
onError=(fn)— replacerunSync()’s default reporting for a failed event handler. The callback receives the failed `Fiber, whoseerrorandstackTracedescribe the abort. -
quit()— break out of the loop. Widgets and global handlers call this from their key/mouse handlers. -
modal(widget)— push a modal, drain events until it pops or the App stops, then return the widget so the caller can read itsresult. A modal whoseclosesOnOutsideClick(event)method accepts a mouse event receives an Escape when that event occurs outside its bounds. List-style popups accept button 1 and right-click; Help accepts any ordinary mouse-button click. Text prompts and specialized editors reject outside clicks. -
popStatus(message)— show or clear a transient centered overlay that does not intercept input. Useful for "Working…" status while blocking onInput.nextor a long Wren computation. The overlay sits above the foreground widget tree but below the modal stack, so a dialog the user is actively working with isn’t obscured by an indicator behind it. -
releaseFocus()/restoreFocus()— wrap a picker call, where another VM temporarily owns the screen, so the App’s foreground tree doesn’t also draw as focused. Without this, the picker host’s pre-call screen save captures the App’s panes in their focused colour scheme, and the post-call restore re-paints them that way until the next App-driven repaint — visually, two widgets are focused at once. Operates onmodalTop(so a release while a modal is up defocuses the modal’s leaf, not the root’s) and forces an immediate paint so the unfocused state lands on screen before the host UI saves it. Both are idempotent: a secondreleaseFocusbeforerestoreFocusis a no-op, andrestoreFocuswithout a prior release is a no-op. -
invalidateCursorState()— call after a host operation changes conio’s cursor directly. The next draw reapplies the shape, visibility, and colour requested by the focused widget instead of trusting the App’s cached state.releaseFocus() var picked = Host.pickFiles(Host.uploadPath, "*", 0) restoreFocus() -
showHelp()— walks from the focused leaf up the parent chain to the first widget withhelpTextset, then opens aHelpdialog with that text. No-op if nothing in the chain has help. -
post()/post(value)— wake the App’s run-fiber from outside the input / timer paths. See "Externally-driven repaint" below. -
onPost=(fn)— handler for posted values that aren’t the no-payload sentinel. See below. -
runChild(fn)— runfnin an owned child while pumping the async App’s events. Return its result or propagate its error, including errors after an Operation await. Early exit cancels the child through its cleanup scopes. See "Async work in handlers" below. -
onLayout=(fn)— register a callback receiving(width, height)on the first paint and whenever the effective App area changes size. The root Container is resized before the callback runs, allowing the callback to assign stable responsive bounds to its children. -
onUnhandledMouse=(fn)— register a callback receiving(event, hit)after a non-modal mouse event is declined by the hit widget.hitis the declined Widget, ornullwhen the event is outside the root. Returningtrueconsumes the event; returningfalseleaves normal App fallback handling, including right-click Escape and drag selection, in place. The callback is not invoked while a modal owns input. -
theme=— install a custom Theme (see Theme).
Async work in handlers
runChild(fn) spawns a child fiber and pumps the App’s event loop until
that child finishes. Use it when a handler should keep input, ticks, and
repaints responsive while awaiting an operation. Direct operation await is
also safe: its wait defers unrelated wakes, but the handler does not dispatch
those UI events until the operation completes.
Call runChild from the active asynchronous App event fiber (including its
scoped continuations). Calling from an inactive App, runSync, or an
unrelated fiber is an error before the callback starts. Immediate and deferred
callback failures propagate as the same error object. Child completion wakes
the App even when it has no ticks or incoming input. If the App stops before
the child finishes, runChild raises "App stopped before child completed"
and detaches the child’s native waits. Registered host cleanup runs without
resuming the parked user callback. Operation ownership releases abandoned waits.
VM shutdown runs retained cleanup without resuming the parked user callback.
fetchDescAndShow_(path) {
popStatus("Fetching ...")
var d = runChild(Fn.new {
return SFTP.descs(path).await()
})
popStatus(null)
if (d is SFTPError) Alert.show(this, "Failed: " + d.toString)
else Alert.showPreformatted(this, d)
}
The child fiber yields on SFTP.descs; the run-fiber drops into
its own drainOnce_ loop, dispatching keys, mouse, ticks, and
repaints normally while the child is parked. When the SFTP
result wakes the child, its body completes and runChild
returns the value. Modal calls (Alert, Confirm) belong on the
run-fiber side after runChild returns — modals pump
drainOnce_ from whichever fiber called them, and only the
run-fiber receives wakes from the App’s claim handler.
Externally-driven repaint
The async run() parks the run-fiber on Fiber.yield() between
events. A network-driven app (chat client, ticker, log viewer fed
by remote bytes) needs a way for Hook.onInput to nudge the UI
without faking a key press. That’s what post is for:
import "syncterm" for Hook
import "ui_app" for App
var app = App.new()
// ... build widget tree ...
Hook.onInput { |b|
buffer.add(b) // mutate state
someWidget.markDirty() // mark UI as needing repaint
app.post() // wake the App so drainOnce_ runs again
return false
}
app.run()
app.post() calls Wake.post(runFiber, WakeOnly.instance) — a
no-payload sentinel. The next main-loop drain delivers it,
drawAll runs at the top of drainOnce_, and the dirty widget
repaints. The hook returns synchronously — post only
enqueues, satisfying the hooks-must-run-synchronously rule.
app.post(value) carries an arbitrary Wren value. When a non-
sentinel value arrives, onPost (if set) is called with it after
the redraw. Pass anything you can recognise:
app.onPost = Fn.new {|v|
if (v is String && v == "irc.PRIVMSG") chatPane.scrollToBottom()
}
Hook.onInput { |b|
// ...parse, accumulate...
if (gotPrivmsg) app.post("irc.PRIVMSG")
return false
}
post is a no-op when the App isn’t running (no run-fiber).
It’s not supported under runSync — the synchronous variant
blocks on Input.next() at the C level, not on Fiber.yield,
so a wake through the result queue won’t reach it. Use run()
for any app that needs external wake-ups.
App is not itself a Widget but exposes effectiveTheme and
markDirty() so widget tree-walks can terminate at it. Setting a
widget’s parent to an App is supported and is what pushModal
does internally.
The built-in Retro directory sets app.menuPanels = true so MenuUi list
choices use its full-page panel presentation. The default is false, keeping
Classic and custom applications' compact menus. Attached form dropdowns retain
their field-relative layout in either presentation.
Widget
Base class for everything paintable. Holds:
-
bounds— aRectin 1-based screen coords. -
parent— pointer to the containingContainerorApp. -
theme=— a per-widget Theme override; otherwise inherited viaeffectiveThemewalking the parent chain. Changing an override or reparenting an inheriting widget invalidates affected cached surfaces; an explicit descendant override ends that inherited-theme branch. -
focused,visible,focusable,activitySensitive,dirty— boolean state flags. SettingactivitySensitivetofalsemakes ambient screen chrome use its base theme roles regardless of modal activity; it does not affect focus or input dispatch. -
atExit—falseby default. Whentrue, this widget remains interactive after a sticky process-close request. Modals pushed while it is active inherit the property. Ordinary widgets are unwound through Escape and cannot consumeKey.quitthemselves. -
helpText=— string surfaced byApp.showHelp(F1). -
keyHints=— list of[keyLabel, actionLabel]pairs for ambient footer/status UI.App.keyHintsresolves it from the focused tree using the same nearest-widget rule ashelpText. -
closesOnOutsideClick(event)— returns whether the App should send Escape to this widget wheneventoccurs outside its modal bounds. The base implementation returnsfalse. -
shadow=— when true, the parent paints a drop shadow on the cells immediately right and below the widget’s bounds. -
surface— the widget’s private Surface backbuffer, allocated lazily and resized whenboundschanges. -
preferredWidth,preferredHeight— auto-layout sizing hints. Defaultnull(no preference, fill whatever bounds the parent gives). Widgets with a natural minimum size (ListViewwith N items, aFormwith measured rows, …) override these so containers that know how to lay out children (Pane.fitContent) can size themselves around the content.
Layer-aware painting: every widget tracks the App’s active layer
state (whether it or an ancestor is the modal top of stack) and
repaints itself when the cached state no longer matches. No
tree-wide dirty pass is needed when modals push or pop — each
widget notices on its next draw() and repaints with the inactive
theme variant. Subclasses override onPaint_() to draw into
surface; the base Widget.draw() calls onPaint_(), clears the
dirty flag, and returns the surface.
Hardware cursor: cursorPos returns [x, y] in 1-based screen
coords (or null); cursorVisible returns whether the cursor
should be shown while focused; cursorShape optionally returns
"normal" or "solid"; and cursorAttr optionally returns the
legacy text attribute whose foreground colors the cursor. App
reads all four off the focused leaf each frame and applies them. A
visible null shape defaults to "normal"; a null attribute leaves
the current conio cursor color unchanged. Containers forward the
focused child’s values.
tryHotkey(ev) is a parent-driven hotkey hook. Container.handle
scans its children with this when a printable key fell through the
focused child, so a typed letter can activate a button advertising
that letter even when focus is elsewhere.
Container
Widget subclass that manages a child list, a focused-child index,
and event dispatch. add(child) / remove(child) mutate the tree;
the first focusable child added becomes focused automatically.
Focus traversal:
-
Tab/Right—focusNext(), ordered ring with wrap. -
BackTab/Left—focusPrev(). -
Up/Down— spatial nearest-focusable scan. Picks the focusable child whose centre is above / below the current focus’s centre and minimises Manhattan distance. Ties (children on the same row) go to the lower-indexed sibling — i.e. tab order.
Spatial Up/Down does not wrap; it falls back to a hotkey scan if
nothing matches. Widgets that need arrows for their own semantics
(TextInput consumes Left/Right, ListView consumes Up/Down) catch
the keys before they bubble.
Mouse: Container.hitTest(px, py) walks children top-to-bottom
(last-added wins) and returns the deepest visible widget covering
the point, or the Container itself when nothing under it does.
focusedIndex is readable as a property and writable as a setter
for explicit focus management — e.g. the App-level
releaseFocus() / restoreFocus() pair clears and restores it
around blocking host UIs. The getter returns null when no
child is focused, otherwise an integer in 0..count - 1. The
setter toggles .focused on the previously- and newly-focused
child; pass null to clear focus. Direct day-to-day focus
changes still go through focusNext / focusPrev etc., not this
setter.
Pane
Container with a frame, optional title, [?] and [X] corner
buttons, and an inset interior. The default is a control-bearing pane:
the stronger double-line frame, title in its own bar row with a horizontal
separator underneath, and both corner buttons enabled.
Configuration knobs:
-
frameKind=—"control"(the default) or"display". A control frame marks a pane that contains choices, buttons, or editable input and uses the stronger double-line family. A display frame marks informational content and uses the single-line family. Assigning any other value aborts the calling fiber. -
titleAsBar=— when true, the title sits inside the frame in its own row with a horizontal separator underneath. When false, the title is embedded in the top border (-| Title |-). Classic list views use the bar form;Popupsubclasses use the embedded form. -
helpable=/closeable=— show or hide the[?]and[X]corner buttons. Help button callsonHelpif set, elseApp.showHelp(). Close button callsonCloseif set. -
onHelp=,onClose=— function callbacks for the corner buttons.
pane.innerBounds returns the drawable interior Rect after the
frame, title row, and separator are accounted for — children should
size themselves against this.
pane.contentBounds is innerBounds inset by one cell on every
side so text never touches the frame.
Popup-style widgets (Alert / Confirm / Prompt / PopStatus /
Help) lay themselves out inside contentBounds; bare Pane use
sites that want the full frame interior (e.g. a ListView filling
its parent pane) keep using innerBounds.
Pane.focused is a visual flag — set it from the App or a parent
container when the pane is the foreground. It does NOT redirect
keyboard focus; that still flows through `Container’s normal
focused-child routing to a leaf widget inside.
Auto-layout
Pane.fitContent() sizes the pane around its single child’s
preferredWidth / preferredHeight, plus whatever the title bar
and corner buttons require. It repeats measurement after assigning
the child’s bounds, so preferences that depend on the resulting
viewport, such as a ListView scrollbar, settle in one call. The
width is the largest of:
-
the child’s
preferredWidth + 2(left + right border), -
the title’s outer-width demand (see below), and
-
the corner buttons' outer-width demand (each visible button contributes 3 cells; total + 2 corners).
The two title modes have different geometry:
-
titleAsBar— title is centered on its own row inside the frame; outer width =title + 4(frame(2) + 1-cell padding on each side so the title never butts up against the side frame). -
frameTitle(titleAsBar = false) — title sits in the top frame border between─ ` and ` ─brackets; outer width =title + 6(corners(2) + brackets(2) + spaces(2)).
Multi-child panes are not auto-sized — fitContent only inspects
the first child. Lay them out manually via bounds / add.
Pane.fitContent(maximumWidth, maximumHeight) performs the same
layout while constraining the complete pane to the supplied maximum
dimensions. Pane.fitContentToScreen() applies the standard menu
modal limits. It preserves the title row and two-row footer, leaves
room for the two-column right shadow and one-row bottom shadow, and
centers the result in the remaining work area. For a pane with a
requested fixed size rather than a child-defined size,
Pane.fitToScreen(width, height) applies those same limits and
centering. Pane.modalBounds(width, height) returns that constrained
and centered rectangle for manually laid-out shadowed panes.
Pane.centerOnScreen() repositions the pane so its bounds are
centered on the current Screen.size, then re-anchors its single
child into the new innerBounds. Use fitContentToScreen() for the
usual constrained and centered modal layout:
var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen()
ListView
Scrollable list of items with a selection cursor and an optional
scrollbar. Items can be anything; rendering goes through
formatItem(item, width) which subclasses can override for rich
per-row formatting. Default is item.toString.
Setup:
var list = ListView.new()
list.bounds = Rect.new(x, y, w, h)
list.items = ["alpha", "beta", "gamma"]
list.onChange = Fn.new {|i, item| /* selection moved */ }
list.onSelect = Fn.new {|i, item| /* ... */ }
Navigation: Up, Down, PageUp, PageDown, Home, End move
the selection. Enter fires onSelect with (index, item).
Mouse: a single click on a row both selects it and fires onSelect;
each wheel notch over the list content moves the selection one row using
the same wrapping rules as Up and Down. Over the scrollbar, a wheel notch
moves one page. The scrollbar’s top and bottom arrow cells invoke PageUp
and PageDown; track clicks jump proportionally while keeping the lightbar
on the same screen row. The separator column between content and scrollbar
is inert. Button-1 drags fall through to screen selection.
wrap= controls single-row Up/Down movement and defaults to true:
Up at the first row wraps to the last, and Down at the last wraps to
the first. Set it to false to clamp at the ends. PageUp/PageDown,
Home/End, and direct selected= assignments do not wrap.
onChange is independent of activation. It fires with (index, item)
whenever navigation, assignment, search, or a row click changes the
current row. Replacing items also fires it so a detail pane can
refresh even when the selected numeric index remains zero. An empty
list reports (null, null).
items= preserves the selected index and scrollTop when replacing a
populated list, clamping them only when the replacement is shorter. This
allows a menu to rebuild changed row labels without moving its viewport.
resetItems(list) replaces the collection and explicitly selects its
first row at scrollTop=0; use it when navigating to a different
collection rather than redrawing the current one.
Repeating MenuUi.choice and MenuUi.commandChoice loops recreate their
pane after each activation. Construct one ChoiceViewState before the loop
and pass it as the final argument to the callback overload so each pane uses
the same ListView; row-label updates then retain both selection and
scrollTop. Use a separate state for each logical menu.
selected is null when no row is selected (empty list, or
explicitly cleared with list.selected = null); otherwise an
integer in 0..count - 1. selectedItem mirrors the same
contract — null when nothing is selected, the item otherwise.
When a selection is assigned before the list has bounds, first layout
centres an offscreen selected row where possible. A selection already in
the initial viewport leaves that viewport at the top. Normal navigation
scrolls only far enough to keep the moving selection visible.
The selected row is highlighted even when the list does not have focus.
Set highlightWhenUnfocused=false in a multi-list control when only the
list receiving keyboard input should display its selection lightbar. This
does not apply the inactive palette to the other list.
Search
Two complementary search modes, both using Unicode canonical caseless matching and wrapping at the end of the list:
-
Type-to-search — printable text without Control, Alt or GUI grows a rolling buffer and jumps to the first item whose search text starts with it. If the new buffer doesn’t match anywhere, falls back to just the new character (fresh prefix from current+1). Buffer resets on any navigation or activation key, so a paused-then-resumed search starts clean.
-
Ctrl-F / Ctrl-G — Ctrl-F opens an inline
Finddialog (see the Popup family) for a substring query, jumps to the first match. Ctrl-G repeats the last query.
Find and repeat-find use the logical key and modifiers, including native C0 Control-letter events from X11, ANSI and curses. Other modified shortcuts, such as Ctrl-S (Sort Profiles) and Ctrl-D (Quick Connect), pass through type-to-search to the menu dispatcher. The Wren console uses Ctrl+` on graphical backends and Ctrl-Q in ANSI/curses modes, where physical key events are unavailable.
The hook searchTextFor_(item) returns the string to match against;
defaults to formatItem(item, 1024) (the normal display string).
Override in subclasses when the displayed row decorates the underlying
text — the SFTP browser’s BrowserListView, for example, returns
item.name so users type bare filenames rather than the chip-prefixed
[==] foo.dat line.
searchKeys= optionally accepts a List parallel to items, with each value
produced by Text.caselessKey(searchTextFor_(item)). A valid list prefilters
prefix and substring searches without changing their grapheme-boundary-aware
result. A non-List or count mismatch disables the optimization. Replacing
items clears the keys, so callers set searchKeys after items.
Tag mode
selectionMode= accepts "single" (default) or "tag". In tag mode
each row tracks an independent tag flag, toggled by Space on the
current row; tagged returns the indices that are flagged on. A
1-cell marker column appears at the leftmost content position using
the theme’s tag.on / tag.off glyphs (» / blank by default;
> / blank in ASCII-only mode). Switching modes resets the flags;
so does setting items=.
Scrollbar layout knobs:
-
scrollbarSide=—"right"(default) or"left". -
scrollbarSeparator=— when true, paints a|divider between the scrollbar column and the content area. -
showScroll=— set to false to disable the scrollbar entirely.
The scrollbar is only painted when items.count > bounds.h.
ListView always reserves a 1-cell padding between the frame and
the items on the side that doesn’t have a scrollbar (both sides
when no scrollbar is shown at all), so item text never butts up
against the frame the parent Pane draws. innerWidth is
bounds.w - leftInset - rightInset accordingly.
Auto-layout: preferredWidth returns the longest item’s display
length plus the active insets (left + right padding, or scrollbar
+ padding when overflow is expected); preferredHeight returns
items.count, clamped to at least one row. The parent layout owns
screen and container constraints. Combined with
Pane.fitContentToScreen, a list-in-pane modal sizes itself to its
contents:
import "ui_pane" for Pane
import "ui_list" for ListView
var list = ListView.new()
list.items = Host.musicNames
var pane = Pane.new()
pane.title = "ANSI Music Setup"
pane.add(list)
pane.fitContentToScreen() // sized to list, constrained, and centered
Emoji picker
import "syncterm" for Emoji, EmojiEntry provides an offline catalog of
canonical emoji supported by all three bundled emoji banks. Emoji.entries
returns base representatives; Emoji.search(query) returns exact variants
matching a localized name or CLDR keyword substring, using canonical caseless
Unicode matching at grapheme boundaries (an empty query returns the base list).
English names and keywords are also searchable. Each EmojiEntry exposes
text, localized name, keywords (a List of localized and English search
keywords, with duplicates removed), and variants. Language preferences are
discovered once on first metadata lookup for a host, shared by its menu/picker VMs.
Bundled CLDR 49 annotations and derived annotations supply names for joined,
gender, skin-tone, and flag sequences. Locale aliases, likely scripts, and
CLDR parent locales resolve regional/script preferences; missing fields fall
through later preferences, then English. The lookup never changes the process
locale or connection encoding and does not require network access.
text retains the fully-qualified sequence including joiners and selectors.
Entry IDs ending in _ are internal catalog indexes, not persistent values.
The picker shows the highlighted name above a parenthesized keyword list,
truncated to one line to fit the pane.
It uses the screen dimensions with a one-cell margin on each side, reflowing
the emoji grid and preserving the selected entry when the screen is resized.
Emoji.recent returns up to 32 exact entries, newest first.
Emoji.recordUse(entry) promotes an entry in session recents, then persists the
merged recent list. It returns null or a FileError, replacing the former error
String in v2. code preserves the exact native IOErr reason; errno is zero
because the C operation does not supply a captured errno. The error diagnostic
explains that session recents were updated but saving failed. Native partial-write
behavior is unchanged; an error does not imply that the settings file is unchanged.
No rollback or automatic retry is performed. Successful insertion or transmission
is not undone or repeated when recording recents fails; bundled callers log the
returned error. Safe mode changes only session memory, performs no file writes,
and returns null. This existing fixed-purpose operation is available in menu,
picker and connected VMs and grants no arbitrary filesystem access. Invalid
catalog entry arguments retain their ordinary Fiber abort behavior.
Emoji.canSend reports whether this VM has a UTF-8 terminal connection; it
does not restrict local text-field insertion in a menu VM.
App.openEmojiPicker() opens ui_emoji_picker for its focused TextInput.
The default bindings are Alt+P and, when Host.localControlKeys is true,
Ctrl+P. It returns false without a running App and focused text field. Modal
completion preserves the insertion target’s cursor and selection. A changed
or detached target is not written. A full field leaves the picker open with
an explanation rather than inserting part of a sequence.
The mouse wheel scrolls the emoji viewport independently of the selection,
respecting its native magnitude and clamping at either end. Keyboard navigation
reveals the selected entry again; mouse hit testing uses the scrolled rows.
The connected emoji_pick module uses EmojiFlow.run() for Alt+P and the
Online Menu. It saves/restores the screen and mouse settings, suspends terminal
output during the picker, and sends a successful selection with Conn.sendText.
Ctrl+P is not a connected hook. Local Apps reached through Alt+E use their
normal field bindings regardless of the parked connection’s encoding.
TextInput
Single-line text edit field. Stores the value as a list of
codepoint strings, so editing indexes codepoints without splitting UTF-8.
Cursor placement, scrolling, and painting use Screen.textWidth, which
normalizes to NFC and resolves each extended grapheme cluster once. Full
grapheme-cluster editing is not currently provided.
insertText(text) inserts a complete String at the cursor (or replaces the
whole-field selection). It respects insert/overwrite mode and the codepoint
maxLen, returning false without changing the field if the entire payload
does not fit or contains C0/DEL controls. Success returns true and emits one
onChange callback when the value changes. The picker uses this preflight to
preserve joined emoji.
var t = TextInput.new()
t.bounds = Rect.new(x, y, w, 1)
t.value = "hello"
t.maxLen = 64 // optional cap
t.mask = "*" // optional display-only mask
t.onSubmit = Fn.new {|s| /* Enter */ }
t.onChange = Fn.new {|s| /* per-keystroke */ }
t.selectAll() // optional replace-all entry state
Keys use SyncTERM’s standard line-editor behavior. Left, Right, Home, End,
Backspace, and Delete / DelChar move and delete; Ctrl-B and Ctrl-E
alias Home and End, and Ctrl-Y truncates at the cursor. Insert toggles
insert/overwrite mode. Ctrl-C / Ctrl-Insert copy the whole field,
Ctrl-X / Shift-Delete cut it, and Ctrl-V / Shift-Insert paste at the cursor.
Ctrl-Z opens the focused field’s contextual help when one is available.
Enter fires onSubmit; printable codepoints edit at the cursor. Tab,
BackTab, Up, and Down are NOT consumed so containers can use them for
focus traversal. A left click positions the cursor; middle- and right-click
paste there. An unconsumed right-click elsewhere is Escape. Drag events
fall through to the App’s screen-selection handler.
selectAll() puts a non-empty value into a transient whole-field selection
state, reported by the read-only allSelected getter. The next printable,
keyboard paste, Backspace, Delete, or Ctrl-Y operation replaces the complete
value. Cursor movement and mouse positioning preserve the value and dismiss
the selection before ordinary editing continues; other non-editing key events
also dismiss it without changing the value. Assigning value clears the
state, so callers opt into it explicitly after assignment when needed.
SelectOnFocusInput is the existing-value editing variant used by
SyncTERM prompts:
prompts and inline editors. It calls selectAll() whenever it gains focus,
clears the selection on focus loss, highlights only the selected text, and
uses the surrounding default style after cursor movement begins ordinary
editing. Use TextInput when focus should leave an assigned value ready for
appending; use SelectOnFocusInput when typing should replace that value.
insertMode reports whether printable input inserts (true, the initial
mode) or overwrites existing characters (false). The mode is shared by
all TextInput instances, so toggling it in one field applies to the next
field. cursorShape is "normal" in insert mode and "solid" in overwrite
mode, matching SyncTERM’s insert/overwrite cursor convention.
cursorAttr supplies
the focused input style’s legacy attribute so bitmap backends render the
cursor in the field foreground instead of an unrelated global color. Pasted
control characters are discarded, matching typed-input filtering, and
maxLen applies to pasted text.
mask= accepts null or a non-empty String and uses its first
codepoint when painting every stored character. It does not change
value, cursor movement, length, or callback arguments, making it
suitable for password and system-password fields. Changing the mask
recalculates the horizontal viewport because the replacement glyph may
have a different display width.
Assigning or resizing bounds recalculates the horizontal viewport.
An initial value wider than the field displays its end followed by a
cell for the insertion cursor, regardless of whether value or
bounds was assigned first. scrollOff reports the first displayed
codepoint index.
cursorVisible returns true and cursorPos reports the cell that
corresponds to the current insertion point in screen coords —
backends that show the hardware cursor track the input as the user
types.
Button
Single-row "[ label ]" widget. Activates on Enter, Space, or
mouse click within bounds. onPress= sets the activation
callback. intrinsicWidth returns label.count + 4 for sizing
parents.
var b = Button.new("OK")
b.bounds = Rect.new(x, y, b.intrinsicWidth, 1)
b.onPress = Fn.new { app.popModal() }
hotkeyIdx= selects which label letter to highlight (default 0,
the first letter). tryHotkey matches that letter case-
insensitively against typed input, so a button labeled "Yes" with
hotkeyIdx = 0 activates on Y from anywhere in the same
container — even when focus is on a sibling.
Checkbox
Single-row "[X] Label" toggle. value is a Bool, label is a
String. Space or Enter flips the value when focused; mouse
click anywhere on the widget toggles too.
var c = Checkbox.new("Show shadows")
c.bounds = Rect.new(x, y, c.intrinsicWidth, 1)
c.value = true
c.onChange = Fn.new {|v| /* ... */ }
onChange fires only when the value actually changes — assigning
the current value is a no-op. Theme roles: checkbox,
checkbox.focused. Glyphs reused: check.on (√ U+221A), check.off
(space).
RadioGroup
Multi-row mutually-exclusive selector. Owns its own item list and selected index — the whole group is a single focusable widget.
var g = RadioGroup.new()
g.bounds = Rect.new(x, y, w, h)
g.items = ["None", "SSL", "SSH"]
g.selected = 0
g.onChange = Fn.new {|i, item| /* ... */ }
Two pointers: cursor (visually highlighted row) and selected
(the committed value). Up/Down move the cursor; Home / End
jump to ends; Space or Enter commits the cursor as the
selection. Mouse click selects directly. onChange fires only
when the selection actually changes. Both pointers are null
when the group is empty (or explicitly cleared by assigning
null); otherwise integers in 0..count - 1. The cursor highlight only
appears while the widget itself has focus — leaving the group
shows just the filled • glyph on the selected row, so a
multi-field Form doesn’t confuse the user with a stale lightbar.
wrap= controls the edge behavior of Up/Down. Default true:
Up at the top wraps to the bottom and vice versa; every press is
consumed. When false, Up at the top and Down at the bottom
return false instead, letting the parent Container move focus to
the previous / next sibling. Form.addField flips this to false
on RadioGroup children so vertical traversal escapes the group at
its edges.
Theme roles: radio.item, radio.item.focused. Glyphs reused:
radio.on (• U+2022), radio.off (○ U+25CB).
SpinBox
Single-row numeric input with up/down step buttons. Layout:
[ 42 ▲▼].
var s = SpinBox.new()
s.bounds = Rect.new(x, y, w, 1)
s.min = 0
s.max = 100
s.step = 1
s.value = 50
s.onChange = Fn.new {|v| /* ... */ }
Keys: Up / + adds step; Down / - subtracts; PageUp /
PageDown move ten steps; Home / End jump to min / max.
Mouse wheel scrolls one step; clicks on the up/down arrow cells
step ±1. Pressing an arrow steps immediately; holding it waits 400 ms and
then repeats at 8 Hz, accelerating to 16 Hz after two seconds and 32 Hz after
five seconds. Acceleration changes only the repeat rate, so every update is
still one configured step. Releasing or beginning a drag stops repetition,
and a delayed UI wake never produces a burst of catch-up updates.
value= clamps to [min, max]. Theme roles: spinbox,
spinbox.focused. Glyphs reused: scrollbar.up, scrollbar.down.
DatePicker
Embeddable month calendar with a named month/year header, Sunday-through- Saturday columns, and six date rows. Neighboring-month dates fill unused grid cells and can be selected directly. The control does not provide dialog buttons; its caller owns acceptance and cancellation.
var picker = DatePicker.new(2026, 7, 23)
picker.bounds = Rect.new(x, y, picker.preferredWidth,
picker.preferredHeight)
picker.onChange = Fn.new {|year, month, day| /* update preview */ }
picker.onAccept = Fn.new { /* commit picker.value */ }
year, month, and day expose the selected components; date returns
them as a three-element List, and value returns YYYY-MM-DD.
setDate(year, month, day) clamps to years 1 through 9999 and to the
selected month’s valid day range. moveDays(offset) and
moveMonths(offset) provide programmatic navigation. onChange fires
only when the selected date changes; onAccept fires on Enter, Space, or
a date double-click.
Left/Right moves one day, Up/Down moves one week, PageUp/PageDown changes month, and Home/End selects the first/last day of the month. Header-arrow clicks and the mouse wheel change month. A single click selects a visible date.
CalendarDate supplies Gregorian helpers used by the widget:
monthNames, daysInMonth(year, month), iso(year, month, day),
fromTimestamp(seconds), isoFromTimestamp(seconds),
daysFromCivil(year, month, day), civilFromDays(days), and
weekday(year, month, day) (Sunday is 0). Timestamp conversion is UTC.
Preferred size is 28x8 cells. Theme roles: button, list.item,
list.item.focused, and list.item.disabled.
ColorPicker
Embeddable 24-bit colour editor with a compact live sample, editable Red/Green/Blue ramps, visual Hue/Saturation/Value ramps, and six-digit hexadecimal input. The control does not provide dialog buttons; its caller owns acceptance, cancellation, and any application-specific preview.
var picker = ColorPicker.new(0x336699)
picker.bounds = Rect.new(x, y, 44, picker.preferredHeight)
picker.onChange = Fn.new {|rgb| /* update a live preview */ }
value is the current 0xRRGGBB integer. valid is false while the
hexadecimal field is incomplete, and commitEdits() returns false until
the field contains six valid digits. The RGB ramps accept decimal typing
from 0 through 255. HSV ramps remain fully interactive but omit the
rounded numeric labels and do not accept decimal typing.
RGB ramps show their numeric value and accept decimal input. HSV ramps do not show rounded numeric values. A digit starts replacement after focus, after a complete or out-of-range entry, or after Delete. Left/Right and the mouse wheel move one unit. PageUp/PageDown move RGB by 16, hue by 15 degrees, and saturation/value by 10 percent. Up/Down moves between fields, and a containing dialog may complete the navigation ring at the picker boundaries. A completed button-1 click jumps to the clicked ramp position. Button presses and drag events remain unconsumed so App can hand drag selection to conio’s normal text-copy path.
sampleColors(foreground, background) replaces the automatic contrasting
sample pair. The dialing-directory palette editor uses this to make either
row of its sixteen-position contrast grid clickable: selecting a cell shows
that foreground/background combination in the larger sample.
Ramp rows use default while idle and list.item.focused for their
edge-to-edge focus lightbar. Only the three-character RGB numeric field and
the seven-cell hexadecimal field use input / input.focused. Hex input
is limited to six digits; the final cell displays the insertion cursor after
a complete value without scrolling away its first digit. Complete valid
edits are normalized to uppercase without moving the active caret or
discarding its selection; assigning ColorPicker.value externally still
replaces the field and leaves its cursor at the end.
RGB is the canonical value. HSV conversion retains hue for greys and
retains hue/saturation for black, so moving away from those edge cases does
not unexpectedly reset the user’s HSV selection. Ramp and sample cells
carry both 24-bit RGB and a Color.toLegacyAttr() fallback.
The dialing-directory palette editor composes this generic control with a
separate palette-only preview. That preview shows the candidate colour as
both foreground and background against all sixteen effective palette
positions; this behavior is not part of ColorPicker. In that dialog,
Home selects the first ramp and End selects the button row when a ramp has
focus. The same keys retain normal text-cursor behavior in the hex field.
MenuBar
Horizontal strip of activatable items, typically at the top of the
screen. Each item is a [label, Fn] pair; activation calls the
Fn. No nested submenus in v1 — pop a Popup from the callback if
you want one.
var bar = MenuBar.new()
bar.bounds = Rect.new(1, 1, sz[0], 1)
bar.items = [
["File", Fn.new { Alert.show(app, "...") }],
["Edit", Fn.new { /* ... */ }],
["Help", Fn.new { app.showHelp() }],
]
Keys: Left / Right move focus between items with wrap; Home /
End jump to ends; Enter / Space activate the focused item; a
typed Unicode scalar (canonical caseless) matched against item labels'
first characters activates that item. focusedItem is null
when the bar is empty (or explicitly cleared); otherwise an
integer in 0..count - 1. tryHotkey(ev) is exposed
on the widget so a Container parent can route a letter pressed
elsewhere into the bar’s matcher. The focusedItem cursor is painted with
the focused role only while the MenuBar widget itself has focus, so multiple
bars may retain their navigation positions without appearing simultaneously
active. Set onFocus= when a containing editor needs a mouse click to move
its own focus to the bar before activation. A completed mouse click activates
the clicked item; the initial press and any drag do not. Clicks on inter-item
gaps are dropped. Theme roles:
menubar, menubar.item, menubar.item.focused.
StatusBar
Single-row strip used at the bottom (or top) of the screen for status text and key hints. Not focusable.
var s = StatusBar.new()
s.bounds = Rect.new(1, sz[1], sz[0], 1)
s.text = "F1 Help Esc Quit"
// or — multi-segment:
s.segments = [
["F1 Help", "left"],
["Connected", "center"],
["09:42", "right"],
]
text= sets a single left-aligned string. segments= takes a list
of [text, align] pairs where align is "left", "center", or
"right". Left segments stack from the left edge with a 2-cell
gap; right segments flush to the right edge inward; one center
segment is centred in the remaining space. Setting either form
overrides the other. Theme role: statusbar (black on cyan).
Form
Container subclass that lays out (label, widget) pairs in a
vertical stack with right-aligned labels in a column on the left.
Optional OK / Cancel buttons appear on the row below the last field
when onSubmit / onCancel are wired.
var f = Form.new()
f.bounds = pane.innerBounds
f.addField("Name:", nameInput)
f.addField("Port:", portSpin)
f.addFieldH("Encryption:", encRadio, 3) // 3 rows tall
f.addField("", autoCheckbox) // no label
f.onSubmit = Fn.new { /* read field values */ }
f.onCancel = Fn.new { app.quit() }
pane.add(f)
-
addField(label, widget)— queues a one-row field. -
addFieldH(label, widget, h)— queues a multi-row field (e.g. RadioGroup). -
clearFields()— drops every queued field and removes the widgets as children. -
rowGap=— blank rows between fields. Default 0. -
rowH=— default per-field height. Default 1.
The label column width auto-sizes to the longest label; widgets
start one column past the longest label plus a 2-cell gap. Form keeps its
managed child order as fields in addField declaration order followed by
the implicit OK and Cancel buttons, regardless of when their callbacks are
assigned. Container’s normal insertion-order Tab / BackTab traversal then
uses that order. Esc fires onCancel if wired.
onSubmit= / onCancel= are idempotent setters — assigning the
same callback twice doesn’t double-add the OK / Cancel button, and
assigning null removes the button.
Popup family
Modal dialogs built on Pane (control frame, embedded title, drop
shadow) and pushed onto the App’s modal stack. Each show is
synchronous: the App’s modal() pumps drain until the popup pops itself,
then control returns with the result. Help is the informational
exception and selects the display frame; transient PopStatus uses the
display frame as well.
import "ui" for Alert, Confirm, Prompt, LinePrompt
Alert.show(app, "Disk full")
Alert.show(app, "Warning", "Disk full")
Alert.show(app, "Warning", "Disk full", "# Disk Full\n\nFree space first.")
if (Confirm.show(app, "Delete file?", "# Delete\n\nThis cannot be undone.")) {
// ...
}
var name = Prompt.show(app, "Your name?", "anonymous")
if (name != null) {
// user submitted
}
var path = LinePrompt.show(app, "Path", "/tmp")
Alert — single OK button. Enter, Space, O, Esc, or a mouse click
on OK dismisses it; unrelated keys do not. show returns null.
Confirm — Yes / No buttons. Y / N letter shortcuts dismiss
directly; Enter activates the focused button; Tab cycles focus.
show returns true on Yes, false on No or Esc.
The four-argument titled Alert.show(app, title, message, helpText)
and three-argument Confirm.show(app, message, helpText) forms attach
Markdown context help to the popup. F1 and Ctrl-Z display that text
while the popup owns focus.
Prompt — SelectOnFocusInput plus OK / Cancel buttons. A non-empty
initial value starts selected: typing, keyboard paste,
Backspace, or Delete replaces it, while cursor movement or mouse positioning
preserves it and begins ordinary editing. Enter in the input or on OK
submits the value; Esc or Cancel returns null. The read-only input
getter exposes that input so trusted UI code can set maxLen or a display-only
mask before presenting the popup.
Prompt.new(message, initial, true) creates a required prompt. Escape
keeps the current edit in place and Enter accepts the field, including an
empty value.
sizeForInput(inputWidth) and
sizeForInput(inputWidth, minimumWidth) size the field for the requested
capacity and cap the complete popup to the standard menu modal work area. The
MenuUi.prompt wrappers use the field’s maxLen for this width.
Short fields retain the normal minimum while URI, path, password,
and other long fields use the available screen width.
LinePrompt — compact UIFC-style single-row entry. Its label appears
to the left of the input on the only interior row; there is no OK / Cancel
button row. Enter submits and Esc returns null. The read-only input
getter and sizeForInput methods have the same purpose as Prompt’s. A
distinct optional title may be placed in the top frame, but menu prompts
omit it when it would merely repeat the field label. MenuUi.prompt uses
this form for ordinary menu editing and application filename entry; host
prompts retain Prompt because their explanatory message is separate from
the dialog title. LinePrompt.runStandalone(app, label, initial) is the
standalone equivalent.
Find — compact single-row variant of Prompt. Title sits in the
top frame border, the input fills the entire innerBounds row (no
padding, no buttons, no [X]). Total height is 3 cells. Its previous query
starts selected under the same replacement rules as Prompt. Used by
`ListView’s Ctrl-F.
import "ui" for Find
var q = Find.show(app, "Find", lastQuery)
if (q != null && q.count > 0) {
// ...
}
Layout
All popups use the standard frame interior padding via
Pane.contentBounds — a 1-cell pad on every side so text never
touches the frame. Buttons (Alert OK, Confirm Yes/No, Prompt
OK/Cancel) anchor hard against the bottom frame; the empty row
between the message and the button row falls out of the height
math as a natural visual separator.
Popup.centeredBounds_(message, extraRows, minW) sizes the dialog
around the wrapped message: width is longest-line + 4 (frame
padding), height is 4 + msgRows + extraRows (2 frame + 2 padding
content). Subclasses pass extraRows for whatever they paint
below the message — 1 for Alert/Confirm (button row), 2 for
Prompt (input + button rows). Message width is measured in display
cells with the resolved default style font; wrapping never splits a
UTF-8 codepoint. A single glyph wider than the available row remains
intact and is left to the painter’s clipping policy.
PopStatus is the non-modal companion: a centered frame with a
message and no buttons, used by App.popStatus(message). It does
not push onto the modal stack — purely decorative — and is
dismissed with app.popStatus(null). Its sizing, centering, and
single-line truncation use the same painted-font display widths, and
truncation stops only at a Unicode codepoint boundary.
Standalone popups
Confirm.show(app, …) (and the other Popup.show family methods)
expect app to already be running — they call app.modal(p), which
pumps drainOnce_() on the existing run loop’s input claim. When
you need a popup from a context with no enclosing app — a
Hook.onKey handler being the canonical case — use the standalone
variants, which push the popup, wire onDismiss to app.quit(),
and run the App so key events are routed:
var app = App.new()
if (Confirm.runStandalone(app, "Disconnect... Are you sure?")) {
// user clicked Yes
}
Standalone helpers are available as Alert.runStandalone(app, msg),
Alert.runStandalone(app, title, msg),
Confirm.runStandalone(app, msg), and
Prompt.runStandalone(app, msg, initial).
For custom popup drivers, onDismiss=(fn) fires from dismissWith_
after the popup pops itself off the modal stack, with the dismissed
value (Bool / String / null depending on the popup subclass). If you
call app.run() yourself, wire onDismiss to app.quit(); otherwise
app.run() would loop forever on an empty modal stack.
Help viewer
A modal scrollable text viewer for context help. The body is parsed once as a markdown subset (see "Markdown subset" below) and laid out lazily — text wraps to the dialog width and reflows on resize.
Set literal = true on a Help instance to display plain text with wrapping
and scrolling, preserving punctuation such as Markdown markers. This mode is
used for the embedded license notices. preformatted = true instead keeps
source lines unwrapped; combining it with literal also disables inline
Markdown parsing.
import "ui" for Help
Help.show(app, "Help — Editor",
"# Editor\n\n" +
"- `Up`/`Down` scroll\n" +
"- `Enter` close\n")
Keys: Up, Down, PageUp, PageDown, Home, End scroll;
any other key dismisses. Wheel scrolls one line over the text and one
page over the scrollbar. Scrollbar clicks jump proportionally; button-1
drags fall through to screen text selection. An ordinary mouse-button
click also dismisses, including a click outside the dialog. Same scrollbar
knobs as ListView (scrollbarSide=, scrollbarSeparator=). Clicking
the frame’s [X] corner button dismisses (inherited from Pane).
App.showHelp (F1 by default) walks from the focused leaf up the
parent chain looking for a widget with helpText set, then calls
Help.show with the title "Help" and that text. Set helpText
on whichever widget is the most-specific scope you want help to
fall back to.
App.helpText, App.helpAvailable, and App.keyHints expose that same
focused context without opening a dialog. The main-menu footer queries
these values only when it paints; command ownership remains with the focused
widget or its nearest containing pane. Custom modal widgets should set
keyHints for their direct commands. The standard choices, prompts,
popups, and Help viewer already do so.
Prompts and other modal widgets can also carry helpText. Because the
focused input or list is their child, the same parent walk finds the modal’s
field-specific help before any help attached to the underlying screen.
Default placement: Help.centeredBounds_() uses the standard menu modal
work area. The frame remains below the title row, its bottom shadow remains
above the two-row footer, and it retains the 2-cell horizontal margins.
Pass an explicit Rect via the bounds= setter after construction to
override.
Padding: 1-cell margin on every side except the scrollbar column, where text is flush. The scrollbar defaults to the right, and its column plus optional separator span the full inner height (between the top and bottom frame chars); only text rows inset by the top/bottom padding.
Markdown subset
Help body strings (and any helpText) are parsed as a small
CommonMark + Pandoc subset by ui_markdown.wren. Supported syntax:
-
Block:
# / / #headings;- ` or `* ` bullets; blank-line- separated paragraphs; Pandoc-style definition lists (term line followed by one or more `: descriptionlines). -
Inline:
bold,. Backslash escapes a literalcode*,`, or\outside a code span. Inside a code span, only the closing backtick is syntax: bold markers and backslashes are literal. Closing code resumes the surrounding bold or ordinary role. -
Hard line break: a line ending in two trailing spaces forces a break at that point inside a paragraph or bullet. Continuation uses the same wrap indent as a soft wrap (so a bullet’s hard- break still hangs under the text). An unmarked source line belongs to a bullet only when the preceding bullet-owned line has this hard break; the rule can chain across multiple lines.
-
Italics are intentionally omitted — terminal italic support varies and dim grey on dark blue is hard to read.
Each block-level token resolves to a style role (help.heading.1,
help.bold, help.code, help.bullet, etc.) that cascades through
help and finally default, so themes can restyle without touching
the parser. Unknown markup falls through as literal text.
Definition lists pad each term to a common column width — capped at
half the dialog — and wrap descriptions inside the description
column, with continuation lines indented to the description start.
Term and description default to help.bold and help.text
respectively.
Headings render as a single-row reverse-video bar: blue-on-cyan
text with one styled space cell on each end (" Title ").
Layout is reflow-on-width: Markdown.layout(doc, cols) returns a
list of MdLine`s, each carrying pre-resolved style runs ready for
`Painter.text. The public layout helper uses font zero; Help
measures every run with the font resolved for that run’s role so its
layout matches painting. Help re-runs layout whenever its bounds,
scrollbar-separator width, or effective theme changes (as well as when
the scrollbar appears or disappears), and clamps the scroll position
accordingly.
Example combining heading + def-list:
# Capture Type
ASCII
: Plain text, no escape sequences
Raw
: Preserves ANSI escape sequences
Binary
: Saves the current screen as IBM-CGA / BinaryText
Theme, Style, Glyphs
A Theme bundles a role → Style map and a Glyphs (name →
glyph) lookup. Style is a four-field tuple (font, legacyAttr,
fgRgb, bgRgb); any field may be null to inherit from a parent
role. Painting picks one of the two color paths based on what the
backend supports — RGB on capable terminals, legacy attr otherwise.
Role cascade: Theme.style(role) walks dotted role suffixes,
merging partial Styles at each level until every field is
populated. "list.item.focused" falls back to "list.item" falls
back to "default". "default" is the cascade terminator and
must be a complete Style.
Inactive cascade: when a role ends in .inactive, the Theme walks
a parallel chain — X.inactive, then parent(X).inactive, …,
finally default.inactive. Falls through to default if the
theme has no inactive variants at all. Widget.style(role)
auto-suffixes .inactive whenever inActiveLayer is false, so a
single layer-state flag cascades through frame, title, list rows,
input field, button labels, and scrollbar without per-widget
bookkeeping.
A widget lands in the inactive layer for either of two reasons:
-
It isn’t part of the App’s modal-top subtree (a modal is on top, and the widget is in the layer behind it).
-
An ancestor that gates focus visibility has
focused == false.Widget.gatesActiveLayerdefaults tofalse;Paneoverrides it totrue, so an unfocused Pane in a multi-pane layout dims every cell it owns AND every descendant’s surface — frame, title, bg fill, list rows all agree on active-vs-inactive without each subclass having to know.
activitySensitive=false opts a widget out of this style selection.
It continues to report its computed inActiveLayer value, but
style(role) always resolves the base role. This is intended for
ambient screen backgrounds, title bars, and status/help bars which do
not have active and inactive forms. Do not use focusable=false for
this purpose: display-only children such as progress bars still need to
inherit an inactive containing Pane.
Theme.default is the C-owned compiled fallback decoded into Wren and
memoized so
someTheme == Theme.default works as identity equality. Theme builders
use it to populate roles and glyphs they do not override, and an unattached
Widget falls back to it when it has no Theme in its parent chain. It uses a
white-on-blue palette, yellow frame/title, lightbar selection, gray-on-blue
scrollbar, and bright-white-on-cyan inactive palette.
Theme.current decodes Host.themeData and caches the result against
Host.themeGeneration. App.new() initializes from this process-wide
selection. The built-in Classic Theme and file themes use the same host
representation; their storage and complete role/glyph registry are
documented in Themes.adoc. Scripts may still construct a Theme directly
or assign app.theme to replace the program theme for one App. Such a Wren
object does not modify the C-owned selection or any other VM.
Theme.fromData(data) constructs an independent Theme from the same
[styleRows, glyphRows] representation returned by Host.themeData and
ThemeDocument.themeData. It is intended for draft previews and other
host-provided snapshots; modifying the returned object does not modify its
source or the process-wide selection.
Glyphs entries are either a single string or [primary,
fallback] pairs — primary is the rich Unicode glyph, fallback is
an ASCII-safe substitute. The host resolves each theme glyph at load time in
Codepoint, CP437, then ASCII order and supplies the resulting Unicode primary
to Wren. Glyphs caches that primary by name. Set
theme.glyphs.asciiOnly = true
to force the fallback for every entry that has one — useful when
the user has selected a font that can’t render line-drawing
characters at all.
Glyph families used by the library:
-
frame.display.*— single-line--borders for informational viewers, plustee.left/right,title.left/right, andseparator. -
frame.control.*— double-line==borders for panes containing choices, buttons, or editable input.Pane.frameKindselects between the two frame families. -
scrollbar.track,scrollbar.thumb,scrollbar.up,scrollbar.down,scrollbar.separator— scrollbar pieces. -
focus.left,focus.right— selection-arrow shapes. Existing atlas arrows uselist.item.focused.indicatorand its.inactivevariant for colours; these inherit the selected-row styles unless overridden. OrdinaryListViewrows do not draw these arrows.
Painter
Painter is the low-level drawing toolbox. Every primitive takes
a Surface as its first argument and mutates the cells in place;
no calls reach Screen.putRect from here. Coordinates inside a
Surface are 0-based (0..width-1, 0..height-1); widgets that
work in absolute screen coords convert at composition time.
The most useful entry points:
fill(s, rect, ch, style) |
Bulk-fill a Surface rect with a single character + Style. |
|---|---|
|
Draw |
|
Box around |
|
Frame with a centered `+ |
|
+` in the top border. |
|
Single-row / single-column lines. |
|
Vertical scrollbar with always-visible up/down arrows on the top/bottom rows when |
|
Resolve a click at row |
|
Paint a drop shadow on the cells around the rect: 2 columns wide on the right, 1 row tall on the bottom. Each shadow cell keeps its existing character and font. The five-argument form uses the compiled |
|
Apply a Style to an existing Cell, leaving null fields untouched. Exposed for callers that mutate a cell view directly. |
UI Modules
The library is split across one module per topic, plus the convenience aggregator:
|
Re-exports every public class. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Demo gallery
scripts/ui_demo.wren is a playground for the library; run it from
the Wren console (see Built-in REPL):
import "ui_demo" for UiDemo
UiDemo.run()
Top level is a list of widget demos; pick one with Enter to launch
it, Esc returns to the gallery. Each demo runs its own App via
runSync (the console blocks the main loop, so doterm can’t
dispatch through to a parked fiber); nesting is fine because every
App restores mouse subscriptions, cursor shape/position, and text attributes.
The caller uses Screen.save/restore or Screen.modalRun to restore screen
contents.
Worked Example: Auto-respond to a Prompt
A small script that watches inbound text for known prompts and sends
canned responses. Hook.onMatch is the right tool for this — it
runs a streaming regex against the inbound byte stream and fires the
callback on each match, no manual buffering required:
import "syncterm" for Hook, Conn
Hook.onMatch("Press any key to continue") { |m|
Conn.sendText("\r")
}
Hook.onMatch("Logon: ") { |m|
Conn.sendText("myhandle\r")
}
onMatch is passthrough-only, so the matched text always reaches
the terminal — the callback just acts on the side (sending bytes
back to the BBS, updating script state, etc.). When a prompt is
preceded by colour codes, use Hook.onMatchClean instead so the
escapes don’t break the literal match.
onMatch substring-matches anywhere in the stream, not anchored to
line boundaries, so prompts that wait for input mid-line (like
`Logon: `) work the same as prompts followed by a newline. See
Hook Events for the regex grammar accepted, including
which constructs aren’t supported (no character classes, no anchors,
no backslash escapes).
Worked Example: Per-byte Inspection
Hook.onInput is the lower-level primitive — fires once per inbound
byte before the byte reaches the terminal. Use it when you need to
react to individual bytes rather than text patterns. Below: count
BEL (0x07) bytes received over the session.
import "syncterm" for Hook
class Stats {
static bells { __bells }
static bells=(n) { __bells = n }
}
Stats.bells = 0
Hook.onInput { |b|
if (b == 0x07) Stats.bells = Stats.bells + 1
return false
}
Inspect the count from the Wren console (see Built-in REPL) — Stats.bells
returns the running total. Returning false lets the byte through
to cterm; returning true would consume it (so the BEL never reaches
the terminal and never beeps). Filtered variants —
Hook.onInput(0x07, fn) — push the byte equality check to the C
side, avoiding a Wren entry on every non-target byte.
CTerm Manual
This manual describes the ANSI-BBS/ECMA-48 terminal. See the emulation manual index for VT52, PETSCII, ATASCII, Prestel/BBC Mode 7, SkyPix, IGS, BIG and Operation Overkill II.
CTerm terminal characteristics
End of line behaviour (wrapping):
The cursor is moved to the first character of the next line as soon as a character is written to the last column of the current line, not on the next character. A tab will wrap to the next line only if the current cursor position is the last character on the line. This behavior is often surprising to people who are used to VT emulators which implement the LCF as documented in [STD-070], who expect the cursor to "stick" in the last column until the next character is received.
At the bottom margin, immediate wrapping scrolls the scrolling region. This applies to every printable character, including a space. Writing column 79 of an 80-column display only moves the cursor to column 80; writing column 80 causes the wrap. Partial scrolling regions follow the same rule as full-height regions.
There are two settable flags that will impact the default behaviour.
CSI ? 7 l will disable wrapping at the end of line
completely, and any characters written to the last column will
not move the cursor at all, overwriting the existing charater.
Default behaviour can be restored with CSI ? 7 h.
If the CSI = 4 h sequence is received, CTerm will enable LCF
mode as documented in [STD-070], and CSI = 4 l will restore
default behaviour. CSI = 5 h will set LCF mode and disable
CSI = 4 l, as well as cause LCF to remain enabled across
an ESC c (RIS).
Specifically, the LCF will be
set when displaying a printable character advances the cursor
to the right margin, and cleared by any of the following being
received:
CSI ? 6 h, CSI ? 6 l, CSI ? 7 l, CSI @, CSI A, CSI B, CSI a
CSI j, CSI H, CSI f, CSI I, CSI Y, CSI J, CSI K, CSI P
CSI X, CSI r, ESC E, ESC M, CR, LF, BS, TAB
Any normal printable character when the cursor is at the right
margin (of the screen or scrollable area).
C0 Control characters
0x00 NUL (NUL)
In doorway mode, indicates that the next character is a literal character. The IBM CP437 character will be displayed. This allows ESC and other control characters to be placed on the screen.
SOURCE: [BANSI]
0x07 Bell (BEL)
Beep
0x08 Backspace (BS)
Non-destructive backspace. Moves cursor position to the previous column unless the current column is the first, in which case no operation is performed.
SOURCE: [ECMA-48]
0x09 Character Tabulation (HT)
Default character tabulation stops are at columns 1, 9, 17, and every eight columns thereafter, through the current terminal width. Resizing retains existing stops, including stops temporarily outside the screen. Growing past the previously initialized width adds defaults in the new columns unless all character tabulation stops have been cleared with TBC. A reset restores defaults for the current width.
Moves to the next character tabulation stop. Does not overwrite any characters in between. If there are no character tabulation stops left in the line, moves to the first position of the next line. If the starting position is on the last line, will perform a scroll, filling the new line at bottom with the current attribute.
|
Note
|
0x0B (VT) is NOT treated as a line tabulation control character.
It is displayed as the CP437 glyph (♂). Use CVT (CSI Pn Y) for
line tabulation.
|
SOURCE: [ECMA-48]
0x0A Line Feed (LF)
Move cursor position to same column of the next row. If current row is the last row, scrolls the screen up and fills the new row with the current attribute.
SOURCE: [ECMA-48]
0x1B Escape (ESC)
Introduces a control code. The ESC and the next byte
together form the control code. If the control code is
not valid, the ESC is ignored.
SOURCE: [ECMA-48]
nF Escape Sequences
nF Escape Sequences are in the following format:
ESC {SPACE to '/}{'0' to '~'}
There may be multiple characters from the {SPACE to '/'} before the
terminating {'@' to '~'} character.
At present, CTerm does not support any nF escape sequences.
SOURCE: [ECMA-35]
Fp Escape Sequences (Private control functions)
Private control functions are in the following format:
ESC {'0' to '?'}
SOURCE: [ECMA-35]
Legal combinations not handled are silently dropped.
ESC : Escaped String Terminator (ESCST)
Reserved for use within STS transmitted content (FETM=INSERT mode).
OSC 8 hyperlink sequences inside an SOS-framed STS response cannot use
bare ST (ESC \) as their terminator because it would prematurely close
the SOS frame. Instead, ESC : \ (0x1B 0x3A 0x5C) is used as a
substitute terminator.
ESC : is an unassigned Fp private-use escape sequence (per [ECMA-35]).
A conformant parser that encounters ESC : outside of STS content
silently drops it (per the rule above). Within STS FETM=INSERT content,
the host parser recognizes the three-byte sequence ESC : \ as "escaped
ST" and converts it to ESC \ before replay.
Fe Escape Sequences (Control functions in the C1 set)
Control codes are in the following format:
ESC {'@' to '_'}
Legal combinations which are not handled are silently dropped.
ESC E Next Line (NEL)
Moves to the line home position of the next line.
(Same as CR LF)
SOURCE: [ECMA-48]
ESC F Start of Selected Area (SSA)
Marks the active presentation position as the first character position of a selected area. The content from SSA to ESA (or to the cursor position, depending on TTM) is eligible for transmission when STS is received.
SSA and ESA are cleared by changes to scroll margins (DECSTBM, DECSLRM), origin mode (DECOM), or RIS.
Scrolling does not invalidate SSA — it marks a position in the presentation component, not the content at that position. When STS triggers, the terminal reads whatever content is currently at the marked positions.
SOURCE: [ECMA-48] (Section 8.3.138)
ESC G End of Selected Area (ESA)
Marks the active presentation position as the last character position (inclusive) of a selected area begun by SSA.
ESA is required when TTM is set to ALL (CSI 16 h). When TTM is
CURSOR (the default), the cursor position defines the end instead.
If no ESA has been issued, the selected area extends to the last cell of the viewport.
SOURCE: [ECMA-48] (Section 8.3.47)
ESC H Character Tabulation Set (HTS)
Sets a character tabulation stop at the current column.
SOURCE: [ECMA-48]
ESC J Line Tabulation Set (VTS)
Sets a line tabulation stop at the current line. Line tabulation stops
are used by CVT (CSI Pn Y) and can be cleared by TBC with parameter
values 1, 4, or 5.
Line tabulation stops are at fixed row numbers and are not affected by scrolling. No default line tabulation stops are set.
SOURCE: [ECMA-48]
ESC P Device Control String (DCS)
Begins a string consisting of the characters 0x08 - 0x0d and
0x20-0x7e, terminated by a String Terminator (ST)
If a byte outside the valid range (other than ESC) is received, the
string is discarded and the byte is re-processed as normal input.
This applies to all command strings: DCS, OSC, PM, and APC.
Introduces Device Control Strings
SOURCE: [ECMA-48]
ESC S Set Transmit State (STS)
Triggers transmission of the selected area content established by SSA (and optionally ESA) back to the host.
The response is framed as SOS CTerm:STS:<N>: <content> ST where
<N> is 0 for FETM=INSERT (attributed) or 1 for FETM=EXCLUDE
(text only).
With TTM=CURSOR (default, CSI 16 l): Content from SSA up to but
excluding the cursor position is transmitted.
With TTM=ALL (CSI 16 h): Content from SSA through ESA (inclusive)
is transmitted regardless of cursor position.
With FETM=INSERT (default, CSI 14 l): Characters are transmitted
with SGR sequences for attribute changes, doorway mode encoding for C0
control characters in cells, and OSC 8 for hyperlink changes. The
stream is valid ECMA-48 that can be replayed to reproduce the region
(after escaped-ST expansion; see below).
Escaped ST in attributed content: OSC 8 sequences require ST (ESC \)
as their terminator, but bare ST would prematurely close the SOS frame.
Within STS FETM=INSERT content, OSC 8 sequences are terminated with
ESC : \ (0x1B 0x3A 0x5C) instead of ESC \ (0x1B 0x5C).
ESC : is an unassigned Fp private-use escape sequence (per ECMA-35)
that any conformant parser silently drops. The host parser recognizes
ESC : \ within STS content as "escaped ST" and converts it to ESC \
before replay.
With FETM=EXCLUDE (CSI 14 h): Only graphic characters are
transmitted. C0 and DEL bytes in cells are replaced with SPACE.
On UTF-8 connections, STS transmits the UTF-8 text mapped to the retained glyph, including multi-codepoint glyphs. A complete wide glyph is transmitted once. Selecting only one of its two cells transmits a space with that cell’s rendition in attributed mode. On byte-oriented connections, STS encodes each cell using its font’s codepage.
The transmitted stream is a linear sequence of character positions in presentation order (left to right, top to bottom). No line boundary markers are emitted — the host slices by the known screen width.
If no SSA has been issued, or the eligible area is empty, an empty
response is returned: SOS CTerm:STS:<N>: ST
STS automatically clears the transmit state after transmission completes.
SOURCE: [ECMA-48] (Section 8.3.145)
ESC X Start Of String (SOS)
As the above strings, but may contain any characters except a Start Of String sequence or a String Terminator sequence.
SOURCE: [ECMA-48]
ESC [ Control Sequence Introducer (CSI)
Introduces Control Sequences
ESC ] Operating System Command (OSC)
Begins a string consisting of the characters 0x08 - 0x0d and 0x20-0x7e, terminated by a String Terminator (ST)
Introduces Operating System Commands
SOURCE: [ECMA-48]
ESC ^ Privacy Message (PM)
Begins a string consisting of the characters 0x08 - 0x0d and
0x20-0x7e, terminated by a String Terminator (ST)
The string is currently ignored.
SOURCE: [ECMA-48]
ESC _ Application Program Command (APC)
Begins a string consisting of the characters 0x08 - 0x0d and 0x20-0x7e, terminated by a String Terminator (ST)
Introduces Application Program Commands
SOURCE: [ECMA-48]
Fs Escape Sequences (Standardized single control functions)
Standardized single control functions are in the following format:
ESC {'`' to '~'}
SOURCE: [ECMA-35]
Legal combinations not handled are silently dropped.
ESC c Reset to Initial State (RIS)
Resets all the terminal settings, clears the screen, and homes the cursor.
SOURCE: [ECMA-48]
Control Sequences
Control sequences start with the Control Sequence Introducer which is
ESC [. CSI will be used to express this from now on.
Control sequences are in the following format:
CSI {'0' (ZERO) to '?'}{SPACE to '/'}{'@' to '~'}
There may be multiple characters from the {'0' (ZERO) to '?'}
and {SPACE to '/'} before the terminating {'@' to '~'} character.
Legal combinations not handled are silently dropped. Illegal combinations are displayed.
Sequence Parameters
Parameters are expressed by the {'0' (ZERO) to '?'} character set.
Sequences which use parameters use decimal parameters separated by a ';'. The use of a ':' from the set is reserved.
If the parameter string begins with '<', '=', '>', or '?' then this is a non-standard extension to the ANSI spec.
|
Indicates a single numeric parameter |
|
Two numeric parameters |
|
Any number of numeric parameters |
|
Single selective parameter |
|
Two selective parameters |
|
Any numer of selective parameters |
If a default is defined, the parameter is optional
CSI Pn @ Insert Character(s) (ICH)
Defaults: Pn = 1
Moves text from the current position to the right edge Pn characters
to the right, with rightmost characters going off-screen and the
resulting hole being filled with the current attribute.
SOURCE: [ECMA-48]
CSI Pn SP @ Scroll Left (SL)
Defaults: Pn = 1
Shifts the contents of the screen left Pn columns(s) with
leftmost columns going off-screen and the resulting hole being
filled with the current attribute.
SOURCE: [ECMA-48]
CSI Pn A Cursor Up (CUU)
Defaults: Pn = 1
Moves the cursor position up Pn lines from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn SP A Scroll Right (SR)
Defaults: Pn = 1
Shifts the contents of the screen right Pn columns(s) with
rightmost columns going off-screen and the resulting hole being
filled with the current attribute.
SOURCE: [ECMA-48]
CSI Pn B Cursor Down (CUD)
Defaults: Pn = 1
Moves the cursor position down Pn lines from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn C Cursor Right (CUF)
Defaults: Pn = 1
Moves the cursor position right Pn columns from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn D Cursor Left (CUB)
Defaults: Pn = 1
Moves the cursor position left Pn columns from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Ps1 ; Ps2 sp D Font Selection (FNT)
Defaults: Ps1 = 0 Ps2 = 0
"sp" indicates a single space character.
Assigns the registered font selector Ps2 (0–255) to position Ps1
(0–9). All ten positions start with the configured default font.
Assignments affect subsequent text. SGR 0 and SGR 10 select the primary
rendition and preserve the assignments.
0 |
Default font |
1 |
Font selected by the high intensity bit when |
2 |
Font selected by the blink intensity bit when |
3 |
Font selected by both the high intensity and blink bits when both |
4–9 |
Alternate fonts selected by SGR 14–19 |
SGR 11–19 explicitly select positions 1–9. The intensity and blink bits select a font only in the primary rendition.
For byte-oriented ANSI text, the selected font supplies the display codepage,
including when position 0 is active. For example, with a CP437 profile and
a CP1251 font, incoming byte 0xC0 displays and copies as Cyrillic А.
Typing or pasting é sends the CP437 byte 0x82. UTF-8 text retains its
Unicode meaning when the font changes.
0 |
Codepage 437 English |
1 |
Codepage 1251 Cyrillic, (swiss) |
2 |
Russian koi8-r |
3 |
ISO-8859-2 Central European |
4 |
ISO-8859-4 Baltic wide (VGA 9bit mapped) |
5 |
Codepage 866 (c) Russian |
6 |
ISO-8859-9 Turkish |
7 |
haik8 codepage (use only with armscii8 screenmap) |
8 |
ISO-8859-8 Hebrew |
9 |
Ukrainian font koi8-u |
10 |
ISO-8859-15 West European, (thin) |
11 |
ISO-8859-4 Baltic (VGA 9bit mapped) |
12 |
Russian koi8-r (b) |
13 |
ISO-8859-4 Baltic wide |
14 |
ISO-8859-5 Cyrillic |
15 |
ARMSCII-8 Character set |
16 |
ISO-8859-15 West European |
17 |
Codepage 850 Multilingual Latin I, (thin) |
18 |
Codepage 850 Multilingual Latin I |
19 |
Codepage 885 Norwegian, (thin) |
20 |
Codepage 1251 Cyrillic |
21 |
ISO-8859-7 Greek |
22 |
Russian koi8-r (c) |
23 |
ISO-8859-4 Baltic |
24 |
ISO-8859-1 West European |
25 |
Codepage 866 Russian |
26 |
Codepage 437 English, (thin) |
27 |
Codepage 866 (b) Russian |
28 |
Codepage 885 Norwegian |
29 |
Ukrainian font cp866u |
30 |
ISO-8859-1 West European, (thin) |
31 |
Codepage 1131 Belarusian, (swiss) |
32 |
Commodore 64 (UPPER) |
33 |
Commodore 64 (Lower) |
34 |
Commodore 128 (UPPER) |
35 |
Commodore 128 (Lower) |
36 |
Atari |
37 |
P0T NOoDLE (Amiga) |
38 |
mO’sOul (Amiga) |
39 |
MicroKnight Plus (Amiga) |
40 |
Topaz Plus (Amiga) |
41 |
MicroKnight (Amiga) |
42 |
Topaz (Amiga) |
43 |
Prestel |
44 |
Atari ST |
45 |
RIPterm |
Not all fonts are supported in all modes. If a font is not supported in the current mode, no action is taken, but there should be a non-zero 'Font Selection result' value in the Font State Report.
SOURCE: [ECMA-48]
CSI Pn E Cursor Next Line (CNL)
Defaults: Pn = 1
Moves the cursor to the first column of the line Pn down from the
current position. Attempting to move past the screen boundaries
stops the cursor at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn F Cursor Preceding Line (CPL)
Defaults: Pn = 1
Moves the cursor to the first column of the row Pn up from the
current position. Attempting to move past the screen boundaries
stops the cursor at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn G Cursor Character Absolute (CHA)
Defaults: Pn = 1
Movies the cursor to column Pn of the current row.
SOURCE: [ECMA-48]
CSI Pn1 ; Pn2 H Cursor Position (CUP)
Defaults: Pn1 = 1 Pn2 = 1
Moves the cursor to the `Pn2`th column of the `Pn1`th line.
SOURCE: [ECMA-48]
CSI Pn I Cursor Forward Tabulation (CHT)
Defaults: Pn = 1
Move the cursor to the Pn-th next tab stop.
Basically the same as sending TAB Pn times.
SOURCE: [ECMA-48]
CSI Ps J Erase in Page (ED)
Defaults: Ps = 0
Erases from the current screen according to the value of Ps
0 |
Erase from the current position to the end of the screen. |
1 |
Erase from the current position to the start of the screen. |
2 |
Erase entire screen. As a violation of ECMA-048, also moves the cursor to position 1/1 as a number of BBS programs assume this behaviour. |
Erased characters are set to the current attribute.
CSI Ps K Erase in Line (EL)
Defaults: Ps = 0
Erases from the current line according to the value pf Ps
0 |
Erase from the current position to the end of the line. |
1 |
Erase from the current position to the start of the line. |
2 |
Erase entire line. |
Erased characters are set to the current attribute.
SOURCE: [ECMA-48]
CSI Pn L Insert Line(s) (IL)
Defaults: Pn = 1
Inserts Pn lines at the current line position. The current line and
those after it are scrolled down and the new empty lines are filled
with the current attribute. If the cursor is not currently inside
the scrolling margins, has no effect.
SOURCE: [ECMA-48]
CSI Pn M Delete Line(s) / "ANSI" Music (DL)
Defaults: Pn = 1
Deletes the current line and the Pn - 1 lines after it scrolling the
first non-deleted line up to the current line and filling the newly
empty lines at the end of the screen with the current attribute.
If the cursor is not currently inside the scrolling margins, has no
effect.
If "ANSI" Music is fully enabled (CSI = 2 M), and no parameter is
specified, performs "ANSI" music instead.
See "ANSI" MUSIC section for more details.
CSI = Ps M CTerm Set ANSI Music (CTSAM)
NON-STANDARD EXTENSION.
Defaults: Ps = 0
Sets the current state of ANSI music parsing.
0 - Only CSI | will introduce an ANSI music string.
1 - Both CSI | and CSI N will introduce an ANSI music string.
2 - CSI |, CSI N, and CSI M will all introduce an ANSI music string.
In this mode, Delete Line will not be available.
CSI N BananaCom ANSI Music (BCAM)
"ANSI" Music / Not implemented.
If "ANSI" Music is set to BananaCom (CSI = 1 M) or fully enabled
(CSI = 2 M) performs "ANSI" music. See "ANSI" MUSIC section for more
details.
SOURCE: [BANSI]
CSI Pn P Delete Character (DCH)
Defaults: Pn = 1
Deletes the character at the current position by shifting all
characters from the current column + Pn left to the current column.
Opened blanks at the end of the line are filled with the current
attribute. If the cursor is not currently inside the scrolling
margins, has no effect.
SOURCE: [ECMA-48]
CSI Pn S Scroll Up (SU)
Defaults: Pn = 1
Scrolls the screen up Pn lines. New lines emptied at the
bottom are filled with the current attribute.
SOURCE: [ECMA-48]
CSI ? Ps1 ; Ps2 S XTerm Set or Request Graphics Attribute (XTSRGA)
If Ps1 is 2, and Ps2 is 1, replies with the graphics screen information
in the following format: CSI ? 2 ; 0 ; Px ; Py S
Where Px is the width of the screen in pixels and Py is the height.
SOURCE: [XTerm]
CSI Pn T Scroll Down (SD)
Defaults: Pn = 1
Scrolls all text on the screen down Pn lines. New lines emptied at the
top are filled with the current attribute.
SOURCE: [ECMA-48]
CSI Pn X Erase Character (ECH)
Defaults: Pn = 1
Erase p1 characters starting at the current character. Will not erase
past the end of line.
Erased characters are set to the current attribute.
This can erase across scroll margins.
SOURCE: [ECMA-48]
CSI Pn Y Cursor Line Tabulation (CVT)
Defaults: Pn = 1
Moves the cursor to the corresponding character position (same column)
of the line corresponding to the Pn-th following line tabulation stop.
Line tabulation stops are set by VTS (ESC J).
If there is no next line tabulation stop, the screen scrolls up one line and the cursor moves to the last row, preserving the current column.
SOURCE: [ECMA-48]
CSI Pn Z Cursor Backward Tabulation (CBT)
Defaults: Pn = 1
Move the cursor to the Pnth preceding tab stop. Will not go past the
start of the line.
SOURCE: [ECMA-48]
CSI Pn ` Character Position Absolute (HPA)
Defaults: Pn = 1
Move the cursor to the specified position on the current row.
Will not go past the end of the line.
SOURCE: [ECMA-48]
CSI Pn a Cursor Position Forward (HPR)
Defaults: Pn = 1
Moves the cursor position forward Pn columns from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn b Repeat (REP)
Defaults: Pn = 1
Repeats the previous graphic character Pn times. Will not repeat
escape sequences.
SOURCE: [ECMA-48]
CSI Ps c Device Attributes (DA)
Defaults: Ps = 0
If Ps is 0, CTerm will reply with the sequence:
CSI = 67;84;101;114;109;pN c
67;84;101;114;109 is the ASCII values of the "CTerm" string. pN is the
revision ID of CTerm with dots converted to semi-colons
(e.g. "1;156"). Use the revision to detect if a specific feature
is available. If you are adding features to a forked version of cterm,
please do so by adding an extra parameter to the end, not by
incrementing any existing one!
SyncTERM APC blob verbs (DrawPPMBlob, DrawJXLBlob, LoadPPMBlob,
LoadJXLBlob, LoadPBMBlob, and audio LoadBlob) are available in
revision 1.329 and later.
SGR pixel-position mouse reporting (DECSET 1016) is available in
revision 1.330 and later.
APC SyncTERM:Q;libsndfileFormat;pm;ps ST is available in revision
1.331 and later.
Graphics APC FX, FY, ZX, and ZY arguments and negative
DX/DY destination coordinates are available in revision 1.332 and
later.
MIDI feature queries, QueueMIDI, and the complete ANSI note range 0..83
are available in revision 1.333 and later.
SOURCE: [ECMA-48]
CSI < Ps c CTerm Device Attributes (CTDA)
Defaults: Ps = 0
If Pn is 0, CTerm will reply with the sequence:
CSI < 0 ; Ps… c
1 |
Loadable fonts are availabe via Device Control Strings |
2 |
Bright Background (ie: DECSET 32) is supported |
3 |
Palette entries may be modified via an Operating System Command string |
4 |
Pixel operations are supported (currently, sixel and PPM graphics) |
5 |
The current font may be selected via |
6 |
Extended palette is available |
7 |
Mouse is available |
8 |
Physical key press/release reports are available |
9 |
Joystick and gamepad reports are available, including when no device is attached |
CSI PN d Line Position Absolute (VPA)
Defaults: Pn = 1
Moves to row specified by Pn.
SOURCE: [ECMA-48]
CSI Pn SP d Tab Stop Remove (TSR)
Defaults: None
Removes a tab stop at postion Pn.
SOURCE: [ECMA-48]
CSI Pn1 ; Pn2 f Character and Line Position (HVP)
Defaults: Pn1 = 1 Pn2 = 1
Moves the cursor to the Pn2th column of the Pn1th line.
SOURCE: [ECMA-48]
CSI Ps g Tabulation Clear (TBC)
Defaults: Ps = 0
Clears tabulation stops according to the value of Ps:
0 |
Clears the character tabulation stop at the current position. |
1 |
Clears the line tabulation stop at the current line. |
3 |
Clears all character tabulation stops. |
4 |
Clears all line tabulation stops. |
5 |
Clears all tabulation stops (both character and line). |
SOURCE: [ECMA-48]
CSI Ps… h Set Mode (SM)
Sets one or more ANSI modes. The following modes are supported:
4 |
INSERTION REPLACEMENT MODE (IRM) = INSERT. Each graphic shifts the cells from the cursor through the right margin to the right by its displayed width. Cells shifted past the margin are lost. After autowrap, insertion continues at the beginning of the next line. |
14 |
FORMAT EFFECTOR TRANSFER MODE (FETM) = EXCLUDE. When set, transmitted data (via STS) contains only graphic characters. C0/DEL bytes in cells are replaced with SPACE. SGR, positioning, and other formator functions are excluded. |
16 |
TRANSFER TERMINATION MODE (TTM) = ALL. When set, the complete selected area from SSA to ESA is transmitted regardless of cursor position. When reset (default), only content preceding the cursor is transmitted (cursor position excluded). |
SOURCE: [ECMA-48] (Sections 7.2.6, 7.2.18)
CSI = 1 h Enable Physical Key Reports
NON-STANDARD EXTENSION
Enables reporting of physical key press and release events. When enabled,
key presses are reported as CSI = Pk[;Pk…]K, and key releases are
reported as CSI = Pk[;Pk…]k.
Pk is an evdev key code number from the EVDEV_KEY_* namespace. Multiple
parameters may be included when several key edges are reported together.
Physical key reports describe key identity before normal character
translation; they do not replace normal translated key input unless
translated key suppression is also enabled.
SOURCE: CTerm only.
CSI = 6 h Enable Joystick and Gamepad Reports
Enable with CSI = 6 h and disable with CSI = 6 l. Reporting starts disabled
and a terminal reset disables it. Query with CSI = 6 $ p. The reply is
CSI = 6 ; Pm $ y, where 0 means unavailable, 1 enabled, and 2 disabled.
Repeated enable is idempotent. Disable has no acknowledgement. Discard the
inventory on disable or reset. Enable again to request a fresh inventory.
SyncTERM discovers devices when reporting is enabled and monitors hotplug
while reports are requested. A mode query only reads the reporting state.
A controller report begins with ESC (0x1b), [, and =, and ends with
uppercase J. All fields are unsigned ASCII decimal integers separated by
semicolons, without whitespace or a line terminator. Keyboard press and
release reports use the same prefix and end with K and k, respectively.
A BBS can use both modes on the same connection.
Report following ESC[= |
Meaning |
|---|---|
|
Device added. Class 1 is a joystick and 2 a gamepad. Source 1 is USB HID, 2 is a mapped libretro port, and 3 is XUSB. |
|
Named evdev control and its inclusive wire range. |
|
Known initial value or changed value. |
|
End of frame. Apply this device’s pending values together. |
|
Device removed. Discard its capabilities, values and any pending frame. |
|
Initial inventory complete. This is the entire inventory for zero devices. |
Each device is announced with all capabilities, all known values, and a frame end, in that order. An absent initial value remains unknown until reported. XUSB gamepads report the left and right triggers as independent axes. Windows XInput omits the Guide button. Hotplug follows the same announcement order. Device IDs are positive and never reused during a connection. Reassigning a control removes the old device and announces its new capabilities under a fresh ID.
-
Type 1 (
EV_KEY) uses literal 0 for released and 1 for pressed. Held buttons do not repeat. A button-based D-pad usesBTN_DPAD_*. Individual directions of a hat can also be assigned to these buttons. A diagonal presses both adjacent directions, independently of the hat axis reports. -
Type 3 (
EV_ABS) uses scaled signed values. Sticks range from −32768 through 32767 with zero at center. Triggers range from 0 through 32767 with zero at rest. Each hat has separate horizontal and vertical axes ranging from −1 through 1. Positive X is right and positive Y is down. -
Each axis minimum, maximum and value uses the same encoding. For a nonnegative integer
n, send2n. For a negative integer, send−2n−1. For example,ESC[=3;1;3;0;3Jmoves device 1’s X axis to −2. A followingESC[=4;1Jcommits the change. SyncTERM reports changes in the scaled value. There is no gameplay dead zone.
In Program Settings, open Controller Mapping. Select a BBS input and move or press the physical control to assign it. To start with the controller, choose Press a control to assign. Unknown button numbers remain unassigned until mapped. The mapper can preview movement, invert an axis, clear a binding, or move a binding between controls. Mappings are shared by devices with the same USB vendor, product, report descriptor and application collection. Each attached unit has a separate device ID. Configure RetroPad assignments in the libretro frontend.
CSI = 2 h Suppress Translated Key Input
NON-STANDARD EXTENSION
Suppresses normal translated key input while leaving physical key reports
enabled if CSI = 1 h has also been set. This mode is intended for programs
that want physical key press/release reports without also receiving the
terminal’s normal key translation for the same input.
SOURCE: CTerm only.
CSI = 4 h Enable Last Column Flag (CTELCF)
NON-STANDARD EXTENSION
Enable Last Column Flag mode
CSI = 5 h Force Last Column Flag (CTFLCF)
NON-STANDARD EXTENSION
Force Last Column Flag mode
CSI ? Ps… h Set Mode (DECSET)
NON-STANDARD EXTENSION
Sets one or more mode. The following modes are supported:
6 |
Enable origin mode. In this mode, position parameters are relative to the top left of the scrolling region, not the screen. Defaults to reset. SOURCE: [VT102] |
7 |
Enable auto wrap This is the normal mode in which a write to the last column of a row will move the cursor to the start of the next line triggering a scroll if required to create a new line. Defaults to set. SOURCE: [VT102] |
9 |
X10 compatible mouse reporting Mouse button presses will send a CSI M <button> <x> <y> Where <button> is ' ' + button number (0-based) <x> and <y> are '!' + position (0-based) SOURCE: [XTerm] |
25 |
Display the cursor. Defaults to set. SOURCE: [VT320] |
31 |
Enable bright alt character set With this mode set, the bright (1) graphic rendition selects characters from an alternate character set. Defaults to reset. |
32 |
Bright Intensity Disable This makes the bright intensity bit not control the intensity.
Mostly for use with |
33 |
Blink to Bright Intensity Background With this mode set, the blink (5,6) graphic renditions cause the background colour to be high intensity rather than causing blink. Defaults to reset. |
34 |
Enable blink alt character set With this mode set, the blink (5, 6) graphic renditions selects characters from an alternate character set. Defaults to reset |
35 |
Blink Disabled This makes the blink (5, 6) graphic renditions not cause the
character to blink. Mostly for use with |
67 |
When set, the backspace key sends a backspace character. Defaults to set. |
69 |
DEC Left Right Margin Mode enabled Enables |
80 |
Sixel Display Mode (Sixel Scrolling Disabled) When this is set, the sixel active position begins in the upper-left corner of the page. Any commands that attempt to advance the sixel position past the bottom of the page are ignored. At the end of the sixel string, the current cursor position is unchanged from where it was when the sixel string started. Defaults to reset. NOTE: The VT330/340 manual had this documented backward. SOURCE: [VT384] |
1000 |
Normal tracking mode mouse reporting Mouse button presses will send a CSI M <button> <x> <y> Where <button> is ' ' + button number (0-based) Mouse button releases will use a button number of 4 <x> and <y> are '!' + position (0-based) SOURCE: [XTerm] |
1001 |
Highlight tracking mode mouse reporting (Not supported by SyncTERM) SOURCE: [XTerm] |
1002 |
Button-event tracking mode mouse reporting Mouse button presses and movement when a button is pressed will send a CSI M <button> <x> <y> Where <button> is ' ' + button number (0-based) 32 is added to the button number for movement events. Mouse button releases will use a button number of 4 <x> and <y> are '!' + position (0-based) SOURCE: [XTerm] |
1003 |
Any-event tracking mode mouse reporting Mouse button presses and movement will send a CSI M <button> <x> <y> Where <button> is ' ' + button number (0-based) 32 is added to the button number for movement events. Mouse button releases will use a button number of 4 <x> and <y> are '!' + position (0-based) If no button is pressed, it reports that all buttons are released. SOURCE: [XTerm] |
1004 |
Focus-event tracking mode mouse reporting (Not supported by SyncTERM) SOURCE: [XTerm] |
1005 |
UTF-8 encoded extended coordinates (Not supported by SyncTERM) SOURCE: [XTerm] |
1006 |
SGR encoded extended coordinates Instead of the CSI M method, the format of mouse reporting is changed to CSI < Pb ; Px ; Py M for presses and CSI < Pb ; Px ; Py m for releases. Instead of CSI M Px and Py are one-based. Pb remains the same (32 added for movement) Button 3 is not used for release (separate code) SOURCE: [XTerm] |
1007 |
Alternate scroll mode (Not supported by SyncTERM) SOURCE: [XTerm] |
1015 |
URXVT encoded extended coordinates (Not supported by SyncTERM) SOURCE: [XTerm] |
1016 |
SGR encoded pixel-position coordinates Uses the same CSI < Pb ; Px ; Py M/m reporting format as mode 1006, but Px and Py are one-based pixel positions instead of character-cell positions. SOURCE: [XTerm] |
2004 |
Set bracketed paste mode SOURCE: [XTerm] |
2026 |
Begin synchronized output (BSU). Bitmap backends display all output received before this sequence and keep that screen animating while the host updates text, graphics, palette and cursor state. Queries see the live terminal state. Repeated BSU preserves the original frame and deadline. SyncTERM releases a hold after three seconds, on terminal reset or disconnect, or when switching the active console. SOURCE: Synchronized Output |
CSI Pn j Character Position Backward (HPB)
Defaults: Pn = 1
Moves the cursor position left Pn columns from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI Pn k Line Position Backward (VPB)
Defaults: Pn = 1
Moves the cursor position up Pn lines from the current position.
Attempting to move past the screen boundaries stops the cursor
at the screen boundary.
SOURCE: [ECMA-48]
CSI = Pk[;Pk…]K Physical Key Press Report
NON-STANDARD EXTENSION
Sent by CTerm when physical key reports are enabled and one or more keys are
pressed.
Each Pk parameter is an evdev key code number from the EVDEV_KEY_*
namespace. Multiple parameters indicate that several press edges are being
reported in one sequence.
SOURCE: CTerm only.
CSI Ps… l Reset Mode (RM)
Resets ANSI modes. Same parameter values as SM above. Resetting mode 4 selects replacement (the default). Resetting mode 14 restores FETM=INSERT (attributed transmission). Resetting mode 16 restores TTM=CURSOR (cursor-exclusive termination).
SOURCE: [ECMA-48]
CSI = 1 l Disable Physical Key Reports
NON-STANDARD EXTENSION
Disables physical key press/release reports and clears CTerm’s remembered
physical-key state. Disabling this mode does not emit release reports for
keys that were held when the mode was disabled.
SOURCE: CTerm only.
CSI = 2 l Restore Translated Key Input
NON-STANDARD EXTENSION
Restores normal translated key input after CSI = 2 h.
SOURCE: CTerm only.
CSI = 4 l (CTDLCF)
NON-STANDARD EXTENSION
Disable Last Column Flag mode
CSI = Pk[;Pk…]k Physical Key Release Report
NON-STANDARD EXTENSION
Sent by CTerm when physical key reports are enabled and one or more keys are
released.
Each Pk parameter is an evdev key code number from the EVDEV_KEY_*
namespace. Multiple parameters indicate that several release edges are being
reported in one sequence.
SOURCE: CTerm only.
CSI ? Ps… l Reset Mode (DECRST)
NON-STANDARD EXTENSION
Resets one or more mode. The following modes are supported:
6 |
Origin Mode With this mode reset, position parameters are relative to the top left of the screen, not the scrolling region. Defaults to reset. SOURCE: [VT102] |
7 |
Disable auto wrap Resetting this mode causes a write to the last column of a to leave the cursor where it was before the write occurred, overwriting anything which was previously written to the same position. SOURCE: [VT102] |
9 |
Disable X10 compatible mouse reporting |
25 |
Hide the cursor. Defaults to set. SOURCE: [VT320] |
31 |
Disable bright alt character set With this mode reset, the bright (1) graphic rendition does not select an alternative font. Defaults to reset. |
32 |
Bright Intensity Enable When reset, bright intensity graphics rendition behaves normally. Defaults to reset. |
33 |
Disable Blink to Bright Intensity Background With this mode set, the blink (5,6) graphic renditions do not affect the background colour. Defaults to reset. |
34 |
Disable blink alt character set With this mode reset, the blink (5, 6) graphic renditions do not select characters from an alternate character set. Defaults to reset. |
35 |
Blink Enable With this mode reset, the blink (5,6) graphic renditions behave normally (cause the characters to blink). Defaults to reset. |
67 |
When reset, the backspace key sends a delete character. Defaults to set. |
69 |
DEC Left Right Margin Mode disabled Disables CSI s from setting the left/right margins, and changes it back to saving the current cursor position. The current left/right margins are maintained. |
80 |
Sixel Display Mode (Sixel Scrolling Enabled) When this is reset, the sixel active position begins in the upper-left corner of the currently active text position. When the sixel active position reaches the bottom of the page, the page is scrolled up. At the end of the sixel string, a sixel newline is appended, and the current cursor position is the one in which the bottom sixel is in. Defaults to reset. NOTE: The VT330/340 manual had this documented backward. SOURCE: [VT384] |
1000 |
Disable Normal tracking mode mouse reporting SOURCE: [XTerm] |
1001 |
Disable Highlight tracking mode mouse reporting (Not supported by SyncTERM) SOURCE: [XTerm] |
1002 |
Disable Button-event tracking mode mouse reporting SOURCE: [XTerm] |
1003 |
Disable Any-event tracking mode mouse reporting SOURCE: [XTerm] |
1004 |
Disable Focus-event tracking mode mouse reporting (Not supported by SyncTERM) SOURCE: [XTerm] |
1005 |
Disable UTF-8 encoded extended coordinates (Not supported by SyncTERM) SOURCE: [XTerm] |
1006 |
Disable SGR encoded extended coordinates SOURCE: [XTerm] |
1007 |
Disable Alternate scroll mode (Not supported by SyncTERM) SOURCE: [XTerm] |
1015 |
Disable URXVT encoded extended coordinates (Not supported by SyncTERM) SOURCE: [XTerm] |
1016 |
Disable SGR encoded pixel-position coordinates SOURCE: [XTerm] |
2004 |
Disable bracketed paste mode |
2026 |
End synchronized output (ESU) and display the completed frame. Repeated ESU has no effect. |
CSI Ps… m Select Graphic Rendition (SGR)
Defaults: Ps1 = 0
Sets or clears one or more text attributes. Unlimited parameters are
supported and are applied in received order. The following are
supported:
|
Description |
Blink |
Bold |
FG |
BG |
TF |
TB |
0 |
Default attribute, white on black |
√ |
√ |
√ |
√ |
√ |
√ |
1 |
Bright Intensity |
√ |
√ |
||||
2 |
Faint intensity. Standard ANSI foregrounds use palette entries 282–289 in ANSI colour order. SGR 1 selects bright intensity and SGR 22 restores normal intensity. Explicit indexed and RGB foregrounds retain their chosen colour. SkyPix uses its own pens. |
√ |
√ |
||||
4 |
Single underline in the foreground colour. Bitmap displays extend each inked row of the selected font’s underscore glyph across the cell. A font without a mapped underscore uses a single bottom row. Link dots occupy the bottom row and coincide with the underline when the font draws it there. |
||||||
5 |
Slow blink. On PC bitmap displays the text is visible for 266 ms and hidden for 266 ms. |
√ |
√ |
||||
6 |
Fast blink. On PC bitmap displays each half-cycle lasts 177⅓ ms (about 169.17 cycles per minute). Fast text completes three blinks for every two slow blinks. Text backends delegate blink timing to the host terminal. |
√ |
√ |
||||
7 |
Negative Image - Reverses FG and BG |
√ |
√ |
√ |
√ |
||
8 |
Conceal. Each character is drawn entirely in its effective background colour. Foreground, background and other rendition changes are retained while conceal is active. Selecting a concealed character reveals it for the duration of the selection. Clipboard copy and both STS modes include the character. Attributed STS also preserves its conceal rendition and hyperlink. |
√ |
√ |
√ |
|||
9 |
Strikethrough. Bitmap displays draw one foreground-colour row across the cell. Counting from zero, the row is the cell height divided by two, rounded down. This is the centre row for odd heights and the lower middle row for even heights. |
||||||
10 |
Primary font. Modes 31 and 34 can select positions 1–3 for bright or blinking text. |
||||||
11–19 |
Select FNT position 1–9 regardless of intensity or blink. |
||||||
21 |
Double underline. Bitmap displays draw the bottom pixel row and the row two pixels above it across the full cell width. Cells less than three pixels tall use the bottom row alone. The last SGR 4 or 21 selects the underline style. Text backends with a single underline attribute use it for either style. |
||||||
22 |
Normal intensity |
√ |
√ |
||||
24 |
End single or double underline. |
||||||
25 |
Steady (Not blinking) |
√ |
√ |
||||
27 |
Positive Image - Restores FG and BG NOTE: This should be a separate attribute than 7 but this implementation makes them equal |
√ |
√ |
√ |
√ |
||
28 |
End conceal. Subsequent characters use the current rendition. |
||||||
29 |
End strikethrough. |
||||||
30 |
Black foreground |
√ |
√ |
||||
31 |
Red foreground |
√ |
√ |
||||
32 |
Green foreground |
√ |
√ |
||||
33 |
Yellow foreground |
√ |
√ |
||||
34 |
Blue foreground |
√ |
√ |
||||
35 |
Magenta foreground |
√ |
√ |
||||
36 |
Cyan foreground |
√ |
√ |
||||
37 |
White foreground |
√ |
√ |
||||
38 |
Extended Foreground (see notes) |
√ |
|||||
39 |
Default foreground (same as white) |
√ |
√ |
||||
40 |
Black background |
√ |
√ |
||||
41 |
Red background |
√ |
√ |
||||
42 |
Green background |
√ |
√ |
||||
43 |
Yellow background |
√ |
√ |
||||
44 |
Blue background |
√ |
√ |
||||
45 |
Magenta background |
√ |
√ |
||||
46 |
Cyan background |
√ |
√ |
||||
47 |
White background |
√ |
√ |
||||
48 |
Extended Background (see notes) |
√ |
|||||
49 |
Default background (same as black) |
√ |
√ |
||||
53 |
Overline. Bitmap displays draw the top pixel row in the foreground colour across the full cell width. Either underline style can be active at the same time. |
||||||
55 |
End overline. |
||||||
90 |
Bright Black foreground |
√ |
√ |
||||
91 |
Bright Red foreground |
√ |
√ |
||||
92 |
Bright Green foreground |
√ |
√ |
||||
93 |
Bright Yellow foreground |
√ |
√ |
||||
94 |
Bright Blue foreground |
√ |
√ |
||||
95 |
Bright Magenta foreground |
√ |
√ |
||||
96 |
Bright Cyan foreground |
√ |
√ |
||||
97 |
Bright White foreground |
√ |
√ |
||||
100 |
Bright Black background |
√ |
√ |
||||
101 |
Bright Red background |
√ |
√ |
||||
102 |
Bright Green background |
√ |
√ |
||||
103 |
Bright Yellow background |
√ |
√ |
||||
104 |
Bright Blue background |
√ |
√ |
||||
105 |
Bright Magenta background |
√ |
√ |
||||
106 |
Bright Cyan background |
√ |
√ |
||||
107 |
Bright White background |
√ |
√ |
All others are ignored.
Blink indicates the blink bit. Bold indicates the bold bit. FG indicates the foreground colour. BG indicates the background colour. TF indicates that the Tru Colour foreground is changed. TB indicates that the Tru Colour background is changed.
|
Note
|
SGR 90-97 select a bright foreground independently of DECSET mode 32 and preserve the current intensity. Faint (SGR 2) renders the corresponding normal palette colour. Normal intensity (SGR 22) restores the selected bright colour. |
|
Note
|
SGR 100-107 select a bright background colour independently of blink and DECSET mode 33. |
|
Note
|
For 38 and 48, two additional formats are supported, a palette selection and a direct colour selection. |
For palette selection, an additional two parameters are required
after that value. They are considered part of the 38/48, not separate
values. The first additional parameter must be a 5. The second
additional parameter specified the palette index to use. To set the
foreground to orange, and the background to a fairly dark grey, you
would send:
CSI 38 ; 5 ; 214 ; 48 ; 5 ; 238 m
The default palette is the XTerm 256-colour palette. [256colors]
For direct colour selection, an additional four parameters are required after that value. They are considered part of the 38/48, not separate values. The first additional parameter must be a 2. The second, third, and fourth specify the R/G/B values respectively.
The colon form groups the colour components into a single SGR parameter.
The optional colour-space identifier between the 2 and the red component
is ignored and may be left empty. For example, CSI 38:2::18:52:86;4 m
sets the foreground to RGB (18, 52, 86) and enables underline.
Use 48 in place of 38 for the background.
CSI Ps n Device Status Report (DSR)
Defaults: Ps = 0
A request for a status report. CTerm handles the following three
requests:
5 |
Request a DSR CTerm will always reply with CSI 0 n indicating "ready, no malfunction detected" |
6 |
Request active cursor position CTerm will reply with CSI y ; x R where y is the current line
and x is
the current row. When origin mode ( |
255 |
NON-STANDARD EXTENSION (BCDSR) Replies as though a CSI 6 n was received with the cursor in the bottom right corner. i.e.: Returns the terminal size as a position report. |
CSI = Ps n State/Mode Request/Report (CTSMRR)
NON-STANDARD EXTENSION
Defaults: Ps = 1
When Ps is 1, CTerm will respond with a Font State Report of the form
CSI = 1 ;pF ;pR ;pS0 ;pS1 ;pS2 ;pS3 n
pF is the first available loadable-font slot number
pR is the result of the previous "Font Selection" request:
0 |
successful font selection |
1 |
failed font selection |
99 |
no font selection request has been received |
pS0 - pS3 contain the font slots numbers of previously successful
"Font Selection" requests for the four attribute-based positions:
|
normal attribute font slot |
|
high intensity foreground attribute font slot |
|
blink attribute font slot |
|
high intensity blink attribute font slot |
When Ps is 2, CTerm will respond with a Mode Report of the form
CSI = 2[;pN [;pN] […]] n
Where pN represent zero or more mode values set previously
(e.g. via CSI ? pN h). Mode values cleared (disabled via CSI ? pN l)
will not be included in the set of values returned in the Mode
Report. If no modes are currently set, an empty parameter will be
included as the first and only pN.
When Ps is 3, CTerm will respond with a Mode Report of the form
CSI = 3 ; pH ; pW n
Where pH is the height of a character cell in pixels, and pW is
the width of a character cell in pixels.
When Ps is 4, CTerm will respond with a Mode Report of the form
CSI = 4 ; pF n
Where pF is 1 if LCF mode is enabled, and 0 if it is disabled.
When Ps is 5, CTerm will respond with a Mode Report of the form
CSI = 5 ; pF n
Where pF is 1 if LCF mode is forced, and 0 if it is not.
When Ps is 6, CTerm will respond with a Mode Report of the form
CSI = 6 ; pA n
Where pA is 1 if OSC 8 hyperlink support is available, and 0 if
it is not.
When Ps is 7, CTerm will respond with an Audio State Report of the form
CSI = 7 [ ; pI ; pS ]… n
where zero or more (pI, pS) pairs are packed into one sequence.
pI is a channel number (0..15) or a feature ID (100+). States are
0 for stopped/unavailable and 1 for running/available. Feature IDs
defined:
100 |
libsndfile |
CSI = 7 n requests all running channels. The response emits one pair
per running channel, omitting non-running channels. A fully idle terminal
replies with just CSI = 7 n and no pairs.
CSI = 7 ; pC n requests one specific channel. The response always
emits exactly one (pC, pS) pair.
CSI = 7 ; pC ; pS n may also be emitted asynchronously when an audio
channel armed via APC SyncTERM:A;Update transitions from running to
stopped.
When Ps is 8, CTerm reports all ten font assignments in position order:
CSI = 8 ;pS0 ;pS1 ;pS2 ;pS3 ;pS4 ;pS5 ;pS6 ;pS7 ;pS8 ;pS9 n.
Each value is the font selector assigned to the corresponding FNT position.
CSI ? Ps [ ; Pn ] n Device Status Report (DECDSR)
When Ps is 62 (DECMSR) and there is no Pn, CTerm will respond
with a Mode Report of the form
CSI 32767 * {
This indicates that 524,272 bytes are available for macro storage.
This is not actually true, SyncTERM will use all available memory
for macro storage, but some software checks this value, and some
parsers don’t allow more than INT16_MAX parameter values.
When Ps is 63 (DECCKSR) Pn defaults to 1, and CTerm will respond
with a checksum of the defined macros in the form
DCS Pn ! xxxx ST
Where xxxx is the hex checksum.
SOURCE: [VT420]
CSI Ps $ p Request Mode — ANSI (DECRQM)
Requests the current state of ANSI mode Ps. The terminal responds
with CSI Ps ; Pm $ y (DECRPM).
The following ANSI modes can be queried:
1 |
GATM — permanently reset (Pm=4) |
2 |
KAM — permanently reset (Pm=4) |
3 |
CRM — permanently reset (Pm=4) |
4 |
IRM — insert (Pm=1) or replace (Pm=2) |
5 |
SRTM — permanently reset (Pm=4) |
6 |
ERM — permanently reset (Pm=4) |
7 |
VEM — permanently reset (Pm=4) |
8 |
BDSM — permanently reset (Pm=4) |
9 |
DCSM — permanently reset (Pm=4) |
10 |
HEM — permanently reset (Pm=4) |
11 |
PUM — permanently reset (Pm=4) |
12 |
SRM — permanently reset (Pm=4) |
13 |
FEAM — permanently reset (Pm=4) |
14 |
FETM — changeable (Pm=1 when set, Pm=2 when reset) |
15 |
MATM — permanently reset (Pm=4) |
16 |
TTM — changeable (Pm=1 when set, Pm=2 when reset) |
17 |
SATM — permanently reset (Pm=4) |
18 |
TSM — permanently reset (Pm=4) |
21 |
GRCM — permanently set (Pm=3) |
22 |
ZDM — permanently set (Pm=3) |
All ECMA-48 standard modes are reported. Modes 14 and 16 are changeable; modes 21 and 22 are permanently set; all others are permanently reset. Any unrecognized mode returns Pm=0.
CSI = Ps $ p Request Mode — CTerm Extension
NON-STANDARD EXTENSION
Requests the current state of CTerm private mode Ps. The terminal
responds with CSI = Ps ; Pm $ y using the same Pm values as
DECRQM above.
The following CTerm modes can be queried:
1 |
Physical key reports |
2 |
Translated key input suppression |
4 |
Last Column Flag mode (CTELCF) |
5 |
Forced Last Column Flag (CTFLCF) — reports 3 (permanently set) when forced |
255 |
DoorWay mode |
CSI ? Ps $ p Request Mode — Private (DECRQM)
Requests the current state of private mode Ps. The terminal responds
with a mode report of the form CSI ? Ps ; Pm $ y (DECRPM) where Pm
indicates the mode state:
0 |
Mode not recognized |
1 |
Set |
2 |
Reset |
3 |
Permanently set |
4 |
Permanently reset |
The following private modes can be queried:
6 |
Origin mode (DECOM) |
7 |
Auto-wrap mode (DECAWM) |
9 |
X10 mouse reporting |
25 |
Cursor visible (DECTCEM) |
31 |
Alternate character set |
32 |
No bright foreground |
33 |
Bright background |
34 |
Blink = alternate character set |
35 |
No blink |
67 |
Backarrow key mode (DECBKM) |
69 |
Left/right margin mode (DECLRMM) |
80 |
Sixel scrolling |
1000–1007, 1015 |
Mouse tracking modes |
2004 |
Bracketed paste mode |
2026 |
Synchronized output (bitmap backends only) |
Any unrecognized mode returns Pm = 0.
SOURCE: [VT320]
CSI Ps SP q Set Cursor Style (DECSCUSR)
Defaults: Ps = 1
Sets the cursor shape and blink. Hiding the cursor with DECTCEM retains this
style. A style selected while hidden takes effect when the cursor is shown.
| Ps | Result |
|---|---|
0 |
Blinking block |
1 |
Blinking block |
2 |
Steady block |
3 |
Blinking underline |
4 |
Steady underline |
SOURCE: [VT520]
CSI Pn1 ; Pn2 r Set Top and Bottom Margins (DECSTBM)
Defaults: Pn1 = 1 Pn2 = last line on screen
Selects top and bottom margins, defining the scrolling region. Pn1 is
the line number of the first line in the scrolling region. Pn2 is the
line number of the bottom line.
SOURCE: [VT100]
CSI Pt ; Pl ; Pb ; Pr ; Ps … Ps $ r Change Attributes in Rectangular Area (DECCARA)
Defaults: Pt = 1 Pl = 1 Pb = last line Pr = last column
Sets SGR attributes in a rectangular screen area without changing
characters. Pt, Pl, Pb, Pr define the rectangle. The
remaining Ps parameters are SGR attribute values (same as CSI m),
including extended colour sequences (38;5;N, 38;2;R;G;B, 48;5;N,
48;2;R;G;B).
If DECSACE is set to 1 (stream mode), the operation applies as a
character stream from (Pt,Pl) to (Pb,Pr) wrapping at line
boundaries. In stream mode, Pl > Pr is permitted when Pt <
Pb.
Coordinates are affected by DECOM (origin mode). Does not change cursor position.
SOURCE: [VT420]
CSI Ps1 ; Ps2 * r Select Communication Speed (DECSCS)
Set the output emulation speed.
If Ps1 or Ps2 are omitted, causes output speed emulation to stop
Ps1 may be empty.
Sequence is ignored if Ps1 is not empty, 0, or 1.
The value of Ps2 sets the output speed emulation as follows:
| Value | Speed |
|---|---|
empty, 0 |
Unlimited |
1 |
300 |
2 |
600 |
3 |
1200 |
4 |
2400 |
5 |
4800 |
6 |
9600 |
7 |
19200 |
8 |
38400 |
9 |
57600 |
10 |
76800 |
11 |
115200 |
SOURCE: [VT420]
CSI Pn1 ; Pn2 s Set Left and Right Margins (DECSLRM)
(Only when DEC Left Right Margin Mode - 69 - is enabled)
Defaults: Pn1 = 1 Pn2 = last column on screen
If either Pn1 or Pn2 is zero, the current setting is retained.
Selects left and right margins, defining the scrolling region. Pn1 is
the column number of the first column in the scrolling region. Pn2 is
the column number of the right column.
SOURCE: [XTerm]
CSI s Save Current Position (SCOSC)
(Only when DEC Left Right Margin Mode - 69 - is disabled)
NON-STANDARD EXTENSION
Saves the current cursor position for later restoring with CSI u
although this is non-standard, it’s so widely used in the BBS world
that any terminal program MUST implement it.
SOURCE: [ANSISYS]
CSI ? Ps… s Save Mode Setting (CTSMS)
NON-STANDARD EXTENSION
Saves the current mode states as specified by CSI ? l and CSI ? h. If
Ps1 is omitted, saves all such states. If one or more values of Ps is
included, saves only the specified states (arguments to CSI ? l/h).
Saving modes preserves the cursor position.
CSI 8 ; rows ; columns t Resize the text area (XTWINOPS)
Changes the active ANSI text grid during a connection. For example,
CSI 8 ; 30 ; 53 t requests 30 usable rows and 53 columns. A reserved status
line occupies an additional row. The current font and cell size carry over.
Text and graphics in the overlapping area are retained, and newly exposed
cells are blank. Shrinking clips the right and bottom edges of the live page.
An omitted dimension retains its current value. Zero uses the available
extent of the emulated display on that axis, which the text area already fills
after accounting for reserved rows. Each explicit dimension can be 1 through
255, subject to the display backend’s size limits. A refused request leaves
the current grid in place. Graphics protocols and embedded graphics text
windows manage their own grids. The resize itself sends no terminal reply.
Use CSI 18 t to read back the active text size.
SOURCE: [XTerm]
CSI Ps t Report window geometry (XTWINOPS)
The single-parameter form reports dimensions of SyncTERM’s virtual screen. Each reply gives height before width.
| Ps | Measurement | Reply |
|---|---|---|
14 |
Full virtual screen raster in pixels |
|
15 |
Full virtual screen raster in pixels |
|
16 |
One character cell in pixels |
|
18 |
Active text area in character cells |
|
19 |
Active text area in character cells |
|
The full raster includes any pixels beyond the cell grid. For example, an 80×43 EGA screen reports 640×350 pixels for both 14 and 15. Reserving a status row reduces the text height reported by both 18 and 19. Scrolling margins leave these sizes unchanged. Pixel queries receive a reply when their dimensions are available.
SOURCE: [XTerm]
CSI Ps ; Pn1 ; Pn2 ; Pn3 t Select a 24-bit colour (CT24BC)
NON-STANDARD EXTENSION
If Ps is 0, sets the background colour.
If Ps is 1, sets the foreground colour.
Pn1, Pn2, Pn3 contains the RGB value to set.
CTerm handles this with an internal temporary palette, so scrollback
may not have the correct colours. The internal palette is large
enough for all cells in a 132x60 screen to have unique foreground
and background colours though, so the current screen should always
be as expected.
CSI Pt ; Pl ; Pb ; Pr ; Ps … Ps $ t Reverse Attributes in Rectangular Area (DECRARA)
Defaults: Pt = 1 Pl = 1 Pb = last line Pr = last column
Toggles (reverses) SGR attributes in a rectangular screen area without
changing characters. Pt, Pl, Pb, Pr define the rectangle.
The remaining Ps parameters specify which attributes to toggle:
| Ps | Action |
|---|---|
0 |
Invert all toggleable attributes (bold, underline, blink, negative, conceal, strikethrough, overline) |
1 or 22 |
Toggle bold (XOR legacy attribute bit 3) |
4, 21 or 24 |
Toggle underline. When enabling it, 21 selects double and 4 or 24 selects single. |
5 or 25 |
Toggle blink (XOR legacy attribute bit 7) |
7 or 27 |
Toggle negative (swap foreground and background) |
8 or 28 |
Toggle conceal |
9 or 29 |
Toggle strikethrough |
53 or 55 |
Toggle overline |
All other Ps values are silently ignored.
If DECSACE is set to 1 (stream mode), the operation applies as a character stream wrapping at line boundaries.
Coordinates are affected by DECOM (origin mode). Does not change cursor position.
SOURCE: [VT420]
CSI u Restore Cursor Position (SCORC)
Move the cursor to the last position saved by CSI s. If no position
has been saved, the cursor is not moved.
SOURCE: [ANSISYS]
CSI ? Ps… u Restore Mode Setting (CTRMS)
NON-STANDARD EXTENSION
Restores the mode states as saved via CSI ? s. If Ps is omitted,
restores all such states. If one or more values of Ps is included,
restores all the specified states (arguments to CSI ? l/h).
Restoring a different origin mode moves the cursor to the new origin.
Restoring the current origin mode or one that has never been saved preserves
the position.
CSI Pts ; Pls ; Pbs ; Prs ; Pps ; Ptd ; Pld ; Ppd $ v Copy Rectangular Area (DECCRA)
Copies a rectangular area of characters from one location to another. The copied text retains its character values, attributes, and hyperlinks.
Pts, Pls, Pbs, Prs define the source rectangle (top, left,
bottom, right). Pps is the source page (ignored — single page).
Ptd, Pld define the destination top-left corner. Ppd is the
destination page (ignored).
Defaults: Pts = 1, Pls = 1, Pbs = last line, Prs = last column,
Ptd = 1, Pld = 1.
If Pbs < Pts or Prs < Pls, DECCRA is ignored.
Coordinates are affected by origin mode (DECOM) but not by margins.
Values exceeding page dimensions are clamped. The cursor does not move.
If the destination area extends past the screen, the off-screen portion
is clipped.
SOURCE: [VT420]
CSI 2 $ w Request Tab Stop Report (DECTABSR)
Requests a list of tab stops.
The list is in the form:
DCS 2 $ u Pt ST
The string Pt is a list of tab stops separated by `/`s.
SOURCE: [VT320]
CSI Pch ; Pt ; Pl ; Pb ; Pr $ x Fill Rectangular Area (DECFRA)
Fills a rectangular area with the character specified by Pch.
The fill character uses the visual attributes set by the most recent
SGR command. Hyperlinks are cleared on filled cells.
Pch is the decimal value of the fill character. Any value from
0x20 to 0x7E or 0x80 to 0xFF is accepted. If Pch is in the C0
range (0x00–0x1F) or is DEL (0x7F), the command is ignored.
Pt, Pl, Pb, Pr define the rectangle (top, left, bottom, right).
Defaults: Pt = 1, Pl = 1, Pb = last line, Pr = last column.
If Pb < Pt or Pr < Pl, DECFRA is ignored.
Coordinates are affected by origin mode (DECOM) but not by margins.
Values exceeding page dimensions are clamped. The cursor does not move.
SOURCE: [VT420]
CSI Ps * x Select Attribute Change Extent (DECSACE)
Controls whether DECCARA and DECRARA operate on a rectangular area or a character stream.
| Ps | Mode |
|---|---|
0 |
Rectangular (default) |
1 |
Stream (linear character sequence wrapping at line boundaries) |
2 |
Rectangular |
Reset to 0 by RIS.
SOURCE: [VT420]
CSI Pn1 ; Ps ; Pn2 ; Pn3 ; Pn4 ; Pn5 * y Request Checksum of Rectangular Area (DECRQCRA)
Returns a checksum for the specified rectangular area.
Pn1 is an ID that is returned in the response.
Ps MUST be 1
Pn2 specifies the top row of the rectangle
Pn3 specifies the left column of the rectangle
Pn4 specifies the bottom row of the rectangle
Pn5 specifies the right column of the rectangle
The return value is in the format of DCS Pn1 ! ~ xxxx ST
Where xxxx is the hex value of the checksum.
Source: [VT420]
CSI Pt ; Pl ; Pb ; Pr $ z Erase Rectangular Area (DECERA)
Erases all character positions in the specified rectangular area. Erased positions are set to SPACE with the visual attributes from the most recent SGR command. Hyperlinks are cleared on erased cells.
Pt, Pl, Pb, Pr define the rectangle (top, left, bottom, right).
Defaults: Pt = 1, Pl = 1, Pb = last line, Pr = last column.
If Pb < Pt or Pr < Pl, DECERA is ignored.
Coordinates are affected by origin mode (DECOM) but not by margins.
Values exceeding page dimensions are clamped. The cursor does not move.
SOURCE: [VT420]
CSI Pn * z Invoke Macro (DECINVM)
Invokes a macro.
Pn specifies the macro number. If Pn is not 0..63, no action is
taken.
SOURCE: [VT420]
CSI = Ps1 ; Ps2 { (CTOSF)
NON-STANDARD EXTENSION (Deprecated)
Defaults: Ps1 = 255 Ps2 = 0
Indicates that a font block is following.
Ps1 indicates the font slot to place the loaded font into. This must
be higher than the last default defined font (See CSI sp D for list
of predefined fonts) Ps2 indicates font size according to the
following table:
0 |
8x16 font, 4096 bytes. |
1 |
8x14 font, 3584 bytes. |
2 |
8x8 font, 2048 bytes. |
The DCS font string should be used instead as of CTerm 1.213
CSI Ps $ } Select Active Status Display (DECSASD)
Defaults: Ps = 0
Selects which display subsequent output is directed to. Ps = 0
sends output to the main display (default); Ps = 1 sends it to
the one-row status line. Ps = 1 is silently ignored unless the
status display type is currently host-writable (DECSSDT Ps = 2).
When the status line is the active display, writes land in a
single-row sub-terminal with its own cursor, SGR attributes, and
saved-cursor slot. Line-feed, wrap-to-next-line, and scroll do
not leave the status row. Selecting Ps = 0 restores the main
display’s cursor and resumes normal output there.
Switching back to Ps = 0 is also forced implicitly whenever
DECSSDT changes to a different type while the status display was
active.
SOURCE: [VT320]
CSI Ps $ ~ Select Status Display Type (DECSSDT)
Defaults: Ps = 1
Selects the status display type. Ps = 0 hides the status row and
extends the main display by one line. Ps = 1 shows SyncTERM’s
native indicator (clock, connection state, help hints) — this is
the default and matches the pre-existing user preference (overridable
from the BBS list or the -n CLI flag). Ps = 2 gives the row to
the host: SyncTERM’s indicator is cleared and the row becomes
writable via DECSASD.
The main display is resized in place across toggles; cursor
position and existing screen content are preserved. Values of
Ps outside 0..2 are silently ignored.
SOURCE: [VT320]
CSI Pn ' } Insert Column (DECIC)
Defaults: Pn = 1
Inserts Pn blank columns into the scrolling region, starting at
the column that has the cursor. Columns between the cursor and the
right margin shift to the right. Columns shifted past the right
margin are lost. The inserted columns are filled with SPACE using
the current SGR attributes. Hyperlinks are cleared on inserted cells.
DECIC has no effect if the cursor is outside the scrolling margins. The cursor does not move.
SOURCE: [VT420]
CSI Pn ' ~ Delete Column (DECDC)
Defaults: Pn = 1
Deletes Pn columns from the scrolling region, starting at the column
that has the cursor. The remaining columns between the cursor and the
right margin shift to the left. Blank columns are added at the right
margin, filled with SPACE using the current SGR attributes. Hyperlinks
are cleared on the new blank cells.
DECDC has no effect if the cursor is outside the scrolling margins. The cursor does not move.
SOURCE: [VT420]
Device Control Strings
A Device Control String Begins with a DCS and ends with a ST
The following commands are supported:
DCS CTerm:Font:p1:<b64> ST CTerm Loadable Font (CTLF)
Indicates the string is a loadable font. (CTerm 1.213)
p1 is a font slot number, which must be higher than the last
default defined font (See CSI sp D for list of predefined
fonts). <b64> is the base64 encoded font data. Font size is
deduced from the size of the data. This replaces the now
deprecated CSI = Ps1 ; Ps2 {
DCS [ p1 [ ; p2 ] ] q ST Sixel Sequence
Defaults: p1 = 0 p2 = 0
Indicates the string is a sixel sequence.
p1 selects the vertical height of a single pixel. This
may be overridden by the raster attributes command, and
is deprecated. Supported values
| Value | Vertical Size |
|---|---|
0,1,5,6 |
2 pixels |
2 |
5 pixels |
3,4 |
3 pixels |
7,8,9 |
1 pixel |
p2 indicates if unset sixels should be set to the current
background colour. If p2 is 1, positions specified as 0
remain at their current colour.
Any additional parameters are ignored.
The rest of the string is made up of sixel data characters and
sixel control functions. Sixel data characters are in the
range of ? (0x3f) to ~ (0x7e). Each sixel data character
represents six vertical pixels. The data is extracted by
subtracting 0x3f from the ASCII value of the character.
The least significant bit is the topmost pixel.
| Function | Parameters | Name | Description |
|---|---|---|---|
|
|
Graphics Repeat Introducer |
The character X is repeated Pn times. |
|
|
Raster Attributes |
p1 indicates the vertical size in pixels of each sixel. |
|
|
Colour Select |
Selects sixel register p1 as the current foreground colour. Register 0 corresponds to OSC 4 index 290, register 1 to index 291, and so on. |
|
|
Palette map |
Defines sixel palette entry p1 and sets it as the
current foreground colour. |
|
Graphics Carriage Return |
Returns the active position to the left border of the same sixel row. Generally, one pass per colour is used. In passes after the first one, sixels with a value of zero are not overwritten with the background colour. |
|
|
Graphics New Line |
Moves the active position to the left border of the next sixel row. |
SOURCE: [VT330/340]
SyncTERM caps repeat counts at 32767 and clamps raster pixel sizes to at least one and at most the corresponding screen dimension (also limiting a six-pixel row to the signed coordinate range). Long decimal parameters saturate before conversion; they never wrap to a smaller value. Background storage is bounded by the visible screen, regardless of the declared block dimensions. Colour selectors outside the available 16-bit palette range are ignored, including any associated palette definition. Cancelling a partial image, resetting the terminal, or replacing its command string releases the image storage and restores the cursor and update state. A successful terminal geometry change also discards an unfinished image; completed rows remain on screen.
DCS $ q pt ST Request Status String (DECRQSS)
pt is the intermediate and/or final characters of a control
function to query the status of. The terminal will send a
response in the format
DCS p1 $ r pt ST
p1 is 1 if the terminal supports querying the control
function and 0 if it does not.
pt is the characters in the control function except the CSI
characters. If p1 is zero, pt is zero-length.
pt |
Description |
|---|---|
m |
Request SGR parameters |
r |
Request top and bottom margins |
s |
Request left and right margins |
t |
Request height in lines |
$| |
Request width in columns |
*| |
Request height in lines |
` q` (space + q) |
Request cursor style ( |
|
Request communication speed ( |
|
Request attribute change extent ( |
|
Request status display type ( |
|
Request active status display ( |
SOURCE: [VT420]
DCS p1 [ ; p2 [ ; p3 ] ! z ST Define Macro (DECDMAC)
Defaults: p2 = 0 p3 = 0
Sets a macro to be replayed using CSI Pn * z
p1 is the macro number to set, and must be between 0 and
63 inclusive.
If p2 is zero, the macro numbered p1 will be deleted before the new
macro is set. If p2 is one, all macros are deleted before the new
macro is set. If the macro is zero length, only the delete action is
stored, you can’t store a zero-length macro.
If p3 is zero, the macro is defined using ASCII characters
(0x20 - 0x7e and 0xa0 - 0xff only). Note that since ESC (0x1b)
is not in this range, ASCII-mode macros cannot contain escape
sequences; use hex-mode (p3 = 1) instead.
If p3 is one, the macro is defined using hex pairs.
When the macro is defined using hex pairs, a repeat
sequence may be included in the format of ! Pn ; D..D ;
Pn specifies the number of repeats (default of one instance)+
D..D is the sequence of pairs to send Pn times. The
terminating ; may be left out if the sequence to be
repeated ends at the end of the string.
SOURCE: [VT420]
Operating System Commands
An Operating System Command Begins with an OSC and ends with a ST
The following commands are supported:
OSC 4;(pX;pY)… ST Palette Redefinition/Query (OSC 4)
Specifies one or more palette redefinitions or queries.
pX is the palette index, and pY is the colour definition
Color format: rgb:R/G/B::
Where R, G, and B are a sequence of one to four
hex digits representing the value of the
red, green, and blue channels respectively.
If pY is ?, CTerm responds with the current colour for palette
index pX in the form OSC 4;pX;rgb:RR/GG/BB ST where
RR, GG, and BB are two hex digit colour values reflecting
the 8-bit-per-channel storage precision.
Entries 282–289 hold the faint versions of black, red, green, yellow, blue, magenta, cyan, and white. Each defaults to half of each RGB channel of the corresponding normal profile colour, rounded down. This includes the profile’s brown or yellow choice. Each faint entry can then be redefined independently with OSC 4.
SOURCE: [XTerm]
OSC 104 [ ; Ps … ] ST Reset Palette Entry (OSC 104)
Resets palette entry to default. If the entire string
is "104" (ie: no Ps present), resets entries 0–289. Otherwise,
only the specified entries in that range are reset. Sixel registers retain
their definitions.
SOURCE: [XTerm]
OSC 10 ; ? ST Query Default Foreground Color (OSC 10)
Queries the default foreground color.
CTerm responds with OSC 10;rgb:RR/GG/BB ST where RR, GG, and BB
are two hex digit color values.
SOURCE: [XTerm]
OSC 11 ; ? ST Query Default Background Color (OSC 11)
Queries the default background color.
CTerm responds with OSC 11;rgb:RR/GG/BB ST where RR, GG, and BB
are two hex digit color values.
SOURCE: [XTerm]
OSC 8 ; params ; uri ST Hyperlink (OSC 8)
Sets a hyperlink on subsequent text output. Text printed after this sequence will be associated with the given URI. An empty URI ends the hyperlink region.
The params field is a colon-separated list of key=value pairs.
The id= parameter allows non-contiguous text runs to share the same
hyperlink.
Only http, https, ftp, and ftps URIs are supported. Other
schemes are silently ignored.
Users can open hyperlinks by clicking when BBS mouse capture is off, or by Ctrl+clicking when mouse capture is active.
ESC ] 8 ; ; https://example.com ST Click here ESC ] 8 ; ; ST ESC ] 8 ; id=link1 ; https://example.com ST part1 ESC ] 8 ; ; ST ... ESC ] 8 ; id=link1 ; https://example.com ST part2 ESC ] 8 ; ; ST
Application Program Commands
An Application Program Command begins with an APC and ends with a ST
SyncTERM implements the following APC commands:
The cache is scoped to the current BBS. Graphics buffers, the buffered mask, audio patches, and dedicated audio channels belong to the current terminal: they survive terminal resets but are released when that terminal is destroyed. Cache operations reject paths outside that cache and do not follow links; only regular files are opened for reading, writing, or checksumming.
APC SyncTERM:VER ST Get SyncTERM Version (CTSV)
SyncTERM responds with
an APC string of the form APC SyncTERM:VER;version ST where
version is the version string of SyncTERM, with UTF-8 α translated to a
and β to b. All other bytes outside 0x08–0x0D and 0x20–0x7E are
removed. For example, SyncTERM 2.0α Debug (Nov 7 2026) is reported as
SyncTERM 2.0a Debug (Nov 7 2026). This filtering applies only to the reply;
the application’s displayed version is unchanged. Atari ST VT52 supports
the same version query and reply, both introduced by ESC ;.
APC SyncTERM:C;S;Ps1;Ps2 ST Store file (CTSFI)
Where Ps1 is a filename and Ps2 is the base64 encoded
contents of the file. The named file is stored in the
cache directory for the current connection.
APC SyncTERM:C;L [ ; Ps] ST List Files (CTLFI)
Defaults: Ps = *
Ps is the glob(3) pattern to use matching files.
SyncTERM responds with
an APC string with lines separated by newlines. The
first line is always SyncTERM:C;L\n and for each
matching file, a line in the form
<Filename> TAB <MD5 sum> LF is sent
(ie: "coolfont.fnt\t595f44fec1e92a71d3e9e77456ba80d1\n")
APC SyncTERM:C;SetFont; Pn ; Ps ST Set Font (CTSF)
Pn must be a font slot number from 46 through 255; Ps is a filename
in the cache. As in v1.10a, this replaces the active font-download slot,
which may differ from the validated Pn argument.
Files must contain exactly 2048, 3584, 4096, or 10240
bytes (8x8, 8x14, 8x16, or 12x20 respectively); variants are retained and the
one matching the current cell dimensions is selected.
APC SyncTERM:C;DrawPPM Ps… Ps1 ST Draw a PPM from Cache (CTDPFC)
Draws a PPM from the cache directory on the screen.
Ps1 is the filename and is required. Arguments for
Ps are optional. The following options can be included
(separated by semi-colons):
| Argument | Description |
|---|---|
|
Sets the left X position in the specified image to copy from. Default = 0. |
|
Sets the top Y position in the specified image to copy from. Default = 0. |
|
Sets the width of the portion of the image to copy. Default = Image width - |
|
Sets the height of the portion of the image to copy. Default = Image height - |
|
Sets the X position on the screen to draw the image at. May be negative. Default = 0. |
|
Sets the Y position on the screen to draw the image at. May be negative. Default = 0. |
|
Flips the selected source rectangle horizontally before drawing. |
|
Flips the selected source rectangle vertically before drawing. |
|
Sets the integer X zoom factor. Default = 1. |
|
Sets the integer Y zoom factor. Default = 1. |
|
Sets the X position in the mask to start applying from. Default = 0. |
|
Sets the Y position in the mask to start applying from. Default = 0. |
|
Sets the overall width of the mask (not the width to apply). If |
|
Sets the overall height of the mask (not the height to apply). If MFILE is not specified, and a mask is (ie: using MASK=), this is required. If MFILE is specified, the width is read from the file. |
|
Specifies a filename in the cache directory of a PBM file specifying a mask of which pixels to copy. Any pixel set to black (ie: 1) in the PBM will be drawn from the source image. Pixels set to white (ie: 0) will be left untouched. |
|
Specifies a base64-encoded tightly-packed row-major bitmap. The first bit is the leftmost pixel of the top row; bits continue across row boundaries with no per-row byte padding. Each set bit will be drawn from the source image, cleared bits will not be drawn. Requires MW= and MH= to be specified. |
|
Uses the loaded mask buffer. |
The PPM file may be raw (preferred) or text. SyncTERM
does not support more than 255 values per colour channel
and assumes it is correctly using the BT.709 transfer function. Samples are
decoded to linear light and re-encoded as sRGB for display; this corrects the
nonlinear-branch conversion error in v1.10a. The APC decoder retains its
single-byte raw-data separator, including when that byte is CR in CRLF.
ZX and ZY must be non-zero. Zoom and flip are applied
to the source image and mask sampling. If the destination area extends
past the screen, the off-screen portion is clipped.
APC SyncTERM:C;DrawPPMBlob Ps… Ps1 ST Draw a PPM Blob (CTDPB)
Draws a base64-encoded PPM directly on the screen without storing it in
the cache directory.
Ps1 is the base64-encoded PPM data and is required. Ps supports the
same arguments as DrawPPM.
APC SyncTERM:C;DrawJXL Ps… Ps1 ST Draw a JPEG XL from Cache (CTDJFC)
Draws a JPEG XL from the cache directory on the screen.
Ps1 is the filename and is required. Arguments for
Ps are optional. The following options can be included
(separated by semi-colons):
| Argument | Description |
|---|---|
|
Sets the left X position in the specified image to copy from. Default = 0. |
|
Sets the top Y position in the specified image to copy from. Default = 0. |
|
Sets the width of the portion of the image to copy. Default = Image width - |
|
Sets the height of the portion of the image to copy. Default = Image height - |
|
Sets the X position on the screen to draw the image at. May be negative. Default = 0. |
|
Sets the Y position on the screen to draw the image at. May be negative. Default = 0. |
|
Flips the selected source rectangle horizontally before drawing. |
|
Flips the selected source rectangle vertically before drawing. |
|
Sets the integer X zoom factor. Default = 1. |
|
Sets the integer Y zoom factor. Default = 1. |
|
Sets the X position in the mask to start applying from. Default = 0. |
|
Sets the Y position in the mask to start applying from. Default = 0. |
|
Sets the overall width of the mask (not the width to apply). If |
|
Sets the overall height of the mask (not the height to apply). If MFILE is not specified, and a mask is (ie: using MASK=), this is required. If MFILE is specified, the width is read from the file. |
|
Specifies a filename in the cache directory of a PBM file specifying a mask of which pixels to copy. Any pixel set to black (ie: 1) in the PBM will be drawn from the source image. Pixels set to white (ie: 0) will be left untouched. |
|
Specifies a base64-encoded tightly-packed row-major bitmap. The first bit is the leftmost pixel of the top row; bits continue across row boundaries with no per-row byte padding. Each set bit will be drawn from the source image, cleared bits will not be drawn. Requires MW= and MH= to be specified. |
|
Uses the loaded mask buffer. |
ZX and ZY must be non-zero. Zoom and flip are applied to the
source image and mask sampling. If the destination area extends past
the screen, the off-screen portion is clipped.
APC SyncTERM:C;DrawJXLBlob Ps… Ps1 ST Draw a JPEG XL Blob (CTDJB)
Draws a base64-encoded JPEG XL directly on the screen without storing it
in the cache directory.
Ps1 is the base64-encoded JPEG XL data and is required. Ps supports
the same arguments as DrawJXL. JXL support remains runtime-dependent;
use APC SyncTERM:Q;JXL ST before selecting this verb.
APC SyncTERM:C;LoadPPM Ps… Ps0 ST Load a PPM to Buffer (CTLPTB)
Loads a PPM to a buffer. Ps0 is the filename
Argument |
Description |
|
Selects the buffer (0 or 1 only) to paste from. |
APC SyncTERM:C;LoadPPMBlob Ps… Ps0 ST Load a PPM Blob to Buffer (CTLPBB)
Loads a base64-encoded PPM directly to a buffer without storing it in the
cache directory. Ps0 is the base64-encoded PPM data. Ps supports
the same arguments as LoadPPM.
APC SyncTERM:C;LoadJXL Ps… Ps0 ST Load a JPEG XL to Buffer (CTLJTB)
Loads a JPEG XL to a buffer. Ps0 is the filename
Argument |
Description |
|
Selects the buffer (0 or 1 only) to paste from. |
APC SyncTERM:C;LoadJXLBlob Ps… Ps0 ST Load a JPEG XL Blob to Buffer (CTLJBB)
Loads a base64-encoded JPEG XL directly to a buffer without storing it in
the cache directory. Ps0 is the base64-encoded JPEG XL data. Ps
supports the same arguments as LoadJXL. JXL support remains
runtime-dependent; use APC SyncTERM:Q;JXL ST before selecting this verb.
APC SyncTERM:C;LoadPBM Ps… Ps0 ST Load a PBM to Buffer (CTLPBTB)
Loads a PBM to a buffer. Ps0 is the filename
APC SyncTERM:C;LoadPBMBlob Ps0 ST Load a PBM Blob to Buffer (CTLPBBB)
Loads a base64-encoded PBM directly to the mask buffer without storing it
in the cache directory. Ps0 is the base64-encoded PBM data.
APC SyncTERM:P;Copy Ps… ST Copy Screen into Buffer (CTCSIB)
Copies a portion of the screen into an internal pixel buffer for use with the Paste function. Defaults to copying the entire screen. All coordinates and dimensions are in pixels.
Argument |
Description |
|
Selects the buffer (0 or 1 only) to copy to. |
|
Sets the left X position on the screen to start copying at. Default = 0. |
|
Sets the top Y position on the screen to start copying at. Default = 0. |
|
Sets the width to copy. Default = Screen width - X. |
|
Sets the height to copy. Default = Screen height - X. |
APC SyncTERM:P;Paste Ps… ST Paste Buffer to Screen (CTPBTS)
Pastes from the copied pixel buffer. Supports the same options as the Cache DrawPPM command except for the filename, and adds the B= option. All coordinates and dimensions are in pixels.
Argument |
Description |
|
Sets the left X position in the specified image to copy from. Default = 0. |
|
Sets the top Y position in the specified image to copy from. Default = 0. |
|
Sets the width of the portion of the image to copy. Default = Image width - |
|
Sets the height of the portion of the image to copy. Default = Image height - |
|
Sets the X position on the screen to draw the image at. May be negative. Default = 0. |
|
Sets the Y position on the screen to draw the image at. May be negative. Default = 0. |
|
Flips the selected source rectangle horizontally before drawing. |
|
Flips the selected source rectangle vertically before drawing. |
|
Sets the integer X zoom factor. Default = 1. |
|
Sets the integer Y zoom factor. Default = 1. |
|
Sets the X position in the mask to start applying from. Default = 0. |
|
Sets the Y position in the mask to start applying from. Default = 0. |
|
Sets the overall width of the mask (not the width to apply). If |
|
Sets the overall height of the mask (not the height to apply). If MFILE is not specified, and a mask is (ie: using MASK=), this is required. If MFILE is specified, the width is read from the file. |
|
Specifies a filename in the cache directory of a PBM file specifying a mask of which pixels to copy. Any pixel set to black (ie: 1) in the PBM will be drawn from the source image. Pixels set to white (ie: 0) will be left untouched. |
|
Specifies a base64-encoded tightly-packed row-major bitmap. The first bit is the leftmost pixel of the top row; bits continue across row boundaries with no per-row byte padding. Each set bit will be drawn from the source image, cleared bits will not be drawn. Requires MW= and MH= to be specified. |
|
Uses the loaded mask buffer. |
|
Selects the buffer (0 or 1 only) to paste from. |
ZX and ZY must be non-zero. Zoom and flip are applied to the
source image and mask sampling. If the destination area extends past
the screen, the off-screen portion is clipped.
APC SyncTERM:ScreenMode;Type[;WidthPx;HeightPx;FontHeightPx;Aspect;AspectW;AspectH] ST
Select the screen mode and text emulation for this connection. Send the
request with the current emulation’s APC introducer: ESC _ in ANSI-BBS
(including Amiga), or ESC ; in Atari ST VT52. Both use ESC \ for ST.
The reply is APC SyncTERM:ScreenMode;Result;activeEngine;ok ST, always in
the request’s framing. Engine IDs are listed below. Success (ok=1)
means the destination is active. On refusal (ok=0), the original mode,
page, and engine remain active. The result precedes processing of any bytes
after ST. A BBS can wait for this reply before changing its output encoding.
| Type | Destination |
|---|---|
0 |
ECMA-48 IBM palette, normal eight-pixel cells |
1 |
ECMA-48 IBM palette, VGA nine-pixel cells with line-graphics extension |
10, 11 |
ECMA-48 Amiga 640×200 and 640×400 respectively |
20, 21, 22 |
Atari ST VT52 320×200 (40×25), 640×200 (80×25), and 640×400 monochrome (80×25) |
30, 31, 32 |
PETSCII C64, C128 40-column, and C128 80-column, all in the lower/upper bank |
40 |
Atari 8-bit ATASCII, 40×24 |
50, 51 |
BBC Micro Mode 7 and Prestel respectively, 40×25 with 12×20 cells |
Only types 0 and 1 read the optional fields. Each empty or omitted field retains its live value. Width and height describe the full pixel raster, including any local status row. Whole cells fill it from the upper left. Spare pixels on the right and bottom remain part of the graphics canvas. The grid must fit 1–255 columns and rows, font height 1–64, and the backend must support the requested display. Allow an extra row for a reserved status line. Fixed types install their preset and ignore all fields after the type.
Aspect 0 selects a 4:3 display, 1 selects square pixels, and 2 selects a
custom display width:height ratio. When first selecting 2, supply both
positive ratio components. For example, ScreenMode;1;720;400;16;0 selects
classic VGA 80×25, and ScreenMode;0;;;;1 selects normal IBM cells and
square pixels while retaining the raster and font height.
An effective change retires the page to scrollback, resets the terminal and restarts a compatible active engine. An incompatible engine is disabled and the result reports engine 0. Repeating an identical request preserves the page. A malformed setter or unknown type returns a refusal. Result messages may be echoed without triggering another reply.
Atari ST, PETSCII, ATASCII and teletext select native bytes for input and
output. Returning to ECMA-48 restores the connection’s ANSI encoding
(CP437 when the connection started in a native emulation). For example,
an ANSI BBS can send ESC _ SyncTERM:ScreenMode;21 ESC \, receive the
ANSI-framed result, then return with ESC ; SyncTERM:ScreenMode;0 ESC \
and receive a VT52-framed result. Spaces in these examples only separate
the fields for readability. PETSCII, ATASCII, BBC and Prestel receive
the entry acknowledgment in the source framing and have no return command.
APC SyncTERM:Q;Graphics ST Query compatible graphics engines
In a connected ANSI-BBS or Atari ST VT52 text stream, this query returns
APC SyncTERM:Graphics;active;id;… ST. The first number identifies the
active engine (0 for plain text). Each following number identifies an engine
selectable through this text emulation on the current display, in ascending order. A BBS can query
again after changing the text area with XTWINOPS or changing the native
graphics resolution. Pixel aspect ratio does not affect the result.
For both graphics commands and their replies, use ESC _ (hex 1B 5F) in
ANSI-BBS text and ESC ; (hex 1B 3B) in Atari ST VT52 text. The terminator
is ESC \ (hex 1B 5C) in both. A DDO F/X full-graphics text window uses
ANSI framing, including its reply when disabling DDO F/X.
| ID | Engine | Compatible display |
|---|---|---|
1 |
RIP 1.54 |
ANSI bitmap display with room for the 640×350 RIP canvas |
2 |
RIP 3 |
ANSI bitmap display |
3 |
SkyPix, Kickstart 1.3 |
ANSI bitmap display with room for the selected canvas |
4 |
SkyPix, Kickstart 3.1 |
Same canvas requirements as ID 3 |
5 |
IGS 2.21 |
Atari ST VT52 in 320×200 or 640×200 with 8×8 cells, or 640×400 with 8×16 cells |
6 |
BIG 1.03 |
ANSI bitmap display in native 640×200 (80×25), 640×350 (80×25), or 640×480 (80×30) geometry |
7 |
DDO F/X 2.0 |
Lite text commands are available on text and bitmap displays. Full graphics requires a bitmap display. |
APC SyncTERM:G;id;enabled ST Enable or disable a graphics engine
Send an engine ID from the table and a single digit, 1 to enable or 0 to
disable. The reply is APC SyncTERM:Graphics;Result;active;ok ST, with
the resulting active engine and 1 for success or 0 for rejection. In VT52 text,
only ID 5 (IGS) can be switched. Requests for other engine IDs in the table
return a rejection for either operation, even if the BBS entry selected that
engine. For permitted IDs, requesting
the state an engine already has succeeds. Disable the active engine before
enabling another. An incompatible engine, a transfer holding the connection,
or a failed initialization can prevent a change. Malformed requests are ignored.
For example, APC SyncTERM:G;2;1 ST enables RIP 3 on a compatible ANSI
display and returns APC SyncTERM:Graphics;Result;2;1 ST. Send the controls
in ordinary terminal text using the framing for that text emulation.
The change takes effect at ST, including when more bytes follow in the
same packet. To switch from a RIP scene with text disabled, first enable
its text stream.
Each connection starts with the engine in its BBS entry. A switch affects only that connection. RIP, SkyPix, IGS and BIG start a fresh terminal page and retire the outgoing page to scrollback. DDO F/X uses the existing text terminal and restores its Lite display when leaving full graphics.
APC SyncTERM:Q;JXL ST Query JXL Support (CTQJS)
Queries support for the JXL image format.
SyncTERM will respond with a CTerm APC State Report of the form
CSI = 1 ; pR - n
pR is 0 if JXL support is not available, and 1 if it is.
APC SyncTERM:Q; Ps ST Feature presence query (CTQF)
Generic feature-availability probe. Ps is the feature name; currently
defined:
| Feature | Meaning |
|---|---|
|
Whether an enabled MIDI method can initialize for this session. The reply
is |
|
Whether libopenmpt and PCM output are available to play tracker modules in
this session. The reply is |
|
Runtime-loaded libsndfile for audio file decoding ( |
|
Queries whether the loaded libsndfile runtime reports support for the
specific container/subtype pair identified by normalized major format
|
The response is a CSI = Ps n audio state report. The libsndfile
query returns the feature ID (100) and availability (0 / 1) as a pair.
Example responses:
-
libsndfile available:
CSI = 7 ; 100 ; 1 n -
libsndfile unavailable:
CSI = 7 ; 100 ; 0 n
The libsndfileFormat query returns feature ID 101, the queried normalized
major format, the queried subtype, and availability:
-
OGG/Opus supported:
CSI = 7 ; 101 ; 32 ; 100 ; 1 n -
OGG/Opus unsupported:
CSI = 7 ; 101 ; 32 ; 100 ; 0 n
For the libsndfileFormat query, pm and ps are derived from
libsndfile’s combined SF_INFO.format field as follows:
pm = (SF_INFO.format & SF_FORMAT_TYPEMASK) >> 16;
ps = SF_INFO.format & SF_FORMAT_SUBMASK;
SyncTERM’s implementation asserts the libsndfile mask layout it depends on:
SF_FORMAT_TYPEMASK == 0x0fff0000 and
SF_FORMAT_SUBMASK == 0x0000ffff. Unknown numeric values are accepted
by the protocol and passed to libsndfile; the following registry is copied
from libsndfile headers for convenience and may be incomplete or out of
date compared to the library installed on the user’s system.
| Name | pm |
|---|---|
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
22 |
|
23 |
|
24 |
|
25 |
|
32 |
|
33 |
|
34 |
|
35 |
| Name | ps |
|---|---|
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
16 |
|
17 |
|
18 |
|
19 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
48 |
|
49 |
|
50 |
|
64 |
|
65 |
|
66 |
|
67 |
|
80 |
|
81 |
|
96 |
|
100 |
|
112 |
|
113 |
|
114 |
|
115 |
|
128 |
|
129 |
|
130 |
Audio APCs
SyncTERM exposes a BBS-facing audio playback API on top of its internal mixer. The model has two pieces:
Patch slots — 256 per-session buffers of S16 stereo 44100 Hz PCM,
addressed by slot number 0..255. Slots are filled by Load (decoding
a file via libsndfile), Synth (in-terminal tone generator), or Copy
(duplicating an existing slot).
Channels — 16 logical playback channels, addressed 0..15. Channel 0 is
cterm’s music FIFO (ANSI/BananANSI/SyncTERM music, MIDI files and tracker modules), including MIDI
which sounds outside the PCM mixer. Channel 1 is the foreground-SFX stream
(RIP / OOII); the BBS can use
Flush, Volume, Wait, and Update on them but cannot Queue
patch audio onto them. Use QueueMIDI or QueueModule to queue a file on channel 0.
ANSI music selects GM Lead 2 (sawtooth), bank 0/program 81 (zero-based), on MIDI
channel zero. Software MIDI renderers use this sustained synth voice to match
K-weighted level to the existing beep/ANSI tone. Frequency weighting and
DC rejection are used for calibration only; no playback EQ or additional
user gain setting is introduced. MIDI files retain their own instrument
choices. FluidSynth’s ANSI voice is dry; its saved effect controllers are
restored before file playback. A fixed source gain is combined with channel
gain in the mixer’s wide accumulator before final soft clipping. Channel defaults,
volume and fades retain their existing meaning; music is not normalized
per file or during playback. Native MIDI destinations do not use PCM source
calibration.
Channels 2..15 are APC-dedicated and lazy-opened at
-12 dB base level on first use.
A Queue moves a slot’s buffer into a channel’s FIFO, after which the
slot is empty. The mixer plays channels concurrently with sample-accurate
volume, fade-in/out envelopes, loop, and crossfade.
Parameter letters
Keys are single characters (C, S, V, etc.) in a ;-delimited
Key=Value list. Two keys (X and L) are presence flags — their
mere inclusion in the token list sets the flag; they take no value.
| Letter | Meaning | Used by |
|---|---|---|
|
Slot number (0..255) — patch source or dest |
Load, Synth, Queue, Copy |
|
Destination slot (Copy only) |
Copy |
|
Waveform / shape |
Synth |
|
Frequency in Hz |
Synth |
|
Time / duration (ms default, see below) |
Synth |
|
Channel number (0..15) |
Queue, Flush, Volume, Wait, Update |
|
Fade-in duration |
Queue |
|
Fade-out duration |
Queue, Flush |
|
Crossfade (presence flag, no value) |
Queue |
|
Loop (presence flag, no value) |
Queue |
|
Volume, both channels |
Queue, Volume |
|
Volume, left channel |
Queue, Volume |
|
Volume, right channel |
Queue, Volume |
Duration grammar for T, I, O:
-
No suffix → milliseconds (
T=500= 500 ms). -
mssuffix → explicit milliseconds. -
fsuffix → frames, sample-exact (T=22050f= half a second @ 44.1 kHz). -
psuffix → full periods ofF, zero-crossing aligned. Valid only in Synth’sT; rejected for Queue/Flush fade durations (which apply to pre-rendered buffers with no single frequency).
Any parse error (unknown suffix, empty, non-numeric) yields a duration
of 0 — Synth with T=0 just produces an empty slot; Queue with I=0
skips that envelope.
Volume grammar for V, VL, VR:
-
No suffix → linear percentage 0..100 (100 = 0 dB unity, 50 ≈ -6 dB, 0 = silence clamped to -60 dB).
-
dBsuffix (case-insensitive) → explicit dB value, parsed as a float with any sign (V=-6.5dB).
Volume parameters on Queue apply to that buf only (summed with the
stream’s base dB during playback). Volume verb updates the channel’s
base level for subsequent playback.
Errors are silent. The BBS can confirm an action succeeded by querying
CSI = 7 ; <ch> n afterward and inspecting the state.
APC SyncTERM:A;Load;S=N;<filename> ST Load patch from Store (CTAL)
Decodes <filename> (a file previously uploaded via SyncTERM:C;S)
into slot N using libsndfile. Silently ignored if libsndfile is not
available — query SyncTERM:Q;libsndfile first to confirm libsndfile
presence, and SyncTERM:Q;libsndfileFormat;pm;ps to confirm support for
a specific container/subtype pair.
APC SyncTERM:A;LoadBlob;S=N;<data> ST Load patch from Blob (CTALB)
Decodes base64-encoded audio file data directly into slot N using
libsndfile without storing it in the cache directory. Silently ignored
if libsndfile is not available — query SyncTERM:Q;libsndfile first to
confirm libsndfile presence, and SyncTERM:Q;libsndfileFormat;pm;ps to
confirm support for a specific container/subtype pair. Raw headerless
PCM is not inferred; use an audio container format with enough metadata
for libsndfile to decode it.
APC SyncTERM:A;Synth;S=N;W=<shape>;F=<hz>;T=<dur> ST Synthesize patch (CTAS)
Generates a waveform into slot N. Shapes: SIN, SAW, SQ,
SINE_HARM, SINE_SAW, SINE_SAW_CHORD, SINE_SAW_HARM, SILENCE.
F=0 or W=SILENCE produces silence regardless of other parameters.
APC SyncTERM:A;Copy;S=N;D=M ST Copy patch (CTAC)
Deep-copies slot N into slot M. Source slot is NOT emptied.
APC SyncTERM:A;QueueMIDI;<filename> ST Queue a MIDI file
Open <filename> through the current BBS cache, using the same confined
filename rules as Load. Accept Standard MIDI File formats 0 and 1,
including RIFF/RMID wrapping, tempo maps, running status, SMPTE timing and
SysEx. Format 2 and malformed files are ignored. SysEx is forwarded normally.
No arbitrary local path or new file access authority is introduced.
Accepted MIDI files, tracker modules and completed ANSI captures share a FIFO on channel 0;
queueing never replaces earlier music. Use Flush;C=0 for replacement.
The FIFO accepts at most 128 requests. Invalid or full requests are rejected
without cancelling accepted music. The active parser/message arena is bounded
to 64 MiB and internal synthesis renders at most 4096 PCM frames ahead.
MIDI files release sustained notes at their end and allow two seconds for their
tails; that interval remains busy. ANSI retains its existing articulation.
All channel 0 controls (Flush, including its fade, Volume, Wait, state
queries and Update) address logical music even when no PCM stream exists.
Internal timing follows PCM consumption; external timing follows a monotonic
clock. Reset, disconnect and shutdown cancel queued events and silence notes.
Native destinations without stereo gain use MIDI channel volume/pan controls
as the stream-volume overlay, with the destination’s MIDI gain resolution.
APC SyncTERM:A;QueueModule;<filename> ST Queue a tracker module
Queue a file from the current BBS cache on channel 0 using the same filename
rules as QueueMIDI. Libopenmpt identifies the format from the file contents.
Each accepted module plays once through PCM in FIFO order, independently of
the selected MIDI method. Channel 0 volume, flush (including fade), wait,
state and update requests apply during playback.
Use APC SyncTERM:Q;module ST to check availability. An unavailable decoder
or PCM output, an invalid file, or a full FIFO leaves earlier music queued.
APC SyncTERM:A;Queue;C=#;S=N;… ST Queue patch on channel (CTAQ)
Moves slot N’s buffer onto channel `C’s FIFO. Slot becomes empty.
Rejected when `C=0 or C=1 (those channels are cterm-owned).
Optional parameters: I= (fade-in), O= (fade-out), X (crossfade),
L (loop), V= / VL= / VR= (per-buf volume).
Crossfade (X): if the channel has a head buf already playing, its
decay overlaps with the new buf’s fade-in over fade_in_frames frames
— both play concurrently during the overlap. No-op if the channel
is empty (the new buf just fades in from silence).
Loop (L): the buf’s mixer cursor wraps at end. A subsequent Queue
(plain or crossfade) ends the loop.
APC SyncTERM:A;Flush;C=#[;O=<dur>] ST Flush channel (CTAFL)
Drains channel C’s queue. If `O= is provided, applies an overlay
fade-out of that length on the current head buf first; otherwise stops
immediately.
APC SyncTERM:A;Volume;C=#;… ST Set channel volume (CTAV)
Updates the channel’s base dB. V= sets both channels; VL= / VR=
override a specific side. If only one side is given, the other is left
at its current value.
An optional T=<duration> parameter turns the change into a dB-linear
ramp that interpolates from the current volume to the target over
<duration> (same grammar as Synth’s `T — milliseconds by default,
f suffix for frames, ms for explicit ms; p periods are rejected).
T=0 or absent → instant change.
APC SyncTERM:A;Wait;C=# ST Wait for channel to idle (CTAW)
Blocks the terminal (stalling further BBS byte processing) until channel `C’s queue is empty. No-op if the head is a looping buf.
APC SyncTERM:A;Update;C=# ST Arm idle notification (CTAU)
Arms a one-shot CSI = 7 ; <ch> ; 0 n emission the next time channel
C transitions from running to stopped. BBS can poll channel state
(SyncTERM:A;Queue followed by a state query) without busy-waiting.
"ANSI" Music
This is the place where the BBS world completely fell on it’s face in ANSI
usage. A programmer with either TeleMate or QModem (the first two programs to
support "ANSI" music as far as I can tell) decided they needed a method of
playing music on a BBS connection. They decided to add an "unused" ANSI code
and go their merry way. Since their product didn’t implement CSI M (Delete
line) they assumed it was unused and blissfully broke the spec. They defined
"ANSI" music as:
CSI M <music string> 0x0e
They used a subset of IBM BASICs PLAY statement functionality for ANSI music
strings which often start with "MF" or "MB", so the M after the CSI was often
considered as part of the music string. You would see things such as:
CSI MFABCD 0x0e and the F would not be played as a note. This just added
further confusion to the mess.
Later on, BananaCom realized the conflict between delete line and music, so
they added another broken code CSI N (Properly, erase in field… not
implemented in many BBS clients) which was to provide an "unbroken" method of
playing music strings. They also used CSI Y to disambiguate delete line, CSI Y
is supposed to be a vertical tab (also not implemented in very many clients).
BananaCom also introduced many more non-standard and standard-breaking control
sequences which are not supported by CTerm.
CTerm has further introduced a standard compliant ANSI music introducer CSI |
By default, CTerm allows both CSI N and CSI | to introduce a music string.
Allowed introducers are set by CSI = p1 M as defined above.
The details of ANSI music then are as follows: The following characters are allowed in music strings: "aAbBcCdDeEfFgGlLmMnNoOpPsStT0123456789.-+#<> " If any character not in this list is present, the music string is ignored as is the introducing code.
If the introducing code is CSI M the first char is examined, and if it is
a one of "BbFfLlSs" or if it is "N" or "n" and is not followed by a decimal
digit, then the music string is treated as though an M is located in front
of the first character.
The music string is then parsed with the following sequences supported:
Mx-
sets misc. music parameters where x is one of the following:
FPlays music in the foreground, waiting for music to complete playing before more characters are processed.
BPlay music in the background, allowing normal processing to continue.
N"Normal" not legato, not staccato
LPlay notes legato
SPlay notes staccato
T###-
Sets the tempo of the music where
###is one or more decimal digits. If the decimal number is greater than 255, it is forced to 255. If it is less than 32, it is forced to 32. The number signifies quarter notes per minute. The default tempo is 120. O###-
Sets the octave of the music where
###is one or more decimal digits. If the decimal number is greater than 6, it is forced to 6. The default octave is 4. N###-
Plays a single note by number. Valid values are 0 - 83. Invalid values are played as silence. Note zero is C in octave 0. See following section for valid note modifiers.
A, B, C, D, E, F, G, or P-
Plays the named note or pause from the current octave. An "Octave" is the rising sequence of the following notes: C, C#, D, D#, E, F, F#, G, G#, A, A#, B The special note
Pis a pause. Notes may be followed by one or more modifier characters which are applied in order. If one overrides a previous one, the last is used. The valid modifiers are:+- Sharp-
The next highest semitone is played. Each sharp character will move up one semitone, so "C++" is equivalent to "D".
#- Sharp-
The next highest semitone is played. Each sharp character will move up one semitone, so "C##" is equivalent to "D".
-- Flat-
The next lowest semitone is played. Each flat character will move down one semitone, so "D--" is equivalent to "C".
.- Duration is 1.5 times what it would otherwise be-
Dots are not cumulative, so
C..is equivalent toC. ###- Notelength as a reciprocal of the fraction of a whole note to play the note for-
For example, 4 would indicate a 1/4 note. The default note length is 4.
L###-
Set the notelength parameter for all following notes which do not have one specified (ie: override the quarter-note default) Legal note lengths are 1-64 indicating the reciprocal of the fraction (ie: 4 indicates a 1/4 note).
<-
Move the next lowest octave. Octave cannot go above six or below zero.
>-
Move to the next highest octave. Octave cannot go above six or below zero.
Both the classic tone renderer and MIDI use all seven complete octaves, C through B. Note 0 is C in octave 0 (MIDI note 36, about 65.406 Hz); note 83 is B in octave 6 (MIDI note 119, about 7902.133 Hz). Pitch uses equal temperament with A = 440 Hz. Accidentals apply before range checking; a final pitch outside 0..83 is a rest.
ANSI captures automatically use the first usable enabled MIDI method and otherwise use classic tones. Both share channel 0 with queued MIDI files and tracker modules. Normal/staccato/legato articulation, integer-millisecond timing, dotted notes, and foreground/background capture semantics apply to both renderers.
NMOTE: If you are playing some ANSI Music then ask the user if they heard it, ALWAYS follow it with an 0x0f 0x0e is the shift lock character which will cause people with anything but an ANSI-BBS terminal (ie: *nix users using the bundled telnet app) to have their screen messed up. 0x0f "undoes" the 0x0e.
Sequences sent by SyncTERM
The following keys in SyncTERM result in the specified sequence being sent to the remote. This is not part of CTerm, but are documented here for people who want to maintain compatibility.
Left Arrow |
"\033[D" |
Right Arrow |
"\033[C" |
Up Arrow |
"\033[A" |
Down Arrow |
"\033[B" |
Home |
"\033[H" |
End |
"\033[K" |
Select |
"\033[K" (Same as End due to termcap weirdness) |
Backspace |
"\b" when DECBKM is set (default), "\x7f" when reset |
Delete |
"\x7f" when DECBKM is set (default), "\033[3~" when reset |
Page Down |
"\033[U" |
Page Up |
"\033[V" |
F1 |
"\033[11~" |
F2 |
"\033[12~" |
F3 |
"\033[13~" |
F4 |
"\033[14~" |
F5 |
"\033[15~" |
F6 |
"\033[17~" (Note the jump from 15 to 17 here) |
F7 |
"\033[18~" |
F8 |
"\033[19~" |
F9 |
"\033[20~" |
F10 |
"\033[21~" |
F11 |
"\033[23~" (Note the jump from 21 to 23 here) |
F12 |
"\033[24~" |
Shift + F1 |
"\033[11;2~" |
Shift + F2 |
"\033[12;2~" |
Shift + F3 |
"\033[13;2~" |
Shift + F4 |
"\033[14;2~" |
Shift + F5 |
"\033[15;2~" |
Shift + F6 |
"\033[17;2~" |
Shift + F7 |
"\033[18;2~" |
Shift + F8 |
"\033[19;2~" |
Shift + F9 |
"\033[20;2~" |
Shift + F10 |
"\033[21;2~" |
Shift + F11 |
"\033[23;2~" |
Shift + F12 |
"\033[24;2~" |
Alt + F1 |
"\033[11;3~" |
Alt + F2 |
"\033[12;3~" |
Alt + F3 |
"\033[13;3~" |
Alt + F4 |
"\033[14;3~" |
Alt + F5 |
"\033[15;3~" |
Alt + F6 |
"\033[17;3~" |
Alt + F7 |
"\033[18;3~" |
Alt + F8 |
"\033[19;3~" |
Alt + F9 |
"\033[20;3~" |
Alt + F10 |
"\033[21;3~" |
Alt + F11 |
"\033[23;3~" |
Alt + F12 |
"\033[24;3~" |
Control + F1 |
"\033[11;5~" |
Control + F2 |
"\033[12;5~" |
Control + F3 |
"\033[13;5~" |
Control + F4 |
"\033[14;5~" |
Control + F5 |
"\033[15;5~" |
Control + F6 |
"\033[17;5~" |
Control + F7 |
"\033[18;5~" |
Control + F8 |
"\033[19;5~" |
Control + F9 |
"\033[20;5~" |
Control + F10 |
"\033[21;5~" |
Control + F11 |
"\033[23;5~" |
Control + F12 |
"\033[24;5~" |
Insert |
"\033[@" |
Back Tab |
"\033[Z" |
Prestel and BBC Micro (Mode 7) Emulation
CTerm implements two related Videotex/Teletext display modes: Prestel (the UK viewdata terminal standard) and BBC Micro Mode 7 (the BBC Microcomputer’s teletext display mode). Both use the same 40×25 character grid with the same mosaic graphics and serial attribute system, but differ in their C0 control character handling and cursor movement behavior.
Both modes use the PRESTEL_40X25 video mode: 40 columns × 25 rows,
12×20 character cells, with the Prestel 8-color palette (black, red,
green, yellow, blue, magenta, cyan, white). Bright backgrounds and
no-blink are NOT enabled in this mode (unlike the Commodore and Atari
modes).
Serial Attributes
Unlike conventional terminals where attributes are invisible state changes, Prestel/Mode 7 uses serial attributes. Control codes in the range 0x40–0x5F (accessed via ESC + character in Prestel mode, or raw bytes 0x80–0x9F as C1 controls, or via ESC in BEEB mode) occupy a character cell position on screen. The control code cell is displayed as either a space or a held mosaic character.
Serial attributes apply to all subsequent cells on the same row until changed by another control code. At the start of each new row, all attributes reset to their defaults: white alphanumeric text, black background, no flash, no conceal, no hold, contiguous mosaics, normal height.
Control code effects are split into before and after phases:
-
Before effects apply to the control code’s own cell position (steady, normal height, conceal, contiguous/separated mosaics, black background, new background, hold mosaics)
-
After effects apply to cells following the control code (alphanumeric colors, mosaic colors, flash, double height, release mosaics)
Serial Attribute Codes
These are the decoded control values (0x40–0x5F range after ESC, or 0x80–0x9F as raw C1 bytes minus 0x40):
| Code | Name | Action |
|---|---|---|
0x41 |
Alpha Red |
Set foreground to red, switch to alphanumeric mode |
0x42 |
Alpha Green |
Set foreground to green, switch to alphanumeric mode |
0x43 |
Alpha Yellow |
Set foreground to yellow, switch to alphanumeric mode |
0x44 |
Alpha Blue |
Set foreground to blue, switch to alphanumeric mode |
0x45 |
Alpha Magenta |
Set foreground to magenta, switch to alphanumeric mode |
0x46 |
Alpha Cyan |
Set foreground to cyan, switch to alphanumeric mode |
0x47 |
Alpha White |
Set foreground to white, switch to alphanumeric mode |
0x48 |
Flash |
Enable flashing (blink attribute) |
0x4D |
Double Height |
Enable double-height for this row (see below) |
0x51 |
Mosaic Red |
Set foreground to red, switch to mosaic mode |
0x52 |
Mosaic Green |
Set foreground to green, switch to mosaic mode |
0x53 |
Mosaic Yellow |
Set foreground to yellow, switch to mosaic mode |
0x54 |
Mosaic Blue |
Set foreground to blue, switch to mosaic mode |
0x55 |
Mosaic Magenta |
Set foreground to magenta, switch to mosaic mode |
0x56 |
Mosaic Cyan |
Set foreground to cyan, switch to mosaic mode |
0x57 |
Mosaic White |
Set foreground to white, switch to mosaic mode |
0x5F |
Release Mosaics |
Clear held mosaic, disable hold mode |
| Code | Name | Action |
|---|---|---|
0x49 |
Steady |
Disable flashing (clear blink attribute) |
0x4C |
Normal Height |
Disable double-height, clear hold and held mosaic |
0x58 |
Conceal |
Enable concealed display (hidden until revealed) |
0x59 |
Contiguous Mosaics |
Switch to contiguous (solid) mosaic rendering |
0x5A |
Separated Mosaics |
Switch to separated (gapped) mosaic rendering |
0x5C |
Black Background |
Set background to black |
0x5D |
New Background |
Set background to current foreground color |
0x5E |
Hold Mosaics |
Enable hold mode (see below) |
Alphanumeric vs Mosaic Mode
The alphanumeric color codes (0x41–0x47) switch to the G0 character set where bytes 0x20–0x7F display as normal text characters.
The mosaic color codes (0x51–0x57) switch to the G1 character set. In mosaic mode, characters in the ranges 0x20–0x3F and 0x60–0x7F are displayed as 2×3 block mosaic graphics (with bit 7 set in the stored character value). Characters 0x40–0x5F remain alphanumeric even in mosaic mode.
Hold Mosaics
When a mosaic color change occurs, the control code cell would normally display as a space. With hold mosaics enabled (code 0x5E), the control code cell instead displays the last mosaic character that was output, preserving visual continuity across color changes.
Hold mode is cleared by: alphanumeric color codes, normal height, double height, and release mosaics.
Double Height
Double-height mode (code 0x4D) causes characters on the current row to be rendered at twice their normal height, spanning two physical screen rows. The top half is rendered on the row containing the double-height code, and the bottom half on the row below.
Double-height tracking is complex:
-
A row containing any double-height code becomes a "top" row
-
The row immediately below a "top" row becomes a "bottom" row
-
Bottom rows in Prestel terminal mode copy attributes and characters from the corresponding top row cell
-
Bottom rows in BEEB mode display the bottom half of the same cell
-
The last screen row cannot be a top row
-
Double-height codes also clear hold mode and the held mosaic
Concealed Display
Code 0x58 enables concealed mode. Concealed characters are stored normally but rendered with the foreground hidden (displayed as background color). The user can toggle reveal mode (in SyncTERM, via Alt-V) to show concealed content.
Concealment is cleared by any alphanumeric or mosaic color code.
Character Translation (BEEB only)
In BBC Micro mode, three characters are translated to match the Mode 7 SAA5050 character set:
-
#(0x23) becomes_(0x5F) — pound sign position -
_(0x5F) becomes`(0x60) -
`(0x60) becomes#(0x23)
C0 Control Characters — Prestel
| Byte | Name | Action |
|---|---|---|
0x00 |
NUL |
Time filling — no action (flushes print buffer) |
0x05 |
ENQ |
Send memory slot 0 contents (Prestel identity) |
0x08 |
APB |
Active Position Backward — move cursor left one position (wraps to end of previous row; top row wraps to bottom) |
0x09 |
APF |
Active Position Forward — move cursor right one position (wraps to start of next row; bottom row wraps to top) |
0x0A |
APD |
Active Position Down — move cursor down one row (wraps to top row) |
0x0B |
APU |
Active Position Up — move cursor up one row (wraps to bottom row) |
0x0C |
CS |
Clear Screen — home cursor and clear page memory, reset reveal mode |
0x0D |
APR |
Active Position Return — move cursor to first position of current row |
0x11 |
CON |
Cursor On — make cursor visible |
0x14 |
COF |
Cursor Off — make cursor invisible |
0x1B |
ESC |
Escape — prefix for serial attribute codes and programming sequences |
0x1E |
APH |
Active Position Home — move cursor to first position of top row |
Per the specification, "for all cursor movements the first character of each row is regarded as contiguous with the last character of the previous row, and the top row is regarded as the row following the bottom row." This means all cursor movement wraps around the screen in Prestel mode.
Bytes 0x20–0x7F are printable (with mosaic translation as described above). Bytes 0x80–0x9F are treated as raw C1 serial attribute controls (value minus 0x40). Other undefined C0 bytes are ignored (section 2.6: "shall take no action on their receipt").
C0 Control Characters — BEEB (BBC Micro Mode 7)
| Byte | Name | Action |
|---|---|---|
0x00 |
NUL |
No-op (flushes print buffer) |
0x07 |
BEL |
Audible bell |
0x08 |
APB |
Active Position Backward — move cursor left (wraps to previous row; scrolls down at top) |
0x09 |
APF |
Active Position Forward — move cursor right (wraps to next row; scrolls up at bottom) |
0x0A |
APD |
Active Position Down — move cursor down one row (scrolls up at bottom) |
0x0B |
APU |
Active Position Up — move cursor up one row (scrolls down at top) |
0x0C |
CS |
Clear Screen — home cursor and clear screen, reset reveal mode |
0x0D |
APR |
Active Position Return — move cursor to first position of current row (via ctputs CR handling) |
0x17 |
VDU 23 |
Start 9-byte VDU 23 sequence (cursor control only) |
0x1C |
APS |
Active Position Set — followed by 2 bytes: column (minus 0x20), row (minus 0x20), both 0-based |
0x1E |
APH |
Active Position Home — move cursor to first position of top row |
0x7F |
DEL |
Destructive backspace — move left, write space, move left |
|
Note
|
LF (0x0A) in BEEB mode is handled by the explicit APD case before reaching ctputs, so it functions as cursor-down with scroll, not as a ctputs line feed. |
Unlike Prestel, BEEB mode scrolls the screen when cursor movement reaches the edges rather than wrapping around.
Cursor Movement Differences
The key behavioral difference between Prestel and BEEB modes is cursor wrapping at screen edges:
-
Prestel: Cursor wraps around the screen. Moving up from the top row wraps to the bottom row. Moving down from the bottom row wraps to the top row.
-
BEEB: Cursor scrolls the screen. Moving up from the top row scrolls content down. Moving down from the bottom row scrolls content up.
Left/right wrapping to adjacent rows is the same in both modes.
ESC Sequences — Prestel
In Prestel mode, ESC is followed by a character that is interpreted as a serial attribute code (the character value is used directly as the control code, range 0x40–0x5F for valid codes).
Additionally, Prestel supports a programming protocol for memory slot management:
-
ESC 1 ESC 2— Begin memory query/program sequence -
ENQ(0x05) within programming — send current memory slot -
ESC 3— advance to next memory slot -
ESC 4— begin programming current memory slot (followed by 16 data bytes using digits 0–9,:,;,?) -
7 memory slots of 16 bytes each are available
ESC/VDU Sequences — BEEB
In BEEB mode, ESC does NOT trigger serial attribute codes (unlike Prestel). Serial attributes in BEEB mode are delivered as raw C1 bytes (0x80–0x9F) which are translated to attribute codes by subtracting 0x40.
ESC in BEEB mode introduces VDU control sequences. Two multi-byte sequences are supported:
-
VDU 23,1,N;0;0;0; (byte 23 + 9 data bytes): Cursor control. N=0 hides cursor, N=1 shows cursor. All other bytes in the sequence must be zero.
-
APS (byte 28 + 2 bytes): Direct cursor addressing. First byte is column (minus 0x20), second is row (minus 0x20), both 0-based.
Bitmap Rendering
Prestel/Mode 7 rendering is represented directly in
struct st_console_cell flags so every console backend sees the same cell
semantics:
-
Separated mosaics: Mosaic characters are rendered with gaps between the 2×3 blocks, using
ST_CONSOLE_CELL_SEPARATED -
Double-height rendering: Characters are stretched vertically across two physical rows, with top/bottom half tracking per row
-
Concealed display:
ST_CONSOLE_CELL_CONCEALsuppresses foreground pixels;ST_CONSOLE_CELL_REVEALmakes concealed content visible -
Row state caching: Double-height row states (top/bottom) are pre-computed to avoid O(rows²) scanning during rendering
The ST_CONSOLE_CELL_TERMINAL_FONT flag distinguishes Prestel terminal
mode from BEEB mode for double-height bottom-row handling: Prestel
copies attributes from the row above, while BEEB uses the cell’s own
attributes.
PETSCII Emulation
CTerm’s PETSCII mode emulates the Commodore 64 and Commodore 128 screen editors. PETSCII (PET Standard Code of Information Interchange) is the character encoding used by Commodore 8-bit computers, with control codes for color, cursor movement, and screen editing.
Three screen modes are supported:
| Mode | Size | Colors | Default Attr |
|---|---|---|---|
C64 40×25 |
40×25 |
16 (C64 palette) |
0x6E (light blue on blue) |
C128 40×25 |
40×25 |
16 (C64 palette) |
0xBD (light green on dark green) |
C128 80×25 |
80×25 |
16 (CGA palette) |
0x07 (light grey on black) |
All three modes have bright backgrounds enabled and blinking disabled (BGBRIGHT and NOBLINK video flags).
The C64 defaults to upper-case/graphics. Control code 14 selects lower-case/upper-case and 142 selects upper-case/graphics on all three machines. Both controls select the font and byte mapping for subsequent text.
Control Codes
| Byte | Name | Action |
|---|---|---|
5 |
White |
Set foreground color to white |
7 |
Bell |
Audible bell |
13 |
Return |
Carriage return + line feed. Also disables reverse mode. Scrolls at bottom. |
14 |
Lower Case |
Switch to lower-case/upper-case font |
17 |
Cursor Down |
Move cursor down one row (scrolls at bottom) |
18 |
Reverse On |
Enable reverse video mode |
19 |
Home |
Move cursor to top-left corner |
20 |
Delete |
Destructive backspace — move cursor left (wrapping to end of previous row), shift remaining characters left, blank inserted at right margin. At top-left, does nothing. |
28 |
Red |
Set foreground color to red |
29 |
Cursor Right |
Move cursor right (wraps to first column of next row, scrolls at bottom) |
30 |
Green |
Set foreground color to green |
31 |
Blue |
Set foreground color to blue |
129 |
Orange |
Set foreground color to orange (C64/C128-40) or magenta (C128-80) |
141 |
Shift+Return |
Line feed (move to first column of next row, scrolls at bottom). Does NOT disable reverse mode. |
142 |
Upper Case |
Switch to upper-case/graphics font |
144 |
Black |
Set foreground color to black |
145 |
Cursor Up |
Move cursor up one row (clamps at top, no scroll) |
146 |
Reverse Off |
Disable reverse video mode |
147 |
Clear Screen |
Clear screen and home cursor |
148 |
Insert |
Insert a blank space at cursor; characters to the right shift right. Character at right margin is lost. |
149 |
Brown |
Set foreground color |
150 |
Light Red |
Set foreground color |
151 |
Dark Grey |
Set foreground color |
152 |
Grey |
Set foreground color |
153 |
Light Green |
Set foreground color |
154 |
Light Blue |
Set foreground color |
155 |
Light Grey |
Set foreground color |
156 |
Purple |
Set foreground color |
157 |
Cursor Left |
Move cursor left (wraps to last column of previous row if at left margin; clamps at top-left) |
158 |
Yellow |
Set foreground color |
159 |
Cyan |
Set foreground color |
Bytes 32–127 and 160–255 are printable characters (unless listed above). Bytes in ranges 0–31 and 128–159 that are not listed above are ignored.
Known Differences from Hardware
The Commodore 128 KERNAL handles several control codes differently from the C64. CTerm currently uses C64 behavior for most of these. The following codes differ between C64 and C128 hardware but are not yet differentiated in CTerm:
| Byte | C64 Hardware | C128 Hardware |
|---|---|---|
0x02 |
Ignored |
UL ON (underline, C128 only) |
0x08 |
LOCK CASE |
TAB SET/CLEAR (HTS) |
0x09 |
UNLOCK CASE |
TAB (HT) |
0x0A |
Ignored |
LINE FEED |
0x0B |
Ignored |
UNLOCK CASE |
0x0C |
Ignored |
LOCK CASE |
0x0F |
Ignored |
FSH ON (flashing, 80-column only) |
0x1B |
Ignored |
ESC |
0x82 |
Ignored |
UL OFF (underline off, C128 only) |
0x8F |
Ignored |
FSH OFF (flashing off, 80-column only) |
|
Note
|
The actual behavior desired may differ from raw hardware because BBS terminal programs (CCGMS, DesTerm, NovaTerm, etc.) running on these systems may have performed their own translation or stripping of control codes before displaying them. |
Color Mapping
The 16 color control codes map to different palette indices depending on the screen mode.
| Byte | Color Name | Index | Byte | Color Name | Index |
|---|---|---|---|---|---|
144 |
Black |
0 |
129 |
Orange |
8 |
5 |
White |
1 |
149 |
Brown |
9 |
28 |
Red |
2 |
150 |
Light Red |
10 |
159 |
Cyan |
3 |
151 |
Dark Grey |
11 |
156 |
Purple |
4 |
152 |
Grey |
12 |
30 |
Green |
5 |
153 |
Light Green |
13 |
31 |
Blue |
6 |
154 |
Light Blue |
14 |
158 |
Yellow |
7 |
155 |
Light Grey |
15 |
| Byte | Color Name | Index | Byte | Color Name | Index |
|---|---|---|---|---|---|
144 |
Black |
0 |
152 |
Grey |
8 |
31 |
Blue |
1 |
154 |
Light Blue |
9 |
30 |
Green |
2 |
153 |
Light Green |
10 |
151 |
Dark Grey |
3 |
159 |
Cyan |
11 |
28 |
Red |
4 |
150 |
Light Red |
12 |
129 |
Orange |
5 |
156 |
Purple |
13 |
149 |
Brown |
6 |
158 |
Yellow |
14 |
155 |
Light Grey |
7 |
5 |
White |
15 |
|
Note
|
The C64 and C128 40-column modes use the C64 VIC-II palette. The C128 80-column mode uses a standard CGA-compatible palette. The same control code byte may map to a different palette index depending on the mode. |
Reverse Video
Reverse video mode (byte 18 on, byte 146 off) swaps the foreground and background nibbles of the attribute byte for all subsequent characters. Byte 13 (Return) also disables reverse mode.
Cursor Movement Details
-
Return (13): Moves cursor to first column and down one row. Scrolls if at bottom. Also disables reverse mode.
-
Shift+Return (141): Same as Return but does NOT disable reverse.
-
Cursor Down (17): Move down one row, scrolls at bottom.
-
Cursor Up (145): Move up one row, clamps at top (no scroll).
-
Cursor Right (29): Move right one column. At right margin, wraps to first column of next row. At bottom-right, scrolls.
-
Cursor Left (157): Move left one column. At left margin, wraps to last column of previous row. At top-left, does nothing.
Font Switching
Two character sets are available per machine type:
| Mode | Upper Case (142) | Lower Case (14) |
|---|---|---|
C64 |
Font 32 (C64 UPPER) |
Font 33 (C64 Lower) |
C128 |
Font 34 (C128 UPPER) |
Font 35 (C128 Lower) |
The upper-case set contains upper-case letters and PETSCII graphics characters. The lower-case set contains both upper and lower-case letters.
Unimplemented Features
-
Flashing on/off (bytes 2/0x82 and 15/0x8F) — C128 80-column only, not implemented
ATASCII Emulation
CTerm’s ATASCII mode emulates the Atari 8-bit computer’s screen editor. ATASCII (Atari ASCII) is the character encoding used by Atari 400/800 and XL/XE series computers, with control codes and cursor behavior specific to the Atari hardware.
Two screen modes are supported:
| Mode | Size | Colors | Notes |
|---|---|---|---|
Standard (Atari 40×24) |
40×24 |
2 |
Dark blue background, light blue foreground |
XEP80 (Atari 80×25) |
80×25 |
2 |
Greyscale (white and black) |
No escape sequences are used; all operations are performed via single-byte control codes.
Character Encoding
The Atari screen editor receives ATASCII. For display, the Atari OS maps
ATASCII 00–1F to internal screen codes 40–5F, maps 20–5F to
00–3F, and leaves 60–7F in place. It preserves bit 7 throughout
the conversion. SyncTERM’s Atari font is arranged in ATASCII order.
Bit 7 selects reverse video for each printable character. For example,
41 C1 41 displays three As with just the middle one in reverse video.
ESC Quoting
ESC (1B) quotes the next ATASCII byte, allowing a control’s glyph to be
displayed. Bit 7 still determines its polarity. End-of-line (9B) always
advances to the next line, including after ESC.
Control Codes
| Byte | Name | Action |
|---|---|---|
27 |
ESC |
Quote the next byte, with the end-of-line exception above |
28 |
Cursor Up |
Move cursor up one row; wraps to bottom of same column |
29 |
Cursor Down |
Move cursor down one row; wraps to top of same column |
30 |
Cursor Left |
Move cursor left one column; wraps to right side of same row |
31 |
Cursor Right |
Move cursor right one column; wraps to left side of same row |
125 |
Clear Screen |
Clear entire screen and home cursor |
126 |
Backspace |
Move cursor left one column and erase the character at the new position. Does NOT wrap; sticks at left margin. |
127 |
Tab |
Advance to next tab stop. If no tab stop is found before end of line, wraps to first column of next row (scrolling if at bottom). |
155 |
Return (EOL) |
Move cursor to first column of next row (CR+LF). Scrolls if at bottom. |
156 |
Delete Line |
Delete the current line; lines below shift up. Cursor moves to first column. |
157 |
Insert Line |
Insert a blank line at cursor row; lines below shift down. Current line is cleared. |
158 |
Clear Tab |
Clear the tab stop at the current cursor column |
159 |
Set Tab |
Set a tab stop at the current cursor column |
253 |
Bell |
Audible bell |
254 |
Delete Char |
Delete the character at the cursor; characters to the right shift left. A blank is inserted at the right margin. |
255 |
Insert Char |
Insert a blank space at the cursor; characters to the right shift right. The character at the right margin is lost. |
All other byte values are printable ATASCII characters.
Cursor Wrapping Behavior
The four cursor movement keys wrap differently than most terminals:
-
Up (28): Wraps from the top row to the bottom row of the same column. Does NOT scroll.
-
Down (29): Wraps from the bottom row to the top row of the same column. Does NOT scroll.
-
Left (30): Wraps from the left margin to the right margin of the same row. Does NOT change rows.
-
Right (31): Wraps from the right margin to the left margin of the same row. Does NOT change rows.
This matches verified Atari 8-bit hardware behavior.
Tab Stops
Tab stops in ATASCII are set and cleared at individual column positions using bytes 159 (Set Tab) and 158 (Clear Tab). Default tab stops are at the standard 8-column intervals. The tab character (byte 127) advances to the next set tab stop; if no stop exists before the end of the line, it wraps to column 1 of the next row (scrolling if necessary).
Atari ST VT52 Emulation
CTerm’s Atari ST VT52 mode emulates the VT52-compatible terminal built into the Atari ST’s TOS/GEM desktop. This includes the standard VT52 command set plus GEMDOS/TOS extensions for color, line editing, and additional cursor control.
Three screen modes are supported, matching the Atari ST’s display hardware:
| Mode | Size | Colors | Notes |
|---|---|---|---|
Low resolution (ST 40×25) |
40×25 |
16 |
Full 16-color palette |
Medium resolution (ST 80×25) |
80×25 |
4 |
White, Red, Green, Black |
High resolution (ST 80×25 Mono) |
80×25 |
2 |
White and Black |
Autowrap is disabled by default (unlike ANSI-BBS mode). All three modes have bright backgrounds enabled and blinking disabled (BGBRIGHT and NOBLINK video flags).
The available colors depend on the screen mode — color commands
(ESC b, ESC c) index into the mode’s palette, and indices beyond
the mode’s color count wrap around (only the low bits are meaningful).
C0 Control Characters
| Byte | Name | Action |
|---|---|---|
0x00 |
NUL |
Ignored |
0x01–0x06 |
— |
Display the Atari ST glyph in received text |
0x07 |
BEL |
Audible bell |
0x08 |
BS |
Backspace — move cursor left one column (no wrap, clamps at left margin) |
0x09 |
HT |
Horizontal tab — advance to next tab stop |
0x0A |
LF |
Line feed — move cursor down one row, scroll if at bottom |
0x0B |
VT |
Vertical tab — same as LF (move down one row, scroll) |
0x0C |
FF |
Form feed — same as LF (move down one row, scroll) |
0x0D |
CR |
Carriage return — move cursor to left margin |
0x0E–0x1A |
— |
Display the Atari ST glyph in received text |
0x1B |
ESC |
Start escape sequence |
0x1C–0x1F |
— |
Display the Atari ST glyph in received text |
0x20–0x7E |
— |
Printable character, displayed at cursor position |
See the VT52 manual for the private-use glyph mappings and generated IGS console behavior.
BS, HT, LF, and CR are processed by the shared ctputs output path.
VT and FF are handled explicitly before output and behave identically
to LF (move down one row with scroll).
Escape Sequences — Standard VT52
All sequences are two bytes: ESC followed by a single character, except ESC Y which takes two additional parameter bytes.
| Sequence | Name | Action |
|---|---|---|
|
Cursor Up |
Move cursor up one row (clamp at top, no scroll) |
|
Cursor Down |
Move cursor down one row (clamp at bottom, no scroll) |
|
Cursor Right |
Move cursor right one column (clamp at right margin) |
|
Cursor Left |
Move cursor left one column (clamp at left margin) |
|
Cursor Home |
Move cursor to top-left corner (row 1, column 1) |
|
Reverse Line Feed |
Move cursor up one row; if at top, scroll down |
|
Erase to End of Page |
Clear from cursor to end of line, then clear all lines below |
|
Erase to End of Line |
Clear from cursor to end of current line |
|
Direct Cursor Address |
Move cursor to position (row − 32, col − 32). Row and column are 0-based offsets encoded as the value + 32 (space = 0). Row is clamped to 0–23, column to 0–79. Parameters below 32 abort the sequence. |
|
— |
Ignored (ESC followed by ESC) |
|
Alternate Keypad |
Enable alternate keypad mode |
|
Normal Keypad |
Disable alternate keypad mode (normal numeric keypad) |
|
— |
Ignored (VT52 graphics mode — not applicable) |
|
— |
Ignored (VT52 graphics mode — not applicable) |
|
— |
Ignored (hold-screen mode — not implemented) |
|
— |
Ignored (hold-screen mode — not implemented) |
Escape Sequences — GEMDOS/TOS Extensions
These are extensions specific to the Atari ST’s TOS operating system.
| Sequence | Name | Action |
|---|---|---|
|
Clear Screen |
Clear entire screen and move cursor to home position |
|
Insert Line |
Insert a blank line at cursor row; lines below shift down. Cursor column is preserved. |
|
Delete Line |
Delete the line at cursor row; lines below shift up. A blank line is added at the bottom. |
|
Set Foreground Color |
Set foreground color to c & 0x0F (4-bit palette index, 0–15) |
|
Set Background Color |
Set background color to c & 0x0F (4-bit palette index, 0–15) |
|
Erase to Start of Page |
Clear from cursor to start of line (inclusive), then clear all lines above |
|
Show Cursor |
Make cursor visible (normal cursor) |
|
Hide Cursor |
Make cursor invisible |
|
Save Cursor |
Save current cursor position |
|
Restore Cursor |
Restore cursor to last saved position. No effect if no position was saved or if saved position is outside the current window. |
|
Clear Line |
Clear the entire current line (cursor position is preserved) |
|
Erase to Start of Line |
Clear from start of line to cursor position (inclusive) |
|
Reverse Video On |
Enable reverse video (swap foreground and background) |
|
Reverse Video Off |
Disable reverse video (restore normal foreground/background) |
|
Enable Autowrap |
Characters at the right margin wrap to the next line |
|
Disable Autowrap |
Characters at the right margin are clamped (no wrap) |
Color Palette
The color parameter for ESC b and ESC c is the low 4 bits of the
byte following the command character (value & 0x0F), giving an index
from 0 to 15 into the current mode’s palette.
In low resolution (40×25), the full 16-color palette is available:
| Index | Color | Index | Color |
|---|---|---|---|
0 |
White |
8 |
Light Red |
1 |
Red |
9 |
Light Green |
2 |
Green |
10 |
Light Yellow |
3 |
Yellow |
11 |
Light Blue |
4 |
Blue |
12 |
Light Magenta |
5 |
Magenta |
13 |
Light Cyan |
6 |
Cyan |
14 |
Dark Grey |
7 |
Light Grey |
15 |
Black |
In medium resolution (80×25), the default palette has 4 colors repeated across all 16 slots: White (0), Red (1), Green (2), Black (3), matching the Atari ST hardware where only 4 simultaneous colors were available.
In high resolution (80×25 mono), the default palette alternates White and Black across all 16 slots, matching the monochrome hardware.
|
Note
|
SyncTERM’s per-entry custom palette feature allows users to override the default palette with up to 16 unique colors in any mode. This does not match hardware behavior where medium and high resolution modes are physically limited to 4 and 2 colors respectively, but provides flexibility for BBS content that uses the additional palette slots. |
|
Note
|
Reverse video (ESC p / ESC q) interacts with color commands.
When reverse video is active, ESC b sets the background color and
ESC c sets the foreground color (the sense is swapped).
|
Negative Image (Reverse Video)
The Atari ST VT52 mode uses the full 4-bit foreground and background
nibbles when swapping for reverse video, unlike ANSI-BBS mode which
only swaps the low 3 bits and preserves the bright/blink bits
independently. In VT52 mode, ESC p swaps all 4 bits of the
foreground nibble with all 4 bits of the background nibble.
Differences from Standard VT52
-
ESC ;introduces SyncTERM version discovery, screen-mode selection and IGS negotiation. See the VT52 manual for the wire format. -
Autowrap is off by default (standard VT52 has no autowrap control)
-
16-color support via
ESC bandESC c(Atari ST extension) -
Insert/delete line (
ESC L/ESC M) are TOS extensions -
Erase-to-start commands (
ESC d,ESC o) are TOS extensions -
Cursor save/restore (
ESC j/ESC k) are TOS extensions -
Show/hide cursor (
ESC e/ESC f) are TOS extensions -
Autowrap control (
ESC v/ESC w) are TOS extensions -
Reverse video (
ESC p/ESC q) are TOS extensions -
Clear line (
ESC l) is a TOS extension -
VT52 Identify (
ESC Z) is not implemented -
VT52 graphics mode (
ESC F/ESC G) is not implemented -
Hold-screen mode (
ESC [/ESC \) is not implemented
References
-
[STD-070] Digital Equipment Corporation. Video Systems Reference Manual. 1989-04-14.
-
[ECMA-48] ECMA. Control Functions for Coded Character Sets. June 1991
-
[XTerm] Edward Moy. XTerm Control Sequences. University of California, Berkeley. Revised by Stephen Gildea. X Consortium (1994). Thomas Dickey. XFree86 Project (1996-2006). invisible-island.net (2006-2024). and updated for XTerm Patch #394 2024/09/19
-
[Paste64] Thomas E. Dickey. XTerm — bracketed paste. 2022
-
[BANSI] Paul Wheaton. BANSI.TXT. 1999
-
[VT102] Digital. VT102 Video Terminal User Guide. 1982.
-
[VT330/340] Digital. VT330/VT340 Programmer Reference Manual, Volume 2: Graphics Programming. May 1988.
-
[VT320] Digital. Installing and Using the VT320 Video Terminal. June 1987.
-
[VT384] Digital. VT382 Kanji Display Terminal Programmer Reference Manual.
-
[256colors] Jonas Jarad Jacek. 256 colors cheat sheet. 2023-12-24.
-
[VT420] Digital. Installing and Using the VT420 Video Terminal. June 1990.
-
[ANSISYS] Wikipedia. ANSI.SYS.
-
[ECMA-35] ECMA. Character Code Structure and Extension Techniques. December 1994
-
[VT520] Digital. VT520/VT525 Video Terminal Programmer Information. July 1994.
-
[VT100] Digital. User Guide VT100. 1981.
SyncTERM Console Library
Introduction
The st_console library is SyncTERM’s character-generator and host-console
abstraction. It owns a grid of character cells, optional software pixel
planes, fonts, palettes, input events, presentation state, and one selected
host backend.
It is not a Borland conio compatibility library. It does not expose global
screen state, putch, cprintf, conio windows, or line editing. Those
operations are either explicit operations on an st_console_t instance or
belong to a higher-level user-interface component. Terminal parsing and
emulation are also separate; CTerm consumes a connection’s byte stream and
writes the resulting cells and pixels through this interface.
An application may attach multiple logical consoles to one
st_console_display_t. The display owns the physical backend, window or host
terminal, presentation worker, and physical-key state. Each st_console_t
retains its own cells, pixels, palette, fonts, cursor, dimensions, title,
pointer preference, update state, and ordered input queue. Exactly one console
is active on a nonempty display at a time.
st_console_display_config holds backend selection, text-terminal encoding
and I/O, an optional RGBA application icon, and initial window size/scaling.
The icon storage remains owned by the caller for the display’s lifetime and is
ignored by non-window backends. st_console_config holds only the logical
console’s cell/raster geometry and rendering policy. The convenience
constructor is st_console_create(result, display_config, console_config);
applications sharing one output instead create a display and attach logical
consoles with st_console_create_on_display(). Initial window settings apply
when the first console opens the backend, not when another console attaches
or becomes active. Switching consoles preserves the current display scale.
st_console_display_activate() synchronously applies the selected console’s
retained mode and state and completes a full presentation. Inactive consoles
can be updated and rasterized without invoking backend callbacks. Events stay
queued on whichever console was active when they arrived.
Input routing changes only after successful activation. A failed activation
restores the previous console’s dimensions, palette, title, pointer preference,
and presentation. If that restoration also fails, the previous console remains
selected but backend operations return IO_ERROR_IO until an explicit
activation succeeds. The application may continue using retained logical
state; it must not assume the physical output is current while suspended.
Attachment, activation, and destruction are serialized per display. Destroying the selected console selects a remaining peer and drains library-owned input and presentation references before freeing memory. If presenting that peer fails, it remains selected with physical output suspended until a successful activation. Destroying the last console shuts down the physical backend; the display object itself can subsequently accept a new first console. If a failed backend cannot detach from a removed console, its storage remains internally retained until successful activation or backend shutdown. The removed handle is invalid to callers regardless of this deferred release.
Public operations on a live instance may be called concurrently. Read-only
state queries share a reader lock; mutations, presentation, and backend
operations are serialized. The owner must prevent new calls and allow active
calls to finish before calling st_console_destroy().
Output Modes
An output mode selects how the retained console state reaches the user. It is separate from the screen mode, which defines the grid, character generator, raster, cursor, blink rules, and intended aspect ratio.
| Backend | Class | Description |
|---|---|---|
ANSI |
Text |
Writes ANSI control sequences and either UTF-8 or CP437 text.
The command-line forms are |
ncurses |
Text |
Uses the host’s curses implementation and terminfo entry.
Unicode, CP437, and ASCII presentation are selected with |
Win32 Console |
Text |
Uses the native Windows console screen-buffer and input APIs. It restores the active buffer, input mode, and cursor when destroyed. |
GDI |
Bitmap |
Native Windows graphical output. Each instance owns its window and message thread. |
Quartz |
Bitmap |
Native macOS graphical output using AppKit and Core Graphics. It supports multiple windows and Retina backing scales without requiring SDL. |
Wayland |
Bitmap |
Native Wayland output using an xdg toplevel and positioned video subsurface. Requests server-side decorations when the optional xdg-decoration protocol is available at build time and supported by the compositor. Alt+left-drag requests an interactive move. |
X11 |
Bitmap |
Native Xlib output. XRender, XRandR, and Xinerama are used when present. Copy and paste use the X11 primary selection, with the legacy clipboard fallback retained for ChromeOS Sommelier. |
SDL |
Bitmap |
Portable graphical fallback, especially useful on Haiku. Native window backends are preferred where available. |
libretro |
Bitmap host |
Pull-based presentation for the enclosing libretro run callback. Frontend input uses the ordinary console event interface. |
Headless |
Off-screen |
Retains cells and optional pixel planes without opening a display. Used by tests and other off-screen consumers. |
Automatic Selection
The caller may request ST_CONSOLE_BACKEND_AUTO; it does not need to prepare
backend-specific supporting state. For a bitmap console, selection prefers
the native GDI or Quartz implementation, then Wayland, X11, and SDL where they
were built and are usable. The fallback text path tries ncurses and then
ANSI. A text-only Windows configuration can select the native Win32 console.
Failure to load an optional runtime library falls through to the next usable
backend.
st_console_get_backend() reports the selected backend.
st_console_build_features() reports what was compiled into the library; it
does not promise that an optional display server or runtime library is usable
on the current host.
The Wayland backend waits without a client-side deadline for the compositor’s
mandatory initial configure event during creation. Once running, loss of the
compositor posts one close event and makes pending and later backend operations
fail. Clipboard source delivery writes the complete payload to the descriptor
supplied by Wayland; a closed receiver abandons that transfer without raising
SIGPIPE, while an open receiver applies the protocol’s ordinary write
backpressure.
Text Backends
Text backends display retained cells but cannot display arbitrary pixel-plane
changes or registered bitmap fonts. ANSI Unicode mode and wide curses obtain
the Unicode text associated with each retained glyph; CP437 modes encode its
scalar through the locale-independent CP437 table and use ? when it is not
representable.
Bitmap glyph indexes never select text-terminal characters. Continuation
cells for wide glyphs are skipped.
Native curses' CP437 mode uses a scoped per-thread C locale where the target
provides newlocale and uselocale, with ncurses' legacy-byte setting when
available. Initialization, output, and input leave the caller’s locale intact.
On curses targets without per-thread locales, the caller supplies a byte
locale for CP437 mode. Native Unicode curses uses the caller’s Unicode locale;
direct UTF-8 output does not depend on the C locale.
For Unicode and CP437, curses entries with standard ANSI cursor, erase, and colour capabilities use SyncTERM’s byte writer. This preserves complete Unicode sequences and CP437 bytes through curses implementations that would decode or discard them. Indexed terminals retain their detected colour count and palette handling; RGB output still requires direct-colour support. Other entries retain native curses rendering.
ANSI direct-colour support and indexed-colour count are separate
capabilities. The ordinary terminal path reads terminfo and also accepts
COLORTERM=truecolor or COLORTERM=24bit when terminfo does not advertise
RGB. Indexed cells stay indexed even on a direct-colour terminal.
The ordinary ANSI backend reads and writes the process standard streams.
Input may be an interactive terminal or a redirected pipe or regular file;
output remains an ANSI byte stream when redirected. End-of-file or a
permanent input error finishes any pending escape or UTF-8 input, posts one
ST_CONSOLE_EVENT_CLOSE, and stops the input worker. Destroying the display
interrupts its input wait without posting a close event. A caller-supplied
st_console_ansi_io replaces output only and does not provide an input
source.
ncurses uses its extended colour-pair interfaces when the required ncurses 6.1 symbols are present, so colour and pair identifiers are not narrowed to signed 16-bit. Palette entries changed through a mutable curses terminal are restored when the instance closes.
ST_CONSOLE_CAP_TEXT_TERMINAL is set for ANSI, ncurses, and Win32 console.
ST_CONSOLE_CAP_LOCAL_CONTROL_KEYS is currently set only for ANSI and
ncurses, where SyncTERM reserves Ctrl+Q and Ctrl+S for local commands. The
native Win32 console is a text terminal but has independent keyboard events.
ST_CONSOLE_CAP_BRIGHT_BACKGROUND is independent of palette mutation and
reports that the backend can present the sixteen-colour bright-background
interpretation. For ncurses, complete 16-bit indexed-palette capability
requires a reported colour count of at least 65,535 together with the
extended colour and pair interfaces; direct colour is a separate path.
Bitmap Backends
Bitmap backends render the complete character-generator model, including registered fonts, direct RGB, indexed palette changes, blink planes, custom cursors, SAA5050 attributes, and pixel graphics. The common bitmap presenter tracks regional damage through font rasterization and every scaling stage so small updates do not become full-frame uploads.
Desktop applications link st_console_main. Its entry wrapper keeps APIs
which require the process main thread—currently SDL and AppKit/Quartz—on that
thread while running the application on a joined secondary thread. Selecting
an automatic backend does not leak that requirement into application code.
X11, Wayland, xkbcommon, and optional SDL are loaded at run time; their development declarations are build capabilities. GDI and the Windows console are part of the Windows programming environment. AppKit and Quartz are part of the macOS programming environment and are linked normally.
Text Modes
A SyncTERM screen mode describes the emulated character generator, not how it is presented to the host. It supplies the grid dimensions, cell dimensions, complete raster, aspect ratio, default cursor scanlines, and blink rules. Raster dimensions may include scanlines or columns outside the text image; these margins do not scroll. For example, 80x43 uses 344 text scanlines in a 350-line raster, leaving six stationary scanlines.
| Mode | Grid | Cell | Raster | Aspect |
|---|---|---|---|---|
80x25 / Current |
80x25 |
8x16 |
640x400 |
4:3 |
LCD 80x25 |
80x25 |
8x16 |
640x400 |
8:5 (square pixels) |
80x28 |
80x28 |
8x14 |
640x392 |
4:3 |
80x30 |
80x30 |
8x16 |
640x480 |
4:3 |
80x43 |
80x43 |
8x8 |
640x350 |
4:3 |
80x50 |
80x50 |
8x8 |
640x400 |
4:3 |
80x60 |
80x60 |
8x8 |
640x480 |
4:3 |
132x37 |
132x37 |
8x16 |
1056x592 |
16:9 (square pixels) |
132x52 |
132x52 |
8x16 |
1056x832 |
5:4 (square pixels) |
132x25 |
132x25 |
8x16 |
1056x400 |
4:3 |
132x28 |
132x28 |
8x14 |
1056x392 |
4:3 |
132x30 |
132x30 |
8x16 |
1056x480 |
4:3 |
132x34 |
132x34 |
8x14 |
1056x476 |
4:3 |
132x43 |
132x43 |
8x8 |
1056x350 |
4:3 |
132x50 |
132x50 |
8x8 |
1056x400 |
4:3 |
132x60 |
132x60 |
8x8 |
1056x480 |
4:3 |
C64 |
40x25 |
8x8 |
320x200 |
6:5 |
C128 40-column |
40x25 |
8x8 |
320x200 |
6:5 |
C128 80-column |
80x25 |
8x8 |
640x200 |
4:3 |
Atari |
40x24 |
8x8 |
320x192 |
4:3 |
Atari XEP80 |
80x25 |
8x16 |
640x400 |
4:3 |
CGA 80x25 |
80x25 |
8x8 |
640x200 |
4:3 |
EGA 80x25 |
80x25 |
8x14 |
640x350 |
4:3 |
VGA 80x25 |
80x25 |
9x16 |
720x400 |
4:3 |
Prestel |
40x25 |
12x20 |
480x500 |
3077:2400 |
BBC Micro |
40x25 |
12x20 |
480x500 |
3077:2400 |
Atari ST 40x25 |
40x25 |
8x8 |
320x200 |
4:3 |
Atari ST 80x25 |
80x25 |
8x8 |
640x200 |
4:3 |
Atari ST mono 80x25 |
80x25 |
8x16 |
640x400 |
4:3 |
The Custom mode takes its grid, font height, and aspect ratio from settings.
The library uses checked uint32_t dimensions and size_t allocation counts
rather than the old conio limits; the backend and available memory still
impose practical limits.
Cells and Coordinates
Coordinates are zero-based. Rectangles have nonzero width and height and
must fit entirely inside the current grid. Strides are cell counts expressed
as size_t.
struct st_console_cell is compact and contains no pointers or separate
allocations. It retains the resolved bitmap glyph, the selected and actual
internal font identifiers, indexed or direct-RGB colours, hyperlink identifier,
and named flag masks. It does not retain the Unicode scalar or grapheme which
selected that glyph. SAA5050 control data is retained in flags separately
from the displayed glyph. The final two bytes retain a zero reserved byte
and the terminal colour rendition used for subsequent attribute edits. Together with compile-time offset and
size assertions, this defines a padding-free 24-byte cell representation for
internal raw rectangle checksums; it does not turn the structure into a
persistent or cross-version file format.
ST_CONSOLE_CELL_BRIGHT and ST_CONSOLE_CELL_BLINK retain source attribute
bits 3 and 7; ST_CONSOLE_CELL_BOLD remains an independent glyph-weight
style. The two legacy-colour provenance flags mean the corresponding stored
base palette index should follow the console’s video-flag policy. An explicit
palette or RGB colour does not acquire that policy merely because its numeric
index is below eight.
The high colour bit selects direct RGB; otherwise values through 65,535 are palette indices. Cells and pixel planes use the same representation, so palette identity survives rasterization, capture, snapshots, and blits.
ST_CONSOLE_CELL_DIRTY is private presentation state. Writes ignore it from
callers and reads do not return it. Content changes mark cells in the
low-bandwidth mutation path; the renderer consumes contiguous dirty runs.
Cell operations accept only resolved font/glyph cells. Before constructing a
cell from semantic text, the caller resolves its normalized grapheme cluster
with st_console_font_lookup_cluster(); the scalar convenience lookup is
st_console_font_lookup(). st_console_write_cells() applies normal
pair-aware cell mutation, while st_console_write_complete_cells() bulk-copies
a complete validated rectangle without per-cell pair synthesis. Neither
operation interprets cell.glyph as a codepoint.
Readback returns the resolved cell, not the scalar or grapheme which selected
its glyph. st_console_font_glyph_text() can provide a representative
registered mapping for text backends and selection, but that mapping is not
lossless provenance and is not required to reproduce the original input.
Fonts and Unicode
Each font registration contains one-bit bitmap data and a sorted Unicode
mapping. There is no implicit codepoint-to-glyph identity map, even for a
256-glyph legacy font. A decoder first resolves legacy
source-bright/source-blink font selectors with
st_console_font_for_flags(), then looks up the resulting (font,
codepoint) pair. These source bits are distinct from the bold style and
remain in the stored cell after font selection.
Lookup checks the selected font first, then the designated Unicode fallback
with matching pixel dimensions. Without a designated fallback it tries
compatible font zero. If
neither maps the scalar, font zero supplies a width-matched replacement.
Mapped width comes from font data; missing-scalar width comes from generated
Unicode East Asian Width and Emoji Presentation tables, never the process
locale or wcwidth().
Normal text suppresses zero-column graphemes before font lookup, cursor
movement, or wrapping, even if a font has a visible diagnostic mapping.
Default ignorables and categories Mn, Me, Cf, and Cc have zero scalar advance;
isolated non-ignorable combining marks retain a visible one-column grapheme
fallback. Attached marks, selectors, and joiners remain in their grapheme.
CR, LF, TAB, and BS keep their text-control actions. Explicit glyph cells and
font lookup are not text output: they can still select diagnostic or blank
glyphs, including glyph zero. st_console_font_lookup_fallback() selects a
width-matched missing glyph directly, without trying any Unicode mapping.
An eight-pixel glyph occupies one cell and a sixteen-pixel glyph occupies two.
The second cell is marked ST_CONSOLE_CELL_CONTINUATION, and region mutations
preserve complete pairs. A wide glyph at the final column wraps before being
written when wrapping is enabled. If it still cannot fit after the wrap, as
in a one-column text window, the glyph is suppressed after the normal line
advance or scroll.
Static registration borrows immutable process-lifetime data. Copy registration owns bitmap and mapping copies until console destruction, which supports downloaded fonts and server-supplied Unicode maps. If all 65,536 identifiers are occupied, a new registration replaces the least-recently-used font, succeeds, and reports the replacement on standard error. Existing cells retain that identifier and are not dirtied merely by the replacement. Registration never reinterprets retained cells; the new mapping applies to subsequent lookups and Unicode cell writes.
SyncTERM retains all 46 legacy 256-glyph font families with explicit Unicode maps. The Font Management screen filters them by the sizes actually present:
| Font | Character set | 8x8 | 8x14 | 8x16 | 12x20 |
|---|---|---|---|---|---|
Codepage 437 English |
CP437 |
✓ |
✓ |
✓ |
✓ |
Codepage 1251 Cyrillic, (swiss) |
CP1251 |
✓ |
|||
Russian koi8-r |
KOI8-R |
✓ |
✓ |
✓ |
|
ISO-8859-2 Central European |
ISO-8859-2 |
✓ |
✓ |
✓ |
|
ISO-8859-4 Baltic wide (VGA 9bit mapped) |
ISO-8859-4 |
✓ |
|||
Codepage 866 (c) Russian |
CP866M |
✓ |
|||
ISO-8859-9 Turkish |
ISO-8859-9 |
✓ |
|||
haik8 codepage (use only with armscii8 screenmap) |
HAIK8 |
✓ |
✓ |
✓ |
|
ISO-8859-8 Hebrew |
ISO-8859-8 |
✓ |
✓ |
✓ |
|
Ukrainian font koi8-u |
KOI8-U |
✓ |
✓ |
✓ |
|
ISO-8859-15 West European, (thin) |
ISO-8859-15 |
✓ |
|||
ISO-8859-4 Baltic (VGA 9bit mapped) |
ISO-8859-4 |
✓ |
✓ |
✓ |
|
Russian koi8-r (b) |
KOI8-R |
✓ |
|||
ISO-8859-4 Baltic wide |
ISO-8859-4 |
✓ |
|||
ISO-8859-5 Cyrillic |
ISO-8859-5 |
✓ |
✓ |
✓ |
|
ARMSCII-8 Character set |
ARMSCII-8 |
✓ |
✓ |
✓ |
|
ISO-8859-15 West European |
ISO-8859-15 |
✓ |
✓ |
✓ |
|
Codepage 850 Multilingual Latin I, (thin) |
CP850 |
✓ |
✓ |
||
Codepage 850 Multilingual Latin I |
CP850 |
✓ |
✓ |
✓ |
|
Codepage 865 Norwegian, (thin) |
CP865 |
✓ |
✓ |
||
Codepage 1251 Cyrillic |
CP1251 |
✓ |
✓ |
✓ |
|
ISO-8859-7 Greek |
ISO-8859-7 |
✓ |
✓ |
✓ |
|
Russian koi8-r (c) |
KOI8-R |
✓ |
|||
ISO-8859-4 Baltic |
ISO-8859-4 |
✓ |
✓ |
✓ |
|
ISO-8859-1 West European |
ISO-8859-1 |
✓ |
✓ |
✓ |
|
Codepage 866 Russian |
CP866M2 |
✓ |
✓ |
✓ |
|
Codepage 437 English, (thin) |
CP437 |
✓ |
✓ |
||
Codepage 866 (b) Russian |
CP866M2 |
✓ |
|||
Codepage 865 Norwegian |
CP865 |
✓ |
✓ |
✓ |
|
Ukrainian font cp866u |
CP866U |
✓ |
✓ |
✓ |
|
ISO-8859-1 West European, (thin) |
ISO-8859-1 |
✓ |
|||
Codepage 1131 Belarusian, (swiss) |
CP1131 |
✓ |
|||
Commodore 64 (UPPER) |
PETSCII upper/graphics |
✓ |
✓ |
||
Commodore 64 (Lower) |
PETSCII lower/upper |
✓ |
✓ |
||
Commodore 128 (UPPER) |
PETSCII upper/graphics |
✓ |
✓ |
||
Commodore 128 (Lower) |
PETSCII lower/upper |
✓ |
✓ |
||
Atari |
ATASCII |
✓ |
✓ |
||
P0T NOoDLE (Amiga) |
ISO-8859-1 |
✓ |
✓ |
||
mO’sOul (Amiga) |
ISO-8859-1 |
✓ |
✓ |
||
MicroKnight Plus (Amiga) |
ISO-8859-1 |
✓ |
|||
Topaz Plus (Amiga) |
ISO-8859-1 |
✓ |
|||
MicroKnight (Amiga) |
ISO-8859-1 |
✓ |
✓ |
||
Topaz (Amiga) |
ISO-8859-1 |
✓ |
✓ |
||
Prestel |
SAA5050 |
✓ |
✓ |
||
Atari ST |
Atari ST |
✓ |
✓ |
||
RIPterm |
CP437 |
✓ |
✓ |
For 8x8 modes, font zero is UNSCII 8x8. For 8x16 modes, the default build
uses SyncTERM Unicode, derived from GNU Unifont with UNSCII overlaid on
matching glyphs; disabling SYNCTERM_ENABLE_UNIFONT uses UNSCII 8x16 alone.
SyncTERM Unicode is distributed under SIL OFL 1.1. Its copyright notices and
full license are available under SyncTERM Settings > Licenses; see also
src/fonts/unifont/LICENSE.OFL-1.1 and src/fonts/unifont/UPSTREAM.md.
The 8x8, 8x14, and 8x16 Unicode fallback fonts also include SyncTERM Emoji,
rasterized from monochrome Noto Emoji under SIL OFL 1.1. They support
single emoji, skin tones, joined emoji, flags, keycaps, and presentation
selectors covered by that source font. Double-column emoji use a 16-pixel
bitmap. The Unicode font of last resort prefers these emoji, while selected
BBS fonts keep their native glyphs. Each console shares one fallback font per
pixel size, reused across catalog reloads. Size-matched emoji remain available after
mode changes and when Unifont is disabled. Read the copyright notice and
full license under SyncTERM Settings > Licenses or in
src/fonts/builtin/LICENSE.NOTO-EMOJI; see src/fonts/builtin/UPSTREAM.md for regeneration details.
Stateful Text Operations
The current style, position, clipping/scroll window, wrapping, cursor, blink mode, video flags, palette, and scaling policy are per instance. Changing the text window preserves the screen position when it lies inside the new bounds. A position outside the new window moves to its upper-left corner.
The seven video flags retain the legacy source-attribute policy without
changing the cell ABI. Source bit 3 may select a bright foreground and/or an
alternate font; source bit 7 may select blink, a bright background, and/or an
alternate font. NO_BRIGHT and NO_BLINK disable only their respective
rendering meanings. EXPAND is fixed by the console geometry; when an
eight-pixel font is displayed in a nine-pixel cell, the ninth column is blank
except that LINE_GRAPHICS_EXPAND repeats column eight for glyph indices
0xC0 through 0xDF. Changing a flag that affects existing presentation
invalidates retained rendering without rewriting cells or their resolved font
identifiers; selector changes apply to subsequent writes.
Filling the final column wraps immediately when wrapping is enabled; at the bottom of the window that wrap immediately scrolls. Carriage return moves to the window’s left edge, line feed retains the column and advances or scrolls, tab writes spaces to the next eight-column stop, and backspace moves left and replaces that cell with a styled space.
UTF-8 decoding is locale-independent. A complete string is validated before any cells change; overlong encodings, surrogates, incomplete sequences, and values beyond U+10FFFF are rejected. Formatted output is not part of this layer.
Direct semantic codepoint writes apply the same Unicode-scalar requirement. Codepoint arguments used by window clearing, scrolling, and line insertion/deletion must occupy exactly one text column. Cell arguments used by rectangle fill and move-and-clear must already contain a resolved one-column glyph. Invalid semantic input or a wide fill is rejected before text or cursor state changes.
Moves have snapshot source semantics when rectangles overlap. Scrolling and
line insertion/deletion move matching cached glyph rasters with the cells, so
retained rows do not pass through the font renderer again. A full-width
top-of-grid scroll advances a circular text-raster origin instead of copying
every pixel row. By default, non-text raster margins do not participate.
st_console_set_full_surface_scroll(console, true) instead rotates the
entire pixel height, including rows below the text grid, for RIP’s 640x350
surface with 43 eight-pixel text rows. Exposed text rows are repainted even
when their cells were already blank; a trailing strip beyond the text width
is cleared to the fill cell’s background. The setter accepts false to
restore text-only scrolling, normalizing any pending ring offset first; it
requires a bitmap console and returns IO_ERROR_NOT_SUPPORTED otherwise.
If a horizontal text-window boundary crosses a wide pair, an affected row
operation clears the complete pair, including its adjacent half outside the
window, before moving the remaining complete cells.
Pixel Planes and Scaling
Providing both cell dimensions creates software pixel planes; providing only one is invalid. Explicit raster dimensions may add non-text margins but cannot be smaller than the text image. Primary and alternate planes are the two blink states.
Pixel writes first bring intersecting character rasters current, then modify the final-raster planes and mark those cells as pixel graphics. A later character-content change regenerates the cell. Text backends reject pixel mutations rather than claiming success for invisible output.
If requested external scaling is unavailable (for example, X11 without XRender or Wayland without viewport support), the same backend uses software scaling. Startup and console switching remain available, and neither the console’s requested mode nor the saved settings are changed by this fallback.
Internal scaling composes the final-size image in software; external scaling hands a native-size retained frame to a capable host. Aspect correction is applied before the requested window scale, and creation never scales below one displayed pixel per source pixel.
Blocky is the default scaling policy. Pointy is the optional traditional SyncTERM smoothing pipeline. Integer multiplication, Pointy, xBR, and one-axis interpolation are stages selected for the actual dimensions, not three separate user-visible scalers. The common case can expand one axis by an exact integer while interpolating only the other.
Damage is transformed through each retained scaling stage. Integer stages
multiply the rectangle, filters expand it by their dependency radius, and
interpolation uses precomputed inverse maps. st_scaler_benchmark measures
full-frame and regional scaling; st_console_benchmark measures rasterization
and sustained scrolling. They are comparison tools, not CTest thresholds.
Presentation and Snapshots
Window bitmap backends wake the presentation worker on the first pending change. The worker resolves dirty pixels into retained native-size images under the console lock, then releases it before scaling and submitting the frame. Writes during display accumulate in the live console. Once the backend is ready, the worker takes the latest completed state. A window resize during an open batch uses the last complete image and the new window dimensions. Libretro consumes pending changes when the frontend queries or copies a frame.
st_console_begin_update() and st_console_end_update() provide explicit,
nestable batching. The outermost end makes the batch eligible for normal
presentation. st_console_present() is a synchronous forced boundary even
inside a batch. On an inactive console it drains only the retained off-screen
state and does not invoke the display backend. Text backends remain
synchronous so failures can be returned.
Wayland does not wait when both shared-memory buffers remain owned by the compositor. It skips that frame and requests the latest state when a buffer is released.
Snapshot creation is a drain boundary: pending changes are handed to the backend and live dirty flags are consumed before the copy. A snapshot retains cells, pixel planes, palette, style, window, position, cursor, wrapping, and video/scaling state, but never dirty flags. It can only be restored to its originating console with identical dimensions. Font registrations are instance resources and are not copied.
For libretro, st_console_display_libretro_frame_size() queries the physical
display’s last completed frame and st_console_display_libretro_frame_copy()
copies it. The size can change between those calls, including on console
activation. Copy therefore takes both the destination stride and its row
capacity; an undersized destination is rejected without writing to it.
Input Events
Each logical console has one ordered event queue. Translated keys, physical keys, committed text, DoorWay scan codes, mouse actions, resize, focus, and close are distinct event types. Backends post only semantics they actually receive.
st_console_display_post_event() delivers host input to the console active
when delivery is serialized. st_console_post_event() explicitly targets the
given console’s queue, including an inactive console. Switching does not move
already queued events between consoles.
Normalized non-text keys use ST_CONSOLE_KEY_*; ASCII controls retain their
byte values. Graphical backends translate Control combined with an ASCII
letter, @, [, \\, ], ^, _, or Space into that control’s
KEY_CODE byte. Physical events carry evdev-style identity, modifiers,
press/release, and repeat state. Held physical-key state belongs to the
display, including physical events submitted through the explicit-console
entry point. Focus loss queues releases on the event’s target console before
the focus event and clears the display’s held set. Clearing queued events does
not alter held state.
st_console_synthesize_physical_key() atomically compares that held state and
queues only a real transition, so a failed queue reservation cannot change the
state without delivering its edge.
X11 committed text comes from its UTF-8 input context, preserving layouts, dead keys, compose processing, and external input methods. Wayland uses xkbcommon. SDL and Windows also separate physical identity from committed Unicode. ANSI and ncurses decode only what the enclosing terminal supplies; they do not invent physical identities or key-release events.
ANSI and ncurses host-terminal resizing schedules an independent repaint of the retained screen, even while the application is idle. A resize event reports the new host dimensions; it does not resize the logical console.
Mouse coordinates are in the logical console pixel grid, independent of final window scaling. Button state, event-time modifiers, action, coordinates, and wheel deltas remain separate fields.
Window and Host Operations
Bitmap window backends consume Alt+Left and Alt+Right to snap to adjacent integer display scales, Alt+Home to centre the window where positioning is permitted, and Alt+Enter to toggle fullscreen. The monitor containing the window—not the whole multi-monitor root desktop—controls centring, limits, maximization, and fullscreen. Wayland also consumes Alt+left-drag for interactive movement. These commands are not also delivered as application keys.
Changing bitmap modes retains approximately the same window diagonal, choosing the closest scale that fits the current monitor. Integer-scaled windows stay integer-scaled; manually sized windows retain fractional scaling. The scale multiplier itself is not preserved across different native raster sizes. Scale shortcuts use the native raster’s controlling axis, avoiding rounding errors in aspect-corrected dimensions such as C64’s 640-by-533 2x size.
Title and pointer visibility are retained per console and restored on
activation. Clipboard, URL, and fullscreen operations belong to the physical
display; the single-console convenience calls forward to that display. Each
operation independently returns IO_ERROR_NOT_SUPPORTED when unavailable.
Backend-returned text is released with
st_console_free_text() so allocation does not cross the library boundary.
st_console_display_get_scaling() reports the active bitmap window’s physical
scale relative to its source raster while accounting for aspect correction.
The X11, Wayland, SDL, GDI, and Quartz backends support the query. Text,
libretro, and headless backends return IO_ERROR_NOT_SUPPORTED. A window
smaller than the
minimum source presentation is an invalid backend state and returns
IO_ERROR_OUT_OF_RANGE; the result argument is unchanged on every failure.
Unresolved host capability detection is documented in
src/console/CAPABILITY_GAPS.md. Missing implementation work is not a
host-capability gap.