A Python rewrite of chenglou/pretext – fast, accurate, and concise text measurement and layout.
Pretext-py brings the powerful text layout engine from the original JavaScript library to Python. It excels at precise line breaking, character segmentation, and advanced typographic control, making it ideal for applications that require complex text rendering (e.g., editorial design, dynamic typesetting, and creative coding).
This project depends on my other library: intl-segmenter-py.
Due to current technical limitations, setting custom locales is not yet supported. However, you can provide your own Segmenter implementation – see custom_segmenter.md for details.
If you have any insights on how to fully replicate the Intl.Segmenter API in Python, please reach out – contributions and suggestions are welcome!
The default implementation uses pygame (located in pretext_py/py_canvas) and is intentionally kept minimal. For production use, you should replace it with your own measurement function. Refer to custom_canvas.md for guidance.
Currently, only two tests in pretext_py/layout_test.py are failing. The discrepancies stem from minor differences between the built‑in Intl.Segmenter and its JavaScript counterpart – these will be addressed in future updates.
Two examples have been ported so far:
- dragon_fast.py – Due to font constraints and Pygame limitations, some scripts (e.g., Arabic, emoji) may not render perfectly.
- editorial_engine.py – Renders beautifully with impressive visual quality, showcasing the full potential of the layout engine.
Pretext-py 是 chenglou/pretext 的 Python 重写版本,专注于快速、精确且简洁的文本测量与排版。它适用于需要复杂文本布局的场景,如编辑设计、动态排版和创意编程。
本项目使用了我的另一个库:intl-segmenter-py。
由于技术原因,目前尚不支持设置自定义 locales,但我们提供了自定义 Segmenter 的接口,详见 custom_segmenter.md。
如果您有关于完整实现 Intl.Segmenter 的任何信息或建议,欢迎告知!
默认实现位于 pretext_py/py_canvas,基于 pygame 提供了最简单的测量功能。在实际项目中,建议您替换为自己的测量函数,具体方法请参考 custom_canvas.md。
目前 pretext_py/layout_test.py 中仅有 两个测试用例未通过,原因是内置的 Intl.Segmenter 与 JavaScript 版本仍存在细微差异,后续将持续优化。
目前已移植两个示例:
- dragon_fast.py – 受字体和 Pygame 限制,部分字符(如阿拉伯文、emoji)可能渲染不完美。
- editorial_engine.py – 渲染效果出色,视觉效果极佳,充分展示了排版引擎的能力。


