Compare commits

...
Author SHA1 Message Date
copilot-swe-agent[bot]andTyriar 369ca9b525 Add error handling for dynamic imports
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:58:45 +00:00
copilot-swe-agent[bot]andTyriar a5422d1b11 Add dynamic imports for AccessibilityManager and OverviewRulerRenderer
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:56:13 +00:00
copilot-swe-agent[bot]andTyriar c2890d8a4d Add error handling for dynamic import in loadCustomGlyphDefinitions
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:14:01 +00:00
copilot-swe-agent[bot]andTyriar 7a7abddc45 Use dynamic imports for custom glyphs in WebGL addon
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 01:12:01 +00:00
copilot-swe-agent[bot]andTyriar 8c71bfd65f Revert @xterm/xterm alias to use package.json resolution
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 00:41:57 +00:00
copilot-swe-agent[bot]andTyriar 3c2b911439 Set up code splitting for ESM build
Co-authored-by: Tyriar <2193314+Tyriar@users.noreply.github.com>
2026-01-16 00:40:40 +00:00
copilot-swe-agent[bot] 5ee8760418 Initial plan 2026-01-16 00:31:02 +00:00
Daniel Imms 777a46445a Merge pull request #5609 from xtermjs/merogge/show-cursor
add `showCursorImmediately` option
2026-01-13 08:47:50 -08:00
meganrogge a20ff565b0 add showCursorImmediately option 2026-01-13 10:36:35 -06:00
Daniel Imms d28046ebed Merge pull request #5607 from Tyriar/5606
Fix blur due to canvas dim mismatch in glyph renderer
2026-01-13 06:35:40 -08:00
Daniel Imms 4ddd982e42 Fix blur due to canvas dim mismatch in glyph renderer
Fixes #5606
2026-01-13 06:23:10 -08:00
Daniel Imms a3228bd1b8 Merge pull request #5604 from Tyriar/2357_2
Fix capital letters and ctrl+letter in win32-input-mode
2026-01-11 09:10:31 -08:00
Daniel Imms a1fca4feb8 Fix ctrl+letter when inside pwsh->WSL 2026-01-11 09:02:44 -08:00
Daniel Imms afc6f0b7eb Fix caps not working in win32InputMode
Part of #2357
2026-01-11 09:00:08 -08:00
Daniel Imms f4c77d37b4 Merge pull request #5603 from Tyriar/2357
Implement win32-input-mode
2026-01-10 06:04:17 -08:00
Daniel Imms 9d0beb7c38 Use 0b over 0x for flags 2026-01-10 05:57:13 -08:00
Daniel Imms f88650ec1c Use win32InputMode in demo on Windows 2026-01-10 05:54:48 -08:00
Daniel Imms 8b35c67dd3 useWin32 -> useWin32InputMode 2026-01-10 05:52:19 -08:00
Daniel Imms 53dc85eca2 Add copyright 2026-01-10 05:48:48 -08:00
Daniel Imms 0946386cc4 Make unit tests more compact 2026-01-10 05:48:30 -08:00
Daniel Imms ebe18b3da5 Add more test cases 2026-01-10 05:42:17 -08:00
Daniel Imms 6c2792a1d5 Fix tests 2026-01-10 05:33:08 -08:00
Daniel Imms ee47054678 Implement win32-input-mode
Fixes #2357
2026-01-10 05:27:03 -08:00
Daniel Imms 91c4761b82 Merge pull request #5600 from Tyriar/4198_kitty
Implement kitty keyboard protocol (CSI =|?|>|< u)
2026-01-10 04:46:38 -08:00
Daniel Imms c9fc6fca8e Lint 2026-01-10 04:39:26 -08:00
Daniel Imms 73cba6dda3 Clean up, add sgr extension to api 2026-01-10 04:38:06 -08:00
Daniel Imms 50b0f3d7ee Add vtExtensions.kittySgrBoldFaintControl 2026-01-10 04:31:36 -08:00
Daniel Imms 686c67a14b Make mandatory browser services readonly 2026-01-10 04:20:29 -08:00
Daniel Imms ec78500f86 Create IKeyboardService 2026-01-10 04:19:23 -08:00
Daniel Imms 98ea14824a Make lint happy 2026-01-09 13:14:30 -08:00
Daniel Imms 4c905dad33 Update API jsdoc 2026-01-09 13:02:18 -08:00
Daniel Imms e3fdcc7869 Fix API lint 2026-01-09 13:01:22 -08:00
Daniel Imms 0674663a5a Remove unused import 2026-01-09 12:56:45 -08:00
Daniel Imms e07832a420 Merge branch 'master' into 4198_kitty 2026-01-09 12:51:48 -08:00
Daniel Imms 934b5dc8fa Merge pull request #5602 from Tyriar/5601
Add SGR 221 and 222
2026-01-09 12:21:43 -08:00
Daniel Imms 7a544d8346 Add SGR 221 and 222
Fixes #5601
2026-01-09 12:13:40 -08:00
Daniel Imms c624a47780 Maintain different buffer flags, stack limit, tests 2026-01-09 11:59:50 -08:00
Daniel Imms 5a29d489c3 Separate out kitty keyboard handlers 2026-01-09 11:46:57 -08:00
Daniel Imms 4a67836a5b Remove support responses
Wrong place for them
2026-01-09 11:42:00 -08:00
Daniel Imms 3adf6be988 Fix some edge cases 2026-01-09 10:36:13 -08:00
Daniel Imms 566589f7c1 More comprehensive tests 2026-01-09 07:23:12 -08:00
Daniel Imms 8dbc91dc24 Add vtExtensions to demo 2026-01-09 07:15:45 -08:00
Daniel Imms 992da3cc4d Hook up vt extensions option 2026-01-09 07:07:10 -08:00
Daniel Imms 3fbaef06ef Align behavior closer with kitty 2026-01-09 06:53:12 -08:00
Daniel Imms 2265fa2ade Implement kitty keyboard protocol (CSI u)
Fixes #4198
2026-01-09 05:59:57 -08:00
Daniel Imms 756c353237 Merge pull request #5593 from kallsyms/improve-lines-cache-perf
improve SearchLineCache performance
2026-01-09 05:59:54 -08:00
Daniel Imms 49a8ac8fc0 Merge pull request #5599 from Tyriar/flush
Flush writes on resize
2026-01-09 05:37:21 -08:00
Daniel Imms bf7c95b6cc Flush writes on resize
Fixes #5597
2026-01-09 05:25:22 -08:00
Daniel Imms 8112fbf210 Merge pull request #5598 from Tyriar/5588
Fix exception on resize during write
2026-01-08 18:10:41 -08:00
Daniel Imms 16a13f8504 Fix exception on resize during write
Fixes #5588
2026-01-08 18:03:42 -08:00
Daniel Imms 9bd128b315 Merge pull request #5594 from Tyriar/onSelectionChangeClear
Fire onSelectionChange on clear
2026-01-08 17:44:16 -08:00
Daniel Imms 729a670043 Merge pull request #5596 from Tyriar/lint_changes
New npm script to lint only changes
2026-01-08 17:39:34 -08:00
Daniel Imms bd8454db55 Another poll case 2026-01-08 17:37:44 -08:00
Daniel Imms d6f6a6af9a Lint instructions 2026-01-08 17:32:50 -08:00
Daniel Imms d65f9312ea Add lint-changes npm scripts 2026-01-08 17:32:15 -08:00
Daniel Imms a437d12004 Poll to avoid a race 2026-01-08 17:25:26 -08:00
Daniel Imms 437490308c Merge pull request #5595 from Tyriar/download_fonts
Remove download fonts
2026-01-08 17:18:36 -08:00
Daniel Imms 3250c31202 Remove download fonts 2026-01-08 17:09:26 -08:00
Daniel Imms 55d12e03d1 Remove unneeded test 2026-01-08 17:04:35 -08:00
Daniel Imms 6efb319ece Add tests more thorough tests for onSelectionChange 2026-01-08 17:01:56 -08:00
Daniel Imms b69afe5765 Merge remote-tracking branch 'upstream/master' into onSelectionChangeClear 2026-01-08 16:51:54 -08:00
Daniel Imms 613aa6ba23 Fire onSelectionChange when starting to drag 2026-01-08 16:51:45 -08:00
Nick Gregory a8c9128841 improve SearchLineCache performance 2026-01-07 16:04:49 -08:00
Daniel Imms 94a264679e Merge pull request #5591 from Tyriar/5586
Ensure mouse listeners are removed on dispose
2026-01-05 12:38:41 -08:00
Daniel Imms cb35d1b487 Ensure mouse listeners are removed on dispose
Also use ? over ! just in case

Fixes #5586
2026-01-05 12:31:54 -08:00
Daniel Imms c97abced76 Merge pull request #5590 from Tyriar/5587
Add undefined checks in erase calls
2026-01-05 11:17:40 -08:00
Daniel Imms 9db31db886 Add undefined checks in erase calls
This is likely a race condition during a resize which is hard to say
what the right behavior is. Instead of hard failing by throwing an
error, silently ignore if this happens.

Fixes #5587
2026-01-05 11:10:56 -08:00
Daniel Imms ccf9727b85 Merge pull request #5583 from Tyriar/root
Clean up root, remove auto approve settings
2026-01-04 06:44:57 -08:00
Daniel Imms 1dfdde9e27 Clean up root, remove auto approve settings
These are automatically auto approved in upcoming vscode
2026-01-04 06:38:53 -08:00
Daniel Imms 2712e88d0a Merge pull request #5582 from Tyriar/readme2
Update readme 2
2026-01-04 06:28:32 -08:00
Daniel Imms b5da8a28f6 Update readme 2 2026-01-04 06:27:22 -08:00
Daniel Imms 66c4f8b116 Merge pull request #5581 from Tyriar/readme
Update readme
2026-01-04 06:20:48 -08:00
Daniel Imms 9148c80d1a Update readme
- Added x2 scale logo
- Revised wording
- Added new addons
2026-01-04 06:18:50 -08:00
Daniel Imms e1bfc7dd1f Merge pull request #5178 from jerch/webfonts-addon
Add webfonts addon
2026-01-04 05:43:01 -08:00
Daniel Imms c6c4a2ffbc Delete unwanted eslintrc 2026-01-03 15:39:24 -08:00
Daniel Imms 2cf2929869 Publish webfonts 2026-01-03 15:36:36 -08:00
Daniel Imms b0145998c5 Fix lint 2026-01-03 15:36:31 -08:00
Daniel Imms 0e57643f16 Move fonts into folder 2026-01-03 15:33:13 -08:00
Daniel Imms a35223a819 Add web fonts window to demo 2026-01-03 15:31:24 -08:00
Daniel Imms 5e95dc1f10 Sync package lock 2026-01-03 15:24:11 -08:00
Daniel Imms b4e9a7f9ea Merge remote-tracking branch 'upstream/master' into pr/jerch/5178 2026-01-03 15:21:50 -08:00
Daniel Imms 73e3357526 Merge pull request #5579 from Tyriar/proposed
Make everything except unicode APIs stable
2026-01-03 15:04:25 -08:00
Daniel Imms 483c7b4a81 Merge pull request #5580 from Tyriar/5572
Update demo dims on font family change
2026-01-03 14:58:57 -08:00
Daniel Imms f4453b3e18 Merge pull request #5566 from xtermjs/dependabot/npm_and_yarn/qs-6.14.1
Bump qs from 6.14.0 to 6.14.1
2026-01-03 14:58:39 -08:00
Daniel Imms 7389a1097d Update tests to use unicode for proposed check 2026-01-03 14:57:55 -08:00
Daniel Imms 0c7b1cb448 Update demo dims on font family change
Fixes #5572
2026-01-03 14:52:32 -08:00
Daniel Imms 7a3b5339e7 Merge pull request #5578 from Tyriar/5576
Lint demo code
2026-01-03 14:41:48 -08:00
Daniel Imms 8193ceae12 Make everything except unicode APIs stable 2026-01-03 14:40:07 -08:00
Daniel Imms 064e299bb0 Merge pull request #5577 from Tyriar/ext_recommendation
Recommend eslint extension in vscode
2026-01-03 14:38:45 -08:00
Daniel Imms 6211bf078c Lint demo code
Fixes #5576
2026-01-03 14:35:39 -08:00
Daniel Imms a639808196 Recommend eslint extension in vscode
Fixes #5575
2026-01-03 14:32:16 -08:00
Daniel Imms b522e255f0 Merge pull request #5571 from Tyriar/5341
Fix isNode detection when process module is used in webpack
2026-01-03 14:25:33 -08:00
Daniel Imms d7850af9a2 Fix lint 2026-01-03 14:19:36 -08:00
Daniel Imms 4182f2226f Merge pull request #5573 from Tyriar/5570_oom
Fix infinite recursion OOM crash in addon-ligatures
2026-01-03 14:15:11 -08:00
Daniel Imms e2f45b5f4e Fix for modern node that includes a navigator.userAgent 2026-01-03 14:10:44 -08:00
Daniel Imms 8712f8067d Fix infinite recursion OOM crash in addon-ligatures
1. processLookahead/BacktrackPosition created separate entry objects
   for each glyph at each position (O(N^M) with N glyphs, M positions).
   Now all glyphs at a position share one entry object.
2. cloneEntry, cloneTree, flattenEntry, and mergeTreeEntry could
   infinitely recurse or duplicate work on shared/cyclic references.
   Added visited/merged tracking maps to cache results.

Note that parsing CommitMono locks up the renderer for some time still
so there is still a performance issue here, this fixes the OOM though.
This was mostly defensive generated code since the codebase is
unfamiliar to me.

Fixes #5570
2026-01-03 14:06:57 -08:00
Daniel Imms 08c49301b7 Fix isNode detection when process module is used in webpack
Fixes #5341
2026-01-03 11:19:23 -08:00
dependabot[bot] 917a8ded92 Bump qs from 6.14.0 to 6.14.1
Bumps [qs](https://github.com/ljharb/qs) from 6.14.0 to 6.14.1.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.0...v6.14.1)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.14.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-03 17:44:20 +00:00
Daniel Imms d06d278f0c Merge pull request #5569 from Tyriar/5568_font_ligatures
Merge font-ligatures package into addon-ligatures
2026-01-03 09:43:07 -08:00
Daniel Imms f84384c83a Fix lint 2026-01-03 09:31:45 -08:00
Daniel Imms ec03109c39 2 space indent 2026-01-03 09:25:39 -08:00
Daniel Imms 21b8f77afb Move unit tests to right folder, push font fixtures 2026-01-03 09:16:58 -08:00
Daniel Imms 363fc84fd2 Merge font-ligatures into addon-ligatures
Fixes #5568
2026-01-03 09:02:06 -08:00
Daniel Imms 8e4de23c11 Merge pull request #5565 from Tyriar/2797
Support ctrl+^ -> RS, move to physical key
2026-01-01 05:25:52 -08:00
Daniel Imms 1caf6dbe50 Fix tests 2026-01-01 05:19:56 -08:00
Daniel Imms 1c97e40a6a Support ctrl+^ -> RS, move to physical key
Fixes #2797
Part of #1862
2026-01-01 04:41:44 -08:00
Daniel Imms cdbafb231d Merge pull request #5564 from Tyriar/3364
Serialize showCursor
2025-12-31 17:14:02 -08:00
Daniel Imms 44a8c7efbc Fix test expectations 2025-12-31 17:08:05 -08:00
Daniel Imms 6277bb363c Serialize showCursor
Fixes #3364
2025-12-31 08:12:39 -08:00
Daniel Imms 40f2eefec7 Merge pull request #5563 from Tyriar/5489
Fix touch scrolling
2025-12-31 06:33:36 -08:00
Daniel Imms 519b1c5ef7 Fix touch scrolling
Fixes #5489
2025-12-31 06:27:45 -08:00
Daniel Imms 97e356fb83 Merge pull request #5562 from Tyriar/2117_3
Add tests for CSI Pm d, e, f, g, m
2025-12-31 05:24:41 -08:00
Daniel Imms 42872a84dd Add tests for CSI Pm d, e, f, g, m
Fixes #2117
2025-12-31 05:18:17 -08:00
Daniel Imms 4700e18833 Merge pull request #5561 from Tyriar/5558
Fix allowTransparency in lib and demo
2025-12-31 05:08:29 -08:00
Daniel Imms d143340b60 Fix allowTransparency in lib and demo
Fixes #5558
Fixes #5560
2025-12-31 05:00:33 -08:00
Daniel Imms a8f26bb758 Merge pull request #5559 from Tyriar/2117_2
Add tests for CSI `Ps K`, `? Ps K`, `Ps S`, `Ps T`, `Ps X`, `Ps Z`, `Ps ^`, `Ps \``
2025-12-30 07:06:37 -08:00
Daniel Imms da4243cf02 Don't skip new tests, implement CSI Ps ^ 2025-12-30 06:59:27 -08:00
Daniel Imms 54e66f3ac4 Add some more CSI tests 2025-12-30 06:48:28 -08:00
Daniel Imms 7d8ef60860 Merge pull request #5557 from Tyriar/playwright_update2
Update playwright test to latest
2025-12-30 06:47:24 -08:00
Daniel Imms 595c119404 Move skip into dom file 2025-12-30 06:05:46 -08:00
Daniel Imms 481431fbc1 Update playwright test to latest 2025-12-30 06:03:17 -08:00
Daniel Imms 5c2cd474ce Merge pull request #5556 from Tyriar/5555
Migrate evaluate calls to use terminal proxy
2025-12-30 05:43:14 -08:00
Daniel Imms 0b9a7cb856 Migrate MouseTracking and Terminal to playwright proxy
Fixes #5555
2025-12-30 05:37:09 -08:00
Daniel Imms a8a4455189 Migrate InputHandler.test.ts to playwright proxy
Part of #5555
2025-12-30 05:27:28 -08:00
Daniel Imms 11fbdb3db7 Merge pull request #5554 from Tyriar/2117
Add unit test for CSI Ps SP @ - SL
2025-12-30 05:10:44 -08:00
Daniel Imms 88ce0d40e7 Add unit test for CSI Ps SP @ - SL
Part of #2117
2025-12-30 05:04:20 -08:00
Daniel Imms 2785f11860 Merge pull request #5553 from Tyriar/1526
Save cursor and restore more modes
2025-12-30 04:55:51 -08:00
Daniel Imms 857c4529cd Save cursor and restore more modes
Fixes #1526
2025-12-30 04:49:54 -08:00
Daniel Imms d30c3e7204 Merge pull request #5552 from Tyriar/contrib
Rework contributing doc
2025-12-30 04:42:18 -08:00
Daniel Imms 982f5e15ff Merge pull request #5551 from Tyriar/702
Add dimensions API
2025-12-30 04:37:31 -08:00
Daniel Imms ec3e4f2af1 Rework contributing doc
Fixes #5550
2025-12-30 04:33:57 -08:00
Daniel Imms 13914ee01e Remove private use in ImageRenderer 2025-12-30 04:09:56 -08:00
Daniel Imms e27cc2c089 Remove private API access from tests/demo 2025-12-30 04:06:26 -08:00
Daniel Imms 214289aaab Add dimensions API
Fixes #702
2025-12-30 03:58:26 -08:00
Daniel Imms a5af434e3e Merge pull request #5549 from Tyriar/5548
Use OffscreenCanvas over DOM for WidthCache
2025-12-30 03:38:15 -08:00
Daniel Imms a513120348 Get dom/width cache tests passing in node 2025-12-30 03:32:34 -08:00
Daniel Imms ef978b370b Use OffscreenCanvas over DOM for WidthCache
Fixes #5548
2025-12-30 02:57:09 -08:00
Daniel Imms 00ad3eac40 Merge pull request #5547 from Tyriar/3433
Serialize scroll region
2025-12-29 07:59:49 -08:00
Daniel Imms 29d3eb2e52 Serialize scroll region
fixes #3433
2025-12-29 07:53:43 -08:00
Daniel Imms 8b594140e9 Merge pull request #5546 from Tyriar/progress
Add progress indicator custom glyphs (EE00-EE0B)
2025-12-29 07:37:53 -08:00
Daniel Imms 7cf48c1eb5 Add progress indicator custom glyphs (EE00-EE0B)
Fixes #5478
2025-12-29 07:31:52 -08:00
Daniel Imms 8e6b6e7464 Merge pull request #5545 from Tyriar/nf
Add nerd fonts test button
2025-12-29 06:39:13 -08:00
Daniel Imms 1b0554714b Add nerd fonts test button
Fixes #5544
2025-12-29 06:33:27 -08:00
Daniel Imms abdfa2628c Merge pull request #5543 from Tyriar/underline_inspect
Report underline attributes in demo cell inspector
2025-12-29 06:23:38 -08:00
Daniel Imms 5b4d794f7a Report underline attributes in demo cell inspector 2025-12-29 06:17:36 -08:00
Daniel Imms 9eb1da79e3 Merge pull request #5542 from Tyriar/4064
Make curly underline more vivid
2025-12-29 06:14:01 -08:00
Daniel Imms d4ba4c109b Make curly underline more vivid
Fixes #4064
2025-12-29 06:04:29 -08:00
Daniel Imms 1ad23d6081 Merge pull request #5539 from Tyriar/ris
Add RIS metadata comment
2025-12-29 05:06:07 -08:00
Daniel Imms 73c01cae89 Merge pull request #5541 from Tyriar/4114
Fix fit using correct dims on demo
2025-12-29 05:03:58 -08:00
Daniel Imms 5174a7310f Add RIS metadata comment
Fixes #5043
2025-12-29 05:00:13 -08:00
Daniel Imms 1d793c9054 Fix fit using correct dims on demo
This doesn't add the debounce suggested in the issue, but it does
comment about it.

Fixes #4114
2025-12-29 04:58:12 -08:00
Daniel Imms 1b7c61a6fc Merge pull request #5540 from Tyriar/4855
Fix decorations with height > 1
2025-12-29 04:20:51 -08:00
Daniel Imms 9780b44115 Fix decorations with height > 1
Fixes #4855
2025-12-29 04:14:56 -08:00
Daniel Imms 8d532a35c4 Merge pull request #5538 from Tyriar/4731_mobile_warn
Update viewport dims when dpr changes
2025-12-28 16:36:30 -08:00
Daniel Imms d6df8d7902 Update viewport dims when dpr changes
Fixes #4731
2025-12-28 16:30:44 -08:00
Daniel Imms 4b9566cef0 Merge pull request #5535 from Tyriar/5408_2
Fix firefox selection when in shadow dom take 2
2025-12-28 16:05:49 -08:00
Daniel Imms b30bb1e3b0 Fix stack overflow 2025-12-28 15:59:29 -08:00
Loïc Mangeonjean d67e73a4da fix(fit-addon): call getComputedStyle on the right window element 2025-12-28 15:55:21 -08:00
Loïc Mangeonjean e7434a932d fix: fix computed style computation on firefox inside a shadow dom 2025-12-28 15:55:21 -08:00
Daniel Imms cdb0497d0d Merge pull request #5534 from Tyriar/5184_sync_reset
Force reset to use sync render
2025-12-28 15:22:13 -08:00
Daniel Imms 2fb42c554e Force reset to use sync render
Fixes #5184
2025-12-28 15:16:23 -08:00
Daniel Imms 3632496c94 Merge pull request #5533 from Tyriar/5532
Fix addon build issue on macOS
2025-12-28 15:08:12 -08:00
Daniel Imms a6407fb3c6 Fix addon build issue on macOS
Fixes #5532
2025-12-28 15:02:16 -08:00
Daniel Imms 65aa28464c Merge pull request #5530 from Tyriar/4339
Fix double annoucne of too much output
2025-12-28 14:57:09 -08:00
Daniel Imms 2baad39ccf Fix double annoucne of too much output
Fixes #4339
2025-12-28 14:51:12 -08:00
Daniel Imms c975956f2a Merge pull request #5529 from Tyriar/worktree1
Force a sync render after resize occurs
2025-12-28 14:44:44 -08:00
Daniel Imms 4619a755b1 Force a sync render after resize occurs
Fixes #4922
Related microsoft/vscode#230120
2025-12-28 14:38:42 -08:00
Daniel Imms bc795d36c0 Merge pull request #5528 from Tyriar/4528
Serialize rich underline styles
2025-12-28 14:26:35 -08:00
Daniel Imms b989c5a568 Fix lint 2025-12-28 14:20:55 -08:00
Daniel Imms d66214b25e Serialize rich underline styles 2025-12-28 14:16:53 -08:00
Daniel Imms 6157f523a8 Merge pull request #5523 from Tyriar/4628
Add idle timeout which pauses cursor blink
2025-12-28 14:04:49 -08:00
Daniel Imms 3ab93ea083 Merge pull request #5526 from Tyriar/lint
Remove eol-last eslint rule
2025-12-28 14:04:18 -08:00
Daniel Imms 7ef4c55ca9 Merge pull request #5525 from Tyriar/demo_hover
Implement cell inspector in demo
2025-12-28 13:57:35 -08:00
Daniel Imms d393154271 Remove eol-last eslint rule
This one's just troublesome when working with generated code. It
doesn't make a difference in the end anyway.
2025-12-28 13:56:22 -08:00
Daniel Imms 2c32ef5963 Fix lint 2025-12-28 13:53:03 -08:00
Daniel Imms a730533790 Implement cell inspector in demo
Fixes #5524
2025-12-28 13:50:37 -08:00
Daniel Imms 8a5ffc1bb1 Tidy comments 2025-12-28 13:42:22 -08:00
Daniel Imms a966f7d591 Explain idle in cursorBlink option 2025-12-28 13:41:21 -08:00
Daniel Imms 4985c9f3f9 Use shared constant for idle timeout 2025-12-28 13:37:25 -08:00
Daniel Imms 2e1651badd Pull dom renderer blink management into class 2025-12-28 13:35:57 -08:00
Daniel Imms 7d1f74fb8b Use const enums for constants 2025-12-28 13:33:51 -08:00
Daniel Imms f8c1f5a32f Add idle timeout which pauses cursor blink
Fixes #4628
2025-12-28 13:30:58 -08:00
Daniel Imms 79944f7524 Merge pull request #5521 from Tyriar/5314
Add quirks setting to control DECSET/DECRST 12
2025-12-28 08:07:47 -08:00
Daniel Imms 52b6710b19 Hide quirks from demo for now 2025-12-28 08:01:56 -08:00
Daniel Imms 2a283a307c Fix lint 2025-12-28 07:56:31 -08:00
Daniel Imms ab4524873b Add test for DECSET quirks 2025-12-28 07:49:12 -08:00
Daniel Imms eb5f0d709a Merge pull request #5522 from Tyriar/5295
Note in API that reflowCursorLine will not move the cursor
2025-12-28 07:43:50 -08:00
Daniel Imms 8a8f262616 Note in API that reflowCursorLine will not move the cursor
Fixes #5295
2025-12-28 07:37:50 -08:00
Daniel Imms ca5a681363 Add quirks setting to control DECSET/DECRST 12
Fixes #5314
2025-12-28 07:34:55 -08:00
Daniel Imms fb10cd62c9 Merge pull request #5520 from Tyriar/4961
Ignore soft hyphen
2025-12-27 14:57:12 -08:00
Daniel Imms 28b62a5e0b Ignore soft hyphen
Fixes #4961
2025-12-27 14:51:07 -08:00
Daniel Imms bedf7e8326 Merge pull request #5519 from Tyriar/5444
Add onBeforeSearch and onAfterSearch APIs
2025-12-27 14:38:30 -08:00
Daniel Imms f50028abce Add onBeforeSearch and onAfterSearch APIs
Fixes #5444
2025-12-27 14:32:39 -08:00
Daniel Imms 7a4c9cadff Merge pull request #5518 from Tyriar/style
Demo: Improve style, remove headers from windows
2025-12-27 09:03:02 -08:00
Daniel Imms 01c1c477c3 Demo: Improve style, remove headers from windows 2025-12-27 08:57:26 -08:00
Daniel Imms 33daadb4ea Merge pull request #5516 from Tyriar/activeMatchBg
Ensure activeMatchBackground decoration is on top
2025-12-27 08:04:50 -08:00
Daniel Imms ef6013aac9 Merge pull request #5517 from Tyriar/demo_addons
Demo: Add addon tabs, shuffle order
2025-12-27 08:04:31 -08:00
Daniel Imms 82f24ad5a5 Demo: Add addon tabs, shuffle order 2025-12-27 06:47:17 -08:00
Daniel Imms 97c435862b Merge pull request #5439 from nya3jp/keydup
Fix key duplication on Android with physical keyboards
2025-12-27 06:38:28 -08:00
Daniel Imms 6488e839a1 Merge branch 'master' into keydup 2025-12-27 06:32:16 -08:00
Daniel Imms 5d3564bb38 Ensure activeMatchBackground decoration is on top
Fixes #5369
2025-12-27 06:30:02 -08:00
Daniel Imms 50985d30f9 Merge pull request #5515 from Tyriar/5457_ctrl+slash
Add ctrl+/ -> ^_ keybinding
2025-12-27 06:05:48 -08:00
Daniel Imms 733e48ec73 Add ctrl+/ -> ^_ keybinding
Fixes #5457
2025-12-27 05:57:43 -08:00
Daniel Imms 057fefd39e Merge pull request #5514 from Tyriar/demo6
Ensure types are checked in demo, fix errors, emit to out-demo
2025-12-27 05:40:41 -08:00
Daniel Imms 4d48f8624b Ensure types are checked in demo, fix errors, emit to out-demo
Part of #5509
2025-12-27 05:31:21 -08:00
Daniel Imms 995b491a7a Merge pull request #5513 from Tyriar/esbuild_warn
Set esbuild log level to warning
2025-12-27 05:23:44 -08:00
Daniel Imms 4fe118a8ff Set esbuild log level to warning
This suppresses a safe to ignore debug log in server task
2025-12-27 05:18:00 -08:00
Daniel Imms 45375c94e2 Merge pull request #5512 from Tyriar/demo_server
Move server.js to TypeScript
2025-12-27 05:12:14 -08:00
Daniel Imms f83760d027 Add esbuild server build task 2025-12-27 04:57:55 -08:00
Daniel Imms 1a1bdefc83 Move server to TS
Fixes #5509
2025-12-27 04:36:18 -08:00
Daniel Imms e28db9e8a9 Merge pull request #5511 from Tyriar/settings
Simplify vscode settings
2025-12-27 04:09:31 -08:00
Daniel Imms be5f510bfb Merge pull request #5510 from Tyriar/dev
Make default build task use a single terminal via concurrently
2025-12-27 04:07:16 -08:00
Daniel Imms ac6b8ebb10 Simplify vscode settings 2025-12-27 04:03:24 -08:00
Daniel Imms 1ada355048 Make default build task use a single terminal via concurrently 2025-12-27 03:41:47 -08:00
Daniel Imms 4ce3e3106b Merge pull request #5508 from Tyriar/demo4
Fix css not being used in demo
2025-12-27 03:15:58 -08:00
Daniel Imms 942aff6af7 Merge pull request #5507 from Tyriar/ts5.9
Upgrade to typescript 5.9.3
2025-12-27 03:14:38 -08:00
Daniel Imms 635b898dc0 Fix css not being used in demo 2025-12-27 03:09:39 -08:00
Daniel Imms e01d1f2f17 Upgrade to typescript 5.9.3 2025-12-27 03:06:14 -08:00
Daniel Imms bd16eeed90 Merge pull request #5506 from Tyriar/shared_compile
Fix type error in SharedRendererTests.ts
2025-12-27 03:01:27 -08:00
Daniel Imms df8f9fc519 Merge pull request #5505 from Tyriar/canvasExceptions
Remove unused skip canvas exceptions from playwright
2025-12-27 02:59:27 -08:00
Daniel Imms 373bf513f1 Fix type error in SharedRendererTests.ts 2025-12-27 02:55:43 -08:00
Daniel Imms 25a5497329 Remove unused skip canvas exceptions from playwright 2025-12-27 02:53:28 -08:00
Daniel Imms 4406043e6b Merge pull request #5504 from Tyriar/onRender_headless
Implement onRender in xterm-headless
2025-12-26 11:33:01 -08:00
Daniel Imms 82f961f76f Move new onRender behavior into headless Terminal impl 2025-12-26 11:27:38 -08:00
Daniel Imms a26471b9f3 Implement onRender in xterm-headless
This effectively enabled implementing an efficient renderer on top
of xterm-headless. See #5392
2025-12-26 11:19:59 -08:00
Daniel Imms ba989a6e6c Merge pull request #5503 from Tyriar/copilot_approve
Add some npm scripts that copilot can approve
2025-12-26 11:16:36 -08:00
Daniel Imms d4f725c649 Merge pull request #5502 from Tyriar/xtversion
Support reporting XTVERSION
2025-12-26 11:13:53 -08:00
Daniel Imms 79f5198b2d Add some npm scripts that copilot can approve 2025-12-26 11:10:53 -08:00
Daniel Imms d8a93b757a Support reporting XTVERSION
Fixes #5342
2025-12-26 11:06:55 -08:00
Daniel Imms 9453634f56 Merge pull request #5501 from Tyriar/demo3
Make clear css file is for index.html
2025-12-26 10:59:43 -08:00
Daniel Imms 10e12cf743 Make clear css file is for index.html
Follow up on #5500
2025-12-26 10:54:07 -08:00
Daniel Imms 79621a4e3f Merge pull request #5500 from Tyriar/demo2
More demo refactors
2025-12-26 10:51:49 -08:00
Daniel Imms 546c5e081d Inline simplified style to test.html 2025-12-26 10:46:27 -08:00
Daniel Imms e6ad59b1b1 Disable grid layout in test.html 2025-12-26 10:38:39 -08:00
Daniel Imms 8eab98b78d Change banner bg color 2025-12-26 04:41:05 -08:00
Daniel Imms 0ed6fd0db6 Fix order of init 2025-12-26 04:40:22 -08:00
Daniel Imms e3f87ab8a1 More move handlers into addons and test window 2025-12-26 04:36:51 -08:00
Daniel Imms 8119bb0a4a Simplify window interaction 2025-12-26 04:31:06 -08:00
Daniel Imms dc0d7c81d9 Add terminal and addon refs to all windows 2025-12-26 04:24:07 -08:00
Daniel Imms fa87ecdc4e Move more handlers into testWindow.ts 2025-12-26 04:15:13 -08:00
Daniel Imms b82e8f345f Move more handlers out, addon types into shared file 2025-12-26 04:09:24 -08:00
Daniel Imms 02e9e56eef Move more handlers into testWindow.ts 2025-12-26 04:04:08 -08:00
Daniel Imms 4fffb96f25 Move addCjk into window, move window interactions out of createTerminal 2025-12-26 03:51:01 -08:00
Daniel Imms 6fe5a124ca Merge pull request #5498 from Tyriar/demo
Improve demo
2025-12-26 03:29:03 -08:00
Daniel Imms f62043de91 Merge pull request #5497 from xtermjs/Tyriar-patch-1
Box Elements -> Block Elements
2025-12-25 04:27:12 -08:00
Daniel Imms 55e5ec6037 Box Elements -> Block Elements 2025-12-25 04:21:47 -08:00
Daniel Imms 7b2a5cb50f Merge pull request #5496 from xtermjs/Tyriar-patch-1
Replace range separator with hyphen
2025-12-25 04:05:17 -08:00
Daniel Imms 8740dcda4d Replace range separator with hyphen 2025-12-25 03:59:54 -08:00
Daniel Imms c046f5b4b1 More refactors 2025-12-25 03:41:47 -08:00
Daniel Imms 6bde923f07 Register the windows 2025-12-24 17:09:20 -08:00
Daniel Imms 40b2bbef34 Improve demo by making full screen, add control bar 2025-12-24 16:43:35 -08:00
Daniel Imms c04806fc92 Merge pull request #5495 from Tyriar/tyriar/git_branch
Support custom glyphs for Git Branch Symbols (PUA U+F5D0-U+F60D)
2025-12-24 16:42:45 -08:00
Daniel Imms 8b1306f46d More polish 2025-12-24 16:13:11 -08:00
Daniel Imms 6612153c44 Add alignment tests 2025-12-24 16:10:36 -08:00
Daniel Imms 2be529ce85 Polish definitions 2025-12-24 16:05:42 -08:00
Daniel Imms 96aa97ce11 Add extended symbols 2025-12-24 15:51:00 -08:00
Daniel Imms 98f4c3128c Stub second batch of glyphs 2025-12-24 15:35:46 -08:00
Daniel Imms ce1ab6fdc4 Correct order or curved glyphs 2025-12-24 15:31:49 -08:00
Daniel Imms e87e0f5443 Add git branch symbol alignment tests 2025-12-24 15:27:30 -08:00
Daniel Imms 4a8d8bd247 Partially implement git branch symbols
Part of #5477
2025-12-24 15:03:28 -08:00
Daniel Imms edf100a24b Merge pull request #5494 from Tyriar/tyriar/scale
Add char-based custom glyph scaling
2025-12-24 13:23:23 -08:00
Daniel Imms ed2d8b8fdc Merge branch 'master' into tyriar/scale 2025-12-24 12:36:32 -08:00
Daniel Imms faeefb53bf Merge pull request #5481 from BattlefieldDuck/fix/incorrect-theme-reference
Fix incorrect ITheme reference in comments
2025-12-24 12:29:40 -08:00
Daniel Imms 32ff1f2115 Merge pull request #5492 from Tyriar/sinon
Remove need for sinon
2025-12-24 12:25:41 -08:00
Daniel Imms acb59daf33 Fix lint 2025-12-24 12:20:12 -08:00
Daniel Imms a3d6bf6710 Merge pull request #5493 from Tyriar/tyriar/node
Upgrade missed parts from node 18 -> 22
2025-12-24 12:10:26 -08:00
Daniel Imms 5e5c623d8b Create test ts project in ligatures addon 2025-12-24 12:09:28 -08:00
Daniel Imms 168520f727 Upgrade missed parts from node 18 -> 22 2025-12-24 11:39:10 -08:00
Daniel Imms 23f61911e2 Remove need for sinon 2025-12-24 11:35:20 -08:00
Daniel Imms 491fa5586a Merge pull request #5491 from Tyriar/jsdom
Upgrade jsdom
2025-12-24 11:33:33 -08:00
Daniel Imms 2f549d74ae Merge pull request #5490 from Tyriar/lint
Update eslint and nyc
2025-12-24 11:26:35 -08:00
Daniel Imms 9df2430433 Upgrade jsdom 2025-12-24 11:26:19 -08:00
Daniel Imms ce9f6275ed Fix lint-api 2025-12-24 11:19:06 -08:00
Daniel Imms 9ca04799fe Merge remote-tracking branch 'origin/master' into lint 2025-12-24 11:16:01 -08:00
Daniel Imms 83757d1bf0 Polish arrow strokes 2025-12-24 11:13:58 -08:00
Daniel Imms 60fa9122a2 Remove old yarn rule and regen package lock 2025-12-24 10:46:59 -08:00
Daniel Imms a8d40a1edf Update eslint and nyc 2025-12-24 10:44:46 -08:00
Daniel Imms 78cc07f88a Split arrow parts into hybrid scaling 2025-12-24 10:30:34 -08:00
Daniel Imms 72d7c69a29 Add char-based custom glyph scaling
Draw calls can now be scaled by the char bounding box instead of the
cell bounding box. This means these character won't be stretched. Both
can also be used at the same like as is the case with 1FBBC RIGHT OPEN
SQUARED DOT.

Fixes #5488
2025-12-24 10:19:11 -08:00
Daniel Imms 0e0b445784 Merge pull request #5487 from Tyriar/tyriar/5480
Move customGlyphs option into webgl addon
2025-12-24 08:46:27 -08:00
Daniel Imms 5d24866042 Move customGlyphs option into webgl addon
Fixes #5480
2025-12-24 08:35:06 -08:00
Daniel Imms cbea462737 Merge pull request #5486 from Tyriar/tyriar/powerline_extra
Implement remaining powerline extra symbols
2025-12-24 08:23:39 -08:00
Daniel Imms a3ae94af1d Correct range 2025-12-24 08:18:19 -08:00
Daniel Imms 0e35521810 Add powerline alignment tests 2025-12-24 08:15:50 -08:00
Daniel Imms 40590fedfa Merge branch 'master' into tyriar/powerline_extra 2025-12-24 08:07:37 -08:00
Daniel Imms 1551d94de4 Implement remaining powerline extra symbols
- Uses fontforge + helper bin/convert_svg_to_custom_glyph.js
- Some of these are very large. They'll be much smaller after gzip but
  if this becomes a problem we can compile the svgs into a binary format

Fixes #5479
2025-12-24 08:06:20 -08:00
Daniel Imms d605803866 Merge pull request #5485 from Tyriar/tyriar/braille
Support custom gylphs for braille patterns (U+2800-U+28FF)
2025-12-24 07:09:40 -08:00
Daniel Imms a797852dfd Support custom gylphs for braille patterns (U+2800-U+28FF)
Fixes #5476
2025-12-24 07:00:53 -08:00
Daniel Imms d42f2b54ff Merge pull request #5484 from Tyriar/tyriar/fix_sextants
Fix sextant rendering
2025-12-24 06:43:57 -08:00
Daniel Imms 79084c3066 Fix sextant rendering
Broke in #5483
2025-12-24 06:38:21 -08:00
Daniel Imms b4f4946cca Merge pull request #5483 from Tyriar/glyph_cleanup
Consolidate custom glyph definition parts
2025-12-24 06:21:11 -08:00
Daniel Imms ed779b9062 Replace PATH_FUNCTION_WITH_WEIGHT with a generic strokeWidth prop 2025-12-24 06:14:41 -08:00
Daniel Imms 20fdfba16f Replace BLOCK_PATTERN_WITH_REGION with new clipPath 2025-12-24 04:33:32 -08:00
Daniel Imms 11dae84ff7 Support clip path on any draw definition 2025-12-24 04:25:59 -08:00
Daniel Imms 579573e77d Merge pull request #5482 from xtermjs/Tyriar-patch-1
Remove line ending editorconfig file
2025-12-24 04:24:04 -08:00
Daniel Imms 2114abe88c Support multiple glyphs with multiple draw calls 2025-12-24 04:19:14 -08:00
Daniel Imms d4fd96639f Remove line ending editorconfig file
This is normalized by git and ends up causing git status to show files that don't actually need to be committed after line ending normalization.
2025-12-24 04:18:31 -08:00
Daniel Imms 269d8c20ae Merge pull request #5475 from Tyriar/depc
Remove remnants of deprecated options
2025-12-24 04:03:49 -08:00
TatLead 49b49627f1 Fix incorrect ITheme reference in comments 2025-12-24 07:10:12 +08:00
Daniel Imms 663b94011a Remove remnants of deprecated options
Following up on #5462
2025-12-23 08:24:35 -08:00
Daniel Imms 54fcb1ea2f Merge pull request #5474 from Tyriar/demo_warn
Fix warnings in demo
2025-12-23 08:17:29 -08:00
Daniel Imms a9da3fbf05 Merge pull request #5473 from Tyriar/tyriar/5466_legacy_computing
Support entire Symbols for Legacy Computing unicode block (0x1FB00-0x1FBFF), add missing powerline symbol
2025-12-23 08:15:05 -08:00
Daniel Imms 091c3967f7 Fix warnings in demo 2025-12-23 08:12:12 -08:00
Daniel Imms 10d6ce3805 Update customGlyphs option 2025-12-23 08:09:46 -08:00
Daniel Imms eb285af11d Add diagonal alignment tests 2025-12-23 08:05:02 -08:00
Daniel Imms 0976935f87 Implement remaining Terminal graphic characters (1FBC0-1FBCA) 2025-12-23 07:42:57 -08:00
Daniel Imms 884b667f4e Implement stick figures 1FBC5-1FBC9 2025-12-23 07:04:19 -08:00
Daniel Imms b8843732bf Implement Terminal graphic characters (1FBCB-1FBCD) 2025-12-23 04:49:46 -08:00
Daniel Imms 44d8d2c873 Finish implementing Terminal graphic characters (1FBB9-1FBBC) 2025-12-23 04:28:45 -08:00
Daniel Imms 3d3abf9cf2 Implement folder 1FBB9-1FBBA 2025-12-23 04:22:19 -08:00
Daniel Imms 268f7af5db Implement running man 1FBB2 and 1FBB3 2025-12-23 04:15:41 -08:00
Daniel Imms 16b72dfd63 Mark powerline symbol range as reserved 2025-12-23 03:50:34 -08:00
Daniel Imms a0e658a18c Add column number powerline symbol 2025-12-23 03:42:41 -08:00
Daniel Imms ea6385f310 Comment alignment 2025-12-23 03:39:37 -08:00
Daniel Imms 02a9d2b047 Indicate reserved codepoints in demo 2025-12-23 03:30:02 -08:00
Daniel Imms 5c0c553936 Implement Arrows (1FBB4-1FBB8) 2025-12-22 19:46:35 -08:00
Daniel Imms eb743e0e19 Implement Terminal graphic character (1FBFA-1FBFA) 2025-12-22 19:15:00 -08:00
Daniel Imms 29d91fe264 Fill in remaining parts of legacy computing 2025-12-22 16:27:41 -08:00
Daniel Imms e8dcf46f39 Add PATH_NEGATIVE, simplify 1FBBD-1FBBF 2025-12-22 16:22:06 -08:00
Daniel Imms 66c1316f87 Implement ARROWHEAD-SHAPED POINTER 2025-12-22 15:43:53 -08:00
Daniel Imms e1803ed5a5 Implement Triangular shade characters (1FB9C-1FB9F) 2025-12-22 15:30:55 -08:00
Daniel Imms 1c3813f3d4 Implement Negative terminal graphic characters (1FBBD-1FBBF) 2025-12-22 15:28:51 -08:00
Daniel Imms e12aef9287 Implement Block elements (1FBCE-1FBCF) 2025-12-22 15:21:10 -08:00
Daniel Imms f5edba0b64 Improve docs on segmentedDigit 2025-12-22 15:18:42 -08:00
Daniel Imms 5a995e5595 Implement Geometric shapes (1FBE0-1FBEF) 2025-12-22 15:14:40 -08:00
Daniel Imms 2bae212f83 Implement Character cell diagonals (1FBD0-1FBDF) 2025-12-22 14:19:02 -08:00
Daniel Imms bde3680cd1 Implement 2 more parts 2025-12-22 14:15:26 -08:00
Daniel Imms 717399ceb6 Implement diagonal fill chars and light solid line with stroke 2025-12-22 14:04:51 -08:00
Daniel Imms 51121f1913 Stub legacy computing custom glyph ranges
Part of #5466
2025-12-22 13:42:38 -08:00
Daniel Imms 483acd3335 Merge pull request #5472 from Tyriar/tyriar/5466_refactor__unified
Custom glyph: Unify rendering function and move all definitions into a single ordered object
2025-12-22 13:31:36 -08:00
Daniel Imms 9dc8cecea3 Fix imports 2025-12-22 13:04:44 -08:00
Daniel Imms 89c2649504 Merge branch 'master' into tyriar/5466_refactor__unified 2025-12-22 12:57:03 -08:00
Daniel Imms 390076fc3f Order box drawing consistently 2025-12-22 12:56:16 -08:00
Daniel Imms a4edeed85d Add box drawing to custom glyph ranges test 2025-12-22 12:48:23 -08:00
Daniel Imms e61697fc86 Start organizing box drawing characters 2025-12-22 12:46:43 -08:00
Daniel Imms 9c019b44c3 unified -> customGlyph 2025-12-22 12:39:31 -08:00
Daniel Imms 5579d83f7d Move box drawing into unified 2025-12-22 12:39:14 -08:00
Daniel Imms 429065487a Move block elements and like into unified 2025-12-22 12:34:12 -08:00
Daniel Imms 219036cb0f Add powerline to glyph ranges test 2025-12-22 12:26:58 -08:00
Daniel Imms 3e80637145 Move powerline to unified 2025-12-22 12:14:50 -08:00
Daniel Imms 0af884d379 Correct shade rectangle rendering 2025-12-22 12:09:41 -08:00
Daniel Imms 5ae9ddf4b8 Add range to headers in ranges test 2025-12-22 12:06:59 -08:00
Daniel Imms 7ac068844c Fix warnings in unicodeTables.ts 2025-12-22 12:06:27 -08:00
Daniel Imms 5bf3d57d16 Move rectangular shade chars into unified 2025-12-22 12:05:47 -08:00
Daniel Imms 6461829411 Clean up symbols for legacy def 2025-12-22 11:48:45 -08:00
Daniel Imms efd6a52033 Support path without function 2025-12-22 11:46:53 -08:00
Daniel Imms 3d9e976cb3 Move main symbols for legacy computing into unified 2025-12-22 11:41:49 -08:00
Daniel Imms 415de67106 Start move to unified draw definition
Part of #5466
2025-12-22 11:35:41 -08:00
Daniel Imms c17c01086f Merge pull request #5471 from Tyriar/tyriar/5466_refactor
Refactor custom glyph to move into folder, split definition from raster
2025-12-22 11:34:43 -08:00
Daniel Imms ce41b175ee Remove cyclic dep 2025-12-22 11:11:50 -08:00
Daniel Imms 32b4547c5a Tweak symbol names 2025-12-22 11:09:02 -08:00
Daniel Imms b64543aa59 Make medium shade consistent, make all shades less heavy 2025-12-22 10:57:59 -08:00
Daniel Imms f049c42acc Add CustomGlyph to exports from rasterizer 2025-12-22 10:48:50 -08:00
Daniel Imms 28760cf482 Move custom glyphs into new folder 2025-12-22 10:47:35 -08:00
Daniel Imms 4982305b51 Split definitions and rasterizer 2025-12-22 10:46:53 -08:00
Daniel Imms 7fee40ddcd Merge pull request #5470 from Tyriar/tyriar/5466_shade
Custom glyph support for rectangular shade/combo chars
2025-12-22 10:41:54 -08:00
Daniel Imms 180183e876 Custom glyph support for rectangular shade/combo chars
Range: U+1FB8C-U+1FB94

Part of #5466
2025-12-22 10:29:22 -08:00
Daniel Imms 8308ede3f5 Merge pull request #5468 from Tyriar/5466_mosaic
Custom glyph support for mosaic terminal graphics chars
2025-12-22 10:27:53 -08:00
Daniel Imms a6db7b41f6 Suppress naming-convention for file as it conflicts with unicode props 2025-12-22 08:34:43 -08:00
Daniel Imms f11241d9de Custom glyph support for mosaic terminal graphics chars
Range: U+1FB3C-U+1FB6F

Part of #5466
2025-12-22 08:29:03 -08:00
Daniel Imms 937deb9f4b Merge pull request #5467 from Tyriar/5464_block_sextants
Custom glyph support for block sextants (U+1FB00-U+1FB3B)
2025-12-22 08:27:29 -08:00
Daniel Imms 6acc861b06 Lint 2025-12-22 07:54:47 -08:00
Daniel Imms 8f05b1854b Lint 2025-12-22 07:41:18 -08:00
Daniel Imms 0f461e7a3e Custom glyph support for block sextants (U+1FB00-U+1FB3B)
Fixes #5464
2025-12-22 07:33:43 -08:00
Daniel Imms 4237d82923 Merge pull request #5465 from Tyriar/5464_demo_helper
Add demo helper to print Symbols for Legacy Computing
2025-12-22 07:26:42 -08:00
Daniel Imms 187156764a Add demo helper to print Symbols for Legacy Computing
Range: 1FB00–1FBFF

Part of #5464
2025-12-22 07:16:22 -08:00
Daniel Imms f447274f43 Merge pull request #5463 from Tyriar/tyriar/v6
v6.0.0, bump addon versions, publish unicode graphemes
2025-12-22 05:48:49 -08:00
Daniel Imms f68d1e5d58 Skip sync output tests for now 2025-12-21 13:03:25 -08:00
Daniel Imms 30691e8b46 v6.0.0, bump addon versions, publish unicode graphemes
Part of #5147
2025-12-21 12:49:37 -08:00
Daniel Imms 5fa632518e Merge pull request #5462 from Tyriar/tyriar/deprecated
Remove deprecated windowsMode and fastScrollModifier
2025-12-21 05:06:56 -08:00
Daniel Imms 3571d1f51a Remove windowsMode in favor of windowsPty 2025-12-21 05:01:15 -08:00
Daniel Imms ebc0d83d8e Remove deprecated/unused fastScrollModifier 2025-12-21 04:58:45 -08:00
Daniel Imms d1c50c14e3 Merge pull request #5461 from Tyriar/tyriar/glob
Remove need for glob module
2025-12-20 08:44:33 -08:00
Daniel Imms 92b43bdf9b Remove only 2025-12-20 08:33:56 -08:00
Daniel Imms a9d3ca19f4 Merge pull request #5449 from iSuslov/exports/esm-headless-node
Configure "exports" field in package.json [headless]
2025-12-20 07:47:58 -08:00
Daniel Imms cb4d1ef2c0 Merge pull request #5453 from chrislloyd/feat/synchronized-output
Add synchronized output support (DEC mode 2026)
2025-12-20 07:44:32 -08:00
Daniel Imms 34fd0dcf53 Remove need for glob module 2025-12-20 07:44:24 -08:00
Daniel Imms 7335f15943 Merge pull request #5460 from Tyriar/tyriar/test-results
Git ignore test-results/
2025-12-20 07:37:43 -08:00
Daniel Imms 5e9cd6208f Git ignore test-results/ 2025-12-20 07:37:20 -08:00
Daniel Imms 6733e13a44 Invert initial assertion 2025-12-20 07:33:18 -08:00
Daniel Imms ad07f2cf76 Revert last frame request cache clearing 2025-12-20 07:23:20 -08:00
Daniel Imms 5396243bce Merge pull request #5450 from iSuslov/fix-esm-path-addon-unicode-graphemes
Fix wrong export path for ESM target in [addon-unicode-graphemes]
2025-12-20 07:20:08 -08:00
Daniel Imms 12c4f9536e Use underline cursor style to ensure cursor color isn't reported 2025-12-20 07:13:41 -08:00
Daniel Imms e9ba31f1b6 Explicitly set background color in playwright tests 2025-12-20 06:40:16 -08:00
Daniel Imms ed0ab5f9e4 Add missing property to headless API test assertion 2025-12-20 06:39:27 -08:00
Daniel Imms 0741f8be5c Merge pull request #5452 from iSuslov/upgrade-glob-version-fix-tsc-build
Fix tsc build - upgrade glob version
2025-12-20 06:37:06 -08:00
Daniel Imms 2edd121f1b Add node about serialize addon support 2025-12-20 06:17:31 -08:00
Daniel Imms 1eee5cdf18 Add synchronizedOutput mode to headless terminal object 2025-12-20 06:14:45 -08:00
Daniel Imms 20c1674d00 Update package-lock.json 2025-12-20 06:12:41 -08:00
Daniel Imms 32553fff06 Add synchronizedOutputMode to xterm-headless.d.ts 2025-12-20 06:05:36 -08:00
Daniel Imms 832aa54478 Fix colors and clear cached frames to pass tests 2025-12-20 06:04:11 -08:00
Daniel Imms 7f50b56ae4 Fix one playwright test 2025-12-10 08:44:13 -08:00
Daniel Imms bd361af105 Fix lint 2025-12-10 07:59:52 -08:00
Daniel Imms 9ea059de6f Move SynchronizedOutputHandler to bottom of file 2025-12-10 07:50:59 -08:00
Daniel Imms 7cdf3f9dd7 Prefer const enum so the number is inlined 2025-12-10 07:50:28 -08:00
Daniel Imms 7f81df5a3a Add BSU and ESU to VT tab in demo 2025-12-10 07:49:07 -08:00
Chris LloydandClaude af5dbfcd2c Add DECRQM support for synchronized output mode
Applications can now detect synchronized output support by querying
CSI ? 2026 $ p and receiving CSI ? 2026 ; <mode> $ y response.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-09 08:26:04 -08:00
Chris LloydandClaude 5d0eae8576 Fix spec URL to use master branch
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-09 08:23:37 -08:00
Chris LloydandClaude 6b63c5f260 Address PR review feedback for synchronized output
- Remove synchronizedOutputTimeout public API, hardcode 1s timeout
- Extract SynchronizedOutputHandler class for cleaner code
- Update spec URL to contour-terminal/vt-extensions
- Remove unnecessary comment in InputHandler
- Delete unit tests, add integration tests in SharedRendererTests
- Fix whitespace issue

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-09 07:58:31 -08:00
Chris LloydandClaude 7228e2e2dc Add synchronized output support (DEC mode 2026)
Implement synchronized output mode (CSI ? 2026 h/l) which allows
applications to batch terminal updates and render them atomically,
preventing screen tearing during rapid output.

Features:
- BSU (CSI ? 2026 h) pauses rendering, buffering row updates
- ESU (CSI ? 2026 l) flushes buffer and renders atomically
- Configurable timeout via synchronizedOutputTimeout option (default 5s)
- Exposed via terminal.modes.synchronizedOutputMode

Closes #3375

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-04 11:16:25 -08:00
Ivan Suslov a3e1ecf91b Fix tsc build - upgrade glob version 2025-12-04 07:28:40 -05:00
Ivan Suslov b41d3ef130 Fix ESM export path for addon-unicode-graphemes 2025-12-04 05:02:12 -05:00
Ivan Suslov 8338418471 Added exports field to headless package.json 2025-12-04 03:56:32 -05:00
Daniel Imms 46c510a76d Merge pull request #5413 from afska/patch-1
Adding EmuDevz to the "Real-world uses" list
2025-11-23 13:47:40 -08:00
Daniel Imms 80c3164070 Merge pull request #5446 from Tyriar/tyriar/npm
Migrate from yarn to npm, node 18 -> 22, use npm workspaces
2025-11-23 13:47:15 -08:00
Daniel Imms 236004ce6c Merge branch 'master' into tyriar/npm 2025-11-23 12:53:21 -08:00
Daniel Imms 741d9c3273 Remove install-addon calls 2025-11-23 10:00:21 -08:00
Daniel Imms bf4fb3ad64 Migrate to npm workspaces 2025-11-23 09:54:17 -08:00
Daniel Imms da4ab8a01e Remove peer dependency, generate lock files 2025-11-23 09:35:43 -08:00
Daniel Imms 92eddf8a61 Move to npm 2025-11-23 09:01:24 -08:00
Daniel Imms 637231e6e1 Merge pull request #5445 from Tyriar/tyriar/perf
Prefer performance.now() over Date.now()
2025-11-23 08:46:24 -08:00
Daniel Imms 6468a78237 Fix comment lint 2025-11-23 08:40:35 -08:00
Daniel Imms 98e234992b Prefer performance.now() over Date.now()
performance.now() is faster than Date.now() as there's no need to
consult the system clock. The more important part of this is that
performance.now() is monotonic and is guaranteed to never to backwards.
2025-11-23 08:32:35 -08:00
Daniel Imms e1023d7ec2 Merge pull request #5442 from Tyriar/tyriar/5441
Fix headless module path
2025-11-14 10:18:17 -08:00
Daniel Imms d186a3a115 Fix headless module path
Fixes #5441
2025-11-12 09:30:11 -08:00
Shuhei Takahashi d03416467d Fix key duplication on Android with physical keyboards
When typing rapidly on Android with physical keyboards, characters often
duplicate on the terminal. This is because physical keyboard events
always go through IME on Android, even for plain English characters, and
rapid typing causes a race condition in the composition helper.

This patch fixes the issue by making sure textarea changes are handled
correctly.
2025-11-07 12:33:59 +09:00
Daniel Imms 65a0e03b66 Merge pull request #5437 from xtermjs/anthonykim1/preventPageScrollWhenMouseOff
Prevent entire page from scrolling when scrolling in alt buffer with mouse event off
2025-11-02 03:54:46 -08:00
Anthony Kim 6ae020f51e add this.cancel(ev, true) when line is zero on wheel handler 2025-10-31 14:39:42 -07:00
Daniel Imms 6c79a46513 Merge pull request #5436 from xtermjs/merogge/serialize-range
add range to IHTMLSerializeOptions
2025-10-28 09:41:17 -07:00
meganrogge 4a62856153 fix test 2025-10-28 12:30:54 -04:00
meganrogge 5121867bbb rm line 2025-10-28 11:56:56 -04:00
meganrogge 5a467da137 pass in startLine, endLine, startCol 2025-10-28 11:46:41 -04:00
meganrogge 18bafaf9c9 fix indentation 2025-10-28 10:30:22 -04:00
meganrogge 5141a91bba add range to IHTMLSerializeOptions 2025-10-28 10:27:00 -04:00
Daniel Imms 9fce067266 Merge pull request #5425 from xtermjs/anthonykim1/parsingDataCharCode
Only show char codes for parsing data on trace
2025-10-22 19:08:47 -07:00
Daniel Imms 59241e467c Update src/common/InputHandler.ts 2025-10-22 19:02:14 -07:00
Anthony Kim 09e26980d3 I dont think we need () => in front of typeof data === 'string' 2025-10-22 16:23:35 -07:00
Anthony Kim c3bb36bad9 if trace, debug each AND remove array.from 2025-10-22 16:11:22 -07:00
Anthony Kim 2c57b3219b Only show char codes for parsing data on trace 2025-10-22 09:47:33 -07:00
Daniel Imms e9e8206467 Merge pull request #5423 from Tyriar/tyriar/resize5300
Clear selection on vertical resize
2025-10-19 01:21:28 -07:00
Daniel Imms 9a7517d3eb Clear selection on vertical resize
Fixes #5300
2025-10-19 01:15:30 -07:00
Daniel Imms 1bf90d9f47 Merge pull request #5422 from xtermjs/Tyriar-patch-1
Explain filtering unit tests by file
2025-10-18 13:49:38 -07:00
Daniel Imms 1527e89ad5 Explain filtering unit tests by file 2025-10-18 06:40:45 -07:00
Daniel Imms 95cc31566a Merge pull request #5421 from xtermjs/Tyriar-patch-1
Use Windows PowerShell instead of pwsh 7 in demo
2025-10-18 06:20:41 -07:00
Daniel Imms 7274e1bbea Use Windows PowerShell instead of pwsh 7 in demo
When pwsh 7 isn't installed it's hard to figure out what the problem is.
2025-10-18 06:15:19 -07:00
Daniel Imms a8fabcfa01 Merge pull request #5420 from xtermjs/anthonykim1/charCodesForVerbose
Only log character codes for trace log
2025-10-17 11:39:21 -07:00
Anthony Kim 67cf25989a only send codes, not the data when in trace 2025-10-17 11:26:34 -07:00
Anthony KimandDaniel Imms f87e574971 Update src/common/services/CoreService.ts
Co-authored-by: Daniel Imms <2193314+Tyriar@users.noreply.github.com>
2025-10-17 11:23:24 -07:00
Anthony Kim 5269462817 Only log character codes for verbose/trace 2025-10-17 10:12:10 -07:00
Anthony Kim f4baddaaf1 Merge pull request #5411 from xtermjs/anthonykim1/fixTeleportWhenAltScroll
Fix teleport when exiting out of alt buffer. v2
2025-10-17 09:20:23 -07:00
Rodrigo Alfonso 3aa836e5d7 Adding EmuDevz to the "Real-world uses" list 2025-10-10 03:24:12 -03:00
Anthony Kim 2a6e22e8f8 set this._latestYDisp = undefined onBufferActivate 2025-10-01 20:36:06 -07:00
Anthony Kim 32c3cb01a1 Make sure this._latestYDisp is up to date 2025-09-30 23:04:04 -07:00
Daniel Imms a1d8e96fdd Merge pull request #5406 from Tyriar/tyriar/search_refactor
Refactor search addon into multiple files, add unit tests
2025-09-26 18:24:44 +09:00
Daniel Imms c4780e54fd Merge branch 'master' into tyriar/search_refactor 2025-09-26 17:52:47 +09:00
Daniel Imms c56336b32b Fix unit tests 2025-09-26 17:49:20 +09:00
Daniel Imms d11f411c17 Bring back respecting of cached search term 2025-09-26 17:09:54 +09:00
Daniel Imms f03dfbb3ba Merge pull request #5407 from Tyriar/tyriar/bd09_copilot_instructions
Improve Copilot instructions and add test guidelines
2025-09-26 16:51:46 +09:00
Daniel Imms ffd6dc6ab7 Fix import issue 2025-09-19 09:06:53 -07:00
Daniel Imms 5b4b93acc6 Improve Copilot instructions and add test guidelines
- Enhanced copilot instructions with detailed architecture overview
- Added comprehensive development workflow documentation
- Documented addon development patterns and key examples
- Added project-specific conventions and TypeScript structure
- Included common patterns for parser integration and buffer access
- Added critical implementation details for rendering and events
- Created unit test instructions file with addon testing rules
- Specified preferences for assertions and self-documenting tests
2025-09-19 09:03:02 -07:00
Daniel Imms 2b329eb7b7 Search engine tests 2025-09-19 08:58:30 -07:00
Daniel Imms 9c5644ddc0 Add SearchEngine tests 2025-09-19 08:52:14 -07:00
Daniel Imms 398e87490d Add coding guidelines and lint-fix script
- Add coding guidelines section to copilot instructions
- Specify rule about avoiding comments in unit tests
- Add lint-fix npm script for auto-fixing ESLint issues
2025-09-18 13:27:12 -07:00
Daniel Imms a191370d54 refactor: remove unnecessary interface exports
- Remove export from IHighlight and IMultiHighlight interfaces
- Remove export from ISelectedDecoration interface
- Remove export from ISearchPosition interface
- Keep ISearchResult exported as it's used across multiple files
- Make ISelectedDecoration extend IDisposable for consistency
2025-09-18 13:26:43 -07:00
Daniel Imms bf9ce3bfaf Clean up SearchLineCache.test.ts comments
- Remove unnecessary inline comments from unit tests
- Add descriptive assertion messages where appropriate
- Follow coding guidelines for test comment usage
2025-09-18 13:21:07 -07:00
Daniel Imms ca7e8ca3b7 refactor(addon-search): extract components
- Extract SearchEngine for core search algorithms
- Extract DecorationManager for visual decorations
- Extract SearchState for state management
- Extract SearchResultTracker for result tracking
- Simplify SearchAddon by delegating to components
- Improve modularity and maintainability
2025-09-18 07:38:42 -07:00
Daniel Imms ab43a3bd22 Merge pull request #5405 from Tyriar/tyriar/b8d4_search_interface_refactor
Refactor search addon interfaces
2025-09-18 06:31:18 -07:00
Daniel Imms 32e58c71fe Refactor search addon interfaces
- Move ISearchAddonOptions and ISearchResultChangeEvent to types
- Make noScroll property required in IInternalSearchOptions
- Change exported interfaces to internal scope where appropriate
2025-09-18 06:25:12 -07:00
Daniel Imms b12a9393f1 Merge pull request #5404 from Tyriar/tyriar/1de3_timeout_cleanup
Replace timeout handling with disposableTimeout
2025-09-17 15:12:00 -07:00
Daniel Imms c27af4fa2e Remove thenable from more places 2025-09-17 15:06:33 -07:00
Daniel Imms 90bf20d9d8 Remove Thenable 2025-09-17 15:02:27 -07:00
Daniel Imms 8ffcbd98c4 Replace timeout handling with disposableTimeout
- Use disposableTimeout instead of manual timeout management
- Replace MutableDisposable pattern for SearchAddon highlight timeout
- Replace SearchLineCache timeout with MutableDisposable approach
- Clean up timeout disposal logic in both classes
2025-09-17 14:48:11 -07:00
Daniel Imms 15d90826f9 Merge pull request #5403 from Tyriar/tyriar/76c0_search_line_cache
Add SearchLineCache for improved search performance
2025-09-17 14:38:34 -07:00
Daniel Imms 304143a166 Add SearchLineCache for improved search performance
- Add SearchLineCache class to cache translated buffer lines
- Integrate caching into SearchAddon for line translation
- Improve search performance by avoiding repeated translation
- Add cache invalidation on terminal resize and writes
2025-09-17 14:28:03 -07:00
Daniel Imms 02b3704af0 Merge pull request #5402 from Tyriar/tyriar/9436_copilot_instructions
Update GitHub Copilot instructions with test details
2025-09-17 09:28:07 -07:00
Daniel Imms eb1330ca18 Merge pull request #5401 from Tyriar/tyriar/search-refactor
Refactor search addon types and internal handling
2025-09-17 09:22:07 -07:00
Daniel Imms 3a15c8080d Update GitHub Copilot instructions with test details
- Add comprehensive unit test examples with yarn test-unit
- Include integration test examples with yarn test-integration
- Document test filtering by file path and wildcard patterns
- Explain test runner frameworks (mocha and playwright)
2025-09-17 09:21:40 -07:00
Daniel Imms 6ac9f59ef4 Fix tests 2025-09-17 09:16:20 -07:00
Daniel Imms bffdc59901 Merge branch 'master' into tyriar/search-refactor 2025-09-17 08:53:54 -07:00
Daniel Imms 76a8a8e347 Refactor search addon types and internal handling
- Import search types from addon-search package
- Add IInternalSearchOptions interface for noScroll param
- Update _updateMatches to use internal search methods
- Pass internal options through search method chain
2025-09-17 08:52:38 -07:00
Daniel Imms e37aba5924 Merge pull request #5399 from Tyriar/tyriar/search-constants-refactor
Refactor search constants and improve documentation
2025-09-17 08:16:51 -07:00
Daniel Imms 5c0107462e Merge pull request #5379 from xtermjs/dependabot/npm_and_yarn/addons/addon-ligatures/form-data-4.0.4
Bump form-data from 4.0.0 to 4.0.4 in /addons/addon-ligatures
2025-09-17 08:13:12 -07:00
Daniel Imms 87a45acae7 Refactor search constants and improve documentation
- Convert standalone constants to Constants enum with detailed docs
- Fix spacing issue in SearchAddon class declaration
- Update all references to use Constants enum for consistency
2025-09-17 08:06:56 -07:00
Daniel Imms ab01a5fd65 Merge pull request #5398 from Tyriar/tyriar/search-api-typing
Add proper typing for search results change event
2025-09-17 07:54:29 -07:00
Daniel Imms 6e833e5d5d Add proper typing for search results change event
- Export ISearchResultChangeEvent interface in addon-search
- Use proper Event<T> typing instead of inline object
- Improve API consistency and type safety for consumers
2025-09-17 07:33:43 -07:00
Daniel Imms d7d7f1b023 Merge pull request #5391 from Tyriar/tyriar/mouse_events
Bring back partial wheel tracking
2025-09-09 18:42:38 -07:00
Anthony Kim 9c42fb348b ignore fastScrollModifier 2025-09-09 13:21:37 -07:00
Anthony Kim e4f222f6b0 Make test happy 2025-09-09 12:03:51 -07:00
Anthony Kim 38bee71630 More clear comments 2025-09-09 12:00:19 -07:00
Anthony Kim 1a6a807f68 Remove stale comment 2025-09-09 11:59:29 -07:00
Anthony Kim 03ce26c697 Questions, possible concern 2025-09-09 11:56:28 -07:00
Anthony Kim cf6b868dfb fastScrollModifier seems deprecated 2025-09-09 11:51:27 -07:00
Anthony Kim d862c82386 no stale comments 2025-09-08 21:14:20 -07:00
Anthony Kim 50df7a69e6 remove unused var 2025-09-08 21:06:37 -07:00
Anthony Kim 26ecba8de1 Fix sluggish mouse problem. Now similar to trackpad 2025-09-08 21:03:05 -07:00
Daniel Imms 0d1e6b7a5e Merge pull request #5390 from xtermjs/anthonykim1/fixTeleportAltBuffer
Fix scrollbar teleport after exiting alt buffer
2025-08-29 05:41:52 -07:00
Anthony Kim b104a5b953 Respect original formatting 2025-08-28 22:56:15 -07:00
Anthony Kim ebddd5d346 Move from CoreBrowerTerminal to CoreMouseService. Still slow though 2025-08-28 22:54:50 -07:00
Daniel Imms 5bd7b4aaec Bring back partial wheel tracking
Part of microsoft/vscode#224750
2025-08-28 10:28:19 -07:00
Anthony Kim a6fdf043ce Respect original formatting 2025-08-28 08:57:25 -07:00
Anthony Kim 287702610c More clean up after removing test 2025-08-28 08:54:01 -07:00
Anthony Kim 4d59eca5f9 Clean up 2025-08-28 08:52:46 -07:00
Anthony Kim 753ea81fc0 BufferService listen to onBufferActivate, remove tests 2025-08-28 08:46:27 -07:00
Anthony Kim 675b2c3a70 Improve test 2025-08-27 21:31:34 -07:00
Anthony Kim 86745e1320 Add some tests from copilot 2025-08-27 21:12:15 -07:00
Anthony Kim a3ab942ea1 Fix teleport issue when coming back from alt buffer 2025-08-27 20:45:52 -07:00
Daniel Imms e969832946 Merge pull request #5385 from anthonykim1/anthonykim1/fixWrappedTerminalFind
Fix terminal find when wrapped
2025-08-21 12:40:01 -07:00
Anthony Kim 95a9531ec1 Try to add tests 2025-08-20 22:49:03 -07:00
Daniel Imms 7637a2de19 Merge pull request #5386 from alexkozy/safe-guards
fix: ensure that currentRow can not go out of the range
2025-08-20 14:15:08 -07:00
Alexey Kozy a589be2826 fix: ensure that currentRow can not go out of the range 2025-08-20 13:47:40 -07:00
Anthony Kim b53096f4a2 Clean code 2025-08-20 10:55:47 -07:00
Anthony Kim 687d8277e7 Fix terminal find when wrapped 2025-08-20 10:53:40 -07:00
Daniel Imms 4c0cf27cfc Merge pull request #5334 from CodinGame/webgl-renderer-shadow-dom
Support shadow dom in webgl renderer
2025-07-31 08:32:44 -07:00
Loïc Mangeonjean 149527ddb8 refactor: apply requested style change 2025-07-31 17:08:30 +02:00
dependabot[bot] 9c3eb170d2 Bump form-data from 4.0.0 to 4.0.4 in /addons/addon-ligatures
Bumps [form-data](https://github.com/form-data/form-data) from 4.0.0 to 4.0.4.
- [Release notes](https://github.com/form-data/form-data/releases)
- [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md)
- [Commits](https://github.com/form-data/form-data/compare/v4.0.0...v4.0.4)

---
updated-dependencies:
- dependency-name: form-data
  dependency-version: 4.0.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-21 23:07:47 +00:00
Daniel Imms c4b707e9ca Merge pull request #5362 from Tyriar/tyriar/steps2
Move copilot steps to correct folder
2025-06-21 11:01:00 -07:00
Daniel Imms 9d35d59fb3 Move copilot steps to correct folder 2025-06-21 11:00:33 -07:00
Loïc Mangeonjean 3ad83dd70e chore: add webgl shadow dom test 2025-05-21 21:51:01 +02:00
Loïc Mangeonjean 496b53d84d fix: support shadow dom in webgl renderer 2025-05-20 16:31:17 +02:00
Jörg Breitbart 085a275038 fix promise return, reject on missing family name, doc polish 2024-10-06 23:53:30 +02:00
Jörg Breitbart 104c63d7e0 cleanup files 2024-10-04 17:52:45 +02:00
Jörg Breitbart 70c9861c39 Merge branch 'master' into webfonts-addon 2024-10-04 17:51:18 +02:00
Jörg Breitbart c93623cb3b CI tests 2024-10-04 14:24:36 +02:00
Jörg Breitbart b0389a2ed1 future proof demo 2024-10-04 05:31:47 +02:00
Jörg Breitbart 7907f13774 add license notes for fonts 2024-10-04 04:14:10 +02:00
Jörg Breitbart 956c7cbcba demo tests 2024-10-04 04:00:20 +02:00
Jörg Breitbart 23bef99132 cleanup API 2024-10-04 02:06:02 +02:00
Jörg Breitbart b104bcd144 remove await remnants 2024-10-04 00:42:38 +02:00
Jörg Breitbart 809b9aa1ad fix test runner 2024-10-04 00:15:49 +02:00
Jörg Breitbart 9a536f758d fix integration test runner 2024-10-03 22:23:31 +02:00
Jörg Breitbart 15a63bae22 change to global replacement 2024-10-03 22:10:40 +02:00
Jörg Breitbart 41640d9402 make linter happy 2024-10-03 22:07:10 +02:00
Jörg Breitbart 15664de472 initial 2024-10-03 21:50:34 +02:00
236 changed files with 27186 additions and 10108 deletions
+3 -3
View File
@@ -1,15 +1,15 @@
{
"name": "xterm.js",
"image": "mcr.microsoft.com/devcontainers/typescript-node:18-bookworm",
"image": "mcr.microsoft.com/devcontainers/typescript-node:22-bookworm",
"features": {
"ghcr.io/devcontainers/features/node:1": {
"version": 18
"version": 22
} // yarn
},
"forwardPorts": [
3000
],
"postCreateCommand": "yarn install && yarn setup",
"postCreateCommand": "npm install && npm run setup",
"customizations": {
"vscode": {
"extensions": [
-1
View File
@@ -5,7 +5,6 @@ indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
[*.{j,t}s]
max_line_length = 100
-273
View File
@@ -1,273 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": [
"demo/tsconfig.json",
"src/browser/tsconfig.json",
"src/common/tsconfig.json",
"src/headless/tsconfig.json",
"src/vs/tsconfig.json",
"test/benchmark/tsconfig.json",
"test/playwright/tsconfig.json",
"addons/addon-attach/src/tsconfig.json",
"addons/addon-attach/test/tsconfig.json",
"addons/addon-clipboard/src/tsconfig.json",
"addons/addon-clipboard/test/tsconfig.json",
"addons/addon-fit/src/tsconfig.json",
"addons/addon-fit/test/tsconfig.json",
"addons/addon-image/src/tsconfig.json",
"addons/addon-image/test/tsconfig.json",
"addons/addon-ligatures/src/tsconfig.json",
"addons/addon-progress/src/tsconfig.json",
"addons/addon-progress/test/tsconfig.json",
"addons/addon-search/src/tsconfig.json",
"addons/addon-search/test/tsconfig.json",
"addons/addon-serialize/src/tsconfig.json",
"addons/addon-serialize/test/tsconfig.json",
"addons/addon-serialize/benchmark/tsconfig.json",
"addons/addon-unicode11/src/tsconfig.json",
"addons/addon-unicode11/test/tsconfig.json",
"addons/addon-unicode-graphemes/src/tsconfig.json",
"addons/addon-unicode-graphemes/test/tsconfig.json",
"addons/addon-unicode-graphemes/benchmark/tsconfig.json",
"addons/addon-web-links/src/tsconfig.json",
"addons/addon-web-links/test/tsconfig.json",
"addons/addon-webgl/src/tsconfig.json",
"addons/addon-webgl/test/tsconfig.json"
],
"sourceType": "module"
},
"ignorePatterns": [
"addons/*/src/third-party/*.ts",
"src/vs/*",
"out/*",
"out-test/*",
"out-esbuild/*",
"out-esbuild-test/*",
"**/inwasm-sdks/*",
"**/typings/*.d.ts",
"**/node_modules",
"**/*.js",
"**/*.mjs"
],
"plugins": [
"@stylistic/ts",
"@typescript-eslint",
"jsdoc"
],
"rules": {
"@stylistic/ts/indent": [
"warn",
2
],
"@stylistic/ts/semi": [
"warn",
"always"
],
"@stylistic/ts/quotes": [
"warn",
"single",
{ "allowTemplateLiterals": true }
],
"@typescript-eslint/array-type": [
"warn",
{
"default": "array",
"readonly": "generic"
}
],
"@typescript-eslint/consistent-type-assertions": "warn",
"@typescript-eslint/consistent-type-definitions": "warn",
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowExpressions": true
}
],
"@typescript-eslint/explicit-member-accessibility": [
"warn",
{
"accessibility": "explicit",
"overrides": {
"constructors": "off"
}
}
],
"@typescript-eslint/member-delimiter-style": [
"warn",
{
"multiline": {
"delimiter": "semi",
"requireLast": true
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/naming-convention": [
"warn",
{ "selector": "default", "format": ["camelCase"],
"filter": {
"regex": "^[a-z]",
"match": true
}
},
// variableLike
{ "selector": "variable", "format": ["camelCase", "UPPER_CASE"] },
{ "selector": "variable", "filter": "^I.+Service$", "format": ["PascalCase"], "prefix": ["I"] },
// memberLike
{ "selector": "memberLike", "modifiers": ["private"], "format": ["camelCase"], "leadingUnderscore": "require" },
{ "selector": "memberLike", "modifiers": ["protected"], "format": ["camelCase"], "leadingUnderscore": "require" },
{ "selector": "enumMember", "format": ["UPPER_CASE"] },
// memberLike - Allow enum-like objects to use UPPER_CASE
{ "selector": "property", "modifiers": ["public"], "format": ["camelCase", "UPPER_CASE"],
"filter": {
"regex": "^[a-z]",
"match": true
}
},
// restrict on* naming for events only
{ "selector": "method", "modifiers": ["public"], "format": ["camelCase", "UPPER_CASE"], "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
{ "selector": "method", "modifiers": ["private"], "format": ["camelCase"], "leadingUnderscore": "require", "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
{ "selector": "method", "modifiers": ["protected"], "format": ["camelCase"], "leadingUnderscore": "require", "custom": {
"regex": "^on[A-Z].+",
"match": false
} },
// typeLike
{ "selector": "typeLike", "format": ["PascalCase"] },
{ "selector": "interface", "format": ["PascalCase"], "prefix": ["I"] }
],
"@typescript-eslint/no-confusing-void-expression": [
"warn",
{ "ignoreArrowShorthand": true }
],
"@typescript-eslint/no-useless-constructor": "warn",
"@typescript-eslint/prefer-namespace-keyword": "warn",
"@typescript-eslint/type-annotation-spacing": "warn",
"comma-dangle": [
"warn",
{
"objects": "never",
"arrays": "never",
"functions": "never"
}
],
"curly": [
"warn",
"multi-line"
],
"eol-last": "warn",
"eqeqeq": [
"warn",
"always"
],
"jsdoc/check-alignment": 1,
"jsdoc/check-param-names": 1,
"jsdoc/no-multi-asterisks": 1,
"keyword-spacing": "warn",
"max-len": [
"warn",
{
"code": 1000, // Don't enforce for code
"comments": 100,
"ignoreTrailingComments": true,
"ignoreUrls": true,
"ignorePattern": "^ *((?<vt_comment>(//|\\*) @vt)|(?<table_comment>\\* \\| )|(?<commented_code>// ))"
}
],
"new-parens": "warn",
"no-duplicate-imports": "warn",
"no-else-return": [
"warn",
{
"allowElseIf": false
}
],
"no-eval": "warn",
"no-extra-semi": "error",
"no-irregular-whitespace": "warn",
"no-restricted-imports": [
"warn",
{
"patterns": [
".*\\/out\\/.*"
]
}
],
"no-restricted-syntax": [
"warn",
{
"selector": "CallExpression[callee.name='requestAnimationFrame']",
"message": "The global requestAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression[callee.name='cancelAnimationFrame']",
"message": "The global cancelAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression > MemberExpression[object.name='window'][property.name='requestAnimationFrame']",
"message": "window.requestAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "CallExpression > MemberExpression[object.name='window'][property.name='cancelAnimationFrame']",
"message": "window.cancelAnimationFrame() should be avoided, call it on the parent window from ICoreBrowserService."
},
{
"selector": "MemberExpression[object.name='window'][property.name='devicePixelRatio']",
"message": "window.devicePixelRatio should be avoided, get it from ICoreBrowserService."
}
],
"no-trailing-spaces": "warn",
"no-unsafe-finally": "warn",
"no-unused-vars": ["warn", {
"vars": "all",
"args": "none"
}],
"no-var": "warn",
"one-var": [
"warn",
"never"
],
"object-curly-spacing": [
"warn",
"always"
],
"prefer-const": "warn",
"spaced-comment": [
"warn",
"always",
{
"markers": ["/"],
"exceptions": ["-"]
}
]
},
"overrides": [
{
"files": [
"**/*.api.ts",
"**/*.test.ts"
],
"rules": {
"object-curly-spacing": "off",
"max-len": "off",
"no-unused-vars": "off"
}
}
]
}
-107
View File
@@ -1,107 +0,0 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@stylistic/ts",
"@typescript-eslint",
"jsdoc"
],
"rules": {
"@stylistic/ts/indent": [
"warn",
2
],
"@stylistic/ts/semi": [
"warn",
"always"
],
"@stylistic/ts/quotes": [
"warn",
"single",
{ "allowTemplateLiterals": true }
],
"@typescript-eslint/array-type": [
"warn",
{
"default": "array",
"readonly": "generic"
}
],
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowExpressions": true
}
],
"@typescript-eslint/member-delimiter-style": [
"warn",
{
"multiline": {
"delimiter": "semi",
"requireLast": true
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/naming-convention": [
"warn",
{ "selector": "typeLike", "format": ["PascalCase"] },
{ "selector": "interface", "format": ["PascalCase"], "prefix": ["I"] }
],
"@typescript-eslint/prefer-namespace-keyword": "warn",
"@typescript-eslint/type-annotation-spacing": "warn",
"comma-dangle": [
"warn",
{
"objects": "never",
"arrays": "never",
"functions": "never"
}
],
"curly": [
"warn",
"multi-line"
],
"eol-last": "warn",
"eqeqeq": [
"warn",
"always"
],
"jsdoc/check-alignment": 1,
"jsdoc/check-param-names": 1,
"keyword-spacing": "warn",
"max-len": [
"warn",
{
"code": 1000, // Don't enforce for code
"comments": 80,
"ignoreUrls": true,
"ignorePattern": "^ *(?<ps_description>\\* Ps=)"
}
],
"no-extra-semi": "error",
"no-irregular-whitespace": "warn",
"no-trailing-spaces": "warn",
"object-curly-spacing": [
"warn",
"always"
],
"spaced-comment": [
"warn",
"always",
{
"markers": ["/"],
"exceptions": ["-"]
}
]
}
}
+90 -7
View File
@@ -1,10 +1,93 @@
This is a TypeScript-based repository with a Ruby client for certain API endpoints. It includes several sub projects called addons which are built separately. It contains a demo application which showcases the functionality of the project.
# xterm.js Copilot Instructions
Please follow these guidelines when contributing:
## Architecture Overview
## Development Flow
**Core Structure**: xterm.js is a multi-target terminal emulator with three main distributions:
- `src/browser/`: Full-featured browser terminal with DOM rendering
- `src/headless/`: Server-side terminal for Node.js (no DOM)
- `src/common/`: Shared core logic (parsing, buffer management, terminal state)
- Install dependencies: `npm install && npm run setup`
- Build and bundle demo: `npm run build && npm run esbuild`
- Run unit tests: `npm run test-unit`
- Run playwright-based integration tests: `npm run test-integration`
**Key Classes**:
- `Terminal` (browser/headless): Public API wrapper
- `CoreTerminal` (common): Core terminal logic and state
- `CoreBrowserTerminal` (browser): Browser-specific terminal implementation
## Development Workflow
**Build System**:
```bash
npm run build && npm run esbuild # Build all TypeScript and bundle
```
**Testing**:
- Unit tests: `npm run test-unit` (Mocha)
- Unit tests filtering to file: `npm run test-unit -- **/fileName.ts
- Per-addon unit tests: `npm run test-unit addons/addon-image/out-esbuild/*.test.js`
- Integration tests: `npm run test-integration` (Playwright across Chrome/Firefox/WebKit)
- Integration tests by file: `npm run test-integration -- test/playwright/InputHandler.test.ts`. Never use grep to filter tests, it doesn't work
- Integration tests by addon: `npm run test-integration --suite=addon-search`. Suites always follow the format `addon-<something>`
- Lint changes: `npm run lint-changes` to lint only changed files, `npm run lint-changes-fix` to fix them
## Addon Development Pattern
All addons follow this structure:
```typescript
export class MyAddon implements ITerminalAddon {
activate(terminal: Terminal): void {
// Called when loaded via terminal.loadAddon()
// Register handlers, access terminal APIs
}
dispose(): void {
// Cleanup when addon is disposed
}
}
```
**Key Examples**:
- `addons/addon-fit/`: Terminal sizing
- `addons/addon-webgl/`: GPU-accelerated rendering
- `addons/addon-search/`: Text search functionality
## Project-Specific Conventions
**TypeScript Project Structure**: Uses TypeScript project references (`tsconfig.all.json`) for incremental builds across browser/headless/addons.
**API Design**:
- Browser and headless terminals share the same public API
- Proposed APIs require `allowProposedApi: true` option
- Constructor-only options (cols, rows) cannot be changed after instantiation
**Testing Utilities**: Use `TestUtils.ts` helpers:
- `openTerminal(ctx, options)` for setup
- `pollFor(page, fn, expectedValue)` for async assertions
- `writeSync(page, data)` for terminal input
## Common Patterns
**Parser Integration**: Register custom escape sequence handlers:
```typescript
terminal.parser.registerCsiHandler('m', params => {
// Handle SGR sequences
return true; // Handled
});
```
**Buffer Access**: Read terminal content via buffer API:
```typescript
const line = terminal.buffer.active.getLine(0);
const cell = line?.getCell(0);
```
**Events**: All terminals emit standard events (onData, onResize, onRender) plus platform-specific ones.
## Critical Implementation Details
- Terminal rendering uses either DOM or WebGL renderers
- Buffer lines are immutable; create new instances for modifications
- Character width handling supports Unicode 11+ and grapheme clustering
- Mouse events translate web events to terminal protocols (X10, VT200, etc.)
- Color theming supports both palette and true color modes
## Writing unit tests
- Unit tests live alongside the source code file of the thing it's testing with a .test.ts suffix.
@@ -0,0 +1,8 @@
---
applyTo: '**/*.test.ts'
---
When writing unit tests follow these rules:
- When writing unit tests for addons, always create a real xterm.js instance instead of mocking it.
- Prefer `assert.ok` over `assert.notStrictEqual` when checking something is undefined or not.
- Avoid comments as most tests should be self-documenting.
+49 -47
View File
@@ -12,17 +12,17 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- name: Use Node.js 18.x
- name: Use Node.js 22.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'yarn'
node-version: 22.x
cache: 'npm'
- name: Install dependencies
run: yarn --frozen-lockfile
run: npm ci
- name: Setup and run tsc
run: yarn setup
run: npm run setup
- name: Esbuild
run: yarn esbuild
run: npm run esbuild
- name: Zip artifacts
run: |
zip -r compressed-build \
@@ -62,6 +62,9 @@ jobs:
./addons/addon-web-links/lib/* \
./addons/addon-web-links/out/* \
./addons/addon-web-links/out-*/* \
./addons/addon-web-fonts/lib/* \
./addons/addon-web-fonts/out/* \
./addons/addon-web-fonts/out-*/* \
./addons/addon-webgl/lib/* \
./addons/addon-webgl/out/* \
./addons/addon-webgl/out-*st/*
@@ -77,21 +80,20 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- name: Use Node.js 18.x
- name: Use Node.js 22.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'yarn'
node-version: 22.x
cache: 'npm'
- name: Install dependencies
run: |
yarn --frozen-lockfile
yarn install-addons
npm ci
- name: Lint code
env:
NODE_OPTIONS: --max_old_space_size=4096
run: yarn lint
run: npm run lint
- name: Lint API
run: yarn lint-api
run: npm run lint-api
test-unit-coverage:
needs: build
@@ -99,15 +101,14 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- name: Use Node.js 18.x
- name: Use Node.js 22.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'yarn'
node-version: 22.x
cache: 'npm'
- name: Install dependencies
run: |
yarn --frozen-lockfile
yarn install-addons
npm ci
- uses: actions/download-artifact@v4
with:
name: build-artifacts
@@ -122,7 +123,7 @@ jobs:
ls -R
- name: Unit test coverage
run: |
yarn test-unit-coverage --forbid-only
npm run test-unit-coverage --forbid-only
EXIT_CODE=$?
./node_modules/.bin/nyc report --reporter=cobertura
exit $EXIT_CODE
@@ -131,7 +132,7 @@ jobs:
timeout-minutes: 20
strategy:
matrix:
node-version: [18]
node-version: [22]
runs-on: [ubuntu, macos, windows]
runs-on: ${{ matrix.runs-on }}-latest
steps:
@@ -140,11 +141,10 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}.x
cache: 'yarn'
cache: 'npm'
- name: Install dependencies
run: |
yarn --frozen-lockfile
yarn install-addons
npm ci
- name: Wait for build job
uses: NathanFirmo/wait-for-other-job@v1.1.1
with:
@@ -163,13 +163,13 @@ jobs:
fi
ls -R
- name: Unit tests
run: yarn test-unit --forbid-only
run: npm run test-unit --forbid-only
test-integration:
timeout-minutes: 20
strategy:
matrix:
node-version: [18] # just one as integration tests are about testing in browser
node-version: [22] # just one as integration tests are about testing in browser
runs-on: [ubuntu-22.04] # macos is flaky
browser: [chromium, firefox, webkit]
runs-on: ${{ matrix.runs-on }}
@@ -179,11 +179,10 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}.x
cache: 'yarn'
cache: 'npm'
- name: Install dependencies
run: |
yarn --frozen-lockfile
yarn install-addons
npm ci
- name: Install playwright
run: npx playwright install --with-deps ${{ matrix.browser }}
- name: Wait for build job
@@ -203,50 +202,53 @@ jobs:
unzip -o compressed-build.zip
fi
ls -R
- name: Build demo
run: yarn esbuild-demo
- name: Build demo client
run: npm run esbuild-demo-client
- name: Build demo server
run: npm run esbuild-demo-server
- name: Integration tests (core) # Tests use 50% workers to reduce flakiness
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=core
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=core
- name: Integration tests (addon-attach)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-attach
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-attach
- name: Integration tests (addon-clipboard)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-clipboard
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-clipboard
- name: Integration tests (addon-fit)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-fit
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-fit
- name: Integration tests (addon-image)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-image
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-image
- name: Integration tests (addon-progress)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-progress
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-progress
- name: Integration tests (addon-search)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-search
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-search
- name: Integration tests (addon-serialize)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-serialize
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-serialize
- name: Integration tests (addon-unicode-graphemes)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode-graphemes
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode-graphemes
- name: Integration tests (addon-unicode11)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode11
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-unicode11
- name: Integration tests (addon-web-fonts)
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-fonts
- name: Integration tests (addon-web-links)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-links
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-web-links
- name: Integration tests (addon-webgl)
run: yarn test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-webgl
run: npm run test-integration-${{ matrix.browser }} --workers=50% --forbid-only --suite=addon-webgl
release-dry-run:
needs: build
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18]
node-version: [22]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}.x
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}.x
cache: 'yarn'
cache: 'npm'
- name: Install dependencies
run: |
yarn --frozen-lockfile
yarn install-addons
npm ci
- name: Install playwright
run: npx playwright install
- uses: actions/download-artifact@v4
@@ -263,7 +265,7 @@ jobs:
ls -R
- name: Package headless
run: |
yarn package-headless
npm run package-headless
node ./bin/package_headless.js
- name: Publish to npm (dry run)
run: node ./bin/publish.js --dry
@@ -19,18 +19,14 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Use Node.js 20.x
- name: Use Node.js 22.x
uses: actions/setup-node@v3
with:
node-version: 20.x
cache: 'yarn'
node-version: 22.x
cache: 'npm'
- name: Install dependencies
run: yarn --frozen-lockfile
run: npm ci
- name: Setup and run tsc
run: yarn setup
run: npm run setup
- name: Esbuild
run: yarn esbuild
run: npm run esbuild
+6 -6
View File
@@ -11,18 +11,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node.js 18.x
- name: Use Node.js 22.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'yarn'
node-version: 22.x
cache: 'npm'
- name: Install dependencies
run: yarn --frozen-lockfile
run: npm ci
- name: Build
run: yarn setup
run: npm run setup
- name: Package headless
run: |
yarn package-headless
npm run package-headless
node ./bin/package_headless.js
- name: Publish to npm
env:
+3 -1
View File
@@ -3,6 +3,7 @@ node_modules/
.lock-wscript
lib/
out/
out-demo/
out-test/
out-esbuild/
out-esbuild-test/
@@ -18,7 +19,8 @@ npm-debug.log
.env
build/
.DS_Store
package-lock.json
yarn.lock
test-results/
# Keep bundled code out of Git
dist/
-7
View File
@@ -1,7 +0,0 @@
Antonis Kalipetis <akalipetis@sourcelair.com>
Antonis Kalipetis <akalipetis@sourcelair.com> <akalipetis@gmail.com>
Daniel Imms <daimms@microsoft.com> <tyriar@tyriar.com>
Paris Kasidiaris <paris@sourcelair.com>
Paris Kasidiaris <pariskasidiaris@gmail.com>
Thanasis Daglis <thanasis@sourcelair.com>
Thanasis Daglis <thanasis@sourcelair.com> <ath.daglis@gmail.com>
-1
View File
@@ -1 +0,0 @@
NODE_PATH=./out
-5
View File
@@ -1,5 +0,0 @@
require:
- source-map-support/register
reporter: spec
color: true
check-leaks: true
-1
View File
@@ -1 +0,0 @@
package-lock=false
+1 -1
View File
@@ -1 +1 @@
18
22
+5
View File
@@ -0,0 +1,5 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
}
+1 -1
View File
@@ -61,7 +61,7 @@
"runtimeExecutable": "npm",
"runtimeArgs": ["start"],
"stopOnEntry": true,
"runtimeVersion": "18",
"runtimeVersion": "22",
"serverReadyAction": {
"action": "openExternally",
"pattern": "App listening to (http://.*?:[0-9]+)"
+1 -20
View File
@@ -1,23 +1,4 @@
{
"files.associations": {
".eslintrc.json.typings": "jsonc"
},
"files.exclude": {
"**/.nyc_output": true
},
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.preferences.quoteStyle": "single",
"mochaExplorer.envPath": ".mocha.env",
"mochaExplorer.files": [
"out/**/*.test.js",
"addons/**/out/*.test.js",
"out-*/**/*.test.js",
"addons/**/out-*/*.test.js"
],
"mochaExplorer.watch": [
"out/**/*.js",
"addons/**/out/*.js",
"out-*/**/*.js",
"addons/**/out-*/*.js"
]
"typescript.preferences.quoteStyle": "single"
}
+25 -4
View File
@@ -10,13 +10,22 @@
"tasks": [
// Compound tasks
{
"label": "Development",
"dependsOn": ["demo-server", "tsc", "esbuild", "esbuild-demo"],
"label": "dev",
"detail": "Runs all tasks required to run the demo in a single terminal using concurrently. This does not support problem matching.",
"type": "npm",
"script": "dev",
"isBackground": true,
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "dev (separate terminals)",
"detail": "Runs all tasks required to run the demo in separate terminals. This does support problem matching.",
"dependsOn": ["demo-server", "tsc", "esbuild", "esbuild-demo-client", "esbuild-demo-server"],
"group": "build"
},
// Demo
{
@@ -55,9 +64,21 @@
}
},
{
"label": "esbuild-demo",
"label": "esbuild-demo-client",
"type": "npm",
"script": "esbuild-demo-watch",
"script": "esbuild-demo-client-watch",
"dependsOn": ["esbuild", "tsc"],
"group": "build",
"isBackground": true,
"problemMatcher": "$esbuild-watch",
"presentation": {
"group": "xterm-demo"
}
},
{
"label": "esbuild-demo-server",
"type": "npm",
"script": "esbuild-demo-server-watch",
"dependsOn": ["esbuild", "tsc"],
"group": "build",
"isBackground": true,
+35 -89
View File
@@ -1,104 +1,50 @@
# How to contribute to xterm.js
- [Opening issues for bug reports or feature requests](#opening-issues)
- [Contributing code](#contributing-code)
- [Opening issues](#opening-issues)
- [Answering discussion questions](#answering-discussion-questions)
## Contributing code
You can find issues to work on by looking at issues labeled with [help wanted](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) or [good first issue](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). It's a good idea to comment on the issue saying that you're looking into it, just in case someone else comes along and you duplicate work. Once you have your issue, here are the steps to contribute:
- Fork [xterm.js](https://github.com/xtermjs/xterm.js/) ([how to fork a repo](https://help.github.com/articles/fork-a-repo)).
- Get the [xterm.js demo](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo) running.
- Make the fix and verify it works in the demo. Be sure to follow thew general code style of the rest of the project.
- If your changes are easy to test or likely to regress in the future, add tests. These could be unit or integration (playwright) tests.
- Submit a pull request ([how to create a pull request](https://help.github.com/articles/fork-a-repo)).
> ![TIP]
> Don't put more than one feature or fix in a single pull request. The smaller pull requests are the easier they are to review and merge.
By contributing code to xterm.js you:
- Agree to license the contributed code under xterm.js' [MIT license](LICENSE).
- Confirm that you have the right to contribute and license the code in question. This means that either you hold all rights on the code, or the rights holder has explicitly granted the right to use it like this, through a compatible open source license or through a direct agreement with you.
## Opening issues
The preferred way to report bugs or request features is to use
[GitHub issues](http://github.com/sourcelair/xterm.js/issues). Before
opening an issue, read these pointers.
[GitHub issues](http://github.com/xtermjs/xterm.js/issues).
### Opening issues effectively
### Creating great issues
- Include information about **the browser in which the problem occurred**. Even
if you tested several browsers, and the problem occurred in all of them,
mention this fact in the bug report. Also include browser version numbers and
the operating system that you're on.
- Include information about **the browser in which the problem occurred** or the terminal being used. If you tested several browsers and the problem occurred in all of them, mention this fact in the bug report. Also include browser version numbers and the operating system that you're on.
- Include the version of xterm.js being used, preferably either with the latest `beta` tagged release on npm or reproducing in the demo on the `master` branch.
- Mention precisely what went wrong. What did you expect to happen? What happened instead? Describe the exact steps a maintainer has to take to make the problem occur.
- If the problem can not be reproduced in the [demo of xterm.js](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo), provide an HTML document that demonstrates the problem.
- Be polite and follow [the code of conduct](https://github.com/xtermjs/xterm.js?tab=coc-ov-file#readme).
- Mention which release of xterm.js you're using. Preferably, try also with
the current HEAD of the master branch, to ensure the problem has not already been
fixed.
### Issue triaging philosophy
- Mention precisely what went wrong. What did you expect to happen? What happened instead? Describe the
exact steps a maintainer has to take to make the problem occur.
It's pretty common for maintainers of large open source projects to suffer from burnout, especially when needing to triage a large number of incoming issues instead of actually building things. Here are some of the steps we take to try mitigate this:
- If the problem can not be reproduced in the [demo of xterm.js](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo), please provide an HTML document that demonstrates the problem.
- Be polite. Issues with an indignant or belligerent tone tend to be moved to the
bottom of the pile.
- Support questions live in [GH discussions](https://github.com/xtermjs/xterm.js/discussions), issues may be transfered there without further comment and core maintainers may or may not participate in discussions.
- Issues are strictly for well defined features or bugs that are _actionable_.
- Sometimes features are out of scope. A common example of this is a niche feature that the pricipal implementation ([VS Code](https://code.visualstudio.com/)) won't leverage and therefore would be difficult to maintain and likely suffer from bitrot. The reporter may not agree with this, but you could always create an addon if that works or maintain your own fork if it comes to that.
- If a feature does not have a clear way forward or needs more discussion it may be closed ro moved to a discussion.
- If a bug is not easily reproducible it may be closed or moved to a discussion. Generally issues that are labeled are something we want to do or has actionable steps to look into further.
## Answering discussion questions
Issues are only meant to track (likely) feature requests and bugs. We use [GitHub Discussions](https://github.com/xtermjs/xterm.js/discussions) for general Q&A as well as discussing possible features. If you want to help out, many questions get asked over at the [discussions page](https://github.com/xtermjs/xterm.js/discussions) which could use an expert as the core team is often stretched thin.
## Contributing code
You can find issues to work on by looking at the [help wanted](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) or [good first issue](https://github.com/xtermjs/xterm.js/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) issues. It's a good idea to comment on the issue saying that you're taking it, just in case someone else comes along and you duplicate work. Once you have your issue, here are the steps to contribute:
- Fork [xterm.js](https://github.com/sourcelair/xterm.js/)
([how to fork a repo](https://help.github.com/articles/fork-a-repo)).
- Get the [xterm.js demo](https://github.com/xtermjs/xterm.js/wiki/Contributing#running-the-demo) running.
- Make your changes.
- If your changes are easy to test or likely to regress, add tests. Tests go into `test`, directory.
- Follow the general code style of the rest of the project (see below).
- Submit a pull request
([how to create a pull request](https://help.github.com/articles/fork-a-repo)).
Don't put more than one feature/fix in a single pull request.
By contributing code to xterm.js you:
- Agree to license the contributed code under xterm.js' [MIT
license](LICENSE).
- Confirm that you have the right to contribute and license the code
in question. (Either you hold all rights on the code, or the rights
holder has explicitly granted the right to use it like this,
through a compatible open source license or through a direct
agreement with you.)
### Test coverage
One area that always needs attention is improving out unit test coverage, you can view the code coverage report on [Azure Pipelines](https://dev.azure.com/xtermjs/xterm.js/_build/latest?definitionId=3) by clicking the Code Coverage tab.
## Testing
### Unit tests
Unit tests are run with `yarn test-unit`:
```sh
# All unit tests
yarn test-unit
# Absolute file path
yarn test-unit out-esbuild/browser/Terminal.test.js
# Filter by wildcard
yarn test-unit out-esbuild/**/Terminal.test.js
# Specific addon unit tests tests
yarn test-unit addons/addon-image/out-esbuild/*.test.js
# Multiple files
yarn test-unit out-esbuild/**/Terminal.test.js out-esbuild/**/InputHandler.test.js
```
These use mocha to run all `.test.js` files within the esbuild output (`out-esbuild/`).
### Integration tests
Integration tests are run with `yarn test-integration`:
```sh
# All integration tests
yarn test-integration
# Core integration tests
yarn test-integration --suite=core
# Specific addon integration tests
yarn test-integration --suite=addon-search
```
These use `@playwright/test` to run all tests within the esbuild test output (`out-esbuild-test/`).
Issues are only meant to track (likely) feature requests and bugs. We use [GitHub Discussions](https://github.com/xtermjs/xterm.js/discussions) for general Q&A as well as discussing possible features. If you want to help out, many questions get asked over at the [discussions page](https://github.com/xtermjs/xterm.js/discussions) which could use an expert as the core team is often stretched thin.
+28 -28
View File
@@ -1,27 +1,27 @@
# [![xterm.js logo](images/logo-full.png)](https://xtermjs.org)
# [![xterm.js](images/logo-full.png)](https://xtermjs.org)
Xterm.js is a front-end component written in TypeScript that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code, Hyper and Theia.
Xterm.js is a frontend component that enables applications to bring fully-featured terminals to their users in the browser. It's used by popular projects such as [VS Code](https://code.visualstudio.com/) (and its forks), [Tabby](https://tabby.sh/) and [Hyper](https://hyper.is/).
## Features
- **Terminal apps just work**: Xterm.js works with most terminal apps such as `bash`, `vim`, and `tmux`, including support for curses-based apps and mouse events.
- **Performant**: Xterm.js is *really* fast, it even includes a GPU-accelerated renderer.
- **Performant**: Xterm.js is *really* fast and includes an optional GPU-accelerated renderer.
- **Rich Unicode support**: Supports CJK, emojis, and IMEs.
- **Self-contained**: Requires zero dependencies to work.
- **Accessible**: Screen reader and minimum contrast ratio support can be turned on.
- **And much more**: Links, theming, addons, well documented API, etc.
- **Self-contained**: The core library has zero dependencies.
- **Accessible**: Screen reader mode and minimum contrast ratio support can be turned on.
- **And much more**: Links, theming, custom glyphs, addons, well documented API, etc.
## What xterm.js is not
- Xterm.js is not a terminal application that you can download and use on your computer.
- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output).
- Xterm.js is not `bash`. Xterm.js can be connected to processes like `bash` and let you interact with them (provide input, receive output) through a library like [node-pty](https://github.com/microsoft/node-pty).
## Getting Started
First, you need to install the module, we ship exclusively through [npm](https://www.npmjs.com/), so you need that installed and then add xterm.js as a dependency by running:
First, you need to install the module. We ship exclusively through [npm](https://www.npmjs.com), so you need that installed and then add [@xterm/xterm](https://www.npmjs.com/package/@xterm/xterm) as a dependency by running:
```bash
npm install @xterm/xterm
npm install --save @xterm/xterm
```
To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your HTML page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself. Finally, instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
@@ -54,12 +54,10 @@ import { Terminal } from '@xterm/xterm';
### Addons
⚠️ *This section describes the new addon format introduced in v3.14.0, see [here](https://github.com/xtermjs/xterm.js/blob/3.14.2/README.md#addons) for the instructions on the old format*
Addons are separate modules that extend the `Terminal` by building on the [xterm.js API](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts). To use an addon, you first need to install it in your project:
```bash
npm i -S @xterm/addon-web-links
npm install --save @xterm/addon-web-links
```
Then import the addon, instantiate it and call `Terminal.loadAddon`:
@@ -80,50 +78,51 @@ The xterm.js team maintains the following addons, but anyone can build them:
- [`@xterm/addon-clipboard`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-clipboard): Access the browser's clipboard
- [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit): Fits the terminal to the containing element
- [`@xterm/addon-image`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-image): Adds image support
- [`@xterm/addon-ligatures`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-ligatures): Enables rendering of ligatures
- [`@xterm/addon-progress`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-progress): Adds support for the progress API (`OSC 9;4`)
- [`@xterm/addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-search): Adds search functionality
- [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize): Serializes the terminal's buffer to a VT sequences or HTML
- [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize): Serializes the terminal's buffer to VT sequences or HTML
- [`@xterm/addon-unicode-graphemes`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode-graphemes): Enhanced unicode support including grapheme clustering (experimental)
- [`@xterm/addon-unicode11`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode11): Updates character widths to their unicode11 values
- [`@xterm/addon-web-fonts`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-fonts): Easily integrate web fonts
- [`@xterm/addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-links): Adds web link detection and interaction
- [`@xterm/addon-webgl`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-webgl): Renders xterm.js using a `canvas` element's webgl2 context
## Browser Support
Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*.
Xterm.js works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
Since xterm.js is typically implemented as a developer tool, generally only modern evergreen browsers are supported officially. Specifically the latest versions of *Chrome*, *Edge*, *Firefox*, and *Safari*. Xterm.js also works seamlessly in [Electron](https://electronjs.org/) apps and may even work on earlier versions of the browsers. These are the versions we strive to keep working.
### Node.js Support
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the serialize addon so it can get all state restored upon reconnection.
We also publish [`xterm-headless`](https://www.npmjs.com/package/xterm-headless) which is a stripped down version of xterm.js that runs headless in Node.js. An example use case for this is to keep track of a terminal's state where the process is running and using the [serialize addon](https://www.npmjs.com/package/@xterm/addon-serialize) so it can get all state restored upon reconnection.
## API
The full API for xterm.js is contained within the [TypeScript declaration file](https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts), use the branch/tag picker in GitHub (`w`) to navigate to the correct version of the API.
Note that some APIs are marked *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
Some APIs may be marked with *experimental*, these are added to enable experimentation with new ideas without committing to support it like a normal [semver](https://semver.org/) API. Note that these APIs can change radically between versions, so be sure to read release notes if you plan on using experimental APIs.
## Releases
Xterm.js follows a monthly release cycle roughly.
All current and past releases are available on this repo's [Releases page](https://github.com/sourcelair/xterm.js/releases), you can view the [high-level roadmap on the wiki](https://github.com/xtermjs/xterm.js/wiki/Roadmap) and see what we're working on now by looking through [Milestones](https://github.com/sourcelair/xterm.js/milestones).
Stable releases are done on an as needed basis. All current and past releases are available on this repo's [releases page](https://github.com/sourcelair/xterm.js/releases), you can see what's planned for upcoming releases looking through the repository [milestones](https://github.com/sourcelair/xterm.js/milestones).
### Beta builds
Our CI releases beta builds to npm for every change that goes into master. Install the latest beta build with:
Beta releases are continuously published off the `master` branch. Install the latest beta build with:
```bash
npm install -S @xterm/xterm@beta
npm install --save @xterm/xterm@beta
```
These should generally be stable, but some bugs may slip in. We recommend using the beta build primarily to test out new features and to verify bug fixes.
The principal implementation (VS Code) typically uses the latest or near the latest beta build. Generally they are quite stable but can potentially contain bugs or breaking changes. If stability is very important we recommend using the beta build primarily to test out new features and to verify bug fixes, unless you're tracking what's landing and are comfortable taking that risk.
## Contributing
You can read the [guide on the wiki](https://github.com/xtermjs/xterm.js/wiki/Contributing) to learn how to contribute and set up xterm.js for development.
Read [CONTRIBUTING.md](https://github.com/xtermjs/xterm.js/blob/master/CONTRIBUTING.md) to learn how to contribute to the project.
## Real-world uses
Xterm.js is used in several world-class applications to provide great terminal experiences.
Xterm.js is used in many world-class applications to provide great terminal experiences.
- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js.
- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile, and powerful open source code editor that provides an integrated terminal based on xterm.js.
@@ -229,14 +228,15 @@ Xterm.js is used in several world-class applications to provide great terminal e
- [**pyTermTk**](https://github.com/ceccopierangiolieugenio/pyTermTk): Python Terminal Toolkit - a Spiced Up Cross Compatible TUI Library 🌶️, use xterm.js for the [HTML5 exporter](https://ceccopierangiolieugenio.github.io/pyTermTk/sandbox/sandbox.html).
- [**ecmaOS**](https://ecmaos.sh): A kernel and suite of applications tying modern web technologies into a browser-based operating system.
- [**LabEx**](https://labex.io): Interactive learning platform with hands-on labs and xterm.js-based online terminals, focused on learn-by-doing approach.
- [**EmuDevz**](https://afska.github.io/emudevz): A free coding game where players learn how to build an emulator from scratch.
- [And much more...](https://github.com/xtermjs/xterm.js/network/dependents?package_id=UGFja2FnZS0xNjYzMjc4OQ%3D%3D)
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Note: Please add any new contributions to the end of the list only.
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it on our list. Please add any new contributions to the end of the list.
## License Agreement
If you contribute code to this project, you implicitly allow your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work.
Copyright (c) 2017-2022, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
Copyright (c) 2017-2026, [The xterm.js authors](https://github.com/xtermjs/xterm.js/graphs/contributors) (MIT License)<br>
Copyright (c) 2014-2017, SourceLair, Private Company ([www.sourcelair.com](https://www.sourcelair.com/home)) (MIT License)<br>
Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-attach",
"version": "0.11.0",
"version": "0.12.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -21,8 +21,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-clipboard",
"version": "0.1.0",
"version": "0.2.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -22,9 +22,6 @@
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.4.0"
},
"dependencies": {
"js-base64": "^3.7.5"
}
-8
View File
@@ -1,8 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
js-base64@^3.7.5:
version "3.7.7"
resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-3.7.7.tgz#e51b84bf78fbf5702b9541e2cb7bfcb893b43e79"
integrity sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-fit",
"version": "0.10.0",
"version": "0.11.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -21,8 +21,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+16 -12
View File
@@ -3,9 +3,8 @@
* @license MIT
*/
import type { Terminal, ITerminalAddon } from '@xterm/xterm';
import type { Terminal, ITerminalAddon, IRenderDimensions } from '@xterm/xterm';
import type { FitAddon as IFitApi } from '@xterm/addon-fit';
import { IRenderDimensions } from 'browser/renderer/shared/Types';
import { ViewportConstants } from 'browser/shared/Constants';
interface ITerminalDimensions {
@@ -23,6 +22,17 @@ interface ITerminalDimensions {
const MINIMUM_COLS = 2;
const MINIMUM_ROWS = 1;
function getWindow(e: Node): Window {
if (e?.ownerDocument?.defaultView) {
return e.ownerDocument.defaultView;
}
return window;
}
function _getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return getWindow(el).getComputedStyle(el, null);
}
export class FitAddon implements ITerminalAddon , IFitApi {
private _terminal: Terminal | undefined;
@@ -38,12 +48,8 @@ export class FitAddon implements ITerminalAddon , IFitApi {
return;
}
// TODO: Remove reliance on private API
const core = (this._terminal as any)._core;
// Force a full render
if (this._terminal.rows !== dims.rows || this._terminal.cols !== dims.cols) {
core._renderService.clear();
this._terminal.resize(dims.cols, dims.rows);
}
}
@@ -57,11 +63,9 @@ export class FitAddon implements ITerminalAddon , IFitApi {
return undefined;
}
// TODO: Remove reliance on private API
const core = (this._terminal as any)._core;
const dims: IRenderDimensions = core._renderService.dimensions;
const dims: IRenderDimensions | undefined = this._terminal.dimensions;
if (dims.css.cell.width === 0 || dims.css.cell.height === 0) {
if (!dims || dims.css.cell.width === 0 || dims.css.cell.height === 0) {
return undefined;
}
@@ -69,10 +73,10 @@ export class FitAddon implements ITerminalAddon , IFitApi {
? 0
: (this._terminal.options.overviewRuler?.width || ViewportConstants.DEFAULT_SCROLL_BAR_WIDTH));
const parentElementStyle = window.getComputedStyle(this._terminal.element.parentElement);
const parentElementStyle = _getComputedStyle(this._terminal.element.parentElement);
const parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
const parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));
const elementStyle = window.getComputedStyle(this._terminal.element);
const elementStyle = _getComputedStyle(this._terminal.element);
const elementPadding = {
top: parseInt(elementStyle.getPropertyValue('padding-top')),
bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),
-1
View File
@@ -17,7 +17,6 @@ npm-debug.log
.env
build/
.DS_Store
package-lock.json
yarn.lock
# Keep bundled code out of Git
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-image",
"version": "0.8.0",
"version": "0.9.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -23,9 +23,6 @@
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.2.0"
},
"devDependencies": {
"sixel": "^0.16.0",
"xterm-wasm-parts": "^0.1.0"
+1 -1
View File
@@ -105,7 +105,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
return true;
}
const blob = new Blob([this._dec.data8], { type: this._metrics.mime });
const blob = new Blob([new Uint8Array(this._dec.data8)], { type: this._metrics.mime });
this._dec.release();
if (!window.createImageBitmap) {
+1 -1
View File
@@ -176,7 +176,7 @@ export class HeaderParser {
try {
const v = this._buffer.slice(0, pos);
this.fields[this._key] = DECODERS[this._key] ? DECODERS[this._key](v) : v;
} catch (e) {
} catch {
return false;
}
return true;
+1 -1
View File
@@ -124,7 +124,7 @@ export class ImageRenderer extends Disposable implements IDisposable {
* Forwarded from internal render service.
*/
public get dimensions(): IRenderDimensions | undefined {
return this._renderService?.dimensions;
return this._terminal.dimensions;
}
/**
+1 -1
View File
@@ -99,7 +99,7 @@ export class SixelHandler implements IDcsHandler, IResetHandler {
}
const canvas = ImageRenderer.createCanvas(undefined, width, height);
canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8, width, height), 0, 0);
canvas.getContext('2d')?.putImageData(new ImageData(this._dec.data8 as Uint8ClampedArray<ArrayBuffer>, width, height), 0, 0);
if (this._dec.memoryUsage > MEM_PERMA_LIMIT) {
this._dec.release();
}
+1 -1
View File
@@ -300,7 +300,7 @@ test.describe('ImageAddon', () => {
* terminal access helpers.
*/
async function getDimensions(): Promise<IDimensions> {
const dimensions: any = await ctx.page.evaluate(`term._core._renderService.dimensions`);
const dimensions: any = await ctx.page.evaluate(`term.dimensions`);
return {
cellWidth: Math.round(dimensions.css.cell.width),
cellHeight: Math.round(dimensions.css.cell.height),
-2
View File
@@ -3,11 +3,9 @@ node_modules/
coverage/
lib/
fonts/
.env
.vscode/
*.swp
*.tgz
npm-debug.log*
yarn-error.log*
+27 -3
View File
@@ -1,6 +1,30 @@
MIT License
Copyright (c) 2018
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
The code that analyzes font ligatures is forked from https://github.com/princjef/font-ligatures with this license:
MIT License
Copyright (c) 2018 Jeffrey Principe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -1,78 +0,0 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const axios = require('axios').default;
const mkdirp = require('mkdirp');
const yauzl = require('yauzl');
const urls = {
fira: 'https://github.com/tonsky/FiraCode/raw/d42e7276fa925e5f82748f3ec9ea429736611b48/distr/otf/FiraCode-Regular.otf',
iosevka: 'https://github.com/be5invis/Iosevka/releases/download/v1.14.3/01-iosevka-1.14.3.zip'
};
const writeFile = util.promisify(fs.writeFile);
const fontsFolder = path.join(__dirname, '../fonts');
async function download() {
await mkdirp(fontsFolder);
try {
await downloadFiraCode();
await downloadIosevka();
console.log('Loaded all fonts for testing')
} catch (e) {
console.warn('Fonts failed to download, ligature tests will not work', e);
}
}
async function downloadFiraCode() {
const file = path.join(fontsFolder, 'firaCode.otf');
if (await util.promisify(fs.exists)(file)) {
console.log('Fira Code already loaded');
} else {
console.log('Downloading Fira Code...');
await writeFile(
file,
(await axios.get(urls.fira, { responseType: 'arraybuffer' })).data
);
}
}
async function downloadIosevka() {
const file = path.join(fontsFolder, 'iosevka.ttf');
if (await util.promisify(fs.exists)(file)) {
console.log('Iosevka already loaded');
} else {
console.log('Downloading Iosevka...');
const iosevkaContents = (await axios.get(urls.iosevka, { responseType: 'arraybuffer' })).data;
const iosevkaZipfile = await util.promisify(yauzl.fromBuffer)(iosevkaContents);
await new Promise((resolve, reject) => {
iosevkaZipfile.on('entry', entry => {
if (entry.fileName === 'ttf/iosevka-regular.ttf') {
iosevkaZipfile.openReadStream(entry, (err, stream) => {
if (err) {
return reject(err);
}
const writeStream = fs.createWriteStream(file);
stream.pipe(writeStream);
writeStream.on('close', () => resolve());
});
}
});
});
}
}
download();
process.on('unhandledRejection', e => {
console.error(e);
process.exit(1);
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-ligatures",
"version": "0.9.0",
"version": "0.10.0",
"description": "Add support for programming ligatures to xterm.js",
"author": {
"name": "The xterm.js authors",
@@ -14,7 +14,6 @@
"node": ">8.0.0"
},
"scripts": {
"prepare": "node bin/download-fonts.js",
"build": "tsc -p src",
"watch": "tsc -w -p src",
"prepackage": "npm run build",
@@ -32,17 +31,15 @@
],
"license": "MIT",
"dependencies": {
"font-finder": "^1.1.0",
"font-ligatures": "^1.4.1"
"lru-cache": "^6.0.0",
"opentype.js": "^0.8.0"
},
"devDependencies": {
"@types/sinon": "^5.0.1",
"@types/lru-cache": "^5.1.0",
"@types/opentype.js": "^0.7.0",
"axios": "^1.6.0",
"font-finder": "^1.1.0",
"mkdirp": "0.5.5",
"sinon": "6.3.5",
"yauzl": "^2.10.0"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { Font, loadBuffer } from 'font-ligatures';
import { Font, loadBuffer } from './fontLigatures/index';
import parse from './parse';
@@ -0,0 +1,40 @@
import { ILookupTree, IFlattenedLookupTree, ILookupTreeEntry, IFlattenedLookupTreeEntry } from './types';
export default function flatten(tree: ILookupTree, visited: Map<ILookupTreeEntry, IFlattenedLookupTreeEntry> = new Map()): IFlattenedLookupTree {
const result: IFlattenedLookupTree = {};
for (const [glyphId, entry] of Object.entries(tree.individual)) {
result[glyphId] = flattenEntry(entry, visited);
}
for (const { range, entry } of tree.range) {
const flattened = flattenEntry(entry, visited);
for (let glyphId = range[0]; glyphId < range[1]; glyphId++) {
result[glyphId] = flattened;
}
}
return result;
}
function flattenEntry(entry: ILookupTreeEntry, visited: Map<ILookupTreeEntry, IFlattenedLookupTreeEntry>): IFlattenedLookupTreeEntry {
if (visited.has(entry)) {
return visited.get(entry)!;
}
const result: IFlattenedLookupTreeEntry = {};
visited.set(entry, result);
if (entry.forward) {
result.forward = flatten(entry.forward, visited);
}
if (entry.reverse) {
result.reverse = flatten(entry.reverse, visited);
}
if (entry.lookup) {
result.lookup = entry.lookup;
}
return result;
}
@@ -0,0 +1,358 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import * as path from 'path';
import * as fs from 'fs';
import { assert } from 'chai';
import { loadBuffer } from './index';
interface IFont {
findLigatures(text: string): { outputGlyphs: number[], contextRanges: [number, number][] };
findLigatureRanges(text: string): [number, number][];
}
interface ITestCase {
font: string;
input: string;
glyphs: number[];
ranges: [number, number][];
}
const fira = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Fira Code', input, glyphs, ranges });
const iosevka = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Iosevka', input, glyphs, ranges });
const monoid = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Monoid', input, glyphs, ranges });
const ubuntu = (input: string, glyphs: number[], ranges: [number, number][]): ITestCase =>
({ font: 'Ubuntu Mono', input, glyphs, ranges });
const firaCases: ITestCase[] = [
fira('abc', [133, 145, 146], []),
fira('.=', [1614, 1081], [[0, 2]]),
fira('..=', [1614, 1614, 1083], [[0, 3]]),
fira('.-', [1614, 1080], [[0, 2]]),
fira(':=', [1614, 1055], [[0, 2]]),
fira('=:=', [1614, 1614, 1483], [[0, 3]]),
fira('=!=', [1614, 1614, 1484], [[0, 3]]),
fira('__', [1614, 1099], [[0, 2]]),
fira('==', [1614, 1485], [[0, 2]]),
fira('!=', [1614, 1058], [[0, 2]]),
fira('===', [1614, 1614, 1486], [[0, 3]]),
fira('!==', [1614, 1614, 1059], [[0, 3]]),
fira('=/=', [1614, 1614, 1491], [[0, 3]]),
fira('<-<', [1614, 1614, 1513], [[0, 3]]),
fira('<<-', [1614, 1614, 1522], [[0, 3]]),
fira('<--', [1614, 1614, 1511], [[0, 3]]),
fira('<-', [1614, 1510], [[0, 2]]),
fira('<->', [1614, 1614, 1512], [[0, 3]]),
fira('->', [1614, 1064], [[0, 2]]),
fira('-->', [1614, 1614, 1063], [[0, 3]]),
fira('->>', [1614, 1614, 1065], [[0, 3]]),
fira('>->', [1614, 1614, 1493], [[0, 3]]),
fira('<=<', [1614, 1614, 1519], [[0, 3]]),
fira('<<=', [1614, 1614, 1523], [[0, 3]]),
fira('<==', [1614, 1614, 1517], [[0, 3]]),
fira('<=>', [1614, 1614, 1518], [[0, 3]]),
fira('=>', [1614, 1488], [[0, 2]]),
fira('==>', [1614, 1614, 1487], [[0, 3]]),
fira('=>>', [1614, 1614, 1489], [[0, 3]]),
fira('>=>', [1614, 1614, 1495], [[0, 3]]),
fira('>>=', [1614, 1614, 1498], [[0, 3]]),
fira('>>-', [1614, 1614, 1497], [[0, 3]]),
fira('>-', [1614, 1492], [[0, 2]]),
fira('<~>', [1614, 1614, 1526], [[0, 3]]),
fira('-<', [1614, 1066], [[0, 2]]),
fira('-<<', [1614, 1614, 1067], [[0, 3]]),
fira('=<<', [1614, 1614, 1490], [[0, 3]]),
fira('<~~', [1614, 1614, 1527], [[0, 3]]),
fira('<~', [1614, 1525], [[0, 2]]),
fira('~~', [1614, 1534], [[0, 2]]),
fira('~>', [1614, 1533], [[0, 2]]),
fira('~~>', [1614, 1614, 1535], [[0, 3]]),
fira('<<<', [1614, 1614, 1524], [[0, 3]]),
fira('<<', [1614, 1521], [[0, 2]]),
fira('<=', [1614, 1516], [[0, 2]]),
fira('<>', [1614, 1520], [[0, 2]]),
fira('>=', [1614, 1494], [[0, 2]]),
fira('>>', [1614, 1496], [[0, 2]]),
fira('>>>', [1614, 1614, 1499], [[0, 3]]),
fira('{.', [1001, 977], [[0, 2]]),
fira('{|', [1614, 1049], [[0, 2]]),
fira('[|', [1614, 1050], [[0, 2]]),
fira('<:', [1614, 1506], [[0, 2]]),
fira(':>', [1614, 1056], [[0, 2]]),
fira('|]', [1614, 1474], [[0, 2]]),
fira('|}', [1614, 1473], [[0, 2]]),
fira('.}', [977, 1002], [[0, 2]]),
fira('<|||', [1614, 1614, 1614, 1504], [[0, 4]]),
fira('<||', [1614, 1614, 1503], [[0, 3]]),
fira('<|', [1614, 1502], [[0, 2]]),
fira('<|>', [1614, 1614, 1505], [[0, 3]]),
fira('|>', [1614, 1477], [[0, 2]]),
fira('||>', [1614, 1614, 1472], [[0, 3]]),
fira('|||>', [1614, 1614, 1614, 1470], [[0, 4]]),
fira('<$', [1614, 1507], [[0, 2]]),
fira('<$>', [1614, 1614, 1508], [[0, 3]]),
fira('$>', [1614, 1479], [[0, 2]]),
fira('<+', [1614, 1514], [[0, 2]]),
fira('<+>', [1614, 1614, 1515], [[0, 3]]),
fira('+>', [1614, 1482], [[0, 2]]),
fira('<*', [1614, 1500], [[0, 2]]),
fira('<*>', [1614, 1614, 1501], [[0, 3]]),
fira('*>', [1614, 1047], [[0, 2]]),
fira('/*', [1614, 1092], [[0, 2]]),
fira('*/', [1614, 1048], [[0, 2]]),
fira('///', [1614, 1614, 1097], [[0, 3]]),
fira('//', [1614, 1096], [[0, 2]]),
fira('</', [1614, 1528], [[0, 2]]),
fira('<!--', [1614, 1614, 1614, 1509], [[0, 4]]),
fira('</>', [1614, 1614, 1529], [[0, 3]]),
fira('/>', [1614, 1095], [[0, 2]]),
fira('0xff', [895, 270, 166, 166], [[0, 3]]),
fira('10x10', [896, 895, 270, 896, 895], [[1, 4]]),
fira('9:45', [904, 998, 899, 900], [[0, 2]]),
fira('[:]', [1003, 998, 1004], [[0, 2]]),
fira(';;', [1614, 1091], [[0, 2]]),
fira('::', [1614, 1052], [[0, 2]]),
fira(':::', [1614, 1614, 1053], [[0, 3]]),
fira('..', [1614, 1082], [[0, 2]]),
fira('...', [1614, 1614, 1085], [[0, 3]]),
fira('..<', [1614, 1614, 1084], [[0, 3]]),
fira('!!', [1614, 1057], [[0, 2]]),
fira('??', [1614, 1090], [[0, 2]]),
fira('%%', [1614, 1536], [[0, 2]]),
fira('&&', [1614, 1468], [[0, 2]]),
fira('||', [1614, 1469], [[0, 2]]),
fira('?.', [1614, 1089], [[0, 2]]),
fira('?:', [1614, 1087], [[0, 2]]),
fira('++', [1614, 1480], [[0, 2]]),
fira('+++', [1614, 1614, 1481], [[0, 3]]),
fira('--', [1614, 1061], [[0, 2]]),
fira('---', [1614, 1614, 1062], [[0, 3]]),
fira('**', [1614, 1045], [[0, 2]]),
fira('***', [1614, 1614, 1046], [[0, 3]]),
fira('~=', [1614, 1532], [[0, 2]]),
fira('~-', [1614, 1531], [[0, 2]]),
fira('www', [1614, 1614, 271], [[0, 3]]),
fira('-~', [1614, 1068], [[0, 2]]),
fira('~@', [1614, 1530], [[0, 2]]),
fira('^=', [1614, 1478], [[0, 2]]),
fira('?=', [1614, 1088], [[0, 2]]),
fira('/=', [1614, 1093], [[0, 2]]),
fira('/==', [1614, 1614, 1094], [[0, 3]]),
fira('-|', [1614, 1060], [[0, 2]]),
fira('_|_', [1614, 1614, 1098], [[0, 3]]),
fira('|-', [1614, 1475], [[0, 2]]),
fira('|=', [1614, 1476], [[0, 2]]),
fira('||=', [1614, 1614, 1471], [[0, 3]]),
fira('#!', [1614, 1071], [[0, 2]]),
fira('#=', [1614, 1075], [[0, 2]]),
fira('##', [1614, 1072], [[0, 2]]),
fira('###', [1614, 1614, 1073], [[0, 3]]),
fira('####', [1614, 1614, 1614, 1074], [[0, 4]]),
fira('#{', [1614, 1069], [[0, 2]]),
fira('#[', [1614, 1070], [[0, 2]]),
fira(']#', [1614, 1051], [[0, 2]]),
fira('#(', [1614, 1076], [[0, 2]]),
fira('#?', [1614, 1077], [[0, 2]]),
fira('#_', [1614, 1078], [[0, 2]]),
fira('#_(', [1614, 1614, 1079], [[0, 3]]),
fira('::=', [1614, 1614, 1054], [[0, 3]]),
fira('.?', [1614, 1086], [[0, 2]]),
fira('===>', [1614, 1614, 1486, 1148], [[0, 4]])
];
const iosevkaCases: ITestCase[] = [
iosevka('<-', [31, 3127], [[0, 2]]),
iosevka('<--', [31, 3129, 3139], [[0, 3]]),
iosevka('<---', [31, 3129, 3150, 3139], [[0, 4]]),
iosevka('<-----', [31, 3129, 3150, 3139, 3151, 3151], [[0, 6]]),
iosevka('->', [3126, 33], [[0, 2]]),
iosevka('-->', [3140, 3128, 33], [[0, 3]]),
iosevka('--->', [3140, 3150, 3128, 33], [[0, 4]]),
iosevka('----->', [3153, 3153, 3140, 3150, 3128, 33], [[0, 6]]),
iosevka('<->', [31, 3149, 33], [[0, 3]]),
iosevka('<-->', [31, 3129, 3128, 33], [[0, 4]]),
iosevka('<--->', [31, 3129, 3150, 3128, 33], [[0, 5]]),
iosevka('<----->', [31, 3129, 3150, 3150, 3150, 3128, 33], [[0, 7]]),
iosevka('<=', [3094, 3095], [[0, 2]]),
iosevka('<==', [31, 3158, 3168], [[0, 3]]),
iosevka('<===', [31, 3158, 3179, 3168], [[0, 4]]),
iosevka('<=====', [31, 3158, 3179, 3168, 3180, 3180], [[0, 6]]),
iosevka('=>', [3155, 33], [[0, 2]]),
iosevka('==>', [3169, 3157, 33], [[0, 3]]),
iosevka('===>', [3169, 3179, 3157, 33], [[0, 4]]),
iosevka('=====>', [3182, 3182, 3169, 3179, 3157, 33], [[0, 6]]),
iosevka('<=>', [31, 3178, 33], [[0, 3]]),
iosevka('<==>', [31, 3158, 3157, 33], [[0, 4]]),
iosevka('<===>', [31, 3158, 3179, 3157, 33], [[0, 5]]),
iosevka('<=====>', [31, 3158, 3179, 3179, 3179, 3157, 33], [[0, 7]]),
iosevka('<!--', [31, 3184, 3130, 3139], [[0, 4]]),
iosevka('<!---', [31, 3184, 3130, 3150, 3139], [[0, 5]]),
iosevka('<!-----', [31, 3184, 3130, 3150, 3139, 3151, 3151], [[0, 7]]),
iosevka('a:b', [68, 29, 69], []),
iosevka('a::b', [68, 3012, 3013, 69], [[1, 3]]),
iosevka('a:::b', [68, 3012, 3010, 3013, 69], [[1, 4]]),
iosevka(':=', [3011, 32], [[0, 2]]),
iosevka(':-', [3011, 16], [[0, 2]]),
iosevka(':+', [3011, 14], [[0, 2]]),
iosevka('=:', [32, 3011], [[0, 2]]),
iosevka('-:', [16, 3011], [[0, 2]]),
iosevka('+:', [14, 3011], [[0, 2]]),
iosevka('<*', [31, 3023], [[0, 2]]),
iosevka('*>', [3023, 33], [[0, 2]]),
iosevka('<*>', [31, 3023, 33], [[1, 3]]),
iosevka('<**>', [31, 3023, 3023, 33], [[1, 4]]),
iosevka('<****>', [31, 3023, 3023, 3023, 3023, 33], [[0, 3], [3, 6]]),
iosevka('==', [3083, 3084], [[0, 2]]),
iosevka('!=', [3098, 3084], [[0, 2]]),
iosevka('===', [3083, 3085, 3084], [[0, 3]]),
iosevka('!==', [3099, 3085, 3084], [[0, 3]]),
iosevka('====', [3083, 3085, 3085, 3084], [[0, 4]]),
iosevka('!===', [3100, 3085, 3085, 3084], [[0, 4]])
];
const monoidCases: ITestCase[] = [
monoid('<!--', [775, 775, 775, 643], [[0, 4]]),
monoid('-->', [779, 779, 628], [[0, 3]]),
monoid('<--', [776, 776, 627], [[0, 3]]),
monoid('->>', [780, 780, 626], [[0, 3]]),
monoid('<<-', [777, 777, 625], [[0, 3]]),
monoid('->', [781, 623], [[0, 2]]),
monoid('<-', [778, 624], [[0, 2]]),
monoid('=>', [793, 666], [[0, 2]]),
monoid('<=>', [785, 785, 760], [[0, 3]]),
monoid('<==>', [786, 786, 786, 771], [[0, 4]]),
monoid('==>', [787, 787, 672], [[0, 3]]),
monoid('<==', [788, 788, 671], [[0, 3]]),
monoid('>>=', [791, 791, 758], [[0, 3]]),
monoid('=<<', [792, 792, 759], [[0, 3]]),
monoid('--', [667, 667], [[0, 2]]),
monoid(':=', [29, 761], [[0, 2]]),
monoid('=:=', [789, 789, 665], [[0, 3]]),
monoid('==', [794, 641], [[0, 2]]),
monoid('!==', [782, 782, 646], [[0, 3]]),
monoid('!=', [783, 629], [[0, 2]]),
monoid('<=', [790, 630], [[0, 2]]),
monoid('>=', [792, 631], [[0, 2]]),
monoid('//', [621, 664], [[0, 2]]),
monoid('/**', [18, 753, 753], [[0, 3]]),
monoid('/*', [18, 753], [[0, 2]]),
monoid('*/', [754, 18], [[0, 2]]),
monoid('&&', [633, 775], [[0, 2]]),
monoid('.&', [17, 755], [[0, 2]]),
monoid('||', [634, 635], [[0, 2]]),
monoid('!!', [769, 770], [[0, 2]]),
monoid('::', [772, 773], [[0, 2]]),
monoid('>>', [637, 638], [[0, 2]]),
monoid('<<', [639, 640], [[0, 2]]),
monoid('¯\\_(ツ)_/¯', [113, 765, 66, 767, 613, 768, 66, 766, 113], [[0, 3], [3, 6], [6, 9]]),
monoid('__', [763, 764], [[0, 2]])
];
const ubuntuCases: ITestCase[] = [
ubuntu('==>', [32, 32, 33], [])
];
const fontPaths: Record<string, string> = {
'Fira Code': path.join(__dirname, '../../fonts/FiraCode-Regular.otf'),
'Iosevka': path.join(__dirname, '../../fonts/iosevka-regular.ttf'),
'Monoid': path.join(__dirname, '../../fonts/Monoid-Regular.ttf'),
'Ubuntu Mono': path.join(__dirname, '../../fonts/UbuntuMono-Regular.ttf')
};
const fontCache: Map<string, IFont> = new Map();
function loadFont(fontName: string): IFont {
let font = fontCache.get(fontName);
if (!font) {
const fontPath = fontPaths[fontName];
const buffer = fs.readFileSync(fontPath);
font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
fontCache.set(fontName, font);
}
return font;
}
describe('addon-ligatures - index', () => {
describe('findLigatures', () => {
for (const { font: fontName, input, glyphs, ranges } of [...firaCases, ...iosevkaCases, ...monoidCases, ...ubuntuCases]) {
it(`${fontName}: '${input}'`, () => {
const font = loadFont(fontName);
const result = font.findLigatures(input);
assert.deepEqual(result.outputGlyphs, glyphs);
assert.deepEqual(result.contextRanges, ranges);
});
}
});
describe('findLigatureRanges', () => {
for (const { font: fontName, input, ranges } of [...firaCases, ...iosevkaCases, ...monoidCases, ...ubuntuCases]) {
it(`${fontName}: '${input}'`, () => {
const font = loadFont(fontName);
const result = font.findLigatureRanges(input);
assert.deepEqual(result, ranges);
});
}
});
describe('caching', () => {
it('findLigatures caches successive calls correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatures('in --> out');
const result2 = font.findLigatures('in --> out');
assert.deepEqual(result1, result2);
});
it('findLigatureRanges caches successive calls correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatureRanges('in --> out');
const result2 = font.findLigatureRanges('in --> out');
assert.deepEqual(result1, result2);
});
it('caches calls to findLigatures after findLigatureRanges correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const uncached = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
const uncachedResult1 = uncached.findLigatureRanges('in --> out');
const uncachedResult2 = uncached.findLigatures('in --> out');
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatureRanges('in --> out');
const result2 = font.findLigatures('in --> out');
assert.deepEqual(result1, uncachedResult1);
assert.deepEqual(result2, uncachedResult2);
assert.deepEqual(result1, result2.contextRanges);
});
it('caches calls to findLigatureRanges after findLigatures correctly', () => {
const fontPath = fontPaths['Fira Code'];
const buffer = fs.readFileSync(fontPath);
const uncached = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
const uncachedResult1 = uncached.findLigatures('in --> out');
const uncachedResult2 = uncached.findLigatureRanges('in --> out');
const font = loadBuffer(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength), { cacheSize: 100 });
const result1 = font.findLigatures('in --> out');
const result2 = font.findLigatureRanges('in --> out');
assert.deepEqual(result1, uncachedResult1);
assert.deepEqual(result2, uncachedResult2);
assert.deepEqual(result1.contextRanges, result2);
});
});
});
@@ -0,0 +1,262 @@
import * as opentype from 'opentype.js';
import LRUCache = require('lru-cache');
import { IFont, ILigatureData, IFlattenedLookupTree, ILookupTree, IOptions } from './types';
import mergeTrees from './merge';
import walkTree from './walk';
import mergeRange from './mergeRange';
import buildTreeGsubType6Format1 from './processors/6-1';
import buildTreeGsubType6Format2 from './processors/6-2';
import buildTreeGsubType6Format3 from './processors/6-3';
import buildTreeGsubType8Format1 from './processors/8-1';
import flatten from './flatten';
class FontImpl implements IFont {
private _font: opentype.Font;
private _lookupTrees: { tree: IFlattenedLookupTree, processForward: boolean }[] = [];
private _glyphLookups: { [glyphId: string]: number[] } = {};
private _cache?: LRUCache<string, ILigatureData | [number, number][]>;
constructor(font: opentype.Font, options: Required<IOptions>) {
this._font = font;
if (options.cacheSize > 0) {
this._cache = new LRUCache({
max: options.cacheSize,
length: ((val: ILigatureData | [number, number][], key: string) => key.length) as any
});
}
const caltFeatures = this._font.tables.gsub && this._font.tables.gsub.features.filter((f: { tag: string }) => f.tag === 'calt') || [];
const lookupIndices: number[] = caltFeatures
.reduce((acc: number[], val: { feature: { lookupListIndexes: number[] } }) => [...acc, ...val.feature.lookupListIndexes], []);
const allLookups = this._font.tables.gsub && this._font.tables.gsub.lookups || [];
const lookupGroups = allLookups.filter((l: unknown, i: number) => lookupIndices.some(idx => idx === i));
for (const [index, lookup] of lookupGroups.entries()) {
const trees: ILookupTree[] = [];
switch (lookup.lookupType) {
case 6:
for (const [index, table] of lookup.subtables.entries()) {
switch (table.substFormat) {
case 1:
trees.push(buildTreeGsubType6Format1(table, allLookups, index));
break;
case 2:
trees.push(buildTreeGsubType6Format2(table, allLookups, index));
break;
case 3:
trees.push(buildTreeGsubType6Format3(table, allLookups, index));
break;
}
}
break;
case 8:
for (const [index, table] of lookup.subtables.entries()) {
trees.push(buildTreeGsubType8Format1(table, index));
}
break;
}
const tree = flatten(mergeTrees(trees));
this._lookupTrees.push({
tree,
processForward: lookup.lookupType !== 8
});
for (const glyphId of Object.keys(tree)) {
if (!this._glyphLookups[glyphId]) {
this._glyphLookups[glyphId] = [];
}
this._glyphLookups[glyphId].push(index);
}
}
}
public findLigatures(text: string): ILigatureData {
const cached = this._cache && this._cache.get(text);
if (cached && !Array.isArray(cached)) {
return cached;
}
const glyphIds: number[] = [];
for (const char of text) {
glyphIds.push(this._font.charToGlyphIndex(char));
}
// If there are no lookup groups, there's no point looking for
// replacements. This gives us a minor performance boost for fonts with
// no ligatures
if (this._lookupTrees.length === 0) {
return {
inputGlyphs: glyphIds,
outputGlyphs: glyphIds,
contextRanges: []
};
}
const result = this._findInternal(glyphIds.slice());
const finalResult: ILigatureData = {
inputGlyphs: glyphIds,
outputGlyphs: result.sequence,
contextRanges: result.ranges
};
if (this._cache) {
this._cache.set(text, finalResult);
}
return finalResult;
}
public findLigatureRanges(text: string): [number, number][] {
// Short circuit the process if there are no possible ligatures in the
// font
if (this._lookupTrees.length === 0) {
return [];
}
const cached = this._cache && this._cache.get(text);
if (cached) {
return Array.isArray(cached) ? cached : cached.contextRanges;
}
const glyphIds: number[] = [];
for (const char of text) {
glyphIds.push(this._font.charToGlyphIndex(char));
}
const result = this._findInternal(glyphIds);
if (this._cache) {
this._cache.set(text, result.ranges);
}
return result.ranges;
}
private _findInternal(sequence: number[]): { sequence: number[], ranges: [number, number][] } {
const ranges: [number, number][] = [];
let nextLookup = this._getNextLookup(sequence, 0);
while (nextLookup.index !== null) {
const lookup = this._lookupTrees[nextLookup.index];
if (lookup.processForward) {
let lastGlyphIndex = nextLookup.last;
for (let i = nextLookup.first; i < lastGlyphIndex; i++) {
const result = walkTree(lookup.tree, sequence, i, i);
if (result) {
for (let j = 0; j < result.substitutions.length; j++) {
const sub = result.substitutions[j];
if (sub !== null) {
sequence[i + j] = sub;
}
}
mergeRange(
ranges,
result.contextRange[0] + i,
result.contextRange[1] + i
);
// Substitutions can end up extending the search range
if (i + result.length >= lastGlyphIndex) {
lastGlyphIndex = i + result.length + 1;
}
i += result.length - 1;
}
}
} else {
// We don't need to do the lastGlyphIndex tracking here because
// reverse processing isn't allowed to replace more than one
// character at a time.
for (let i = nextLookup.last - 1; i >= nextLookup.first; i--) {
const result = walkTree(lookup.tree, sequence, i, i);
if (result) {
for (let j = 0; j < result.substitutions.length; j++) {
const sub = result.substitutions[j];
if (sub !== null) {
sequence[i + j] = sub;
}
}
mergeRange(
ranges,
result.contextRange[0] + i,
result.contextRange[1] + i
);
i -= result.length - 1;
}
}
}
nextLookup = this._getNextLookup(sequence, nextLookup.index + 1);
}
return { sequence, ranges };
}
/**
* Returns the lookup and glyph range for the first lookup that might
* contain a match.
*
* @param sequence Input glyph sequence
* @param start The first input to try
*/
private _getNextLookup(sequence: number[], start: number): { index: number | null, first: number, last: number } {
const result: { index: number | null, first: number, last: number } = {
index: null,
first: Infinity,
last: -1
};
// Loop through each glyph and find the first valid lookup for it
for (let i = 0; i < sequence.length; i++) {
const lookups = this._glyphLookups[sequence[i]];
if (!lookups) {
continue;
}
for (let j = 0; j < lookups.length; j++) {
const lookupIndex = lookups[j];
if (lookupIndex >= start) {
// Update the lookup information if it's the one we're
// storing or earlier than it.
if (result.index === null || lookupIndex <= result.index) {
result.index = lookupIndex;
if (result.first > i) {
result.first = i;
}
result.last = i + 1;
}
break;
}
}
}
return result;
}
}
/**
* Load the font from it's binary data. The returned value can be used to find
* ligatures for the font.
*
* @param buffer ArrayBuffer of the font to load
*/
export function loadBuffer(buffer: ArrayBuffer, options?: IOptions): IFont {
const font = opentype.parse(buffer);
return new FontImpl(font, {
cacheSize: 0,
...options
});
}
export { IFont as Font, ILigatureData as LigatureData, IOptions as Options };
@@ -0,0 +1,225 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import mergeTrees from './merge';
interface ILookupResult {
contextRange: [number, number];
index: number;
subIndex: number;
length: number;
substitutions: number[];
}
function lookup(substitutionGlyph: number, index?: number, subIndex?: number): ILookupResult {
return {
contextRange: [0, 1],
index: index || 0,
subIndex: subIndex || 0,
length: 1,
substitutions: [substitutionGlyph]
};
}
describe('addon-ligatures - merge', () => {
describe('mergeTrees', () => {
it('combines disjoint trees', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(2) },
range: [2, 4]
}]
},
{
individual: {
'5': { lookup: lookup(3) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(4) },
range: [8, 10]
}]
}
]);
assert.deepEqual(result, {
individual: {
'1': { lookup: lookup(1) },
'5': { lookup: lookup(3) }
},
range: [{
entry: { lookup: lookup(2) },
range: [2, 4]
}, {
entry: { lookup: lookup(4) },
range: [8, 10]
}]
});
});
it('merges matching individual glyphs', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1, 1) }
},
range: []
},
{
individual: {
'1': { lookup: lookup(2, 0) }
},
range: []
},
{
individual: {
'1': { lookup: lookup(3, 2) }
},
range: []
}
]);
assert.deepEqual(result, {
individual: {
'1': { lookup: lookup(2, 0) }
},
range: []
});
});
it('merges range glyphs overlapping individual glyphs', () => {
const result = mergeTrees([
{
individual: {
'1': { lookup: lookup(1, 0) }
},
range: []
},
{
individual: {},
range: [{
entry: { lookup: lookup(2, 1) },
range: [0, 4]
}]
}
]);
assert.deepEqual(result, {
individual: {
'0': { lookup: lookup(2, 1) },
'1': { lookup: lookup(1, 0) }
},
range: [{
entry: { lookup: lookup(2, 1) },
range: [2, 4]
}]
});
});
it('merges individual glyphs overlapping range glyphs', () => {
const result = mergeTrees([
{
individual: {},
range: [{
entry: { lookup: lookup(2, 1) },
range: [0, 4]
}]
},
{
individual: {
'1': { lookup: lookup(1, 0) }
},
range: []
}
]);
assert.deepEqual(result, {
individual: {
'0': { lookup: lookup(2, 1) },
'1': { lookup: lookup(1, 0) }
},
range: [{
entry: { lookup: lookup(2, 1) },
range: [2, 4]
}]
});
});
it('merges multiple overlapping ranges', () => {
const result = mergeTrees([
{
individual: {},
range: [{
entry: { lookup: lookup(1, 2) },
range: [0, 3]
}, {
entry: { lookup: lookup(2, 1) },
range: [6, 12]
}, {
entry: { lookup: lookup(5, 3) },
range: [15, 20]
}, {
entry: { lookup: lookup(7, 4) },
range: [20, 22]
}]
},
{
individual: {},
range: [{
entry: { lookup: lookup(3, 0) },
range: [2, 8]
}, {
entry: { lookup: lookup(4, 0) },
range: [10, 13]
}, {
entry: { lookup: lookup(6, 0) },
range: [16, 21]
}]
}
]);
assert.deepEqual(result, {
individual: {
'2': { lookup: lookup(3, 0) },
'12': { lookup: lookup(4, 0) },
'15': { lookup: lookup(5, 3) },
'20': { lookup: lookup(6, 0) },
'21': { lookup: lookup(7, 4) }
},
range: [{
entry: { lookup: lookup(1, 2) },
range: [0, 2]
}, {
entry: { lookup: lookup(3, 0) },
range: [6, 8]
}, {
entry: { lookup: lookup(3, 0) },
range: [3, 6]
}, {
entry: { lookup: lookup(2, 1) },
range: [8, 10]
}, {
entry: { lookup: lookup(4, 0) },
range: [10, 12]
}, {
entry: { lookup: lookup(6, 0) },
range: [16, 20]
}]
});
});
});
});
@@ -0,0 +1,393 @@
import { ILookupTree, ILookupTreeEntry } from './types';
/**
* Merges the provided trees into a single lookup tree. When conflicting lookups
* are encountered between two trees, the one with the lower index, then the
* lower subindex is chosen.
*
* @param trees Array of trees to merge. Entries in earlier trees are favored
* over those in later trees when there is a choice.
*/
export default function mergeTrees(trees: ILookupTree[]): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const mergedEntries = new WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>();
for (const tree of trees) {
mergeSubtree(result, tree, mergedEntries);
}
return result;
}
/**
* Recursively merges the data for the mergeTree into the mainTree.
*
* @param mainTree The tree where the values should be merged
* @param mergeTree The tree to be merged into the mainTree
* @param mergedEntries WeakMap to track already merged entry pairs
*/
function mergeSubtree(mainTree: ILookupTree, mergeTree: ILookupTree, mergedEntries: WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>): void {
// Need to fix this recursively (and handle lookups)
for (const [glyphId, value] of Object.entries(mergeTree.individual)) {
// The main tree is guaranteed to have no overlaps between the
// individual and range values, so if we match an invididual, there
// must not be a range
if (mainTree.individual[glyphId]) {
mergeTreeEntry(mainTree.individual[glyphId], value, mergedEntries);
} else {
let matched = false;
for (const [index, { range, entry }] of mainTree.range.entries()) {
const overlap = getIndividualOverlap(Number(glyphId), range);
// Don't overlap
if (overlap.both === null) {
continue;
}
matched = true;
// If they overlap, we have to split the range and then
// merge the overlap
mainTree.individual[glyphId] = value;
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
// When there's an overlap, we also have to fix up the range
// that we had already processed
mainTree.range.splice(index, 1);
for (const glyph of overlap.second) {
if (Array.isArray(glyph)) {
mainTree.range.push({
range: glyph,
entry: cloneEntry(entry)
});
} else {
mainTree.individual[glyph] = cloneEntry(entry);
}
}
}
if (!matched) {
mainTree.individual[glyphId] = value;
}
}
}
for (const { range, entry } of mergeTree.range) {
// Ranges are more complicated, because they can overlap with
// multiple things, individual and range alike. We start by
// eliminating ranges that are already present in another range
let remainingRanges: (number | [number, number])[] = [range];
for (let index = 0; index < mainTree.range.length; index++) {
const { range, entry: resultEntry } = mainTree.range[index];
for (const [remainingIndex, remainingRange] of remainingRanges.entries()) {
if (Array.isArray(remainingRange)) {
const overlap = getRangeOverlap(remainingRange, range);
if (overlap.both === null) {
continue;
}
mainTree.range.splice(index, 1);
index--;
const entryToMerge: ILookupTreeEntry = cloneEntry(resultEntry);
if (Array.isArray(overlap.both)) {
mainTree.range.push({
range: overlap.both,
entry: entryToMerge
});
} else {
mainTree.individual[overlap.both] = entryToMerge;
}
mergeTreeEntry(entryToMerge, cloneEntry(entry), mergedEntries);
for (const second of overlap.second) {
if (Array.isArray(second)) {
mainTree.range.push({
range: second,
entry: cloneEntry(resultEntry)
});
} else {
mainTree.individual[second] = cloneEntry(resultEntry);
}
}
remainingRanges = overlap.first;
} else {
const overlap = getIndividualOverlap(remainingRange, range);
if (overlap.both === null) {
continue;
}
// If they overlap, we have to split the range and then
// merge the overlap
mainTree.individual[remainingRange] = cloneEntry(entry);
mergeTreeEntry(mainTree.individual[remainingRange], cloneEntry(resultEntry), mergedEntries);
// When there's an overlap, we also have to fix up the range
// that we had already processed
mainTree.range.splice(index, 1);
index--;
for (const glyph of overlap.second) {
if (Array.isArray(glyph)) {
mainTree.range.push({
range: glyph,
entry: cloneEntry(resultEntry)
});
} else {
mainTree.individual[glyph] = cloneEntry(resultEntry);
}
}
remainingRanges.splice(remainingIndex, 1, ...overlap.first);
break;
}
}
}
// Next, we run the same against any individual glyphs
for (const glyphId of Object.keys(mainTree.individual)) {
for (const [remainingIndex, remainingRange] of remainingRanges.entries()) {
if (Array.isArray(remainingRange)) {
const overlap = getIndividualOverlap(Number(glyphId), remainingRange);
if (overlap.both === null) {
continue;
}
// If they overlap, we have to merge the overlap
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
// Update the remaining ranges
remainingRanges.splice(remainingIndex, 1, ...overlap.second);
break;
} else {
if (Number(glyphId) === remainingRange) {
mergeTreeEntry(mainTree.individual[glyphId], cloneEntry(entry), mergedEntries);
break;
}
}
}
}
// Any remaining ranges should just be added directly
for (const remainingRange of remainingRanges) {
if (Array.isArray(remainingRange)) {
mainTree.range.push({
range: remainingRange,
entry: cloneEntry(entry)
});
} else {
mainTree.individual[remainingRange] = cloneEntry(entry);
}
}
}
}
/**
* Recursively merges the entry forr the mergeTree into the mainTree
*
* @param mainTree The entry where the values should be merged
* @param mergeTree The entry to merge into the mainTree
* @param mergedEntries WeakMap to track already merged entry pairs
*/
function mergeTreeEntry(mainTree: ILookupTreeEntry, mergeTree: ILookupTreeEntry, mergedEntries: WeakMap<ILookupTreeEntry, Set<ILookupTreeEntry>>): void {
// Check if we've already merged this pair
let mergedSet = mergedEntries.get(mainTree);
if (mergedSet?.has(mergeTree)) {
return;
}
if (!mergedSet) {
mergedSet = new Set();
mergedEntries.set(mainTree, mergedSet);
}
mergedSet.add(mergeTree);
if (
mergeTree.lookup && (
!mainTree.lookup ||
mainTree.lookup.index > mergeTree.lookup.index ||
(mainTree.lookup.index === mergeTree.lookup.index && mainTree.lookup.subIndex > mergeTree.lookup.subIndex)
)
) {
mainTree.lookup = mergeTree.lookup;
}
if (mergeTree.forward) {
if (!mainTree.forward) {
mainTree.forward = mergeTree.forward;
} else {
mergeSubtree(mainTree.forward, mergeTree.forward, mergedEntries);
}
}
if (mergeTree.reverse) {
if (!mainTree.reverse) {
mainTree.reverse = mergeTree.reverse;
} else {
mergeSubtree(mainTree.reverse, mergeTree.reverse, mergedEntries);
}
}
}
interface IOverlap {
first: (number | [number, number])[];
second: (number | [number, number])[];
both: number | [number, number] | null;
}
/**
* Determines the overlap (if any) between two ranges. Returns the distinct
* ranges for each range and the overlap (if any).
*
* @param first First range
* @param second Second range
*/
function getRangeOverlap(first: [number, number], second: [number, number]): IOverlap {
const result: IOverlap = {
first: [],
second: [],
both: null
};
// Both
if (first[0] < second[1] && second[0] < first[1]) {
const start = Math.max(first[0], second[0]);
const end = Math.min(first[1], second[1]);
result.both = rangeOrIndividual(start, end);
}
// Before
if (first[0] < second[0]) {
const start = first[0];
const end = Math.min(second[0], first[1]);
result.first.push(rangeOrIndividual(start, end));
} else if (second[0] < first[0]) {
const start = second[0];
const end = Math.min(second[1], first[0]);
result.second.push(rangeOrIndividual(start, end));
}
// After
if (first[1] > second[1]) {
const start = Math.max(first[0], second[1]);
const end = first[1];
result.first.push(rangeOrIndividual(start, end));
} else if (second[1] > first[1]) {
const start = Math.max(first[1], second[0]);
const end = second[1];
result.second.push(rangeOrIndividual(start, end));
}
return result;
}
/**
* Determines the overlap (if any) between the individual glyph and the range
* provided. Returns the glyphs and/or ranges that are unique to each provided
* and the overlap (if any).
*
* @param first Individual glyph
* @param second Range
*/
function getIndividualOverlap(first: number, second: [number, number]): IOverlap {
// Disjoint
if (first < second[0] || first > second[1]) {
return {
first: [first],
second: [second],
both: null
};
}
const result: IOverlap = {
first: [],
second: [],
both: first
};
if (second[0] < first) {
result.second.push(rangeOrIndividual(second[0], first));
}
if (second[1] > first) {
result.second.push(rangeOrIndividual(first + 1, second[1]));
}
return result;
}
/**
* Returns an individual glyph if the range is of size one or a range if it is
* larger.
*
* @param start Beginning of the range (inclusive)
* @param end End of the range (exclusive)
*/
function rangeOrIndividual(start: number, end: number): number | [number, number] {
if (end - start === 1) {
return start;
}
return [start, end];
}
/**
* Clones an individual lookup tree entry.
*
* @param entry Lookup tree entry to clone
* @param visited Map to track already cloned entries (prevents infinite loops)
*/
function cloneEntry(entry: ILookupTreeEntry, visited: Map<ILookupTreeEntry, ILookupTreeEntry> = new Map()): ILookupTreeEntry {
if (visited.has(entry)) {
return visited.get(entry)!;
}
const result: ILookupTreeEntry = {};
visited.set(entry, result);
if (entry.forward) {
result.forward = cloneTree(entry.forward, visited);
}
if (entry.reverse) {
result.reverse = cloneTree(entry.reverse, visited);
}
if (entry.lookup) {
result.lookup = {
contextRange: entry.lookup.contextRange.slice() as [number, number],
index: entry.lookup.index,
length: entry.lookup.length,
subIndex: entry.lookup.subIndex,
substitutions: entry.lookup.substitutions.slice()
};
}
return result;
}
/**
* Clones a lookup tree.
*
* @param tree Lookup tree to clone
* @param visited Map to track already cloned entries (prevents infinite loops)
*/
function cloneTree(tree: ILookupTree, visited: Map<ILookupTreeEntry, ILookupTreeEntry> = new Map()): ILookupTree {
const individual: { [glyphId: string]: ILookupTreeEntry } = {};
for (const [glyphId, entry] of Object.entries(tree.individual)) {
individual[glyphId] = cloneEntry(entry, visited);
}
return {
individual,
range: tree.range.map(({ range, entry }) => ({
range: range.slice() as [number, number],
entry: cloneEntry(entry, visited)
}))
};
}
@@ -0,0 +1,49 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import mergeRange from './mergeRange';
describe('addon-ligatures - mergeRange', () => {
it('inserts a new range before the existing ones', () => {
const result = mergeRange([[1, 2], [2, 3]], 0, 1);
assert.deepEqual(result, [[0, 1], [1, 2], [2, 3]]);
});
it('inserts in between two ranges', () => {
const result = mergeRange([[0, 2], [4, 6]], 2, 4);
assert.deepEqual(result, [[0, 2], [2, 4], [4, 6]]);
});
it('inserts after the last range', () => {
const result = mergeRange([[0, 2], [4, 6]], 6, 8);
assert.deepEqual(result, [[0, 2], [4, 6], [6, 8]]);
});
it('extends the beginning of a range', () => {
const result = mergeRange([[0, 2], [4, 6]], 3, 5);
assert.deepEqual(result, [[0, 2], [3, 6]]);
});
it('extends the end of a range', () => {
const result = mergeRange([[0, 2], [4, 6]], 1, 4);
assert.deepEqual(result, [[0, 4], [4, 6]]);
});
it('extends the last range', () => {
const result = mergeRange([[0, 2], [4, 6]], 5, 7);
assert.deepEqual(result, [[0, 2], [4, 7]]);
});
it('connects two ranges', () => {
const result = mergeRange([[0, 2], [4, 6]], 1, 5);
assert.deepEqual(result, [[0, 6]]);
});
it('connects more than two ranges', () => {
const result = mergeRange([[0, 2], [4, 6], [8, 10], [12, 14]], 1, 10);
assert.deepEqual(result, [[0, 10], [12, 14]]);
});
});
@@ -0,0 +1,66 @@
/**
* Merges the range defined by the provided start and end into the list of
* existing ranges. The merge is done in place on the existing range for
* performance and is also returned.
*
* @param ranges Existing range list
* @param newRangeStart Start position of the range to merge, inclusive
* @param newRangeEnd End position of range to merge, exclusive
*/
export default function mergeRange(ranges: [number, number][], newRangeStart: number, newRangeEnd: number): [number, number][] {
let inRange = false;
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
if (!inRange) {
if (newRangeEnd <= range[0]) {
// Case 1: New range is before the search range
ranges.splice(i, 0, [newRangeStart, newRangeEnd]);
return ranges;
}
if (newRangeEnd <= range[1]) {
// Case 2: New range is either wholly contained within the
// search range or overlaps with the front of it
range[0] = Math.min(newRangeStart, range[0]);
return ranges;
}
if (newRangeStart < range[1]) {
// Case 3: New range either wholly contains the search range
// or overlaps with the end of it
range[0] = Math.min(newRangeStart, range[0]);
inRange = true;
} else {
// Case 4: New range starts after the search range
continue;
}
} else {
if (newRangeEnd <= range[0]) {
// Case 5: New range extends from previous range but doesn't
// reach the current one
ranges[i - 1][1] = newRangeEnd;
return ranges;
}
if (newRangeEnd <= range[1]) {
// Case 6: New range extends from prvious range into the
// current range
ranges[i - 1][1] = Math.max(newRangeEnd, range[1]);
ranges.splice(i, 1);
inRange = false;
return ranges;
}
// Case 7: New range extends from previous range past the
// end of the current range
ranges.splice(i, 1);
i--;
}
}
if (inRange) {
// Case 8: New range extends past the last existing range
ranges[ranges.length - 1][1] = newRangeEnd;
} else {
// Case 9: New range starts after the last existing range
ranges.push([newRangeStart, newRangeEnd]);
}
return ranges;
}
@@ -0,0 +1,82 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 1.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#61-chaining-context-substitution-format-1-simple-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat1, lookups: Lookup[], tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const firstGlyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId, index } of firstGlyphs) {
const chainRuleSet = table.chainRuleSets[index];
// If the chain rule set is null there's nothing to do with this table.
if (!chainRuleSet) {
continue;
}
for (const [subIndex, subTable] of chainRuleSet.entries()) {
let currentEntries: IEntryMeta[] = getInputTree(
result,
subTable.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
// We walk forward, then backward
for (const [index, glyph] of subTable.input.entries()) {
currentEntries = processInputPosition(
[glyph],
index + 1,
currentEntries,
subTable.lookupRecords,
lookups
);
}
for (const glyph of subTable.lookahead) {
currentEntries = processLookaheadPosition(
[glyph],
currentEntries
);
}
for (const glyph of subTable.backtrack) {
currentEntries = processBacktrackPosition(
[glyph],
currentEntries
);
}
// When we get to the end, insert the lookup information
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
length: subTable.input.length + 1,
index: tableIndex,
subIndex,
contextRange: [
-1 * subTable.backtrack.length,
1 + subTable.input.length + subTable.lookahead.length
]
};
}
}
}
return result;
}
@@ -0,0 +1,96 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import mergeTrees from '../merge';
import { listGlyphsByIndex } from './coverage';
import getGlyphClass, { listClassGlyphs } from './classDef';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 2.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#62-chaining-context-substitution-format-2-class-based-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat2, lookups: Lookup[], tableIndex: number): ILookupTree {
const results: ILookupTree[] = [];
const firstGlyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId } of firstGlyphs) {
const firstInputClass = getGlyphClass(table.inputClassDef, glyphId);
for (const [glyphId, inputClass] of firstInputClass.entries()) {
// istanbul ignore next - invalid font
if (inputClass === null) {
continue;
}
const classSet = table.chainClassSet[inputClass];
// If the class set is null there's nothing to do with this table.
if (!classSet) {
continue;
}
for (const [subIndex, subTable] of classSet.entries()) {
const result: ILookupTree = {
individual: {},
range: []
};
let currentEntries: IEntryMeta[] = getInputTree(
result,
subTable.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
for (const [index, classNum] of subTable.input.entries()) {
currentEntries = processInputPosition(
listClassGlyphs(table.inputClassDef, classNum),
index + 1,
currentEntries,
subTable.lookupRecords,
lookups
);
}
for (const classNum of subTable.lookahead) {
currentEntries = processLookaheadPosition(
listClassGlyphs(table.lookaheadClassDef, classNum),
currentEntries
);
}
for (const classNum of subTable.backtrack) {
currentEntries = processBacktrackPosition(
listClassGlyphs(table.backtrackClassDef, classNum),
currentEntries
);
}
// When we get to the end, all of the entries we've accumulated
// should have a lookup defined
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex,
length: subTable.input.length + 1,
contextRange: [
-1 * subTable.backtrack.length,
1 + subTable.input.length + subTable.lookahead.length
]
};
}
results.push(result);
}
}
}
return mergeTrees(results);
}
@@ -0,0 +1,73 @@
import { ChainingContextualSubstitutionTable, Lookup } from '../tables';
import { ILookupTree } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processInputPosition, processLookaheadPosition, processBacktrackPosition, getInputTree, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 6, format 3.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#63-chaining-context-substitution-format-3-coverage-based-glyph-contexts
*
* @param table JSON representation of the table
* @param lookups List of lookup tables
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: ChainingContextualSubstitutionTable.IFormat3, lookups: Lookup[], tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const firstGlyphs = listGlyphsByIndex(table.inputCoverage[0]);
for (const { glyphId } of firstGlyphs) {
let currentEntries: IEntryMeta[] = getInputTree(
result,
table.lookupRecords,
lookups,
0,
glyphId
).map(({ entry, substitution }) => ({ entry, substitutions: [substitution] }));
for (const [index, coverage] of table.inputCoverage.slice(1).entries()) {
currentEntries = processInputPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
index + 1,
currentEntries,
table.lookupRecords,
lookups
);
}
for (const coverage of table.lookaheadCoverage) {
currentEntries = processLookaheadPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
for (const coverage of table.backtrackCoverage) {
currentEntries = processBacktrackPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
// When we get to the end, all of the entries we've accumulated
// should have a lookup defined
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex: 0,
length: table.inputCoverage.length,
contextRange: [
-1 * table.backtrackCoverage.length,
table.inputCoverage.length + table.lookaheadCoverage.length
]
};
}
}
return result;
}
@@ -0,0 +1,69 @@
import { IReverseChainingContextualSingleSubstitutionTable } from '../tables';
import { ILookupTree, ILookupTreeEntry } from '../types';
import { listGlyphsByIndex } from './coverage';
import { processLookaheadPosition, processBacktrackPosition, IEntryMeta } from './helper';
/**
* Build lookup tree for GSUB lookup table 8, format 1.
* https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#81-reverse-chaining-contextual-single-substitution-format-1-coverage-based-glyph-contexts
*
* @param table JSON representation of the table
* @param tableIndex Index of this table in the overall lookup
*/
export default function buildTree(table: IReverseChainingContextualSingleSubstitutionTable, tableIndex: number): ILookupTree {
const result: ILookupTree = {
individual: {},
range: []
};
const glyphs = listGlyphsByIndex(table.coverage);
for (const { glyphId, index } of glyphs) {
const initialEntry: ILookupTreeEntry = {};
if (Array.isArray(glyphId)) {
result.range.push({
entry: initialEntry,
range: glyphId
});
} else {
result.individual[glyphId] = initialEntry;
}
let currentEntries: IEntryMeta[] = [{
entry: initialEntry,
substitutions: [table.substitutes[index]]
}];
// We walk forward, then backward
for (const coverage of table.lookaheadCoverage) {
currentEntries = processLookaheadPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
for (const coverage of table.backtrackCoverage) {
currentEntries = processBacktrackPosition(
listGlyphsByIndex(coverage).map(glyph => glyph.glyphId),
currentEntries
);
}
// When we get to the end, insert the lookup information
for (const { entry, substitutions } of currentEntries) {
entry.lookup = {
substitutions,
index: tableIndex,
subIndex: 0,
length: 1,
contextRange: [
-1 * table.backtrackCoverage.length,
1 + table.lookaheadCoverage.length
]
};
}
}
return result;
}
@@ -0,0 +1,84 @@
import { ClassDefTable } from '../tables';
/**
* Get the number of the class to which the glyph belongs, or null if it doesn't
* belong to any of them.
*
* @param table JSON representation of the class def table
* @param glyphId Index of the glyph to look for
*/
export default function getGlyphClass(table: ClassDefTable, glyphId: number | [number, number]): Map<number | [number, number], number | null> {
switch (table.format) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-2
case 2:
if (Array.isArray(glyphId)) {
return getRangeGlyphClass(table, glyphId);
}
return new Map([[
glyphId,
getIndividualGlyphClass(table, glyphId)
]]);
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-1
default:
return new Map([[glyphId, null]]);
}
}
function getRangeGlyphClass(table: ClassDefTable.IFormat2, glyphId: [number, number]): Map<number | [number, number], number | null> {
const classStart: number = glyphId[0];
const currentClass: number | null = getIndividualGlyphClass(table, classStart);
let search: number = glyphId[0] + 1;
const result = new Map<[number, number] | number, number | null>();
while (search < glyphId[1]) {
const clazz = getIndividualGlyphClass(table, search);
if (clazz !== currentClass) {
if (search - classStart <= 1) {
result.set(classStart, currentClass);
} else {
result.set([classStart, search], currentClass);
}
}
search++;
}
if (search - classStart <= 1) {
result.set(classStart, currentClass);
} else {
result.set([classStart, search], currentClass);
}
return result;
}
function getIndividualGlyphClass(table: ClassDefTable.IFormat2, glyphId: number): number | null {
for (const range of table.ranges) {
if (range.start <= glyphId && range.end >= glyphId) {
return range.classId;
}
}
return null;
}
export function listClassGlyphs(table: ClassDefTable, index: number): (number | [number, number])[] {
switch (table.format) {
case 2:
const results: (number | [number, number])[] = [];
for (const range of table.ranges) {
if (range.classId !== index) {
continue;
}
if (range.end === range.start) {
results.push(range.start);
} else {
results.push([range.start, range.end + 1]);
}
}
return results;
default:
return [];
}
}
@@ -0,0 +1,43 @@
import { CoverageTable } from '../tables';
/**
* Get the index of the given glyph in the coverage table, or null if it is not
* present in the table.
*
* @param table JSON representation of the coverage table
* @param glyphId Index of the glyph to look for
*/
export default function getCoverageGlyphIndex(table: CoverageTable, glyphId: number): number | null {
switch (table.format) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-1
case 1:
const index = table.glyphs.indexOf(glyphId);
return index !== -1
? index
: null;
// https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-2
case 2:
const range = table.ranges
.find(range => range.start <= glyphId && range.end >= glyphId);
return range
? range.index
: null;
}
}
export function listGlyphsByIndex(table: CoverageTable): { glyphId: number | [number, number], index: number }[] {
switch (table.format) {
case 1:
return table.glyphs.map((glyphId, index) => ({ glyphId, index }));
case 2:
const results: { glyphId: number | [number, number], index: number }[] = [];
for (const [index, range] of table.ranges.entries()) {
if (range.end === range.start) {
results.push({ glyphId: range.start, index });
} else {
results.push({ glyphId: [range.start, range.end + 1], index });
}
}
return results;
}
}
@@ -0,0 +1,187 @@
import { ILookupTreeEntry, ILookupTree } from '../types';
import { ISubstitutionLookupRecord, Lookup } from '../tables';
import { getIndividualSubstitutionGlyph, getRangeSubstitutionGlyphs } from './substitution';
export interface IEntryMeta {
entry: ILookupTreeEntry;
substitutions: (number | null)[];
}
export function processInputPosition(
glyphs: (number | [number, number])[],
position: number,
currentEntries: IEntryMeta[],
lookupRecords: ISubstitutionLookupRecord[],
lookups: Lookup[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
for (const currentEntry of currentEntries) {
currentEntry.entry.forward = {
individual: {},
range: []
};
for (const glyph of glyphs) {
nextEntries.push(...getInputTree(
currentEntry.entry.forward,
lookupRecords,
lookups,
position,
glyph
).map(({ entry, substitution }) => ({
entry,
substitutions: [...currentEntry.substitutions, substitution]
})));
}
}
return nextEntries;
}
export function processLookaheadPosition(
glyphs: (number | [number, number])[],
currentEntries: IEntryMeta[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
const processedEntries = new Set<ILookupTreeEntry>();
for (const currentEntry of currentEntries) {
// Skip if we've already processed this entry object
if (processedEntries.has(currentEntry.entry)) {
continue;
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.forward) {
currentEntry.entry.forward = {
individual: {},
range: []
};
}
// All glyphs at this position share ONE entry - lookahead just needs to match,
// all paths lead to the same result
const sharedEntry: ILookupTreeEntry = {};
for (const glyph of glyphs) {
if (Array.isArray(glyph)) {
currentEntry.entry.forward.range.push({
entry: sharedEntry,
range: glyph
});
} else {
currentEntry.entry.forward.individual[glyph] = sharedEntry;
}
}
nextEntries.push({
entry: sharedEntry,
substitutions: currentEntry.substitutions
});
}
return nextEntries;
}
export function processBacktrackPosition(
glyphs: (number | [number, number])[],
currentEntries: IEntryMeta[]
): IEntryMeta[] {
const nextEntries: IEntryMeta[] = [];
const processedEntries = new Set<ILookupTreeEntry>();
for (const currentEntry of currentEntries) {
// Skip if we've already processed this entry object
if (processedEntries.has(currentEntry.entry)) {
continue;
}
processedEntries.add(currentEntry.entry);
if (!currentEntry.entry.reverse) {
currentEntry.entry.reverse = {
individual: {},
range: []
};
}
// All glyphs at this position share ONE entry - backtrack just needs to match,
// all paths lead to the same result
const sharedEntry: ILookupTreeEntry = {};
for (const glyph of glyphs) {
if (Array.isArray(glyph)) {
currentEntry.entry.reverse.range.push({
entry: sharedEntry,
range: glyph
});
} else {
currentEntry.entry.reverse.individual[glyph] = sharedEntry;
}
}
nextEntries.push({
entry: sharedEntry,
substitutions: currentEntry.substitutions
});
}
return nextEntries;
}
export function getInputTree(tree: ILookupTree, substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], inputIndex: number, glyphId: number | [number, number]): { entry: ILookupTreeEntry, substitution: number | null }[] {
const result: { entry: ILookupTreeEntry, substitution: number | null }[] = [];
if (!Array.isArray(glyphId)) {
tree.individual[glyphId] = {};
result.push({
entry: tree.individual[glyphId],
substitution: getSubstitutionAtPosition(substitutions, lookups, inputIndex, glyphId)
});
} else {
const subs = getSubstitutionAtPositionRange(substitutions, lookups, inputIndex, glyphId);
for (const [range, substitution] of subs) {
const entry: ILookupTreeEntry = {};
if (Array.isArray(range)) {
tree.range.push({ range, entry });
} else {
tree.individual[range] = {};
}
result.push({ entry, substitution });
}
}
return result;
}
function getSubstitutionAtPositionRange(substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], index: number, range: [number, number]): Map<number | [number, number], number | null> {
for (const substitution of substitutions.filter(s => s.sequenceIndex === index)) {
for (const substitutionTable of (lookups[substitution.lookupListIndex] as Lookup.IType1).subtables) {
const sub = getRangeSubstitutionGlyphs(
substitutionTable,
range
);
if (!Array.from(sub.values()).every(val => val !== null)) {
return sub;
}
}
}
return new Map([[range, null]]);
}
function getSubstitutionAtPosition(substitutions: ISubstitutionLookupRecord[], lookups: Lookup[], index: number, glyphId: number): number | null {
for (const substitution of substitutions.filter(s => s.sequenceIndex === index)) {
for (const substitutionTable of (lookups[substitution.lookupListIndex] as Lookup.IType1).subtables) {
const sub = getIndividualSubstitutionGlyph(
substitutionTable,
glyphId
);
if (sub !== null) {
return sub;
}
}
}
return null;
}
@@ -0,0 +1,62 @@
import { SubstitutionTable } from '../tables';
import getCoverageGlyphIndex from './coverage';
/**
* Get the substitution glyph for the givne glyph, or null if the glyph was not
* found in the table.
*
* @param table JSON representation of the substitution table
* @param glyphId The index of the glpyh to find substitutions for
*/
export function getRangeSubstitutionGlyphs(table: SubstitutionTable, glyphId: [number, number]): Map<[number, number] | number, number | null> {
const replacementStart: number = glyphId[0];
const currentReplacement: number | null = getIndividualSubstitutionGlyph(table, replacementStart);
let search: number = glyphId[0] + 1;
const result = new Map<[number, number] | number, number | null>();
while (search < glyphId[1]) {
const sub = getIndividualSubstitutionGlyph(table, search);
if (sub !== currentReplacement) {
if (search - replacementStart <= 1) {
result.set(replacementStart, currentReplacement);
} else {
result.set([replacementStart, search], currentReplacement);
}
}
search++;
}
if (search - replacementStart <= 1) {
result.set(replacementStart, currentReplacement);
} else {
result.set([replacementStart, search], currentReplacement);
}
return result;
}
export function getIndividualSubstitutionGlyph(table: SubstitutionTable, glyphId: number): number | null {
const coverageIndex = getCoverageGlyphIndex(table.coverage, glyphId);
// istanbul ignore next - invalid font
if (coverageIndex === null) {
return null;
}
switch (table.substFormat) {
// https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#11-single-substitution-format-1
case 1:
// TODO: determine if there's a rhyme or reason to the 16-bit
// wraparound and if it can ever be a different number
return (glyphId + table.deltaGlyphId) % (2 ** 16);
// https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#12-single-substitution-format-2
case 2:
// eslint-disable-next-line eqeqeq
return table.substitute[coverageIndex] != null
? table.substitute[coverageIndex]
: null;
}
}
@@ -0,0 +1,112 @@
export type SubstitutionTable = SubstitutionTable.IFormat1 | SubstitutionTable.IFormat2;
export namespace SubstitutionTable {
export interface IFormat1 {
substFormat: 1;
coverage: CoverageTable;
deltaGlyphId: number;
}
export interface IFormat2 {
substFormat: 2;
coverage: CoverageTable;
substitute: number[];
}
}
export type CoverageTable = CoverageTable.IFormat1 | CoverageTable.IFormat2;
export namespace CoverageTable {
export interface IFormat1 {
format: 1;
glyphs: number[];
}
export interface IFormat2 {
format: 2;
ranges: {
start: number;
end: number;
index: number;
}[];
}
}
export type ChainingContextualSubstitutionTable = ChainingContextualSubstitutionTable.IFormat1 |
ChainingContextualSubstitutionTable.IFormat2 | ChainingContextualSubstitutionTable.IFormat3;
export namespace ChainingContextualSubstitutionTable {
export interface IFormat1 {
substFormat: 1;
coverage: CoverageTable;
chainRuleSets: ChainSubRuleTable[][];
}
export interface IFormat2 {
substFormat: 2;
coverage: CoverageTable;
backtrackClassDef: ClassDefTable;
inputClassDef: ClassDefTable;
lookaheadClassDef: ClassDefTable;
chainClassSet: (null | IChainSubClassRuleTable[])[];
}
export interface IFormat3 {
substFormat: 3;
backtrackCoverage: CoverageTable[];
inputCoverage: CoverageTable[];
lookaheadCoverage: CoverageTable[];
lookupRecords: ISubstitutionLookupRecord[];
}
}
export interface IReverseChainingContextualSingleSubstitutionTable {
substFormat: 1;
coverage: CoverageTable;
backtrackCoverage: CoverageTable[];
lookaheadCoverage: CoverageTable[];
substitutes: number[];
}
export type ClassDefTable = ClassDefTable.IFormat2;
export namespace ClassDefTable {
export interface IFormat2 {
format: 2;
ranges: {
start: number;
end: number;
classId: number;
}[];
}
}
export interface ISubstitutionLookupRecord {
sequenceIndex: number;
lookupListIndex: number;
}
export type ChainSubRuleTable = IChainSubClassRuleTable;
export interface IChainSubClassRuleTable {
backtrack: number[];
input: number[];
lookahead: number[];
lookupRecords: ISubstitutionLookupRecord[];
}
export type Lookup = Lookup.IType1 | Lookup.IType6 | Lookup.IType8;
export namespace Lookup {
export interface IType1 {
lookupType: 1;
lookupFlag: number;
subtables: SubstitutionTable[];
}
export interface IType6 {
lookupType: 6;
lookupFlag: number;
subtables: ChainingContextualSubstitutionTable[];
}
export interface IType8 {
lookupType: 8;
lookupFlag: number;
subtables: IReverseChainingContextualSingleSubstitutionTable[];
}
}
@@ -0,0 +1,86 @@
export interface ISubstitutionResult {
index: number;
contextRange: [number, number];
}
/**
* Information about ligatures found in a sequence of text
*/
export interface ILigatureData {
/**
* The list of font glyphs in the input text.
*/
inputGlyphs: number[];
/**
* The list of font glyphs after performing replacements for font ligatures.
*/
outputGlyphs: number[];
/**
* Sorted array of ranges that must be rendered together to produce the
* ligatures in the output sequence. The ranges are inclusive on the left and
* exclusive on the right.
*/
contextRanges: [number, number][];
}
export interface IFont {
/**
* Scans the provided text for font ligatures, returning an object with
* metadata about the text and any ligatures found.
*
* @param text String to search for ligatures
*/
findLigatures(text: string): ILigatureData;
/**
* Scans the provided text for font ligatures, returning an array of ranges
* where ligatures are located.
*
* @param text String to search for ligatures
*/
findLigatureRanges(text: string): [number, number][];
}
export interface IOptions {
/**
* Optional size of previous results to store, measured in total number of
* characters from input strings. Defaults to no cache (0)
*/
cacheSize?: number;
}
export interface ILookupTree {
individual: {
[glyphId: string]: ILookupTreeEntry;
};
range: {
range: [number, number];
entry: ILookupTreeEntry;
}[];
}
export interface ILookupTreeEntry {
lookup?: ILookupResult;
forward?: ILookupTree;
reverse?: ILookupTree;
}
export interface ILookupResult {
substitutions: (number | null)[];
length: number;
index: number;
subIndex: number;
contextRange: [number, number];
}
export interface IFlattenedLookupTree {
[glyphId: string]: IFlattenedLookupTreeEntry;
}
export interface IFlattenedLookupTreeEntry {
lookup?: ILookupResult;
forward?: IFlattenedLookupTree;
reverse?: IFlattenedLookupTree;
}
@@ -0,0 +1,67 @@
import { IFlattenedLookupTree, ILookupResult } from './types';
export default function walkTree(tree: IFlattenedLookupTree, sequence: number[], startIndex: number, index: number): ILookupResult | undefined {
const glyphId = sequence[index];
const subtree = tree[glyphId];
if (!subtree) {
return undefined;
}
let lookup = subtree.lookup;
if (subtree.reverse) {
const reverseLookup = walkReverse(subtree.reverse, sequence, startIndex);
if (
(!lookup && reverseLookup) ||
(
reverseLookup && lookup && (
lookup.index > reverseLookup.index ||
(lookup.index === reverseLookup.index && lookup.subIndex > reverseLookup.subIndex)
)
)
) {
lookup = reverseLookup;
}
}
if (++index >= sequence.length || !subtree.forward) {
return lookup;
}
const forwardLookup = walkTree(subtree.forward, sequence, startIndex, index);
if (
(!lookup && forwardLookup) ||
(
forwardLookup && lookup && (
lookup.index > forwardLookup.index ||
(lookup.index === forwardLookup.index && lookup.subIndex > forwardLookup.subIndex)
)
)
) {
lookup = forwardLookup;
}
return lookup;
}
function walkReverse(tree: IFlattenedLookupTree, sequence: number[], index: number): ILookupResult | undefined {
let subtree = tree[sequence[--index]];
let lookup: ILookupResult | undefined = subtree && subtree.lookup;
while (subtree) {
if (
(!lookup && subtree.lookup) ||
(subtree.lookup && lookup && lookup.index > subtree.lookup.index)
) {
lookup = subtree.lookup;
}
if (--index < 0 || !subtree.reverse) {
break;
}
subtree = subtree.reverse[sequence[index]];
}
return lookup;
}
+1 -1
View File
@@ -4,7 +4,7 @@
*/
import type { Terminal } from '@xterm/xterm';
import { Font } from 'font-ligatures';
import { Font } from './fontLigatures/index';
import load from './font';
+1 -2
View File
@@ -4,11 +4,10 @@
*/
import { assert } from 'chai';
import parse from './parse';
// TODO: integrate tests from http://test.csswg.org/suites/css-fonts-4_dev/nightly-unstable/
describe('parse', () => {
describe('addon-ligatures - parse', () => {
it('parses individual families', () => {
assert.deepEqual(parse('monospace'), ['monospace']);
});
+3 -1
View File
@@ -9,7 +9,9 @@
"noUnusedLocals": true,
"preserveWatchOutput": true,
"types": [
"../../../node_modules/@types/mocha"
"../../../node_modules/@types/mocha",
// HACK: src shouldn't use node types but it's needed for index.test.ts
"../../../node_modules/@types/node"
],
"paths": {
"@xterm/addon-ligatures" : [
@@ -4,61 +4,62 @@
*/
import * as path from 'path';
import * as sinon from 'sinon';
import { assert } from 'chai';
import * as fontFinder from 'font-finder';
import * as ligatureSupport from '.';
// Use require to get a mutable module object (ESM imports create read-only bindings)
const fontFinder = require('font-finder');
const ligatureSupport = require('../out-esbuild/index');
const originalList = fontFinder.list;
describe('LigaturesAddon', () => {
let onRefresh: sinon.SinonStub;
let onRefresh: { called: boolean, callCount: number, (...args: any[]): void };
let term: MockTerminal;
// -> forms a ligature in Fira Code and Iosevka, but www only forms a ligature
// in Fira Code
const input = 'a -> b www c';
before(() => {
sinon.stub(fontFinder, 'list').returns(Promise.resolve({
// eslint-disable-next-line @typescript-eslint/naming-convention
fontFinder.list = () => Promise.resolve({
'Fira Code': [{
path: path.join(__dirname, '../fonts/firaCode.otf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Iosevka': [{
path: path.join(__dirname, '../fonts/iosevka.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Nonexistant Font': [{
path: path.join(__dirname, '../fonts/nonexistant.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}]
} as fontFinder.FontList));
});
});
after(() => {
fontFinder.list = originalList;
});
beforeEach(() => {
onRefresh = sinon.stub();
onRefresh = Object.assign((..._args: any[]) => { onRefresh.called = true; onRefresh.callCount++; }, { called: false, callCount: 0 });
term = new MockTerminal(onRefresh);
ligatureSupport.enableLigatures(term as any);
});
it('registers itself correctly', () => {
const term = new MockTerminal(sinon.spy());
const term = new MockTerminal(() => {});
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
});
it('registers itself correctly when called directly', () => {
const term = new MockTerminal(sinon.spy());
const term = new MockTerminal(() => {});
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
@@ -72,14 +73,14 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = 'Nonexistant Font, monospace';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
});
it('returns nothing if the font is not present on the system', async () => {
term.options.fontFamily = 'notinstalled';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -87,7 +88,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = 'monospace';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -95,7 +96,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = '';
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
assert.deepEqual(term.joiner!(input), []);
});
@@ -103,7 +104,7 @@ describe('LigaturesAddon', () => {
term.options.fontFamily = {} as any;
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.strictEqual(onRefresh.callCount, 0);
});
});
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ESNext",
"lib": [
"es2021"
],
"rootDir": ".",
"outDir": "../out-esbuild-test",
"sourceMap": true,
"removeComments": true,
"baseUrl": ".",
"strict": true,
"types": [
"../../../node_modules/@types/mocha",
"../../../node_modules/@types/node"
]
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
+2 -1
View File
@@ -2,6 +2,7 @@
"files": [],
"include": [],
"references": [
{ "path": "./src" }
{ "path": "./src" },
{ "path": "./test" }
]
}
-272
View File
@@ -1,272 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@sinonjs/commons@^1", "@sinonjs/commons@^1.0.2", "@sinonjs/commons@^1.3.0", "@sinonjs/commons@^1.7.0":
version "1.8.0"
resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.0.tgz#c8d68821a854c555bba172f3b06959a0039b236d"
integrity sha512-wEj54PfsZ5jGSwMX68G8ZXFawcSglQSXqCftWX3ec8MDUzQdHgcKvw97awHbY0efQEL5iKUOAmmVtoYgmrSG4Q==
dependencies:
type-detect "4.0.8"
"@sinonjs/formatio@^3.0.0", "@sinonjs/formatio@^3.2.1":
version "3.2.2"
resolved "https://registry.yarnpkg.com/@sinonjs/formatio/-/formatio-3.2.2.tgz#771c60dfa75ea7f2d68e3b94c7e888a78781372c"
integrity sha512-B8SEsgd8gArBLMD6zpRw3juQ2FVSsmdd7qlevyDqzS9WTCtvF55/gAL+h6gue8ZvPYcdiPdvueM/qm//9XzyTQ==
dependencies:
"@sinonjs/commons" "^1"
"@sinonjs/samsam" "^3.1.0"
"@sinonjs/samsam@^2.1.2":
version "2.1.3"
resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-2.1.3.tgz#62cf2a9b624edc795134135fe37fc2ae8ea36be3"
integrity sha512-8zNeBkSKhU9a5cRNbpCKau2WWPfan+Q2zDlcXvXyhn9EsMqgYs4qzo0XHNVlXC6ABQL8fT6nV+zzo5RTHJzyXw==
"@sinonjs/samsam@^3.1.0":
version "3.3.3"
resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-3.3.3.tgz#46682efd9967b259b81136b9f120fd54585feb4a"
integrity sha512-bKCMKZvWIjYD0BLGnNrxVuw4dkWCYsLqFOUWw8VgKF/+5Y+mE7LfHWPIYoDXowH+3a9LsWDMo0uAP8YDosPvHQ==
dependencies:
"@sinonjs/commons" "^1.3.0"
array-from "^2.1.1"
lodash "^4.17.15"
"@sinonjs/text-encoding@^0.7.1":
version "0.7.1"
resolved "https://registry.yarnpkg.com/@sinonjs/text-encoding/-/text-encoding-0.7.1.tgz#8da5c6530915653f3a1f38fd5f101d8c3f8079c5"
integrity sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==
"@types/sinon@^5.0.1":
version "5.0.1"
resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-5.0.1.tgz#a15b36ec42f1f53166617491feabd1734cb03e21"
array-from@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/array-from/-/array-from-2.1.1.tgz#cfe9d8c26628b9dc5aecc62a9f5d8f1f352c1195"
integrity sha1-z+nYwmYoudxa7MYqn12PHzUsEZU=
asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
axios@^1.6.0:
version "1.8.2"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.8.2.tgz#fabe06e241dfe83071d4edfbcaa7b1c3a40f7979"
integrity sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==
dependencies:
follow-redirects "^1.15.6"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
buffer-crc32@~0.2.3:
version "0.2.13"
resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
dependencies:
delayed-stream "~1.0.0"
delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
diff@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12"
fd-slicer@~1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e"
dependencies:
pend "~1.2.0"
follow-redirects@^1.15.6:
version "1.15.9"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.9.tgz#a604fa10e443bf98ca94228d9eebcc2e8a2c8ee1"
integrity sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==
font-finder@^1.0.3:
version "1.0.4"
resolved "https://registry.yarnpkg.com/font-finder/-/font-finder-1.0.4.tgz#2ca944954dd8d0e1b5bdc4c596cc08607761d89b"
dependencies:
get-system-fonts "^2.0.0"
promise-stream-reader "^1.0.1"
font-finder@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/font-finder/-/font-finder-1.1.0.tgz#2bff2b2762acba720239c8bec898a96daae90858"
integrity sha512-wpCL2uIbi6GurJbU7ZlQ3nGd61Ho+dSU6U83/xJT5UPFfN35EeCW/rOtS+5k+IuEZu2SYmHzDIPL9eA5tSYRAw==
dependencies:
get-system-fonts "^2.0.0"
promise-stream-reader "^1.0.1"
font-ligatures@^1.4.1:
version "1.4.1"
resolved "https://registry.npmjs.org/font-ligatures/-/font-ligatures-1.4.1.tgz#e8c9df7cf6bee80c0cca4a9a578618c7b1f5d8de"
integrity sha512-7W6zlfyhvCqShZ5ReUWqmSd9vBaUudW0Hxis+tqUjtHhsPU+L3Grf8mcZAtCiXHTzorhwdRTId2WeH/88gdFkw==
dependencies:
font-finder "^1.0.3"
lru-cache "^6.0.0"
opentype.js "^0.8.0"
form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
get-system-fonts@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/get-system-fonts/-/get-system-fonts-2.0.0.tgz#a43b9a33f05c0715a60176d2aad5ce6e98f0a3c6"
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
isarray@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
just-extend@^4.0.2:
version "4.1.0"
resolved "https://registry.yarnpkg.com/just-extend/-/just-extend-4.1.0.tgz#7278a4027d889601640ee0ce0e5a00b992467da4"
integrity sha512-ApcjaOdVTJ7y4r08xI5wIqpvwS48Q0PBG4DJROcEkH1f8MdAiNFyFxz3xoL0LWAVwjrwPYZdVHHxhRHcx/uGLA==
lodash.get@^4.4.2:
version "4.4.2"
resolved "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99"
lodash@^4.17.15:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
lolex@^2.7.5:
version "2.7.5"
resolved "https://registry.yarnpkg.com/lolex/-/lolex-2.7.5.tgz#113001d56bfc7e02d56e36291cc5c413d1aa0733"
integrity sha512-l9x0+1offnKKIzYVjyXU2SiwhXDLekRzKyhnbyldPHvC7BvLPVpdNUNR2KeMAiCN2D/kLNttZgQD5WjSxuBx3Q==
lolex@^5.0.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/lolex/-/lolex-5.1.2.tgz#953694d098ce7c07bc5ed6d0e42bc6c0c6d5a367"
integrity sha512-h4hmjAvHTmd+25JSwrtTIuwbKdwg5NzZVRMLn9saij4SZaepCrTCxPr35H/3bjwfMJtN+t3CX8672UIkglz28A==
dependencies:
"@sinonjs/commons" "^1.7.0"
lru-cache@^6.0.0:
version "6.0.0"
resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
dependencies:
yallist "^4.0.0"
mime-db@1.52.0:
version "1.52.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70"
integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==
mime-types@^2.1.12:
version "2.1.35"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a"
integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
dependencies:
mime-db "1.52.0"
minimist@^1.2.5:
version "1.2.6"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44"
integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==
mkdirp@0.5.5:
version "0.5.5"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def"
integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==
dependencies:
minimist "^1.2.5"
nise@^1.4.5:
version "1.5.3"
resolved "https://registry.yarnpkg.com/nise/-/nise-1.5.3.tgz#9d2cfe37d44f57317766c6e9408a359c5d3ac1f7"
integrity sha512-Ymbac/94xeIrMf59REBPOv0thr+CJVFMhrlAkW/gjCIE58BGQdCj0x7KRCb3yz+Ga2Rz3E9XXSvUyyxqqhjQAQ==
dependencies:
"@sinonjs/formatio" "^3.2.1"
"@sinonjs/text-encoding" "^0.7.1"
just-extend "^4.0.2"
lolex "^5.0.1"
path-to-regexp "^1.7.0"
opentype.js@^0.8.0:
version "0.8.0"
resolved "https://registry.yarnpkg.com/opentype.js/-/opentype.js-0.8.0.tgz#acabcfa1642fbe894a3e4d759e43ba694e02bd35"
dependencies:
tiny-inflate "^1.0.2"
path-to-regexp@^1.7.0:
version "1.9.0"
resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-1.9.0.tgz#5dc0753acbf8521ca2e0f137b4578b917b10cf24"
integrity sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==
dependencies:
isarray "0.0.1"
pend@~1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50"
promise-stream-reader@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/promise-stream-reader/-/promise-stream-reader-1.0.1.tgz#4e793a79c9d49a73ccd947c6da9c127f12923649"
proxy-from-env@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
sinon@6.3.5:
version "6.3.5"
resolved "https://registry.yarnpkg.com/sinon/-/sinon-6.3.5.tgz#0f6d6a5b4ebaad1f6e8e019395542d1d02c144a0"
integrity sha512-xgoZ2gKjyVRcF08RrIQc+srnSyY1JDJtxu3Nsz07j1ffjgXoY6uPLf/qja6nDBZgzYYEovVkFryw2+KiZz11xQ==
dependencies:
"@sinonjs/commons" "^1.0.2"
"@sinonjs/formatio" "^3.0.0"
"@sinonjs/samsam" "^2.1.2"
diff "^3.5.0"
lodash.get "^4.4.2"
lolex "^2.7.5"
nise "^1.4.5"
supports-color "^5.5.0"
type-detect "^4.0.8"
supports-color@^5.5.0:
version "5.5.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==
dependencies:
has-flag "^3.0.0"
tiny-inflate@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/tiny-inflate/-/tiny-inflate-1.0.2.tgz#93d9decffc8805bd57eae4310f0b745e9b6fb3a7"
type-detect@4.0.8, type-detect@^4.0.8:
version "4.0.8"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
yallist@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
yauzl@^2.10.0:
version "2.10.0"
resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
dependencies:
buffer-crc32 "~0.2.3"
fd-slicer "~1.1.0"
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-progress",
"version": "0.1.0",
"version": "0.2.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -21,8 +21,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+1 -2
View File
@@ -12,8 +12,7 @@
"removeComments": true,
"strict": true,
"types": [
"../../../node_modules/@types/mocha",
"../../../src/vs/typings/thenable"
"../../../node_modules/@types/mocha"
],
"paths": {
"browser/*": [
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-search",
"version": "0.15.0",
"version": "0.16.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -20,8 +20,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
@@ -0,0 +1,158 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal, IDisposable, IDecoration } from '@xterm/xterm';
import type { ISearchDecorationOptions } from '@xterm/addon-search';
import { dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
import type { ISearchResult } from './SearchEngine';
/**
* Interface for managing a highlight decoration.
*/
interface IHighlight extends IDisposable {
decoration: IDecoration;
match: ISearchResult;
}
/**
* Interface for managing multiple decorations for a single match.
*/
interface IMultiHighlight extends IDisposable {
decorations: IDecoration[];
match: ISearchResult;
}
/**
* Manages visual decorations for search results including highlighting and active selection
* indicators. This class handles the creation, styling, and disposal of search-related decorations.
*/
export class DecorationManager extends Disposable {
private _highlightDecorations: IHighlight[] = [];
private _highlightedLines: Set<number> = new Set();
constructor(private readonly _terminal: Terminal) {
super();
this._register(toDisposable(() => this.clearHighlightDecorations()));
}
/**
* Creates decorations for all provided search results.
* @param results The search results to create decorations for.
* @param options The decoration options.
*/
public createHighlightDecorations(results: ISearchResult[], options: ISearchDecorationOptions): void {
this.clearHighlightDecorations();
for (const match of results) {
const decorations = this._createResultDecorations(match, options, false);
if (decorations) {
for (const decoration of decorations) {
this._storeDecoration(decoration, match);
}
}
}
}
/**
* Creates decorations for the currently active search result.
* @param result The active search result.
* @param options The decoration options.
* @returns The multi-highlight decoration or undefined if creation failed.
*/
public createActiveDecoration(result: ISearchResult, options: ISearchDecorationOptions): IMultiHighlight | undefined {
const decorations = this._createResultDecorations(result, options, true);
if (decorations) {
return { decorations, match: result, dispose() { dispose(decorations); } };
}
return undefined;
}
/**
* Clears all highlight decorations.
*/
public clearHighlightDecorations(): void {
dispose(this._highlightDecorations);
this._highlightDecorations = [];
this._highlightedLines.clear();
}
/**
* Stores a decoration and tracks it for management.
* @param decoration The decoration to store.
* @param match The search result this decoration represents.
*/
private _storeDecoration(decoration: IDecoration, match: ISearchResult): void {
this._highlightedLines.add(decoration.marker.line);
this._highlightDecorations.push({ decoration, match, dispose() { decoration.dispose(); } });
}
/**
* Applies styles to the decoration when it is rendered.
* @param element The decoration's element.
* @param borderColor The border color to apply.
* @param isActiveResult Whether the element is part of the active search result.
*/
private _applyStyles(element: HTMLElement, borderColor: string | undefined, isActiveResult: boolean): void {
if (!element.classList.contains('xterm-find-result-decoration')) {
element.classList.add('xterm-find-result-decoration');
if (borderColor) {
element.style.outline = `1px solid ${borderColor}`;
}
}
if (isActiveResult) {
element.classList.add('xterm-find-active-result-decoration');
}
}
/**
* Creates a decoration for the result and applies styles
* @param result the search result for which to create the decoration
* @param options the options for the decoration
* @param isActiveResult whether this is the currently active result
* @returns the decorations or undefined if the marker has already been disposed of
*/
private _createResultDecorations(result: ISearchResult, options: ISearchDecorationOptions, isActiveResult: boolean): IDecoration[] | undefined {
// Gather decoration ranges for this match as it could wrap
const decorationRanges: [number, number, number][] = [];
let currentCol = result.col;
let remainingSize = result.size;
let markerOffset = -this._terminal.buffer.active.baseY - this._terminal.buffer.active.cursorY + result.row;
while (remainingSize > 0) {
const amountThisRow = Math.min(this._terminal.cols - currentCol, remainingSize);
decorationRanges.push([markerOffset, currentCol, amountThisRow]);
currentCol = 0;
remainingSize -= amountThisRow;
markerOffset++;
}
// Create the decorations
const decorations: IDecoration[] = [];
for (const range of decorationRanges) {
const marker = this._terminal.registerMarker(range[0]);
const decoration = this._terminal.registerDecoration({
marker,
x: range[1],
width: range[2],
layer: isActiveResult ? 'top' : 'bottom',
backgroundColor: isActiveResult ? options.activeMatchBackground : options.matchBackground,
overviewRulerOptions: this._highlightedLines.has(marker.line) ? undefined : {
color: isActiveResult ? options.activeMatchColorOverviewRuler : options.matchOverviewRuler,
position: 'center'
}
});
if (decoration) {
const disposables: IDisposable[] = [];
disposables.push(marker);
disposables.push(decoration.onRender((e) => this._applyStyles(e, isActiveResult ? options.activeMatchBorder : options.matchBorder, false)));
disposables.push(decoration.onDispose(() => dispose(disposables)));
decorations.push(decoration);
}
}
return decorations.length === 0 ? undefined : decorations;
}
}
+125 -634
View File
@@ -3,129 +3,92 @@
* @license MIT
*/
import type { Terminal, IDisposable, ITerminalAddon, IDecoration } from '@xterm/xterm';
import type { SearchAddon as ISearchApi } from '@xterm/addon-search';
import { Emitter } from 'vs/base/common/event';
import { combinedDisposable, Disposable, dispose, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import type { Terminal, IDisposable, ITerminalAddon } from '@xterm/xterm';
import type { SearchAddon as ISearchApi, ISearchOptions, ISearchAddonOptions, ISearchResultChangeEvent } from '@xterm/addon-search';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { disposableTimeout } from 'vs/base/common/async';
import { SearchLineCache } from './SearchLineCache';
import { SearchState } from './SearchState';
import { SearchEngine, type ISearchResult } from './SearchEngine';
import { DecorationManager } from './DecorationManager';
import { SearchResultTracker } from './SearchResultTracker';
export interface ISearchOptions {
regex?: boolean;
wholeWord?: boolean;
caseSensitive?: boolean;
incremental?: boolean;
decorations?: ISearchDecorationOptions;
noScroll?: boolean;
interface IInternalSearchOptions {
noScroll: boolean;
}
interface ISearchDecorationOptions {
matchBackground?: string;
matchBorder?: string;
matchOverviewRuler: string;
activeMatchBackground?: string;
activeMatchBorder?: string;
activeMatchColorOverviewRuler: string;
}
export interface ISearchPosition {
startCol: number;
startRow: number;
}
export interface ISearchAddonOptions {
highlightLimit: number;
}
export interface ISearchResult {
term: string;
col: number;
row: number;
size: number;
}
type LineCacheEntry = [
/**
* Configuration constants for the search addon functionality.
*/
const enum Constants {
/**
* The string representation of a line (as opposed to the buffer cell representation).
* Default maximum number of search results to highlight simultaneously. This limit prevents
* performance degradation when searching for very common terms that would result in excessive
* highlighting decorations.
*/
lineAsString: string,
/**
* The offsets where each line starts when the entry describes a wrapped line.
*/
lineOffsets: number[]
];
interface IHighlight extends IDisposable {
decoration: IDecoration;
match: ISearchResult;
DEFAULT_HIGHLIGHT_LIMIT = 1000
}
interface IMultiHighlight extends IDisposable {
decorations: IDecoration[];
match: ISearchResult;
}
const NON_WORD_CHARACTERS = ' ~!@#$%^&*()+`-=[]{}|\\;:"\',./<>?';
const LINES_CACHE_TIME_TO_LIVE = 15 * 1000; // 15 secs
const DEFAULT_HIGHLIGHT_LIMIT = 1000;
export class SearchAddon extends Disposable implements ITerminalAddon , ISearchApi {
export class SearchAddon extends Disposable implements ITerminalAddon, ISearchApi {
private _terminal: Terminal | undefined;
private _cachedSearchTerm: string | undefined;
private _highlightedLines: Set<number> = new Set();
private _highlightDecorations: IHighlight[] = [];
private _selectedDecoration: MutableDisposable<IMultiHighlight> = this._register(new MutableDisposable());
private _highlightLimit: number;
private _lastSearchOptions: ISearchOptions | undefined;
private _highlightTimeout: number | undefined;
/**
* translateBufferLineToStringWithWrap is a fairly expensive call.
* We memoize the calls into an array that has a time based ttl.
* _linesCache is also invalidated when the terminal cursor moves.
*/
private _linesCache: LineCacheEntry[] | undefined;
private _linesCacheTimeoutId = 0;
private _linesCacheDisposables = new MutableDisposable();
private _highlightTimeout = this._register(new MutableDisposable<IDisposable>());
private _lineCache = this._register(new MutableDisposable<SearchLineCache>());
private readonly _onDidChangeResults = this._register(new Emitter<{ resultIndex: number, resultCount: number }>());
public readonly onDidChangeResults = this._onDidChangeResults.event;
// Component instances
private _state = new SearchState();
private _engine: SearchEngine | undefined;
private _decorationManager: DecorationManager | undefined;
private _resultTracker = this._register(new SearchResultTracker());
private readonly _onAfterSearch = this._register(new Emitter<void>());
public readonly onAfterSearch = this._onAfterSearch.event;
private readonly _onBeforeSearch = this._register(new Emitter<void>());
public readonly onBeforeSearch = this._onBeforeSearch.event;
public get onDidChangeResults(): Event<ISearchResultChangeEvent> {
return this._resultTracker.onDidChangeResults;
}
constructor(options?: Partial<ISearchAddonOptions>) {
super();
this._highlightLimit = options?.highlightLimit ?? DEFAULT_HIGHLIGHT_LIMIT;
this._highlightLimit = options?.highlightLimit ?? Constants.DEFAULT_HIGHLIGHT_LIMIT;
}
public activate(terminal: Terminal): void {
this._terminal = terminal;
this._lineCache.value = new SearchLineCache(terminal);
this._engine = new SearchEngine(terminal, this._lineCache.value);
this._decorationManager = new DecorationManager(terminal);
this._register(this._terminal.onWriteParsed(() => this._updateMatches()));
this._register(this._terminal.onResize(() => this._updateMatches()));
this._register(toDisposable(() => this.clearDecorations()));
}
private _updateMatches(): void {
if (this._highlightTimeout) {
window.clearTimeout(this._highlightTimeout);
}
if (this._cachedSearchTerm && this._lastSearchOptions?.decorations) {
this._highlightTimeout = setTimeout(() => {
const term = this._cachedSearchTerm;
this._cachedSearchTerm = undefined;
this.findPrevious(term!, { ...this._lastSearchOptions, incremental: true, noScroll: true });
this._highlightTimeout.clear();
if (this._state.cachedSearchTerm && this._state.lastSearchOptions?.decorations) {
this._highlightTimeout.value = disposableTimeout(() => {
const term = this._state.cachedSearchTerm;
this._state.clearCachedTerm();
this.findPrevious(term!, { ...this._state.lastSearchOptions, incremental: true }, { noScroll: true });
}, 200);
}
}
public clearDecorations(retainCachedSearchTerm?: boolean): void {
this._selectedDecoration.clear();
dispose(this._highlightDecorations);
this._highlightDecorations = [];
this._highlightedLines.clear();
this._resultTracker.clearSelectedDecoration();
this._decorationManager?.clearHighlightDecorations();
this._resultTracker.clearResults();
if (!retainCachedSearchTerm) {
this._cachedSearchTerm = undefined;
this._state.clearCachedTerm();
}
}
public clearActiveDecoration(): void {
this._selectedDecoration.clear();
this._resultTracker.clearSelectedDecoration();
}
/**
@@ -135,174 +98,78 @@ export class SearchAddon extends Disposable implements ITerminalAddon , ISearchA
* @param searchOptions Search options.
* @returns Whether a result was found.
*/
public findNext(term: string, searchOptions?: ISearchOptions): boolean {
if (!this._terminal) {
public findNext(term: string, searchOptions?: ISearchOptions, internalSearchOptions?: IInternalSearchOptions): boolean {
if (!this._terminal || !this._engine) {
throw new Error('Cannot use addon until it has been loaded');
}
const didOptionsChanged = this._lastSearchOptions ? this._didOptionsChange(this._lastSearchOptions, searchOptions) : true;
this._lastSearchOptions = searchOptions;
if (searchOptions?.decorations) {
if (this._cachedSearchTerm === undefined || term !== this._cachedSearchTerm || didOptionsChanged) {
this._highlightAllMatches(term, searchOptions);
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
this._highlightAllMatches(term, searchOptions!);
}
const found = this._findNextAndSelect(term, searchOptions);
const found = this._findNextAndSelect(term, searchOptions, internalSearchOptions);
this._fireResults(searchOptions);
this._cachedSearchTerm = term;
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
private _highlightAllMatches(term: string, searchOptions: ISearchOptions): void {
if (!this._terminal) {
if (!this._terminal || !this._engine || !this._decorationManager) {
throw new Error('Cannot use addon until it has been loaded');
}
if (!term || term.length === 0) {
if (!this._state.isValidSearchTerm(term)) {
this.clearDecorations();
return;
}
searchOptions = searchOptions || {};
// new search, clear out the old decorations
this.clearDecorations(true);
const searchResultsWithHighlight: ISearchResult[] = [];
const results: ISearchResult[] = [];
let prevResult: ISearchResult | undefined = undefined;
let result = this._find(term, 0, 0, searchOptions);
let result = this._engine.find(term, 0, 0, searchOptions);
while (result && (prevResult?.row !== result.row || prevResult?.col !== result.col)) {
if (searchResultsWithHighlight.length >= this._highlightLimit) {
if (results.length >= this._highlightLimit) {
break;
}
prevResult = result;
searchResultsWithHighlight.push(prevResult);
result = this._find(
results.push(prevResult);
result = this._engine.find(
term,
prevResult.col + prevResult.term.length >= this._terminal.cols ? prevResult.row + 1 : prevResult.row,
prevResult.col + prevResult.term.length >= this._terminal.cols ? 0 : prevResult.col + 1,
searchOptions
);
}
for (const match of searchResultsWithHighlight) {
const decorations = this._createResultDecorations(match, searchOptions.decorations!, false);
if (decorations) {
for (const decoration of decorations) {
this._storeDecoration(decoration, match);
}
}
this._resultTracker.updateResults(results, this._highlightLimit);
if (searchOptions.decorations) {
this._decorationManager.createHighlightDecorations(results, searchOptions.decorations);
}
}
private _storeDecoration(decoration: IDecoration, match: ISearchResult): void {
this._highlightedLines.add(decoration.marker.line);
this._highlightDecorations.push({ decoration, match, dispose() { decoration.dispose(); } });
}
private _find(term: string, startRow: number, startCol: number, searchOptions?: ISearchOptions): ISearchResult | undefined {
if (!this._terminal || !term || term.length === 0) {
this._terminal?.clearSelection();
this.clearDecorations();
return undefined;
private _findNextAndSelect(term: string, searchOptions?: ISearchOptions, internalSearchOptions?: IInternalSearchOptions): boolean {
if (!this._terminal || !this._engine) {
return false;
}
if (startCol > this._terminal.cols) {
throw new Error(`Invalid col: ${startCol} to search in terminal of ${this._terminal.cols} cols`);
}
let result: ISearchResult | undefined = undefined;
this._initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
// Search startRow
result = this._findInLine(term, searchPosition, searchOptions);
// Search from startRow + 1 to end
if (!result) {
for (let y = startRow + 1; y < this._terminal.buffer.active.baseY + this._terminal.rows; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
// If the current line is wrapped line, increase index of column to ignore the previous scan
// Otherwise, reset beginning column index to zero with set new unwrapped line index
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
return result;
}
private _findNextAndSelect(term: string, searchOptions?: ISearchOptions): boolean {
if (!this._terminal || !term || term.length === 0) {
this._terminal?.clearSelection();
if (!this._state.isValidSearchTerm(term)) {
this._terminal.clearSelection();
this.clearDecorations();
return false;
}
const prevSelectedPos = this._terminal.getSelectionPosition();
this._terminal.clearSelection();
let startCol = 0;
let startRow = 0;
if (prevSelectedPos) {
if (this._cachedSearchTerm === term) {
startCol = prevSelectedPos.end.x;
startRow = prevSelectedPos.end.y;
} else {
startCol = prevSelectedPos.start.x;
startRow = prevSelectedPos.start.y;
}
}
this._initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
// Search startRow
let result = this._findInLine(term, searchPosition, searchOptions);
// Search from startRow + 1 to end
if (!result) {
for (let y = startRow + 1; y < this._terminal.buffer.active.baseY + this._terminal.rows; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
// If the current line is wrapped line, increase index of column to ignore the previous scan
// Otherwise, reset beginning column index to zero with set new unwrapped line index
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
// If we hit the bottom and didn't search from the very top wrap back up
if (!result && startRow !== 0) {
for (let y = 0; y < startRow; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
// If there is only one result, wrap back and return selection if it exists.
if (!result && prevSelectedPos) {
searchPosition.startRow = prevSelectedPos.start.y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
}
// Set selection and scroll if a result was found
return this._selectResult(result, searchOptions?.decorations, searchOptions?.noScroll);
const result = this._engine.findNextWithSelection(term, searchOptions, this._state.cachedSearchTerm);
return this._selectResult(result, searchOptions?.decorations, internalSearchOptions?.noScroll);
}
/**
* Find the previous instance of the term, then scroll to and select it. If it
* doesn't exist, do nothing.
@@ -310,357 +177,44 @@ export class SearchAddon extends Disposable implements ITerminalAddon , ISearchA
* @param searchOptions Search options.
* @returns Whether a result was found.
*/
public findPrevious(term: string, searchOptions?: ISearchOptions): boolean {
if (!this._terminal) {
public findPrevious(term: string, searchOptions?: ISearchOptions, internalSearchOptions?: IInternalSearchOptions): boolean {
if (!this._terminal || !this._engine) {
throw new Error('Cannot use addon until it has been loaded');
}
const didOptionsChanged = this._lastSearchOptions ? this._didOptionsChange(this._lastSearchOptions, searchOptions) : true;
this._lastSearchOptions = searchOptions;
if (searchOptions?.decorations) {
if (this._cachedSearchTerm === undefined || term !== this._cachedSearchTerm || didOptionsChanged) {
this._highlightAllMatches(term, searchOptions);
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
this._highlightAllMatches(term, searchOptions!);
}
const found = this._findPreviousAndSelect(term, searchOptions);
const found = this._findPreviousAndSelect(term, searchOptions, internalSearchOptions);
this._fireResults(searchOptions);
this._cachedSearchTerm = term;
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
private _didOptionsChange(lastSearchOptions: ISearchOptions, searchOptions?: ISearchOptions): boolean {
if (!searchOptions) {
private _fireResults(searchOptions?: ISearchOptions): void {
this._resultTracker.fireResultsChanged(!!searchOptions?.decorations);
}
private _findPreviousAndSelect(term: string, searchOptions?: ISearchOptions, internalSearchOptions?: IInternalSearchOptions): boolean {
if (!this._terminal || !this._engine) {
return false;
}
if (lastSearchOptions.caseSensitive !== searchOptions.caseSensitive) {
return true;
}
if (lastSearchOptions.regex !== searchOptions.regex) {
return true;
}
if (lastSearchOptions.wholeWord !== searchOptions.wholeWord) {
return true;
}
return false;
}
private _fireResults(searchOptions?: ISearchOptions): void {
if (searchOptions?.decorations) {
let resultIndex = -1;
if (this._selectedDecoration.value) {
const selectedMatch = this._selectedDecoration.value.match;
for (let i = 0; i < this._highlightDecorations.length; i++) {
const match = this._highlightDecorations[i].match;
if (match.row === selectedMatch.row && match.col === selectedMatch.col && match.size === selectedMatch.size) {
resultIndex = i;
break;
}
}
}
this._onDidChangeResults.fire({ resultIndex, resultCount: this._highlightDecorations.length });
}
}
private _findPreviousAndSelect(term: string, searchOptions?: ISearchOptions): boolean {
if (!this._terminal) {
throw new Error('Cannot use addon until it has been loaded');
}
if (!this._terminal || !term || term.length === 0) {
this._terminal?.clearSelection();
if (!this._state.isValidSearchTerm(term)) {
this._terminal.clearSelection();
this.clearDecorations();
return false;
}
const prevSelectedPos = this._terminal.getSelectionPosition();
this._terminal.clearSelection();
let startRow = this._terminal.buffer.active.baseY + this._terminal.rows - 1;
let startCol = this._terminal.cols;
const isReverseSearch = true;
this._initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
let result: ISearchResult | undefined;
if (prevSelectedPos) {
searchPosition.startRow = startRow = prevSelectedPos.start.y;
searchPosition.startCol = startCol = prevSelectedPos.start.x;
if (this._cachedSearchTerm !== term) {
// Try to expand selection to right first.
result = this._findInLine(term, searchPosition, searchOptions, false);
if (!result) {
// If selection was not able to be expanded to the right, then try reverse search
searchPosition.startRow = startRow = prevSelectedPos.end.y;
searchPosition.startCol = startCol = prevSelectedPos.end.x;
}
}
}
if (!result) {
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
}
// Search from startRow - 1 to top
if (!result) {
searchPosition.startCol = Math.max(searchPosition.startCol, this._terminal.cols);
for (let y = startRow - 1; y >= 0; y--) {
searchPosition.startRow = y;
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
if (result) {
break;
}
}
}
// If we hit the top and didn't search from the very bottom wrap back down
if (!result && startRow !== (this._terminal.buffer.active.baseY + this._terminal.rows - 1)) {
for (let y = (this._terminal.buffer.active.baseY + this._terminal.rows - 1); y >= startRow; y--) {
searchPosition.startRow = y;
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
if (result) {
break;
}
}
}
// Set selection and scroll if a result was found
return this._selectResult(result, searchOptions?.decorations, searchOptions?.noScroll);
}
/**
* Sets up a line cache with a ttl
*/
private _initLinesCache(): void {
const terminal = this._terminal!;
if (!this._linesCache) {
this._linesCache = new Array(terminal.buffer.active.length);
this._linesCacheDisposables.value = combinedDisposable(
terminal.onLineFeed(() => this._destroyLinesCache()),
terminal.onCursorMove(() => this._destroyLinesCache()),
terminal.onResize(() => this._destroyLinesCache())
);
}
window.clearTimeout(this._linesCacheTimeoutId);
this._linesCacheTimeoutId = window.setTimeout(() => this._destroyLinesCache(), LINES_CACHE_TIME_TO_LIVE);
}
private _destroyLinesCache(): void {
this._linesCache = undefined;
this._linesCacheDisposables.clear();
if (this._linesCacheTimeoutId) {
window.clearTimeout(this._linesCacheTimeoutId);
this._linesCacheTimeoutId = 0;
}
}
/**
* A found substring is a whole word if it doesn't have an alphanumeric character directly
* adjacent to it.
* @param searchIndex starting indext of the potential whole word substring
* @param line entire string in which the potential whole word was found
* @param term the substring that starts at searchIndex
*/
private _isWholeWord(searchIndex: number, line: string, term: string): boolean {
return ((searchIndex === 0) || (NON_WORD_CHARACTERS.includes(line[searchIndex - 1]))) &&
(((searchIndex + term.length) === line.length) || (NON_WORD_CHARACTERS.includes(line[searchIndex + term.length])));
}
/**
* Searches a line for a search term. Takes the provided terminal line and searches the text line,
* which may contain subsequent terminal lines if the text is wrapped. If the provided line number
* is part of a wrapped text line that started on an earlier line then it is skipped since it will
* be properly searched when the terminal line that the text starts on is searched.
* @param term The search term.
* @param searchPosition The position to start the search.
* @param searchOptions Search options.
* @param isReverseSearch Whether the search should start from the right side of the terminal and
* search to the left.
* @returns The search result if it was found.
*/
protected _findInLine(term: string, searchPosition: ISearchPosition, searchOptions: ISearchOptions = {}, isReverseSearch: boolean = false): ISearchResult | undefined {
const terminal = this._terminal!;
const row = searchPosition.startRow;
const col = searchPosition.startCol;
// Ignore wrapped lines, only consider on unwrapped line (first row of command string).
const firstLine = terminal.buffer.active.getLine(row);
if (firstLine?.isWrapped) {
if (isReverseSearch) {
searchPosition.startCol += terminal.cols;
return;
}
// This will iterate until we find the line start.
// When we find it, we will search using the calculated start column.
searchPosition.startRow--;
searchPosition.startCol += terminal.cols;
return this._findInLine(term, searchPosition, searchOptions);
}
let cache = this._linesCache?.[row];
if (!cache) {
cache = this._translateBufferLineToStringWithWrap(row, true);
if (this._linesCache) {
this._linesCache[row] = cache;
}
}
const [stringLine, offsets] = cache;
const offset = this._bufferColsToStringOffset(row, col);
let searchTerm = term;
let searchStringLine = stringLine;
if (!searchOptions.regex) {
searchTerm = searchOptions.caseSensitive ? term : term.toLowerCase();
searchStringLine = searchOptions.caseSensitive ? stringLine : stringLine.toLowerCase();
}
let resultIndex = -1;
if (searchOptions.regex) {
const searchRegex = RegExp(searchTerm, searchOptions.caseSensitive ? 'g' : 'gi');
let foundTerm: RegExpExecArray | null;
if (isReverseSearch) {
// This loop will get the resultIndex of the _last_ regex match in the range 0..offset
while (foundTerm = searchRegex.exec(searchStringLine.slice(0, offset))) {
resultIndex = searchRegex.lastIndex - foundTerm[0].length;
term = foundTerm[0];
searchRegex.lastIndex -= (term.length - 1);
}
} else {
foundTerm = searchRegex.exec(searchStringLine.slice(offset));
if (foundTerm && foundTerm[0].length > 0) {
resultIndex = offset + (searchRegex.lastIndex - foundTerm[0].length);
term = foundTerm[0];
}
}
} else {
if (isReverseSearch) {
if (offset - searchTerm.length >= 0) {
resultIndex = searchStringLine.lastIndexOf(searchTerm, offset - searchTerm.length);
}
} else {
resultIndex = searchStringLine.indexOf(searchTerm, offset);
}
}
if (resultIndex >= 0) {
if (searchOptions.wholeWord && !this._isWholeWord(resultIndex, searchStringLine, term)) {
return;
}
// Adjust the row number and search index if needed since a "line" of text can span multiple
// rows
let startRowOffset = 0;
while (startRowOffset < offsets.length - 1 && resultIndex >= offsets[startRowOffset + 1]) {
startRowOffset++;
}
let endRowOffset = startRowOffset;
while (endRowOffset < offsets.length - 1 && resultIndex + term.length >= offsets[endRowOffset + 1]) {
endRowOffset++;
}
const startColOffset = resultIndex - offsets[startRowOffset];
const endColOffset = resultIndex + term.length - offsets[endRowOffset];
const startColIndex = this._stringLengthToBufferSize(row + startRowOffset, startColOffset);
const endColIndex = this._stringLengthToBufferSize(row + endRowOffset, endColOffset);
const size = endColIndex - startColIndex + terminal.cols * (endRowOffset - startRowOffset);
return {
term,
col: startColIndex,
row: row + startRowOffset,
size
};
}
}
private _stringLengthToBufferSize(row: number, offset: number): number {
const line = this._terminal!.buffer.active.getLine(row);
if (!line) {
return 0;
}
for (let i = 0; i < offset; i++) {
const cell = line.getCell(i);
if (!cell) {
break;
}
// Adjust the searchIndex to normalize emoji into single chars
const char = cell.getChars();
if (char.length > 1) {
offset -= char.length - 1;
}
// Adjust the searchIndex for empty characters following wide unicode
// chars (eg. CJK)
const nextCell = line.getCell(i + 1);
if (nextCell && nextCell.getWidth() === 0) {
offset++;
}
}
return offset;
}
private _bufferColsToStringOffset(startRow: number, cols: number): number {
const terminal = this._terminal!;
let lineIndex = startRow;
let offset = 0;
let line = terminal.buffer.active.getLine(lineIndex);
while (cols > 0 && line) {
for (let i = 0; i < cols && i < terminal.cols; i++) {
const cell = line.getCell(i);
if (!cell) {
break;
}
if (cell.getWidth()) {
// Treat null characters as whitespace to align with the translateToString API
offset += cell.getCode() === 0 ? 1 : cell.getChars().length;
}
}
lineIndex++;
line = terminal.buffer.active.getLine(lineIndex);
if (line && !line.isWrapped) {
break;
}
cols -= terminal.cols;
}
return offset;
}
/**
* Translates a buffer line to a string, including subsequent lines if they are wraps.
* Wide characters will count as two columns in the resulting string. This
* function is useful for getting the actual text underneath the raw selection
* position.
* @param lineIndex The index of the line being translated.
* @param trimRight Whether to trim whitespace to the right.
*/
private _translateBufferLineToStringWithWrap(lineIndex: number, trimRight: boolean): LineCacheEntry {
const terminal = this._terminal!;
const strings = [];
const lineOffsets = [0];
let line = terminal.buffer.active.getLine(lineIndex);
while (line) {
const nextLine = terminal.buffer.active.getLine(lineIndex + 1);
const lineWrapsToNext = nextLine ? nextLine.isWrapped : false;
let string = line.translateToString(!lineWrapsToNext && trimRight);
if (lineWrapsToNext && nextLine) {
const lastCell = line.getCell(line.length - 1);
const lastCellIsNull = lastCell && lastCell.getCode() === 0 && lastCell.getWidth() === 1;
// a wide character wrapped to the next line
if (lastCellIsNull && nextLine.getCell(0)?.getWidth() === 2) {
string = string.slice(0, -1);
}
}
strings.push(string);
if (lineWrapsToNext) {
lineOffsets.push(lineOffsets[lineOffsets.length - 1] + string.length);
} else {
break;
}
lineIndex++;
line = nextLine;
}
return [strings.join(''), lineOffsets];
const result = this._engine.findPreviousWithSelection(term, searchOptions, this._state.cachedSearchTerm);
return this._selectResult(result, searchOptions?.decorations, internalSearchOptions?.noScroll);
}
/**
@@ -668,96 +222,33 @@ export class SearchAddon extends Disposable implements ITerminalAddon , ISearchA
* @param result The result to select.
* @returns Whether a result was selected.
*/
private _selectResult(result: ISearchResult | undefined, options?: ISearchDecorationOptions, noScroll?: boolean): boolean {
const terminal = this._terminal!;
this._selectedDecoration.clear();
if (!result) {
terminal.clearSelection();
private _selectResult(result: ISearchResult | undefined, options?: any, noScroll?: boolean): boolean {
if (!this._terminal || !this._decorationManager) {
return false;
}
terminal.select(result.col, result.row, result.size);
this._resultTracker.clearSelectedDecoration();
if (!result) {
this._terminal.clearSelection();
return false;
}
this._terminal.select(result.col, result.row, result.size);
if (options) {
const decorations = this._createResultDecorations(result, options, true);
if (decorations) {
this._selectedDecoration.value = { decorations, match: result, dispose() { dispose(decorations); } };
const activeDecoration = this._decorationManager.createActiveDecoration(result, options);
if (activeDecoration) {
this._resultTracker.selectedDecoration = activeDecoration;
}
}
if (!noScroll) {
// If it is not in the viewport then we scroll else it just gets selected
if (result.row >= (terminal.buffer.active.viewportY + terminal.rows) || result.row < terminal.buffer.active.viewportY) {
let scroll = result.row - terminal.buffer.active.viewportY;
scroll -= Math.floor(terminal.rows / 2);
terminal.scrollLines(scroll);
if (result.row >= (this._terminal.buffer.active.viewportY + this._terminal.rows) || result.row < this._terminal.buffer.active.viewportY) {
let scroll = result.row - this._terminal.buffer.active.viewportY;
scroll -= Math.floor(this._terminal.rows / 2);
this._terminal.scrollLines(scroll);
}
}
return true;
}
/**
* Applies styles to the decoration when it is rendered.
* @param element The decoration's element.
* @param borderColor The border color to apply.
* @param isActiveResult Whether the element is part of the active search result.
* @returns
*/
private _applyStyles(element: HTMLElement, borderColor: string | undefined, isActiveResult: boolean): void {
if (!element.classList.contains('xterm-find-result-decoration')) {
element.classList.add('xterm-find-result-decoration');
if (borderColor) {
element.style.outline = `1px solid ${borderColor}`;
}
}
if (isActiveResult) {
element.classList.add('xterm-find-active-result-decoration');
}
}
/**
* Creates a decoration for the result and applies styles
* @param result the search result for which to create the decoration
* @param options the options for the decoration
* @returns the {@link IDecoration} or undefined if the marker has already been disposed of
*/
private _createResultDecorations(result: ISearchResult, options: ISearchDecorationOptions, isActiveResult: boolean): IDecoration[] | undefined {
const terminal = this._terminal!;
// Gather decoration ranges for this match as it could wrap
const decorationRanges: [number, number, number][] = [];
let currentCol = result.col;
let remainingSize = result.size;
let markerOffset = -terminal.buffer.active.baseY - terminal.buffer.active.cursorY + result.row;
while (remainingSize > 0) {
const amountThisRow = Math.min(terminal.cols - currentCol, remainingSize);
decorationRanges.push([markerOffset, currentCol, amountThisRow]);
currentCol = 0;
remainingSize -= amountThisRow;
markerOffset++;
}
// Create the decorations
const decorations: IDecoration[] = [];
for (const range of decorationRanges) {
const marker = terminal.registerMarker(range[0]);
const decoration = terminal.registerDecoration({
marker,
x: range[1],
width: range[2],
backgroundColor: isActiveResult ? options.activeMatchBackground : options.matchBackground,
overviewRulerOptions: this._highlightedLines.has(marker.line) ? undefined : {
color: isActiveResult ? options.activeMatchColorOverviewRuler : options.matchOverviewRuler,
position: 'center'
}
});
if (decoration) {
const disposables: IDisposable[] = [];
disposables.push(marker);
disposables.push(decoration.onRender((e) => this._applyStyles(e, isActiveResult ? options.activeMatchBorder : options.matchBorder, false)));
disposables.push(decoration.onDispose(() => dispose(disposables)));
decorations.push(decoration);
}
}
return decorations.length === 0 ? undefined : decorations;
}
}
@@ -0,0 +1,708 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import { SearchEngine } from './SearchEngine';
import { SearchLineCache } from './SearchLineCache';
import { Terminal } from 'browser/public/Terminal';
import type { ISearchOptions } from '@xterm/addon-search';
import { DisposableStore } from 'vs/base/common/lifecycle';
function writeP(terminal: Terminal, data: string): Promise<void> {
return new Promise(r => terminal.write(data, r));
}
describe('SearchEngine', () => {
let store: DisposableStore;
let terminal: Terminal;
let lineCache: SearchLineCache;
let searchEngine: SearchEngine;
beforeEach(() => {
store = new DisposableStore();
terminal = store.add(new Terminal({ cols: 80, rows: 24 }));
lineCache = store.add(new SearchLineCache(terminal));
searchEngine = new SearchEngine(terminal, lineCache);
});
afterEach(() => {
store.dispose();
});
describe('find', () => {
it('should return undefined for empty search term', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.find('', 0, 0), undefined);
});
it('should find basic text in terminal content', async () => {
await writeP(terminal, 'Hello World');
assert.deepStrictEqual(searchEngine.find('World', 0, 0), {
term: 'World',
col: 6,
row: 0,
size: 5
});
});
it('should find text starting from specified position', async () => {
await writeP(terminal, 'Hello Hello Hello');
assert.deepStrictEqual(searchEngine.find('Hello', 0, 7), {
term: 'Hello',
col: 12,
row: 0,
size: 5
});
});
it('should search across multiple rows', async () => {
await writeP(terminal, 'Line 1\r\nLine 2 target\r\nLine 3');
assert.deepStrictEqual(searchEngine.find('target', 0, 0), {
term: 'target',
col: 7,
row: 1,
size: 6
});
});
it('should return undefined when text is not found', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.find('NotFound', 0, 0), undefined);
});
it('should throw error for invalid column position', async () => {
await writeP(terminal, 'Hello World');
assert.throws(() => {
searchEngine.find('Hello', 0, 100);
}, /Invalid col: 100 to search in terminal of 80 cols/);
});
it('should handle search starting from last column', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.find('Hello', 0, 79), undefined);
});
it('should handle search from middle of match', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.find('llo', 0, 3), undefined); // Should not find partial match that starts before search position
});
});
describe('search options', () => {
describe('caseSensitive', () => {
it('should find text with case-insensitive search (default)', async () => {
await writeP(terminal, 'Hello WORLD');
assert.deepStrictEqual(searchEngine.find('world', 0, 0), {
term: 'world',
col: 6,
row: 0,
size: 5
});
});
it('should find text with case-sensitive search when enabled', async () => {
await writeP(terminal, 'Hello WORLD');
assert.deepStrictEqual(searchEngine.find('WORLD', 0, 0, { caseSensitive: true }), {
term: 'WORLD',
col: 6,
row: 0,
size: 5
});
});
it('should not find text with case-sensitive search when case differs', async () => {
await writeP(terminal, 'Hello WORLD');
assert.strictEqual(searchEngine.find('world', 0, 0, { caseSensitive: true }), undefined);
});
});
describe('wholeWord', () => {
it('should find whole word when enabled', async () => {
await writeP(terminal, 'Hello world wonderful');
assert.deepStrictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), {
term: 'world',
col: 6,
row: 0,
size: 5
});
});
it('should not find partial word when wholeWord is enabled', async () => {
await writeP(terminal, 'Hello wonderful');
assert.strictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), undefined);
});
it('should find word at beginning of line with wholeWord', async () => {
await writeP(terminal, 'world is great');
assert.deepStrictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), {
term: 'world',
col: 0,
row: 0,
size: 5
});
});
it('should find word at end of line with wholeWord', async () => {
await writeP(terminal, 'hello world');
assert.deepStrictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), {
term: 'world',
col: 6,
row: 0,
size: 5
});
});
it('should handle word boundaries with punctuation', async () => {
await writeP(terminal, 'hello,world!test');
assert.deepStrictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), {
term: 'world',
col: 6,
row: 0,
size: 5
});
});
it('should not match when not whole word', async () => {
await writeP(terminal, 'helloworld');
assert.strictEqual(searchEngine.find('world', 0, 0, { wholeWord: true }), undefined);
});
});
describe('regex', () => {
it('should find text using simple regex pattern', async () => {
await writeP(terminal, 'Hello 123 World');
assert.deepStrictEqual(searchEngine.find('[0-9]+', 0, 0, { regex: true }), {
term: '123',
col: 6,
row: 0,
size: 3
});
});
it('should find text using regex with case-insensitive flag', async () => {
await writeP(terminal, 'Hello WORLD');
assert.deepStrictEqual(searchEngine.find('world', 0, 0, { regex: true, caseSensitive: false }), {
term: 'WORLD',
col: 6,
row: 0,
size: 5
});
});
it('should find text using regex with case-sensitive flag', async () => {
await writeP(terminal, 'Hello WORLD world');
assert.deepStrictEqual(searchEngine.find('WORLD', 0, 0, { regex: true, caseSensitive: true }), {
term: 'WORLD',
col: 6,
row: 0,
size: 5
});
});
it('should handle complex regex patterns', async () => {
await writeP(terminal, 'Email: test@example.com and another@domain.org');
assert.deepStrictEqual(searchEngine.find('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}', 0, 0, { regex: true }), {
term: 'test@example.com',
col: 7,
row: 0,
size: 16
});
});
it('should return undefined for invalid regex pattern', async () => {
await writeP(terminal, 'Hello World');
// Invalid regex should be handled gracefully
assert.throws(() => {
searchEngine.find('[invalid', 0, 0, { regex: true });
}, /Invalid regular expression/);
});
it('should handle empty regex matches', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.find('.*?', 0, 0, { regex: true }), undefined); // Empty matches should be ignored
});
});
describe('combined options', () => {
it('should handle regex + caseSensitive combination', async () => {
await writeP(terminal, 'Hello WORLD world');
assert.deepStrictEqual(searchEngine.find('[A-Z]+', 0, 0, { regex: true, caseSensitive: true }), {
term: 'H',
col: 0,
row: 0,
size: 1
});
});
it('should handle wholeWord + caseSensitive combination', async () => {
await writeP(terminal, 'Hello WORLD wonderful');
const result1 = searchEngine.find('WORLD', 0, 0, { wholeWord: true, caseSensitive: true });
assert.deepStrictEqual(result1, {
term: 'WORLD',
col: 6,
row: 0,
size: 5
});
const result2 = searchEngine.find('world', 0, 0, { wholeWord: true, caseSensitive: true });
assert.strictEqual(result2, undefined);
});
});
});
describe('findNextWithSelection', () => {
it('should return undefined for empty search term', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.findNextWithSelection(''), undefined);
});
it('should find first occurrence when no selection exists', async () => {
await writeP(terminal, 'Hello World Hello');
assert.deepStrictEqual(searchEngine.findNextWithSelection('Hello'), {
term: 'Hello',
col: 0,
row: 0,
size: 5
});
});
it('should find next occurrence after current selection', async () => {
await writeP(terminal, 'Hello World Hello Again');
// Mock the getSelectionPosition to return a selection at first "Hello"
terminal.getSelectionPosition = () => ({ start: { x: 0, y: 0 }, end: { x: 5, y: 0 } });
assert.deepStrictEqual(searchEngine.findNextWithSelection('Hello', undefined, 'Hello'), {
term: 'Hello',
col: 12,
row: 0,
size: 5
});
});
it('should wrap around to beginning when reaching end', async () => {
await writeP(terminal, 'Hello World Hello');
// Mock selection at the end
terminal.getSelectionPosition = () => ({ start: { x: 12, y: 0 }, end: { x: 17, y: 0 } });
assert.deepStrictEqual(searchEngine.findNextWithSelection('Hello', undefined, 'Hello'), {
term: 'Hello',
col: 0,
row: 0,
size: 5
}); // Should wrap to first occurrence
});
it('should wrap across multiple rows', async () => {
await writeP(terminal, 'Line 1 test\r\nLine 2\r\nLine 3 test');
// Mock selection at first "test"
terminal.getSelectionPosition = () => ({ start: { x: 7, y: 0 }, end: { x: 11, y: 0 } });
assert.deepStrictEqual(searchEngine.findNextWithSelection('test', undefined, 'test'), {
term: 'test',
col: 7,
row: 2,
size: 4
});
});
it('should return same selection if only one match exists', async () => {
await writeP(terminal, 'Hello World');
// Mock selection at "Hello"
terminal.getSelectionPosition = () => ({ start: { x: 0, y: 0 }, end: { x: 5, y: 0 } });
assert.deepStrictEqual(searchEngine.findNextWithSelection('Hello'), {
term: 'Hello',
col: 0,
row: 0,
size: 5
});
});
it('should clear selection and return undefined when term not found', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.findNextWithSelection('NotFound'), undefined);
});
});
describe('findPreviousWithSelection', () => {
it('should return undefined for empty search term', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.findPreviousWithSelection(''), undefined);
});
it('should find last occurrence when no selection exists', async () => {
await writeP(terminal, 'Hello World Hello');
assert.deepStrictEqual(searchEngine.findPreviousWithSelection('Hello'), {
term: 'Hello',
col: 12,
row: 0,
size: 5
});
});
it('should find previous occurrence before current selection', async () => {
await writeP(terminal, 'Hello World Hello Again');
// Mock selection at second "Hello"
terminal.getSelectionPosition = () => ({ start: { x: 12, y: 0 }, end: { x: 17, y: 0 } });
const result = searchEngine.findPreviousWithSelection('Hello');
assert.notStrictEqual(result, undefined);
// It may find the same selection first due to expansion attempt
assert.strictEqual(typeof result!.col, 'number');
assert.strictEqual(result!.row, 0);
});
it('should wrap around to end when reaching beginning', async () => {
await writeP(terminal, 'Hello World Hello');
// Mock selection at first "Hello"
terminal.getSelectionPosition = () => ({ start: { x: 0, y: 0 }, end: { x: 5, y: 0 } });
const result = searchEngine.findPreviousWithSelection('Hello');
assert.notStrictEqual(result, undefined);
// Due to the expansion attempt, it may find the same Hello first
assert.strictEqual(typeof result!.col, 'number');
assert.strictEqual(result!.row, 0);
});
it('should work across multiple rows in reverse', async () => {
await writeP(terminal, 'test Line 1\r\nLine 2\r\ntest Line 3');
// Mock selection at last "test"
terminal.getSelectionPosition = () => ({ start: { x: 0, y: 2 }, end: { x: 4, y: 2 } });
const result = searchEngine.findPreviousWithSelection('test');
assert.notStrictEqual(result, undefined);
// The algorithm will find the current selection first due to expansion attempt
assert.strictEqual(typeof result!.row, 'number');
assert.strictEqual(typeof result!.col, 'number');
});
it('should handle selection expansion correctly', async () => {
await writeP(terminal, 'Hello World Hello');
// Mock selection at first "Hello"
terminal.getSelectionPosition = () => ({ start: { x: 0, y: 0 }, end: { x: 5, y: 0 } });
const result = searchEngine.findPreviousWithSelection('Hello');
assert.notStrictEqual(result, undefined);
// The algorithm tries expansion first, so it may find the same Hello
assert.strictEqual(typeof result!.col, 'number');
assert.strictEqual(result!.row, 0);
});
it('should clear selection and return undefined when term not found', async () => {
await writeP(terminal, 'Hello World');
assert.strictEqual(searchEngine.findPreviousWithSelection('NotFound'), undefined);
});
});
describe('edge cases and error handling', () => {
describe('unicode and special characters', () => {
it('should handle unicode characters correctly', async () => {
await writeP(terminal, 'Hello 世界 World');
assert.deepStrictEqual(searchEngine.find('世界', 0, 0), {
term: '世界',
col: 6,
row: 0,
size: 4
});
});
it('should handle wide characters', async () => {
await writeP(terminal, '中文测试');
assert.deepStrictEqual(searchEngine.find('测试', 0, 0), {
term: '测试',
col: 4,
row: 0,
size: 4
});
});
});
describe('wrapped lines', () => {
it('should handle search across wrapped lines', async () => {
const longText = 'A'.repeat(100) + 'target' + 'B'.repeat(50);
await writeP(terminal, longText);
assert.deepStrictEqual(searchEngine.find('target', 0, 0), {
term: 'target',
col: 20,
row: 1,
size: 6
});
});
it('should handle wrapped lines with unicode', async () => {
const longText = '中'.repeat(50) + 'target' + '文'.repeat(30);
await writeP(terminal, longText);
assert.deepStrictEqual(searchEngine.find('target', 0, 0), {
term: 'target',
col: 20,
row: 1,
size: 6
});
});
it('should skip wrapped lines correctly in findInLine', async () => {
const longText = 'A'.repeat(200);
await writeP(terminal, longText + '\r\nNext line with target');
assert.deepStrictEqual(searchEngine.find('target', 0, 0), {
term: 'target',
col: 15,
row: 3,
size: 6
});
});
});
describe('buffer boundaries', () => {
it('should handle empty buffer gracefully', () => {
assert.strictEqual(searchEngine.find('anything', 0, 0), undefined);
});
it('should handle search beyond buffer size', () => {
assert.strictEqual(searchEngine.find('test', 1000, 0), undefined);
});
});
describe('invalid inputs', () => {
it('should handle undefined search options gracefully', async () => {
await writeP(terminal, 'Hello World');
assert.deepStrictEqual(searchEngine.find('Hello', 0, 0, undefined), {
term: 'Hello',
col: 0,
row: 0,
size: 5
});
});
it('should handle negative start positions', async () => {
await writeP(terminal, 'Hello World');
assert.deepStrictEqual(searchEngine.find('Hello', -1, -1), {
term: 'Hello',
col: 0,
row: 0,
size: 5
});
});
it('should handle search options with undefined properties', async () => {
await writeP(terminal, 'Hello World');
const options: ISearchOptions = {
caseSensitive: undefined,
regex: undefined,
wholeWord: undefined
};
assert.deepStrictEqual(searchEngine.find('Hello', 0, 0, options), {
term: 'Hello',
col: 0,
row: 0,
size: 5
});
});
});
});
describe('private method behaviors (tested indirectly)', () => {
describe('_isWholeWord behavior', () => {
it('should recognize word boundaries with various punctuation', async () => {
await writeP(terminal, 'word1 word2,word3(word4)word5[word6]word7{word8}');
const tests = [
{ term: 'word1', expected: true },
{ term: 'word2', expected: true },
{ term: 'word3', expected: true },
{ term: 'word4', expected: true },
{ term: 'word5', expected: true },
{ term: 'word6', expected: true },
{ term: 'word7', expected: true },
{ term: 'word8', expected: true }
];
for (const test of tests) {
const result = searchEngine.find(test.term, 0, 0, { wholeWord: true });
if (test.expected) {
assert.notStrictEqual(result, undefined, `Should find whole word: ${test.term}`);
} else {
assert.strictEqual(result, undefined, `Should not find non-whole word: ${test.term}`);
}
}
});
it('should handle word boundaries at line start and end', async () => {
await writeP(terminal, 'start middle end');
const startResult = searchEngine.find('start', 0, 0, { wholeWord: true });
assert.deepStrictEqual(startResult, {
term: 'start',
col: 0,
row: 0,
size: 5
});
const endResult = searchEngine.find('end', 0, 0, { wholeWord: true });
assert.deepStrictEqual(endResult, {
term: 'end',
col: 13,
row: 0,
size: 3
});
const middleResult = searchEngine.find('middle', 0, 0, { wholeWord: true });
assert.deepStrictEqual(middleResult, {
term: 'middle',
col: 6,
row: 0,
size: 6
});
});
});
describe('buffer offset calculations', () => {
it('should handle wide character offset calculations', async () => {
await writeP(terminal, '中文 test 测试');
const result = searchEngine.find('test', 0, 0);
assert.notStrictEqual(result, undefined);
assert.strictEqual(result!.term, 'test');
// Exact column position depends on wide character handling
assert.strictEqual(typeof result!.col, 'number');
});
});
describe('string to buffer size conversions', () => {
it('should correctly calculate size for simple text', async () => {
await writeP(terminal, 'Hello World');
assert.deepStrictEqual(searchEngine.find('World', 0, 0), {
term: 'World',
col: 6,
row: 0,
size: 5
});
});
it('should correctly calculate size for unicode text', async () => {
await writeP(terminal, 'Hello 世界');
const result = searchEngine.find('世界', 0, 0);
assert.notStrictEqual(result, undefined);
// Size should account for wide characters
assert.strictEqual(typeof result!.size, 'number');
assert.strictEqual(result!.size >= 2, true);
});
it('should handle size calculation across wrapped lines', async () => {
const longMatch = 'A'.repeat(100);
await writeP(terminal, longMatch);
const result = searchEngine.find(longMatch, 0, 0);
assert.notStrictEqual(result, undefined);
assert.strictEqual(result!.size >= 100, true);
});
});
});
describe('integration with SearchLineCache', () => {
it('should use cache for line translation', async () => {
await writeP(terminal, 'Hello World');
// Initialize cache
lineCache.initLinesCache();
const result1 = searchEngine.find('World', 0, 0);
const result2 = searchEngine.find('World', 0, 0);
assert.notStrictEqual(result1, undefined);
assert.notStrictEqual(result2, undefined);
assert.deepStrictEqual(result1, result2);
});
it('should handle cache misses gracefully', async () => {
await writeP(terminal, 'Hello World');
// Don't initialize cache
assert.deepStrictEqual(searchEngine.find('World', 0, 0), {
term: 'World',
col: 6,
row: 0,
size: 5
});
});
it('should work correctly with cache invalidation', async () => {
await writeP(terminal, 'Initial text');
lineCache.initLinesCache();
const result1 = searchEngine.find('Initial', 0, 0);
assert.notStrictEqual(result1, undefined);
// Change terminal content which should invalidate cache
await writeP(terminal, '\r\nNew line');
const result2 = searchEngine.find('New', 0, 0);
assert.deepStrictEqual(result2, {
term: 'New',
col: 0,
row: 1,
size: 3
});
});
});
});
+394
View File
@@ -0,0 +1,394 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal } from '@xterm/xterm';
import type { ISearchOptions } from '@xterm/addon-search';
import type { SearchLineCache } from './SearchLineCache';
/**
* Represents the position to start a search from.
*/
interface ISearchPosition {
startCol: number;
startRow: number;
}
/**
* Represents a search result with its position and content.
*/
export interface ISearchResult {
term: string;
col: number;
row: number;
size: number;
}
/**
* Configuration constants for the search engine functionality.
*/
const enum Constants {
/**
* Characters that are considered non-word characters for search boundary detection. These
* characters are used to determine word boundaries when performing whole-word searches. Includes
* common punctuation, symbols, and whitespace characters.
*/
NON_WORD_CHARACTERS = ' ~!@#$%^&*()+`-=[]{}|\\;:"\',./<>?'
}
/**
* Core search engine that handles finding text within terminal content.
* This class is responsible for the actual search algorithms and position calculations.
*/
export class SearchEngine {
constructor(
private readonly _terminal: Terminal,
private readonly _lineCache: SearchLineCache
) {}
/**
* Find the first occurrence of a term starting from a specific position.
* @param term The search term.
* @param startRow The row to start searching from.
* @param startCol The column to start searching from.
* @param searchOptions Search options.
* @returns The search result if found, undefined otherwise.
*/
public find(term: string, startRow: number, startCol: number, searchOptions?: ISearchOptions): ISearchResult | undefined {
if (!term || term.length === 0) {
this._terminal.clearSelection();
return undefined;
}
if (startCol > this._terminal.cols) {
throw new Error(`Invalid col: ${startCol} to search in terminal of ${this._terminal.cols} cols`);
}
this._lineCache.initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
// Search startRow
let result = this._findInLine(term, searchPosition, searchOptions);
// Search from startRow + 1 to end
if (!result) {
for (let y = startRow + 1; y < this._terminal.buffer.active.baseY + this._terminal.rows; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
return result;
}
/**
* Find the next occurrence of a term with wrapping and selection management.
* @param term The search term.
* @param searchOptions Search options.
* @param cachedSearchTerm The cached search term to determine incremental behavior.
* @returns The search result if found, undefined otherwise.
*/
public findNextWithSelection(term: string, searchOptions?: ISearchOptions, cachedSearchTerm?: string): ISearchResult | undefined {
if (!term || term.length === 0) {
this._terminal.clearSelection();
return undefined;
}
const prevSelectedPos = this._terminal.getSelectionPosition();
this._terminal.clearSelection();
let startCol = 0;
let startRow = 0;
if (prevSelectedPos) {
if (cachedSearchTerm === term) {
startCol = prevSelectedPos.end.x;
startRow = prevSelectedPos.end.y;
} else {
startCol = prevSelectedPos.start.x;
startRow = prevSelectedPos.start.y;
}
}
this._lineCache.initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
// Search startRow
let result = this._findInLine(term, searchPosition, searchOptions);
// Search from startRow + 1 to end
if (!result) {
for (let y = startRow + 1; y < this._terminal.buffer.active.baseY + this._terminal.rows; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
// If we hit the bottom and didn't search from the very top wrap back up
if (!result && startRow !== 0) {
for (let y = 0; y < startRow; y++) {
searchPosition.startRow = y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
if (result) {
break;
}
}
}
// If there is only one result, wrap back and return selection if it exists.
if (!result && prevSelectedPos) {
searchPosition.startRow = prevSelectedPos.start.y;
searchPosition.startCol = 0;
result = this._findInLine(term, searchPosition, searchOptions);
}
return result;
}
/**
* Find the previous occurrence of a term with wrapping and selection management.
* @param term The search term.
* @param searchOptions Search options.
* @param cachedSearchTerm The cached search term to determine if expansion should occur.
* @returns The search result if found, undefined otherwise.
*/
public findPreviousWithSelection(term: string, searchOptions?: ISearchOptions, cachedSearchTerm?: string): ISearchResult | undefined {
if (!term || term.length === 0) {
this._terminal.clearSelection();
return undefined;
}
const prevSelectedPos = this._terminal.getSelectionPosition();
this._terminal.clearSelection();
let startRow = this._terminal.buffer.active.baseY + this._terminal.rows - 1;
let startCol = this._terminal.cols;
const isReverseSearch = true;
this._lineCache.initLinesCache();
const searchPosition: ISearchPosition = {
startRow,
startCol
};
let result: ISearchResult | undefined;
if (prevSelectedPos) {
searchPosition.startRow = startRow = prevSelectedPos.start.y;
searchPosition.startCol = startCol = prevSelectedPos.start.x;
if (cachedSearchTerm !== term) {
// Try to expand selection to right first.
result = this._findInLine(term, searchPosition, searchOptions, false);
if (!result) {
// If selection was not able to be expanded to the right, then try reverse search
searchPosition.startRow = startRow = prevSelectedPos.end.y;
searchPosition.startCol = startCol = prevSelectedPos.end.x;
}
}
}
if (!result) {
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
}
// Search from startRow - 1 to top
if (!result) {
searchPosition.startCol = Math.max(searchPosition.startCol, this._terminal.cols);
for (let y = startRow - 1; y >= 0; y--) {
searchPosition.startRow = y;
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
if (result) {
break;
}
}
}
// If we hit the top and didn't search from the very bottom wrap back down
if (!result && startRow !== (this._terminal.buffer.active.baseY + this._terminal.rows - 1)) {
for (let y = (this._terminal.buffer.active.baseY + this._terminal.rows - 1); y >= startRow; y--) {
searchPosition.startRow = y;
result = this._findInLine(term, searchPosition, searchOptions, isReverseSearch);
if (result) {
break;
}
}
}
return result;
}
/**
* A found substring is a whole word if it doesn't have an alphanumeric character directly
* adjacent to it.
* @param searchIndex starting index of the potential whole word substring
* @param line entire string in which the potential whole word was found
* @param term the substring that starts at searchIndex
*/
private _isWholeWord(searchIndex: number, line: string, term: string): boolean {
return ((searchIndex === 0) || (Constants.NON_WORD_CHARACTERS.includes(line[searchIndex - 1]))) &&
(((searchIndex + term.length) === line.length) || (Constants.NON_WORD_CHARACTERS.includes(line[searchIndex + term.length])));
}
/**
* Searches a line for a search term. Takes the provided terminal line and searches the text line,
* which may contain subsequent terminal lines if the text is wrapped. If the provided line number
* is part of a wrapped text line that started on an earlier line then it is skipped since it will
* be properly searched when the terminal line that the text starts on is searched.
* @param term The search term.
* @param searchPosition The position to start the search.
* @param searchOptions Search options.
* @param isReverseSearch Whether the search should start from the right side of the terminal and
* search to the left.
* @returns The search result if it was found.
*/
private _findInLine(term: string, searchPosition: ISearchPosition, searchOptions: ISearchOptions = {}, isReverseSearch: boolean = false): ISearchResult | undefined {
const row = searchPosition.startRow;
const col = searchPosition.startCol;
// Ignore wrapped lines, only consider on unwrapped line (first row of command string).
const firstLine = this._terminal.buffer.active.getLine(row);
if (firstLine?.isWrapped) {
if (isReverseSearch) {
searchPosition.startCol += this._terminal.cols;
return;
}
// This will iterate until we find the line start.
// When we find it, we will search using the calculated start column.
searchPosition.startRow--;
searchPosition.startCol += this._terminal.cols;
return this._findInLine(term, searchPosition, searchOptions);
}
let cache = this._lineCache.getLineFromCache(row);
if (!cache) {
cache = this._lineCache.translateBufferLineToStringWithWrap(row, true);
this._lineCache.setLineInCache(row, cache);
}
const [stringLine, offsets] = cache;
const offset = this._bufferColsToStringOffset(row, col);
let searchTerm = term;
let searchStringLine = stringLine;
if (!searchOptions.regex) {
searchTerm = searchOptions.caseSensitive ? term : term.toLowerCase();
searchStringLine = searchOptions.caseSensitive ? stringLine : stringLine.toLowerCase();
}
let resultIndex = -1;
if (searchOptions.regex) {
const searchRegex = RegExp(searchTerm, searchOptions.caseSensitive ? 'g' : 'gi');
let foundTerm: RegExpExecArray | null;
if (isReverseSearch) {
// This loop will get the resultIndex of the _last_ regex match in the range 0..offset
while (foundTerm = searchRegex.exec(searchStringLine.slice(0, offset))) {
resultIndex = searchRegex.lastIndex - foundTerm[0].length;
term = foundTerm[0];
searchRegex.lastIndex -= (term.length - 1);
}
} else {
foundTerm = searchRegex.exec(searchStringLine.slice(offset));
if (foundTerm && foundTerm[0].length > 0) {
resultIndex = offset + (searchRegex.lastIndex - foundTerm[0].length);
term = foundTerm[0];
}
}
} else {
if (isReverseSearch) {
if (offset - searchTerm.length >= 0) {
resultIndex = searchStringLine.lastIndexOf(searchTerm, offset - searchTerm.length);
}
} else {
resultIndex = searchStringLine.indexOf(searchTerm, offset);
}
}
if (resultIndex >= 0) {
if (searchOptions.wholeWord && !this._isWholeWord(resultIndex, searchStringLine, term)) {
return;
}
// Adjust the row number and search index if needed since a "line" of text can span multiple
// rows
let startRowOffset = 0;
while (startRowOffset < offsets.length - 1 && resultIndex >= offsets[startRowOffset + 1]) {
startRowOffset++;
}
let endRowOffset = startRowOffset;
while (endRowOffset < offsets.length - 1 && resultIndex + term.length >= offsets[endRowOffset + 1]) {
endRowOffset++;
}
const startColOffset = resultIndex - offsets[startRowOffset];
const endColOffset = resultIndex + term.length - offsets[endRowOffset];
const startColIndex = this._stringLengthToBufferSize(row + startRowOffset, startColOffset);
const endColIndex = this._stringLengthToBufferSize(row + endRowOffset, endColOffset);
const size = endColIndex - startColIndex + this._terminal.cols * (endRowOffset - startRowOffset);
return {
term,
col: startColIndex,
row: row + startRowOffset,
size
};
}
}
private _stringLengthToBufferSize(row: number, offset: number): number {
const line = this._terminal.buffer.active.getLine(row);
if (!line) {
return 0;
}
for (let i = 0; i < offset; i++) {
const cell = line.getCell(i);
if (!cell) {
break;
}
// Adjust the searchIndex to normalize emoji into single chars
const char = cell.getChars();
if (char.length > 1) {
offset -= char.length - 1;
}
// Adjust the searchIndex for empty characters following wide unicode
// chars (eg. CJK)
const nextCell = line.getCell(i + 1);
if (nextCell && nextCell.getWidth() === 0) {
offset++;
}
}
return offset;
}
private _bufferColsToStringOffset(startRow: number, cols: number): number {
let lineIndex = startRow;
let offset = 0;
let line = this._terminal.buffer.active.getLine(lineIndex);
while (cols > 0 && line) {
for (let i = 0; i < cols && i < this._terminal.cols; i++) {
const cell = line.getCell(i);
if (!cell) {
break;
}
if (cell.getWidth()) {
// Treat null characters as whitespace to align with the translateToString API
offset += cell.getCode() === 0 ? 1 : cell.getChars().length;
}
}
lineIndex++;
line = this._terminal.buffer.active.getLine(lineIndex);
if (line && !line.isWrapped) {
break;
}
cols -= this._terminal.cols;
}
return offset;
}
}
@@ -0,0 +1,287 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import { SearchLineCache, LineCacheEntry } from './SearchLineCache';
import { Terminal } from 'browser/public/Terminal';
import { timeout } from 'vs/base/common/async';
function writeP(terminal: Terminal, data: string): Promise<void> {
return new Promise(r => terminal.write(data, r));
}
describe('SearchLineCache', () => {
let terminal: Terminal;
let cache: SearchLineCache;
beforeEach(() => {
terminal = new Terminal({ cols: 80, rows: 24 });
cache = new SearchLineCache(terminal);
});
afterEach(() => {
cache.dispose();
terminal.dispose();
});
describe('constructor', () => {
it('should create a SearchLineCache instance', () => {
assert.instanceOf(cache, SearchLineCache);
});
it('should start with no cache initialized', () => {
assert.equal(cache.getLineFromCache(0), undefined);
});
});
describe('initLinesCache', () => {
it('should initialize the lines cache array', () => {
cache.initLinesCache();
assert.equal(cache.getLineFromCache(0), undefined, 'cache should be initialized but empty');
});
it('should not reinitialize if cache already exists', () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
cache.initLinesCache();
const entry = cache.getLineFromCache(0);
assert.deepEqual(entry, ['test', [0]], 'cache should still contain the previously set entry');
});
it('should set up TTL timeout', () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
assert.deepEqual(cache.getLineFromCache(0), ['test', [0]], 'entry should exist after initialization');
});
});
describe('getLineFromCache', () => {
it('should return undefined when cache is not initialized', () => {
assert.equal(cache.getLineFromCache(0), undefined);
assert.equal(cache.getLineFromCache(10), undefined);
});
it('should return undefined for unset entries when cache is initialized', () => {
cache.initLinesCache();
assert.equal(cache.getLineFromCache(0), undefined);
assert.equal(cache.getLineFromCache(50), undefined);
});
it('should return cached entries', () => {
cache.initLinesCache();
const entry: LineCacheEntry = ['test content', [0]];
cache.setLineInCache(5, entry);
assert.deepEqual(cache.getLineFromCache(5), entry);
});
});
describe('setLineInCache', () => {
it('should not set entries when cache is not initialized', () => {
const entry: LineCacheEntry = ['test content', [0]];
cache.setLineInCache(0, entry);
assert.equal(cache.getLineFromCache(0), undefined);
});
it('should set entries when cache is initialized', () => {
cache.initLinesCache();
const entry: LineCacheEntry = ['test content', [0]];
cache.setLineInCache(10, entry);
assert.deepEqual(cache.getLineFromCache(10), entry);
});
it('should overwrite existing entries', () => {
cache.initLinesCache();
const entry1: LineCacheEntry = ['first content', [0]];
const entry2: LineCacheEntry = ['second content', [0]];
cache.setLineInCache(0, entry1);
assert.deepEqual(cache.getLineFromCache(0), entry1);
cache.setLineInCache(0, entry2);
assert.deepEqual(cache.getLineFromCache(0), entry2);
});
});
describe('translateBufferLineToStringWithWrap', () => {
it('should translate a single line without wrapping', async () => {
await writeP(terminal, 'Hello World');
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.equal(result[0], 'Hello World');
assert.deepEqual(result[1], [0]);
});
it('should handle trimRight parameter', async () => {
await writeP(terminal, 'Hello World ');
const resultTrimmed = cache.translateBufferLineToStringWithWrap(0, true);
const resultNotTrimmed = cache.translateBufferLineToStringWithWrap(0, false);
assert.equal(resultTrimmed[0].trimEnd(), 'Hello World');
assert.isTrue(resultNotTrimmed[0].startsWith('Hello World '));
assert.isTrue(resultNotTrimmed[0].length > resultTrimmed[0].length, 'non-trimmed result should be longer');
});
it('should handle wrapped lines', async () => {
const longText = 'A'.repeat(200);
await writeP(terminal, longText);
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.equal(result[0], longText);
assert.isTrue(result[1].length > 1, 'should have multiple offsets due to wrapping');
assert.equal(result[1][0], 0, 'first offset should be 0');
});
it('should handle wide characters', async () => {
await writeP(terminal, 'Hello 世界');
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.equal(result[0], 'Hello 世界');
assert.deepEqual(result[1], [0]);
});
it('should handle empty lines', () => {
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.equal(result[0], '');
assert.deepEqual(result[1], [0]);
});
it('should handle lines beyond buffer', () => {
const result = cache.translateBufferLineToStringWithWrap(1000, true);
assert.equal(result[0], '');
assert.deepEqual(result[1], [0]);
});
it('should handle complex wrapped content', async () => {
await writeP(terminal, 'Line 1\r\n');
await writeP(terminal, 'Line 2 with some longer content that might wrap\r\n');
await writeP(terminal, 'Line 3');
const result1 = cache.translateBufferLineToStringWithWrap(0, true);
const result2 = cache.translateBufferLineToStringWithWrap(1, true);
const result3 = cache.translateBufferLineToStringWithWrap(2, true);
assert.equal(result1[0], 'Line 1');
assert.equal(result2[0], 'Line 2 with some longer content that might wrap');
assert.equal(result3[0], 'Line 3');
});
});
describe('cache invalidation', () => {
it('should invalidate cache on line feed', async () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
assert.deepEqual(cache.getLineFromCache(0), ['test', [0]]);
terminal.write('test\r\n');
await timeout(10);
assert.equal(cache.getLineFromCache(0), undefined);
});
it('should invalidate cache on cursor move', async () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
assert.deepEqual(cache.getLineFromCache(0), ['test', [0]]);
await writeP(terminal, 'some text');
await timeout(10);
assert.equal(cache.getLineFromCache(0), undefined);
});
it('should invalidate cache on resize', async () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
assert.deepEqual(cache.getLineFromCache(0), ['test', [0]]);
terminal.resize(100, 30);
await timeout(10);
assert.equal(cache.getLineFromCache(0), undefined);
});
});
describe('disposal', () => {
it('should clean up resources on dispose', () => {
cache.initLinesCache();
cache.setLineInCache(0, ['test', [0]]);
assert.deepEqual(cache.getLineFromCache(0), ['test', [0]]);
cache.dispose();
assert.equal(cache.getLineFromCache(0), undefined, 'cache should be destroyed after disposal');
});
it('should be safe to dispose multiple times', () => {
cache.initLinesCache();
cache.dispose();
cache.dispose();
assert.equal(cache.getLineFromCache(0), undefined);
});
});
describe('LineCacheEntry type', () => {
it('should handle complex line offsets', () => {
const entry: LineCacheEntry = [
'A very long line that wraps multiple times across several terminal lines',
[0, 20, 40, 60]
];
cache.initLinesCache();
cache.setLineInCache(0, entry);
const retrieved = cache.getLineFromCache(0);
assert.deepEqual(retrieved, entry);
assert.equal(retrieved![0].length, 72);
assert.equal(retrieved![1].length, 4);
});
it('should handle unicode characters in cache entries', () => {
const entry: LineCacheEntry = [
'Hello 世界 🌍 测试',
[0]
];
cache.initLinesCache();
cache.setLineInCache(0, entry);
const retrieved = cache.getLineFromCache(0);
assert.deepEqual(retrieved, entry);
assert.equal(retrieved![0], 'Hello 世界 🌍 测试');
});
});
describe('integration with real terminal content', () => {
it('should correctly translate real buffer content', async () => {
await writeP(terminal, 'Hello World');
const cached = cache.translateBufferLineToStringWithWrap(0, true);
const directTranslation = terminal.buffer.active.getLine(0)?.translateToString(true) || '';
assert.equal(cached[0], directTranslation);
});
it('should handle real wrapped content correctly', async () => {
const longContent = 'This is a very long line that will definitely wrap around in an 80 column terminal and should be handled correctly by the cache';
await writeP(terminal, longContent);
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.equal(result[0], longContent);
assert.isTrue(result[1].length > 1, 'should have wrapped');
});
it('should work with real escape sequences', async () => {
await writeP(terminal, 'Before\x1b[31mRed Text\x1b[0mAfter');
const result = cache.translateBufferLineToStringWithWrap(0, true);
assert.include(result[0], 'Before');
assert.include(result[0], 'Red Text');
assert.include(result[0], 'After');
});
});
});
+136
View File
@@ -0,0 +1,136 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal } from '@xterm/xterm';
import { combinedDisposable, Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { disposableTimeout } from 'vs/base/common/async';
export type LineCacheEntry = [
/**
* The string representation of a line (as opposed to the buffer cell representation).
*/
lineAsString: string,
/**
* The offsets where each line starts when the entry describes a wrapped line.
*/
lineOffsets: number[]
];
/**
* Configuration constants for the search line cache functionality.
*/
const enum Constants {
/**
* Time-to-live for cached search results in milliseconds. After this duration, cached search
* results will be invalidated to ensure they remain consistent with terminal content changes.
*/
LINES_CACHE_TIME_TO_LIVE = 15000
}
export class SearchLineCache extends Disposable {
/**
* translateBufferLineToStringWithWrap is a fairly expensive call.
* We memoize the calls into an array that has a time based ttl.
* _linesCache is also invalidated when the terminal cursor moves.
*/
private _linesCache: LineCacheEntry[] | undefined;
private _linesCacheTimeout = this._register(new MutableDisposable());
private _linesCacheDisposables = this._register(new MutableDisposable());
// Track access to avoid recreating a timeout on every init call which occurs once per search
// result (findNext/findPrevious -> _highlightAllMatches -> find loop).
private _lastAccessTimestamp = 0;
constructor(private readonly _terminal: Terminal) {
super();
this._register(toDisposable(() => this._destroyLinesCache()));
}
/**
* Sets up a line cache with a ttl
*/
public initLinesCache(): void {
if (!this._linesCache) {
this._linesCache = new Array(this._terminal.buffer.active.length);
this._linesCacheDisposables.value = combinedDisposable(
this._terminal.onLineFeed(() => this._destroyLinesCache()),
this._terminal.onCursorMove(() => this._destroyLinesCache()),
this._terminal.onResize(() => this._destroyLinesCache())
);
}
this._lastAccessTimestamp = Date.now();
if (!this._linesCacheTimeout.value) {
this._scheduleLinesCacheTimeout(Constants.LINES_CACHE_TIME_TO_LIVE);
}
}
private _destroyLinesCache(): void {
this._linesCache = undefined;
this._lastAccessTimestamp = 0;
this._linesCacheDisposables.clear();
this._linesCacheTimeout.clear();
}
private _scheduleLinesCacheTimeout(delay: number): void {
this._linesCacheTimeout.value = disposableTimeout(() => {
if (!this._linesCache) {
return;
}
const now = Date.now();
const elapsed = now - this._lastAccessTimestamp;
if (elapsed >= Constants.LINES_CACHE_TIME_TO_LIVE) {
this._destroyLinesCache();
return;
}
this._scheduleLinesCacheTimeout(Constants.LINES_CACHE_TIME_TO_LIVE - elapsed);
}, delay);
}
public getLineFromCache(row: number): LineCacheEntry | undefined {
return this._linesCache?.[row];
}
public setLineInCache(row: number, entry: LineCacheEntry): void {
if (this._linesCache) {
this._linesCache[row] = entry;
}
}
/**
* Translates a buffer line to a string, including subsequent lines if they are wraps.
* Wide characters will count as two columns in the resulting string. This
* function is useful for getting the actual text underneath the raw selection
* position.
* @param lineIndex The index of the line being translated.
* @param trimRight Whether to trim whitespace to the right.
*/
public translateBufferLineToStringWithWrap(lineIndex: number, trimRight: boolean): LineCacheEntry {
const strings = [];
const lineOffsets = [0];
let line = this._terminal.buffer.active.getLine(lineIndex);
while (line) {
const nextLine = this._terminal.buffer.active.getLine(lineIndex + 1);
const lineWrapsToNext = nextLine ? nextLine.isWrapped : false;
let string = line.translateToString(!lineWrapsToNext && trimRight);
if (lineWrapsToNext && nextLine) {
const lastCell = line.getCell(line.length - 1);
const lastCellIsNull = lastCell && lastCell.getCode() === 0 && lastCell.getWidth() === 1;
// a wide character wrapped to the next line
if (lastCellIsNull && nextLine.getCell(0)?.getWidth() === 2) {
string = string.slice(0, -1);
}
}
strings.push(string);
if (lineWrapsToNext) {
lineOffsets.push(lineOffsets[lineOffsets.length - 1] + string.length);
} else {
break;
}
lineIndex++;
line = nextLine;
}
return [strings.join(''), lineOffsets];
}
}
@@ -0,0 +1,119 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { ISearchResultChangeEvent } from '@xterm/addon-search';
import type { IDisposable } from '@xterm/xterm';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import type { ISearchResult } from './SearchEngine';
/**
* Interface for managing a currently selected decoration.
*/
interface ISelectedDecoration extends IDisposable {
match: ISearchResult;
}
/**
* Tracks search results, manages result indexing, and fires events when results change.
* This class provides centralized management of search result state and notifications.
*/
export class SearchResultTracker extends Disposable {
private _searchResults: ISearchResult[] = [];
private _selectedDecoration: ISelectedDecoration | undefined;
private readonly _onDidChangeResults = this._register(new Emitter<ISearchResultChangeEvent>());
public get onDidChangeResults(): Event<ISearchResultChangeEvent> { return this._onDidChangeResults.event; }
/**
* Gets the current search results.
*/
public get searchResults(): ReadonlyArray<ISearchResult> {
return this._searchResults;
}
/**
* Gets the currently selected decoration.
*/
public get selectedDecoration(): ISelectedDecoration | undefined {
return this._selectedDecoration;
}
/**
* Sets the currently selected decoration.
*/
public set selectedDecoration(decoration: ISelectedDecoration | undefined) {
this._selectedDecoration = decoration;
}
/**
* Updates the search results with a new set of results.
* @param results The new search results.
* @param maxResults The maximum number of results to track.
*/
public updateResults(results: ISearchResult[], maxResults: number): void {
this._searchResults = results.slice(0, maxResults);
}
/**
* Clears all search results.
*/
public clearResults(): void {
this._searchResults = [];
}
/**
* Clears the selected decoration.
*/
public clearSelectedDecoration(): void {
if (this._selectedDecoration) {
this._selectedDecoration.dispose();
this._selectedDecoration = undefined;
}
}
/**
* Finds the index of a result in the current results array.
* @param result The result to find.
* @returns The index of the result, or -1 if not found.
*/
public findResultIndex(result: ISearchResult): number {
for (let i = 0; i < this._searchResults.length; i++) {
const match = this._searchResults[i];
if (match.row === result.row && match.col === result.col && match.size === result.size) {
return i;
}
}
return -1;
}
/**
* Fires a result change event with the current state.
* @param hasDecorations Whether decorations are enabled.
*/
public fireResultsChanged(hasDecorations: boolean): void {
if (!hasDecorations) {
return;
}
let resultIndex = -1;
if (this._selectedDecoration) {
resultIndex = this.findResultIndex(this._selectedDecoration.match);
}
this._onDidChangeResults.fire({
resultIndex,
resultCount: this._searchResults.length
});
}
/**
* Resets all state.
*/
public reset(): void {
this.clearSelectedDecoration();
this.clearResults();
}
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { ISearchOptions } from '@xterm/addon-search';
/**
* Manages search state including cached search terms, options tracking, and validation.
* This class provides a centralized way to handle search state consistency and option changes.
*/
export class SearchState {
private _cachedSearchTerm: string | undefined;
private _lastSearchOptions: ISearchOptions | undefined;
/**
* Gets the currently cached search term.
*/
public get cachedSearchTerm(): string | undefined {
return this._cachedSearchTerm;
}
/**
* Sets the cached search term.
*/
public set cachedSearchTerm(term: string | undefined) {
this._cachedSearchTerm = term;
}
/**
* Gets the last search options used.
*/
public get lastSearchOptions(): ISearchOptions | undefined {
return this._lastSearchOptions;
}
/**
* Sets the last search options used.
*/
public set lastSearchOptions(options: ISearchOptions | undefined) {
this._lastSearchOptions = options;
}
/**
* Validates a search term to ensure it's not empty or invalid.
* @param term The search term to validate.
* @returns true if the term is valid for searching.
*/
public isValidSearchTerm(term: string): boolean {
return !!(term && term.length > 0);
}
/**
* Determines if search options have changed compared to the last search.
* @param newOptions The new search options to compare.
* @returns true if the options have changed.
*/
public didOptionsChange(newOptions?: ISearchOptions): boolean {
if (!this._lastSearchOptions) {
return true;
}
if (!newOptions) {
return false;
}
if (this._lastSearchOptions.caseSensitive !== newOptions.caseSensitive) {
return true;
}
if (this._lastSearchOptions.regex !== newOptions.regex) {
return true;
}
if (this._lastSearchOptions.wholeWord !== newOptions.wholeWord) {
return true;
}
return false;
}
/**
* Determines if a new search should trigger highlighting updates.
* @param term The search term.
* @param options The search options.
* @returns true if highlighting should be updated.
*/
public shouldUpdateHighlighting(term: string, options?: ISearchOptions): boolean {
if (!options?.decorations) {
return false;
}
return this._cachedSearchTerm === undefined ||
term !== this._cachedSearchTerm ||
this.didOptionsChange(options);
}
/**
* Clears the cached search term.
*/
public clearCachedTerm(): void {
this._cachedSearchTerm = undefined;
}
/**
* Resets all state.
*/
public reset(): void {
this._cachedSearchTerm = undefined;
this._lastSearchOptions = undefined;
}
}
+6
View File
@@ -18,6 +18,9 @@
"common/*": [
"../../../src/common/*"
],
"browser/*": [
"../../../src/browser/*"
],
"vs/*": [
"../../../src/vs/*"
],
@@ -34,6 +37,9 @@
{
"path": "../../../src/common"
},
{
"path": "../../../src/browser"
},
{
"path": "../../../src/vs"
}
+80 -1
View File
@@ -19,8 +19,8 @@ test.afterAll(async () => await ctx.page.close());
test.describe('Search Tests', () => {
test.beforeEach(async () => {
await ctx.proxy.reset();
await ctx.page.evaluate(`
window.term.reset()
window.search?.dispose();
window.search = new SearchAddon();
window.term.loadAddon(window.search);
@@ -385,6 +385,34 @@ test.describe('Search Tests', () => {
});
});
test.describe('onBeforeSearch and onAfterSearch', () => {
test.beforeEach(async () => {
await ctx.page.evaluate(`
window.events = [];
window.search.onBeforeSearch(() => window.events.push('before'));
window.search.onAfterSearch(() => window.events.push('after'));
`);
});
test('should fire before and after findNext', async () => {
await ctx.proxy.write('abc');
await ctx.page.evaluate(`window.search.findNext('a')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after']);
});
test('should fire before and after findPrevious', async () => {
await ctx.proxy.write('abc');
await ctx.page.evaluate(`window.search.findPrevious('a')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after']);
});
test('should fire for each search call', async () => {
await ctx.proxy.write('abc abc');
await ctx.page.evaluate(`window.search.findNext('abc')`);
await ctx.page.evaluate(`window.search.findNext('abc')`);
deepStrictEqual(await ctx.page.evaluate('window.events'), ['before', 'after', 'before', 'after']);
});
});
test.describe('Regression tests', () => {
test.describe('#2444 wrapped line content not being found', () => {
let fixture: string;
@@ -480,6 +508,57 @@ test.describe('Search Tests', () => {
]);
});
});
test.describe('Wrapped line search functionality', () => {
test('should correctly count matches across multiple wrapped lines', async () => {
await ctx.page.evaluate(`
window.calls = [];
window.search.onDidChangeResults(e => window.calls.push(e));
`);
const content = 'a'.repeat(300);
await ctx.proxy.write(content);
strictEqual(await ctx.page.evaluate(`window.search.findNext('${content}', { decorations: { activeMatchColorOverviewRuler: '#ff0000', matchOverviewRuler: '#ffff00' } })`), true);
deepStrictEqual(await ctx.page.evaluate('window.calls'), [
{ resultCount: 1, resultIndex: 0 }
]);
});
test('should handle reverse search across wrapped lines', async () => {
await ctx.page.evaluate(`
window.calls = [];
window.search.onDidChangeResults(e => window.calls.push(e));
`);
const content = 'x'.repeat(300);
await ctx.proxy.write(content);
strictEqual(await ctx.page.evaluate(`window.search.findPrevious('${content}', { decorations: { activeMatchColorOverviewRuler: '#ff0000', matchOverviewRuler: '#ffff00' } })`), true);
deepStrictEqual(await ctx.page.evaluate('window.calls'), [
{ resultCount: 1, resultIndex: 0 }
]);
});
test('should update counts when content changes across wrapped lines', async () => {
await ctx.page.evaluate(`
window.calls = [];
window.search.onDidChangeResults(e => window.calls.push(e));
`);
const content = 'z'.repeat(300);
await ctx.proxy.write(content);
strictEqual(await ctx.page.evaluate(`window.search.findNext('${content}', { decorations: { activeMatchColorOverviewRuler: '#ff0000', matchOverviewRuler: '#ffff00' } })`), true);
deepStrictEqual(await ctx.page.evaluate('window.calls'), [
{ resultCount: 1, resultIndex: 0 }
]);
await ctx.proxy.write('\\n\\r' + content);
await timeout(300);
deepStrictEqual(await ctx.page.evaluate('window.calls'), [
{ resultCount: 1, resultIndex: 0 },
{ resultCount: 2, resultIndex: 0 }
]);
});
});
});
function makeData(length: number): string {
+27 -4
View File
@@ -75,6 +75,21 @@ declare module '@xterm/addon-search' {
activeMatchColorOverviewRuler: string;
}
/**
* Event data fired when search results change.
*/
export interface ISearchResultChangeEvent {
/**
* The index of the currently active result, -1 when the threshold of matches is exceeded.
*/
resultIndex: number;
/**
* The total number of search results found.
*/
resultCount: number;
}
/**
* Options for the search addon.
*/
@@ -137,10 +152,18 @@ declare module '@xterm/addon-search' {
public clearActiveDecoration(): void;
/**
* When decorations are enabled, fires when
* the search results change.
* @returns -1 for resultIndex when the threshold of matches is exceeded.
* Fires after a search is performed.
*/
readonly onDidChangeResults: IEvent<{ resultIndex: number, resultCount: number }>;
readonly onAfterSearch: IEvent<void>;
/**
* Fires before a search is performed.
*/
readonly onBeforeSearch: IEvent<void>;
/**
* When decorations are enabled, fires when the search results change.
*/
readonly onDidChangeResults: IEvent<ISearchResultChangeEvent>;
}
}
+3 -3
View File
@@ -34,9 +34,9 @@ See the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/addon-
```shell
$ git clone https://github.com/xtermjs/xterm.js.git
$ cd xterm.js
$ yarn
$ npm ci
$ cd addons/addon-serialize
$ yarn benchmark && yarn benchmark-baseline
$ npm run benchmark && npm run benchmark-baseline
$ # change some code in `@xterm/addon-serialize`
$ yarn benchmark-eval
$ npm run benchmark-eval
```
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-serialize",
"version": "0.13.0",
"version": "0.14.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -24,8 +24,5 @@
"benchmark": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json",
"benchmark-baseline": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json --baseline out-benchmark/benchmark/*benchmark.js",
"benchmark-eval": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json --eval out-benchmark/benchmark/*benchmark.js"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
@@ -112,6 +112,116 @@ describe('SerializeAddon', () => {
}), 'world');
});
});
describe('underline styles', () => {
it('should serialize single underline with style', async () => {
await writeP(terminal, sgr('4:1') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:1mtest\u001b[0m');
});
it('should serialize double underline', async () => {
await writeP(terminal, sgr('4:2') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:2mtest\u001b[0m');
});
it('should serialize curly underline', async () => {
await writeP(terminal, sgr('4:3') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:3mtest\u001b[0m');
});
it('should serialize dotted underline', async () => {
await writeP(terminal, sgr('4:4') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:4mtest\u001b[0m');
});
it('should serialize dashed underline', async () => {
await writeP(terminal, sgr('4:5') + 'test' + sgr('24'));
assert.equal(serializeAddon.serialize(), '\u001b[4:5mtest\u001b[0m');
});
it('should serialize underline with RGB color', async () => {
await writeP(terminal, sgr('4', '58;2;255;128;64') + 'test' + sgr('24'));
const result = serializeAddon.serialize();
assert.ok(result.includes('4:1'), result);
assert.ok(result.includes('58:2::255:128:64'), result);
});
it('should serialize underline with palette color', async () => {
await writeP(terminal, sgr('4', '58;5;46') + 'test' + sgr('24'));
const result = serializeAddon.serialize();
assert.ok(result.includes('4:1'), result);
assert.ok(result.includes('58:5:46'), result);
});
});
describe('scroll region', () => {
let scrollTerminal: Terminal;
let scrollAddon: SerializeAddon;
beforeEach(() => {
scrollTerminal = new Terminal({ cols: 10, rows: 5, allowProposedApi: true });
scrollAddon = new SerializeAddon();
scrollTerminal.loadAddon(scrollAddon);
});
it('should serialize scroll region when margins are set', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const buffer = (scrollTerminal as any)._core.buffer;
assert.equal(buffer.scrollTop, 1, 'scrollTop should be 1');
assert.equal(buffer.scrollBottom, 3, 'scrollBottom should be 3');
const result = scrollAddon.serialize();
assert.ok(result.includes('\x1b[2;4r'), result);
});
it('should not serialize scroll region when excludeModes is true', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const result = scrollAddon.serialize({ excludeModes: true });
assert.ok(!result.includes('\x1b[2;4r'), result);
});
it('should restore scroll region correctly when deserialized', async () => {
await writeP(scrollTerminal, '\x1b[2;4r');
const serialized = scrollAddon.serialize();
const terminal2 = new Terminal({ cols: 10, rows: 5, allowProposedApi: true });
terminal2.loadAddon(new SerializeAddon());
await writeP(terminal2, serialized);
const buffer = (terminal2 as any)._core.buffer;
assert.equal(buffer.scrollTop, 1);
assert.equal(buffer.scrollBottom, 3);
});
});
describe('cursor visibility', () => {
it('should serialize hidden cursor', async () => {
await writeP(terminal, 'hello\x1b[?25l');
assert.equal(terminal.modes.showCursor, false);
const result = serializeAddon.serialize();
assert.ok(result.includes('\x1b[?25l'), result);
});
it('should not serialize visible cursor (default state)', async () => {
await writeP(terminal, 'hello');
assert.equal(terminal.modes.showCursor, true);
const result = serializeAddon.serialize();
assert.ok(!result.includes('\x1b[?25l'), result);
assert.ok(!result.includes('\x1b[?25h'), result);
});
it('should not serialize cursor visibility when excludeModes is true', async () => {
await writeP(terminal, 'hello\x1b[?25l');
const result = serializeAddon.serialize({ excludeModes: true });
assert.ok(!result.includes('\x1b[?25l'), result);
});
it('should restore hidden cursor correctly when deserialized', async () => {
await writeP(terminal, 'hello\x1b[?25l');
const serialized = serializeAddon.serialize();
const terminal2 = new Terminal({ cols: 10, rows: 2, allowProposedApi: true });
terminal2.loadAddon(new SerializeAddon());
await writeP(terminal2, serialized);
assert.equal(terminal2.modes.showCursor, false);
});
});
});
describe('html', () => {
@@ -148,6 +258,22 @@ describe('SerializeAddon', () => {
assert.equal((output.match(/<div><span>&lt;a>&amp;pi;<\/span><\/div>/g) || []).length, 1, output);
});
it('serializes rows within a provided range', async () => {
await writeP(terminal, 'bye hello\r\nworld');
const output = serializeAddon.serializeAsHTML({
range: {
startLine: 0,
endLine: 0,
startCol: 4
}
});
const rowMatches = output.match(/<div><span>.*?<\/span><\/div>/g) || [];
assert.equal(rowMatches.length, 1, output);
assert.ok(rowMatches[0]?.includes('hello'));
assert.ok(!output.includes('bye'));
assert.ok(!output.includes('world'));
});
it('cells with bold styling', async () => {
await writeP(terminal, ' ' + sgr('1') + 'terminal' + sgr('22') + ' ');
@@ -176,6 +302,50 @@ describe('SerializeAddon', () => {
assert.equal((output.match(/<span style='text-decoration: underline;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with double underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:2') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline double;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with curly underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:3') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline wavy;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with dotted underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:4') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline dotted;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with dashed underline styling', async () => {
await writeP(terminal, ' ' + sgr('4:5') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.equal((output.match(/<span style='text-decoration: underline dashed;'>terminal<\/span>/g) || []).length, 1, output);
});
it('cells with underline color (palette)', async () => {
await writeP(terminal, ' ' + sgr('4', '58;5;46') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.ok(output.includes('text-decoration: underline;'), output);
assert.ok(output.includes('text-decoration-color: #00ff00;'), output);
});
it('cells with underline color (RGB)', async () => {
await writeP(terminal, ' ' + sgr('4', '58;2;255;128;64') + 'terminal' + sgr('24') + ' ');
const output = serializeAddon.serializeAsHTML();
assert.ok(output.includes('text-decoration: underline;'), output);
assert.ok(output.includes('text-decoration-color: #ff8040;'), output);
});
it('cells with invisible styling', async () => {
await writeP(terminal, ' ' + sgr('8') + 'terminal' + sgr('28') + ' ');
+134 -7
View File
@@ -9,6 +9,7 @@ import type { IBuffer, IBufferCell, IBufferRange, ITerminalAddon, Terminal } fro
import type { IHTMLSerializeOptions, SerializeAddon as ISerializeApi, ISerializeOptions, ISerializeRange } from '@xterm/addon-serialize';
import { IAttributeData, IColor } from 'common/Types';
import { DEFAULT_ANSI_COLORS } from 'browser/Types';
import { UnderlineStyle } from 'common/buffer/Constants';
function constrain(value: number, low: number, high: number): number {
return Math.max(low, Math.min(value, high));
@@ -82,10 +83,24 @@ function equalBg(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boole
&& cell1.getBgColor() === cell2.getBgColor();
}
function equalUnderline(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
// If neither cell has underline, consider them equal regardless of internal underline color
// values
if (!cell1.isUnderline() && !cell2.isUnderline()) {
return true;
}
const cell1Data = cell1 as unknown as IAttributeData;
const cell2Data = cell2 as unknown as IAttributeData;
return cell1Data.getUnderlineStyle() === cell2Data.getUnderlineStyle()
&& cell1Data.getUnderlineColor() === cell2Data.getUnderlineColor()
&& cell1Data.getUnderlineColorMode() === cell2Data.getUnderlineColorMode();
}
function equalFlags(cell1: IBufferCell | IAttributeData, cell2: IBufferCell): boolean {
return cell1.isInverse() === cell2.isInverse()
&& cell1.isBold() === cell2.isBold()
&& cell1.isUnderline() === cell2.isUnderline()
&& equalUnderline(cell1, cell2)
&& cell1.isOverline() === cell2.isOverline()
&& cell1.isBlink() === cell2.isBlink()
&& cell1.isInvisible() === cell2.isInvisible()
@@ -274,7 +289,27 @@ class StringSerializeHandler extends BaseSerializeHandler {
if (flagsChanged) {
if (cell.isInverse() !== oldCell.isInverse()) { sgrSeq.push(cell.isInverse() ? 7 : 27); }
if (cell.isBold() !== oldCell.isBold()) { sgrSeq.push(cell.isBold() ? 1 : 22); }
if (cell.isUnderline() !== oldCell.isUnderline()) { sgrSeq.push(cell.isUnderline() ? 4 : 24); }
if (!equalUnderline(cell, oldCell)) {
const cellData = cell as unknown as IAttributeData;
const style = cellData.getUnderlineStyle();
if (style === UnderlineStyle.NONE) {
sgrSeq.push(24);
} else {
// Use SGR 4:X format for underline styles
sgrSeq.push('4:' + style as unknown as number);
// Handle underline color
if (!cellData.isUnderlineColorDefault()) {
const color = cellData.getUnderlineColor();
if (cellData.isUnderlineColorRGB()) {
sgrSeq.push('58:2::' + ((color >>> 16) & 0xFF) + ':' + ((color >>> 8) & 0xFF) + ':' + (color & 0xFF) as unknown as number);
} else {
sgrSeq.push('58:5:' + color as unknown as number);
}
}
}
} else if (cell.isUnderline() !== oldCell.isUnderline()) {
sgrSeq.push(cell.isUnderline() ? 4 : 24);
}
if (cell.isOverline() !== oldCell.isOverline()) { sgrSeq.push(cell.isOverline() ? 53 : 55); }
if (cell.isBlink() !== oldCell.isBlink()) { sgrSeq.push(cell.isBlink() ? 5 : 25); }
if (cell.isInvisible() !== oldCell.isInvisible()) { sgrSeq.push(cell.isInvisible() ? 8 : 28); }
@@ -450,6 +485,13 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
const buffer = terminal.buffer.active;
const handler = new HTMLSerializeHandler(buffer, terminal, options);
const onlySelection = options.onlySelection ?? false;
const range = options.range;
if (range) {
return handler.serialize({
start: { x: range.startCol, y: typeof range.startLine === 'number' ? range.startLine : range.startLine },
end: { x: terminal.cols, y: typeof range.endLine === 'number' ? range.endLine : range.endLine }
});
}
if (!onlySelection) {
const maxRows = buffer.length;
const scrollback = options.scrollback;
@@ -471,6 +513,25 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
return '';
}
/**
* Serializes the scroll region (DECSTBM) if it's not set to the full terminal size.
* Uses internal API access since scroll region is not exposed in the public API.
*/
private _serializeScrollRegion(terminal: Terminal): string {
// HACK: Internal API access since scroll region is not exposed in the public API
const buffer = (terminal as any)._core.buffer;
const scrollTop: number = buffer.scrollTop;
const scrollBottom: number = buffer.scrollBottom;
// Only serialize if scroll region is not the default (full terminal size)
if (scrollTop !== 0 || scrollBottom !== terminal.rows - 1) {
// DECSTBM uses 1-based indices: CSI Ps ; Ps r
return `\x1b[${scrollTop + 1};${scrollBottom + 1}r`;
}
return '';
}
private _serializeModes(terminal: Terminal): string {
let content = '';
const modes = terminal.modes;
@@ -483,6 +544,7 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
if (modes.originMode) content += '\x1b[?6h';
if (modes.reverseWraparoundMode) content += '\x1b[?45h';
if (modes.sendFocusMode) content += '\x1b[?1004h';
// synchronizedOutputMode doesn't need to be serialized as it's a temporary mode
// Default: true
if (modes.wraparoundMode === false) content += '\x1b[?7l';
@@ -497,6 +559,12 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
}
}
// Cursor visibility (DECTCEM)
// Default: visible
if (!modes.showCursor) {
content += '\x1b[?25l';
}
return content;
}
@@ -519,9 +587,10 @@ export class SerializeAddon implements ITerminalAddon , ISerializeApi {
}
}
// Modes
// Modes and scroll region
if (!options?.excludeModes) {
content += this._serializeModes(this._terminal);
content += this._serializeScrollRegion(this._terminal);
}
return content;
@@ -619,6 +688,42 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
return undefined;
}
private _getUnderlineColor(cell: IBufferCell): string | undefined {
const cellData = cell as unknown as IAttributeData;
if (cellData.isUnderlineColorDefault()) {
return undefined;
}
const color = cellData.getUnderlineColor();
if (cellData.isUnderlineColorRGB()) {
const rgb = [
(color >> 16) & 255,
(color >> 8) & 255,
(color ) & 255
];
return '#' + rgb.map(x => this._padStart(x.toString(16), 2, '0')).join('');
}
// Palette color
return this._ansiColors[color].css;
}
private _getUnderlineStyle(cell: IBufferCell): string {
const cellData = cell as unknown as IAttributeData;
switch (cellData.getUnderlineStyle()) {
case UnderlineStyle.SINGLE:
return 'underline';
case UnderlineStyle.DOUBLE:
return 'underline double';
case UnderlineStyle.CURLY:
return 'underline wavy';
case UnderlineStyle.DOTTED:
return 'underline dotted';
case UnderlineStyle.DASHED:
return 'underline dashed';
default:
return 'underline';
}
}
private _diffStyle(cell: IBufferCell, oldCell: IBufferCell): string[] | undefined {
const content: string[] = [];
@@ -639,14 +744,36 @@ export class HTMLSerializeHandler extends BaseSerializeHandler {
if (cell.isInverse()) { content.push('color: #000000; background-color: #BFBFBF;'); }
if (cell.isBold()) { content.push('font-weight: bold;'); }
if (cell.isUnderline() && cell.isOverline()) { content.push('text-decoration: overline underline;'); }
else if (cell.isUnderline()) { content.push('text-decoration: underline;'); }
else if (cell.isOverline()) { content.push('text-decoration: overline;'); }
if (cell.isBlink()) { content.push('text-decoration: blink;'); }
// Handle text-decoration (underline, overline, strikethrough, blink)
const decorations: string[] = [];
if (cell.isUnderline()) {
decorations.push(this._getUnderlineStyle(cell));
}
if (cell.isOverline()) {
decorations.push('overline');
}
if (cell.isStrikethrough()) {
decorations.push('line-through');
}
if (cell.isBlink()) {
decorations.push('blink');
}
if (decorations.length > 0) {
content.push('text-decoration: ' + decorations.join(' ') + ';');
}
// Handle underline color
if (cell.isUnderline()) {
const underlineColor = this._getUnderlineColor(cell);
if (underlineColor) {
content.push('text-decoration-color: ' + underlineColor + ';');
}
}
if (cell.isInvisible()) { content.push('visibility: hidden;'); }
if (cell.isItalic()) { content.push('font-style: italic;'); }
if (cell.isDim()) { content.push('opacity: 0.5;'); }
if (cell.isStrikethrough()) { content.push('text-decoration: line-through;'); }
return content;
}
+11
View File
@@ -90,6 +90,17 @@ declare module '@xterm/addon-serialize' {
* Whether to include the global background of the terminal. False by default.
*/
includeGlobalBackground: boolean;
/**
* The range to serialize. This is prioritized over {@link onlySelection}.
*/
range?: ISerializeBufferRange;
}
export interface ISerializeBufferRange {
startLine: number;
endLine: number;
startCol: number;
}
export interface ISerializeRange {
+2 -5
View File
@@ -1,12 +1,12 @@
{
"name": "@xterm/addon-unicode-graphemes",
"version": "0.3.0",
"version": "0.4.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"main": "lib/addon-unicode-graphemes.js",
"module": "lib/.addon-unicode-graphemes.mjs",
"module": "lib/addon-unicode-graphemes.mjs",
"types": "typings/addon-unicode-graphemes.d.ts",
"repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode-graphemes",
"license": "MIT",
@@ -24,8 +24,5 @@
"benchmark": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json out-benchmark/benchmark/*benchmark.js",
"benchmark-baseline": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json --baseline out-benchmark/benchmark/*benchmark.js",
"benchmark-eval": "NODE_PATH=../../out:./out:./out-benchmark/ ../../node_modules/.bin/xterm-benchmark -r 5 -c benchmark/benchmark.json --eval out-benchmark/benchmark/*benchmark.js"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+1 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-unicode11",
"version": "0.8.0",
"version": "0.9.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -21,8 +21,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2024, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+220
View File
@@ -0,0 +1,220 @@
## @xterm/addon-web-fonts
Addon to use webfonts with [xterm.js](https://github.com/xtermjs/xterm.js).
This addon requires xterm.js v5+.
### Install
```bash
npm install --save @xterm/addon-web-fonts
```
### Issue with Webfonts
Webfonts are announced by CSS `font-face` rules (or its Javascript `FontFace` counterparts).
Since font files tend to be quite big assets, browser engines often postpone their loading
to an actual styling request of a codepoint matching a font file's `unicode-range`.
In short - font files will not be loaded until really needed.
xterm.js on the other hand heavily relies on exact measurement of character glyphs
to layout its output. This is done by determining the glyph width (DOM renderer) or
by creating a glyph texture (WebGl renderer) for every output character.
For performance reasons both is done in synchronous code and cached.
This logic only works properly, if a font glyph is available on its first usage,
otherwise the browser will pick a glyph from a fallback font messing up the metrics.
For webfonts and xterm.js this means that we cannot rely on the default loading strategy
of the browser, but have to preload the font files before using that font in xterm.js.
### Static Preloading for the Rescue?
If you dont mind higher initial loading times with a white page shown,
you can tell the browser to preload the needed font files by placing the following
link elements in the document's head above any other CSS/Javascript:
```html
<link rel="preload" as="font" href="/path/to/your/fontfile1.woff" type="font/woff2" crossorigin="anonymous">
<link rel="preload" as="font" href="/path/to/your/fontfile2.woff" type="font/woff2" crossorigin="anonymous">
...
<!-- CSS with font-face rules matching the URLs above -->
```
Browsers also will resort to system fonts, if the preloading takes too long.
So this solution has only a very limited scope.
### Loading with WebFontsAddon
The webfonts addon offers several ways to deal with font assets loading
without leaving the terminal in an unusable state.
Recap - normally boostrapping of a new terminal involves these basic steps (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
// create a `Terminal` instance with some options, e.g. a custom font family
const terminal = new Terminal({fontFamily: 'monospace'});
// create and load all addons you want to use, e.g. fit addon
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
// finally: call `open` of the terminal instance
terminal.open(your_terminal_div_element); // <-- critical path for webfonts
// more boostrapping goes here ...
```
This code is guaranteed to work in all browsers synchronously, as the identifier `monospace`
will always be available. It will also work synchronously with any installed system font,
but breaks horribly with webfonts. The actual culprit here is the call to `terminal.open`,
which attaches the terminal to the DOM and starts the renderer with all the glyph caching
mentioned above, while the webfont is not yet fully available.
To fix that, the webfonts addon provides a waiting condition (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
import { WebFontsAddon } from '@xterm/addon-web-fonts';
// create a `Terminal` instance, now with webfonts
const terminal = new Terminal({fontFamily: '"Web Mono 1", "Super Powerline", monospace'});
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
const webFontsInstance = new WebFontsAddon();
terminal.loadAddon(webFontsInstance);
// wait for webfonts to be fully loaded
webFontsInstance.loadFonts(['Web Mono 1', 'Super Powerline']).then(() => {
terminal.open(your_terminal_div_element);
// more boostrapping goes here ...
});
```
Here `loadFonts` will look up the font face objects in `document.fonts`
and load them before continuing. For this to work, you have to make sure,
that the CSS `font-face` rules for these webfonts are loaded beforehand,
otherwise `loadFonts` will not find the font family names (promise will be
rejected for missing font family names).
Please note, that this cannot run synchronous anymore, so you will have to split your
bootstrapping code into several stages. If that is too much of a hassle,
you can also move the whole bootstrapping under the waiting condition by using
the static loader instead (Typescript):
```typescript
import { Terminal } from '@xterm/xterm';
import { XYAddon } from '@xterm/addon-xy';
// import static loader
import { loadFonts } from '@xterm/addon-web-fonts';
loadFonts(['Web Mono 1', 'Super Powerline']).then(() => {
// create a `Terminal` instance, now with webfonts
const terminal = new Terminal({fontFamily: '"Web Mono 1", "Super Powerline", monospace'});
const xyInstance = new XYAddon();
terminal.loadAddon(xyInstance);
// optional when using static loader
const webfontsInstance = new WebFontsAddon();
terminal.loadAddon(webfontsInstance);
terminal.open(your_terminal_div_element);
// more boostrapping goes here ...
});
```
With the static loader creating and loading of the actual addon can be omitted,
as fonts are already loaded before any terminal setup happens.
### Webfont Loading at Runtime
Given you have a terminal already running and want to change the font family
to a different not yet loaded webfont:
```typescript
// either create font face objects in javascript
const ff1 = new FontFace('New Web Mono', url1, ...);
const ff2 = new FontFace('New Web Mono', url2, ...);
// and await their loading
loadFonts([ff1, ff2]).then(() => {
// apply new webfont to terminal
terminal.options.fontFamily = 'New Web Mono';
// since the new font might have slighly different metrics,
// also run the fit addon here (or any other custom resize logic)
fitAddon.fit();
});
// or alternatively use CSS to add new font-face rules, e.g.
document.styleSheets[0].insertRule(
"@font-face { font-family: 'New Web Mono'; src: url(newfont.woff); }", 0);
// and await the new font family name
loadFonts(['New Web Mono']).then(() => {
// apply new webfont to terminal
terminal.options.fontFamily = 'New Web Mono';
// since the new font might have slighly different metrics,
// also run the fit addon here (or any other custom resize logic)
fitAddon.fit();
});
```
### Forced Layout Update
If you have the addon loaded into your terminal, you can force the terminal to update
the layout with the method `WebFontsAddon.relayout`. This might come handy,
if the terminal shows webfont related output issue for unknown reasons:
```typescript
...
// given - terminal shows weird font issues, run:
webFontsInstance.relayout().then(() => {
// also run resize logic here, e.g. fit addon
fitAddon.fit();
});
```
Note that this method is only meant as a quickfix on a running terminal to keep it
in a working condition. A production-ready integration should never rely on it,
better fix the real root cause (most likely not properly awaiting the font loader
higher up in the code).
### Webfonts from Fontsource
The addon has been tested to work with webfonts from fontsource.
Javascript example for `vite` with ESM import:
```javascript
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { loadFonts } from '@xterm/addon-web-fonts';
import '@xterm/xterm/css/xterm.css';
import '@fontsource/roboto-mono';
import '@fontsource/roboto-mono/400.css';
import '@fontsource/roboto-mono/400-italic.css';
import '@fontsource/roboto-mono/700.css';
import '@fontsource/roboto-mono/700-italic.css';
async function main() {
let fontFamily = '"Roboto Mono", monospace';
try {
await loadFonts(['Roboto Mono']);
} catch (e) {
fontFamily = 'monospace';
}
const terminal = new Terminal({ fontFamily });
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(document.getElementById('your-xterm-container-div'));
fitAddon.fit();
// sync writing shows up in Roboto Mono w'o FOUT
// and a fallback to monospace
terminal.write('put any unicode char here');
}
main();
```
The fontsource packages download the font files to your project folder to be delivered
from there later on. For security sensitive projects this should be the preferred way,
as it brings the font files under your control.
The example furthermore contains proper exception handling with a fallback
(skipped in all other examples for better readability).
---
Also see the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/addon-web-fonts/typings/addon-web-fonts.d.ts).
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@xterm/addon-web-fonts",
"version": "0.1.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"main": "lib/addon-web-fonts.js",
"module": "lib/addon-web-fonts.mjs",
"types": "typings/addon-web-fonts.d.ts",
"repository": "https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-fonts",
"license": "MIT",
"keywords": [
"terminal",
"xterm",
"xterm.js"
],
"scripts": {
"build": "../../node_modules/.bin/tsc -p .",
"prepackage": "npm run build",
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"dependencies": {}
}
+152
View File
@@ -0,0 +1,152 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal, ITerminalAddon } from '@xterm/xterm';
import type { WebFontsAddon as IWebFontsApi } from '@xterm/addon-web-fonts';
/**
* Unquote a font family name.
*/
function unquote(s: string): string {
if (s[0] === '"' && s[s.length - 1] === '"') return s.slice(1, -1);
if (s[0] === '\'' && s[s.length - 1] === '\'') return s.slice(1, -1);
return s;
}
/**
* Quote a font family name conditionally.
* @see https://mathiasbynens.be/notes/unquoted-font-family
*/
function quote(s: string): string {
const pos = s.match(/([-_a-zA-Z0-9\xA0-\u{10FFFF}]+)/u);
const neg = s.match(/^(-?\d|--)/m);
if (!neg && pos && pos[1] === s) return s;
return `"${s.replace(/"/g, '\\"')}"`;
}
function splitFamily(family: string | undefined): string[] {
if (!family) return [];
return family.split(',').map(e => unquote(e.trim()));
}
function createFamily(families: string[]): string {
return families.map(quote).join(', ');
}
/**
* Hash a font face from it properties.
* Used in `loadFonts` to avoid bloating
* `document.fonts` from multiple calls.
*/
function hashFontFace(ff: FontFace): string {
return JSON.stringify([
unquote(ff.family),
ff.stretch,
ff.style,
ff.unicodeRange,
ff.weight
]);
}
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
function _loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
const ffs = Array.from(document.fonts);
if (!fonts || !fonts.length) {
return Promise.all(ffs.map(ff => ff.load()));
}
let toLoad: FontFace[] = [];
const ffsHashed = ffs.map(ff => hashFontFace(ff));
for (const font of fonts) {
if (font instanceof FontFace) {
const fontHashed = hashFontFace(font);
const idx = ffsHashed.indexOf(fontHashed);
if (idx === -1) {
document.fonts.add(font);
ffs.push(font);
ffsHashed.push(fontHashed);
toLoad.push(font);
} else {
toLoad.push(ffs[idx]);
}
} else {
// string as font
const familyFiltered = ffs.filter(ff => font === unquote(ff.family));
toLoad = toLoad.concat(familyFiltered);
if (!familyFiltered.length) {
return Promise.reject(`font family "${font}" not registered in document.fonts`);
}
}
}
return Promise.all(toLoad.map(ff => ff.load()));
}
export function loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
return document.fonts.ready.then(() => _loadFonts(fonts));
}
export class WebFontsAddon implements ITerminalAddon, IWebFontsApi {
private _term: Terminal | undefined;
constructor(public initialRelayout: boolean = true) { }
public dispose(): void {
this._term = undefined;
}
public activate(term: Terminal): void {
this._term = term;
if (this.initialRelayout) {
document.fonts.ready.then(() => this.relayout());
}
}
public loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]> {
return loadFonts(fonts);
}
public async relayout(): Promise<void> {
if (!this._term) {
return;
}
await document.fonts.ready;
const family = this._term.options.fontFamily;
const families = splitFamily(family);
const webFamilies = Array.from(new Set(Array.from(document.fonts).map(e => unquote(e.family))));
const dirty: string[] = [];
const clean: string[] = [];
for (const fam of families) {
(webFamilies.indexOf(fam) !== -1 ? dirty : clean).push(fam);
}
if (!dirty.length) {
return;
}
await _loadFonts(dirty);
if (this._term) {
this._term.options.fontFamily = clean.length ? createFamily(clean) : 'monospace';
this._term.options.fontFamily = family;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2021",
"lib": [
"dom",
"es2015",
"dom.iterable"
],
"rootDir": ".",
"outDir": "../out",
"sourceMap": true,
"removeComments": true,
"strict": true,
"types": [
"../../../node_modules/@types/mocha"
],
"paths": {
"@xterm/addon-web-fonts": [
"../typings/addon-web-fonts.d.ts"
]
}
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
@@ -0,0 +1,120 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import test from '@playwright/test';
import { deepStrictEqual, strictEqual } from 'assert';
import { ITestContext, createTestContext, openTerminal, pollFor, timeout } from '../../../test/playwright/TestUtils';
let ctx: ITestContext;
test.beforeAll(async ({ browser }) => {
ctx = await createTestContext(browser);
await openTerminal(ctx, { cols: 40 });
});
test.afterAll(async () => await ctx.page.close());
test.describe('WebFontsAddon', () => {
test.beforeEach(async () => {
// make sure that we start with no webfonts in the document
const empty = await await getDocumentFonts();
deepStrictEqual(empty, []);
});
test.afterEach(async () => {
// for font loading tests to work, we have to remove added rules and fonts
// to work around the quite aggressive font caching done by the browsers
await ctx.page.evaluate(`
document.styleSheets[0].deleteRule(1);
document.styleSheets[0].deleteRule(0);
document.fonts.clear();
`);
});
test.describe('font loading at runtime', () => {
test('loadFonts (JS)', async () => {
await ctx.page.evaluate(`
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
loadFonts([ff1, ff2]);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('loadFonts (CSS, unquoted)', async () => {
await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
document.styleSheets[0].insertRule("@font-face {font-family: BPdots; src: url(/bpdots.regular.otf) format('opentype')}", 1);
loadFonts(['Kongtext', 'BPdots']);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('loadFonts (CSS, quoted)', async ({ browser }) => {
// NOTE: firefox preserves family quotes from CSS rules in fontface, all other browsers unquote them
await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: 'Kongtext'; src: url(/kongtext.regular.ttf) format('truetype')}", 0);
document.styleSheets[0].insertRule("@font-face {font-family: 'BPdots'; src: url(/bpdots.regular.otf) format('opentype')}", 1);
loadFonts(['Kongtext', 'BPdots']);
`);
if (browser.browserType().name() === 'firefox') {
deepStrictEqual(await getDocumentFonts(), [{ family: '"Kongtext"', status: 'loaded' }, { family: '"BPdots"', status: 'loaded' }]);
} else {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
}
});
test('FontFace hashing', async () => {
// multiple calls of `loadFonts` with the same objects shall not bloat document.fonts
await ctx.page.evaluate(`
const ff1 = new FontFace('Kongtext', "url(/kongtext.regular.ttf) format('truetype')");
const ff2 = new FontFace('BPdots', "url(/bpdots.regular.otf) format('opentype')");
loadFonts([ff1, ff2]);
loadFonts([ff1, ff2]);
loadFonts([ff1, ff2]).then(() => loadFonts([ff1, ff2]));
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }, { family: 'BPdots', status: 'loaded' }]);
});
test('autoload & relayout from ctor', async ({ browser }) => {
// to make this test work, we exclude the default measurement char W (x57) by restricting unicode-range
// now the browser will postpone font loading until codepoint is hit --> wrong glyph metrics on first usage
const data = await ctx.page.evaluate(`
document.styleSheets[0].insertRule("@font-face {font-family: Kongtext; src: url(/kongtext.regular.ttf) format('truetype'); unicode-range: U+00A0-00FF}", 0);
`);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
// broken case: webfont in ctor without addon usage
await ctx.page.evaluate(`
window.helperTerm = new Terminal({fontFamily: '"Kongtext", ' + term.options.fontFamily});
window.helperTerm.open(term.element);
`);
// safari loads the font, firefox & chrome dont
if (browser.browserType().name() === 'webkit') {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
} else {
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'unloaded' }]);
}
// good case: addon fixes layout for webfont in ctor
// the relayout happens async, so wait a bit with a promise
await ctx.page.evaluate(`
window.helperTerm.dispose();
window.helperTerm = new Terminal({fontFamily: '"Kongtext", ' + term.options.fontFamily});
window._webfontsAddon = new WebFontsAddon();
window.helperTerm.loadAddon(window._webfontsAddon);
window.helperTerm.open(term.element);
`);
await timeout(100);
deepStrictEqual(await getDocumentFonts(), [{ family: 'Kongtext', status: 'loaded' }]);
// cleanup this messy test case
await ctx.page.evaluate(`
window.helperTerm.dispose();
window._webfontsAddon.dispose();
`);
});
});
});
async function getDocumentFonts(): Promise<any> {
return ctx.page.evaluate(`Array.from(document.fonts).map(ff => ({family: ff.family, status: ff.status}))`);
}
@@ -0,0 +1,35 @@
import { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: '.',
timeout: 10000,
projects: [
{
name: 'ChromeStable',
use: {
browserName: 'chromium',
channel: 'chrome'
}
},
{
name: 'FirefoxStable',
use: {
browserName: 'firefox'
}
},
{
name: 'WebKit',
use: {
browserName: 'webkit'
}
}
],
reporter: 'list',
webServer: {
command: 'npm run start',
port: 3000,
timeout: 120000,
reuseExistingServer: !process.env.CI
}
};
export default config;
+42
View File
@@ -0,0 +1,42 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2021",
"lib": [
"es2021",
],
// "downlevelIteration": true,
"rootDir": ".",
"outDir": "../out-test",
"sourceMap": true,
"removeComments": true,
"baseUrl": ".",
"paths": {
"common/*": [
"../../../src/common/*"
],
"browser/*": [
"../../../src/browser/*"
]
},
"strict": true,
"types": [
"../../../node_modules/@types/node"
]
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
],
"references": [
{
"path": "../../../src/common"
},
{
"path": "../../../src/browser"
},
{
"path": "../../../test/playwright"
}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"files": [],
"include": [],
"references": [
{ "path": "./src" },
{ "path": "./test" }
]
}
+67
View File
@@ -0,0 +1,67 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Terminal, ITerminalAddon } from '@xterm/xterm';
declare module '@xterm/addon-web-fonts' {
/**
* Addon to use webfonts in xterm.js
*/
export class WebFontsAddon implements ITerminalAddon {
/**
* @param initialRelayout Force initial relayout, if a webfont was found (default true).
*/
constructor(initialRelayout?: boolean);
public activate(terminal: Terminal): void;
public dispose(): void;
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
public loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]>;
/**
* Force a terminal relayout by altering `options.FontFamily`.
*
* Found webfonts in `fontFamily` are temporarily removed until the webfont
* resources are fully loaded.
*
* Call this method, if a terminal with webfonts is stuck with broken
* glyph metrics.
*
* The returned promise will resolve, when font loading and layouting are done.
*/
public relayout(): Promise<void>;
}
/**
* Wait for webfont resources to be loaded.
*
* Without any argument, all fonts currently listed in
* `document.fonts` will be loaded.
* For a more fine-grained loading strategy you can populate
* the `fonts` argument with:
* - font families : loads all fontfaces in `document.fonts`
* matching the family names
* - fontface objects : loads given fontfaces and adds them to
* `document.fonts`
*
* The returned promise will resolve, when all loading is done.
*/
function loadFonts(fonts?: (string | FontFace)[]): Promise<FontFace[]>;
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Copyright (c) 2024 The xterm.js authors. All rights reserved.
* @license MIT
*/
const path = require('path');
const addonName = 'WebFontsAddon';
const mainFile = 'addon-web-fonts.js';
module.exports = {
entry: `./out/${addonName}.js`,
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
use: ["source-map-loader"],
enforce: "pre",
exclude: /node_modules/
}
]
},
output: {
filename: mainFile,
path: path.resolve('./lib'),
library: addonName,
libraryTarget: 'umd',
// Force usage of globalThis instead of global / self. (This is cross-env compatible)
globalObject: 'globalThis',
},
mode: 'production'
};
+1 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@xterm/addon-web-links",
"version": "0.11.0",
"version": "0.12.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
@@ -21,9 +21,5 @@
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package",
"start": "node ../../demo/start"
},
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
}

Some files were not shown because too many files have changed in this diff Show More