Commit Graph

74 Commits

Author SHA1 Message Date
Kinneyzhang
f6aa64b3b1 feat: right-edge protrusion — hanging punctuation (C 1.4)
ekp-protrusion enables microtype-style character protrusion at the
right edge: a line ending in fullwidth punctuation (。、」…) hangs
the whitespace half of the glyph past the flush edge — visually
identical to CLREQ line-end punctuation compression — and latin
periods/commas/quotes and soft hyphens protrude by their configured
ratios (ekp-protrusion-ratios).

Mechanics: per-box tail protrusion, folded through trailing space
boxes into a per-gap array; each DP candidate widens its effective
target (lw = width + release), mirrored exactly in the renderer's
per-line effective width and in the C-result reconstruction, so DP,
rendering and both engines stay coherent.  Left-edge protrusion is
documented as out of scope (Emacs cannot render before the line
origin).  ekp-region reserves the protrusion width in auto layouts
(ekp-region-protrusion-reserve).

Off by default; all-zero arrays make it a no-op on the shared path.
C module 1.4: break-with-arrays 12→14 args (tail-protrudes array,
hyphen-protrude scalar), batch vectors 14 elements.

Tests: 59 ERT green (deterministic hang check, flush-when-off,
protrusion C parity); fuzz 300/300.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 21:32:54 +08:00
Kinneyzhang
57a3abe853 feat: alignment modes — ragged-right, ragged-left, center (C 1.3)
ekp-alignment selects the paragraph alignment. Non-justify modes keep
inter-word glue rigid (arrays and class params zeroed at para build)
while the DP gains a per-line flexibility ekp-ragged-stretch-pixel
(default ≈2 em): badness = 100·(shortfall/R)³, so Knuth-Plass still
globally minimizes raggedness — this is \raggedright with a finite
\rightskip stretch, not first-fit.

Rendering distributes each line's leftover by mode: trailing
(ragged-right), split evenly (center), leading (ragged-left); the
spacers are ekp-glue-marked, so buffer roundtrips stay exact.

C module 1.3: set-penalties gains an extra-stretch scalar (reset when
omitted); max_w widens by it, so the prefix-based flexibility picks it
up automatically. Cache keys include alignment and R.

Tests: 56 ERT green incl. per-mode invariants (fit, rigid interior
glue, flush edges, centered leftover ±1px) and four-mode C parity;
fuzz 300/300.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 21:22:19 +08:00
Kinneyzhang
ea96a6dc96 feat: no-break spans, NBSP/WORD JOINER support, verbatim atoms
- text property ekp-no-break turns any span into a rigid typesetting
  atom: no line break inside, no hyphenation, literal spacing (space
  runs inside the span become preserved space boxes instead of
  stretchable glue) — inline code, product names, numbers with units
- character-driven joins: NBSP, NARROW NBSP, FIGURE SPACE keep their
  neighbors together (they are boxes whose adjacent gaps are
  unbreakable and glue-free — the character supplies its spacing);
  WORD JOINER / ZWNBSP attach invisibly like combining marks
- new commands: ekp-no-break-region / ekp-allow-break-region
- overlong atoms fall back to single emergency lines (atomic-run
  handling from the break-permission layer); zero C changes needed

Tests: 52 ERT green incl. atomicity across widths, hyphenation
suppression, NBSP/WJ adjacency sweeps; fuzz 300/300 with C parity.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 21:12:07 +08:00
Kinneyzhang
64eb2f38d5 refactor!: per-gap break permissions — punctuation as first-class boxes
Kinsoku moves from merge-based box attachment to a general break-
permission layer, the foundation for no-break spans, NBSP, verbatim
atoms and punctuation protrusion:

- tokenizer: every CJK char (punctuation included) is its own box;
  the hold/attach machinery is gone.  Fixes two latent bugs: a second
  consecutive closer (字。」) could start a line, and an opener held
  across spaces reordered box content vs the original string
- ekp--str-type: cjk-punct splits into cjk-open (Ps/Pi) / cjk-close
- ekp-para gains breaks-allowed (bool-vector) + forbidden-positions
  (sparse, for C); glue at unbreakable punct gaps is nws, so
  punctuation hugs its content and justification stretch no longer
  opens gaps at 「x or x。
- halfwidth kinsoku: boxes consisting purely of .,;:!?)]}’”»›… may
  not start a line ((&[{‘“«‹ may not end one) — an ASCII comma after
  a CJK char no longer dangles at line start (old behavior violated
  CLREQ)
- DP (elisp 1D, elisp loose 2D, C): forbidden gaps are skipped as
  candidates while the line keeps extending; the emergency fallback
  generalizes from single boxes to atomic runs (no permitted break
  inside), recording real gap counts so multi-box emergency lines
  render correctly
- C module 1.2: ekp-c-break-with-arrays 11→12 args
  (forbidden-positions), batch vectors 12 elements, version gate bumped

Hyphenation improvement: 「Hello / Hello」 previously failed the
word regexp as merged boxes and were never hyphenated; as separate
boxes they hyphenate normally.

Tests: 48 ERT green (split tests migrated to the new box contract;
new unit test for break permissions and a rendered-output kinsoku
sweep across widths); 300-case fuzz 0 failures with C 1.2 parity.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 21:05:50 +08:00
Kinneyzhang
33981a647e docs: describe lossless renderer markers in developer docs
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 20:25:03 +08:00
Kinneyzhang
95ed2b32d1 feat: buffer-level justification — region commands and auto-justify mode
The renderer (shared by both engines) is now lossless: synthesized
glue carries the original text it replaced (ekp-glue), soft line
breaks carry the whitespace swallowed around the break
(ekp-soft-break), break hyphens are marked (ekp-soft-hyphen), and
paragraph-edge whitespace survives as zero-display ekp-hidden text.
Orphaned ekp--combine-glues-and-boxes / ekp--interleave removed.

New ekp-region.el:
- ekp-justify-region / ekp-unjustify-region: in-place justification
  with exact structural restore (character- and property-exact),
  robust to edits made while justified
- ekp-auto-justify-mode: keeps the buffer justified at the window
  width; debounced re-flow on window resize, incremental
  per-paragraph re-justification after edits (served by the
  paragraph cache)
- fix found in live GUI testing: buffer-local members of
  window-size-change-functions receive the WINDOW as argument and
  may run with an unrelated buffer current; the handler now resolves
  window and buffer explicitly (regression test included)

Tests: 47 ERT (36 core + 11 region) passing; 300-case fuzz 0
failures (C/elisp parity unchanged); byte-compile clean with
error-on-warn. Verified interactively in GUI Emacs: justified at
1403px maximized, auto-reflowed to 614px on frame resize.

docs: interactive-use section in readme.md / readme_zh.md
ci: byte-compile list includes ekp-region.el

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 20:23:03 +08:00
Kinneyzhang
d3972fdc26 ci: add GitHub Actions workflow
Two jobs on ubuntu-latest:
- elisp-only matrix (Emacs 29.1 floor + 30.1): byte-compile with
  error-on-warn, then the ERT suite (C-module tests auto-skip)
- C-module job (apt Emacs 29.3): build ekp.so, full ERT suite with
  C/elisp parity tests, then the 300-case property fuzz

Both paths were dry-run in a local ubuntu:24.04 container before
committing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 19:53:40 +08:00
Kinneyzhang
9afe491e1a chore: silence build warnings on non-macOS toolchains
- ekp_hyphen.c: check fgets return when skipping the dictionary
  encoding line (gcc -Wunused-result via glibc fortify); behavior
  unchanged — an empty file already fell through to EOF in the loops
- ekp-utils.el: declare-function for font-info, which does not exist
  in non-window-system builds (emacs-nox); call site is runtime-guarded
  by display-multi-font-p. Keeps byte-compile-error-on-warn green.

Verified: clean gcc build + 36/36 ERT + 300-case fuzz on Ubuntu 24.04
(Emacs 29.3, arm64), clean clang build + 36/36 ERT on macOS (30.2).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 19:53:39 +08:00
Kinneyzhang
112b3a0e52 refactor!: overhaul KP core — correctness, C parity, performance, tests, docs
- fix: ekp-param-set silently reset after first justify (now persists;
  ekp-param-reset added)
- fix: narrow-width CJK returned empty string (data loss); two-pass
  emergency-break strategy guarantees output for any input
- fix: K-P penalties never synced to C module; space-box metrics
  divergence between C and Elisp engines
- fix: para cache ignored ekp-latin-lang (stale hyphenation after
  language switch) and used collision-prone sxhash keys
- fix: fullwidth letters/digits misclassified as CJK punctuation
- fix: combining chars split from their base char in the tokenizer
- fix: punctuation-wrapped words (word!/(word)/word;) never hyphenated
- fix: renderer double-counted stripped space widths; negative glue
  clamped; batch/tty font detection no longer crashes
- feat: real looseness support via (position × line-count) DP
- perf: O(1) line metrics and gap counts via prefix arrays (inner loop
  previously allocated O(n) subsequences → O(n³) total); box measurement
  dedupe; eq fast-path para lookup; prebuilt per-para glue arrays
  → zh justify 7547ms → 96ms (compiled elisp) / 57ms (C);
    range-justify 68.5s → 0.48s / 34ms; C module itself 3–19× faster
- test: 36 batch-safe ERT tests + 300-case property fuzz (C/elisp
  byte-identical output, zero content loss) replacing ad-hoc suite
- docs: readme/readme_zh/DEVELOPER/DEVELOPER_ZH/ekp_c-README rewritten
  to match the implementation; phase handoff in .phrase/phases/

BREAKING: requires Emacs 29.1+; C module must be rebuilt (v1.1, new
arities); ekp-threshold-factor / ekp-flagged-penalty /
ekp-forced-break-penalty removed; Rust module stubs removed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 18:44:02 +08:00
Geekinney
11437cb029
Merge pull request #10 from Kinneyzhang/copilot/fix-issue-9
fix: enforce kinsoku rules for CJK opening punctuation (Fixes #9)
2026-05-25 12:18:47 +08:00
copilot-swe-agent[bot]
7287bec474
chore: add *.elc to .gitignore and remove accidentally committed .elc
Agent-Logs-Url: https://github.com/Kinneyzhang/emacs-kp/sessions/d05069f4-db64-4601-9816-f582edad4a1b

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-05-24 15:23:13 +00:00
copilot-swe-agent[bot]
50d41ed30f
fix: enforce kinsoku rules for CJK opening punctuation in box splitting
Opening brackets ((, 「, 《, etc.) are now attached to the following
character instead of the preceding one, preventing them from appearing
at the end of a line which violates kinsoku typographic rules.

Fixes #9

Agent-Logs-Url: https://github.com/Kinneyzhang/emacs-kp/sessions/d05069f4-db64-4601-9816-f582edad4a1b

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-05-24 15:22:52 +00:00
Kinneyzhang
caf6576260 update 2026-02-20 11:52:54 +08:00
Geekinney
f7280df9c3
Merge pull request #8 from Kinneyzhang/copilot/analyze-repo-issues
refactor: eliminate code duplication and fix correctness bugs across Elisp and C modules
2026-02-20 11:44:32 +08:00
copilot-swe-agent[bot]
9b89115b5d fix: address code review feedback - improve docstrings and use defalias consistently
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-02-10 12:19:22 +00:00
copilot-swe-agent[bot]
af855e3394 refactor: Linus-style code quality improvements across Elisp and C modules
- Extract shared binary search from duplicate ekp--hyphenate-p/ekp--flagged-p
- Remove duplicate ekp-root-dir definition (shadowed ekp-utils.el version)
- Remove dead ekp-clear-caches from ekp-utils.el (cleared non-existent var)
- Replace hardcoded 'zsh' with shell-file-name for portability
- Deduplicate module reload: shared ekp--module-reload for Rust/C
- Add NULL guard for ekp_global in ekp_paragraph.c (crash prevention)
- Track actual thread count in pool to fix destroy joining wrong count
- Normalize line endings (CRLF→LF) in ekp-utils.el

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-02-10 12:18:00 +00:00
copilot-swe-agent[bot]
ddfa26fafc Initial plan 2026-02-10 12:11:27 +00:00
Kinneyzhang
262b5eefdc Makefile supports multiple plantform 2026-01-26 11:51:19 +08:00
Kinneyzhang
136e53fe8e improve C module 2026-01-26 01:24:47 +08:00
Kinneyzhang
f42c2bda00 delete unnecessary code 2026-01-25 21:32:34 +08:00
copilot-swe-agent[bot]
6d65902933 Fix: preserve all leading spaces in paragraph indentation
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 13:23:00 +00:00
copilot-swe-agent[bot]
5e3571f689 Fix: preserve paragraph indentation, strip only line-break artifact spaces
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 13:09:59 +00:00
copilot-swe-agent[bot]
8e39dc2b83 Fix: DP line metrics now excludes leading/trailing space box widths to match rendering
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 12:55:58 +00:00
copilot-swe-agent[bot]
c60ddb3903 Fix: DP algorithm now excludes leading/trailing space box widths to match rendering behavior
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 12:41:04 +00:00
copilot-swe-agent[bot]
836ff75c89 Refactor: use efficient char list building instead of string concat in loop
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 12:30:08 +00:00
copilot-swe-agent[bot]
5b8a328855 Fix: words with embedded hyphens now split at hyphens instead of using hyphenation algorithm
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 12:28:09 +00:00
copilot-swe-agent[bot]
a855bce99b Initial plan 2026-01-25 12:19:56 +00:00
Kinneyzhang
06e28b078d add test 2026-01-25 20:12:38 +08:00
copilot-swe-agent[bot]
a421926e91 Fix C module single-box line handling order to match Elisp
Bug: C module and Elisp produced different results for same text.

Root cause: Different condition checking order for single-box vs last-line:
- Elisp: single-box check comes BEFORE is-last check
- C: is_last check came BEFORE is_single_box check (now fixed)

When the last line has only one box, Elisp uses single-box calculation
while C was using last-line calculation, resulting in different demerits
and different final breakpoints.

Fix: Moved is_single_box check before is_last check in dp_process_position()
to match Elisp's ekp--dp-compute-line-demerits behavior.

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 12:02:09 +00:00
copilot-swe-agent[bot]
4a84723181 Refactor C module to eliminate duplicate DP logic
Extracted shared DP core algorithm into dp_process_position() function:

1. Added dp_input_t struct - unified input interface for DP algorithm
   - Contains prefix arrays, glue arrays, hyphen info
   - Contains K-P parameters (penalties, ratios)

2. Added dp_is_hyphen() function - unified hyphen position detection
   - Uses O(log n) binary search
   - Replaces is_hyphen_pos() function

3. Added dp_process_position() function - core DP algorithm
   - Processes single start position i, tries all end positions k
   - Contains complete demerits calculation, fitness classification
   - Both entry functions now call this shared core

4. Refactored process_dp_range()
   - Builds temporary glue arrays from ekp_paragraph_t
   - Creates dp_input_t and calls dp_process_position()

5. Refactored ekp_break_with_prefixes()
   - Directly uses input arrays to create dp_input_t
   - Calls dp_process_position() for each position

Benefits:
- Single point of maintenance: DP bugs only need fixing once
- Consistency guaranteed: both paths use identical algorithm
- ~100 lines of duplicate code removed
- Better testability: core algorithm can be tested independently

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 11:55:27 +00:00
copilot-swe-agent[bot]
32021fbe35 Implement Looseness, Threshold Pruning, and Flagged Penalties
Feature 1: Looseness (Complete Implementation)
- Added alt-paths hash table to track alternative paths by (position, line-count)
- Modified DP loop to track all paths reaching each position
- ekp--dp-trace-breaks-with-looseness uses alt-paths to find closest match
- Added ekp--dp-trace-alt-path helper with safety limit

Feature 2: Threshold Pruning
- Added ekp-threshold-factor variable (default 0 = disabled)
- Paths with demerits > best × (1 + factor) are skipped
- Tracks best-end-demerits during DP for pruning decisions

Feature 3: Flagged Penalties (Forced Breaks)
- Added flagged-positions field to ekp-para struct
- Added ekp-flagged-penalty variable (negative = preferred)
- Added ekp--flagged-p with O(log n) binary search
- Modified DP to always accept flagged breaks

Tests:
- ekp-test-unit--hyphenate-p-binary-search
- ekp-test-unit--flagged-p-binary-search
- ekp-test-unit--alt-paths-hash
- ekp-test-unit--threshold-factor
- ekp-test-unit--flagged-penalty
- Updated ekp-test-unit--struct-access for new fields

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 11:35:30 +00:00
copilot-swe-agent[bot]
b70affb9ef Optimize hyphen position lookup O(n)->O(log n) and add named constants
Performance:
- ekp--hyphenate-p: O(n) cl-find -> O(log n) binary search
- is_hyphen_break: O(n) linear -> O(log n) binary search
- is_hyphen_pos: O(n) linear -> O(log n) binary search

In O(n²) DP loop, this reduces worst-case complexity from O(n³) to O(n² log n)

Code quality:
- Add ekp-consecutive-hyphen-penalty (was hardcoded 100)
- Add ekp-forced-break-penalty (was hardcoded 10000)
- Add ekp-last-line-short-penalty (was hardcoded 50)
- Update ekp-looseness docstring noting partial implementation

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 11:15:42 +00:00
copilot-swe-agent[bot]
fb58a9b19a Fix remaining global glue param usages in DP and glue distribution functions
Code review found additional functions using global glue params instead
of para's stored params:
- ekp--compute-stretch-capacity: now takes para param
- ekp--compute-shrink-capacity: now takes para param
- ekp--line-badness-and-fitness: now takes para param
- ekp--dp-compute-line-demerits: now takes para param
- ekp--distribute-gap-adjustment: now takes para param

All capacity/distribution calculations now use para's stored glue params
for full consistency across multi-font paragraphs.

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 11:03:27 +00:00
copilot-swe-agent[bot]
333618bb57 Fix glue parameter caching inconsistency for multi-font paragraphs
When multiple paragraphs with different fonts were processed, subsequent
executions would use wrong glue parameters from the cache. This caused
misalignment because different fonts have different spacing values.

Changes:
- Add glue-params field to ekp-para struct to store params at creation
- Add helper functions: ekp--para-glue-ideal/shrink/stretch/min/max
- Update all C module interface functions to use para's stored params
- Update all glue computation functions for consistency

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 10:52:45 +00:00
copilot-swe-agent[bot]
fee05f769d Fix C module to match Elisp behavior for last-line overflow handling
When is_last && ideal > line_width, the C module now correctly
triggers force break logic, matching ekp--dp-cache-elisp behavior.
This ensures consistent results between C module and pure Elisp paths.

Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2026-01-25 10:32:06 +00:00
copilot-swe-agent[bot]
b296de0928 Initial plan 2026-01-25 10:25:46 +00:00
Kinneyzhang
a790aa87c3 update 2026-01-25 18:23:33 +08:00
Kinneyzhang
68ca9b191a improve C module parallel 2026-01-25 17:28:04 +08:00
Kinneyzhang
6cf6f75f71 fix bugs of C moudule 2026-01-25 16:53:23 +08:00
Kinneyzhang
aaeea099c9 fix bug 2026-01-25 15:11:47 +08:00
Kinneyzhang
c88bbdd395 add dynamic moudle to improve prefermance 2026-01-25 13:50:46 +08:00
Kinneyzhang
91d9bbc1e9 process spaces between words 2026-01-25 01:17:18 +08:00
Kinneyzhang
6cf17e0066 update knuth-plass paper link 2026-01-24 22:46:48 +08:00
Kinneyzhang
6421f6b1fb refactor ekp cache and code improve 2026-01-24 22:40:53 +08:00
Kinneyzhang
68b46f8337 code improve 2026-01-24 20:44:38 +08:00
copilot-swe-agent[bot]
dab9ca280e Add optional use-cache parameter to ekp-pixel-justify and ekp-pixel-range-justify
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2025-11-29 17:56:42 +00:00
copilot-swe-agent[bot]
c4240fe15c Initial plan 2025-11-29 17:54:24 +00:00
copilot-swe-agent[bot]
f56ec5a520 Fix ekp-text-hash to consider text properties
Co-authored-by: Kinneyzhang <38454496+Kinneyzhang@users.noreply.github.com>
2025-11-29 17:09:16 +00:00
copilot-swe-agent[bot]
5c646bf6be Initial plan 2025-11-29 17:06:09 +00:00
Kinneyzhang
ca9349e99f fix bug when text is blank string 2025-09-26 00:18:37 +08:00