Новый модуль mdview2_raw.c (+ mdview2.h с общими константами/атрибутами и
extern'ами) — первый шаг разбиения монолита. Опционален через mdview2_conf.h
(#define WITH_RAW): при 0 — пустой объектник, нулевой расход (проверено:
размер как до RAW).
RAW-просмотр (без markdown-форматирования):
- работает по активному буферу (8-бит как есть / UTF-8 декодированный), 1 байт
= 1 ячейка, \t→пробел, ремап CP1251/KOI8 на отрисовке;
- два под-режима: wrap (перенос кратно 80) и hscroll (одна строка + ←/→);
- прокрутка на 1 строку через аппаратный scroll + отрисовка одной строки;
вывод char-буфером (bios_write_until по фону ATTR_TEXT), без win_rest/scratch;
- индекс/кэш markdown не используются, 0 доп. EMM.
Клавиши/меню:
- F2 — тумблер RAW↔MD (запоминает под-режим RAW);
- F3 — Wrap/Unwrap (только в RAW), метка показывает целевой режим;
- меню перестроено: блоки по 8 кол (col i*8), номера всех 10 клавиш без 'F'
(' 1'..' 9','10'), текст-функция 6 симв. сразу за номером и только когда
функция доступна; F8 сокращён до CodePg.
Инкрементальная UTF-8→CP866 конвертация: вместо полного прохода перед
индексацией — чанками впереди позиции чтения (CONV_MARGIN), первый экран
появляется быстро. Конвертер читает оригинал через cv_read (своя W3-страница),
index_lines докручивает конвертацию; progress_tick рисует по текущему виду
(MD/RAW), без мелькания чужого вида.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A.1: таблицы ремапа cp1251/koi8r 256→128 (старшие байты; младшие в
ремапе не используются — win_rest_remap трогает только ch>=0x80).
A.2: conv_emit_cp switch → таблица структур utf_sym_t {utf8, cp866}
(читаемо, добавление символа = одна строка; … и BOM — спецветки).
A.3: common_* цепочки сравнений → таблицы детекции + in_set10.
B1: удалён мёртвый код в scan_join_stream — условия
`if(!soft_break)...else q++` во всех непробельных ветках
(там soft_break всегда 0, т.к. ch!=' ').
_CODE (mdview2.c): 23284 → 22246 байт. Поведение не менялось.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Детекция при открытии (BOM + эвристика по первым 4 КБ).
- 8-битные (CP866/CP1251/KOI8-R) — общий индекс/кэш, переключение
мгновенным ремапом глифов [128-255] на отрисовке по attr (структурные
глифы — рамка/HR/маркеры — не ремапятся).
- UTF-8 — отдельный набор: декодирование в CP866 (кириллица + ходовые
символы: стрелки/галка/буллет/тире/кавычки/box), свой индекс/кэш.
- Два набора (docset_t g_doc[2]) со свапом «живых» глобалов; второй
строится ЛЕНИВО при первом F8-переходе в него (build-on-demand).
- F8: цикл CP866→CP1251→KOI8R→UTF8; метка в меню видна только когда
переключение возможно; во время сборки 8-бит первичного F8 крутит 8-бит.
- F1-справка: секция Encoding; меню разбито на блоки (F1/F8/F10).
- Фикс: g_doc обязан быть инициализирован (SDCC z80 не обнуляет статики
надёжно) — иначе мусорный built вёл к показу неинициализированного набора.
- Убрана отладка времени обработки из статус-бара.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Таблица обрабатывается как блок в два прохода:
- проход 1: границы блока + ОТРЕНДЕРЕННЫЕ ширины колонок (мерим тем же
inline_scan, что и при отрисовке — невидимые маркеры стиля **/код не
раздувают столбцы);
- проход 2: верхняя рамка ┌┬┐ → строки данных │ ячейка<pad> │ → разделитель
заголовка ├┼┤ (из строки |---|) → нижняя рамка └┴┘.
Колонки выровнены по содержимому, рамка CP866 box-drawing. Широкая таблица
остаётся nowrap+hscroll. Ячейки разбиваются cell-итератором (без массивов
на стеке); пустой g_cells под измерение освобождается ручным флашем
pending-сегмента (флаг g_skip_flush в emit_seg, чтобы не флашить повторно).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1. Экранирование пунктуации: \* \_ \` \[ … → литерал, маркером НЕ считается
(CommonMark ASCII-punctuation). Напр. "**...FILE\***" → болд "...FILE*".
Не действует внутри инлайн-кода.
2. [x] / [ ] — ровно один символ в квадратных скобках → болд (нестандартно,
для читабельного отображения task-list checkbox-ов). Не внутри кода.
3. Соседние пункты списка: если следующий имеет МЕНЬШИЙ отступ (dedent),
пустую строку между ними больше не подавляем — пункты визуально разделены.
4. Абзац с ведущим отступом: все его перенесённые строки получают такой же
отступ (continuation-префикс из col пробелов, как у списка/цитаты).
Реализация — в обоих inline-сканерах (inline_scan/scan_join_stream) + ветках
index_lines; новый helper is_escapable() и leading_spaces().
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Препроцессинг 52КБ занимает ~10с; теперь UI не ждёт его завершения.
index_lines() кооперативно вызывает progress_tick() (без прерываний —
IM2 отложен):
- первый экран рисуется, как только готово ≥ VIEW_H строк (~0.3с);
- статус-бар показывает растущее число обработанных строк с многоточием
("L 1-30 / 247...");
- ↑↓ PgUp PgDn Home End (=последняя готовая страница) и F1 работают по
УЖЕ готовым строкам (drawable_lines = [0..n_lines-2], т.к. последний
сегмент ещё в g_cells до flush);
- Esc/F10 во время загрузки — корректный выход (прерывание индексации
флагом g_abort + штатный unload_file/pal_reset/clrscr).
После каждого тика форсируем ре-маппинг W3 (cur_page=0xFF), т.к.
отрисовка/WINREST/BIOS могли сбить страницу, на которую опирается fb().
Временно: debug-индикатор времени обработки "t=Ns" в зоне имени файла
(по просьбе — следить за временем при дальнейших оптимизациях).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
После полной миграции на merge флаги g_cur_merged/g_next_merged всегда
равны 1 (все типы блоков строит форвард-сканер). Убраны сами флаги и ~30
гвардов `if (g_cur_merged)` в горячем посимвольном цикле — это и небольшое
ускорение (ветка на символ), и чистка.
Проверено замером: инлайн gc_put (макрос/inline) в этот регистро-нагруженный
цикл, наоборот, ЗАМЕДЛЯЕТ (~11→13с) из-за роста спиллов — оставлен функцией.
Вывод: per-char микрооптимизации здесь исчерпаны (asm-fb не помог, инлайн
навредил, снятие гвардов дало ~1с).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Раньше препроцессинг сканировал файл ДВАЖДЫ: index_lines считал точки
переноса (forward-сканеры scan_join_stream/inline_scan), а отдельный
render_line_to_cache заново сканировал каждый сегмент для сборки
(char,attr)-ячеек. Профилирование показало, что всё время — в этих двух
посимвольных проходах (bank I/O и cont-walk ≈ 0).
Теперь forward-сканер собирает ячейки в g_cells ПО ХОДУ единственного
прохода; emit_seg флашит ячейки предыдущего сегмента в кэш (lag-1),
последний — после цикла. Перенос строки усекает буфер до снимка на
последнем пробеле (g_ncells_at_space), continuation-сегменты получают
префикс (отступ списка / маркер цитаты 0xB3 / title только в 1-й строке
заголовка). Прямые типы (код verbatim, HR, таблица через nowrap-inline,
blank/fence) строят ячейки на месте.
Миграция шла по типам блоков с dual-verify (старый render строил эталон,
merge сверял ячейки) — найдены и согласованы расхождения forward-сканера
со старым рендером: backtick внутри эмфазиса = литерал; одиночный маркер
закрывает ЛЮБОЙ активный эмфазис; soft-join пропускает ведущие пробелы
строки-продолжения; хвостовые пробелы нерелевантны. Все типы дали 0
расхождений, после чего render_line_to_cache / cc_put / cc_fill /
handle_inline_marker и verify-каркас удалены (−185 строк).
Итог на 52КБ README: 22→11с (2×). Совокупно с прошлым коммитом 24→11с.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Профилирование (52КБ README, раздельный замер): препроцессинг 24с, из них
bank I/O ~0с, cont-walk ~1с — всё время в посимвольных скан-циклах
(индексация 8с + рендер 13с, два прохода по файлу).
- fb() переписана на ассемблере (была закомментированная заготовка): убран
вызов функции и 32-битная арифметика на каждый байт. Раскладка __sdcccall(1)
для uint32 аргумента (p=HLDE) и возврат char в A сверены через sdcc -S;
координация маппинга с bank_read держится на том, что _io_page_w3 — порт
(__sfr 0xE2), пишем OUT — bank_read читает IN.
- render_line_to_cache: горячий путь обычного текста больше не вызывает
handle_inline_marker (6 аргументов) на каждый символ — только на маркерах
` * _ ~; cc_put заинлайнен. Поведение идентично.
Итого 24→18с. Индекс-скан (8с) лёгкого инлайна не имеет (нет per-char
вызовов). Следующий шаг — merge двух проходов в один.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Горизонтальный скролл (Фаза 5, финал):
- Скроллим по ТИПУ, а не по длине: новый флаг IF_HSCROLL ставится только
на код и таблицы; HR и границы fence (IF_NOWRAP без IF_HSCROLL) не
двигаются. Блок едет целиком, включая строки короче 80.
- Обход бага кодогенерации SDCC z80: `if (n!=g) g=n;` пишет (n-g) вместо n
(SUB сравнения затирает A, store переиспользует испорченный A). Лечится
записью viewport_x ДО сравнения. Минимальный репродьюсер и оба описания
для трекера — в docs/bugs/sdcc-z80-cmp-store-a/ (воспроизводится на чистом
sdcc 4.5, в т.ч. с --no-peep → это кодогенератор, не peephole).
Рендеринг:
- Отступленный fence (```c внутри списка) теперь распознаётся: is_fence_raw
пропускает ведущие пробелы/табы; то же в рендере прячет строку-границу.
- Строки-разделители (HR, ровно 80) больше не участвуют в скролле.
Чистка: удалён мёртвый код (is_fence_delim, get_init_style[_raw], is_cont,
seg_flags). Makefile (mdview/mdview2): iconv UTF-8→CP866 завершается ненулевым
кодом при отбрасывании символов — игнорируем (|| true).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
New examples/mdview2 — render-cache version of mdview: each logical
line is rendered into an EMM (char,attr) buffer once during file load
(interleaved with index_lines()), then scrolling draws straight from
the cache via ESTEX WINREST, with no re-parsing or fb() access in the
steady state. Horizontal scroll still uses the old live-render path
(Phase 5, not yet migrated).
Format and budget were derisked empirically first (tests/winrest):
confirmed ESTEX WINCOPY/WINREST buffer layout and measured EMM free
space, both folded into the implementation.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace per-character wrchar() loops in render_line/fill_row/help screens
with batched BIOS calls (bios_writeattr/bios_fillcharattr), and cache the
per-line index record (idx_get) instead of refetching it ~13 times per
rendered line — each refetch cost two W3 bank switches via bank_read().
Also fixes a pre-existing indexer bug: when word-wrap pushes a token that
starts with an emphasis/code marker (e.g. `_text_`) onto a new line, the
marker got re-scanned a second time during the wrap continuation, flipping
line_style back off and corrupting the rendered attribute of the next
word. Fixed by snapshotting line_style at the last seen space and rolling
back to that snapshot (both the saved continuation style and the live
scan state) when a wrap is taken.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- исправлен rewind до первого non-cont сегмента для continuation
- для quote-потока newline обрабатывается как soft join с пропуском сырого ' > ' маркера
- восстановлен quote-префикс на continuation строках
Co-Authored-By: Oz <oz-agent@warp.dev>
- Quote blocks now join consecutive quote lines into one paragraph with
soft breaks and wrap continuation under quote prefix.
- Empty quote lines ('>' / '> ') act as quote-paragraph separators.
- Nested quote starts ('> > ...') are not merged into the parent text and
stay separate rows.
- Keeps existing inline emphasis handling inside quote content.
Co-Authored-By: Oz <oz-agent@warp.dev>
Replace status-line printf formatting with compact manual decimal rendering
(u16/u8 right-aligned helpers + wrchar/put_str_attr). This removes runtime
printf usage from mdview.c and keeps fixed status columns without stale digits.
Co-Authored-By: Oz <oz-agent@warp.dev>
- List items (UL/OL) can now span multiple source lines: non-marker
lines are joined into the current item as lazy continuation.
- Continuation-line leading indentation is trimmed before joining so
wrapped item text is separated by a single space.
- A single blank line between adjacent list markers is suppressed
(same visual list), while 2+ blank lines still produce a separator.
Co-Authored-By: Oz <oz-agent@warp.dev>
- Paragraph scanning no longer swallows the blank line separating it from
the next block; runs of blank lines collapse to one row. Restores blank
separation between paragraphs, headers and horizontal rules.
- Detect table rows (first non-space char '|') as nowrap segments; they are
no longer merged into surrounding text or each other.
- Continuation (wrapped) rows render content as plain text and are no longer
re-classified, so a wrapped word starting with '-'/'#'/'>' is not mis-drawn
as a list/heading/quote marker.
Co-Authored-By: Oz <oz-agent@warp.dev>
- A trailing backslash before a newline now forces an in-paragraph line
break (like two trailing spaces); render consumes the marker (non-code).
- Add ~~strikethrough~~ inline style (INIT_STYLE_STRIKE / EM_STRIKE),
parsed in inline_scan, the paragraph merger and render, mirroring **.
- Horizontal pan is bounded by the widest nowrap segment on screen, and a
'<' indicator marks hidden content off the left edge.
Co-Authored-By: Oz <oz-agent@warp.dev>
- Index is now an 8-byte record per visible segment in a dedicated EMM
block (idx_get/idx_put), freeing ~11 KB of near RAM and lifting the
old 2048-line cap (dynamic max_lines = index_pages * 2048).
- The per-byte scan keeps the previous segment offset in a near var
(cur_seg_off) and mirrors the last record (cur_rec), so it never reads
the index back from the bank.
- fb()/map_page() are inlined now that there is code headroom, removing
per-byte call + 32-bit argument marshalling overhead.
Co-Authored-By: Oz <oz-agent@warp.dev>
Decode page/offset from the 32-bit offset's bytes to avoid SDCC z80
32-bit shift/mask helpers on the hot path; map_page() uses a cached
file_phys[] table to skip mem_get_page() on every W3 swap.
Behaviour-preserving.
Co-Authored-By: Oz <oz-agent@warp.dev>
- Add fenced code block tracking to the wrap-pass in index_lines().
line_style is reset to PLAIN at every ``` delimiter, and all segs
inside a fenced block get init_style=PLAIN. This prevents emphasis
markers (e.g. _ in __var) inside code blocks from leaking into later
normal text.
- Also carry init_style across wrap continuation segs so that a long
bold/italic line that is wrapped continues with the correct style on
the next segment.
- The fence bitmap pass now only updates in_code[], since init_style is
already set correctly by the wrap pass.
- Split tests/ (libc feature tests) and examples/ (real apps); shared
app.mk in repo root, was examples/example.mk
- libc/io/* split into libc/{conio,env,errno,file,mouse,string,sys,
time,video}/ — clearer module boundaries
- New examples/mdview/: markdown viewer (Phases 1-5 + light nested
lists). Headers (H1-H4), HR, ulist/olist/quote with nesting via
leading spaces, fenced code blocks, inline emphasis (bold/italic/
underscore/code), wrap/unwrap mode with soft wrap (F2), horizontal
pan (← →) with '>' truncation indicator
- libc additions: scroll() in conio (ESTEX SCROLL), strlwr/strupr,
gets() test
- Makefile updates across tests/ for the new shared app.mk path
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
print_hex(uint8_t) was an early bare-metal helper doing exactly what
hex8() in the freshly-ported hex_print.c does (two-digit hex via
putchar()). hex8() is smaller (asm cp/sbc/daa nibble trick, no LUT)
and consistent with the dec8/hex16/dec16/hex32/dec32 family.
• Replaced print_hex() calls with hex8() in examples/banked and
examples/bankedbg.
• Removed libc/stdio/print_hex.c, dropped its prototype from
sprinter.h and its entry from lib/Makefile.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
libc/mem/:
• Split bank_io.c into bank_io_w3.c (existing W3 helpers, base 0xC000,
port 0xE2) and bank_io_w1.c (new mirror through W1, base 0x4000,
port 0xA2). Two .rel files so DCE picks only the needed group:
a W3-only user pulls ~70 bytes instead of all 134. W1 variants are
`--memory tiny`-only (any other mode runs code from W1 or uses W1
for the banked-code segment, swapping it crashes).
• mem_alloc.c: add CF=err checks for mem_free_block and mem_get_page
(were silently ignored), per-function docstrings on alloc/free/
get_page/info, drop the confused "wait wrong order" comment in
mem_info. Header sprinter_mem.h gets matching per-function doc.
libc/stdio/:
• Add hex_print.c (hex8/hex16/hex32, ~26 bytes) and dec_print.c
(dec8/dec16/dec32, ~170 bytes) ported from solid-c STDLIB.ASM.
Replaces the printf("%u"/"%X") wrappers in solid_helpers.c that
dragged in the 3-5 KB printf machinery.
- hex* use the classic cp 10 / sbc 0x69 / daa nibble→ASCII trick;
hex8 self-calls for the high nibble, hex16/hex32 tail-call hex8.
- dec32 is the master routine; dec8/dec16 jump into shared entry
points (__dec_entry3 / __dec_entry5). 32-bit subtract-power-of-10
keeps the high 16 bits in HL alt (shadow set).
- DISCOVERY: ESTEX PUTCHAR ($5B) on our Sprinter build preserves
the main register set + IX but CLOBBERS the shadow set
(BC'/DE'/HL'). solid-c's original code assumed otherwise and
garbled output for values ≥ 6 digits. Fix: save/restore HL alt
around the RST 10 in _dec_emit_or_skip. Documented in
memory/estex_putchar_abi.md.
• file.c: drop stdaux/stdprn (no Sprinter printer API), change
stdin/stdout/stderr fd markers to 0/-1/-2 (positive fds clash with
ESTEX OPEN return values), add TODO header pointing at v2 buffered
FILE rewrite (see docs/TODO.md for the Solid-C reference struct).
bin/sprinter-cc:
• --memory big and --memory huge now always use crt0_banked.s (was:
only with --bank flags), matching docs/memory_modes_implemented.md.
When the user has no --bank flags, generate a tiny stub with
`const uint8_t n_banks = 0;` and assemble bank.s for _bank_pages.
Without this fix, openenv with --memory big could not see the
estex_file_handle symbol exported by crt0_banked.
examples/openenv:
• Add usage of estex_file_handle to confirm the crt0_banked startup-
info is reachable. Local extern decl — keeps the symbol out of
sprinter.h since it only exists in big/huge builds.
examples/dec_test:
• New regression test covering hex8/16/32 and dec8/16/32 across the
interesting boundary values.
.gitignore: add .kilo/ (editor session cache).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>