Skip to content

Ultimate64/II BASIC tokenizer - #616

Open
radius75 wants to merge 73 commits into
GideonZ:masterfrom
radius75:basic-tokenizer-editor-abbreviation
Open

radius75 wants to merge 73 commits into
GideonZ:masterfrom
radius75:basic-tokenizer-editor-abbreviation

Conversation

@radius75

@radius75 radius75 commented Jan 14, 2026 •

Copy link
Copy Markdown
Contributor

The changes introduced here continue the work discussed in #450. Detailed technical descriptions are included in the commit messages.

Description

This PR improves the Ultimate BASIC editor and tokenizer with an interactive PETSCII table, BASIC keyword abbreviations, external mapping profiles, and clearer error handling.

Key enhancements

  1. Interactive PETSCII table and tooltips

    • Added a clickable table covering $00–$FF.
    • Tooltips describe characters and their C64 key combinations.
    • Clicking an entry inserts its tag at the editor selection.
  2. Special character tags

    • Tags can be typed manually or inserted from the table.
    • The default profile uses CBM prg Studio syntax, such as {white} and {sh a}.
    • Repetition syntax supports both {space*3} and {3 space}.
  3. External profiles

    • special.js selects the mapping profile to load.
    • cbm_prg_studio.js provides the default keywords, special characters, tooltips, and startup text.
    • The former internal mapping has been removed. A valid external profile is required for upload.
    • Profile settings control text normalization.
    • Custom profiles can define keyword and character mappings, tooltips, welcome text, and BASIC examples.
  4. Shorter startup text and editor navigation

    • Profile content is split into WELCOME_TEXT and optional BASIC_CODE.
    • Show profile examples is unchecked by default. Its state is saved in sessionStorage and applied after a page reload.
    • Changing the checkbox displays a reload notice without replacing the current editor content.
    • The BASIC Editor tab is restored after a reload if it was active. Other tabs return to Home.
    • Editor dialogs close when switching tabs.
  5. BASIC keywords and abbreviations

    • The default profile accepts uppercase and lowercase keywords and supported C64 abbreviations.
    • Keyword tokenization is disabled inside quoted strings, after REM, and within DATA until an unquoted colon.
  6. Validation and program upload

    • Line numbers are validated against the 16-bit range, 0–65535.
    • Line length is checked after tokenization.
    • Detected tokenization errors prevent upload.
    • Upload and Run runs the program only after a successful upload.
    • Lines without a leading line number are ignored, allowing instructions and comments between BASIC lines.
  7. Line pointers and null bytes

    • Next-line pointers are calculated from the generated line lengths.
    • A generated 0x00 byte stops processing the current source line. Content following it is not included.
  8. Firmware updater integration

    • Added build support for .js resources.
    • All five updater build variants include and install special.js and cbm_prg_studio.js alongside the web interface.

Validation

  • Firmware builds completed successfully for all five updater build variants.
  • Hardware installation was tested on Ultimate II+ only.
  • Installation into an empty /Flash/html directory correctly created both JavaScript files.
  • Reinstallation without formatting Flash correctly overwrote modified copies of both files.
  • Installed file contents matched the supplied sources after accounting for LF/CRLF line endings.

How to test

  1. Type tags such as {delete} and {white}, then upload the program and check the output.
  2. Insert tags using the PETSCII table and verify insertion at the current editor selection.
  3. Hover over entries to check tooltip descriptions and key combinations.
  4. Change the profile selected in special.js, reload the page, and verify the table and startup text.
  5. Toggle Show profile examples and confirm that the editor content changes only after reloading.
  6. Upload multi-line programs and verify their behavior and line pointers.
  7. Check that invalid tags, line numbers above 65535, and oversized tokenized lines prevent upload.

AI assistance and further review

This code were developed with AI - ChatGPT GPT6.1 Sol Light - assistance. Review of the tokenizer and memory pointer logic is welcome. Tooltip descriptions and character mappings may need further corrections based on wider testing.

Sample test code in CBMprgStudio format:

!- CBM prg Studio
!- --------------
!-
!- userport i/o control
!-
!- clear screen, set uppercase and disable shift + c=
!- for default: set pb0-pb7 as inputs, disable outputs activity, set temp as 0
0 print"{clear}{uppercase}{switch off}":poke56579,0:poke56577,0:te=0
!- decimal to binary precalculation
5 dimb$(255),c$(15)
10 fora=0to15:readc$(a):next
15 a=0:forh=0to15:forl=0to15
20 b$(a)=c$(h)+c$(l):a=a+1:nextl,h
25 data "0000","0001","0010","0011","0100","0101","0110","0111"
30 data "1000","1001","1010","1011","1100","1101","1110","1111"
!- screen
35 print"{clear}";
!-
50 print "          {white}userport i/o control          ";
51 print "                                        ";
52 print "               pb7>{gray}B{white}76543210{gray}B{white}<pb0       ";
53 print "{gray}{sh asterisk*12}CCCCCCC{sh +}{sh asterisk*8}{sh +}CCCCCCCCCCC";
54 print "{white}port current status{gray}B{white}--------{gray}B {white}---  56577";
55 print "{gray}{sh asterisk*12}CCCCCCC{cm w}{light gray}^^^^^^^^{gray}{cm q}CCCCCCCCCCC";
56 print "      {white}entered value{gray}B{white}--------{gray}B {white}---  56577";
57 print "{gray}{sh asterisk*13}CCCCCC{cm w}{light gray}^^^^^^^^{gray}{cm q}CCCCCCCCCCC";
58 print " {white}set port as in/out{gray}B{white}--------{gray}B {white}---  56579";
59 print "{gray}{sh asterisk*12}CCCCCCC{cm e}{sh asterisk*8}{cm e}CCCCCCCCCCC";
60 print "                                        ";
61 print "{white}set line as in-{reverse on}0{reverse off} or out-{reverse on}1{reverse off}, press {reverse on}1{reverse off}-{reverse on}8{reverse off} key";
62 print "   change output state, press {reverse on}q{reverse off}-{reverse on}i{reverse off} key   ";
63 print "{light gray}if the pb line is set as an output then ";
64 print " it has a higher short-circuit current. ";
65 print " do not connect external out to pb out. ";
66 print "                                        ";
67 print "        {black}g {red}+                   {black}g         ";
68 print "        n {red}5               {pink}9 9 {black}n         ";
69 print "        d {red}v               {pink}v v {black}d         ";
70 print "       {white}{cm a}{reverse on}{cm o}{reverse off}{cm r}{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}{cm r}{reverse on}{cm o}{reverse off}C{reverse on}{cm o}{reverse off}{cm s}        ";
71 print "       {cm z}{reverse on}{cm u}{reverse off}{cm e}{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}{cm e}{reverse on}{cm u}{reverse off}C{reverse on}{cm u}{reverse off}{cm x}        ";
72 print "        {black}g   {green}p p p p p p p p   {black}g         ";
73 print "        n   {green}b b b b b b b b   {black}n         ";
74 print "        d   {green}0 1 2 3 4 5 6 7   {black}d";

!- main loop
165 geta$:ifa$<>""thena=val(a$)-1:a2=2^a:gosub200
170 se=peek(56579):cu=peek(56577)
175 print"{home}{white}{down}{down}{down}{down}";
180 print,,b$(cu),"{left}";cu;"{left}  "
185 print,,b$(te),"{left}";te;"{left}  "
190 print,,b$(se),"{left}";se;"{left}  "
195 goto165
200 ifa<0ora>7then215
205 if(seanda2)=a2thenpoke56579,se-a2:return
210 poke56579,seora2:return
215 ifa$="q"thena2=2^0:goto260
220 ifa$="w"thena2=2^1:goto260
225 ifa$="e"thena2=2^2:goto260
230 ifa$="r"thena2=2^3:goto260
235 ifa$="t"thena2=2^4:goto260
240 ifa$="y"thena2=2^5:goto260
245 ifa$="u"thena2=2^6:goto260
250 ifa$="i"thena2=2^7:goto260
255 return
260 if(teanda2)=a2thente=te-a2:poke56577,te:return
265 te=teora2:poke56577,te:return
!- end main loop
270 rem radius75, 2024

Closes #450

radius75 added 30 commits May 14, 2025 13:34
- abbreviation
- shifted letter is needed
- notation of remaining symbols consistent with cbm prg studio
…aced between program lines are ignored during tokenization
…andard from an editor I haven't encountered yet
…into basic-tokenizer-editor-abbreviation

# Conflicts:
#	html/index.html
"additional entries found in COMPUTES!'s Gazette" moved to special.js file
…into basic-tokenizer-editor-abbreviation

# Conflicts:
#	html/index.html
clean short guide
… to the BASIC Tokenizer textarea to prevent visual distractions and ensure a proper coding experience.
…y notes.

Switched // comments to !- within the BASIC template for CBM prg Studio compatibility.
Standardized the external configuration file (SPECIAL.js logic/loader) for clarity.
- Replaced unreliable setTimeout with script.onload combined with jQuery readiness to eliminate race conditions.
- Centralized editor and table initialization into initializeTokenizerUI() to ensure atomic UI updates.
- Corrected loading order of jQuery and external assets in <head> to prevent reference errors.
- Refactored renderSpecialTable to use .empty().append() for consistent UI refreshes when switching profiles.
- Cleaned up redundant script blocks at the end of <body> to maintain a single source of truth for initialization.
Description:
- Data: Reorganized SPECIAL token array to a full 0-255 PETSCII map, following the CBM prg Studio standard.
- UI: Replaced the 16-column table with a high-density 8x32 grid for better space optimization.
- Color: Integrated the Pepto PAL palette for authentic Commodore 64 color reproduction.
- Accessibility: Implemented adaptive contrast logic to toggle white/black text based on background luminance.
- Layout: Standardized spacing with 4px HEX-to-symbol gaps, 16px column gutters, and red vertical separators.
- Stability: Fixed missing HEX assignments for alternate symbols and ensured strict monospace vertical alignment.
…tability to the C64.

Key changes:
1. Added interactivity to renderSpecialTable():
   - Special characters are now clickable and automatically inserted into the BASIC editor.
   - Insertion occurs at the current cursor position (selectionStart/End) instead of at the end of the text.
   - Added 'special-token' class and 'data-token' attributes for better DOM event handling.

2. Enhanced Editor UX:
   - Implemented scroll locking (preventScroll) and manual scroll position restoration to eliminate page "jumping" when selecting characters.
   - Added automatic focus on the editor after a symbol is selected.

3. Fixed a ReferenceError in parseBASIC:
   - Correctly synchronized the program's end address variables, ensuring stable code transmission to memory.

4. Organized technical documentation:
   - Refined internal comments within the rendering function (sections 1-4).

Goal: To facilitate the input of PETSCII control characters and improve the overall consistency of the editor interface.
    Terminate line processing immediately when 0x00 (NULL) is encountered.
    Fixes incorrect line pointers in generated .prg files.
…into basic-tokenizer-editor-abbreviation

# Conflicts:
#	html/index.html
Limit the total number of special character repetitions
in a BASIC line to prevent excessive memory usage during expansion.
Repetition counts are validated before generating
the expanded string. If the combined count exceeds the safety limit,
tokenization is stopped and the program is not sent.
This applies to both supported repetition
formats: {space*3} and {3 space}.
@radius75

radius75 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Regarding the latest commit limiting the number of special character repetitions, I tested the following program:

10 print "{space*999}"
20 print "{space*1000}"
30 print "{space*900}{space*99}{space*1}"
40 print "{999 space}"
50 print "{1000 space}"
60 print "{900 space}{99 space}{1 space}"

Each line tests a different case:

10 — a single CBMprgStudio-style repetition at the safety limit (999).
20 — a single CBMprgStudio-style repetition exceeding the limit (1000).
30 — multiple CBMprgStudio-style repetitions that individually stay within the limit, but exceed it when combined (900 + 99 + 1 = 1000).
40 — a single magazine-style repetition at the safety limit (999).
50 — a single magazine-style repetition exceeding the limit (1000).
60 — multiple magazine-style repetitions that individually stay within the limit, but exceed it when combined (900 + 99 + 1 = 1000).

This verifies both supported repetition syntaxes as well as the cumulative repetition-count check.

The safety limit prevents the browser from attempting to expand extremely large repetition counts, which could consume excessive memory and cause the page or browser tab to become unresponsive.

--
dd47dfc only adds a safety limit to special character repetition expansion. It is not the BASIC line length limit — the final tokenized line length is still checked separately and limited to 256 bytes.

@radius75

Copy link
Copy Markdown
Contributor Author

Hi @chrisgleissner

I've done quite a lot of compatibility testing of the Ultimate tokenizer,
comparing its output and behavior with the CBM prg Studio tokenizer and
with a real C64. So far, these tests have been successful and I haven't
found any significant compatibility problems that would require changes
to the current tokenizer.

As an additional source of real-world test programs, I've been using the
listings from the two Commodore 64 Games Book volumes:

https://archive.org/details/commodore-64-games-book_202304/mode/1up

https://archive.org/details/commodore-64-games-book-2_202409/mode/2up

Transcribed versions of these and many other C64 book listings can also
be found here:

https://github.com/TypeInBooks/books/tree/master/commodore/c64

One thing worth noting is that the descriptions/instructions for some
games do not always match what the programs actually do. However, in the
cases I've checked, these discrepancies were already present in the
original books and are not tokenizer or transcription errors.
The code in the GitHub repository is about eight years old and was most
likely created using a CBM prg Studio 3.1x-era version. This should also
be kept in mind when using it as a compatibility reference, since the
current CBM prg Studio version is 4.10 and its tokenizer may have changed
in various ways since then.

One more question regarding the PR: should I now keep this branch updated
against master instead of test-merge?

@chrisgleissner
chrisgleissner changed the base branch from test-merge to master September 13, 2026 12:43
@chrisgleissner

Copy link
Copy Markdown
Collaborator

Hi @radius75 ,

excellent work!

About the target branch:

  • The test-merge branch has been retired and should no longer be used.
  • All PRs should target master.
  • We will continue to cut releases from master for fixing 3.15 bugs, e.g. 3.15a (already cut), 3.15b, etc.
  • Once all major issues on 3.15 have been fixed, in particular regression issues, we will repurpose master to accept larger work (new features etc.) in preparation for release 3.16.
  • We may at that point create a releases/3.15 branch for fixing 3.15 issues that cannot wait for 3.16. The need for that is likely to be small if we continue to focus on 3.15 fixes for now.

This is as per the Github Flow model aka trunk based development: Only a single master which is always release-ready.

The above has been discussed with @GideonZ (except for the releases/3.15 part), but of course it is ultimately his call.

Thanks
Christian

…into basic-tokenizer-editor-abbreviation
Repository owner deleted a comment from UltimateC64Ultimate64fan Sep 23, 2026
@chrisgleissner chrisgleissner added the ui Menus, navigation, file-list view, dialogs, editors, and monitor presentation; not data corruption. label Oct 3, 2026
@chrisgleissner

chrisgleissner commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Review of da4b875 (BASIC editor / tokenizer profiles)

Assessment: not ready to merge. The editor itself is usable and the error handling is good. Two problems remain: the profile files are not shipped by the updater, and the new test does not run on current master.

I checked the branch merged onto master at dbc7e24 in a scratch worktree (nothing pushed), served html/ locally and drove the editor in headless Chrome.

Blocking

1. special.js and cbm_prg_studio.js are not installed by any updater. This is the issue raised on 2026-01-17 and it is still open. index.html loads special.js, which names the profile file, and both come from /Flash/html/. SRCS_HTML in the seven updater makefiles is still index.html api.html (for example target/u64ii/riscv/update/Makefile:145), and the update*.cc files only write those two. A device updated to a firmware containing this PR therefore gets the new index.html without the two files it depends on. The editor then has no keyword table, shows the following, and refuses to upload:

profile files missing

On current master the editor works without any extra files, so this is a regression for every user who has not copied the files by hand. The author's comment of 2026-08-29 says the editor is not expected to go into the official firmware. If that is still the intent, this should not be merged to master. Otherwise the files need to be packaged (makefile objects plus a write in each updater) or folded into index.html, as suggested in the thread.

2. tests/e2e/web/tokenizer_test.py fails to import on current master. It does from device_stub import DeviceStub. That module is not in the tree. index_test.py on master uses tests/lib/device_double.py and bootstrap. Running the merged tree gives ModuleNotFoundError: No module named 'device_stub'. The CI job is green because this suite is registered as manual=True, so no check has exercised the new test since the base moved. It needs to be ported to DeviceDouble and re-run in Chrome and Firefox before it counts as coverage.

Is the editor still easy to use?

Yes, with two reservations. Layout at 1500x1100:

initial view

  • The editor, the five buttons and the start of the code table are all visible without scrolling. The table sits below the buttons and does not push the editor out of view.
  • The table has about 480 clickable entries in eight columns inside its own scroll box. Rows are short and each column is readable. Full page:

full page

  • Typing in an empty editor does not involve the table at all:

typed program

  • Clicking {white} then {clear} inserted {white}{clear} at the caret, and the caret ended after the second tag (position 24):

click insert

  • An unknown tag is reported with the line number and the offending text, and nothing is sent:

bad tag

Line number 99999 gives Error in line 99999. Invalid BASIC line number. Max is 65535. Program was not sent. (screenshot: https://gist.githubusercontent.com/chrisgleissner/4e537b3afca0ccdd96d0991eec5daa34/raw/ea744ae8083e2c256be5b444ead09a0b07c185f0/09_bad_lineno.png).

Reservations:

  • The welcome text that fills the editor at start is a long !- comment block (about 30 lines) and the editor only shows 11 of them. A user has to select all and delete it, or use Clear, before typing. It is easy to understand, but it is the first thing every user does and it is one extra step. A shorter default text would help.
  • At a 420 px wide window the table and editor are cut off with a horizontal scrollbar, and the page sidebar takes about 40% of the width:

narrow

The sidebar is existing layout, not part of this PR, so I would not hold the PR for it.

Not verified

  • Tooltips. 482 elements carry a title with the key mapping text, but native tooltips do not appear in headless screenshots.
  • Upload to a real device. The page posts to the hostname without a port, so my local server could not receive it. The bytes were not checked in this pass. The earlier byte-level comparisons in the thread (CBMprgStudio and a C64) were not repeated.
  • Firefox. Only Chrome was driven.

Other

  • The branch is 18 commits behind master and merges without conflicts.
  • Tokenizing is case sensitive by design, so an upper-case listing pasted into the editor uploads as shifted characters unless a profile sets NORMALIZE_TO_LOWERCASE. The default profile does not. The in-editor text documents this, but a user pasting a published listing gets no warning.

@chrisgleissner

Copy link
Copy Markdown
Collaborator

Hi @radius75 , hope you are well. It's been a while :-) I left a review of your PR in my previous comment. I know this is taking quite a while, but it is targeted for 3.16 anyway, and we are still preparing to release 3.15c based on what I know.

Thanks for addressing the findings.
All the best.

@radius75

Copy link
Copy Markdown
Contributor Author

Hi @chrisgleissner

I've been thinking about your suggestion regarding the long welcome text.

My idea is to split the current BASIC_CODE in the profile JS file into two separate variables:

  • WELCOME_TEXT – a short welcome message identifying the loaded profile, always displayed after successful profile loading.
  • BASIC_CODE – the instructions and BASIC examples provided by the profile, displayed optionally.

I'd add a "Show profile examples" checkbox next to the existing "Uppercase" checkbox, unchecked by default.

The checkbox state would be stored in sessionStorage, so the preference survives page reloads in the same browser tab.

Changing the checkbox would not immediately modify the editor content, avoiding accidental loss of a BASIC program the user is working on. The new setting would only take effect after reloading the page (F5 or Ctrl+F5).

This way, users would see only a short profile identification by default, while the detailed instructions and BASIC examples would still be available when needed.

What do you think?

- Split profile content into `WELCOME_TEXT` and optional `BASIC_CODE`.
- Add a "Show profile examples" checkbox, disabled by default.
- Save the checkbox preference in `sessionStorage`.
- Apply changes only after page reload to prevent overwriting user code.
- Update profile documentation and add a checkbox tooltip.
- Restore the BASIC Editor tab after F5 or Ctrl+F5 if it was previously active.
- Return to Home when reloading from any other tab.
- Preserve the active tab when using machine control buttons.
@radius75

radius75 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Shorten the BASIC Editor Welcome Text

Previously, the cbm_prg_studio.js profile automatically displayed a lengthy welcome message, instructions, and a sample BASIC program. This change displays only a short welcome message by default while keeping the full examples available.

Changes Made

  • Split the profile content into WELCOME_TEXT (short welcome message) and BASIC_CODE (instructions and examples).
  • Added a Show profile examples checkbox, unchecked by default, with a tooltip explaining its behavior.
  • The checkbox state is saved in sessionStorage and applied only after F5/Ctrl+F5 to avoid overwriting the user's current BASIC code.
  • The welcome text is inserted only after the profile has loaded successfully (CBM_SIGNATURE === "READY"), ensuring that error messages remain visible.
  • Updated the profile structure documentation in cbm_prg_studio.js.
  • Added restoration of the BASIC Editor tab after F5/Ctrl+F5 if it was active before the reload. Otherwise, the Home tab is displayed.

Summary

The changes affect index.html and cbm_prg_studio.js. They do not modify BASIC tokenization or existing editor functionality. Automatic editor focus was intentionally omitted because it caused unwanted scrolling to the end of long BASIC programs.
obraz

- Add a reload notice when the "Show profile examples" setting is changed.
- Reuse the existing Clear BASIC dialog styling for the new notice.
- Automatically close both dialogs when switching tabs.
- Restore the Home page after returning from API Explorer instead of reopening the BASIC editor.
- Prevent the Clear BASIC and Reload notice dialogs from overlapping by closing one before opening the other.
@radius75

Copy link
Copy Markdown
Contributor Author

I've added a reload notice for the "Show profile examples" setting and improved navigation. Both dialogs close when switching tabs, returning from API Explorer opens Home, and only one dialog can be displayed at a time.
obraz

Remove leftover code from the former 160-character line length limiter.
Line length is now checked after tokenization.
@chrisgleissner

Copy link
Copy Markdown
Collaborator

Nice one @radius75! Did you also address the issue that some of your files were not installed by any firmware updater? Could you please install your PR from scratch and verify, plus mention all the devices you tested it on? Thanks.

@radius75

radius75 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@chrisgleissner I tested the firmware installation on my Ultimate II+ only.

I first emptied /Flash/html and confirmed that the updater correctly installed special.js and cbm_prg_studio.js. I then modified both files and reinstalled the firmware without formatting Flash. Both files were correctly overwritten.

The installed files match the source content. The only difference is LF line endings instead of CRLF in my local copies, which makes the installed files slightly smaller.

@chrisgleissner

chrisgleissner commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Many thanks for that test @radius75 , much appreciated!

@GideonZ From my perspective, this PR is ready to be merged, after many review cycles and much great work by @radius75 over the past 10 months.

Given this is a new feature and not a bug fix, I suggest this could go in after 3.15c will have been tagged and we are ready to onboard 3.16-related changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.16 Targeted for release 3.16. enhancement New functionality or an improvement to existing behavior, including formats and developer tooling. ui Menus, navigation, file-list view, dialogs, editors, and monitor presentation; not data corruption.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Req.] Web API. Basic Tokenizer/Editor - abbreviation

4 participants