@xincli/opentui-core 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (476) hide show
  1. package/README.md +63 -0
  2. package/dev/keypress-debug-renderer.ts +148 -0
  3. package/dev/keypress-debug.ts +43 -0
  4. package/dev/print-env-vars.ts +32 -0
  5. package/dev/test-tmux-graphics-334.sh +68 -0
  6. package/dev/test-tmux-theme-queries.sh +151 -0
  7. package/dev/thai-debug-test.ts +68 -0
  8. package/dev/theme-mode.ts +290 -0
  9. package/docs/development.md +144 -0
  10. package/package.json +102 -0
  11. package/prebuilt/aarch64-android/libopentui.so +0 -0
  12. package/scripts/build-android.ts +226 -0
  13. package/scripts/build-native-termux.sh +525 -0
  14. package/scripts/build.ts +530 -0
  15. package/scripts/dist-test.ts +312 -0
  16. package/scripts/package-prebuilt.ts +110 -0
  17. package/scripts/publish.ts +60 -0
  18. package/scripts/test-node-hook.mjs +16 -0
  19. package/scripts/test-node.ts +241 -0
  20. package/scripts/vendor-deps.sh +73 -0
  21. package/src/NativeSpanFeed.ts +375 -0
  22. package/src/Renderable.ts +1878 -0
  23. package/src/__snapshots__/buffer.test.ts.snap +28 -0
  24. package/src/animation/Timeline.test.ts +2709 -0
  25. package/src/animation/Timeline.ts +598 -0
  26. package/src/ansi.ts +22 -0
  27. package/src/audio.ts +479 -0
  28. package/src/benchmark/attenuation-benchmark.ts +81 -0
  29. package/src/benchmark/audio-playback-benchmark.ts +344 -0
  30. package/src/benchmark/box-draw-benchmark.ts +1042 -0
  31. package/src/benchmark/colormatrix-benchmark.ts +123 -0
  32. package/src/benchmark/gain-benchmark.ts +80 -0
  33. package/src/benchmark/latest-all-bench-run.json +707 -0
  34. package/src/benchmark/latest-async-bench-run.json +336 -0
  35. package/src/benchmark/latest-default-bench-run.json +657 -0
  36. package/src/benchmark/latest-large-bench-run.json +707 -0
  37. package/src/benchmark/latest-quick-bench-run.json +207 -0
  38. package/src/benchmark/layout-benchmark.ts +2547 -0
  39. package/src/benchmark/markdown-benchmark.ts +1796 -0
  40. package/src/benchmark/native-span-feed-async-benchmark.ts +355 -0
  41. package/src/benchmark/native-span-feed-benchmark.md +56 -0
  42. package/src/benchmark/native-span-feed-benchmark.ts +596 -0
  43. package/src/benchmark/native-span-feed-compare.ts +280 -0
  44. package/src/benchmark/render-traversal-benchmark.ts +928 -0
  45. package/src/benchmark/text-buffer-render-benchmark.ts +874 -0
  46. package/src/benchmark/text-table-benchmark.ts +948 -0
  47. package/src/buffer.test.ts +292 -0
  48. package/src/buffer.ts +564 -0
  49. package/src/console.test.ts +629 -0
  50. package/src/console.ts +1253 -0
  51. package/src/edit-buffer.test.ts +1852 -0
  52. package/src/edit-buffer.ts +417 -0
  53. package/src/editor-view.test.ts +1056 -0
  54. package/src/editor-view.ts +290 -0
  55. package/src/index.ts +25 -0
  56. package/src/lib/KeyHandler.integration.test.ts +292 -0
  57. package/src/lib/KeyHandler.stopPropagation.test.ts +289 -0
  58. package/src/lib/KeyHandler.test.ts +662 -0
  59. package/src/lib/KeyHandler.ts +222 -0
  60. package/src/lib/RGBA.test.ts +60 -0
  61. package/src/lib/RGBA.ts +343 -0
  62. package/src/lib/ascii.font.ts +330 -0
  63. package/src/lib/border.test.ts +83 -0
  64. package/src/lib/border.ts +170 -0
  65. package/src/lib/bunfs.test.ts +27 -0
  66. package/src/lib/bunfs.ts +18 -0
  67. package/src/lib/clipboard.test.ts +63 -0
  68. package/src/lib/clipboard.ts +41 -0
  69. package/src/lib/clock.ts +35 -0
  70. package/src/lib/data-paths.test.ts +133 -0
  71. package/src/lib/data-paths.ts +109 -0
  72. package/src/lib/debounce.ts +106 -0
  73. package/src/lib/detect-links.test.ts +98 -0
  74. package/src/lib/detect-links.ts +56 -0
  75. package/src/lib/env.test.ts +228 -0
  76. package/src/lib/env.ts +209 -0
  77. package/src/lib/extmarks-history.ts +51 -0
  78. package/src/lib/extmarks-multiwidth.test.ts +324 -0
  79. package/src/lib/extmarks.test.ts +3547 -0
  80. package/src/lib/extmarks.ts +861 -0
  81. package/src/lib/fonts/block.json +405 -0
  82. package/src/lib/fonts/grid.json +265 -0
  83. package/src/lib/fonts/huge.json +741 -0
  84. package/src/lib/fonts/pallet.json +314 -0
  85. package/src/lib/fonts/shade.json +591 -0
  86. package/src/lib/fonts/slick.json +321 -0
  87. package/src/lib/fonts/tiny.json +69 -0
  88. package/src/lib/hast-styled-text.ts +59 -0
  89. package/src/lib/index.ts +22 -0
  90. package/src/lib/keybinding.internal.test.ts +342 -0
  91. package/src/lib/keybinding.internal.ts +182 -0
  92. package/src/lib/objects-in-viewport.test.ts +789 -0
  93. package/src/lib/objects-in-viewport.ts +153 -0
  94. package/src/lib/output.capture.ts +58 -0
  95. package/src/lib/parse.keypress-kitty.protocol.test.ts +347 -0
  96. package/src/lib/parse.keypress-kitty.test.ts +712 -0
  97. package/src/lib/parse.keypress-kitty.ts +470 -0
  98. package/src/lib/parse.keypress.test.ts +2020 -0
  99. package/src/lib/parse.keypress.ts +480 -0
  100. package/src/lib/parse.mouse.test.ts +552 -0
  101. package/src/lib/parse.mouse.ts +232 -0
  102. package/src/lib/paste.ts +18 -0
  103. package/src/lib/queue.ts +65 -0
  104. package/src/lib/render-geometry.ts +36 -0
  105. package/src/lib/renderable.validations.test.ts +87 -0
  106. package/src/lib/renderable.validations.ts +83 -0
  107. package/src/lib/scroll-acceleration.ts +98 -0
  108. package/src/lib/selection.ts +261 -0
  109. package/src/lib/singleton.ts +34 -0
  110. package/src/lib/stdin-parser.test.ts +2439 -0
  111. package/src/lib/stdin-parser.ts +2007 -0
  112. package/src/lib/styled-text.ts +178 -0
  113. package/src/lib/terminal-capability-detection.test.ts +226 -0
  114. package/src/lib/terminal-capability-detection.ts +98 -0
  115. package/src/lib/terminal-palette.test.ts +954 -0
  116. package/src/lib/terminal-palette.ts +441 -0
  117. package/src/lib/tree-sitter/assets/README.md +119 -0
  118. package/src/lib/tree-sitter/assets/javascript/highlights.scm +205 -0
  119. package/src/lib/tree-sitter/assets/javascript/tree-sitter-javascript.wasm +0 -0
  120. package/src/lib/tree-sitter/assets/markdown/highlights.scm +150 -0
  121. package/src/lib/tree-sitter/assets/markdown/injections.scm +27 -0
  122. package/src/lib/tree-sitter/assets/markdown/tree-sitter-markdown.wasm +0 -0
  123. package/src/lib/tree-sitter/assets/markdown_inline/highlights.scm +115 -0
  124. package/src/lib/tree-sitter/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  125. package/src/lib/tree-sitter/assets/typescript/highlights.scm +604 -0
  126. package/src/lib/tree-sitter/assets/typescript/tree-sitter-typescript.wasm +0 -0
  127. package/src/lib/tree-sitter/assets/update.ts +360 -0
  128. package/src/lib/tree-sitter/assets/zig/highlights.scm +284 -0
  129. package/src/lib/tree-sitter/assets/zig/tree-sitter-zig.wasm +0 -0
  130. package/src/lib/tree-sitter/assets.d.ts +9 -0
  131. package/src/lib/tree-sitter/cache.test.ts +291 -0
  132. package/src/lib/tree-sitter/client.test.ts +1434 -0
  133. package/src/lib/tree-sitter/client.ts +847 -0
  134. package/src/lib/tree-sitter/default-parsers.ts +133 -0
  135. package/src/lib/tree-sitter/download-utils.ts +148 -0
  136. package/src/lib/tree-sitter/index.ts +75 -0
  137. package/src/lib/tree-sitter/parser.worker.ts +1098 -0
  138. package/src/lib/tree-sitter/parsers-config.ts +81 -0
  139. package/src/lib/tree-sitter/resolve-ft.test.ts +55 -0
  140. package/src/lib/tree-sitter/resolve-ft.ts +189 -0
  141. package/src/lib/tree-sitter/types.ts +132 -0
  142. package/src/lib/tree-sitter/update-assets.ts +10 -0
  143. package/src/lib/tree-sitter-styled-text.test.ts +1253 -0
  144. package/src/lib/tree-sitter-styled-text.ts +314 -0
  145. package/src/lib/validate-dir-name.ts +55 -0
  146. package/src/lib/yoga.options.test.ts +628 -0
  147. package/src/lib/yoga.options.ts +346 -0
  148. package/src/native-event-worker-repro.test.ts +48 -0
  149. package/src/native-event-worker-repro.worker.ts +9 -0
  150. package/src/native-handle.test.ts +221 -0
  151. package/src/platform/ffi.test.ts +516 -0
  152. package/src/platform/ffi.ts +653 -0
  153. package/src/platform/runtime.test.ts +52 -0
  154. package/src/platform/runtime.ts +121 -0
  155. package/src/platform/test.ts +45 -0
  156. package/src/platform/worker-handler-cleanup.fixture.ts +12 -0
  157. package/src/platform/worker-onmessage-startup.fixture.ts +10 -0
  158. package/src/platform/worker-startup.fixture.ts +9 -0
  159. package/src/platform/worker.node-test.ts +153 -0
  160. package/src/platform/worker.ts +425 -0
  161. package/src/plugins/core-slot.ts +579 -0
  162. package/src/plugins/registry.ts +402 -0
  163. package/src/plugins/types.ts +46 -0
  164. package/src/post/effects.ts +948 -0
  165. package/src/post/filters.ts +512 -0
  166. package/src/post/matrices.ts +288 -0
  167. package/src/renderables/ASCIIFont.ts +219 -0
  168. package/src/renderables/Box.test.ts +474 -0
  169. package/src/renderables/Box.ts +353 -0
  170. package/src/renderables/Code.test.ts +2388 -0
  171. package/src/renderables/Code.ts +555 -0
  172. package/src/renderables/Diff.regression.test.ts +381 -0
  173. package/src/renderables/Diff.test.ts +3212 -0
  174. package/src/renderables/Diff.ts +1278 -0
  175. package/src/renderables/EditBufferRenderable.test.ts +288 -0
  176. package/src/renderables/EditBufferRenderable.ts +1152 -0
  177. package/src/renderables/FrameBuffer.ts +47 -0
  178. package/src/renderables/Input.test.ts +1310 -0
  179. package/src/renderables/Input.ts +273 -0
  180. package/src/renderables/LineNumberRenderable.ts +725 -0
  181. package/src/renderables/Markdown.ts +2144 -0
  182. package/src/renderables/ScrollBar.ts +423 -0
  183. package/src/renderables/ScrollBox.ts +903 -0
  184. package/src/renderables/Select.test.ts +1134 -0
  185. package/src/renderables/Select.ts +535 -0
  186. package/src/renderables/Slider.test.ts +456 -0
  187. package/src/renderables/Slider.ts +342 -0
  188. package/src/renderables/TabSelect.test.ts +238 -0
  189. package/src/renderables/TabSelect.ts +447 -0
  190. package/src/renderables/Text.selection-buffer.test.ts +118 -0
  191. package/src/renderables/Text.test.ts +2662 -0
  192. package/src/renderables/Text.ts +147 -0
  193. package/src/renderables/TextBufferRenderable.ts +504 -0
  194. package/src/renderables/TextNode.test.ts +1137 -0
  195. package/src/renderables/TextNode.ts +379 -0
  196. package/src/renderables/TextTable.test.ts +1411 -0
  197. package/src/renderables/TextTable.ts +1434 -0
  198. package/src/renderables/Textarea.ts +425 -0
  199. package/src/renderables/TimeToFirstDraw.ts +89 -0
  200. package/src/renderables/__snapshots__/Code.test.ts.snap +13 -0
  201. package/src/renderables/__snapshots__/Diff.test.ts.snap +785 -0
  202. package/src/renderables/__snapshots__/Text.test.ts.snap +421 -0
  203. package/src/renderables/__snapshots__/TextTable.test.ts.snap +215 -0
  204. package/src/renderables/__tests__/Code.test.ts +55 -0
  205. package/src/renderables/__tests__/LineNumberRenderable.scrollbox-simple.test.ts +144 -0
  206. package/src/renderables/__tests__/LineNumberRenderable.scrollbox.test.ts +827 -0
  207. package/src/renderables/__tests__/LineNumberRenderable.test.ts +1906 -0
  208. package/src/renderables/__tests__/LineNumberRenderable.wrapping.test.ts +85 -0
  209. package/src/renderables/__tests__/Markdown.code-colors.test.ts +288 -0
  210. package/src/renderables/__tests__/Markdown.test.ts +4175 -0
  211. package/src/renderables/__tests__/MultiRenderable.selection.test.ts +87 -0
  212. package/src/renderables/__tests__/Textarea.buffer.test.ts +683 -0
  213. package/src/renderables/__tests__/Textarea.destroyed-events.test.ts +675 -0
  214. package/src/renderables/__tests__/Textarea.editing.test.ts +2120 -0
  215. package/src/renderables/__tests__/Textarea.error-handling.test.ts +35 -0
  216. package/src/renderables/__tests__/Textarea.events.test.ts +738 -0
  217. package/src/renderables/__tests__/Textarea.highlights.test.ts +590 -0
  218. package/src/renderables/__tests__/Textarea.keybinding.test.ts +3275 -0
  219. package/src/renderables/__tests__/Textarea.paste.test.ts +357 -0
  220. package/src/renderables/__tests__/Textarea.rendering.test.ts +1927 -0
  221. package/src/renderables/__tests__/Textarea.scroll.test.ts +733 -0
  222. package/src/renderables/__tests__/Textarea.selection.test.ts +1589 -0
  223. package/src/renderables/__tests__/Textarea.stress.test.ts +670 -0
  224. package/src/renderables/__tests__/Textarea.undo-redo.test.ts +383 -0
  225. package/src/renderables/__tests__/Textarea.visual-lines.test.ts +310 -0
  226. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.code.test.ts.snap +221 -0
  227. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox-simple.test.ts.snap +89 -0
  228. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.scrollbox.test.ts.snap +457 -0
  229. package/src/renderables/__tests__/__snapshots__/LineNumberRenderable.test.ts.snap +158 -0
  230. package/src/renderables/__tests__/__snapshots__/Textarea.rendering.test.ts.snap +387 -0
  231. package/src/renderables/__tests__/markdown-parser.test.ts +241 -0
  232. package/src/renderables/__tests__/renderable-test-utils.ts +60 -0
  233. package/src/renderables/composition/README.md +8 -0
  234. package/src/renderables/composition/VRenderable.ts +32 -0
  235. package/src/renderables/composition/constructs.ts +127 -0
  236. package/src/renderables/composition/vnode.ts +277 -0
  237. package/src/renderables/index.ts +23 -0
  238. package/src/renderables/markdown-parser.ts +79 -0
  239. package/src/renderer-theme-mode.ts +199 -0
  240. package/src/renderer.ts +4975 -0
  241. package/src/runtime-plugin-support-configure.ts +63 -0
  242. package/src/runtime-plugin-support.ts +13 -0
  243. package/src/runtime-plugin.ts +626 -0
  244. package/src/specs/terminal-startup.md +64 -0
  245. package/src/syntax-style.test.ts +841 -0
  246. package/src/syntax-style.ts +274 -0
  247. package/src/testing/README.md +219 -0
  248. package/src/testing/bun-test-node.ts +880 -0
  249. package/src/testing/capture-spans.test.ts +216 -0
  250. package/src/testing/integration.test.ts +276 -0
  251. package/src/testing/manual-clock.ts +117 -0
  252. package/src/testing/mock-keys.test.ts +1378 -0
  253. package/src/testing/mock-keys.ts +457 -0
  254. package/src/testing/mock-mouse.test.ts +218 -0
  255. package/src/testing/mock-mouse.ts +247 -0
  256. package/src/testing/mock-tree-sitter-client.ts +81 -0
  257. package/src/testing/spy.ts +13 -0
  258. package/src/testing/terminal-capabilities.ts +47 -0
  259. package/src/testing/test-recorder.test.ts +410 -0
  260. package/src/testing/test-recorder.ts +133 -0
  261. package/src/testing/test-renderer.ts +375 -0
  262. package/src/testing/test-renderer.wait.test.ts +278 -0
  263. package/src/testing/test-streams.ts +31 -0
  264. package/src/testing.ts +9 -0
  265. package/src/tests/__snapshots__/absolute-positioning.snapshot.test.ts.snap +481 -0
  266. package/src/tests/__snapshots__/renderable.snapshot.test.ts.snap +19 -0
  267. package/src/tests/__snapshots__/scrollbox.test.ts.snap +29 -0
  268. package/src/tests/absolute-positioning.snapshot.test.ts +638 -0
  269. package/src/tests/allocator-stats.test.ts +53 -0
  270. package/src/tests/audio.test.ts +303 -0
  271. package/src/tests/destroy-during-render.test.ts +200 -0
  272. package/src/tests/destroy-on-exit.fixture.ts +36 -0
  273. package/src/tests/destroy-on-exit.test.ts +62 -0
  274. package/src/tests/ffi-borrowed-pointer-callsites.test.ts +153 -0
  275. package/src/tests/hover-cursor.test.ts +98 -0
  276. package/src/tests/native-backed-measurement-lifecycle.test.ts +133 -0
  277. package/src/tests/native-backed-measurement-parity.test.ts +322 -0
  278. package/src/tests/native-span-feed-async.test.ts +173 -0
  279. package/src/tests/native-span-feed-close.test.ts +120 -0
  280. package/src/tests/native-span-feed-coverage.test.ts +227 -0
  281. package/src/tests/native-span-feed-edge-cases.test.ts +384 -0
  282. package/src/tests/native-span-feed-use-after-free.test.ts +45 -0
  283. package/src/tests/opacity.test.ts +123 -0
  284. package/src/tests/renderable.snapshot.test.ts +524 -0
  285. package/src/tests/renderable.test.ts +1851 -0
  286. package/src/tests/renderer.clock.test.ts +270 -0
  287. package/src/tests/renderer.console-startup.test.ts +2151 -0
  288. package/src/tests/renderer.control.test.ts +458 -0
  289. package/src/tests/renderer.core-slot-binding.test.ts +962 -0
  290. package/src/tests/renderer.cursor.test.ts +26 -0
  291. package/src/tests/renderer.custom-stdout.test.ts +1112 -0
  292. package/src/tests/renderer.destroy-during-render.test.ts +147 -0
  293. package/src/tests/renderer.focus-restore.test.ts +257 -0
  294. package/src/tests/renderer.focus.test.ts +329 -0
  295. package/src/tests/renderer.idle.test.ts +219 -0
  296. package/src/tests/renderer.input.test.ts +2615 -0
  297. package/src/tests/renderer.kitty-flags.test.ts +195 -0
  298. package/src/tests/renderer.lifecycle.test.ts +34 -0
  299. package/src/tests/renderer.mouse.test.ts +1315 -0
  300. package/src/tests/renderer.notifications.test.ts +27 -0
  301. package/src/tests/renderer.palette.test.ts +1199 -0
  302. package/src/tests/renderer.remote.test.ts +247 -0
  303. package/src/tests/renderer.render-stats.test.ts +146 -0
  304. package/src/tests/renderer.scrollback-surface.test.ts +474 -0
  305. package/src/tests/renderer.selection.test.ts +138 -0
  306. package/src/tests/renderer.slot-registry.test.ts +684 -0
  307. package/src/tests/renderer.tracker.test.ts +202 -0
  308. package/src/tests/renderer.useMouse.test.ts +83 -0
  309. package/src/tests/runtime-plugin-node-modules-cycle.fixture.ts +76 -0
  310. package/src/tests/runtime-plugin-node-modules-import-like-string.fixture.ts +48 -0
  311. package/src/tests/runtime-plugin-node-modules-mjs.fixture.ts +43 -0
  312. package/src/tests/runtime-plugin-node-modules-no-bare-rewrite.fixture.ts +67 -0
  313. package/src/tests/runtime-plugin-node-modules-package-type-cache.fixture.ts +72 -0
  314. package/src/tests/runtime-plugin-node-modules-runtime-specifier.fixture.ts +44 -0
  315. package/src/tests/runtime-plugin-node-modules-scoped-package-bare-rewrite.fixture.ts +85 -0
  316. package/src/tests/runtime-plugin-path-alias.fixture.ts +43 -0
  317. package/src/tests/runtime-plugin-resolve-roots.fixture.ts +65 -0
  318. package/src/tests/runtime-plugin-support-configure.fixture.ts +31 -0
  319. package/src/tests/runtime-plugin-support-late-addition.fixture.ts +17 -0
  320. package/src/tests/runtime-plugin-support.fixture.ts +11 -0
  321. package/src/tests/runtime-plugin-support.test.ts +54 -0
  322. package/src/tests/runtime-plugin-windows-file-url.fixture.ts +30 -0
  323. package/src/tests/runtime-plugin.fixture.ts +40 -0
  324. package/src/tests/runtime-plugin.test.ts +369 -0
  325. package/src/tests/scrollbox-culling-bug.test.ts +114 -0
  326. package/src/tests/scrollbox-hitgrid-resize.test.ts +136 -0
  327. package/src/tests/scrollbox-hitgrid.test.ts +909 -0
  328. package/src/tests/scrollbox.test.ts +1895 -0
  329. package/src/tests/wrap-resize-perf.test.ts +276 -0
  330. package/src/tests/yoga-api-coverage.test.ts +409 -0
  331. package/src/tests/yoga-callback-stress.test.ts +122 -0
  332. package/src/tests/yoga-ffi.test.ts +117 -0
  333. package/src/tests/yoga-setters.test.ts +921 -0
  334. package/src/tests/yoga-upstream/YGAlignBaselineTest.test.ts +124 -0
  335. package/src/tests/yoga-upstream/YGComputedBorderTest.test.ts +27 -0
  336. package/src/tests/yoga-upstream/YGComputedMarginTest.test.ts +27 -0
  337. package/src/tests/yoga-upstream/YGComputedPaddingTest.test.ts +27 -0
  338. package/src/tests/yoga-upstream/YGDirtiedTest.test.ts +157 -0
  339. package/src/tests/yoga-upstream/YGErrataTest.test.ts +40 -0
  340. package/src/tests/yoga-upstream/YGFlexBasisAuto.test.ts +23 -0
  341. package/src/tests/yoga-upstream/YGHasNewLayout.test.ts +81 -0
  342. package/src/tests/yoga-upstream/YGMeasureCacheTest.test.ts +31 -0
  343. package/src/tests/yoga-upstream/YGMeasureTest.test.ts +70 -0
  344. package/src/tests/yoga-upstream/generated/YGAbsolutePositionTest.test.ts +1864 -0
  345. package/src/tests/yoga-upstream/generated/YGAlignContentTest.test.ts +5829 -0
  346. package/src/tests/yoga-upstream/generated/YGAlignItemsTest.test.ts +2444 -0
  347. package/src/tests/yoga-upstream/generated/YGAlignSelfTest.test.ts +293 -0
  348. package/src/tests/yoga-upstream/generated/YGAndroidNewsFeed.test.ts +315 -0
  349. package/src/tests/yoga-upstream/generated/YGAspectRatioTest.test.ts +231 -0
  350. package/src/tests/yoga-upstream/generated/YGAutoTest.test.ts +347 -0
  351. package/src/tests/yoga-upstream/generated/YGBorderTest.test.ts +256 -0
  352. package/src/tests/yoga-upstream/generated/YGBoxSizingTest.test.ts +2747 -0
  353. package/src/tests/yoga-upstream/generated/YGDimensionTest.test.ts +129 -0
  354. package/src/tests/yoga-upstream/generated/YGDisplayContentsTest.test.ts +109 -0
  355. package/src/tests/yoga-upstream/generated/YGDisplayTest.test.ts +1097 -0
  356. package/src/tests/yoga-upstream/generated/YGFlexDirectionTest.test.ts +4562 -0
  357. package/src/tests/yoga-upstream/generated/YGFlexTest.test.ts +677 -0
  358. package/src/tests/yoga-upstream/generated/YGFlexWrapTest.test.ts +2071 -0
  359. package/src/tests/yoga-upstream/generated/YGGapTest.test.ts +3303 -0
  360. package/src/tests/yoga-upstream/generated/YGIntrinsicSizeTest.test.ts +582 -0
  361. package/src/tests/yoga-upstream/generated/YGJustifyContentTest.test.ts +2150 -0
  362. package/src/tests/yoga-upstream/generated/YGMarginTest.test.ts +1963 -0
  363. package/src/tests/yoga-upstream/generated/YGMinMaxDimensionTest.test.ts +1446 -0
  364. package/src/tests/yoga-upstream/generated/YGPaddingTest.test.ts +354 -0
  365. package/src/tests/yoga-upstream/generated/YGPercentageTest.test.ts +1760 -0
  366. package/src/tests/yoga-upstream/generated/YGRoundingTest.test.ts +1161 -0
  367. package/src/tests/yoga-upstream/generated/YGSizeOverflowTest.test.ts +207 -0
  368. package/src/tests/yoga-upstream/generated/YGStaticPositionTest.test.ts +6338 -0
  369. package/src/tests/yoga-upstream/tools/MeasureCounter.ts +54 -0
  370. package/src/tests/yoga-upstream/tools/utils.ts +81 -0
  371. package/src/text-buffer-view.test.ts +722 -0
  372. package/src/text-buffer-view.ts +193 -0
  373. package/src/text-buffer.test.ts +512 -0
  374. package/src/text-buffer.ts +250 -0
  375. package/src/types.ts +199 -0
  376. package/src/utils.ts +88 -0
  377. package/src/yoga.ts +1146 -0
  378. package/src/zig/ansi.zig +502 -0
  379. package/src/zig/audio.zig +1206 -0
  380. package/src/zig/bench/README.md +50 -0
  381. package/src/zig/bench/buffer-color-blending_bench.zig +350 -0
  382. package/src/zig/bench/buffer-draw-box_bench.zig +786 -0
  383. package/src/zig/bench/buffer-draw-text-buffer_bench.zig +894 -0
  384. package/src/zig/bench/edit-buffer_bench.zig +476 -0
  385. package/src/zig/bench/editor-view_bench.zig +169 -0
  386. package/src/zig/bench/native-span-feed_bench.zig +107 -0
  387. package/src/zig/bench/rope-markers_bench.zig +713 -0
  388. package/src/zig/bench/rope_bench.zig +514 -0
  389. package/src/zig/bench/styled-text_bench.zig +476 -0
  390. package/src/zig/bench/text-buffer-coords_bench.zig +362 -0
  391. package/src/zig/bench/text-buffer-view_bench.zig +459 -0
  392. package/src/zig/bench/text-chunk-graphemes_bench.zig +272 -0
  393. package/src/zig/bench/utf8_bench.zig +799 -0
  394. package/src/zig/bench-utils.zig +431 -0
  395. package/src/zig/bench.zig +223 -0
  396. package/src/zig/buffer-methods.zig +215 -0
  397. package/src/zig/buffer.zig +2515 -0
  398. package/src/zig/build.zig +700 -0
  399. package/src/zig/build.zig.zon +19 -0
  400. package/src/zig/edit-buffer.zig +900 -0
  401. package/src/zig/editor-view.zig +812 -0
  402. package/src/zig/event-bus.zig +28 -0
  403. package/src/zig/event-emitter.zig +65 -0
  404. package/src/zig/file-logger.zig +92 -0
  405. package/src/zig/grapheme.zig +838 -0
  406. package/src/zig/handles.zig +267 -0
  407. package/src/zig/lib.zig +2813 -0
  408. package/src/zig/link.zig +349 -0
  409. package/src/zig/logger.zig +43 -0
  410. package/src/zig/mem-registry.zig +126 -0
  411. package/src/zig/miniaudio_shim.c +21 -0
  412. package/src/zig/native-renderable.zig +112 -0
  413. package/src/zig/native-span-feed-bench-lib.zig +7 -0
  414. package/src/zig/native-span-feed.zig +747 -0
  415. package/src/zig/renderer-output.zig +677 -0
  416. package/src/zig/renderer.zig +2106 -0
  417. package/src/zig/rope.zig +1220 -0
  418. package/src/zig/split-scrollback.zig +88 -0
  419. package/src/zig/syntax-style.zig +174 -0
  420. package/src/zig/terminal.zig +1652 -0
  421. package/src/zig/test.zig +82 -0
  422. package/src/zig/tests/README.md +18 -0
  423. package/src/zig/tests/ansi_test.zig +18 -0
  424. package/src/zig/tests/audio_test.zig +439 -0
  425. package/src/zig/tests/buffer-methods_test.zig +1111 -0
  426. package/src/zig/tests/buffer_test.zig +2926 -0
  427. package/src/zig/tests/edit-buffer-history_test.zig +299 -0
  428. package/src/zig/tests/edit-buffer_test.zig +1688 -0
  429. package/src/zig/tests/editor-view_test.zig +3454 -0
  430. package/src/zig/tests/event-emitter_test.zig +249 -0
  431. package/src/zig/tests/grapheme_test.zig +1329 -0
  432. package/src/zig/tests/handles_test.zig +123 -0
  433. package/src/zig/tests/link_test.zig +220 -0
  434. package/src/zig/tests/mem-registry_test.zig +473 -0
  435. package/src/zig/tests/memory_leak_regression_test.zig +234 -0
  436. package/src/zig/tests/native-renderable_test.zig +16 -0
  437. package/src/zig/tests/native-span-feed_test.zig +1266 -0
  438. package/src/zig/tests/renderer_test.zig +2604 -0
  439. package/src/zig/tests/rope-nested_test.zig +712 -0
  440. package/src/zig/tests/rope_fuzz_test.zig +238 -0
  441. package/src/zig/tests/rope_test.zig +2362 -0
  442. package/src/zig/tests/segment-merge.test.zig +148 -0
  443. package/src/zig/tests/split-scrollback_test.zig +70 -0
  444. package/src/zig/tests/syntax-style_test.zig +558 -0
  445. package/src/zig/tests/terminal_test.zig +1489 -0
  446. package/src/zig/tests/test-renderer.zig +126 -0
  447. package/src/zig/tests/text-buffer-drawing_test.zig +3291 -0
  448. package/src/zig/tests/text-buffer-highlights_test.zig +706 -0
  449. package/src/zig/tests/text-buffer-iterators_test.zig +776 -0
  450. package/src/zig/tests/text-buffer-segment_test.zig +320 -0
  451. package/src/zig/tests/text-buffer-selection_test.zig +1056 -0
  452. package/src/zig/tests/text-buffer-selection_viewport_test.zig +358 -0
  453. package/src/zig/tests/text-buffer-view_test.zig +3672 -0
  454. package/src/zig/tests/text-buffer_test.zig +2191 -0
  455. package/src/zig/tests/unicode-width-map.zon +3909 -0
  456. package/src/zig/tests/utf8_no_zwj_test.zig +260 -0
  457. package/src/zig/tests/utf8_test.zig +4060 -0
  458. package/src/zig/tests/utf8_wcwidth_cursor_test.zig +267 -0
  459. package/src/zig/tests/utf8_wcwidth_test.zig +357 -0
  460. package/src/zig/tests/word-wrap-editing_test.zig +498 -0
  461. package/src/zig/tests/wrap-cache-perf_test.zig +113 -0
  462. package/src/zig/tests/yoga_test.zig +65 -0
  463. package/src/zig/text-buffer-iterators.zig +496 -0
  464. package/src/zig/text-buffer-segment.zig +403 -0
  465. package/src/zig/text-buffer-view.zig +1428 -0
  466. package/src/zig/text-buffer.zig +1272 -0
  467. package/src/zig/utf8.zig +1954 -0
  468. package/src/zig/utils.zig +12 -0
  469. package/src/zig/uucode-stub.zig +76 -0
  470. package/src/zig/vendor/miniaudio/miniaudio.h +93468 -0
  471. package/src/zig/yoga.zig +658 -0
  472. package/src/zig-structs.ts +381 -0
  473. package/src/zig.ts +5260 -0
  474. package/tsconfig.build.json +17 -0
  475. package/tsconfig.json +27 -0
  476. package/tsconfig.node-test.json +138 -0
@@ -0,0 +1,1272 @@
1
+ const std = @import("std");
2
+ const Allocator = std.mem.Allocator;
3
+ const seg_mod = @import("text-buffer-segment.zig");
4
+ const iter_mod = @import("text-buffer-iterators.zig");
5
+ const mem_registry_mod = @import("mem-registry.zig");
6
+ const ss = @import("syntax-style.zig");
7
+ const gp = @import("grapheme.zig");
8
+ const ansi = @import("ansi.zig");
9
+ const link = @import("link.zig");
10
+
11
+ const utf8 = @import("utf8.zig");
12
+ const utils = @import("utils.zig");
13
+
14
+ const logger = @import("logger.zig");
15
+
16
+ const Segment = seg_mod.Segment;
17
+ const UnifiedRope = seg_mod.UnifiedRope;
18
+ const LineInfo = iter_mod.LineInfo;
19
+
20
+ // Re-export types from segment module
21
+ pub const TextChunk = seg_mod.TextChunk;
22
+ pub const MemRegistry = mem_registry_mod.MemRegistry;
23
+ pub const RGBA = seg_mod.RGBA;
24
+ pub const TextSelection = seg_mod.TextSelection;
25
+ pub const TextBufferError = seg_mod.TextBufferError;
26
+ pub const Highlight = seg_mod.Highlight;
27
+ pub const StyleSpan = seg_mod.StyleSpan;
28
+ pub const WrapMode = seg_mod.WrapMode;
29
+ pub const ChunkFitResult = seg_mod.ChunkFitResult;
30
+ pub const GraphemeInfo = seg_mod.GraphemeInfo;
31
+
32
+ pub const SyntaxStyle = ss.SyntaxStyle;
33
+
34
+ pub const TextBuffer = UnifiedTextBuffer;
35
+
36
+ /// A styled text chunk passed from TypeScript across the FFI boundary.
37
+ /// Each chunk carries raw text bytes, optional packed RGBA colors, text
38
+ /// attributes, and an optional hyperlink URL.
39
+ ///
40
+ /// The color pointers point to 4 consecutive u16 values in the packed RGBA
41
+ /// format defined by ansi.zig. Use utils.ptrToRGBA to read them.
42
+ pub const StyledChunk = extern struct {
43
+ text_ptr: [*]const u8,
44
+ text_len: usize,
45
+ /// Optional foreground color as 4 packed u16 values (see ansi.RGBA).
46
+ fg_ptr: ?[*]const u16,
47
+ /// Optional background color as 4 packed u16 values (see ansi.RGBA).
48
+ bg_ptr: ?[*]const u16,
49
+ attributes: u32,
50
+ link_ptr: ?[*]const u8 = null,
51
+ link_len: usize = 0,
52
+ };
53
+
54
+ pub const UnifiedTextBuffer = struct {
55
+ const Self = UnifiedTextBuffer;
56
+
57
+ mem_registry: MemRegistry,
58
+ default_fg: ?RGBA,
59
+ default_bg: ?RGBA,
60
+ default_attributes: ?u32,
61
+
62
+ allocator: Allocator,
63
+ global_allocator: Allocator,
64
+ arena: *std.heap.ArenaAllocator,
65
+
66
+ _rope: UnifiedRope,
67
+ syntax_style: ?*const SyntaxStyle,
68
+
69
+ pool: *gp.GraphemePool,
70
+ link_pool: *link.LinkPool,
71
+ link_tracker: ?link.LinkTracker,
72
+
73
+ width_method: utf8.WidthMethod,
74
+
75
+ view_dirty_flags: std.ArrayListUnmanaged(bool),
76
+ next_view_id: u32,
77
+ free_view_ids: std.ArrayListUnmanaged(u32),
78
+
79
+ /// Monotonic counter that increments on every content change. Views use this
80
+ /// to detect stale caches even after clearViewDirty() runs.
81
+ content_epoch: u64,
82
+
83
+ // Per-line highlight cache (invalidated on edits)
84
+ // Maps line_idx to highlights for that line
85
+ line_highlights: std.ArrayListUnmanaged(std.ArrayListUnmanaged(Highlight)),
86
+ line_spans: std.ArrayListUnmanaged(std.ArrayListUnmanaged(StyleSpan)),
87
+ internal_highlight_count: usize,
88
+ highlight_batch_depth: u32,
89
+ dirty_span_lines: std.AutoHashMap(usize, void),
90
+
91
+ styled_text_mem_id: ?u8,
92
+ styled_buffer: ?[]u8,
93
+ styled_capacity: usize,
94
+
95
+ tab_width: u8,
96
+
97
+ pub const Defaults = struct {
98
+ fg: ?RGBA,
99
+ bg: ?RGBA,
100
+ attributes: ?u32,
101
+ };
102
+
103
+ /// Accessor: return default fg/bg/attributes as a struct.
104
+ pub fn defaults(self: *const Self) Defaults {
105
+ return .{
106
+ .fg = self.default_fg,
107
+ .bg = self.default_bg,
108
+ .attributes = self.default_attributes,
109
+ };
110
+ }
111
+
112
+ /// Accessor: return a const pointer to the mem registry.
113
+ pub fn memRegistry(self: *const Self) *const MemRegistry {
114
+ return &self.mem_registry;
115
+ }
116
+
117
+ /// Accessor: return the width method.
118
+ pub fn widthMethod(self: *const Self) utf8.WidthMethod {
119
+ return self.width_method;
120
+ }
121
+
122
+ /// Accessor: return tab width.
123
+ pub fn tabWidth(self: *const Self) u8 {
124
+ return self.tab_width;
125
+ }
126
+
127
+ /// Accessor: return the internal allocator.
128
+ pub fn getAllocator(self: *const Self) Allocator {
129
+ return self.allocator;
130
+ }
131
+
132
+ /// Accessor: return pointer to the rope (for edit-path callers).
133
+ /// Const-preserving: returns *UnifiedRope or *const UnifiedRope depending on receiver.
134
+ pub fn rope(self: anytype) blk: {
135
+ const T = @TypeOf(self);
136
+ break :blk if (T == *Self) *UnifiedRope else if (T == *const Self) *const UnifiedRope else @compileError("expected *Self or *const Self");
137
+ } {
138
+ return &self._rope;
139
+ }
140
+
141
+ /// Accessor: get line width at a given row.
142
+ pub fn lineWidthAt(self: *const Self, row: u32) u32 {
143
+ return iter_mod.lineWidthAt(@constCast(&self._rope), row);
144
+ }
145
+
146
+ /// Accessor: get maximum line width across all lines.
147
+ pub fn lineWidthColsMax(self: *const Self) u32 {
148
+ return iter_mod.getMaxLineWidth(&self._rope);
149
+ }
150
+
151
+ pub fn getGraphemeWidthAt(self: *const Self, row: u32, col: u32) u32 {
152
+ return iter_mod.getGraphemeWidthAt(@constCast(&self._rope), &self.mem_registry, row, col, self.tab_width, self.width_method);
153
+ }
154
+
155
+ pub fn getPrevGraphemeWidth(self: *const Self, row: u32, col: u32) u32 {
156
+ return iter_mod.getPrevGraphemeWidth(@constCast(&self._rope), &self.mem_registry, row, col, self.tab_width, self.width_method);
157
+ }
158
+
159
+ pub fn getWrapOffsetsFor(self: *const Self, chunk: *const TextChunk) TextBufferError![]const utf8.WrapBreak {
160
+ return chunk.getWrapOffsets(self.allocator, &self.mem_registry, self.width_method);
161
+ }
162
+
163
+ /// Accessor: walk all lines and segments via callbacks.
164
+ pub fn walkLinesAndSegments(
165
+ self: *const Self,
166
+ ctx: *anyopaque,
167
+ segment_callback: *const fn (ctx: *anyopaque, line_idx: u32, chunk: *const TextChunk, chunk_idx_in_line: u32) void,
168
+ line_end_callback: *const fn (ctx: *anyopaque, line_info: LineInfo) void,
169
+ ) void {
170
+ iter_mod.walkLinesAndSegments(&self._rope, ctx, segment_callback, line_end_callback);
171
+ }
172
+
173
+ pub fn init(
174
+ global_allocator: Allocator,
175
+ pool: *gp.GraphemePool,
176
+ link_pool: *link.LinkPool,
177
+ width_method: utf8.WidthMethod,
178
+ ) TextBufferError!*Self {
179
+ const self = global_allocator.create(Self) catch return TextBufferError.OutOfMemory;
180
+ errdefer global_allocator.destroy(self);
181
+
182
+ const internal_arena = global_allocator.create(std.heap.ArenaAllocator) catch return TextBufferError.OutOfMemory;
183
+ errdefer global_allocator.destroy(internal_arena);
184
+ internal_arena.* = std.heap.ArenaAllocator.init(global_allocator);
185
+
186
+ const internal_allocator = internal_arena.allocator();
187
+
188
+ const init_rope = UnifiedRope.init(internal_allocator) catch return TextBufferError.OutOfMemory;
189
+
190
+ var view_dirty_flags: std.ArrayListUnmanaged(bool) = .{};
191
+ errdefer view_dirty_flags.deinit(global_allocator);
192
+
193
+ var free_view_ids: std.ArrayListUnmanaged(u32) = .{};
194
+ errdefer free_view_ids.deinit(global_allocator);
195
+
196
+ var mem_registry = MemRegistry.init(global_allocator);
197
+ errdefer mem_registry.deinit();
198
+
199
+ var dirty_span_lines = std.AutoHashMap(usize, void).init(global_allocator);
200
+ errdefer dirty_span_lines.deinit();
201
+
202
+ self.* = .{
203
+ .mem_registry = mem_registry,
204
+ .default_fg = null,
205
+ .default_bg = null,
206
+ .default_attributes = null,
207
+ .allocator = internal_allocator,
208
+ .global_allocator = global_allocator,
209
+ .arena = internal_arena,
210
+ ._rope = init_rope,
211
+ .syntax_style = null,
212
+ .pool = pool,
213
+ .link_pool = link_pool,
214
+ .link_tracker = null,
215
+ .width_method = width_method,
216
+ .view_dirty_flags = view_dirty_flags,
217
+ .next_view_id = 0,
218
+ .free_view_ids = free_view_ids,
219
+ .content_epoch = 0,
220
+ .line_highlights = .{},
221
+ .line_spans = .{},
222
+ .internal_highlight_count = 0,
223
+ .highlight_batch_depth = 0,
224
+ .dirty_span_lines = dirty_span_lines,
225
+ .styled_text_mem_id = null,
226
+ .styled_buffer = null,
227
+ .styled_capacity = 0,
228
+ .tab_width = 2,
229
+ };
230
+
231
+ return self;
232
+ }
233
+
234
+ pub fn deinit(self: *Self) void {
235
+ const global_allocator = self.global_allocator;
236
+ defer global_allocator.destroy(self);
237
+
238
+ if (self.syntax_style) |style| {
239
+ (@constCast(style)).offDestroy(@ptrCast(self), onSyntaxStyleDestroyed);
240
+ }
241
+
242
+ self.view_dirty_flags.deinit(self.global_allocator);
243
+ self.free_view_ids.deinit(self.global_allocator);
244
+
245
+ // Free highlight/span caches
246
+ for (self.line_highlights.items) |*hl_list| {
247
+ hl_list.deinit(self.global_allocator);
248
+ }
249
+ self.line_highlights.deinit(self.global_allocator);
250
+
251
+ for (self.line_spans.items) |*span_list| {
252
+ span_list.deinit(self.global_allocator);
253
+ }
254
+ self.line_spans.deinit(self.global_allocator);
255
+
256
+ // Free dirty span lines hashmap
257
+ self.dirty_span_lines.deinit();
258
+
259
+ // Free persistent styled text buffer
260
+ if (self.styled_buffer) |buf| {
261
+ self.global_allocator.free(buf);
262
+ }
263
+
264
+ if (self.link_tracker) |*tracker| {
265
+ tracker.deinit();
266
+ }
267
+
268
+ self.mem_registry.deinit();
269
+ self.arena.deinit();
270
+ global_allocator.destroy(self.arena);
271
+ self.* = undefined;
272
+ }
273
+
274
+ // View registration (same as original)
275
+ pub fn registerView(self: *Self) TextBufferError!u32 {
276
+ if (self.free_view_ids.items.len > 0) {
277
+ const id = self.free_view_ids.items[self.free_view_ids.items.len - 1];
278
+ _ = self.free_view_ids.pop();
279
+ self.view_dirty_flags.items[id] = true;
280
+ return id;
281
+ }
282
+
283
+ const id = self.next_view_id;
284
+ self.next_view_id += 1;
285
+ try self.view_dirty_flags.append(self.global_allocator, true);
286
+ return id;
287
+ }
288
+
289
+ pub fn unregisterView(self: *Self, view_id: u32) void {
290
+ if (view_id < self.view_dirty_flags.items.len) {
291
+ self.free_view_ids.append(self.global_allocator, view_id) catch {};
292
+ }
293
+ }
294
+
295
+ pub fn isViewDirty(self: *const Self, view_id: u32) bool {
296
+ if (view_id < self.view_dirty_flags.items.len) {
297
+ return self.view_dirty_flags.items[view_id];
298
+ }
299
+ return false;
300
+ }
301
+
302
+ pub fn clearViewDirty(self: *Self, view_id: u32) void {
303
+ if (view_id < self.view_dirty_flags.items.len) {
304
+ self.view_dirty_flags.items[view_id] = false;
305
+ }
306
+ }
307
+
308
+ /// Returns the current content epoch. Use this to detect buffer changes
309
+ /// independent of the dirty flag (other code paths may clear dirty).
310
+ pub fn getContentEpoch(self: *const Self) u64 {
311
+ return self.content_epoch;
312
+ }
313
+
314
+ fn markAllViewsDirty(self: *Self) void {
315
+ // Increment epoch first so views see the new value when checking caches.
316
+ // Use wrapping add for safety, though u64 won't overflow in practice.
317
+ self.content_epoch +%= 1;
318
+ for (self.view_dirty_flags.items) |*flag| {
319
+ flag.* = true;
320
+ }
321
+ }
322
+
323
+ pub fn markViewsDirty(self: *Self) void {
324
+ self.markAllViewsDirty();
325
+ }
326
+
327
+ // Basic queries using unified rope
328
+ pub fn getLength(self: *const Self) u32 {
329
+ const metrics = self._rope.root.metrics();
330
+ return metrics.custom.total_width;
331
+ }
332
+
333
+ pub fn getByteSize(self: *const Self) u32 {
334
+ const metrics = self._rope.root.metrics();
335
+ const total_bytes = metrics.custom.total_bytes;
336
+
337
+ // Add newlines between lines (line_count - 1)
338
+ const line_count = iter_mod.getLineCount(&self._rope);
339
+ if (line_count > 0) {
340
+ return total_bytes + (line_count - 1); // newlines
341
+ }
342
+ return total_bytes;
343
+ }
344
+
345
+ pub fn measureText(self: *const Self, text: []const u8) u32 {
346
+ // For grapheme-accurate width calculation (used by highlighting system),
347
+ // use utf8.calculateTextWidth which properly handles grapheme clusters
348
+ const is_ascii = utf8.isAsciiOnly(text);
349
+ return utf8.calculateTextWidth(text, self.tab_width, is_ascii, self.width_method);
350
+ }
351
+
352
+ /// Clear the text content without resetting arena or memory registry.
353
+ /// Preserves highlights, memory buffers, and arena allocations.
354
+ /// Use this for frequent text updates where undo/redo history should be preserved.
355
+ pub fn clear(self: *Self) void {
356
+ self.clearLinkRefs();
357
+ self._rope.clear();
358
+ self.markAllViewsDirty();
359
+ }
360
+
361
+ pub fn reset(self: *Self) void {
362
+ self.clearLinkRefs();
363
+
364
+ // Free highlight/span arrays (they use global_allocator, not arena)
365
+ for (self.line_highlights.items) |*hl_list| {
366
+ hl_list.deinit(self.global_allocator);
367
+ }
368
+ self.line_highlights.clearRetainingCapacity();
369
+ self.internal_highlight_count = 0;
370
+
371
+ for (self.line_spans.items) |*span_list| {
372
+ span_list.deinit(self.global_allocator);
373
+ }
374
+ self.line_spans.clearRetainingCapacity();
375
+
376
+ // Free persistent styled text buffer
377
+ if (self.styled_buffer) |buf| {
378
+ self.global_allocator.free(buf);
379
+ }
380
+ self.styled_buffer = null;
381
+ self.styled_text_mem_id = null;
382
+ self.styled_capacity = 0;
383
+
384
+ // Now reset the arena (frees all the internal memory)
385
+ _ = self.arena.reset(if (self.arena.queryCapacity() > 0) .retain_capacity else .free_all);
386
+
387
+ self.mem_registry.clear();
388
+
389
+ self._rope = UnifiedRope.init(self.allocator) catch return;
390
+
391
+ self.markAllViewsDirty();
392
+ }
393
+
394
+ // Default colors/attributes
395
+ pub fn setDefaultFg(self: *Self, fg: ?RGBA) void {
396
+ self.default_fg = fg;
397
+ }
398
+
399
+ pub fn setDefaultBg(self: *Self, bg: ?RGBA) void {
400
+ self.default_bg = bg;
401
+ }
402
+
403
+ pub fn setDefaultAttributes(self: *Self, attributes: ?u32) void {
404
+ self.default_attributes = attributes;
405
+ }
406
+
407
+ pub fn resetDefaults(self: *Self) void {
408
+ self.default_fg = null;
409
+ self.default_bg = null;
410
+ self.default_attributes = null;
411
+ }
412
+
413
+ fn onSyntaxStyleDestroyed(ctx_ptr: *anyopaque) void {
414
+ const self = @as(*Self, @ptrCast(@alignCast(ctx_ptr)));
415
+ self.syntax_style = null;
416
+ }
417
+
418
+ pub fn setSyntaxStyle(self: *Self, syntax_style: ?*const SyntaxStyle) void {
419
+ if (self.syntax_style == syntax_style) return;
420
+
421
+ if (syntax_style) |style| {
422
+ (@constCast(style)).onDestroy(@ptrCast(self), onSyntaxStyleDestroyed) catch return;
423
+ }
424
+ if (self.syntax_style) |prev| {
425
+ (@constCast(prev)).offDestroy(@ptrCast(self), onSyntaxStyleDestroyed);
426
+ }
427
+ self.syntax_style = syntax_style;
428
+ }
429
+
430
+ pub fn getSyntaxStyle(self: *const Self) ?*const SyntaxStyle {
431
+ return self.syntax_style;
432
+ }
433
+
434
+ fn getLinkTracker(self: *Self) *link.LinkTracker {
435
+ if (self.link_tracker == null) {
436
+ self.link_tracker = link.LinkTracker.init(self.global_allocator, self.link_pool);
437
+ }
438
+
439
+ return &self.link_tracker.?;
440
+ }
441
+
442
+ fn clearLinkRefs(self: *Self) void {
443
+ if (self.link_tracker) |*tracker| {
444
+ tracker.clear();
445
+ }
446
+ }
447
+
448
+ /// Set the text content using SIMD-optimized line break detection
449
+ pub fn setText(self: *Self, text: []const u8) TextBufferError!void {
450
+ self.clearInternalHighlights();
451
+ self.clear();
452
+ const mem_id = try self.mem_registry.register(text, false);
453
+ try self.setTextInternal(mem_id, text);
454
+ }
455
+
456
+ /// Set text from a pre-registered memory ID
457
+ pub fn setTextFromMemId(self: *Self, mem_id: u8) TextBufferError!void {
458
+ const text = self.mem_registry.get(mem_id) orelse return TextBufferError.InvalidMemId;
459
+ self.clearInternalHighlights();
460
+ self.clear();
461
+ try self.setTextInternal(mem_id, text);
462
+ }
463
+
464
+ /// Append text to the end of the buffer without clearing
465
+ pub fn append(self: *Self, text: []const u8) TextBufferError!void {
466
+ if (text.len == 0) {
467
+ return;
468
+ }
469
+
470
+ const mem_id = try self.mem_registry.register(text, false);
471
+ try self.appendInternal(mem_id, text);
472
+ }
473
+
474
+ /// Append text from a pre-registered memory ID
475
+ pub fn appendFromMemId(self: *Self, mem_id: u8) TextBufferError!void {
476
+ const text = self.mem_registry.get(mem_id) orelse return TextBufferError.InvalidMemId;
477
+ try self.appendInternal(mem_id, text);
478
+ }
479
+
480
+ /// Internal append that doesn't register memory
481
+ fn appendInternal(self: *Self, mem_id: u8, text: []const u8) TextBufferError!void {
482
+ if (text.len == 0) {
483
+ return;
484
+ }
485
+
486
+ // The rope's boundary rewrite will handle normalization at join points
487
+ var result = try self.textToSegments(self.global_allocator, text, mem_id, 0, false);
488
+ defer result.segments.deinit(result.allocator);
489
+
490
+ const insert_pos = self._rope.count();
491
+ try self._rope.insert_slice(insert_pos, result.segments.items);
492
+
493
+ self.markAllViewsDirty();
494
+ }
495
+
496
+ /// Internal setText that doesn't call clear (for use by setStyledText)
497
+ fn setTextInternal(self: *Self, mem_id: u8, text: []const u8) TextBufferError!void {
498
+ if (text.len == 0) {
499
+ self.markAllViewsDirty();
500
+ return;
501
+ }
502
+
503
+ var result = try self.textToSegments(self.global_allocator, text, mem_id, 0, true);
504
+ defer result.segments.deinit(result.allocator);
505
+
506
+ try self._rope.setSegments(result.segments.items);
507
+
508
+ self.markAllViewsDirty();
509
+ }
510
+
511
+ /// Create a TextChunk from a memory buffer range
512
+ pub fn createChunk(
513
+ self: *const Self,
514
+ mem_id: u8,
515
+ byte_start: u32,
516
+ byte_end: u32,
517
+ ) TextChunk {
518
+ const mem_buf = self.mem_registry.get(mem_id).?;
519
+ const chunk_bytes = mem_buf[byte_start..byte_end];
520
+ const is_ascii = utf8.isAsciiOnly(chunk_bytes);
521
+
522
+ var flags: u8 = 0;
523
+ if (chunk_bytes.len > 0 and is_ascii) {
524
+ flags |= TextChunk.Flags.ASCII_ONLY;
525
+ }
526
+
527
+ const chunk_width: u16 = @intCast(@min(65535, utf8.calculateTextWidth(chunk_bytes, self.tab_width, is_ascii, self.width_method)));
528
+
529
+ return .{
530
+ .mem_id = mem_id,
531
+ .byte_start = byte_start,
532
+ .byte_end = byte_end,
533
+ .width = chunk_width,
534
+ .flags = flags,
535
+ };
536
+ }
537
+
538
+ /// Convert text to segments with line breaks
539
+ /// Returns segments array and total width
540
+ pub fn textToSegments(
541
+ self: *const Self,
542
+ allocator: Allocator,
543
+ text: []const u8,
544
+ mem_id: u8,
545
+ byte_offset: u32,
546
+ prepend_linestart: bool,
547
+ ) TextBufferError!struct { segments: std.ArrayListUnmanaged(Segment), total_width: u32, allocator: Allocator } {
548
+ var break_result = utf8.LineBreakResult.init(allocator);
549
+ defer break_result.deinit();
550
+ try utf8.findLineBreaks(text, &break_result);
551
+
552
+ var segments: std.ArrayListUnmanaged(Segment) = .{};
553
+ errdefer segments.deinit(allocator);
554
+
555
+ if (prepend_linestart) {
556
+ try segments.append(allocator, .{ .linestart = {} });
557
+ }
558
+
559
+ var local_start: u32 = 0;
560
+ var total_width: u32 = 0;
561
+
562
+ for (break_result.breaks.items) |line_break| {
563
+ const break_pos: u32 = @intCast(line_break.pos);
564
+ const local_end: u32 = switch (line_break.kind) {
565
+ .CRLF => break_pos - 1,
566
+ .CR, .LF => break_pos,
567
+ };
568
+
569
+ if (local_end > local_start) {
570
+ const chunk = self.createChunk(mem_id, byte_offset + local_start, byte_offset + local_end);
571
+ try segments.append(allocator, .{ .text = chunk });
572
+ total_width += chunk.width;
573
+ }
574
+
575
+ try segments.append(allocator, .{ .brk = {} });
576
+ try segments.append(allocator, .{ .linestart = {} });
577
+
578
+ local_start = break_pos + 1;
579
+ }
580
+
581
+ if (local_start < text.len) {
582
+ const chunk = self.createChunk(mem_id, byte_offset + local_start, byte_offset + @as(u32, @intCast(text.len)));
583
+ try segments.append(allocator, .{ .text = chunk });
584
+ total_width += chunk.width;
585
+ }
586
+
587
+ return .{ .segments = segments, .total_width = total_width, .allocator = allocator };
588
+ }
589
+
590
+ pub fn getLineCount(self: *const Self) u32 {
591
+ const count = self._rope.count();
592
+ if (count == 0) return 0; // Truly empty (after reset)
593
+ return iter_mod.getLineCount(&self._rope);
594
+ }
595
+
596
+ pub fn lineCount(self: *const Self) u32 {
597
+ return self.getLineCount();
598
+ }
599
+
600
+ /// Register a memory buffer
601
+ pub fn registerMemBuffer(self: *Self, data: []const u8, owned: bool) TextBufferError!u8 {
602
+ return self.mem_registry.register(data, owned);
603
+ }
604
+
605
+ pub fn replaceMemBuffer(self: *Self, mem_id: u8, data: []const u8, owned: bool) TextBufferError!void {
606
+ try self.mem_registry.replace(mem_id, data, owned);
607
+ }
608
+
609
+ pub fn clearMemRegistry(self: *Self) void {
610
+ self.mem_registry.clear();
611
+ }
612
+
613
+ pub fn getMemBuffer(self: *const Self, mem_id: u8) ?[]const u8 {
614
+ return self.mem_registry.get(mem_id);
615
+ }
616
+
617
+ /// Add a line from a memory buffer (for compatibility with old API)
618
+ /// Note: This is not as efficient as setText for bulk operations
619
+ /// Adds text segment with a break separator before it (if not the first line)
620
+ pub fn addLine(
621
+ self: *Self,
622
+ mem_id: u8,
623
+ byte_start: u32,
624
+ byte_end: u32,
625
+ ) TextBufferError!void {
626
+ _ = self.mem_registry.get(mem_id) orelse return TextBufferError.InvalidMemId;
627
+
628
+ const chunk = self.createChunk(mem_id, byte_start, byte_end);
629
+
630
+ const had_content = self._rope.count() > 1;
631
+
632
+ if (had_content) {
633
+ try self._rope.append(.{ .brk = {} });
634
+ try self._rope.append(.{ .linestart = {} });
635
+ }
636
+
637
+ try self._rope.append(.{ .text = chunk });
638
+
639
+ self.markAllViewsDirty();
640
+ }
641
+
642
+ pub fn getArenaAllocatedBytes(self: *const Self) usize {
643
+ return self.arena.queryCapacity();
644
+ }
645
+
646
+ /// Extract all text as UTF-8 bytes into provided output buffer
647
+ pub fn getPlainTextIntoBuffer(self: *const Self, out_buffer: []u8) usize {
648
+ var out_index: usize = 0;
649
+
650
+ const line_count = self.getLineCount();
651
+
652
+ const Context = struct {
653
+ buffer: *const UnifiedTextBuffer,
654
+ out_buffer: []u8,
655
+ out_index: *usize,
656
+ line_count: u32,
657
+
658
+ fn segmentCallback(ctx_ptr: *anyopaque, line_idx: u32, chunk: *const TextChunk, chunk_idx_in_line: u32) void {
659
+ _ = line_idx;
660
+ _ = chunk_idx_in_line;
661
+ const ctx = @as(*@This(), @ptrCast(@alignCast(ctx_ptr)));
662
+ const chunk_bytes = chunk.getBytes(&ctx.buffer.mem_registry);
663
+ const copy_len = @min(chunk_bytes.len, ctx.out_buffer.len - ctx.out_index.*);
664
+ if (copy_len > 0) {
665
+ @memcpy(ctx.out_buffer[ctx.out_index.* .. ctx.out_index.* + copy_len], chunk_bytes[0..copy_len]);
666
+ ctx.out_index.* += copy_len;
667
+ }
668
+ }
669
+
670
+ fn lineEndCallback(ctx_ptr: *anyopaque, line_info: LineInfo) void {
671
+ const ctx = @as(*@This(), @ptrCast(@alignCast(ctx_ptr)));
672
+ // Add newline between lines (not after last line)
673
+ if (ctx.line_count > 0 and line_info.line_idx < ctx.line_count - 1 and ctx.out_index.* < ctx.out_buffer.len) {
674
+ ctx.out_buffer[ctx.out_index.*] = '\n';
675
+ ctx.out_index.* += 1;
676
+ }
677
+ }
678
+ };
679
+
680
+ var ctx: Context = .{
681
+ .buffer = self,
682
+ .out_buffer = out_buffer,
683
+ .out_index = &out_index,
684
+ .line_count = line_count,
685
+ };
686
+ self.walkLinesAndSegments(&ctx, Context.segmentCallback, Context.lineEndCallback);
687
+
688
+ return out_index;
689
+ }
690
+
691
+ pub fn startHighlightsTransaction(self: *Self) void {
692
+ self.highlight_batch_depth += 1;
693
+ }
694
+
695
+ pub fn endHighlightsTransaction(self: *Self) void {
696
+ if (self.highlight_batch_depth == 0) return;
697
+
698
+ self.highlight_batch_depth -= 1;
699
+
700
+ if (self.highlight_batch_depth == 0) {
701
+ var it = self.dirty_span_lines.keyIterator();
702
+ while (it.next()) |line_idx| {
703
+ self.rebuildLineSpans(line_idx.*) catch {};
704
+ }
705
+ self.dirty_span_lines.clearRetainingCapacity();
706
+ }
707
+ }
708
+
709
+ fn markLineSpansDirty(self: *Self, line_idx: usize) void {
710
+ self.dirty_span_lines.put(line_idx, {}) catch {};
711
+ }
712
+
713
+ // Highlight system
714
+ fn ensureLineHighlightStorage(self: *Self, line_idx: usize) TextBufferError!void {
715
+ while (self.line_highlights.items.len <= line_idx) {
716
+ try self.line_highlights.append(self.global_allocator, .{});
717
+ }
718
+ while (self.line_spans.items.len <= line_idx) {
719
+ try self.line_spans.append(self.global_allocator, .{});
720
+ }
721
+ }
722
+
723
+ pub fn addHighlight(
724
+ self: *Self,
725
+ line_idx: usize,
726
+ col_start: u32,
727
+ col_end: u32,
728
+ style_id: u32,
729
+ priority: u8,
730
+ hl_ref: u16,
731
+ ) TextBufferError!void {
732
+ return self.addHighlightInternal(line_idx, col_start, col_end, style_id, priority, hl_ref, false);
733
+ }
734
+
735
+ fn addHighlightInternal(
736
+ self: *Self,
737
+ line_idx: usize,
738
+ col_start: u32,
739
+ col_end: u32,
740
+ style_id: u32,
741
+ priority: u8,
742
+ hl_ref: u16,
743
+ internal: bool,
744
+ ) TextBufferError!void {
745
+ const line_count = self.getLineCount();
746
+ if (line_idx >= line_count) {
747
+ return TextBufferError.InvalidIndex;
748
+ }
749
+
750
+ if (col_start >= col_end) {
751
+ return; // Empty range
752
+ }
753
+
754
+ try self.ensureLineHighlightStorage(line_idx);
755
+
756
+ const hl: Highlight = .{
757
+ .col_start = col_start,
758
+ .col_end = col_end,
759
+ .style_id = style_id,
760
+ .priority = priority,
761
+ .hl_ref = hl_ref,
762
+ .internal = internal,
763
+ };
764
+
765
+ try self.line_highlights.items[line_idx].append(self.global_allocator, hl);
766
+ if (internal) {
767
+ self.internal_highlight_count += 1;
768
+ }
769
+
770
+ if (self.highlight_batch_depth == 0) {
771
+ try self.rebuildLineSpans(line_idx);
772
+ } else {
773
+ self.markLineSpansDirty(line_idx);
774
+ }
775
+ }
776
+
777
+ pub fn getLineHighlights(self: *const Self, line_idx: usize) []const Highlight {
778
+ if (line_idx < self.line_highlights.items.len) {
779
+ return self.line_highlights.items[line_idx].items;
780
+ }
781
+ return &[_]Highlight{};
782
+ }
783
+
784
+ pub fn getLineSpans(self: *const Self, line_idx: usize) []const StyleSpan {
785
+ if (line_idx < self.line_spans.items.len) {
786
+ return self.line_spans.items[line_idx].items;
787
+ }
788
+ return &[_]StyleSpan{};
789
+ }
790
+
791
+ fn rebuildLineSpans(self: *Self, line_idx: usize) TextBufferError!void {
792
+ if (line_idx >= self.line_spans.items.len) {
793
+ return TextBufferError.InvalidIndex;
794
+ }
795
+
796
+ self.line_spans.items[line_idx].clearRetainingCapacity();
797
+
798
+ if (line_idx >= self.line_highlights.items.len or self.line_highlights.items[line_idx].items.len == 0) {
799
+ return; // No highlights
800
+ }
801
+
802
+ const highlights = self.line_highlights.items[line_idx].items;
803
+
804
+ // Collect all boundary columns
805
+ const Event = struct {
806
+ col: u32,
807
+ is_start: bool,
808
+ hl_idx: usize,
809
+ };
810
+
811
+ var events: std.ArrayListUnmanaged(Event) = .{};
812
+ defer events.deinit(self.global_allocator);
813
+
814
+ for (highlights, 0..) |hl, idx| {
815
+ try events.append(self.global_allocator, .{ .col = hl.col_start, .is_start = true, .hl_idx = idx });
816
+ try events.append(self.global_allocator, .{ .col = hl.col_end, .is_start = false, .hl_idx = idx });
817
+ }
818
+
819
+ // Sort by column, ends before starts at same position
820
+ const sortFn = struct {
821
+ fn lessThan(_: void, a: Event, b: Event) bool {
822
+ if (a.col != b.col) return a.col < b.col;
823
+ if (a.is_start != b.is_start) return !a.is_start; // ends before starts
824
+ // If both are same type at same column, use hl_idx for stable sort
825
+ return a.hl_idx < b.hl_idx;
826
+ }
827
+ }.lessThan;
828
+ std.mem.sort(Event, events.items, {}, sortFn);
829
+
830
+ // Build spans by tracking active highlights
831
+ var active = std.AutoHashMap(usize, void).init(self.global_allocator);
832
+ defer active.deinit();
833
+
834
+ var current_col: u32 = 0;
835
+
836
+ for (events.items) |event| {
837
+ // Find current highest priority style before processing event
838
+ var current_priority: i16 = -1;
839
+ var current_style: u32 = 0;
840
+ var it = active.keyIterator();
841
+ while (it.next()) |hl_idx| {
842
+ const hl = highlights[hl_idx.*];
843
+ if (hl.priority > current_priority) {
844
+ current_priority = @intCast(hl.priority);
845
+ current_style = hl.style_id;
846
+ }
847
+ }
848
+
849
+ // Emit span for the segment leading up to this event
850
+ if (event.col > current_col) {
851
+ try self.line_spans.items[line_idx].append(self.global_allocator, .{
852
+ .col = current_col,
853
+ .style_id = current_style,
854
+ .next_col = event.col,
855
+ });
856
+ current_col = event.col;
857
+ }
858
+
859
+ // Process event
860
+ if (event.is_start) {
861
+ try active.put(event.hl_idx, {});
862
+ } else {
863
+ _ = active.remove(event.hl_idx);
864
+ }
865
+ }
866
+
867
+ // Emit final span after last event if there were any highlights
868
+ // This ensures the line returns to default styling after the last highlight ends
869
+ if (events.items.len > 0 and active.count() == 0) {
870
+ const line_width = self.lineWidthAt(@intCast(line_idx));
871
+ if (current_col < line_width) {
872
+ try self.line_spans.items[line_idx].append(self.global_allocator, .{
873
+ .col = current_col,
874
+ .style_id = 0, // No style (default)
875
+ .next_col = line_width,
876
+ });
877
+ }
878
+ }
879
+ }
880
+
881
+ /// Add highlight by row/col coordinates
882
+ pub fn addHighlightByCoords(
883
+ self: *Self,
884
+ start_row: u32,
885
+ start_col: u32,
886
+ end_row: u32,
887
+ end_col: u32,
888
+ style_id: u32,
889
+ priority: u8,
890
+ hl_ref: u16,
891
+ ) TextBufferError!void {
892
+ const char_start = iter_mod.coordsToOffset(&self._rope, start_row, start_col) orelse return TextBufferError.InvalidIndex;
893
+ const char_end = iter_mod.coordsToOffset(&self._rope, end_row, end_col) orelse return TextBufferError.InvalidIndex;
894
+ return self.addHighlightByCharRange(char_start, char_end, style_id, priority, hl_ref);
895
+ }
896
+
897
+ /// Add highlight by character range
898
+ pub fn addHighlightByCharRange(
899
+ self: *Self,
900
+ char_start: u32,
901
+ char_end: u32,
902
+ style_id: u32,
903
+ priority: u8,
904
+ hl_ref: u16,
905
+ ) TextBufferError!void {
906
+ return self.addHighlightByCharRangeInternal(char_start, char_end, style_id, priority, hl_ref, false);
907
+ }
908
+
909
+ fn addHighlightByCharRangeInternal(
910
+ self: *Self,
911
+ char_start: u32,
912
+ char_end: u32,
913
+ style_id: u32,
914
+ priority: u8,
915
+ hl_ref: u16,
916
+ internal: bool,
917
+ ) TextBufferError!void {
918
+ const line_count = self.getLineCount();
919
+ if (char_start >= char_end or line_count == 0) {
920
+ return;
921
+ }
922
+
923
+ // Walk lines to find which lines this highlight affects
924
+ const Context = struct {
925
+ buffer: *Self,
926
+ char_start: u32,
927
+ char_end: u32,
928
+ style_id: u32,
929
+ priority: u8,
930
+ hl_ref: u16,
931
+ internal: bool,
932
+ start_line_idx: ?usize = null,
933
+
934
+ fn callback(ctx_ptr: *anyopaque, line_info: LineInfo) void {
935
+ const ctx = @as(*@This(), @ptrCast(@alignCast(ctx_ptr)));
936
+ const line_start_col_offset = line_info.col_offset;
937
+ const line_end_col_offset = line_info.col_offset + line_info.width_cols;
938
+
939
+ // Skip lines before the highlight
940
+ if (line_end_col_offset <= ctx.char_start) return;
941
+ // Stop after the highlight ends
942
+ if (line_start_col_offset >= ctx.char_end) return;
943
+
944
+ // This line overlaps with the highlight
945
+ const col_start = if (ctx.char_start > line_start_col_offset)
946
+ ctx.char_start - line_start_col_offset
947
+ else
948
+ 0;
949
+
950
+ const col_end = if (ctx.char_end < line_end_col_offset)
951
+ ctx.char_end - line_start_col_offset
952
+ else
953
+ line_info.width_cols;
954
+
955
+ ctx.buffer.addHighlightInternal(
956
+ line_info.line_idx,
957
+ col_start,
958
+ col_end,
959
+ ctx.style_id,
960
+ ctx.priority,
961
+ ctx.hl_ref,
962
+ ctx.internal,
963
+ ) catch {};
964
+ }
965
+ };
966
+
967
+ var ctx: Context = .{
968
+ .buffer = self,
969
+ .char_start = char_start,
970
+ .char_end = char_end,
971
+ .style_id = style_id,
972
+ .priority = priority,
973
+ .hl_ref = hl_ref,
974
+ .internal = internal,
975
+ };
976
+ iter_mod.walkLines(&self._rope, &ctx, Context.callback, false);
977
+ }
978
+
979
+ fn clearInternalHighlights(self: *Self) void {
980
+ if (self.internal_highlight_count == 0) return;
981
+
982
+ var remaining = self.internal_highlight_count;
983
+ for (self.line_highlights.items, 0..) |*hl_list, line_idx| {
984
+ var i: usize = 0;
985
+ var changed = false;
986
+ while (i < hl_list.items.len) {
987
+ if (hl_list.items[i].internal) {
988
+ _ = hl_list.orderedRemove(i);
989
+ remaining -= 1;
990
+ changed = true;
991
+ continue;
992
+ }
993
+ i += 1;
994
+ }
995
+ if (changed) {
996
+ if (self.highlight_batch_depth == 0) {
997
+ self.rebuildLineSpans(line_idx) catch {};
998
+ } else {
999
+ self.markLineSpansDirty(line_idx);
1000
+ }
1001
+ }
1002
+ if (remaining == 0) break;
1003
+ }
1004
+
1005
+ self.internal_highlight_count = 0;
1006
+ }
1007
+
1008
+ /// Remove all highlights with a specific reference ID
1009
+ pub fn removeHighlightsByRef(self: *Self, hl_ref: u16) void {
1010
+ for (self.line_highlights.items, 0..) |*hl_list, line_idx| {
1011
+ var i: usize = 0;
1012
+ var changed = false;
1013
+ while (i < hl_list.items.len) {
1014
+ if (hl_list.items[i].hl_ref == hl_ref) {
1015
+ if (hl_list.items[i].internal and self.internal_highlight_count > 0) {
1016
+ self.internal_highlight_count -= 1;
1017
+ }
1018
+ _ = hl_list.orderedRemove(i);
1019
+ changed = true;
1020
+ continue;
1021
+ }
1022
+ i += 1;
1023
+ }
1024
+ if (changed) {
1025
+ if (self.highlight_batch_depth == 0) {
1026
+ self.rebuildLineSpans(line_idx) catch {};
1027
+ } else {
1028
+ self.markLineSpansDirty(line_idx);
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ /// Clear all highlights from a specific line
1035
+ pub fn clearLineHighlights(self: *Self, line_idx: usize) void {
1036
+ if (line_idx < self.line_highlights.items.len) {
1037
+ for (self.line_highlights.items[line_idx].items) |hl| {
1038
+ if (hl.internal and self.internal_highlight_count > 0) {
1039
+ self.internal_highlight_count -= 1;
1040
+ }
1041
+ }
1042
+ self.line_highlights.items[line_idx].clearRetainingCapacity();
1043
+ }
1044
+ if (line_idx < self.line_spans.items.len) {
1045
+ self.line_spans.items[line_idx].clearRetainingCapacity();
1046
+ }
1047
+ }
1048
+
1049
+ /// Clear all highlights
1050
+ pub fn clearAllHighlights(self: *Self) void {
1051
+ for (self.line_highlights.items) |*hl_list| {
1052
+ hl_list.clearRetainingCapacity();
1053
+ }
1054
+ self.internal_highlight_count = 0;
1055
+ for (self.line_spans.items) |*span_list| {
1056
+ span_list.clearRetainingCapacity();
1057
+ }
1058
+ }
1059
+
1060
+ /// Get highlights for a specific line
1061
+ pub fn getLineHighlightsSlice(self: *const Self, line_idx: usize) []const Highlight {
1062
+ if (line_idx < self.line_highlights.items.len) {
1063
+ return self.line_highlights.items[line_idx].items;
1064
+ }
1065
+ return &[_]Highlight{};
1066
+ }
1067
+
1068
+ /// Get total number of highlights across all lines
1069
+ pub fn getHighlightCount(self: *const Self) u32 {
1070
+ var count: u32 = 0;
1071
+ for (self.line_highlights.items) |hl_list| {
1072
+ count += @intCast(hl_list.items.len);
1073
+ }
1074
+ return count;
1075
+ }
1076
+
1077
+ /// Set styled text from chunks with individual styling
1078
+ /// Accepts StyledChunk array for FFI compatibility
1079
+ /// TODO: This is for backward compatibility, there should be a better way to do this.
1080
+ pub fn setStyledText(
1081
+ self: *Self,
1082
+ chunks: []const StyledChunk,
1083
+ ) TextBufferError!void {
1084
+ if (chunks.len == 0) {
1085
+ self.clear();
1086
+ self.clearAllHighlights();
1087
+ return;
1088
+ }
1089
+
1090
+ // Calculate total text length
1091
+ var total_len: usize = 0;
1092
+ for (chunks) |chunk| {
1093
+ total_len += chunk.text_len;
1094
+ }
1095
+
1096
+ if (total_len == 0) {
1097
+ self.clear();
1098
+ self.clearAllHighlights();
1099
+ return;
1100
+ }
1101
+
1102
+ self.clear();
1103
+ self.clearAllHighlights();
1104
+
1105
+ _ = self.arena.reset(.retain_capacity);
1106
+
1107
+ self._rope = UnifiedRope.init(self.allocator) catch return TextBufferError.OutOfMemory;
1108
+
1109
+ if (total_len > self.styled_capacity) {
1110
+ if (self.styled_buffer) |old_buf| {
1111
+ self.global_allocator.free(old_buf);
1112
+ }
1113
+ const new_buf = self.global_allocator.alloc(u8, total_len) catch return TextBufferError.OutOfMemory;
1114
+ self.styled_buffer = new_buf;
1115
+ self.styled_capacity = total_len;
1116
+ }
1117
+
1118
+ const full_text = self.styled_buffer.?[0..total_len];
1119
+
1120
+ var offset: usize = 0;
1121
+ for (chunks) |chunk| {
1122
+ if (chunk.text_len > 0) {
1123
+ const chunk_text = chunk.text_ptr[0..chunk.text_len];
1124
+ @memcpy(full_text[offset .. offset + chunk.text_len], chunk_text);
1125
+ offset += chunk.text_len;
1126
+ }
1127
+ }
1128
+
1129
+ if (self.styled_text_mem_id) |mem_id| {
1130
+ try self.mem_registry.replace(mem_id, full_text, false);
1131
+ } else {
1132
+ const mem_id = try self.mem_registry.register(full_text, false);
1133
+ self.styled_text_mem_id = mem_id;
1134
+ }
1135
+
1136
+ try self.setTextInternal(self.styled_text_mem_id.?, full_text);
1137
+
1138
+ if (self.syntax_style) |style| {
1139
+ var seen_link_ids: std.AutoHashMapUnmanaged(u32, void) = .{};
1140
+ defer seen_link_ids.deinit(self.global_allocator);
1141
+
1142
+ self.startHighlightsTransaction();
1143
+ defer self.endHighlightsTransaction();
1144
+
1145
+ var char_pos: u32 = 0;
1146
+ for (chunks, 0..) |chunk, i| {
1147
+ const chunk_text = chunk.text_ptr[0..chunk.text_len];
1148
+ const chunk_len = self.measureText(chunk_text);
1149
+
1150
+ if (chunk_len > 0) {
1151
+ const fg = if (chunk.fg_ptr) |fgPtr| utils.ptrToRGBA(fgPtr) else null;
1152
+ const bg = if (chunk.bg_ptr) |bgPtr| utils.ptrToRGBA(bgPtr) else null;
1153
+
1154
+ var attributes = chunk.attributes;
1155
+ if (chunk.link_ptr) |link_ptr| {
1156
+ if (chunk.link_len > 0) {
1157
+ const tracker = self.getLinkTracker();
1158
+ const url = link_ptr[0..chunk.link_len];
1159
+ const link_id = tracker.pool.alloc(url) catch 0;
1160
+ if (link_id != 0) {
1161
+ const maybe_seen = seen_link_ids.getOrPut(self.global_allocator, link_id) catch null;
1162
+ const should_track = if (maybe_seen) |seen| !seen.found_existing else true;
1163
+ if (should_track) {
1164
+ tracker.addCellRef(link_id);
1165
+ }
1166
+ attributes = ansi.TextAttributes.setLinkId(attributes, link_id);
1167
+ }
1168
+ }
1169
+ }
1170
+
1171
+ var style_name_buf: [64]u8 = undefined;
1172
+ const style_name = std.fmt.bufPrint(&style_name_buf, "chunk{d}", .{i}) catch continue;
1173
+ const style_id = (@constCast(style)).registerStyleDefinition(style_name, .{
1174
+ .fg = fg,
1175
+ .bg = bg,
1176
+ .attributes = attributes,
1177
+ }) catch continue;
1178
+
1179
+ self.addHighlightByCharRangeInternal(char_pos, char_pos + chunk_len, style_id, 1, 0, true) catch {};
1180
+ }
1181
+
1182
+ char_pos += chunk_len;
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ /// Load text from a file path (relative to cwd)
1188
+ /// The file content is allocated in the arena and will be freed when the buffer is destroyed
1189
+ pub fn loadFile(self: *Self, path: []const u8) TextBufferError!void {
1190
+ const file = std.fs.cwd().openFile(path, .{}) catch |err| {
1191
+ return switch (err) {
1192
+ error.FileNotFound => TextBufferError.InvalidIndex,
1193
+ error.AccessDenied => TextBufferError.InvalidIndex,
1194
+ else => TextBufferError.OutOfMemory,
1195
+ };
1196
+ };
1197
+ defer file.close();
1198
+
1199
+ const file_size = file.getEndPos() catch return TextBufferError.OutOfMemory;
1200
+
1201
+ self.clear();
1202
+
1203
+ const content = self.allocator.alloc(u8, file_size) catch return TextBufferError.OutOfMemory;
1204
+ const bytes_read = file.readAll(content) catch return TextBufferError.OutOfMemory;
1205
+ const text = content[0..bytes_read];
1206
+ const mem_id = try self.mem_registry.register(text, false);
1207
+
1208
+ try self.setTextInternal(mem_id, text);
1209
+ }
1210
+
1211
+ pub fn getTabWidth(self: *const Self) u8 {
1212
+ return self.tabWidth();
1213
+ }
1214
+
1215
+ /// Set tab width, rounding up to nearest multiple of 2 (minimum 2).
1216
+ /// Marks all views dirty if the width actually changes, since tab width
1217
+ /// affects measured line widths and virtual line calculations.
1218
+ pub fn setTabWidth(self: *Self, width: u8) void {
1219
+ const clamped_width = @max(2, width);
1220
+ const new_width = if (clamped_width % 2 == 0) clamped_width else clamped_width + 1;
1221
+ if (self.tab_width == new_width) return;
1222
+ self.tab_width = new_width;
1223
+ self.markAllViewsDirty();
1224
+ }
1225
+
1226
+ /// Debug log the rope structure using rope.toText
1227
+ pub fn debugLogRope(self: *const Self) void {
1228
+ logger.debug("=== TextBuffer Rope Debug ===", .{});
1229
+ logger.debug("Line count: {}", .{self.getLineCount()});
1230
+ logger.debug("Char count: {}", .{self.getLength()});
1231
+ logger.debug("Byte size: {}", .{self.getByteSize()});
1232
+
1233
+ const rope_text = self._rope.toText(self.allocator) catch {
1234
+ logger.debug("Failed to generate rope text representation", .{});
1235
+ return;
1236
+ };
1237
+ logger.debug("Rope structure: {s}", .{rope_text});
1238
+ logger.debug("=== End Rope Debug ===", .{});
1239
+ }
1240
+
1241
+ /// Get text within a range of display-width offsets
1242
+ /// Automatically snaps to grapheme boundaries:
1243
+ /// Returns number of bytes written to out_buffer
1244
+ pub fn getTextRange(self: *const Self, start_offset: u32, end_offset: u32, out_buffer: []u8) usize {
1245
+ if (start_offset >= end_offset) return 0;
1246
+ if (out_buffer.len == 0) return 0;
1247
+
1248
+ const total_weight = self._rope.totalWeight();
1249
+ if (start_offset >= total_weight) return 0;
1250
+
1251
+ const clamped_end = @min(end_offset, total_weight);
1252
+
1253
+ return iter_mod.extractTextBetweenOffsets(
1254
+ &self._rope,
1255
+ &self.mem_registry,
1256
+ self.tab_width,
1257
+ start_offset,
1258
+ clamped_end,
1259
+ out_buffer,
1260
+ self.width_method,
1261
+ );
1262
+ }
1263
+
1264
+ /// Get text within a range specified by row/col coordinates
1265
+ /// Automatically snaps to grapheme boundaries:
1266
+ /// Returns number of bytes written to out_buffer
1267
+ pub fn getTextRangeByCoords(self: *Self, start_row: u32, start_col: u32, end_row: u32, end_col: u32, out_buffer: []u8) usize {
1268
+ const start_offset = iter_mod.coordsToOffset(&self._rope, start_row, start_col) orelse return 0;
1269
+ const end_offset = iter_mod.coordsToOffset(&self._rope, end_row, end_col) orelse return 0;
1270
+ return self.getTextRange(start_offset, end_offset, out_buffer);
1271
+ }
1272
+ };