Compare commits
251 Commits
2c3c73e5b9
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2368091d93 | |||
| 1afc896cab | |||
| e3d44f24c0 | |||
| 496c93774f | |||
| c6901eaaa6 | |||
| ce434a1c17 | |||
| 846803a3e2 | |||
| 448c3bf477 | |||
| 815fcccbe8 | |||
| c1bff63111 | |||
| c88582f2ba | |||
| 6b04b6f0ac | |||
| c12d98e348 | |||
| e6d94dcb41 | |||
| ac5c64981d | |||
| 8f4e0fa7fb | |||
| 03931496bf | |||
| ea7c240eb6 | |||
| fbcb519e13 | |||
| 37b47ebc8a | |||
| 5c08aa0a67 | |||
| 0202644efa | |||
| bd71d463a4 | |||
| 6a359cc351 | |||
| cce3b1e469 | |||
| 31203889bb | |||
| 2727425518 | |||
| 33a8c423ac | |||
| 759947736e | |||
| a5a246db77 | |||
| eae3bdba16 | |||
| 4fb1be7972 | |||
| 8f8d96ead9 | |||
| ea04e30072 | |||
| fe039e75c8 | |||
| b062a79bb5 | |||
| 3c270ed7b5 | |||
| a28444a9f2 | |||
| d8cfd27ee6 | |||
| e310b76794 | |||
| 074df97c02 | |||
| 00207b5526 | |||
| a5f92452b3 | |||
| f942f881e6 | |||
| 011dd7cc49 | |||
| 0a01d9a361 | |||
| 5d75964ee2 | |||
| 5697a08c0a | |||
| 2cb3736b92 | |||
| e9a757adc5 | |||
| d8be35e3bd | |||
| b9f29d258c | |||
| adbd2c3f81 | |||
| 02d1422a04 | |||
| 67b42c0d93 | |||
| 14abdfd2cf | |||
| 66250d6c40 | |||
| befa432095 | |||
| 8174e81c5c | |||
| 4511bc2df9 | |||
| a1fdc1e1b0 | |||
| 53c37e6209 | |||
| 2772e6878a | |||
| de6a57e67d | |||
| a6310594c5 | |||
| 6ae8bf06a8 | |||
| b558f82094 | |||
| ef1c377167 | |||
| 0c7abc17fe | |||
| 5b8f8c3f07 | |||
| 2259d61633 | |||
| 9a24302b4e | |||
| 2376a37e5d | |||
| 4cc0453344 | |||
| d67b874b87 | |||
| 0446ec86c7 | |||
| 930735c537 | |||
| 92e1e6e8fd | |||
| a664b807b3 | |||
| c689d9e782 | |||
| 7b950210b8 | |||
| d654522ad4 | |||
| 682427324d | |||
| e37fa509c9 | |||
| d1048df345 | |||
| 284ddd3713 | |||
| 5a8c37b2f2 | |||
| 08fdf2bd0f | |||
| 60a12110fa | |||
| 1df9e66cd5 | |||
| a3be494d57 | |||
| c32d4a7590 | |||
| 1a02502488 | |||
| a93afc7d16 | |||
| 39fd3a669b | |||
| a43094dda3 | |||
| 75dc31b66f | |||
| 16490942d6 | |||
| 3a7e2074b4 | |||
| f5c6d098f8 | |||
| adc44d22db | |||
| de62467208 | |||
| 7b3b3866fd | |||
| 2fd240aca8 | |||
| 08db1801eb | |||
| 5396968b08 | |||
| 168e12160a | |||
| 4aff22377f | |||
| ef4c38d8a7 | |||
| f2d505b952 | |||
| a3aef713e2 | |||
| dcfa50319c | |||
| f26237af78 | |||
| 1cb9a0ddfc | |||
| 77a9111f45 | |||
| 6b27fab075 | |||
| 0000089f42 | |||
| 5243de66fe | |||
| af6496bd5a | |||
| 15968a328c | |||
| 8a1e98819c | |||
| c5f80f27a6 | |||
| 5580d6fbd4 | |||
| 6a43fb9e0c | |||
| 86718221c4 | |||
| a8428f9dde | |||
| cd427f74dc | |||
| 11b31d2621 | |||
| adcc4f2656 | |||
| 2357b5be46 | |||
| e2f33519d1 | |||
| b58fb085a3 | |||
| 00628e0efd | |||
| 142b00118a | |||
| 9526876b04 | |||
| e90d1c3945 | |||
| fd59c05f80 | |||
| 55cdee1a13 | |||
| e84d70463f | |||
| 983f43e710 | |||
| 99fa5a2aff | |||
| e3e087f16f | |||
| 33942b2671 | |||
| 0eec3fc3b9 | |||
| 9d6a0eaeca | |||
| f5ba61624f | |||
| bfdb7c544f | |||
| b16232aa1d | |||
| 8f87b8d3d1 | |||
| 38fcf86195 | |||
| c912abaf17 | |||
| c4f72a45ba | |||
| e36c28c981 | |||
| 7a3c27c30e | |||
| 5382307fcc | |||
| 002f071b0f | |||
| 9f33104cb2 | |||
| b94739183d | |||
| 8c5d218c11 | |||
| d7fbf9a144 | |||
| 6c254f9b0d | |||
| fafec2a6b0 | |||
| d1855dbdb7 | |||
| c35abe0f03 | |||
| d85998e1cb | |||
| 298d586c3e | |||
| bb5c247ab2 | |||
| 1cd56cf3f6 | |||
| 2260817fc0 | |||
| 5e6b602127 | |||
| 971866388c | |||
| 526e243a5f | |||
| 1fd5f98256 | |||
| d64704d4eb | |||
| 9f1ea04f4d | |||
| 054225686e | |||
| 6b7cfdea20 | |||
| 1b8b669ca0 | |||
| 6eb99a792a | |||
| 406f45c6fb | |||
| 7bc5eab22f | |||
| 684ba46a2c | |||
| 52915ffacf | |||
| 8c6a050171 | |||
| 0d3fbc01f8 | |||
| 4cfd068f1c | |||
| d55b7b65d2 | |||
| 05d62aa4a5 | |||
| 393791ab7e | |||
| 9dd6a666d0 | |||
| f85f84a5d1 | |||
| b733446c8b | |||
| d92140afea | |||
| fc382529c5 | |||
| b72a3e206f | |||
| 9f4488c771 | |||
| b41db31831 | |||
| 5bf1f1df59 | |||
| ffdd42fcce | |||
| d6f6203fb6 | |||
| a80f97309b | |||
| a69372fb6e | |||
| 812152fd96 | |||
| aaaa3875aa | |||
| 2756b79f89 | |||
| 503342bff0 | |||
| f595455479 | |||
| ad9b214b8f | |||
| 0b7d4d2c1f | |||
| 1f625a69c4 | |||
| 2e05725a38 | |||
| 7b4bc80538 | |||
| 165930fc1e | |||
| 843e4b9852 | |||
| 0d4601b612 | |||
| 0ca0d89b9e | |||
| 5186714ef5 | |||
| f43a43fd53 | |||
| fc960ea0bf | |||
| 976cfc9e62 | |||
| 86d22d4fa2 | |||
| 54bb196192 | |||
| 9a34669c08 | |||
| 704dce2539 | |||
| 5e0700bb8c | |||
| de47bf6370 | |||
| 1611af2901 | |||
| db5d417a17 | |||
| 2f595ca4ca | |||
| 83c37f5a19 | |||
| 81a2bf9a02 | |||
| f6da7922a1 | |||
| 3f05287d79 | |||
| 4e9378816e | |||
| 232be6a032 | |||
| b6059d5ed9 | |||
| 9d3b25e9d3 | |||
| 287865735f | |||
| 27b94744f0 | |||
| dc0bdd60d0 | |||
| 99028daa9d | |||
| 6152ae6d36 | |||
| d8e2425c65 | |||
| 455108a909 | |||
| 05c044bd02 | |||
| d310be6e6e | |||
| 9a96706c36 | |||
| 2264dcb6e9 | |||
| fcfdc6516d | |||
| d418d670ee | |||
| 548711980c |
@@ -7,3 +7,8 @@ Style/StringLiterals:
|
||||
|
||||
Style/StringLiteralsInInterpolation:
|
||||
EnforcedStyle: double_quotes
|
||||
|
||||
Metrics/BlockLength:
|
||||
AllowedMethods:
|
||||
- refine
|
||||
- Vamp.configure
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Revision descriptions
|
||||
|
||||
Use concise revision descriptions without a `(TODO.md)` suffix. Include a ticket ID only when the task has a real ticket.
|
||||
|
||||
# Compatibility
|
||||
|
||||
Vamp is a single-user, pre-alpha tool. Prefer clean cutovers to the simplest current design across code, configuration, interfaces, and persisted formats. Update callers and remove obsolete paths together; add backwards compatibility or migrations only when explicitly requested.
|
||||
|
||||
Report incompatible persisted data clearly and preserve it unless the user explicitly requests a reset or deletion.
|
||||
|
||||
# Tests
|
||||
|
||||
Keep project tests and test-only fixtures/helpers under `tests/`. `src/` may retain test-module declarations and minimal test hooks; keep test bodies outside implementation files and preserve private access rather than widening production APIs.
|
||||
|
||||
When adding or moving tests, follow [test organization](docs/development.md#test-organization) for module wiring and verification.
|
||||
+9
-1
@@ -23,10 +23,18 @@ The presentation and input experience through which a user interacts with an edi
|
||||
**Capability**:
|
||||
A named frontend ability required by a feature for compatibility, not a permission granted to that feature.
|
||||
|
||||
**Canonical Ex command**:
|
||||
The full command name of a command-capable core action, without its `core.` prefix. For example, `core.quit` names the canonical `quit` command.
|
||||
|
||||
**Command alias**:
|
||||
A shorthand spelling of a canonical Ex command, such as `q` for `quit`. An alias refers to the same action, not a separate command implementation.
|
||||
|
||||
**Conflict History**:
|
||||
A read-only comparison of selected original conflict inputs against a shared base, separate from the editable resolution Draft.
|
||||
|
||||
## Configuration interfaces
|
||||
|
||||
- Prefer typed objects for editor-owned actions, modes, and other closed sets. Expose new core binding targets through `config.core` rather than requiring command-name strings.
|
||||
- `src/editor.rs`'s `CORE_ACTIONS` is authoritative for core action names and eligibility. Ruby action methods and nested namespaces are generated from its startup catalog; add or rename actions there rather than maintaining a second Ruby list.
|
||||
- Use strings for open-ended identifiers: language IDs, paths, and external plugin command names. Interactive Ex command names remain textual.
|
||||
- Ruby action/mode objects provide validation during configuration evaluation and discoverable members, not compile-time enum safety.
|
||||
|
||||
|
||||
Generated
+227
-2
@@ -79,6 +79,9 @@ name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
@@ -148,6 +151,16 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "codebook-tree-sitter-typst"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f785ad90ce80edd9e8b3d00890af0bc163e9a2c38f03daa18aede98d343d093"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compact_str"
|
||||
version = "0.9.1"
|
||||
@@ -180,6 +193,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "critical-section"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
@@ -208,18 +227,24 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
[[package]]
|
||||
name = "crossterm"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bitflags 2.13.2",
|
||||
"crossterm_winapi",
|
||||
"derive_more",
|
||||
"document-features",
|
||||
"filedescriptor",
|
||||
"futures-core",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serial_test",
|
||||
"signal-hook",
|
||||
"signal-hook-mio",
|
||||
"temp-env",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
@@ -370,6 +395,18 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fancy-regex"
|
||||
version = "0.11.0"
|
||||
@@ -427,6 +464,17 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-executor"
|
||||
version = "0.3.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
@@ -513,6 +561,15 @@ dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
@@ -640,6 +697,17 @@ version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.38.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "line-clipping"
|
||||
version = "0.3.8"
|
||||
@@ -804,6 +872,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "numtoa"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -977,6 +1051,12 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
@@ -1053,6 +1133,7 @@ dependencies = [
|
||||
"ratatui-core",
|
||||
"ratatui-crossterm",
|
||||
"ratatui-termina",
|
||||
"ratatui-termion",
|
||||
"ratatui-termwiz",
|
||||
"ratatui-widgets",
|
||||
"serde",
|
||||
@@ -1066,6 +1147,7 @@ checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"compact_str",
|
||||
"critical-section",
|
||||
"hashbrown 0.17.1",
|
||||
"itertools",
|
||||
"kasuari",
|
||||
@@ -1102,6 +1184,17 @@ dependencies = [
|
||||
"termina",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ratatui-termion"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "87c732202fa5a71a9da0991013f0853e53f87048f45198e3a1ca3ee722accc2f"
|
||||
dependencies = [
|
||||
"instability",
|
||||
"ratatui-core",
|
||||
"termion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ratatui-termwiz"
|
||||
version = "0.1.2"
|
||||
@@ -1170,6 +1263,31 @@ version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rsqlite-vfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
|
||||
dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.40.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
@@ -1213,12 +1331,27 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scc"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc"
|
||||
dependencies = [
|
||||
"sdd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "sdd"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
@@ -1269,6 +1402,32 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serial_test"
|
||||
version = "3.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d0b343e184fc3b7bb44dff0705fffcf4b3756ba6aff420dddd8b24ca145e555"
|
||||
dependencies = [
|
||||
"futures-executor",
|
||||
"futures-util",
|
||||
"log",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"scc",
|
||||
"serial_test_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serial_test_derive"
|
||||
version = "3.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f50427f258fb77356e4cd4aa0e87e2bd2c66dbcee41dc405282cae2bfc26c83"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -1317,6 +1476,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "similar"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
|
||||
|
||||
[[package]]
|
||||
name = "siphasher"
|
||||
version = "1.0.4"
|
||||
@@ -1335,6 +1500,18 @@ version = "1.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
|
||||
|
||||
[[package]]
|
||||
name = "sqlite-wasm-rs"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"js-sys",
|
||||
"rsqlite-vfs",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stacker"
|
||||
version = "0.1.25"
|
||||
@@ -1420,6 +1597,15 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "temp-env"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96374855068f47402c3121c6eed88d29cb1de8f3ab27090e273e420bdabcf050"
|
||||
dependencies = [
|
||||
"parking_lot",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termina"
|
||||
version = "0.3.3"
|
||||
@@ -1445,6 +1631,16 @@ dependencies = [
|
||||
"phf_codegen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termion"
|
||||
version = "4.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"numtoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termios"
|
||||
version = "0.3.3"
|
||||
@@ -1620,6 +1816,14 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-honey"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-html"
|
||||
version = "0.23.2"
|
||||
@@ -1736,6 +1940,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-zig"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab11fc124851b0db4dd5e55983bbd9631192e93238389dcd44521715e5d53e28"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@@ -1799,17 +2013,21 @@ dependencies = [
|
||||
name = "vamp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"codebook-tree-sitter-typst",
|
||||
"crossterm",
|
||||
"ignore",
|
||||
"ratatui",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"similar",
|
||||
"tree-sitter",
|
||||
"tree-sitter-bash",
|
||||
"tree-sitter-c",
|
||||
"tree-sitter-cpp",
|
||||
"tree-sitter-css",
|
||||
"tree-sitter-go",
|
||||
"tree-sitter-honey",
|
||||
"tree-sitter-html",
|
||||
"tree-sitter-javascript",
|
||||
"tree-sitter-json",
|
||||
@@ -1821,10 +2039,17 @@ dependencies = [
|
||||
"tree-sitter-toml-ng",
|
||||
"tree-sitter-typescript",
|
||||
"tree-sitter-yaml",
|
||||
"tree-sitter-zig",
|
||||
"unicode-segmentation",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
|
||||
+14
-1
@@ -6,9 +6,11 @@ edition = "2024"
|
||||
[dependencies]
|
||||
crossterm = "0.29"
|
||||
ignore = "0.4"
|
||||
ratatui = { version = "0.30", default-features = false, features = ["crossterm_0_29", "underline-color"] }
|
||||
ratatui = { version = "0.30", default-features = false, features = ["crossterm_0_29", "layout-cache", "underline-color", "unstable-backend-writer", "unstable-rendered-line-info"] }
|
||||
rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
similar = { version = "2", default-features = false }
|
||||
tree-sitter = "0.27.1"
|
||||
tree-sitter-bash = "0.25.1"
|
||||
tree-sitter-c = "0.24.2"
|
||||
@@ -16,6 +18,7 @@ tree-sitter-cpp = "0.23.4"
|
||||
tree-sitter-css = "0.25.0"
|
||||
tree-sitter-go = "0.25.0"
|
||||
tree-sitter-html = "0.23.2"
|
||||
tree-sitter-honey = { path = "vendor/tree-sitter-honey" }
|
||||
tree-sitter-javascript = "0.25.0"
|
||||
tree-sitter-json = "0.24.8"
|
||||
tree-sitter-make = "1.1.1"
|
||||
@@ -24,7 +27,17 @@ tree-sitter-python = "0.25.0"
|
||||
tree-sitter-ruby = "0.23.1"
|
||||
tree-sitter-rust = "0.24.2"
|
||||
tree-sitter-toml-ng = "0.7.0"
|
||||
tree-sitter-typst = { package = "codebook-tree-sitter-typst", version = "=0.12.1" }
|
||||
tree-sitter-typescript = "0.23.2"
|
||||
tree-sitter-yaml = "0.7.2"
|
||||
tree-sitter-zig = "1.1.2"
|
||||
unicode-segmentation = "1.12"
|
||||
unicode-width = "0.2"
|
||||
|
||||
[patch.crates-io]
|
||||
# Remove once upstream Crossterm decodes DEC 2031 color-scheme notifications.
|
||||
crossterm = { path = "vendor/crossterm" }
|
||||
|
||||
[workspace]
|
||||
members = ["vendor/crossterm"]
|
||||
default-members = ["."]
|
||||
|
||||
@@ -13,21 +13,61 @@ cargo run -- --config examples/config.rb notes.txt
|
||||
|
||||
Without a file, vamp opens an unnamed buffer. A nonexistent file opens an empty buffer. `cargo run -- --help` lists the command-line options.
|
||||
|
||||
### Manage local reviews without opening the editor
|
||||
|
||||
```sh
|
||||
vamp --review list --repo .
|
||||
vamp --review list --repo . --json
|
||||
vamp --review show 1 --repo . --json
|
||||
vamp --review show 1 --repo . --all
|
||||
vamp --review delete 1 3 --repo . # Delete comment 3 from review 1
|
||||
vamp --review resolve 1 3 --repo . # Mark comment 3 resolved, preserving its feedback
|
||||
```
|
||||
|
||||
The review CLI discovers the Git/Jujutsu checkout from `--repo` (default: current directory). It uses the same default configuration, `--config PATH`, `--no-config`, and `review_directory` as the editor, but starts no editor workers or terminal UI. Missing storage lists no reviews without creating a database; incompatible storage is rejected and preserved.
|
||||
|
||||
Local reviews are scoped to the canonical checkout and ordered, resolved Before/After pair. Opening a different comparison selects its own review; reopening the same pair resumes its feedback and progress. In-place Working refreshes retain the active review. Ordinary source-buffer comments use separate source reviews. CLI listings identify each review's scope; JSON exposes it as `comparison` (an endpoint pair, or `null` for source reviews).
|
||||
|
||||
Review storage now uses SQLite schema 4 and JSON export version 5. Older formats are rejected and preserved without migration or reset.
|
||||
|
||||
Use the persistent **Review ID** printed by `list`, not a list position. IDs are shared across repositories; listing filters them to the selected checkout, so its first review need not be ID 1. Human-readable listings include a command to show each review. The internal save revision is omitted from text but remains in JSON; it is not a Git/Jujutsu revision. `show all` is not supported: use `show ID --all` to include resolved comments in that review.
|
||||
|
||||
`show` includes unresolved comments by default; `--all` includes resolved comments too. Human-readable output is the default, with source excerpts in language-tagged Markdown code blocks. JSON includes the canonical repository root, storage review ID/revision, summary/verdict, total/resolved/unresolved counts, and comments with exact zero-based, end-exclusive grapheme anchors and raw selected source excerpts—not whole source files or Markdown fences. `list --json` returns the repository and review metadata/counts without comments. Explicit editor JSON exports still contain complete anchor source text.
|
||||
|
||||
`list` omits reviews with no comments in both text and JSON output. Reviews containing only resolved comments remain listed. Commentless reviews remain stored to preserve file checkmarks, summaries, and verdicts; the editor can still resume them, and `show ID` can inspect them directly.
|
||||
|
||||
`list` and `show` are read-only. `delete REVIEW_ID COMMENT_ID` immediately commits deletion of one resolved or unresolved comment. `resolve REVIEW_ID COMMENT_ID` instead marks that comment resolved, preserving its body and original anchor. Repeating resolution succeeds without writing or advancing the review revision. Both commands print the updated review with its remaining unresolved comments (`--json` is supported); use `show REVIEW_ID --all` to verify resolved feedback. Both IDs are required; missing reviews/comments and repository mismatches fail without changing stored reviews or creating missing storage. Deleting the last comment keeps the review, summary, and verdict. Concurrent saves use the same revision-conflict protection as the editor; an already-open editor must reload before saving after a CLI change. Existing JSON exports are not modified.
|
||||
|
||||
`vamp review` still opens a file named `review`; `vamp -- --review` opens a file named `--review`.
|
||||
|
||||
## Getting started
|
||||
|
||||
Vamp starts in Normal mode. Press `i`, type text, then Esc to return to Normal. Type `:w` and Enter to save, or `:w path` to name an unnamed buffer. Type `:q` and Enter to quit; it refuses unsaved changes in any open buffer. `:q!` explicitly discards changes and quits.
|
||||
Vamp starts in Normal mode. Press `i`, type text, then Esc to return to Normal. Type `:save` (alias `:w`) and Enter to save, or `:save path` to name an unnamed buffer. Type `:quit` (alias `:q`) and Enter to quit; it refuses unsaved changes in any open buffer. `:force_quit` (alias `:q!`) explicitly discards changes and quits.
|
||||
|
||||
| Task | Default keys |
|
||||
| --- | --- |
|
||||
| Move in Normal | `h`/`j`/`k`/`l` or arrows; `w`/`b`/`e` for words |
|
||||
| First/last line in Normal or Visual | `gt` / `gb`, at first nonblank; Visual extends the selection |
|
||||
| Enter/leave Insert | `i` / Esc |
|
||||
| Manual LSP completion in Insert | Ctrl+n starts/cycles next; Ctrl+j/k cycles next/previous, replacing text live |
|
||||
| Edit completion snippet arguments | Type to replace the highlighted argument; Tab / Shift+Tab moves next/previous |
|
||||
| Save in Normal | Space then `w`, or `:w` then Enter |
|
||||
| Undo/redo in Normal | `u` / `U` (Shift+u) |
|
||||
| Split panes in Normal | `_` above/below; `\|` left/right; Option/Alt+h/j/k/l changes focus |
|
||||
| Close a pane | `:pane.close`; `:pane.force_close` explicitly discards exclusively displayed unsaved edits |
|
||||
| Open/switch tabs in Normal | `:tab.new` opens the current buffer; Ctrl+Option/Alt+h/l switches previous/next |
|
||||
| Close a tab | `:tab.close`; `:tab.force_close` explicitly discards exclusively displayed unsaved edits |
|
||||
| Delete/change whole lines in Normal | `dd` / `cc`; leading counts work (`3dd`, `2cc`) |
|
||||
| Search in Normal | `/`, type a literal query, Enter; `n`/`N` for next/previous |
|
||||
| Select/copy/cut | `v` in Normal, move to extend, then `y`/`d` in Visual |
|
||||
| Paste in Normal | `p`/`P` after/before the caret; system clipboard by default |
|
||||
| Select/copy/cut | `v` characterwise or `V` whole rows, move to extend, then `y`/`d` in Visual |
|
||||
| Paste in Normal | `p`/`P` after/before the caret or row for linewise fragments; system clipboard by default |
|
||||
| Paste over selected text | `p` / `P` in Visual replaces every selection, preserving the clipboard |
|
||||
| Command palette | Ctrl+p; type to filter, arrows select, Enter accepts, Esc cancels |
|
||||
| Buffer picker in Normal | Space then `b l` or `:buffers`; type to search, arrows select, Enter switches, Esc cancels |
|
||||
| Floating/docked explorer in Normal or Visual | Space then `o` / Space then `e` |
|
||||
| Repository diff in Normal | `:diff`; choose Before then After, Tab changes category, type to search; Esc closes the selector; Working or checkout-matched pinned After is editable; `:diff.close` exits the comparison |
|
||||
| Diff layout in Normal | Space then `v` cycles split/unified; Space then `s` flips left/right vs above/below split |
|
||||
| Resolve jj working-copy conflicts | `:resolve`; edit marker-free Draft versus Alternative, `:resolve.history` for inputs/base, `:w` to save and confirm with jj |
|
||||
|
||||
Space is the default leader: press its suffix keys in order, not simultaneously. The [editing guide](docs/editing.md) contains the complete key table and behavior reference.
|
||||
|
||||
@@ -41,9 +81,9 @@ Ruby configuration and plugins run with your account's filesystem/process permis
|
||||
|
||||
## Current limits
|
||||
|
||||
- One visible buffer at a time; no splits/tabs or graphical frontend.
|
||||
- Modal editing, not full Vim compatibility: characterwise Visual selections, but no line/block selection, named registers, or Vim operators. Search is literal, case-sensitive, and single-line.
|
||||
- Native opt-in LSP supports diagnostics, go-to-definition, and plain-text hover—not completion, rename, formatting, or code actions.
|
||||
- Terminal frontend only; no graphical frontend.
|
||||
- Modal editing, not full Vim compatibility: characterwise and linewise Visual selections and counted `dd`/`cc`, but no block selection, named registers, or general operator–motion grammar. Search is literal, case-sensitive, and single-line.
|
||||
- Native opt-in LSP supports diagnostics, go-to-definition, plain-text hover, manual primary-caret completion with snippet arguments, and automatic semantic highlighting—not rename, formatting, or code actions. Completion has no automatic popup or acceptance step; other carets are preserved and translated through the chosen edits. Snippet regex transforms and unresolved variables without defaults are omitted.
|
||||
- System clipboard access supports macOS and Linux. Separate clipboard mode keeps internal editing available on unsupported/headless environments.
|
||||
|
||||
Performance and subprocess limits are documented in [development](docs/development.md#performance-and-process-limits).
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
- [x] improve: diff picker - if jj managed, present as jj log.
|
||||
- this makes it much easier to determine which revisions to actually pick for before/after
|
||||
- the bookmarks only view could simply filter out unbookmarked revisions but otherwise display in the same way
|
||||
- [ ] feature: diff view - GitHub code review integration after the local review UX is usable.
|
||||
- publish local reviews explicitly: general PR comments, inline line/range comments, review summaries, approval, and requests for changes.
|
||||
- preserve explicit PR identity and reviewed commit IDs; validate anchors against GitHub's PR diff and recheck the PR head before submission.
|
||||
- keep authentication, network requests, publishing, and remote thread synchronization out of the local UX work; treat timed-out writes as unknown outcomes rather than automatically retrying.
|
||||
- define follow-on scope for reading/replying to remote threads, editing/deleting published comments, and resolving threads.
|
||||
- [ ] chore: take a look at the configuration options and their names, and consider whether renaming some of them is warranted, as well as maybe nesting some under some common namespace (like some already are).
|
||||
- [ ] chore: remove the diff palette polling fallback once a released Herdr fix delivers palette-ready DEC 2031 notifications, including palette-only changes with an unchanged light/dark preference. Related upstream issue: [herdrdev/herdr#4183](https://github.com/herdrdev/herdr/issues/4183).
|
||||
- verify that notification-triggered queries return fresh colors in Ghostty through Herdr before removal; retain startup, focus-regain, and notification-driven palette refresh.
|
||||
- [ ] feature: pull a pr description and display it in a buffer:
|
||||
- open a selector that allows you to pick a pr from remote
|
||||
- selector should be searchable
|
||||
- selected pr description is opened in a separate buffer/tab.
|
||||
- open related pr description directly from diff view (should be able to figure out the relevant pr from the branch involved in the diff - if jj, then from tracked bookmark; if just git, then from branch)
|
||||
- [ ] feature: sandboxed, revision-specific LSP analysis for historical diff states and historical tabs.
|
||||
- current limitation: immutable snapshot buffers still use the live repository as their LSP workspace; cross-file analysis can mix historical text with current disk contents.
|
||||
- lazily materialize the complete selected revision, including unchanged files, manifests, and project configuration; run a separate LSP instance rooted in that snapshot.
|
||||
- mount historical source read-only and provide isolated writable scratch directories for caches, indexes, and build output; keep historical navigation targets read-only.
|
||||
- enforce an OS-level sandbox on the LSP process and every child it spawns, including build scripts and procedural macros. A temporary checkout and read-only editor buffers are not security isolation.
|
||||
- deny access to the live checkout, home directory, credentials, and SSH agent; deny network access by default. Additional access or code-execution permissions require explicit approval.
|
||||
- fail closed: if these restrictions cannot be enforced, keep read-only viewing available but do not launch historical LSP analysis; never silently fall back to an unrestricted process.
|
||||
- retain the snapshot and analysis environment while historical views/tabs reference it; stop workers and clean up disposable storage after the final reference closes.
|
||||
@@ -0,0 +1,53 @@
|
||||
Vamp.configure do |config|
|
||||
config.lsp.merge!(
|
||||
"rust" => true,
|
||||
"ruby" => true,
|
||||
"python" => true,
|
||||
)
|
||||
|
||||
# fallback tab spaces
|
||||
config.tab_spaces = 4
|
||||
|
||||
# language specific tab spaces
|
||||
config.language_tab_spaces.merge!(
|
||||
"rust" => 4,
|
||||
"ruby" => 2,
|
||||
"makefile" => nil,
|
||||
)
|
||||
|
||||
# 0 (default): scroll only at viewport edges
|
||||
# nil: center; oversized integer margins also center
|
||||
config.scroll_distance = 7
|
||||
config.scroll_step_lines = 3
|
||||
|
||||
config.highlight_trailing_whitespace = true
|
||||
|
||||
#config.whitespace_scope = "leading" # or "all" (default)
|
||||
#config.whitespace_characters = {
|
||||
# " " => "·",
|
||||
# "\t" => "→",
|
||||
# "\n" => "↵",
|
||||
#}
|
||||
|
||||
# "bar" (default), "symbols", "line_numbers", "none"
|
||||
config.git_gutter = "bar"
|
||||
|
||||
# diff view
|
||||
config.diff_context_lines = 10
|
||||
config.diff_expand_lines = 15
|
||||
|
||||
# general bindings
|
||||
config.bind "leader q", config.core.pane.close
|
||||
config.bind "leader t w", config.core.word_wrap.toggle
|
||||
|
||||
# pane navigation
|
||||
config.bind "ctrl+w h", config.core.pane.focus_left
|
||||
config.bind "ctrl+w j", config.core.pane.focus_down
|
||||
config.bind "ctrl+w k", config.core.pane.focus_up
|
||||
config.bind "ctrl+w l", config.core.pane.focus_right
|
||||
|
||||
# lsp bindings
|
||||
config.bind "K", config.core.lsp.hover
|
||||
config.bind "leader d", config.core.lsp.definition
|
||||
config.bind "leader D", config.core.lsp.diagnostics
|
||||
end
|
||||
+111
-20
@@ -6,52 +6,143 @@ Contributor-facing module boundaries and implementation contracts. Project termi
|
||||
|
||||
## Module ownership
|
||||
|
||||
One crate; no workspace or terminal-coordinate types in the editing backend:
|
||||
One editor crate; the workspace also includes its patched Crossterm dependency. Terminal-coordinate types remain outside the editing backend:
|
||||
|
||||
- `editor`: owns buffer lifecycle and per-buffer text, saved state, primary/selection set, modes, search, and undo/redo; session-wide clipboard policy, independent registers and owned-system fragment metadata, semantic native repeat, action metadata, command-palette and file-picker focus/dispatch, key notation, leader/count prefixes and binding resolution, modal paste policy, saving, command ownership, capabilities, and validated edit effects. Its low-level interface returns an `Invocation` when an external command is selected.
|
||||
- `editor`: owns shared buffer lifecycle/text/saved state/undo history and independent tab/pane layouts, focused views, modes, selections, searches, explorers, and comparisons; session-wide clipboard policy, independent registers and owned-system fragment metadata, semantic native repeat, action metadata, command-palette and file-picker focus/dispatch, key notation, key-sequence/count prefixes and binding resolution, modal paste policy, saving, command ownership, capabilities, and validated edit effects. Its low-level interface returns an `Invocation` when an external command is selected.
|
||||
- `chrome`: owns validated top/bottom bar anchor groups, segment title templates and padding/edge options, builtin defaults, named-value validation, and typed command/search popup anchors. Both bars accept the same segments and layout options. It has no terminal geometry or render callbacks.
|
||||
- `battery`: reads native charge off the input thread, sampling immediately and every 30 seconds through an interruptible worker. macOS CoreFoundation references are type-checked and owned Copy/Create values released; Linux reads system battery sysfs and Windows reads native power status. A one-slot atomic mailbox retains the latest sample; absent/invalid readings clear cached presentation instead of inventing a percentage. Session starts collection only while an unoverridden battery segment is configured.
|
||||
- `shell`: runs explicit `:!` commands off the input thread with inherited environment, closed stdin, and bounded stdout/stderr capture. Each command has a private Unix process group, killed and reaped on worker drop or shell completion. Session owns concurrent workers and combines their delayed spinners in one shared status segment; Editor owns the read-only output popup, queued completed results, and modal scrolling/dismissal state. No repository-command environment overrides or timeouts apply.
|
||||
- `blame`: owns current-line Git attribution against supplied in-memory text and a cancellable background worker. Historical buffers capture their exact Git store, commit, and side-specific path; private stores remain alive while snapshots or requests reference them. Git-backed jj uses an isolated temporary Git store; active refs/checkouts remain untouched.
|
||||
- `files`: owns the gitignore-aware directory/file catalog, authoritative OS paths, compact tree projection, query filtering, browse/search focus, expansion/selection restoration, navigation, and scan/error state shared by floating and docked presentations.
|
||||
Virtual diff leaves retain their original catalog input index for caller-owned annotations. Normal scanned leaves accept optional repository status and old-path metadata without filtering unchanged files; missing tracked deletions add virtual leaves and required directories. Metadata-only updates preserve query, selection, expansion, and view without rebuilding the catalog.
|
||||
- `diff`: owns searchable Before/After selection, category, focus and explorer visibility, request freshness, read-only comparison DTOs, aligned rows with cached grapheme-level change ranges, and shared vertical/independent horizontal offsets. Changed paths form a virtual `files::FilePicker` catalog, reusing the normal tree projection, filtering, and navigation without scanning disk. It has no subprocess or terminal dependencies.
|
||||
- `repository`: discovers jj/Git repositories and local/advertised remote revisions, builds disk snapshots and changed-file hunks, and owns isolated temporary comparison repositories with bounded, cancellable subprocesses. It never saves editor buffers or modifies active refs/checkouts.
|
||||
- `review`: owns the validated local review model, exact immutable anchors, persisted file checkmarks, SQLite storage through bundled rusqlite, and atomic JSON import/export with external-change protection. Schema 4 stores review identity, repository, revision, summary, verdict, and nullable ordered comparison endpoints in `reviews`; null endpoints identify source reviews. `comments` stores ordered comment IDs, bodies, resolution states, and explicit immutable anchor fields. `reviewed_files` stores revision pairs, paths, optional old paths, and optional exact live After text. Foreign keys, unique keys, and checks enforce relationships and scalar invariants. Full `u64` comment IDs use checked decimal text because SQLite integers are signed. No JSON documents are stored in SQLite.
|
||||
`Store` retains compare-and-swap review revisions and atomic whole-review saves: metadata and replacement comment/checkmark rows commit together. A stored review cannot be reassigned to another scope. Read transactions reconstruct validated reviews from one consistent snapshot, including when listing in descending ID order. Stored text is bounded to 64 MiB per review, including a fixed per-comment/checkmark overhead. JSON version 5 is an independent import/export format. Incompatible databases, including schema 3, are rejected and preserved without migration or reset. CLI metadata and selectors reuse loaded reviews; selector choices live only in the displayed buffer.
|
||||
The review CLI keeps `list`/`show` read-only. Comment deletion and resolution validate the explicit review/comment IDs through an existing read-only store before opening it for a compare-and-swap save; absent storage and invalid targets do not create reviews or a database. Resolution preserves comment bodies and immutable anchors; already-resolved comments succeed without writing or advancing the revision.
|
||||
CLI listings exclude reviews with zero comments, not reviews with zero unresolved comments. Filtering stays at the CLI boundary: storage listing and editor restoration retain commentless reviews and their file checkmarks, summaries, and verdicts.
|
||||
`editor_review` owns tab-local review state selected by canonical repository root and ordered resolved comparison identities, or a separate source scope for ordinary repository buffers. A sole scope-matching review restores automatically; multiple matches open the floating selector. `diff` freezes initial review endpoints through in-place Working refreshes; explicit comparisons and moved bookmark endpoints resolve their own scope. Source and comparison panes share the comment editor, immutable anchors, storage, and review commands, not their review documents. Dirty drafts block scope changes, and stored/JSON opens reject mismatched scopes before replacing state. Comment/summary text saves explicitly; dismissing discards that editor's unsaved text, while switching may retain hidden drafts. Verdicts/deletions/resolution changes commit immediately without saving drafts. Exports retain their own file baseline and do not become automatic persistence targets; imports get fresh database identities. Review editors remain tab-owned native panes outside the workspace `PaneTree`. The session supplies the configured or XDG default directory; direct `Editor` callers inject a directory with `set_review_directory` to enable persistence.
|
||||
Successful SQLite autosaves and JSON-only saves share one acknowledgement operation: clear review dirtiness and advance the owning tab's native draft saved baselines only after persistence succeeds. Failed writes retain unsaved state; JSON exports do not acknowledge a pending SQLite save.
|
||||
Review replacement and comment deletion are private editor-owned operations. Replacement loads and validates its Stored/JSON/New source before retiring old bindings, installing the document, and resetting selection/navigation. Deletion retires and acknowledges only the matching comment drafts, preventing stale text from overwriting reused IDs. Both persist before opening the overview; a post-mutation save failure retains the applied, unsaved identity change. Native text/undo and general transition guards remain unchanged.
|
||||
- `clipboard`: owns native plain-text provider selection and bounded subprocess I/O; it never computes selections or editing offsets.
|
||||
- `syntax`: owns Tree-sitter grammar detection, per-buffer incremental trees, bundled highlight/local/injection queries, and semantic byte spans; it has no terminal color/geometry or editing dependency.
|
||||
- `plugin`: owns generic document snapshots/events, zero-based grapheme positions, diagnostics, and versioned asynchronous update contracts. It has no LSP protocol types.
|
||||
- `lsp`: owns opt-in native server workers, bounded framed JSON-RPC, synchronization/capability negotiation, settings, UTF-16/file-URI conversion, and definition/hover results. Its private configuration resolver supplies presets without restricting language IDs.
|
||||
- `session`: `EditorSession` owns the editor, native LSP, and Ruby hosts together. It loads configuration once, registers eligible plugins before installing shared bindings, tracks document open/change/save/close events, polls native and plugin results, validates versioned diagnostics/navigation, and retires failed plugin ownership.
|
||||
- `tui`: translates terminal events to session input, renders read-only active-buffer state, keeps frontend-owned viewports and syntax caches by stable buffer ID, and advertises `text`, `styled_text`, and `diagnostics` capabilities. It maps semantic tokens and diagnostics to terminal styling and has no server/protocol logic or paste acceptance policy.
|
||||
- `syntax`: owns Tree-sitter grammar detection, per-buffer incremental trees, bundled highlight/local/injection queries, and syntax byte spans; it has no terminal color/geometry or editing dependency.
|
||||
- `markdown`: owns native Markdown link/reference resolution, local destination decoding, and heading fragment lookup through the installed block/inline grammars. It has no editor lifecycle, terminal, LSP, or external-process dependency.
|
||||
- `plugin`: owns generic document snapshots/events, zero-based grapheme positions, diagnostics, frontend-independent semantic token kinds/modifiers and completion edit/item DTOs, and versioned asynchronous update contracts. Semantic token and completion updates are native-only, not part of the Ruby wire protocol; it has no LSP protocol types.
|
||||
- `lsp`: owns opt-in native server workers, bounded framed JSON-RPC, synchronization/capability negotiation, settings, UTF-16/file-URI conversion, definition/hover results, completion decoding, and semantic token requests/legend decoding. Its private configuration resolver supplies presets without restricting language IDs.
|
||||
- `snippet`: owns bounded, frontend-independent template parsing and expansion into plain replacement text and byte-relative tabstops with per-occurrence ancestry. It never edits documents or owns input policy.
|
||||
- `session`: `EditorSession` owns the editor, native LSP, and Ruby hosts together. It loads configuration once, registers eligible plugins before installing shared bindings, tracks document open/change/save/close events, polls native and plugin results, validates versioned diagnostics/navigation/completion, and retires failed plugin ownership. Each tab with a comparison has a cancellable repository worker; inactive tabs keep their workers and receive tagged results without changing visible focus. Closed or superseded comparisons reject stale results. Focused diff text supports native LSP navigation, hover, and diagnostics; read-only buffers still reject asynchronous editing effects, and selectors/file lists are not document-action targets.
|
||||
- `tui`: translates terminal events to session input, renders read-only active-buffer state, keeps frontend-owned viewports and syntax caches by stable buffer ID or immutable diff snapshot/file identity, and advertises `text`, `styled_text`, and `diagnostics` capabilities. It maps semantic tokens and diagnostics to terminal styling and has no server/protocol logic or paste acceptance policy.
|
||||
- `ruby`: evaluates configuration and runs isolated plugin hosts. Protocol, deadlines, and process cleanup stay inside this module.
|
||||
- The executable selects paths and frontend capabilities, opens an editor session, and launches the TUI.
|
||||
- The executable selects paths and frontend capabilities, opens an editor session, and launches the TUI inside a terminal guard covering startup, rendering, session teardown, and executable handoff. On restart, it drops the entire `EditorSession`, including workers and plugin hosts, then briefly disables raw mode and input reporting without leaving the alternate screen before relaunching the same executable with the original CLI arguments. Unix replaces the process with `exec`; other platforms spawn a fresh process and wait for it. Startup rereads configuration and the original startup file, or creates an unnamed buffer; current buffers, tabs, views, and session state are not restored.
|
||||
|
||||
## Frontend interface
|
||||
|
||||
Frontends drive `EditorSession::handle` or `execute`, periodically call `poll()` even without input, and inspect `editor()`; there is no mutable editor getter that could independently alter plugin registration. `poll()` reports whether background activity requires redrawing. Pasted text uses `Input::Paste(String)` through the same input seam as keys. Plugin effects are applied internally so a rejected result also retires its owner; there is no generic frontend effects entry point.
|
||||
Frontends inspect `selections()` for document-ordered, end-exclusive Visual ranges of grapheme coordinates (empty outside Visual), `carets()` for all active cursors in document order, `cursor()` for the primary, and `selection_count()` for the total target count. A range ending at the next row's column 0 includes the previous row's newline; an empty final-row range contains no text. Selection normalization, clipboard contents, edit planning, and history remain inside the editor module.
|
||||
|
||||
`Editor::should_quit()` tells the frontend to exit its input/render loop for either quit or restart; `Editor::should_restart()` distinguishes a requested executable relaunch from an ordinary exit. Normal-mode `core.restart` / `:restart` first closes clean buffers across all tabs, panes, and historical views. Remaining dirty buffers retain unsaved text and undo/redo history, block the exit/relaunch request with a warning, and leave the editor interactive; already closed clean buffers remain closed. `core.force_restart` / `:force_restart` (alias `:restart!`) requests relaunch without saving, discarding unsaved text. Both commands take no arguments and have no default binding. Force restart uses palette confirmation, while configured action bindings execute directly.
|
||||
|
||||
Session polling schedules synchronous `Editor::refresh_files()` metadata scans every 250 ms; the editor method itself is unthrottled and reports whether a redraw is needed. Scans include active and parked live buffers across inactive tabs/panes, but never immutable historical snapshots, and read content only after metadata changes. Valid changed disk text replaces only clean buffers, updates the saved baseline and text revision, clears stale undo/redo, preserves/clamps every associated view, clears diagnostics and stale requests, remaps retained semantic colors, and refreshes live comparisons. Dirty buffers keep edits; missing, unreadable, or invalid changed files preserve text and report a warning.
|
||||
|
||||
Every save independently re-reads disk content and compares its LF-normalized text with the saved baseline, rather than trusting polling or modification timestamps. Normal writes refuse external changes/deletion; newly opened nonexistent paths can be created normally. Typed `core.force_save` / `core.force_save_and_quit` expose canonical `:force_save [path]` / `:force_save_and_quit [path]` and aliases `:w!` / `:wq!`. Force bypasses only the external-change check, retaining snapshot read-only, target-symlink, and another-buffer path-ownership protections. Both save-and-quit variants quit only after a successful save and only when all buffers are clean.
|
||||
Frontends inspect `selections()` for document-ordered, end-exclusive Visual ranges of grapheme coordinates, including selections retained during command input, `carets()` for all active cursors in document order, `cursor()` for the primary, and `selection_count()` for the total target count. `visual_linewise()` and `linewise_rows()` likewise retain whole-row shape during a command prompt entered from Visual; binding modes and Ruby mode names still report Command. Linewise ranges expand to complete rows. A range ending at the next row's column 0 includes the previous row's newline; an empty final-row range contains no text. `linewise_rows()` includes an empty final row without changing `selections()` cardinality. The TUI highlights copied text and one cell per copied newline, never unused viewport space or the gutter; the mode label remains COMMAND while typing. Selection normalization, clipboard shape and contents, edit planning, and history remain inside the editor module.
|
||||
The TUI also observes the editor's logical caret-reveal generation. Core motion/navigation dispatch advances it even when the resulting position is unchanged, so a detached viewport can resume following without duplicating key-binding policy or changing text revisions and LSP freshness.
|
||||
Frontends inspect `palette()` for the optional read-only query, filtered command entries, selected index, effective bindings, and eligibility. Palette input handling and acceptance stay in the editor; registered command execution stays in the session.
|
||||
Frontends use cached `selection_navigation_hint()` for command lists and `file_navigation_hint()` for the active file view/context, without reconstructing input policy.
|
||||
Frontends inspect `count()` for the optional pending motion prefix; parsing and counted motion dispatch remain editor-owned.
|
||||
Frontends inspect `leader_pending()` for the cached display of a pending leader sequence; prefix recognition, cancellation, and dispatch remain editor-owned.
|
||||
Frontends inspect `count()` for the optional pending numeric prefix; parsing, counted motion dispatch, and counted Normal line actions remain editor-owned.
|
||||
Frontends inspect `sequence_pending()` for the cached display of a pending key sequence; prefix recognition, cancellation, and dispatch remain editor-owned. Symbolic leader routes and explicit key prefixes share the same binding storage and dispatcher; explicit prefixes do not change when the leader is reconfigured.
|
||||
Frontends inspect `g_pending()` for the built-in Normal/Visual `gt`/`gb` prefix and Normal-only `gf`. Document-edge motions share multi-target motion dispatch and viewport reveal, retaining Visual anchors and selection shape. Markdown following preflights links and headings before buffer/caret mutation; an unloaded target is validated/prepared once, while loaded targets use their current unsaved text. File identity and activation stay editor-owned.
|
||||
Frontends inspect `line_operator_pending()` for the optional Normal `d`/`c` prefix. Dedicated `dd`/`cc` actions project counted caret rows through existing linewise selection normalization, clipboard publication, and atomic range editing, without exposing a temporary Visual mode. Clipboard failures restore the original targets before returning. Repeat recipes retain the requested row count rather than the originally clamped range; change recipes share the existing Insert undo group. There is no general operator–motion parser.
|
||||
Editor-owned jump history is a bounded 100-location `VecDeque` of stable tab/pane identities, buffer IDs, grapheme cursors, and optional comparison identity/file/focus/binding metadata, with no copied paths/text. Successful high-level navigation records departure/destination once; traversal resolves a valid destination view before switching buffers, restores comparison binding and exact cursor visibility, and truncates forward entries only on a distinct new jump. Closed or replaced views fall back only to safe existing ordinary panes; history cannot resurrect a closed comparison or replace an unrelated one. Unavailable destinations are skipped without corrupting branch position. Session synchronization permanently invalidates pending LSP position requests after their source buffer/revision/caret/mode is left, so returning through history cannot revive an old definition reply.
|
||||
Frontends inspect `buffer_id()`, `buffer_count()`, `has_buffer(id)`, and the ascending-ID `buffers()` iterator of borrowed path/dirty/active metadata. Existing text, cursor, selection, search, and mode methods describe only the active buffer.
|
||||
Frontends inspect `file_picker()` for query, presentation, view, explorer-local INSERT/filter subfocus, selection, and errors, and iterate borrowed `FileRow` metadata (actual path, display label, directory flag, visible depth, expansion). Dock side is a logical preference. They allocate rectangles, add folder suffixes/colors, and render; hierarchy, filtering, parent/child navigation, focus transitions, and selected-file opening remain backend-owned.
|
||||
Frontends inspect `diagnostics()` and `diagnostic_at_cursor()` for validated active-buffer annotations. Diagnostics are owned by core LSP or a plugin and buffer revision; text changes and owner/server retirement clear them. The TUI underlines annotated text, colors affected gutter numbers by severity, and displays the primary caret's diagnostic message without replacing search/selection backgrounds.
|
||||
Frontends inspect `hover()` for optional read-only content and logical-line/grapheme scroll offsets. Popup request eligibility, dismissal, and scrolling stay editor/session-owned; the TUI clips the panel inside the document workspace without changing the primary cursor or viewport.
|
||||
Frontends inspect `tab_id()` for stable identity, `tab_index()` for display order, `tab_count()`, and `tab_buffer(index)` for borrowed title metadata. `pane_layout()` describes only the active tab; globally unique pane IDs keep inactive tabs' viewports alive. Documents remain unique across all tabs, while independent pane/buffer views are parked and restored without copying text.
|
||||
Frontends borrow `top_bar_config()` and `bottom_bar_config()` for validated ordered left/center/right segment groups and effective segment styles, and `label(name)` for session-wide custom values. The TUI owns terminal-cell widths, full-row center anchoring, clipping, and accent styling. Label effects carry only a name and plain text; they are global presentation updates, not buffer/revision-bound results or render callbacks.
|
||||
Frontends borrow `popup_config()` for independently configured command/search anchors. The TUI resolves each anchor against the chrome-free workspace using the existing bounded popup size; startup configuration does not alter buffer text, modal input, or notification positioning.
|
||||
Frontends borrow `lsp_label()` / `lsp_names()` for the focused buffer's cached ready-server metadata. Initialization-only worker events trigger status redraws independently of diagnostics; session synchronization clears or replaces names when focus changes or a server retires. `notification_visible()` gates persistent operation/diagnostic popups independently of stored message text, so Escape dismissal neither alters text nor collapses carets. Display-only home abbreviation does not change document identity.
|
||||
|
||||
Current-line blame is enabled by default. Session loads whole-file incremental attribution into one active-buffer cache keyed by buffer/text/save revision, disk stamp, path, and optional historical source; cursor, tab, and pane movements within that source reuse it without copying file text or issuing repository commands. Cold results select the current row when they arrive. Edits, saves, source changes, disk refreshes, focus regain, and disabling invalidate attribution; stale results cannot replace a newer source. Comparison provenance follows accepted snapshot/checkout/bookmark refreshes and is retained by immutable buffers independently of their original comparison. Historical queries use a private HEAD and object alternates, never live-file existence or the current checkout baseline. Metadata is shared per commit with `Arc`, and same-commit navigation reuses the sanitized label. Ordinary and split/unified diff rendering use only spare cells after the current logical line's final visible continuation and hide the label when the primary caret is offscreen. Disabling drops the worker.
|
||||
|
||||
Frontends inspect `file_picker()` for query, presentation, view, explorer-local INSERT/filter subfocus, selection, and errors, and iterate borrowed `FileRow` metadata (actual path, display label, directory flag, visible depth, expansion, optional repository status and old path). Dock side is a logical preference. They allocate rectangles, add folder suffixes/colors and sanitized rename labels, and render; hierarchy, filtering, parent/child navigation, focus transitions, and selected-file opening remain backend-owned.
|
||||
Frontends inspect `diagnostics()` and `diagnostic_at_cursor()` for validated active-buffer annotations. Diagnostics are owned by core LSP or a plugin and buffer revision; text changes clear them. Native server retirement removes only that server's contribution, preserving sibling diagnostics. The TUI underlines annotated text, colors affected gutter numbers by severity, and displays the primary caret's diagnostic message without replacing search/selection backgrounds.
|
||||
Frontends borrow `semantic_tokens()` for sorted, single-line grapheme spans from the active buffer. Immutable `Arc` slices are shared by native LSP and buffer storage; painting does not copy tokens. Text replacements retain tokens outside the changed range and shift following positions using whole graphemes, including newline changes. Tokens overlapping the changed range are dropped; disjoint edits conservatively invalidate the range between their first and last changes. This applies to typing, undo/redo, completion, plugin replacements, and disk reloads. Path changes discard overlays. Native updates validate the whole applicable annotation batch before mutation. The TUI merges semantic styling into its existing glyph pass above syntax foregrounds but below diagnostic/search/selection/caret styling.
|
||||
Frontends inspect `hover()` for optional read-only content and logical-line/grapheme scroll offsets. Popup request eligibility, dismissal, and scrolling stay editor/session-owned; the TUI clips the panel inside the full editor area without changing the primary cursor or viewport. Its hover-local syntax cache treats content as Markdown, including named fenced-code injections, and rebuilds only when content changes. The popup shares the document syntax palette and preserves raw Markdown text and logical scroll coordinates.
|
||||
Frontends borrow `completion()` for the read-only item list and selected index: zero is Original text, and other indices select `items[selected - 1]`. The editor owns the immutable original document/carets, atomic candidate transactions, cycling/dismissal, pending Insert undo, and final-only repeat recording. It changes only the primary completion target and translates secondary carets through all edits. The TUI places a windowed list near the current caret, bounded by the full editor rather than its pane, sanitizes/clips labels and detail by grapheme, and preserves logical cursor ownership; wheel input over the list is consumed without dispatching edits.
|
||||
Frontends borrow `snippet_selections()` for the active argument's end-exclusive grapheme ranges, including mirrors and empty tabstops. The editor caches those ranges after previews, argument edits, and navigation; rendering adds no snippet allocation. Template edits stay primary-only, translate other carets, and fold resolved replacement text and caret placement into the pending completion repeat step. Per-occurrence ancestry distinguishes nested arguments from adjacent empty stops, allowing enclosing replacements to retire only overwritten descendants.
|
||||
|
||||
## Terminal lifecycle and layout
|
||||
|
||||
The terminal adapter owns raw mode, alternate-screen state, bracketed paste, and its panic hook for one session lifetime. Entry failure, normal return, I/O errors, and unwinding panics restore the caller's hook; active-terminal cleanup runs before caller panic diagnostics. Panics retain their original payload and propagate rather than being swallowed. Terminal state and panic hooks are process-global: run one TUI at a time and do not replace its hook while that session is active.
|
||||
The terminal guard owns raw mode, alternate-screen state, bracketed paste, mouse capture, focus reporting, DEC 2031 color-scheme notifications, and its panic hook across startup, rendering, session teardown, and relaunch. An inherited-screen restart installs cleanup and its panic hook before argument, file, or configuration parsing, resumes raw mode and input reporting without entering the alternate screen again, and clears and repaints inherited contents in its first synchronized frame. A private first-argument marker identifies this handoff without changing the original CLI arguments. Final quit, startup or I/O errors, failed relaunch, and unwinding panics restore normal input modes, the normal screen, cursor visibility, and the caller's hook; active-terminal cleanup runs before caller panic diagnostics. Panics retain their original payload and propagate rather than being swallowed. Terminal state and panic hooks are process-global: run one TUI at a time and do not replace its hook while the guard is active.
|
||||
|
||||
The TUI uses Ratatui constraint-based layout for a flexible buffer viewport, a one-row status bar, and a one-row prompt/message area. Scrolling, clipping, highlights, and cursor placement use the allocated regions, not terminal-wide offsets. Below three rows the status bar is hidden; at one row the buffer remains visible unless an active command/search prompt takes priority. Zero-sized terminals render nothing. Layout and terminal-cell text mapping remain frontend-owned.
|
||||
`tui::TerminalSession::run(inherited_screen, body)` scopes this ownership; `tui::run(&mut session, inherited_screen)` renders inside that active guard. On Unix, a fresh alternate screen pushes disambiguated keyboard flags so Ctrl+i stays distinct from Tab; final cleanup pops them. `TerminalSession::prepare_restart()` resets process-local input state without leaving the alternate screen or popping its keyboard flags. The replacement process inherits that stack entry rather than pushing another, and the guard stays armed if relaunch fails.
|
||||
|
||||
The buffer viewport includes a fixed left gutter with right-aligned hybrid line numbers: the highlighted primary cursor line shows its one-based absolute number; every other line shows its distance from the primary. Secondary carets do not establish separate numbering origins. Gutter width follows the total line count plus one separator cell, including an empty final row after a trailing newline. Horizontal scrolling affects only text; search/selection highlights and carets never paint over the gutter. Rows beyond the buffer have no number. The gutter is hidden when it would leave no text column.
|
||||
Redraws stage Ratatui's buffer diff, logical cursor placement, and DEC synchronized-update commands (mode 2026) in a reusable byte buffer, then write and flush the complete frame to the terminal. Frame computation never suspends terminal presentation; synchronization covers transmitted painting rather than layout/highlighting work. `WheelPanels::cursor` records the final focused cursor position; the software cursor is painted after overlays, using the same named ANSI mode palette as the bars. `SoftwareCursorBackend` delegates drawing and cursor coordinates but suppresses hardware-cursor visibility, retaining input-method placement without a second cursor or OSC 12 dependency. The hardware cursor stays hidden even when synchronization is unsupported. Terminal cleanup releases synchronization before leaving the alternate screen, then restores cursor visibility before returning or invoking caller panic diagnostics. Backend-writer access is enabled solely for this staging seam.
|
||||
|
||||
`terminal_colors` intercepts crossterm's key-shaped OSC 11/4 replies before editor dispatch, assembles a bounded RGB background/red/green triple, and preserves unrelated events and opaque bracketed paste. Queries never block input and start after painting, so syntax initialization does not spend their reply deadline. Startup, color-scheme notifications, and focus-regain queries replace cached diff tints atomically. While any rendered pane shows a diff, a one-second fallback probes for silent palette changes or missed notifications; ordinary editor views do not poll. Its injected-time deadline prevents overlapping periodic requests. An unanswered/partial query expires after 250 ms and removes stale tints rather than assuming a dark theme. Valid late replies are consumed without becoming editing commands. The frontend precomputes rounded RGB blends from the original background (18% row, 38% character), propagating them to active, parked, and newly created panes.
|
||||
|
||||
`vendor/crossterm` retains Crossterm 0.29.0's upstream source and MIT license, with a small Unix decoder patch exposing `Event::ColorSchemeChanged` for `CSI ? 997 ; 1/2 n`. The report signals a palette refresh, not a choice of hard-coded light/dark colors. Valid fragmented reports and malformed color reports leave following keys intact. Cargo patches both direct and Ratatui dependency paths to this one copy; remove the patch/workspace member once upstream supports these notifications.
|
||||
|
||||
The TUI allocates a flexible buffer viewport and optional one-row top/bottom bars, with no reserved prompt/message footer. Both bars derive visibility from configured content: empty content takes no row, and tabs-only content is hidden with a single tab in either position. Both render across ordinary, split, diff, and selector views. Ordered left/center/right groups use full-row centering, active-tab collision priority, internal padding, and independent styled edges; accented content and edges share the focused mode's ANSI palette colors. Floating Command/Search input owns the software cursor; non-focusable operation/diagnostic notifications anchor bottom-right inside the chrome-free workspace and hide obscured document carets. Higher-priority modal overlays suppress them without changing input state. Wheel hit regions clear each frame and consume reports over these popups. Zero-sized terminals render nothing; minimal-height input never reserves another row. Layout and terminal-cell text mapping remain frontend-owned.
|
||||
|
||||
Comparison views reserve no separate metadata header or native-buffer help footer. Revision labels render bottom-left in pane borders (combined on single-pane views), with per-side editability top-right and focus indicated by border styling. Dock and document geometry use the reclaimed workspace rows; conditional loading/error/file notices remain separate from the border metadata.
|
||||
|
||||
Each comparison owns its split/unified mode and split axis; startup defaults apply only when opening a comparison. Source alignment and file-side availability stay independent of presentation. Unified display rows carry a side projection: equal context maps both sources, changed runs emit Before rows followed by After rows, and folds retain aligned coordinates. Native navigation/editing continues to bind source buffers rather than a synthetic unified document. The TUI reuses side-specific syntax/wrap/overlay pipelines in one unified region or the existing axis-based split geometry, exposing only the active logical side for unified hit-testing and directional focus.
|
||||
|
||||
The resolver owns a dedicated native tab with an editable Draft and frozen read-only Alternatives projected from the current raw working buffer. Projection replaces only conflict regions; automatically merged text and pre-existing outside edits remain identical across initial alternatives. Native undo includes initial seeding. Resolution reuses DiffState alignment, excerpts, highlighting and viewport mapping, including equal-text editing. A separate read-only History uses the original jj inputs/bases; native buffer identity and frontend offsets retain draft/view state. `resolve` reads all alternating Git-backed `jj:trees` terms. Background guarded saves retain checkout/disk validation and jj snapshot/status authority; no presentation change bypasses these write guards.
|
||||
|
||||
Resolution exposes its projected comparison through the same active DiffState and native FilePicker as ordinary diffs. Pane labels and writability are explicit comparison properties; file selection, bindings, native navigation, layout and scrolling share the existing interaction path. Conflict state owns only projections, source choices and guarded save/check metadata; there is no separate resolver filter or file-list renderer.
|
||||
|
||||
Conflict History alignment lives in `diff::HistoryComparison`: it joins the selected inputs at shared base rows, combines base change ranges, retains native EOF rows, and exposes immutable column projections with source/display mapping. The frontend consumes each projection's source side rather than assigning Before/After conventions itself. `HistoryDiff` retains only presentation state: geometry, wrapping, shared scrolling, and caret visibility. Ordinary comparisons and Draft resolution continue to use their existing `DiffState` behavior.
|
||||
|
||||
Content painting and native caret overlays consume a borrowed `diff::ColumnView` for both ordinary comparisons and Conflict History. It resolves folds, gaps, source text and coordinates, native terminal rows, newline state, and side-specific change ranges without copying text or building a row catalog. Native caret mapping remains separate from review membership: unified equal context can carry anchors from either original source. Review freshness/filtering, pane chrome, viewport policy, wrapping, scope labels, and colors stay with their existing owners; the content painter receives only the view and already-filtered review annotations. History retains its internal pairwise `DiffState` storage.
|
||||
|
||||
`WheelPanels::draw_documents` owns the complete ordinary/Resolution document frame: tree preparation, viewport anchoring and scroll projection, visible-row highlighting, content/native caret painting, scope overlays, and final geometry publication. It returns only the surviving document caret for outer popup placement. Selectors, cached-error notices, and file navigation remain in outer orchestration; cached syntax errors are read before preparation to preserve notice-layout timing. The existing owner also retains immediate ordered wheel handling and previous-frame geometry; Conflict History keeps its separate presentation flow.
|
||||
|
||||
`Editor::scroll_distance()` supplies the session-wide optional edge margin. The TUI applies it to document/diff visual rows and unwrapped text columns, and retains independent picker offsets across navigation frames. Picker windows exclude their fixed chrome and align whole multi-row entries. File projections carry a monotonic viewport revision, so catalog/filter/expansion changes invalidate picker identity without hashing the entire catalog on every redraw. Metadata-only status changes do not move the viewport. Explicit LSP/wrap-toggle anchors and detached wheel views retain precedence.
|
||||
|
||||
Keyboard viewport actions queue per-view row and configured-step counts without moving carets. `Editor::take_viewport_scroll(height)` resolves step counts using the session-wide `scroll_step_lines` preference, or half the focused viewport when unset, and saturates multiplication before the frontend clamps movement to content bounds. Ordinary, diff, and conflict-history rendering share this resolution.
|
||||
|
||||
Mouse wheel input uses the last rendered document/panel rectangles for hit-testing. Document offsets and explorer scroll state remain frontend-owned; three-row wheel steps never become document cursor motions. Manual document views persist until logical caret-reveal, caret/selection, mode, revision, or buffer changes; offscreen primary and browsing-selection cursors are not placed. Hover wheel input reuses the existing editor-owned popup scrolling.
|
||||
|
||||
Already-ready mouse reports share a redraw: at most 64 reports are applied in their original order before painting, without dropping or summing away wheel steps. Readiness checks do not wait. The first non-mouse event is retained for the next iteration after rendering, so keys, paste, and resizes cannot reuse geometry from before their layout changes. The batch bound keeps continuous mouse input from starving drawing or background polling.
|
||||
|
||||
Already-ready Insert typing and directly bound Normal/Visual document motions also share a redraw, with the same 64-key bound and non-waiting readiness checks. The editor classifies motion bindings, including remaps and comparison text panes, so the TUI does not hard-code navigation keys. Each key still passes through session dispatch separately, preserving counts, intermediate column clamping, Visual ranges, and history. Mode changes end a batch; pending key/operator/seek prefixes, focused lists/popups, non-motion bindings, release reports, and non-key events remain redraw boundaries. No repeat timer or acceleration is added.
|
||||
|
||||
Ratatui's bounded layout cache is enabled: unchanged geometry and constraints reuse solved rectangles during scrolling; resizes and panel-layout changes use their own cache keys.
|
||||
|
||||
The buffer viewport includes a fixed left gutter with right-aligned hybrid line numbers: the highlighted primary cursor line shows its one-based absolute number; every other line shows its distance from the primary. Secondary carets do not establish separate numbering origins. Width follows the total line count plus one separator cell, including an empty final row after a trailing newline; `git_gutter` bar/symbol modes add a blank cell and a marker cell between the number and separator. Number-color/none modes add no width. Horizontal scrolling affects only text; search/selection highlights and carets never paint over the gutter. Wrapped continuations and rows beyond the buffer have no number or marker. The gutter is hidden when it would leave no text column.
|
||||
|
||||
Repository gutter work runs off the render/editor thread. Revision/path-validated worker results update marker vectors belonging to ordinary source buffers, not historical snapshots; panes and tabs borrow their own buffer's markers. After text edits, the last completed markers for the same path remain visible until a current-revision result replaces them, rather than disappearing during each asynchronous refresh. The worker compares editor text with Git HEAD or Git-backed jj's single parent, independently of save baselines and index state. The frontend paints green additions, red deletion anchors, and yellow modifications as `▌`, symbols, or number colors; current-line cyan/bold overrides repository colors in number-color mode.
|
||||
|
||||
The same cancellable worker collects normal-picker status for the startup project root, including when line-gutter rendering is disabled and no picker is open. The editor retains the last completed project-wide result across picker closure and shares it with ordinary pickers in every tab; new pickers apply it before their first render. Opening or closing a picker does not restart status work. Normal file rows reserve a fixed marker column even before the first result or when the checkout is clean. Disk metadata and dirty-buffer overlays use Git HEAD or jj's single parent without snapshotting jj or writing active refs, objects, or indexes. A private baseline index retains its stat cache across polls; conflicted jj parents are projected once per root/parent. Root, baseline, store, or builtin Git conversion-setting changes invalidate that cache. Private queries disable user filters, external diff, and textconv. Request/root checks reject stale picker results; unchanged catalogs retain their ordinary scanner and filtering rules.
|
||||
|
||||
## Syntax caches
|
||||
|
||||
Each buffer has a frontend-owned parser/tree cache. Unchanged revision/path skips comparison and parsing; unchanged text at a later revision also avoids parsing. Actual text changes produce a minimal UTF-8-safe byte edit with newline-aware Tree-sitter Points, edit the prior tree, then parse using that tree for incremental reuse. Grammar changes reset the tree, including TypeScript versus TSX despite their shared display name. Native highlight/local/injection queries resolve capture precedence and scoped definitions into nonoverlapping original-line spans; unchanged injected trees are reused. Buffer switching restores its cache, and closing retires it. Incomplete text and grammar ERROR nodes remain highlightable; genuine language/query/parser failures expose a status error and readable plain text. Full-tree highlight queries still run after incremental parsing—a deliberate ceiling to revisit if measured costly. There is no second highlighting engine or runtime grammar download.
|
||||
Each buffer has a frontend-owned parser/tree cache. Unchanged revision/path skips comparison and parsing; unchanged text at a later revision also avoids parsing. Actual text changes produce a minimal UTF-8-safe byte edit with newline-aware Tree-sitter Points, edit the prior tree, then parse using that tree for incremental reuse. Grammar changes reset the tree, including TypeScript versus TSX despite their shared display name. Native highlight/local/injection queries resolve capture precedence and scoped definitions into nonoverlapping original-line spans; unchanged injected trees are reused. Buffer switching restores its cache, and closing retires it. Incomplete text and grammar ERROR nodes remain highlightable; genuine language/query/parser failures expose a status error and readable plain text. Full-tree highlight queries still run after incremental parsing—a deliberate ceiling to revisit if measured costly. There is no local semantic inference engine or runtime grammar download.
|
||||
|
||||
Full-source syntax work is bounded to 1 MiB, with a maximum 64 KiB source line (UTF-8 bytes, including normalized line separators in the total). Oversized buffers retain language detection and an explicit plain-text status, but allocate no source copy, per-row spans, scopes, or parse tree. Crossing either budget releases existing parser/cache allocations; unchanged oversized revisions return immediately, and shrinking below both budgets resumes normal parsing. The same policy covers ordinary buffers, diff sources including their separately stored final newline, and text-only hover caches.
|
||||
|
||||
Diff highlighting lazily owns two instances of the same syntax cache, keyed by the accepted comparison request ID and selected file. Before detects language from the old path when renamed; After uses the new path. Scrolling, focus changes, and explorer toggling reuse parsed spans without copying/reparsing snapshots. A fresh comparison identity prevents stale Working-checkout colors even when labels and paths are unchanged. Closing the view releases snapshot caches. Syntax styles patch foreground/modifiers over diff backgrounds; historical panes never receive live-buffer semantic tokens.
|
||||
|
||||
Scope context is a lazily built row index over the existing primary/injected syntax trees, invalidated by source or grammar changes and warmed by diff updates. Ordinary buffer highlighting does not build it. The frontend's visual-row projection inserts inline/sticky scope labels in wrapped and unwrapped diffs; source alignment and excerpt ranges contain no label rows. Coloring, native selection/caret overlays, and source navigation skip these presentation rows. Before/After labels use their independent trees rather than live-workspace symbol analysis.
|
||||
Cached scope metadata records the declaration identifier's source point separately from its extent, including decorated definitions. The projection checks that point against each pane's actual source rows and column/wrap ranges, suppressing redundant labels and refilling reclaimed rows. Caret anchoring skips source/wrap positions only while their maximum possible label height cannot reach the target, then projects the remaining candidates. This retains the first matching anchor even when declaration visibility changes label height non-monotonically.
|
||||
|
||||
## Clipboard providers
|
||||
|
||||
macOS uses fixed JXA/AppKit `NSPasteboardTypeString` access through `osascript`, preserving literal RTF/EPS text rather than treating it as rich clipboard data. Linux supports Wayland with `wl-paste`/`wl-copy`, or X11 with `xclip`, on PATH with the corresponding display environment. Other platforms report unsupported access. Commands have a two-second deadline and bounded output; failures terminate/reap their process group.
|
||||
macOS publishes `public.utf8-plain-text` through the native Pasteboard Manager, checking allocation and OS-status failures before reporting success. Publication is synchronous and avoids per-copy interpreter/process startup; native calls do not have a subprocess deadline. Reads retain fixed JXA/AppKit `NSPasteboardTypeString` access through `osascript`. Both paths preserve literal RTF/EPS text rather than treating it as rich clipboard data. Linux supports Wayland with `wl-paste`/`wl-copy`, or X11 with `xclip`, on PATH with the corresponding display environment. Other platforms report unsupported access. Subprocess-backed access has a two-second deadline and bounded output; failures terminate/reap the process group.
|
||||
|
||||
## Native LSP
|
||||
|
||||
The native module initializes each server, sends `initialization_options` as `initializationOptions`, answers `workspace/configuration` from `settings` (including dotted sections; missing sections return `null`), honors open/change/save capabilities, synchronizes in-memory text including hidden dirty buffers, and sends close events. Incremental servers receive whole-document range replacements. Process/pipe I/O and requests stay on bounded background workers; input and idle diagnostic redraw do not wait for server responses.
|
||||
|
||||
Diff snapshots retain a separate immutable document identity, full source text, side-specific path (the old path for renamed Before), and UTF-16 positions. Native definition updates preserve their UTF-16 ranges until the editor resolves the target's actual snapshot, dirty buffer, disk text, or lazily loaded comparison file; generic plugin navigation remains grapheme-based. Target ranges overlapping actual changed rows route within the same comparison and reveal the exact selection, including an unchanged declaration above a changed body. Wholly unchanged/context/omitted targets and files outside its changes open an ordinary tab without changing the original comparison or view. Snapshot-URI targets keep their immutable identity. Freshness includes tab, pane, source buffer/revision/caret/mode, and comparison/side; deferred file-load navigation also checks its originating view before moving focus. Invalid targets fail before opening a tab. Completion remains restricted to writable After, whether Working or a checkout-matched pinned endpoint.
|
||||
|
||||
Language configurations can own an ordered server stack. The first matching language wins extension overlap; all its matching servers receive document events, while the first handles hover/definition/completion. The Python preset uses ty then Ruff. LSP merges each worker's latest diagnostic snapshot in assignment order before emitting the unchanged core-owned update. Empty publications/retirement remove only their source; revision/path/root changes and close discard all contributions. Worker snapshots retain identity so queued pre-rename diagnostics cannot attach to a new path with the same text revision. Combined diagnostic message bytes remain bounded to 4 MiB; an overflowing publication retires its worker instead of discarding healthy sibling annotations. Workers are stored in config/root order, avoiding per-poll key cloning/sorting. Shutdown flushes the exit notification and waits for peer termination within the existing bounded grace period before process cleanup.
|
||||
|
||||
Semantic tokens belong only to the first assigned server. Initialization advertises standard token types/modifiers, relative encoding, full/range requests, and server refresh support; deltas, overlapping/multiline tokens, and dynamic registration are not advertised. Each buffer has at most one request in flight; changes/refreshes coalesce into the latest snapshot. Text-change notifications discard cached server coordinates without publishing an empty overlay over the editor's remapped colors. Full requests are preferred, with whole-document range fallback. A linear UTF-16 decoder validates raw coordinates and legend indices before outward grapheme rounding; overlong ends truncate at EOL, unknown types and invisible spans fall back to syntax. Both wire frames and decoded spans are bounded to 4 MiB. Snapshot identity rejects stale/renamed/closed replies before decoding. Invalid semantic replies clear the overlay and report an error without retiring diagnostics/navigation; primary retirement clears its overlays, and sibling retirement leaves them intact.
|
||||
|
||||
Manual completion dispatches the Insert-only `core.lsp.completion` action directly to the session, without the Ex execution path's mode/history transitions. The native worker sends the primary caret as UTF-16 and normalizes results into `CompletionItem { label, detail, primary_edit, edits, snippet }`; each `CompletionEdit` uses original-document, end-exclusive grapheme coordinates. Snippet primary text is expanded and newline-normalized before byte-relative metadata is assigned; additional edits remain plain text. Primary and additional edits form one atomic candidate. Session freshness includes the latest request, buffer/revision, primary caret, Insert source mode, and absence of modal overlays; any intervening input invalidates a pending reply. Decoding/validation errors remain completion-local and preserve healthy diagnostics/semantic tokens. Server commands, indentation adjustment, resolve requests, and automatic triggers are not supported; both frames and aggregate decoded completion text remain bounded.
|
||||
|
||||
## Ruby action catalog
|
||||
|
||||
Ruby builds `config.core` from the Rust action catalog before loading configuration or plugin scripts. Dotted identifiers create nested namespaces automatically; each namespace and Action value is frozen. Action names are not duplicated in Ruby, so Rust catalog additions/renames immediately change the Ruby interface without code generation or handwritten exports.
|
||||
`src/editor.rs`'s `CORE_ACTIONS` catalog owns core action names, eligible modes, optional Ex aliases, and prompt policies. It generates the Rust Action enum and protected core command registration. Typed keys and textual Ex aliases share Action-backed execution; the palette has one row per core action and searches its alias without adding duplicate command rows.
|
||||
|
||||
Rust supplies name/Ex-alias descriptors before loading configuration or plugin scripts. Ruby generates `config.core` methods and a frozen built-in alias lookup from those descriptors, rejecting built-in string binding targets without a second command list. Dotted identifiers create nested namespaces automatically; each namespace and Action value is frozen.
|
||||
|
||||
+360
-25
@@ -13,14 +13,35 @@ Rejected configuration opens a centered floating **Configuration error** window,
|
||||
Vamp.configure do |config|
|
||||
config.leader = "space"
|
||||
config.clipboard_mode = "system"
|
||||
config.git_blame = true # false disables current-line attribution
|
||||
config.git_gutter = "bar" # or "symbols", "line_numbers", "none"
|
||||
config.cursor = {} # mode colors enabled; all modes use a block cursor
|
||||
# config.cursor = { mode_colors: false, insert: :bar, visual: :underline }
|
||||
config.scroll_distance = 0 # nonnegative edge distance, or nil to center
|
||||
config.scroll_step_lines = nil # Ctrl+u/d: half viewport, or a positive screen-row count
|
||||
config.highlight_trailing_whitespace = false # true marks line-end whitespace in red
|
||||
config.whitespace_characters = {} # opt in: { " " => "·", "\t" => "→", "\n" => "↵" }
|
||||
config.whitespace_scope = "all" # or "leading" for indentation only
|
||||
config.tab_spaces = nil # opt in with a fixed number of spaces per Tab, e.g. 4
|
||||
# config.language_tab_spaces.merge!("ruby" => 2, "makefile" => nil)
|
||||
config.file_explorer_side = "right"
|
||||
config.file_explorer_view = "tree"
|
||||
config.file_picker_view = "tree"
|
||||
config.diff_context_lines = 10
|
||||
config.diff_expand_lines = 15
|
||||
config.diff_view_mode = "split" # or "unified"
|
||||
config.diff_split_orientation = "vertical" # or "horizontal"
|
||||
config.diff_follow_working_copy = true
|
||||
config.pull_request_review_requested_symbol = "🙏"
|
||||
config.pull_request_approved_symbol = "👍"
|
||||
config.resolve_history_layout = "columns" # or "base_below"
|
||||
config.review_directory = nil # XDG data directory; override with an absolute or config-relative path
|
||||
config.bind "ctrl+h", config.core.left, mode: config.modes.tree
|
||||
config.bind "ctrl+l", config.core.right, mode: config.modes.tree
|
||||
config.plugin "plugins/greeting.rb"
|
||||
config.bind "g", "greet"
|
||||
config.bind "leader g", "greet"
|
||||
config.bind "leader q", config.core.quit
|
||||
config.bind "ctrl+r", config.core.redo
|
||||
config.bind "shift+j", config.core.join_lines
|
||||
config.bind "ctrl+c", config.core.normal, mode: config.modes.insert
|
||||
@@ -35,25 +56,202 @@ end
|
||||
|
||||
## Preferences
|
||||
|
||||
Plugin paths resolve relative to the config file, not the shell's working directory. `config.bind key, target, mode: config.modes.normal` overrides one key or leader-prefixed sequence; editing modes are `config.modes.normal`, `config.modes.insert`, `config.modes.command`, `config.modes.search`, and `config.modes.visual`. `config.modes.selection` configures shared list navigation; `config.modes.tree` overrides it in tree browsing. Omitting `mode` selects Normal. The leader defaults to `"space"` and is applied before configured bindings.
|
||||
Plugin paths resolve relative to the config file, not the shell's working directory. `config.bind key, target, mode: config.modes.normal` overrides one key or a whitespace-separated key sequence; editing modes are `config.modes.normal`, `config.modes.insert`, `config.modes.command`, `config.modes.search`, and `config.modes.visual`. Sequences require Normal/Visual. `config.modes.selection` configures shared list navigation; `config.modes.tree` overrides it in tree browsing. Omitting `mode` selects Normal. The leader defaults to `"space"` and is applied before configured bindings.
|
||||
`config.file_explorer_side` defaults to `"right"`; other choices are `"left"`, `"top"`, and `"bottom"`. Independent `file_explorer_view` / `file_picker_view` preferences both default to `"tree"` and accept `"list"` as an alternative. Invalid preference strings report notices and retain defaults while valid bindings still install. Non-string/empty values disable the whole configuration like other Ruby type errors.
|
||||
`config.clipboard_mode` accepts `"system"` (default) or `"separate"`. An invalid policy string reports a notice and retains System while valid bindings still install; non-string/empty values reject the whole Ruby configuration.
|
||||
|
||||
`config.cursor` accepts a partial hash. `mode_colors` defaults to `true`: the primary software cursor and secondary text carets use the terminal's ANSI cyan in Normal, green in Insert, magenta in Visual (including Visual Line), yellow in Command, and blue in Search. These are palette entries from the current terminal color scheme, not fixed RGB colors. Set `config.cursor = { mode_colors: false }` for a neutral reverse-video block cursor (default text color for bar/underline); secondary carets retain their magenta highlight.
|
||||
|
||||
The `normal`, `insert`, `visual`, `command`, and `search` keys select software cursor shapes: `:block`, `:bar`, or `:underline` (strings also work). Every mode defaults to a steady block. Block and underline preserve the displayed grapheme; the bar draws `▏` over the hovered character until the cursor moves. For example, `config.cursor = { insert: :bar, visual: :underline }` changes those two shapes without disabling mode colors. Each assignment replaces the cursor configuration; omitted keys retain built-in defaults. Unknown keys, nonboolean `mode_colors`, unsupported shapes, and non-hash values reject the configuration.
|
||||
|
||||
Shapes apply to the primary cursor, including command/search prompts, pickers, and historical/diff text; secondary carets remain cell highlights. The cursor is painted after the focused view's overlays, takes precedence over syntax/search/selection colors, and disappears when its position is offscreen or covered by a notification. The hardware cursor stays hidden during editing; its logical position is retained for input methods, and normal exit/errors/panics restore its visibility. Vamp does not change terminal cursor color or shape settings, so multiplexers need no native cursor-color support. File contents and cursor positions remain unchanged.
|
||||
|
||||
`config.scroll_distance` defaults to `0`: keep the viewport still until its primary cursor or selected picker entry would leave it. A nonnegative integer reserves that many visible rows above/below the cursor, and terminal-cell columns left/right in unwrapped text. `nil` keeps it centered; integers at least half the current viewport dimension behave the same way until resizing makes that margin usable. The start of content limits centering, while trailing blank space allows centering near the end. Whole two-row picker entries stay aligned, using the nearest entry to the center when exact margins cannot fit.
|
||||
|
||||
The setting applies to ordinary and historical buffers, split/unified diff panes, file pickers and explorers, command/buffer palettes, completion lists, and revision selectors. Wrapped text measures visual rows, not source lines; picker distances use result rows, excluding borders, search fields, and help. Manual mouse-wheel scrolling remains detached until keyboard navigation resumes. Only `nil` or integers from `0` through the platform's Rust `usize` maximum (`18446744073709551615` on 64-bit systems) are accepted; other values reject the configuration.
|
||||
|
||||
`config.scroll_step_lines` controls Normal/Visual Ctrl+u/Ctrl+d (`core.scroll_step_up` / `core.scroll_step_down`). The default `nil` scrolls half the focused text viewport, rounded down with a minimum of one screen row. A positive integer, such as `config.scroll_step_lines = 3`, fixes the distance in screen rows, including wrapped continuations and diff display rows. Counts multiply that distance; `2` then Ctrl+d scrolls six rows with this example. This session-wide setting applies to ordinary, historical, diff, and conflict text panes without moving carets or selections. It does not change the cursor-edge margin, one-row scroll actions, mouse wheel, or picker navigation. Only `nil` or integers from `1` through the platform's Rust `usize` maximum are accepted; other values reject the configuration. Distances and count multiplication saturate at Rust's `isize` limit before the viewport clamps to content bounds.
|
||||
|
||||
`config.highlight_trailing_whitespace` defaults to `false`. Set it to `true` to give trailing whitespace a red background in ordinary and historical buffers and both sides of split/unified diffs, including wrapped and horizontally scrolled text. Spaces, expanded tab cells, and Unicode whitespace at the end of a source line are highlighted; whitespace-only lines are included, but empty lines and padding beyond the text are not. Wrapping does not make interior whitespace trailing. Search, selections, and secondary carets retain their background precedence; diagnostic underlines remain visible. This changes display only, not file contents. Only literal Ruby booleans are accepted; other values reject the configuration.
|
||||
|
||||
`config.whitespace_characters` defaults to `{}` (disabled). Assign a hash mapping literal whitespace characters to dim display markers, for example `{ " " => "·", "\t" => "→", "\u00a0" => "⍽", "\n" => "↵" }` for spaces, tabs, nonbreaking spaces, and line breaks. Unlisted characters keep their ordinary appearance. Keys and values must be single-character strings; keys must be whitespace with visible terminal width, tabs, or `"\n"`, and values must be printable one-cell characters. Carriage returns and other control characters, zero-width markers, and wide markers reject the configuration. Only indicator cells receive terminal dim styling; source-text colors, diagnostic underlines, and highlighted backgrounds remain intact.
|
||||
|
||||
`config.whitespace_scope` defaults to `"all"`. Use `"leading"` to mark only the initial whitespace prefix of each source line; a whitespace-only line is entirely leading, but wrapping and horizontal scrolling do not create new indentation. Only the strings `"all"` and `"leading"` are accepted; other values reject the configuration.
|
||||
|
||||
A `"\n"` map entry marks actual line breaks independently of `whitespace_scope`, including blank lines and a file's final newline when present. Soft wraps, missing final newlines, and the virtual empty EOF row do not gain markers. The glyph occupies the existing end-of-line caret cell on the final wrapped segment; a full-width line uses the existing extra caret segment. In unwrapped text, an offscreen end-of-line marker is clipped like other source cells. Newline markers inside syntax-recognized strings are suppressed along with horizontal whitespace markers.
|
||||
|
||||
Whitespace inside strings recognized by the bundled syntax grammar stays literal, including raw/multiline strings, heredocs, interpolated strings, and strings with embedded-language highlighting. Outside strings, configured markers still apply. String boundaries come from the original source, so wrapping, horizontal scrolling, and split/unified historical diffs retain this distinction. Plain text and unknown languages have no syntax-defined string boundaries; quotes are not guessed to be strings.
|
||||
|
||||
Markers appear in ordinary and historical buffers and both sides of split/unified diffs. Tabs and wide Unicode whitespace show the marker in their first source cell and leave remaining cells blank, preserving tab stops, wrapping, horizontal scrolling, and cursor/selection geometry. A clipped first cell hides its marker; padding beyond the source does not gain markers. Whitespace with combining characters remains intact. Syntax colors, search, selections, diagnostics, and trailing-whitespace highlighting still apply. This changes display only: editing, copying, and saving retain the original characters.
|
||||
|
||||
`config.tab_spaces` defaults to `nil`, preserving literal tabs. Set an integer from `1` through `255` to insert that many spaces per Tab in Insert mode, at every caret. This is a fixed count, not alignment to the next tab stop; it does not change how existing tab characters are displayed.
|
||||
|
||||
`config.language_tab_spaces` defaults to `{}`. It overrides the global setting using the same case-sensitive language IDs as `config.lsp`, for example `{ "rust" => 4, "ruby" => 2, "python" => 4, "makefile" => nil }`. Syntax detection and built-in LSP presets share canonical IDs rather than maintaining separate naming conventions; other bundled IDs include `shellscript`, `cpp`, and `typescriptreact` for Bash, C++, and TSX. Display labels such as “Ruby” remain presentation-only. A `nil` override preserves literal tabs for that language, even when the global setting uses spaces. Unlisted or unknown languages and unnamed buffers without a recognized shebang use `tab_spaces`. Detection reuses syntax highlighting's filename, extension, and shebang rules, independently of whether an LSP is enabled.
|
||||
|
||||
Like `config.lsp`, `config.language_tab_spaces` exposes a mutable hash: use `merge!` to add or override entries, or `config.language_tab_spaces["ruby"] = 2` to change one entry. Whole-hash assignment with `=` remains supported. Both assignment and the final hash contents are validated; invalid keys or widths inserted through hash mutation reject startup configuration rather than bypassing validation.
|
||||
|
||||
```ruby
|
||||
config.tab_spaces = 4
|
||||
config.language_tab_spaces.merge!(
|
||||
"rust" => 4,
|
||||
"ruby" => 2,
|
||||
"makefile" => nil,
|
||||
)
|
||||
```
|
||||
|
||||
Active snippets retain Tab/Shift+Tab argument navigation; after the final stop, Tab uses the configured insertion setting. Ctrl+i defaults to the same Insert action but has its own binding. Explicit bindings for either key take precedence independently. Bracketed paste, clipboard paste, completion payloads, and plugin text retain literal tab characters. Insert undo/redo and dot repeat preserve the resolved spaces or tab. Widths other than `nil` or integers in `1..255`, non-hash language overrides, and empty, non-string, or control-containing language keys reject the configuration.
|
||||
|
||||
`config.git_blame` defaults to `true`; set it to `false` to disable current-line inline Git blame and its background worker. Only literal Ruby booleans are accepted; other values reject the configuration. Toggle it for the running session with `:git_blame.toggle`, its palette action, or a custom binding such as `config.bind "leader b", config.core.git_blame.toggle`. There is no default shortcut.
|
||||
|
||||
`config.git_gutter` defaults to `"bar"`: a fat `▌` with one blank column between the line number and marker and another before the text. `"symbols"` uses `+` / `-` / `~` with the same spacing. Added, removed, and modified lines use green, red, and yellow respectively. `"line_numbers"` colors the existing numbers without adding a marker column; the current line retains its cyan/bold caret highlight. `"none"` hides line-gutter repository indicators, not line numbers or picker file statuses. Other modes retain diagnostic number colors independently of repository markers. Unsupported strings, empty strings, and non-string values reject the configuration.
|
||||
|
||||
In `"line_numbers"` mode, color precedence is **current-line cyan/bold → highest-severity diagnostic → repository change → default number color**. In bar/symbol modes, diagnostic number colors and repository markers remain independent.
|
||||
|
||||
Indicators compare the current editor text (including unsaved edits) against Git `HEAD`, or the parent `@-` in Git-backed jj repositories, rather than against the last save or Git index. Line endings use the editor's LF normalization. They refresh after edits/saves, on focus regain, and once per second for repository changes. Historical snapshots do not receive live indicators. Eligible named files not yet on disk show nonempty unsaved text as added; tracked files missing on disk still compare their buffer text against the baseline. Non-repository, ignored, binary, symlink, and unsupported files have no indicators; neither do jj working changes with multiple parents. Both colocated and non-colocated Git-backed jj repositories are supported. Files above 16 MiB report an error and clear their indicators; request batches are limited to 64 MiB or 1024 files.
|
||||
|
||||
`config.diff_context_lines = 10` sets how many unchanged aligned lines appear above and below each diff change; it defaults to `10` and accepts nonnegative integers, including `0` for changes only. `config.diff_expand_lines = 15` sets how many additional lines each directional expansion reveals per keypress; it defaults to `15` and accepts positive integers. Both are bounded by the platform's Rust `usize` maximum (`18446744073709551615` on 64-bit systems). Floats, strings, booleans, negative or oversized values, and a zero expansion step reject the whole Ruby configuration.
|
||||
|
||||
`config.diff_view_mode` selects the initial view for each new comparison: `"split"` (default) or `"unified"`. `config.diff_split_orientation` selects `"vertical"` (left/right, default) or `"horizontal"` (above/below) for split views. Invalid values reject the configuration. Normal-mode **Space v** cycles split/unified; **Space s** flips split orientation. These controls affect the current comparison, not startup defaults, and retain their choices across file switches and tabs. Orientation changes apply only in split view.
|
||||
|
||||
`config.diff_follow_working_copy` defaults to `true`. The After picker calls its live-files choice **Follow checkout** when enabled, otherwise **Checkout snapshot**. Following advances to descendant checkouts automatically, including in inactive tabs; `false` disables endpoint following without disabling ordinary live-buffer editing or reload. Only literal booleans are accepted. Before is always frozen. Pinned After endpoints never move, but their checkout-aware editability checks remain enabled regardless of this setting. See [repository diff](editing.md#repository-diff) for ancestry and refresh behavior.
|
||||
|
||||
`config.pull_request_review_requested_symbol` and `config.pull_request_approved_symbol` control the markers before PR numbers in the pull-request picker. Defaults are `"🙏"` for an outstanding personal review request and `"👍"` for your active approval, using the API-authenticated account. Requests take precedence over approvals when both apply. Each option accepts a string without control characters; multi-character and wide Unicode symbols are supported. Set either to `""` to hide that state, or both to `""` to remove the marker gutter. PR numbers and metadata stay aligned by terminal-cell width, including rows without a marker. Non-strings and strings containing tabs, newlines, or other control characters reject the configuration.
|
||||
|
||||
`config.pull_request_sort` optionally overrides saved sorting: `nil` or an omitted option uses saved sorting, then built-in defaults. A configured sort section replaces that entire saved section; omitted criteria use built-in defaults. `config.pull_request_filters` sets the session's initial filter buckets; `nil` or omission includes all buckets. UI filter changes are shared across tabs and picker reopenings for this vamp session only. Restart restores the configured filters or includes all buckets; previously saved filters are ignored.
|
||||
|
||||
```ruby
|
||||
config.pull_request_sort = {
|
||||
updated_at: { precedence: 1, direction: :desc },
|
||||
created_at: { direction: :asc }
|
||||
}
|
||||
config.pull_request_filters = [:requested, :approved]
|
||||
```
|
||||
|
||||
Sort fields are `requested`, `updated_at`, `approved`, and `created_at`, in that default precedence order. Default direction is `desc`; timestamp criteria support `asc` for oldest first. `precedence` is `nil` (unnumbered default position) or a unique integer in `1..4`. Filters are any subset of `requested` (Requested from me), `approved` (Approved by me without an outstanding personal request), and `other` (Other / unavailable). `[]` excludes all requests; `{}` resets sorting to built-in defaults. Unknown fields/options, duplicate ranks/filters, and invalid types or directions reject configuration.
|
||||
|
||||
Enter Apply in the sort menu saves changed sorting to `$XDG_STATE_HOME/vamp/pull_requests.json`, or `~/.local/state/vamp/pull_requests.json` if XDG state is unset or relative. Applying filters never writes this file, and subsequent sort saves exclude filters. This also works with `--no-config`. Configuration remains a startup override, not a lock: UI edits work for the session, but explicitly configured settings win again next startup. Sort save failures report session-only changes. Corrupt, incompatible, or non-regular storage is reported and preserved rather than reset or overwritten.
|
||||
|
||||
`config.resolve_history_layout` controls the read-only conflict inputs opened by `:resolve.history`: `"columns"` (default) places left/base/right side by side; `"base_below"` places left/right above a full-width base. Both layouts share aligned rows and synchronized vertical scrolling. Tab/Shift+Tab follows layout order (left/base/right or left/right/base); directional pane actions follow the displayed geometry. Narrow terminals show the focused source only; the base-below layout does the same when there is insufficient height. This setting does not change the editable Resolution view or ordinary diffs. Invalid values reject the configuration.
|
||||
|
||||
```ruby
|
||||
config.bind "ctrl+b", config.core.diff.mode.toggle
|
||||
config.bind "leader v", config.core.diff.view.toggle
|
||||
config.bind "leader s", config.core.diff.orientation.toggle
|
||||
```
|
||||
|
||||
### Top and bottom bars
|
||||
|
||||
`config.bar.top` and `config.bar.bottom` each accept ordered `left`, `center`, and `right` arrays of segment names. Both bars accept every builtin and custom segment, with the same anchors, title templates, margins, padding, styled edges, and collision handling. Left and right groups anchor to their respective edges; the center group is centered on the whole row, not on the gap remaining between the other groups. Array order is display order within each group. Omitted groups and segment options retain that bar's defaults; an empty array removes that group.
|
||||
|
||||
Accented segments (including active tabs, mode, position, and custom labels), their padding, and decorative edge colors follow the focused editing mode using the same ANSI palette as the software cursor. Both bars change together; inactive tabs, neutral text, separators, and margins retain their existing styling. Setting `config.cursor = { mode_colors: false }` affects cursors only, not the bars.
|
||||
|
||||
The renderer inserts one unstyled blank column between visible items in each group, including tab titles. Hidden items contribute no separator; there is no separator before the first or after the last item. Separator widths count toward anchoring and collision handling. Plain-text segments default to no padding or margins, so adjacent labels do not double their spacing.
|
||||
|
||||
Use the two setters independently; a combined `config.bar = { ... }` assignment is not supported.
|
||||
|
||||
Defaults put `left: [:tabs]` and `right: [:diff, :shell, :battery]` in the top bar; the bottom has `left: [:mode, :pending, :buffer, :diagnostics, :path, :selections, :count]` and `right: [:language, :lsp, :position]`; other groups are empty. Set the bars independently, as in this swapped layout with status information above and tabs plus diff totals, live battery charge, and shell status below:
|
||||
|
||||
```ruby
|
||||
Vamp.configure do |config|
|
||||
config.bar.top = {
|
||||
left: [:mode, :path, :diagnostics, :selections, :count, :pending, :buffer],
|
||||
center: [], right: [:language, :lsp, :position],
|
||||
mode: { padding: 1, leading_edge: "", trailing_edge: "▓░" },
|
||||
position: { padding: 1, leading_edge: "░▓", trailing_edge: "" }
|
||||
}
|
||||
config.bar.bottom = {
|
||||
left: [:tabs], center: [], right: [:diff, :shell, :battery],
|
||||
tabs: {
|
||||
title: "{index} {view}{name}{changes}{modified}", padding: 1,
|
||||
leading_edge: "░▓", trailing_edge: "▓░", first_leading_edge: ""
|
||||
},
|
||||
battery: { padding: 1, leading_edge: "░▓", trailing_edge: "" }
|
||||
}
|
||||
end
|
||||
```
|
||||
|
||||
Builtins are `:tabs`, `:diff`, `:battery`, `:shell`, `:mode`, `:path`, `:position`, `:language`, `:lsp`, `:diagnostics`, `:selections`, `:count`, `:pending`, and `:buffer`, in either bar. They provide tab titles, whole-comparison line counts, battery charge, running shell command/spinner, mode, file path/dirty state, caret position, detected language, ready LSP server names, diagnostics, selection count, numeric prefix, pending key sequence, and buffer identity/count.
|
||||
|
||||
A bar with no visible content consumes no row. For example, `config.bar.top = { left: [], center: [], right: [] }` removes the top bar. A bar whose only visible content is `:tabs` is hidden with a single tab, whether above or below the workspace. Narrow layouts first omit inactive tabs, then optional segments from group ends to avoid overlap; the active tab drops decorations before its title is clipped. Commands and buffer searches use floating input; operation feedback uses a bottom-right popup. Neither reserves a footer row.
|
||||
|
||||
Each segment's `title` is a literal template supporting only `{index}`, `{view}`, `{name}`, `{path}`, `{changes}`, and `{modified}`: the one-based tab index, comparison-view marker, filename, file path, selected-file line counts, and dirty marker (`" [+]"` when dirty, `""` when clean). `{view}` expands to `"Diff · "` for comparisons and revision selectors, or `""` for ordinary tabs. `{changes}` expands to `" +N -M"` for a loaded comparison file and `""` otherwise. Counts follow the selected file and live edits, including inactive tabs. Tabs use each tab's view and buffer metadata; other segments use the active context. Tabs default to `"{index} {view}{name}{changes}{modified}"`; custom templates must include `{changes}` to display per-file counts. An empty title on another segment uses its builtin content or named label value. Templates are not Ruby code and never invoke a render callback.
|
||||
|
||||
`:path` and `{path}` abbreviate the actual home-directory prefix to `~/` (`~` for the home directory itself). This is display-only: save paths, buffer identity, and LSP file URIs retain the original path. Sibling directories with similar names are not abbreviated.
|
||||
|
||||
`:lsp` displays only ready servers assigned to the focused buffer, in configured stack order joined with ` + `. Disabled, initializing, failed, or unassigned servers do not appear. Names come from the initialization reply's `serverInfo.name`, falling back to the configured executable basename; no arbitrary named label can make an inactive server appear active.
|
||||
|
||||
`margin` adds unstyled space outside both edges of a segment, unlike the styled internal `padding`. `leading_margin` and `trailing_margin` override their respective sides. All accept integers from `0` through `64`; all margins default to zero. Explicit margins are additional to the renderer's one-column separator, so leave them at zero for normal inter-item spacing. Margins count toward anchor placement and collision handling; empty segments consume no margin, and margins yield along with padding and edges when only clipped content fits.
|
||||
|
||||
`padding` adds spaces inside the segment's styling, on both sides of its title, and accepts integers from `0` through `64`. It defaults to `0` for plain-text and custom segments and `1` for tabs, mode, position, battery, shell status, and LSP indicators. Diff totals use plain text without a filled background, padding, or edges by default. Internal padding is separate from the inter-item separator; explicit padding can deliberately add more whitespace. `leading_edge` and `trailing_edge` are separate styled glyph strings, not padding; `""` removes an edge. Tabs and shell status default to `"░▓"` / `"▓░"` edges; mode has only the trailing `"▓░"` edge, position and battery only the leading `"░▓"` edge, and other segments have none. `first_leading_edge` optionally overrides the first occurrence's leading glyphs: for tabs this is the actual first tab, not the first tab remaining after clipping; other segments have one occurrence. Tabs default this override to `""`, suppressing the first tab's left fade. Unicode widths are measured in terminal cells. Edge strings must be single-line and contain no control characters. Unknown style keys, invalid templates, and wrong types reject configuration.
|
||||
|
||||
Any other segment name is a custom named value, such as `:build_status`. Set initial strings with `config.labels`; an empty value hides the custom segment, including its title override, margins, padding, and edges. Names match `[A-Za-z_][A-Za-z0-9_]*`. Labels are plain text: control characters are replaced rather than interpreted as terminal escapes. The same named value can appear in either bar.
|
||||
|
||||
`:battery` displays `bat N%` from the OS, with an immediate background reading and refreshes every 30 seconds. macOS uses IOKit, Linux uses system battery sysfs entries, and Windows uses `GetSystemPowerStatus`; no shell commands run. Missing, unsupported, or unreadable batteries hide the segment. macOS/Linux currently report the first present internal/system battery; Windows uses the OS's system percentage.
|
||||
|
||||
Move `:battery` to any anchor group or remove it from both bars to stop battery collection. A nonempty `config.labels[:battery]` or plugin value explicitly overrides the native text and pauses collection; clearing that value restores native readings. Other custom live values use [`editor.label(name, text)` or asynchronous plugin updates](plugins.md#named-label-updates). Configuration runs once at startup; there are no render callbacks.
|
||||
|
||||
`:shell` is one shared segment containing the abbreviations and animated spinners for all running `:!COMMAND` processes. Each entry appears only after its command has run for 200 ms, avoiding flashes for short commands. Completed output is shown immediately or queued behind the current result window. The segment hides when idle. It defaults immediately left of `:battery`, with its own styled edges and the standard one-column separator; move it to any anchor group or omit it without affecting command execution. A nonempty label named `shell` overrides the builtin display; clearing it restores the running indicators.
|
||||
|
||||
`:diff` displays `Diff +N -M` for the active comparison, including unopened and filtered-out files, and hides in revision selectors and ordinary tabs. Live edits and undo/redo update totals. An empty comparison shows `Diff +0 -0`; incomplete statistics show `Diff …`, never a partial total. It defaults left of shell status and battery; move it to either bar or omit it like any builtin. See [counting semantics](editing.md#repository-diff).
|
||||
|
||||
### Command and search popup anchors
|
||||
|
||||
Configure the two input windows independently:
|
||||
|
||||
```ruby
|
||||
Vamp.configure do |config|
|
||||
config.popup.command = { anchor: :top_right }
|
||||
config.popup.search = { anchor: :center }
|
||||
end
|
||||
```
|
||||
|
||||
Both default to `:bottom_left`. Supported anchors are `:top_left`, `:top_center`, `:top_right`, `:center_left`, `:center`, `:center_right`, `:bottom_left`, `:bottom_center`, and `:bottom_right`. String values and string hash keys are also accepted.
|
||||
|
||||
Anchors refer to the chrome-free workspace, not the whole terminal or focused pane. Center positions use the full workspace width/height. The windows remain bounded to 72 columns by 3 rows, preserving titles, internal padding, cursor clipping, and modal behavior. This setting does not move revision selectors or the operation notification.
|
||||
|
||||
Only the `anchor` option is supported; unknown anchors/options, callbacks, nulls, and wrong types reject configuration. Omitting a window or its anchor keeps its default. Use the two setters separately; a combined `config.popup = { ... }` assignment is not supported.
|
||||
|
||||
## Actions and modes
|
||||
|
||||
`config.core` exposes the built-in actions below as immutable `Action` values; `config.modes` exposes immutable `Mode` values. Misspelled methods fail during configuration evaluation, and `bind` rejects the wrong value type. Built-in action strings and mode strings are not accepted. Registered Ex/plugin commands still use exact string names (`"w"`, `"greet"`, etc., without `:` or arguments) and can only be bound in Normal mode. Ruby provides runtime checks, not compile-time checking; the editor still validates action/mode compatibility.
|
||||
`config.core` exposes the built-in actions below as immutable `Action` values; `config.modes` exposes immutable `Mode` values. Misspelled methods fail during configuration evaluation, and `bind` rejects the wrong value type. Built-in action strings, canonical Ex names (such as `"quit"`), shorthand aliases (such as `"q"`), and mode strings are not accepted. Only plugin-owned commands use exact string names (`"greet"`, without `:` or arguments) and can only be bound in Normal mode. Interactive Ex commands remain textual. Ruby provides runtime checks, not compile-time checking; the editor still validates action/mode compatibility.
|
||||
|
||||
Registered command names may contain dot-separated segments, each starting with an ASCII letter followed by ASCII letters/digits/underscores/hyphens, plus one optional trailing `!`. Names cannot contain whitespace, empty segments, or leading/trailing dots. This grammar applies to core and plugin commands alike.
|
||||
|
||||
For command-capable actions, canonical Ex names derive automatically from the action name without `core.`: `config.core.quit` corresponds to `:quit`, while `config.core.diff.close` corresponds to `:diff.close`. The single Rust alias table targets typed actions, so shorthand names such as `:q` follow the canonical name without repeating its spelling. Both canonical names and aliases are reserved against plugin registration; the Ruby ownership map comes from the same catalog and alias table. Native-only action eligibility is unchanged.
|
||||
|
||||
## Key notation
|
||||
|
||||
Key notation follows [Herdr's readable style](https://herdr.dev/docs/configuration/#keybindings). Literal non-control Unicode characters are case-sensitive (`n`, `J`, `+`); named keys and modifiers are case-insensitive:
|
||||
|
||||
- Named keys: `esc`, `enter`, `backspace`, `delete`, `left`, `right`, `up`, `down`, `home`, `end`, `tab`, `space`.
|
||||
- Modifiers: `ctrl+a` through `ctrl+z`, and `shift+a` through `shift+z`. `shift+j` and `J` address the same key.
|
||||
- Modifiers: `ctrl+a` through `ctrl+z`, `alt+a` through `alt+z` (`option+` is an alias for `alt+`), `ctrl+alt+a` through `ctrl+alt+z` (either modifier order), `shift+a` through `shift+z`, and `shift+tab`. `shift+j` and `J` address the same key. Modified Backspace accepts `alt+backspace` / `option+backspace` and `cmd+backspace` / `super+backspace`.
|
||||
- Named punctuation: `minus`, `comma`, `ampersand`, `plus`, `backtick`. Each addresses the same binding as its literal character.
|
||||
|
||||
`ctrl+i` aliases `tab`, and `ctrl+m` aliases `enter`, including inside leader sequences. Ctrl+h and Ctrl+j are distinct control keys, not Backspace/Enter aliases. Only a single modifier on an ASCII letter is supported. Arbitrary non-leader key sequences, Alt/Cmd/Super, combined modifiers, modified special keys, and Vim-style angle-bracket notation are rejected rather than silently treated as another key.
|
||||
`ctrl+i` and `tab` are distinct bindings, including inside sequences; `ctrl+m` aliases `enter`. Ctrl+h and Ctrl+j are distinct control keys, not Backspace/Enter aliases. The Unix TUI requests disambiguated keyboard events so supporting terminals can distinguish Ctrl+i from Tab. Legacy terminals still send both as Tab. ASCII letters support a single modifier or combined Ctrl+Alt/Option; Shift+Tab and the modified Backspace keys above are also supported. Cmd/Super character keys, other combined modifiers, other modified special keys, and Vim-style angle-bracket notation are rejected rather than silently treated as another key.
|
||||
|
||||
Normal mode binds `ctrl+o` to `config.core.jump_back` and `ctrl+i` to `config.core.jump_forward`, including in comparisons. Normal Tab also jumps forward outside comparisons; in comparisons it cycles panes. Insert-mode Tab and Ctrl+i insert literal text outside snippets; inside one they move to the next argument. Override or disable these keys independently with the ordinary per-mode binding interface; jump actions also appear in the command palette.
|
||||
|
||||
`config.core.backspace_word` and `config.core.backspace_line` are typed actions eligible in Insert, Command, and Search. Ctrl+u defaults to `config.core.backspace_line` in all three modes on every platform; it can be rebound or disabled with the ordinary per-mode binding interface. macOS additionally defaults Option+Backspace and Command+Backspace to word and line deletion respectively. Any platform can explicitly bind these actions to supported keys; for example, `config.bind "ctrl+w", config.core.backspace_word, mode: config.modes.insert`. Word deletion follows Unicode word boundaries after skipping trailing whitespace; line deletion removes the caret-to-logical-line-start prefix, not the suffix or newline. Active snippets confine both actions to their argument. macOS prompt and filter queries also recognize these modified Backspace keys.
|
||||
|
||||
Command-mode Tab defaults to `config.core.command_complete`, and Shift+Tab to `config.core.command_complete_previous`: complete a case-sensitive command-name prefix, then cycle alphabetical matches forward/backward with wraparound. Shift+Tab starts at the last match; switching direction retains the original prefix. Core commands, shorthand aliases, and enabled plugin commands share the candidate list; arguments are not completed. For example, `config.bind "ctrl+n", config.core.command_complete, mode: config.modes.command` adds another forward completion key. Override or disable Tab and Shift+Tab independently; Search-mode Tab remains literal text.
|
||||
|
||||
Configuration accepts the Option/Alt and Command/Super Backspace names on every platform, but terminal modifier-event translation for these keys is macOS-only. Native modifier events must deliver Option or Super (Command in Kitty CSI-u); Meta is not Command. Ghostty's default Command+Backspace encoding is Ctrl+u (`\x15`), which invokes the same line-deletion action without a Ghostty override. It remains a distinct Ctrl+u binding, not a reconstructed Command modifier. Legacy ESC+DEL supports Option+Backspace without keyboard protocol negotiation.
|
||||
|
||||
Normal mode uses literal `_` and `|` for above/below and left/right splits, and `alt+h/j/k/l` for directional pane focus. Bind the produced punctuation rather than a physical Shift combination. Close actions have no default binding; for example, `config.bind "leader x", config.core.pane.close`. See [panes and splits](editing.md#panes-and-splits) for shared-buffer and unsaved-change policies.
|
||||
|
||||
Normal mode binds `ctrl+option+h/l` (`ctrl+alt+h/l`) to previous/next tab. Tab actions have no default open/close binding; for example, `config.bind "leader t", config.core.tab.new` and `config.bind "leader x", config.core.tab.close`. See [tabs](editing.md#tabs) for layout preservation and close guards.
|
||||
|
||||
The built-in `gt`/`gb` sequences move to the first/last line in Normal and Visual; `gf` follows Markdown file links in Normal only. Bind `config.core.document_start`, `config.core.document_end`, or `config.core.follow_link` to another key or sequence to add another route. A configured/disabled `g`, a configured sequence starting with `g`, or choosing `g` as the leader overrides the built-in prefix in that binding mode.
|
||||
|
||||
With a decimal prefix, `g` instead jumps immediately to that one-based source line: `42g` goes to line 42, clamped at EOF, at first nonblank. Normal moves all carets; Visual extends selections. In diff text panes, explicit line jumps reveal folded source lines rather than counting only displayed excerpts. `g` without a count still begins `gt`, `gb`, or `gf`; a count followed by `g` is complete and does not await a suffix. Rebind the Normal/Visual native action `config.core.go_to_line` to use the numeric prefix with another key. Existing `g` bindings and prefixes override this default route.
|
||||
|
||||
Normal `yy` copies complete rows without moving the carets; `dd` / `cc` delete/change complete rows; `dw` / `db` delete forward/backward word spans within each caret's current logical line, preserving newlines. `cw` / `cb` cut the same spans and enter Insert. Leading and post-operator counts multiply and word edits stop at the line end/start. Bind `config.core.copy_line`, `config.core.delete_line`, `config.core.change_line`, `config.core.delete_word_forward`, `config.core.delete_word_backward`, `config.core.change_word_forward`, or `config.core.change_word_backward` to another key or sequence for another route. A configured/disabled operator key, a configured sequence starting with that key, or choosing it as the leader overrides its built-in operator prefix. These are dedicated actions, not general operator–motion grammar.
|
||||
|
||||
Normal `C` / `D` / `Y` change/delete/copy the cursor-to-line-end suffix through `config.core.change_to_line_end`, `config.core.delete_to_line_end`, and `config.core.copy_to_line_end`. Normal and Visual `r` wait for a literal replacement character through `config.core.replace_character`: Normal honors the count; Visual replaces each selected grapheme without replacing newlines. Normal `s` deletes the current grapheme and enters Insert through `config.core.substitute_character`. Rebinding these actions preserves their native counts, Unicode boundaries, undo, and read-only guards.
|
||||
|
||||
`f<char>` / `F<char>` seeks forward/backward on the current line in Normal and Visual, with counts such as `2fx`. Rebind `config.core.seek_forward` / `config.core.seek_backward` to a single key or leader sequence; the action then waits for a literal target character. For example, `config.bind "s", config.core.seek_forward` makes `2sx` seek the second following `x`. Pass `mode: config.modes.visual` to install a Visual route. These native-only actions do not have Ex commands.
|
||||
|
||||
Normal and Visual Ctrl+u/Ctrl+d invoke `config.core.scroll_step_up` / `config.core.scroll_step_down` without moving carets or selection endpoints. Counts multiply the configured `scroll_step_lines` distance (half a viewport by default). Bind `config.core.scroll_up` / `config.core.scroll_down` for one screen row per count, for example `config.bind "ctrl+e", config.core.scroll_down` to replace clone-below in Normal. Pass `mode: config.modes.visual` to rebind Visual too. These actions work in ordinary and diff text panes, use wrapped screen rows, and have no Ex commands. Cursor navigation or editing resumes caret following.
|
||||
|
||||
## Action reference
|
||||
|
||||
@@ -61,16 +259,38 @@ Key notation follows [Herdr's readable style](https://herdr.dev/docs/configurati
|
||||
| --- | --- |
|
||||
| Normal | `insert`, `append`, `open_below`, `open_above` |
|
||||
| Normal, Visual | `insert_first_nonblank`, `append_line_end`, `clone_above`, `clone_below` |
|
||||
| Normal | `join_lines`, `undo`, `redo`, `command` |
|
||||
| Normal | `join_lines`, `undo`, `redo` |
|
||||
| Normal, Visual | `command` |
|
||||
| Command | `command_complete`, `command_complete_previous` |
|
||||
| Normal | `copy_line`, `delete_line`, `change_line` |
|
||||
| Normal | `change_to_line_end`, `delete_to_line_end`, `copy_to_line_end`, `substitute_character`, `delete_word_forward`, `delete_word_backward`, `change_word_forward`, `change_word_backward` |
|
||||
| Normal, Visual | `replace_character` |
|
||||
| Normal | `save`, `force_save`, `quit`, `force_quit`, `restart`, `force_restart`, `save_and_quit`, `force_save_and_quit`, `plugins` |
|
||||
| Normal | `edit`, `buffers`, `buffer`, `buffer_next`, `buffer_previous`, `buffer_delete`, `buffer_force_delete` |
|
||||
| Normal | `follow_link` |
|
||||
| Normal | `diff`, `diff.mode.toggle`, `diff.view.toggle`, `diff.orientation.toggle`, `diff.review.toggle` |
|
||||
| Normal, Visual | `comment` |
|
||||
| Normal | `review.edit`, `review.delete`, `review.resolve`, `review.unresolve`, `review.next`, `review.previous`, `review.overview`, `review.copy`, `review.summary`, `review.verdict`, `review.save`, `review.open`, `review.new` |
|
||||
| Normal, Insert, Visual, Command, Search | `diff.close` |
|
||||
| Normal | `resolve`, `resolve.next`, `resolve.previous`, `resolve.use_source`, `resolve.source`, `resolve.base`, `resolve.next_file`, `resolve.previous_file`, `resolve.files`, `resolve.draft`, `resolve.history`, `resolve.view.toggle`, `resolve.close` |
|
||||
| Normal, Insert, Visual, Command, Search | `word_wrap.toggle` |
|
||||
| Normal, Insert, Visual, Command, Search | `git_blame.toggle` |
|
||||
| Normal | `pane.split_horizontal`, `pane.split_vertical`, `pane.focus_left`, `pane.focus_down`, `pane.focus_up`, `pane.focus_right`, `pane.close`, `pane.force_close` |
|
||||
| Normal | `tab.new`, `tab.previous`, `tab.next`, `tab.close`, `tab.force_close` |
|
||||
| Normal | `jump_back`, `jump_forward` |
|
||||
| Normal | `lsp.definition`, `lsp.diagnostics`, `lsp.hover` |
|
||||
| Normal | `search`, `paste_before`, `paste_after` |
|
||||
| Normal | `paste_system_before`, `paste_system_after` |
|
||||
| Normal, Visual | `select`, `search_next`, `search_previous` |
|
||||
| Insert | `lsp.completion`, `snippet.next`, `snippet.previous` |
|
||||
| Normal | `search`, `search_word` |
|
||||
| Normal, Visual | `paste_before`, `paste_after`, `paste_system_before`, `paste_system_after` |
|
||||
| Normal, Visual | `select`, `select_linewise`, `search_next`, `search_previous` |
|
||||
| Normal, Visual | `repeat_last_edit` |
|
||||
| Normal, Visual | `file_picker`, `file_explorer` |
|
||||
| Normal, Visual | `document_start`, `document_end`, `go_to_line` |
|
||||
| Normal, Visual | `seek_forward`, `seek_backward` |
|
||||
| Normal, Visual | `scroll_up`, `scroll_down`, `scroll_step_up`, `scroll_step_down` |
|
||||
| Normal, Insert, Visual | `line_start`, `line_end` |
|
||||
| Normal, Insert, Visual, Tree | `left`, `right` |
|
||||
| Normal, Insert, Visual, Selection, Tree | `down`, `up` |
|
||||
| Normal, Insert, Visual, Command, Search, Selection, Tree | `down`, `up` |
|
||||
| Normal, Insert, Visual | `word_next`, `word_previous`, `word_end`, `big_word_next`, `big_word_previous`, `big_word_end` |
|
||||
| Normal, Insert | `delete` |
|
||||
| Visual | `copy`, `cut`, `change`, `select_lines`, `select_next`, `skip_occurrence`, `select_all` |
|
||||
@@ -80,6 +300,20 @@ Key notation follows [Herdr's readable style](https://herdr.dev/docs/configurati
|
||||
| Insert | `newline` |
|
||||
| Command, Search | `submit` |
|
||||
|
||||
`core.select` (`v`) and `core.select_linewise` (`V`) select characterwise and whole-row Visual shapes. Switching selectors retains endpoints; pressing the active shape's selector again cancels. Both use `config.modes.visual`; there is no separate linewise binding mode. `core.select_lines` (Visual Ctrl+l) still splits touched rows into Normal carets.
|
||||
|
||||
`core.save` saves the current path; `core.save_and_quit` saves the active buffer and quits only if no buffer remains dirty. Both re-read disk text and compare its LF-normalized content with the saved baseline, refusing external changes or deletion with a warning. `core.force_save` and `core.force_save_and_quit` explicitly bypass that external-change check, but never historical-snapshot read-only protection, target-symlink rejection, or another loaded buffer's path ownership. Their canonical commands are `:force_save [path]` and `:force_save_and_quit [path]`, with aliases `:w!` and `:wq!`; guarded `:save [path]` / `:w` and `:save_and_quit [path]` / `:wq` remain unchanged. A new buffer opened at a nonexistent path may save normally. Configured force-save actions act immediately, without confirmation.
|
||||
|
||||
Live clean buffers reload external changes automatically, including inactive tabs/panes, using 250 ms metadata checks and reading content only when metadata changes. Historical snapshots are excluded; dirty buffers keep their edits. Reload clears stale undo/redo, preserves and clamps view positions, and invalidates outdated annotations/requests. Missing, unreadable, or invalid changed files preserve text and report a warning. This polling does not replace the actual-content recheck on save.
|
||||
|
||||
`core.quit` refuses unsaved changes in any buffer. `core.edit` and `core.buffer` open prefilled Ex prompts for their required path or buffer ID; deletion actions target the current buffer. Configured `core.force_quit`, `core.buffer_force_delete`, `core.pane.force_close`, and `core.tab.force_close` keys act immediately, without confirmation.
|
||||
|
||||
`config.core.buffers` opens the searchable buffer picker in Normal mode, also available as `:buffers` and default **Space b l**. Its navigation uses `config.modes.selection`, like the command palette. For example, `config.bind "leader b b", config.core.buffers` adds another opening shortcut. Search, acceptance, and cancellation are described under [Buffers](editing.md#buffers).
|
||||
|
||||
`core.restart` and `core.force_restart` have no default keybindings. Their no-argument commands are `:restart` and `:force_restart`, with `:restart!` as an alias for force restart. Normal restart closes clean buffers across every tab, pane, and historical view; any dirty buffer blocks the relaunch with a warning, retains its text and undo/redo history, and leaves the editor interactive without restoring the clean buffers already closed. Force restart discards unsaved text without writing it. The palette confirms force restart, while a configured `config.core.force_restart` binding executes directly.
|
||||
|
||||
Restart relaunches the same executable with the original CLI arguments after full session teardown. Raw mode and input reporting briefly reset, but the alternate screen remains active across the process handoff; the new process resumes input modes and clears and repaints the screen atomically in its first frame. It rereads configuration and the original startup file (or opens an unnamed buffer when no file was supplied), rather than restoring current buffers, tabs, views, or session state. Final quit, errors, and panics restore normal input modes, the normal screen, cursor visibility, and the prior panic hook.
|
||||
|
||||
## Binding overrides and failures
|
||||
|
||||
Adding a binding keeps the original key. Pass `nil` to disable a key, including literal typing in Insert/Command mode:
|
||||
@@ -93,13 +327,13 @@ Vamp.configure do |config|
|
||||
end
|
||||
```
|
||||
|
||||
The last valid declaration for a key/mode wins. Invalid keys, incompatible action/mode pairs, ambiguous leader prefixes, or unknown command names leave that binding unchanged and appear in the status message; other valid bindings still load. An invalid leader key reports a notice and retains Space, while valid bindings still install. Ruby syntax errors, unknown methods, and type errors—including non-string or empty leader values—disable the entire configuration and fall back to defaults. One plugin's load failure does not prevent other plugins loading. Disabling a plugin removes its single-key and leader bindings, without restoring any default keys they replaced.
|
||||
The last valid declaration for a key/mode wins. Invalid keys, incompatible action/mode pairs, ambiguous sequence prefixes, or unknown command names leave that binding unchanged and appear in the operation notification; other valid bindings still load. An invalid leader key reports a notice and retains Space, while valid bindings still install. Ruby syntax errors, unknown methods, and type errors—including non-string or empty leader values—disable the entire configuration and fall back to defaults. One plugin's load failure does not prevent other plugins loading. Disabling a plugin removes its single-key and sequence bindings, without restoring any default keys they replaced.
|
||||
|
||||
Bindings are resolved inside the editor module, not the terminal adapter. Bracketed paste remains literal and bypasses keybindings. If configuration disables your keys for leaving Insert/Command/Search/Visual mode or entering commands, restart with `--no-config` to restore defaults.
|
||||
|
||||
## Selection-list bindings
|
||||
|
||||
The palette, floating file picker, and focused docked explorer share `config.modes.selection`. It is a binding context, not a buffer editing mode. `config.core.down` moves to the next list item; `config.core.up` moves to the previous. Defaults are Ctrl+j/Down/Ctrl+n for next and Ctrl+k/Up for previous. Remap or disable any single key:
|
||||
The palette, floating file picker, focused docked explorer, and diff selectors/navigation share `config.modes.selection`. It is a binding context, not a buffer editing mode. `config.core.down` moves to the next list item (or scrolls aligned diff rows); `config.core.up` moves to the previous. Defaults are Ctrl+j/Down/Ctrl+n for next and Ctrl+k/Up for previous. Remap or disable any single key:
|
||||
|
||||
```ruby
|
||||
config.bind "ctrl+f", config.core.down, mode: config.modes.selection
|
||||
@@ -116,19 +350,56 @@ config.bind "ctrl+f", config.core.right, mode: config.modes.tree
|
||||
config.bind "ctrl+h", nil, mode: config.modes.tree
|
||||
```
|
||||
|
||||
The diff's changed-file explorer and floating picker use these same tree and selection contexts, including remaps and disabled keys. Enter opens the selected file's comparison; writable After reuses its live buffer. The catalog contains only changed paths, with A/M/D/R status markers, rather than a disk scan.
|
||||
|
||||
Ordinary `config.core.file_picker` and `config.core.file_explorer` bindings work inside comparisons. Ctrl+w closes a focused picker/explorer, retaining its query, selection, and expansion state; the panes use the reclaimed width. Ctrl+e has no reserved diff behavior. Escape closes the revision selector in either stage, but an opened comparison still closes explicitly through `:diff.close`, its palette action, or the generated action value below. `config.core.diff` remains the opening action and exposes immutable `close`, `mode.toggle`, `view.toggle`, and `orientation.toggle` children. New comparisons default to Branch changes (merge base → selected After); Normal-mode Ctrl+b, `:diff.mode.toggle`, or the palette toggles to direct Snapshots and back, preserving the selected endpoints. Selecting Checkout snapshot or Follow checkout forces Snapshots.
|
||||
|
||||
`config.core.diff.review.toggle` is a non-mutating Normal-mode action, also available as `:diff.review.toggle` and in the palette. It marks/unmarks the highlighted changed-file leaf when the comparison's explorer is focused, or the current comparison file from a text pane. Read-only snapshots permit review marks. The default `c` shortcut applies only while browsing the diff's changed-file tree; explicit bindings and disabled keys override it. For example, `config.bind "ctrl+g", config.core.diff.review.toggle`; use the palette or a control-key binding while filtering, including List view, so printable input stays in the query.
|
||||
|
||||
Local comments use `config.core.comment` in Normal or Visual mode in ordinary repository source buffers and diff text panes; the remaining `config.core.review` actions in the table above use Normal mode. File checkmarks use `config.core.diff.review.toggle`. These actions have no default bindings and are available through the palette and Ex commands. `edit`, `delete`, `resolve`, `unresolve`, `verdict`, `save`, and `open` open argument prompts when selected as actions. Comment IDs are optional and default to the overview entry under the caret or selected comment. For example:
|
||||
|
||||
```ruby
|
||||
config.bind "leader r c", config.core.comment
|
||||
config.bind "leader r c", config.core.comment, mode: config.modes.visual
|
||||
config.bind "leader r o", config.core.review.overview
|
||||
config.bind "leader r n", config.core.review.next
|
||||
```
|
||||
|
||||
Review editing uses a floating window without adding workspace splits. `:w` or `:review.save` commits comment/summary text, including hidden drafts; dismissing an editor discards its unsaved text, and switching editors does not save it. Verdicts, deletions, and resolution changes commit immediately without saving drafts. `:review.save path` additionally exports JSON without redirecting autosaves. `config.review_directory` defaults to `nil`, selecting `$XDG_DATA_HOME/vamp/reviews/` (absolute XDG path only), otherwise `~/.local/share/vamp/reviews/`. String overrides are resolved relative to the configuration file; empty/NUL-containing strings and non-string/non-nil values are rejected. These actions do not contact a forge. See [local review behavior](editing.md#repository-diff).
|
||||
|
||||
|
||||
`config.core.pane.close` and `config.core.pane.force_close` close a focused **docked** file list instead of its editor pane, without discarding buffers or exiting the comparison. A floating picker does not intercept these actions: normal close still protects underlying dirty buffers, while force-close retains its existing discard semantics. For example, bind `config.bind "ctrl+x", config.core.pane.close`; focused tree/selection overrides and printable filter input retain priority. Palette-originated close actions retain the originating dock target through force confirmation.
|
||||
|
||||
Focused selector/filter input receives printable text before Normal-mode action bindings, so `:` stays query text instead of opening Command input. Explicit tree/selection navigation overrides remain effective. Control-key editor action bindings and Ctrl+p remain available.
|
||||
|
||||
```ruby
|
||||
config.bind "leader d q", config.core.diff.close
|
||||
```
|
||||
|
||||
Ctrl+h is **not** a Backspace alias or default deletion key in any mode. Raw Ctrl+h (0x08) and Backspace (DEL/0x7f) are distinct, as are CSI-u events. In the tree it navigates in NORMAL and INSERT without deleting query text; it never deletes file-buffer Insert text by default. Explicit `config.core.backspace` bindings remain available if desired.
|
||||
|
||||
Ctrl+j is distinct from Enter: in the TUI's raw mode, LF is Ctrl+j and CR is Enter; CSI-u control events also work. No enhanced-terminal negotiation is required. Ctrl+m remains an Enter alias. Outside lists, existing editing bindings are unchanged: Ctrl+k still clones above in Normal/Visual, and explicit Ctrl+j defaults insert a newline in Insert or submit Command/Search prompts. Enter and Ctrl+j can now be rebound independently.
|
||||
Ctrl+j is distinct from Enter: in the TUI's raw mode, LF is Ctrl+j and CR is Enter; CSI-u control events also work. No enhanced-terminal negotiation is required. Ctrl+m remains an Enter alias. Outside completion and selection lists, Ctrl+k still clones above in Normal/Visual, and Ctrl+j inserts a newline in Insert. In Command/Search, Up/Ctrl+k (`config.core.up`) recalls older history and Down/Ctrl+j (`config.core.down`) recalls newer history or restores unfinished input; Enter alone submits by default. These prompt bindings can be overridden independently with `mode: config.modes.command` or `mode: config.modes.search`; they do not use `config.modes.selection`. While completion is open, Ctrl+j/k cycles candidates; Enter always closes completion and inserts a newline. Enter and Ctrl+j can be rebound independently outside the completion cycle.
|
||||
|
||||
## Leader key
|
||||
## Key sequences and leader
|
||||
|
||||
Space starts a leader sequence in Normal/Visual when it has no direct binding in that mode. Leader bindings use `leader` followed by whitespace-separated single-key names, for example `config.bind "leader b n", "bnext"`. Nested prefixes wait for the next key without a timeout. The status bar shows the actual pending sequence before the file path; the palette advertises effective sequences alongside ordinary bindings.
|
||||
Space starts a leader sequence in Normal/Visual when it has no direct binding in that mode. Leader bindings use `leader` followed by whitespace-separated single-key names, for example `config.bind "leader b n", config.core.buffer_next`. Nested prefixes wait for the next key without a timeout. The status bar shows the actual pending sequence before the file path; the palette advertises effective sequences alongside ordinary bindings.
|
||||
|
||||
Set `config.leader = ","` to change the trigger for every default and configured leader route. Suffix keys stay unchanged: the default palette binding becomes comma then Space, save becomes comma then `w`, and buffer-next becomes comma then `b` then `n`. Choose an unused single key in the existing notation; Escape, ASCII digits, malformed keys, and a new trigger already directly bound in Normal/Visual are rejected without replacing the current choice. A direct binding on the current trigger—including `nil`—takes precedence per mode and hides unreachable leader routes from the palette.
|
||||
Explicit prefixes use the same notation and do not change the leader:
|
||||
|
||||
Esc cancels a pending sequence and count without leaving Visual or collapsing carets. Unknown suffixes consume the key and cancel safely, never falling through to an edit. Paste, external command execution, buffer switching, and binding/leader changes clear pending state. A count before a leader motion applies normally; digits inside a sequence are literal suffix keys. Plugins execute once. Outside Normal/Visual, the leader has no prefix behavior, so Space still types normally in Insert and prompts.
|
||||
```ruby
|
||||
config.bind "ctrl+w h", config.core.pane.focus_left
|
||||
config.bind "ctrl+w j", config.core.pane.focus_down
|
||||
config.bind "ctrl+w k", config.core.pane.focus_up
|
||||
config.bind "ctrl+w l", config.core.pane.focus_right
|
||||
```
|
||||
|
||||
Leader bindings require Normal/Visual and the target's existing mode eligibility; Ex/plugin targets remain Normal-only. A sequence cannot be both a complete binding and another binding's prefix: ambiguous declarations are refused atomically. Disabled leaves remain reserved. Only leader-prefixed sequences are supported—not arbitrary multi-key mappings, timers, or macros.
|
||||
Press Ctrl+w, release it, then press the direction key. Modified suffixes and deeper nesting also work, for example `"ctrl+w ctrl+j"` or `"ctrl+w p j"`. Explicit prefixes must be unbound in that mode and cannot be Escape, an ASCII digit, or the current leader; use `leader` for symbolic leader routes. The prefix remains reserved while any of its leaves exists, including disabled leaves. Tree/selection navigation overrides retain priority while exploring files; configured control/special-key prefixes can start there, and pending suffixes then belong to the sequence rather than tree navigation.
|
||||
|
||||
Set `config.leader = ","` to change the trigger for every default and configured leader route. Explicit prefixes do not move. Suffix keys stay unchanged: the default palette binding becomes comma then Space, save becomes comma then `w`, and buffer-next becomes comma then `b` then `n`. Choose an unused single key in the existing notation; Escape, ASCII digits, malformed keys, and a new trigger already bound or reserved as a sequence prefix in Normal/Visual are rejected without replacing the current choice. A direct binding on the current trigger—including `nil`—takes precedence per mode and hides unreachable leader routes from the palette.
|
||||
|
||||
Esc cancels a pending sequence and count without leaving Visual or collapsing carets. Unknown suffixes consume the key and cancel safely, never falling through to an edit. Paste, external command execution, buffer switching, and binding/leader changes clear pending state. A count before a sequence motion applies normally; digits inside a sequence are literal suffix keys. Plugins execute once. Outside Normal/Visual, sequences have no prefix behavior, so ordinary text still types normally in Insert and prompts.
|
||||
|
||||
Sequences require Normal/Visual and the target's existing mode eligibility; Ex/plugin targets remain Normal-only. A sequence cannot be both a complete binding and another binding's prefix: ambiguous declarations are refused atomically, including collisions between a single-key binding and an explicit prefix. Disabled leaves remain reserved. Sequences wait without a timeout; timers and macros are not supported.
|
||||
|
||||
## Native LSP
|
||||
|
||||
@@ -138,7 +409,8 @@ LSP runs in Rust, independently of Ruby plugin hosts. **Every language server is
|
||||
Vamp.configure do |config|
|
||||
config.lsp["rust"] = true # rust-analyzer, extensions: ["rs"]
|
||||
config.lsp["ruby"] = true # solargraph stdio, extensions: ["rb"]
|
||||
config.lsp["python"] = false # disabled (also the default when absent)
|
||||
config.lsp["python"] = true # ty server + ruff server, extensions: ["py"]
|
||||
config.lsp["typst"] = true # tinymist lsp, extensions: ["typ"]
|
||||
|
||||
config.lsp["my-language"] = {
|
||||
command: ["my-language-server", "--stdio"],
|
||||
@@ -149,29 +421,92 @@ Vamp.configure do |config|
|
||||
config.bind "leader d", config.core.lsp.definition
|
||||
config.bind "leader D", config.core.lsp.diagnostics
|
||||
config.bind "K", config.core.lsp.hover
|
||||
config.bind "ctrl+n", config.core.lsp.completion, mode: config.modes.insert
|
||||
end
|
||||
```
|
||||
|
||||
Keys are arbitrary nonempty strings, used as the protocol's `languageId`; they need no Tree-sitter grammar or hardcoded language enum. Absent/`false` entries are disabled. `true` enables a built-in preset: `"rust"` uses `rust-analyzer`/`rs`, `"python"` uses `pylsp`/`py`, and `"ruby"` uses `solargraph stdio`/`rb`. Unknown keys need a configuration object with nonempty `command` argv and `extensions` (without leading dots). Objects also explicitly enable servers; known presets supply omitted command/extensions. For example, `config.lsp["rust"] = { command: ["/custom/path/rust-analyzer"] }` overrides the executable while retaining `rs`.
|
||||
Keys are arbitrary nonempty strings, used as the protocol's `languageId`; they need no Tree-sitter grammar or hardcoded language enum. Absent/`false` entries are disabled. `true` enables a built-in preset: `"rust"` uses `rust-analyzer`/`rs`, `"python"` uses `ty server` plus `ruff server`/`py`, `"ruby"` uses `solargraph stdio`/`rb`, and `"typst"` uses `tinymist lsp`/`typ`. Unknown keys need a configuration object with nonempty `command` argv or a `servers` list, plus `extensions` (without leading dots). Objects also explicitly enable servers; known presets supply omitted command/extensions. An explicit `command` replaces the entire preset with one server: `config.lsp["rust"] = { command: ["/custom/path/rust-analyzer"] }` retains `rs`, while a Python command override does not also launch Ruff.
|
||||
|
||||
Only `command`, `extensions`, `initialization_options`, and `settings` are accepted. Both option/settings values must be JSON-compatible objects and default to `{}`. Invalid declarations reject configuration with a notice rather than activating a guessed server. Server commands are executable/argument arrays, never shell commands; use an absolute path if the executable is not on PATH. No server installation or restart is automatic.
|
||||
Only `command`, `extensions`, `initialization_options`, `settings`, and `servers` are accepted. Options/settings must be JSON-compatible objects. Without an explicit command/list, options apply to every default server; explicit `initialization_options` replaces preset defaults. `servers` must be a nonempty ordered list of objects with explicit `command` and optional per-server `initialization_options`/`settings`; it shares language-level extensions and cannot be combined with top-level command/options/settings. Invalid declarations reject configuration with a notice rather than activating a guessed server. Commands are executable/argument arrays, never shell commands; use an absolute path if the executable is not on PATH. No server installation or restart is automatic.
|
||||
|
||||
Install Solargraph yourself with `gem install solargraph` in the project's Ruby environment. The Ruby preset launches `["solargraph", "stdio"]`, following [Solargraph's stdio integration](https://solargraph.org/guides/language-server), and uses [YARD annotations](https://solargraph.org/guides/yard) for type information. Explicit `command` overrides replace the entire argv: for a bundled installation, use `config.lsp["ruby"] = { command: ["bundle", "exec", "solargraph", "stdio"] }`; Vamp retains the `rb` extension but does not append `stdio` to your override.
|
||||
|
||||
Servers start lazily only when a matching buffer opens. Extension matching is case-sensitive; if enabled languages overlap, the first language in sorted key order wins. One worker runs per language configuration/project root, with at most 16 enabled languages/server-project keys. Start vamp from your project root: its startup working directory is the workspace; automatic root discovery is not implemented.
|
||||
Install [Tinymist](https://github.com/Myriad-Dreamin/tinymist#installation) separately and enable `config.lsp["typst"] = true` for `.typ` files. The preset launches `["tinymist", "lsp"]` with language ID `typst`; it does not enable preview or add export settings. Tinymist builds that return overlapping semantic tokens despite Vamp advertising no overlap support retain Tree-sitter highlighting and report the rejected tokens; hover and other LSP requests remain available. This occurs with the installed Typst 0.14.2-based build (`tinymist/v0.14.6-rc2`).
|
||||
|
||||
**Config-file lint style:** Solargraph's RuboCop reporter discovers `.rubocop.yml` from the Ruby file's directory, not Vamp's workspace. A config under `~/.config/vamp/` therefore does not inherit this repository's policy. To keep double quotes, multiline trailing argument commas, commented-out settings without a space after `#`, no required frozen-string header, and no block-length limit on `Vamp.configure`, place this `.rubocop.yml` beside `config.rb` (also for a custom `--config` path):
|
||||
|
||||
```yaml
|
||||
Style/StringLiterals:
|
||||
EnforcedStyle: double_quotes
|
||||
|
||||
Style/TrailingCommaInArguments:
|
||||
EnforcedStyleForMultiline: comma
|
||||
|
||||
Style/FrozenStringLiteralComment:
|
||||
Enabled: false
|
||||
|
||||
Layout/LeadingCommentSpace:
|
||||
Enabled: false
|
||||
|
||||
Metrics/BlockLength:
|
||||
AllowedMethods:
|
||||
- refine
|
||||
- Vamp.configure
|
||||
```
|
||||
|
||||
Syntax errors and other lint checks remain enabled. The block-length exemption applies only to `Vamp.configure`, alongside RuboCop's default `refine` exemption; ordinary blocks still have the normal limit. Restart Vamp after changing the policy so Solargraph reloads it; the Ruby config itself need not change.
|
||||
|
||||
**Python (Astral):** install [ty](https://docs.astral.sh/ty/editors/) and [Ruff](https://docs.astral.sh/ruff/editors/setup/) yourself, for example with `uv tool install ty` and `uv tool install ruff`. The Python preset sends the same documents to both servers, uses ty for hover/definition, and merges type errors with Ruff lint diagnostics. Clearing or losing one server preserves the other's diagnostics. Formatting and code actions remain unsupported by Vamp.
|
||||
|
||||
Use `servers` to customize the stack independently; order selects the hover/definition/completion server:
|
||||
|
||||
```ruby
|
||||
config.lsp["python"] = {
|
||||
servers: [
|
||||
{
|
||||
command: ["ty", "server"],
|
||||
initialization_options: { experimental: { useUv: "off" } }
|
||||
},
|
||||
{
|
||||
command: ["ruff", "server"],
|
||||
initialization_options: { settings: { lint: { extendSelect: ["I"] } } }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**uv remains optional project tooling.** Run project setup/synchronization yourself; [ty discovers an existing `.venv`](https://docs.astral.sh/ty/reference/configuration/#python) without a uv launcher. Vamp neither runs `uv sync` nor changes dependencies/lockfiles. The default ty preset sets `experimental.useUv: "off"` so inherited `TY_UV` cannot enable ty's [experimental environment-management integration](https://docs.astral.sh/ty/reference/editor-settings/). Ruff's initialization options default to `{}`. When replacing ty's initialization options, retain that flag if you want the same policy.
|
||||
|
||||
Servers start lazily only when a matching buffer opens. Extension matching is case-sensitive; if enabled languages overlap, the first language in sorted key order wins. All matching servers in that language run, and the first handles hover/definition/completion, semantic highlighting, and the diagnostic-status command without fallback to sibling servers. Each server/project root gets one worker, with at most 16 configured servers and 16 server/project keys; Python uses two slots. Start vamp from your project root: its startup working directory is the workspace; automatic root discovery is not implemented.
|
||||
|
||||
See [native LSP architecture](architecture.md#native-lsp) for synchronization and worker behavior.
|
||||
|
||||
`:lsp.definition` or the configured Space d binding requests a definition at the primary caret, once regardless of selection count. Both Location and LocationLink results are supported; multiple results use the first. Local-file navigation reuses loaded buffers without overwriting unsaved text. LSP UTF-16 positions and percent-encoded file URIs are translated to validated grapheme coordinates. Navigation is ignored if its source buffer, revision, caret, or latest request has changed.
|
||||
|
||||
For programmatic bindings, `config.core.lsp` exposes immutable Normal-mode Action objects: `definition`, `diagnostics`, and `hover`. Each routes to the same native implementation as its Ex command; no LSP keys are bound by default. These actions are also available in the command palette. The namespace is distinct from `config.lsp[language_id]` server configuration.
|
||||
Successful definition jumps center the destination caret's visual row once in its actual text pane, excluding bars and docks. This applies to ordinary buffers, new destination tabs, wrapped text, and split/unified diff panes. Near the beginning of the file, centering clamps to the first line; near EOF, blank space can remain below the centered target. Subsequent cursor motion resumes ordinary scrolling. Failed or stale requests do not request centering; Markdown links, search, and jump-history navigation retain their existing behavior.
|
||||
|
||||
For programmatic bindings, `config.core.lsp` exposes immutable Normal-mode Action objects `definition`, `diagnostics`, and `hover`, plus the **Insert-only** `completion` Action. Normal actions route to their corresponding Ex commands and have no default keys. Completion defaults to Insert Ctrl+n; override or disable it using an Insert binding. It requests directly without leaving Insert or committing pending typing; there is no Normal `:lsp.completion` command. These actions are also available in the command palette according to mode eligibility. The namespace is distinct from `config.lsp[language_id]` server configuration.
|
||||
|
||||
Interactive LSP commands use dotted names (`:lsp.hover`, `:lsp.definition`, `:lsp.diagnostics`). The existing whitespace separator keeps the whole dotted name separate from arguments. Current LSP commands take no arguments.
|
||||
|
||||
Diagnostics appear as severity-colored gutter numbers and text underlines; the primary caret's diagnostic appears in the message row. `:lsp.diagnostics` reports the current document's server state. Older versioned diagnostics are discarded; unversioned diagnostics can only be associated with the arrival-time document revision. Editing clears previous annotations immediately. Server startup/transport failures are reported and clear that server's diagnostics; other servers and native editing remain available. There are no automatic restarts.
|
||||
Diagnostics appear as severity-colored gutter numbers and text underlines; the primary caret's diagnostic can also appear in the bottom-right notification popup. `:lsp.diagnostics` reports the current document's server state. Older versioned diagnostics are discarded; unversioned diagnostics can only be associated with the arrival-time document revision. Editing clears previous annotations immediately. Server startup/transport failures are reported and clear that server's diagnostics; other servers and native editing remain available. There are no automatic restarts.
|
||||
|
||||
Insert mode hides all diagnostic gutter colors, underlines, counts, and caret messages. Incoming results are still stored; leaving Insert reveals only the latest results matching the current text revision. Editing invalidates earlier results, so stale annotations never reappear on exit. Document synchronization stays live for completion and semantic highlighting; this display policy does not stop server-side diagnostic analysis.
|
||||
|
||||
`:lsp.hover` or a configured hover action requests information at the primary caret once, regardless of count or selection count. The response opens a read-only floating popup: arrows/Ctrl+h/j/k/l scroll vertically/horizontally, Home/End select the first/last logical line, and Escape dismisses without collapsing carets. Other input dismisses and continues normal editing. Changes to the source buffer/revision/caret, intervening input, or newer requests prevent pending hover replies from reopening it.
|
||||
|
||||
Hover accepts plaintext/Markdown MarkupContent and string/code MarkedString forms, including arrays. Multiline content is preserved; Markdown is shown as plain text, not rendered markup. Horizontal scrolling exposes long lines without splitting graphemes. Missing/unsupported/invalid hover results report a message without changing text, selections, or undo history. Content is bounded to 4 MiB and terminal controls are sanitized.
|
||||
Hover accepts plaintext/Markdown MarkupContent and string/code MarkedString forms, including arrays. The popup grows up to 100 columns and 40 rows, clamped to the available document workspace and content height. Multiline content and Markdown markers remain visible, with the same Markdown syntax colors as document buffers; named fenced code blocks use their language's bundled highlighter. Highlighting is cached across scrolling and redraws. Horizontal scrolling exposes long lines without splitting graphemes. Missing/unsupported/invalid hover results report a message without changing text, selections, or undo history. Content is bounded to 4 MiB and terminal controls are sanitized.
|
||||
|
||||
Native LSP currently provides synchronization, diagnostics, go-to-definition, and hover—not completion, rename, formatting, code actions, workspace edits, or semantic highlighting. Tree-sitter remains the syntax highlighter.
|
||||
Completion is manual and uses only the primary insertion caret. Ctrl+n requests it; the first candidate replaces text immediately. While the list is open Ctrl+n/Ctrl+j selects next and Ctrl+k previous, including an Original text row that restores the original document and carets. Other keys close the list with no accept key. Snippets expand the whole template and highlight the first argument: typing replaces it and its mirrors, Tab/Shift+Tab moves next/previous, and the final `$0` ends navigation. Outside a snippet Tab inserts a tab; Escape returns to Normal keeping the displayed text. Secondary carets are translated, not completed independently. Cycling and argument edits belong to the pending Insert undo group; repeat records resolved text and caret placement. Rebind the Insert-only `config.core.snippet.next` / `config.core.snippet.previous` actions normally. See [editing behavior](editing.md#manual-lsp-completion).
|
||||
|
||||
The first assigned server must advertise a completion provider. Vamp handles item arrays and CompletionList results, plain text, TextEdit, InsertReplaceEdit (using its replacement range), supported edit-range/format/mode defaults, and atomic additionalTextEdits in the same document. Insert-only fallback text replaces the identifier prefix before the caret; `filterText` and stable `sortText`/label ordering are honored. All edit coordinates are validated at UTF-16 and grapheme boundaries against the immutable request document; malformed or overlapping edits report a completion error without retiring a healthy server. Aggregate completion text is bounded to 4 MiB. Pending replies cannot reopen completion after intervening input, source changes, superseding requests, or modal overlays.
|
||||
|
||||
Supported [LSP snippet syntax](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#snippet_syntax) includes numbered tabstops, nested placeholders/defaults, mirrors, escapes, choices (first option), variable defaults, and `TM_SELECTED_TEXT`, `TM_CURRENT_LINE`, `TM_CURRENT_WORD`, `TM_LINE_INDEX`, `TM_LINE_NUMBER`, `TM_FILEPATH`, `TM_FILENAME`, `TM_FILENAME_BASE`, and `TM_DIRECTORY`. Insert has no selected text, so `TM_SELECTED_TEXT` is empty unless a default is supplied. Unsupported regex transforms, unknown variables without defaults, repeated/nonempty final `$0`, or final stops nested inside arguments omit that candidate. Malformed templates report a completion-local error. Each template and expansion is bounded to 256 KiB, with 4096 parsed nodes, 1024 placeholder occurrences, 32 nesting levels, and a bounded rendering traversal.
|
||||
|
||||
There are no automatic triggers, commit characters, server commands, indentation adjustment, or completion-item resolve requests. Items requiring commands or indentation adjustment are omitted rather than partly applied. Server-specific availability depends on the installed server's advertised capabilities; configuring a preset does not guarantee completion support.
|
||||
|
||||
Semantic highlighting is **enabled automatically** when the first server advertises [LSP semantic tokens](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens). No additional configuration or binding is needed. Full-document requests are preferred; range-only servers receive a whole-document range request. Token colors override Tree-sitter where recognized; unsupported servers, unknown custom token types, missing tokens, and failed replies retain syntax highlighting. Text/path changes clear old semantic colors immediately, and stale replies cannot restore them. Same-text refreshes keep the current overlay until the replacement arrives.
|
||||
|
||||
rust-analyzer and ty support semantic tokens. Solargraph 0.61.0 and Ruff do not; Ruby therefore retains Tree-sitter colors with the Solargraph preset, while Python uses ty's tokens and Ruff's diagnostics. Declaration/definition modifiers use bold, deprecated symbols use strikethrough, and readonly variables/parameters/properties use italics without changing their role's color. Diagnostics, search, selections, and carets retain their existing styling precedence.
|
||||
|
||||
Native LSP currently provides synchronization, diagnostics, go-to-definition, hover, manual completion, and semantic highlighting—not rename, formatting, code actions, or general workspace edits. Semantic token deltas, dynamic registration, and partial-result streaming are not implemented.
|
||||
|
||||
+117
-7
@@ -8,14 +8,23 @@ Local verification and implementation constraints. See [architecture](architectu
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
cargo test -p crossterm color_scheme_notifications
|
||||
cargo test -p crossterm --doc
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo fmt --check
|
||||
cargo fmt --package vamp --check
|
||||
rustfmt --edition 2024 --check tests/unit/battery_macos.rs tests/unit/clipboard_macos.rs
|
||||
for file in src/ruby_*.rb examples/config.rb examples/plugins/greeting.rb; do
|
||||
ruby -c "$file" || exit
|
||||
done
|
||||
rubocop
|
||||
```
|
||||
|
||||
The default workspace member is the editor. `vendor/crossterm` is included to test its minimal DEC 2031 notification decoder patch; the rest of its source retains upstream formatting. The decoder checks cover fragmented reports and keyboard recovery, and its doctests verify the added event does not break upstream examples.
|
||||
|
||||
`vendor/tree-sitter-honey` contains a minimal Rust binding plus the unchanged generated parser, parser header, and highlight query from [`valdemar/tree-sitter-honey`](https://github.com/valdemar/tree-sitter-honey), revision `10f1ff746fe57736ae7d7c8c402f7b265680b26c` (MIT). Builds do not depend on a sibling checkout or an installed Tree-sitter CLI. To update, copy `src/parser.c`, `src/tree_sitter/parser.h`, and `queries/highlights.scm` from the same grammar revision, update the revision recorded here, and run `cargo test --lib syntax::tests`.
|
||||
|
||||
Typst uses the published [`codebook-tree-sitter-typst` 0.12.1 grammar](https://docs.rs/codebook-tree-sitter-typst/0.12.1/codebook_tree_sitter_typst/), aliased as `tree-sitter-typst` and pinned because the crate does not export queries. `src/syntax/languages.rs` supplies supported highlight captures and standard raw-code injection captures against that grammar's AST. After changing the grammar or query, run `cargo test --lib syntax::`; coverage includes Typst markup/code, incremental edits, Markdown fences, and embedded Rust. Live network-denied PTY smoke verifies heading/keyword/string/function colors, the opt-in Tinymist status, an unknown-variable diagnostic, and a `text()` hover signature with unchanged source bytes.
|
||||
|
||||
## Ruby types
|
||||
|
||||
Use YARD `@param`, `@return`, and `@yieldparam` annotations for Ruby APIs, and `@type` for locals where inference needs help. Examples annotate DSL block parameters before the call, without adding runtime assignments or dependencies. `Vamp::Action` / `Vamp::Mode` field types and the dynamically defined mode methods use Solargraph-supported directives.
|
||||
@@ -30,19 +39,120 @@ Rust embeds the Ruby implementation at compile time: [`ruby_values.rb`](../src/r
|
||||
|
||||
## Test organization
|
||||
|
||||
Rust tests live alongside their modules; native LSP integration checks are in [`tests/lsp.rs`](../tests/lsp.rs).
|
||||
Rust tests live under [`tests/`](../tests/). Private unit tests are in [`tests/unit/`](../tests/unit/), linked from their owning modules with `#[cfg(test)]` and `#[path]`; nested macOS modules use `include!` to retain their private/platform scope. Root `tests/*.rs` files remain Cargo integration targets, including native LSP checks in [`tests/lsp.rs`](../tests/lsp.rs).
|
||||
|
||||
`cargo test` runs both groups; `cargo test --lib` and `cargo test --bin vamp` select the library and CLI unit suites. Do not name a unit file `tests/unit/main.rs`: Cargo would discover it as a separate integration target.
|
||||
|
||||
### External-service isolation
|
||||
|
||||
Tests must not contact real websites or APIs. Forge tests inject JSON responses through `page_with`, `metadata_with`, and `resolve_with`; listing workers inject fetch closures. Repository remotes are temporary local repositories (including missing local paths for failure cases). LSP servers, Ruby plugins, and shell commands are local fixture subprocesses. The SSH alias check uses `ssh -G` with a temporary config to inspect configuration without connecting.
|
||||
|
||||
On macOS, verify external-service isolation with networking denied for Cargo and all descendants:
|
||||
|
||||
```sh
|
||||
sandbox-exec -p '(version 1) (allow default) (deny network*)' \
|
||||
cargo test --offline --no-fail-fast -- --test-threads=1 \
|
||||
--skip shell::tests::completed_shell_does_not_leave_background_jobs_holding_output_open \
|
||||
--skip shell::tests::dropping_shell_kills_and_reaps_group_with_pipe_inheriting_descendant
|
||||
cargo test --offline --lib shell::tests:: -- --test-threads=1
|
||||
```
|
||||
|
||||
Dependencies must already be cached. `--offline` prevents Cargo downloads; it does not block networking by tests or subprocesses. The sandbox supplies that boundary, including for real Git/jj operations and fixture programs; do not replace those local integration checks with mocks.
|
||||
|
||||
The two skipped shell cleanup checks execute `/bin/ps`, which macOS refuses to launch even under an allow-all sandbox profile; run them outside the sandbox as shown. Serial execution avoids contention in subprocess fixtures with production deadlines.
|
||||
|
||||
### Coverage
|
||||
|
||||
- Editor checks cover Unicode editing, multi-target state, undo/redo, saving failures, and modal paste acceptance and rejection atomicity.
|
||||
- Prompt-history checks cover separate session-wide command/search entries, Unicode draft restoration, editable recalls, clamped/empty/bounded history, duplicate/empty/cancelled submissions, remapped/disabled keys, and preserved Visual/read-only diff targets. Live PTY smoke exercises arrows and raw Ctrl+k/j, restores drafts, accepts a recalled search with Enter, and checks command/search isolation and unchanged source bytes.
|
||||
- Command-completion checks cover forward/backward alphabetical cycling/wrap across core names, aliases and live plugin registrations, reverse-first completion and direction changes retaining the prefix, explicit execution, edits/history/cancel resets, empty/unknown/Unicode prefixes, untouched arguments, remapped/disabled keys, and preserved Visual/read-only diff targets and literal search tabs. Live PTY smoke cycles `tab.*` in both directions through wraparound, submits a completed `tab.new`, and exits with unchanged source bytes.
|
||||
- Shell-command checks use file-gated subprocesses to prove editing remains live, stdout/stderr/status and cwd handling, null stdin, output bounds, launch/worker errors, and process-group cleanup on completion/drop. Spinner timing uses an injected `Instant`; render checks cover scrolling, dismissal, hidden source caret, and tiny/offset windows. Live PTY smoke gates completion, saves an edit while pending, then observes both output streams and exit status and dismisses the popup.
|
||||
- Visual-command checks preserve directed characterwise/linewise ranges and multiple carets through command cancellation and plugin dispatch, exercise remapped command entry, and submit `:comment` on either historical side. Live PTY smoke selects lines, cancels a prompt, then runs `:comment` directly and verifies the saved original range without using the palette.
|
||||
- Presentation regressions render retained characterwise/linewise highlights during command entry in ordinary, split-diff, and unified views. Floating-review checks preserve source rectangles and the workspace layout, place the caret inside the overlay, retain explicitly saved text across tab switches, and restore source focus on Escape or pane close.
|
||||
- Review prose checks render long comments and summaries with wrapping enabled by default in split/unified views, preserve exact single-line text and source wrapping, and retain an explicit wrap toggle on reopening. Live PTY smoke displays a long comment across continuation rows, saves it, verifies exact text through the review CLI, and reopens it still wrapped.
|
||||
- Precise-range checks cover forward/reversed characterwise and partial-multiline selections on both sides, linewise and caret/empty-line fallbacks, source-column navigation, Unicode grapheme bounds, invalid schemas, and preserved save-conflict checks. Render checks cover exact text/newline cells, wrapping, horizontal clipping, shared unified context, stale suppression, and native Visual precedence. Live PTY smoke saves and reopens a selection containing a wide and combining grapheme.
|
||||
- Markdown navigation checks cover inline/reference destinations, escaped/percent-encoded paths, heading markup and duplicates, same-document fragments, dirty target reuse, failed navigation atomicity, primary-only following, and `gf` prefix cancellation/configuration overrides.
|
||||
- Jump-history checks cover cross-buffer/same-document navigation, search and picker recording, counts and repeated visits, bounded history, branch truncation, closed buffers, edited-coordinate clamping, dirty text/undo preservation, independent Ctrl+i/Tab bindings, and custom bindings. Diff checks exercise Ctrl+i on either side in split/unified views, both control-letter and modified-Tab terminal events, and plain Tab pane cycling. Real LSP fixtures cover definition round-trips and delayed replies after leaving and returning to the same source location.
|
||||
- Tab checks cover shared edits/history with independent pane layouts, focused views, explorers and viewports; cross-tab close guards, immutable snapshots, hidden comparison refresh/result routing, and separate repository workers. Rendered checks cover sanitized/dirty titles, active-tab visibility in narrow terminals, overlay row reservation, and exclusion of hidden diff geometry from palette polling and viewport reporting.
|
||||
- Session and Ruby checks exercise real Ruby execution, command/capability ownership, effect validation, configuration fallback, plugin retirement, crash/timeout recovery, and inherited-pipe cleanup.
|
||||
- Unix terminal-hook checks use isolated child processes and real PTYs to keep process-global hooks out of the parallel runner. They cover cleanup on entry failure, normal return, I/O errors, and panics, including original panic-payload propagation.
|
||||
- Native LSP integration checks launch framed-protocol fixture subprocesses, covering initialization/settings, opt-in startup, synchronization, UTF-16/file-URI conversion, dirty targets, stale requests/diagnostics, and transport failures.
|
||||
- Hover regression checks cover content forms, sanitization, cancelled/superseded replies, invalid results, scrolling/dismissal, Unicode clipping, and preserved editing state.
|
||||
- For chrome changes, exercise anchor/template validation, padding/edge bounds, all builtin/custom segments in either bar, named startup values, and atomic live label batches. Rendering regressions should cover swapped bars across ordinary/split/diff/selector views, full-row center anchoring, terminal-cell glyph widths, empty-content row removal, tabs-only singleton hiding in either position, active-tab preservation, padding inside styled edges, and separate prompt geometry. Labels are session-wide presentation state: test cross-tab/read-only updates and unchanged-value redraw behavior without collecting real battery data or invoking render callbacks.
|
||||
- Battery checks inject samples and refresh gates, use temporary Linux sysfs fixtures, and validate native value types/bounds without depending on the machine's charge or clock. Unit sessions do not automatically read hardware. Live smoke should compare the default indicator with OS telemetry and observe a production refresh; no-battery, explicit overrides, and disabled anchors must not fabricate values.
|
||||
- Status redesign checks cover component-aware home abbreviation without save-path changes; floating command/search submit/cancel, Unicode/tiny/offset clipping and wheel isolation; footer-row reclamation; notification Escape/modal/prefix priority and covered-caret visibility; and ready-server metadata using real framed subprocess fixtures, including stacks, initialization gates, failure, and focus changes.
|
||||
- Unix terminal-hook checks use isolated child processes and real PTYs to keep process-global hooks out of the parallel runner. They cover raw/alternate-screen/mouse-capture cleanup on entry failure, normal return, I/O errors, and panics during frame construction, including original panic-payload propagation.
|
||||
- Redraw checks inspect actual Crossterm output during repeated scrolling: supporting terminals receive synchronized frames, terminals ignoring synchronization never paint with a visible hardware cursor, and the final software caret remains visible. A protocol-state regression verifies that the terminal is not left in synchronized-output mode while the next frame is computed.
|
||||
- Cursor checks render software block/bar/underline shapes, wide/combining graphemes, cell restoration after motion, neutral reverse-video blocks, and shared ANSI mode accents on both banners through Normal, Insert, Visual, Command, and Search. The production backend preserves logical cursor coordinates without showing the hardware cursor. Live PTY screen parsing and an isolated Herdr 0.9.5 full-client smoke verify that mode-colored cells survive multiplexing, match both banners, avoid OSC 12, leave source bytes unchanged, and restore hardware visibility on exit. Document-layer fixtures exclude the final cursor overlay; complete-frame checks use `BufferViewports` with the production backend adapter.
|
||||
- Wheel checks render document/panel views and cover three-row scrolling, unchanged carets/selections/text, first/last-page clamping, offscreen cursor hiding, no-op/custom-bound navigation reveal, manual persistence through idle/resize/palette updates, and floating/unfocused-docked explorer selection and focus preservation. Queued-input checks verify that the next frame shows ordered wheel steps without crossing a key or resize boundary.
|
||||
- Queued-navigation checks cover counted ordered motions through short rows, Normal/Visual ranges, remapped press/repeat keys, rendered caret visibility, edit/layout/prefix and non-key barriers, and the 64-key fairness bound. Burst smoke must verify the final cursor position as well as frame count; batching reduces queued redraws without increasing the OS/terminal repeat rate.
|
||||
- Native LSP integration checks launch framed-protocol fixture subprocesses, covering initialization/settings, opt-in startup, synchronization, UTF-16/file-URI conversion, dirty targets, stale requests/diagnostics, and transport failures. Stack checks cover independent initialization, diagnostic merging/clearing, sibling failure isolation in active/parked buffers, same-revision rename/close identity, aggregate limits, first-server position routing, and both shutdowns. Semantic ordering uses protocol/file gates; elapsed deadlines only bound stuck subprocesses.
|
||||
- Hover regression checks cover content forms, sanitization, cancelled/superseded replies, invalid results, scrolling/dismissal, Unicode clipping, and preserved editing state. Rendered checks cover longer/wider documentation visibility, Markdown heading and fenced-code colors, scrolled color coordinates, and replacement content without stale highlighting.
|
||||
- Semantic-token checks cover full/range requests, legend/modifier remapping, UTF-16 boundaries and grapheme rounding, ASCII tab and Unicode column bounds, refresh/change coalescing, stale rename/close replies, null/empty/error fallback, primary/sibling retirement, and rendered cell precedence with syntax, diagnostics, search, selections, and carets. Retention checks cover typing/undo/redo in editable diffs, column/newline/Unicode remapping, overlapping-token removal, and session polling with delayed/stale server replies. Live PTY smoke holds semantic replies while typing and undoing/redoing, checking that untouched colored text is not repainted in the fallback color.
|
||||
|
||||
Clipboard checks use isolated providers rather than reading or overwriting the desktop clipboard.
|
||||
Clipboard checks use isolated providers rather than reading or overwriting the desktop clipboard. Normal `x`/Delete regressions cover Unicode graphemes, remapped actions, multiple carets with empty rows, characterwise paste, undo/redo, dot-repeat publication and failure atomicity, and unchanged Insert Delete behavior. Live PTY smoke cuts a combining grapheme, repeats over a ZWJ emoji, pastes, undoes/redoes, and checks exact saved bytes using Separate mode.
|
||||
|
||||
Diff checks cover staged category/filter navigation, stale request cancellation, row alignment, read-only buffer isolation, and rendered panes. Repository integration fixtures exercise Git and Git-backed jj, advertised but unfetched remote branches/bookmarks/tags, imported historical commit/change IDs, conflicts, unusual paths, binary/mode/link/submodule changes, and unchanged active metadata. Remote fixtures are local bare copies; they never push. Git fixture identities and commit dates are fixed.
|
||||
|
||||
Pull-request checks cover ranked sort menus, rank collisions/default slots, timestamp directions, independent personal review flags, checkbox unions, Apply/Cancel, category/query composition, streamed updates, and selection identity. Storage and session checks cover restart persistence, config section overrides, corrupt/incompatible-file preservation, and failed writes with isolated paths. Live PTY smoke at 100×24 and 44×16 exercises checkbox Apply/Cancel, restart restoration, creation-rank movement and ascending direction, and a config filter override. All forge responses come from a disposable curl fixture; the editor and descendants run with networking denied.
|
||||
|
||||
Session-filter regressions verify no file creation on filter Apply, retention across picker reopenings, restart reset, and saved sorting without filter data. Previously saved filters, including invalid legacy values, are ignored without altering valid sorting or changing the file on load. Live network-denied PTY smoke checks these transitions plus configured filter restoration and the active-filter indicator.
|
||||
|
||||
Diff-stat checks cover unopened frozen files, additions/deletions/renames, binary/mode changes, CRLF/EOF, refresh, oversized-file laziness, filtering, live edits/undo, and inactive tabs. Live PTY smoke opens a two-file Git Working comparison, observes selected-file `+2 -1` alongside whole-diff `+2 -2` before opening the second file, edits and undoes text, switches to an ordinary tab, and exits with source bytes and HEAD unchanged.
|
||||
|
||||
Local review checks cover native comment/summary composition and undo, Visual ranges on either side, verdicts, JSON save/reopen, external-write refusal, hidden drafts and teardown guards, immutable Working identities in Git/jj, renamed paths, live EOF, and stale anchors. Render checks cover selected/range markers, split/unified context, wrapped continuations, and narrow gutters. Live PTY smoke creates and saves a comment/summary/verdict, closes and reopens the review, edits the reopened comment, changes the reviewed source, and observes stale status without altering the saved anchor. Fixtures are local repositories; no forge writes.
|
||||
|
||||
Ordinary-source review checks cover unsaved Unicode selections, line/empty-line anchors, no storage creation on initialization, explicit save/discard, optimistic conflicts, tab/pane guards, JSON round-trips, stale read-only snapshots, and rendered exact-range markers. Review selection separates source and comparison scopes even within one tab; dirty drafts guard transitions, and mismatched stored/JSON opens cannot reassign feedback. Review state remains tab-owned, with the selected document scoped to its source or comparison.
|
||||
|
||||
Review clipboard checks cover System/Separate routing with isolated providers, exact Unicode excerpts, resolved/stale comments across files, retained unsaved drafts, unchanged storage revisions, and empty/invalid/failed-copy preservation. Live PTY smoke imports a review, copies it, pastes into an empty buffer, and verifies the saved bytes exactly match CLI `show --all`; default CLI output still excludes resolved comments.
|
||||
|
||||
Review text-format checks cover language-tagged excerpts, Honey's `hon` fence alias, special filenames and frozen shebang detection, unknown languages, Unicode, trailing-newline preservation, and nested backtick fences. Live PTY/CLI smoke imports `.hon` and nested Markdown comments, copies/pastes them into a saved buffer, compares its exact bytes with `show --all`, and verifies unresolved filtering, raw JSON excerpts, unchanged source bytes and an unchanged stored review revision.
|
||||
|
||||
SQLite review checks cover exact anchors, ordered comparison-scope round-trips and immutable scope saves, repository isolation, independent connections and optimistic conflicts, locked/unwritable stores, incompatible schema preservation, relational constraints, full unsigned comment IDs, stable comment order, bounded/corrupt rows, rollback after partial comment insertion, private file permissions, and XDG/config path resolution. SQLite schemas through 3 and JSON versions through 4 are rejected without modification. Editor checks cover automatic selection for different endpoint pairs, restoration of the same pair, stable in-place Working refreshes, moved-bookmark scope changes, separate source feedback, per-scope selectors, and explicit draft-save/discard behavior. Live PTY/CLI smoke saves feedback on two immutable pairs, reopens the first to restore only its feedback, retains Working feedback through refresh, saves a separate source comment, and inspects all scopes through SQLite and CLI JSON. Fixtures use isolated repositories and review directories; no forge writes.
|
||||
|
||||
Manual-resolution checks cover immediate persistence, reopen/export/import, independent stale status, conflict-retained drafts, and incompatible version preservation. CLI checks cover filename-safe dispatch, Unicode excerpts, unresolved filtering/counts, absent storage, read-only access and permissions, symlink rejection, and incompatible schema preservation.
|
||||
Live PTY/CLI smoke composes and explicitly saves a comment, resolves it in the editor, observes an empty default CLI comment list with explicit counts, retrieves the resolved comment and exact excerpt with `--all`, and unresolves it. Each transition advances the same stored review revision; listing absent storage creates no data directory.
|
||||
CLI deletion checks exercise explicit review/comment IDs, resolved-comment deletion, repository isolation, preserved summaries/verdicts/other comments, last-comment deletion, missing targets/storage, and stale-save conflicts through the executable. CLI smoke verifies persisted deletion and rejects a repeated deletion without advancing the review revision.
|
||||
CLI resolution checks exercise positive review/comment IDs, preserved bodies/immutable anchors and other review metadata, unresolved filtering/full counts, `show --all`, repository isolation, missing/invalid targets and absent storage, idempotent repeats without revision changes, and stale-save rejection through the executable. CLI smoke: show a review as JSON, resolve one comment with `--repo PATH --json`, confirm counts and default filtering, show it again with `--all` to compare the original body/anchor/excerpt, and repeat resolution to confirm an unchanged storage revision.
|
||||
Relational-storage smoke inspects typed review/comment columns, round-trips exact Unicode anchors through the store and JSON export/import, deletes through the real CLI, and confirms the stored review and existing export remain intact.
|
||||
Reviewed-file checks cover SQLite/JSON round-trips, unmarking, exact revision pairs and rename paths across catalog reordering, lazy loading, live text/final-newline mismatch, edit-triggered invalidation, selected-review isolation, hidden-draft isolation, conflicts, and transactional rollback. Live PTY smoke marks a file in a real Git comparison, verifies the SQLite row, restarts the editor, observes the restored checkmark, unmarks it, and verifies row removal with unchanged source bytes.
|
||||
Per-file persistence also exercises a real Git Working comparison: mark two lazy files, save/reload the review, edit one file, refresh the snapshot, and retain only the unchanged file's mark through detail loading.
|
||||
|
||||
|
||||
Conflicted-revision regressions preserve unchanged symlinks, defer oversized unselected blobs until file selection, compare selected conflict text with jj's projection, and exclude unchanged conflicts when comparing later revisions. Live terminal smoke covers local bookmark selection and opening an actual conflicted file without changing the checkout.
|
||||
|
||||
Resolver checks use isolated real jj repositories: read-only discovery, marker-free all-side/base projections preserving outside edits and EOF, initial seed undo, hunk choice/undo, retained resolved files, jj-authoritative status, checkout/external-write refusal, cancellation, nontext bytes/types/modes/deletion, and directory-child protection. Render checks cover aligned gaps/highlights, context folding, native Draft focus/search/selection, separate History, hidden/on-demand explorer, viewport retention and narrow layouts. Live PTY smoke exercises frozen marker-free alternatives, History/Draft switching, hunk choice and guarded save confirmation without touching user repositories.
|
||||
|
||||
Base-relative resolver regressions cover red display-only removals and green native additions on both sides, deletion/replacement gaps, add/add without a base, native-coordinate round trips and EOF rows. The rendered workspace check exercises both split orientations and unified mode, native edits, hunk choice/undo, and both History layouts. Live PTY smoke checks actual red `-` and green `+` cells on both candidates, opens columns/base-below History, verifies browsing leaves conflict bytes untouched, and takes/saves an Alternative with exact output bytes and jj confirmation.
|
||||
|
||||
Conflict History layout checks load `resolve_history_layout` through the real Ruby configuration and render both left/base/right columns and left/right over base. They cover source contents, full-width base geometry, Tab/directional focus, synchronized wheel scrolling, read-only base protection, narrow/short fallbacks and preserved Draft text. Live PTY smoke opens both layouts, focuses/scrolls the base, returns to Resolution, takes a hunk and saves; jj confirms the checkout is no longer conflicted.
|
||||
|
||||
Shared-workspace checks exercise ordinary and resolver diffs with native chrome, focus and source cursors. Cover native picker selection/remaps, Tree/List and dock/floating actions, excerpt initialization, folded search, focus transfer on wheel, layout controls, loading/History/pane-rebuild transitions, and preserved per-file viewport state. Live PTY smoke uses Space e, Down/Enter file selection and guarded saving through the same explorer path.
|
||||
|
||||
Repository gutter checks cover LF/CRLF normalization, additions/replacements/deletion anchors, staged/disk/unsaved Git text, unborn and missing named files, ignored/unsupported paths, read-only colocated/non-colocated jj queries, stale results and per-buffer isolation, plus rendered modes, colors, current-line precedence, wrap/scroll and narrow/split geometry. Live PTY smoke verifies all four modes, edit/undo refresh, external Git HEAD changes, and jj parent changes without editor restart.
|
||||
|
||||
Blame checks cover selected historical commits rather than live HEAD, renamed/deleted paths, unsafe/nonregular sources, Git-backed non-colocated jj, and privately fetched objects surviving comparison/repository teardown until the final snapshot releases them. Render/session regressions cover both split/unified sides, stale side results, wrapping, narrow panes, detached historical tabs, and Working attribution. Live PTY smoke opens both historical sides and unified view after deleting the file from the checkout, observes the correct commit labels, opens a historical tab, and exits with unchanged HEAD and tracked state.
|
||||
Partial-label checks navigate short and longer source lines with wide/combining author names and long commit summaries in ordinary, split, and unified views. Live PTY smoke repeats three-line navigation in split/unified views with a long summary, observing attribution on every source line with unchanged source bytes and HEAD.
|
||||
|
||||
Normal-picker checks cover staged/disk/unsaved status, binary and mode changes, exact and ambiguous renames, deleted paths, unborn repositories, aliases and unusual filenames, ignores and safe roots, linked worktrees, and read-only colocated/non-colocated/conflicted jj parents. Catalog/render checks retain unchanged rows, query/selection/expansion and Tree/List navigation, clear stale metadata, restore recreated files, and sanitize rename labels. Live PTY smoke checks A/M/D/R colors in floating and docked pickers with the line gutter disabled, Git HEAD/jj parent refresh, and unchanged jj operation state during polling.
|
||||
|
||||
Diff LSP integration checks reuse the real framed-protocol subprocess with test-controlled response/publication gates and local Git comparisons. Cover both immutable historical sides and writable Working After, snapshot text/URI isolation, Unicode UTF-16 requests/targets/diagnostics, normal overlong-column clamping, hover, completion/undo, and read-only editing guards. Definition routing must distinguish ranges overlapping actual changed rows from wholly unchanged/context/omitted targets, use full location-link target ranges with exact selection reveal and exclusive endpoints, route canonical aliases and old/new rename paths, load other changed files on demand, handle added/deleted files, preserve original tabs/panes/excerpts and shared dirty targets, retain snapshot identity in ordinary tabs, and fail atomically for missing/non-UTF-8 files, invalid ranges, and unsupported URIs. Delayed/superseded replies must remain stale across caret moves, edit/undo, side/file/pane/tab changes, and comparison closure/replacement; publications for disposed snapshot identities must not reach their replacements. Private editor checks gate pending repository-load cancellation and exact-row reveal without timing assumptions. Before marking the TODO complete, run native integration/unit checks and an actual terminal smoke of focused diff LSP actions, changed-line routing, external new tabs, and immutable/editable side behavior.
|
||||
|
||||
Changed-file explorer checks cover reuse of the compact directory tree, removed/historical paths, file-to-directory transitions, remapped tree/selection bindings, filter/open/focus transitions, right-dock geometry, and wheel routing without edits to the underlying document.
|
||||
Visibility checks preserve browsing and pane state across Ctrl+e, exclude hidden explorers from focus/wheel routing, and verify full-width review. Status checks preserve catalog associations through sorting, compaction, duplicate inputs, and file/directory collisions, and cover colored A/M/D/R markers, selected/unfocused rows, Tree/List filtering, and sanitized rename paths.
|
||||
Light-terminal explorer selection checks render focused/unfocused rows through theme changes, require readable filename/status/directory contrast on Pumpkin Light, and retain dark/unknown-terminal fallbacks. A live PTY check answers native OSC color queries, opens the explorer with Space e, and observes the pale truecolor selection without changing source bytes.
|
||||
Diff styling checks cover independent snapshot language/shebang/injection detection, accepted/stale snapshot identity, real-parser cache freshness/reuse/release, syntax foreground over changed backgrounds, real empty rows versus missing counterparts, scrolling-stable diagonal hatching, and tab/wide/combining/control-character clipping. TestBackend omits wide-glyph continuation cells; terminal smoke verifies their actual styling.
|
||||
|
||||
## Performance and process limits
|
||||
|
||||
- Undo uses full-buffer snapshots and movement scans the current line. This favors straightforward correctness over large-file performance.
|
||||
- Retained undo/redo history stores only changed rows. Insert/replay/completion transactions still use temporary full-buffer snapshots, and undo/redo reconstructs the buffer. Ordinary single-line edits with one pane and no semantic overlay modify the line in place; multiline, multi-edit, shared-pane, and semantic-overlay batches retain the general whole-buffer path. Dirty-state comparisons are cached until text or the saved baseline changes. Movement and wrapping still scan the current line.
|
||||
- Syntax falls back to plain text above 1 MiB of source or a 64 KiB line, before source copies, tree construction, or per-row syntax allocations. The detected language and fallback reason remain visible; reducing the buffer below both budgets restores highlighting. These are optional syntax limits, not file-opening or editing limits.
|
||||
- Saves use buffered writes before flushing, syncing, and atomically replacing the destination. External-change checks remain independent of dirty-state caching. Large-file verification must include exact saved bytes and edit/undo/redo round-trips, not startup alone.
|
||||
- Blame and gutter snapshots are size-checked before joining buffer lines; files above their existing 16 MiB limits retain editing but have no annotations. Eligibility is cached with the source revision and recovers after shrinking.
|
||||
- Rapid-wheel verification must replay bursts against the running editor and measure arrival at the final viewport after input stops, not just individual frame duration. Cheap frames can still accumulate a visible backlog if each queued report requires its own redraw.
|
||||
- Keyboard viewport scrolling coalesces up to 64 consecutive inputs for the same resolved scroll action into one redraw. Reversals, changes between row/configured-step scrolling, and cursor motions end the batch so boundary clamping and caret reveal happen before the next action. Burst checks must include direction changes at the start/end of the buffer, not just throughput.
|
||||
- PTY throughput alone cannot prove terminal presentation stays smooth: capture the editor and terminal while the user reproduces a pause. Synchronized-output commands must not reach the terminal during frame computation, even when individual frames and queued-input catch-up appear fast.
|
||||
- Annotation coordinate validation fast-paths ASCII grapheme lengths using byte lengths with CRLF pair accounting, retaining Unicode segmentation for non-ASCII text. Validation remains atomic and still checks every token; large Unicode buffers or diagnostic batches can require foreground work.
|
||||
- Legacy synchronous plugin invocation may pause input for up to 500 ms before a host timeout. Async plugins opt into background replies; pending requests and transport queues are bounded. Config/plugin startup has a 2-second deadline per host. Buffer context/document snapshots must fit within a 4 MiB JSON frame; a too-large frame disables that plugin, not editing.
|
||||
- Repository diff requires Unix subprocess-group cancellation and Git-backed jj (or Git alone). Selected comparison sides support 64 MiB and 4,000,000 source lines each; frozen Working snapshots support 512 MiB total. Subprocess streams remain bounded to 64 MiB and commands to 60 seconds. Working text is frozen into private Git blobs; catalogs stay lazy and selected blobs load separately without concatenated batch copies. Limits and transport errors are explicit; temporary stores are removed on close. Picker/gutter annotation budgets remain separate.
|
||||
- Large line comparisons skip equal prefixes/suffixes before allocating diff tokens; added/removed files bypass the diff algorithm. Myers work has a 100 ms deadline, after which unresolved regions can be conservatively shown as replacements without dropping text. Inline highlighting is viewport-lazy above 20,000 combined source rows; large/pathological lines use whole-line change shading. Source/display navigation uses indexed contiguous ranges rather than scanning all preceding rows.
|
||||
- Normal-picker status uses the gutter worker's five-second command and 16 MiB stream limits. Catalogs are bounded to 100,000 paths; dirty-buffer batches to 1,024 files/64 MiB; individual overlays, conflict files, and rename candidates to 16 MiB; conflict/rename data to 64 MiB. Temporary baseline stores are retained for warm metadata polling and removed when the worker stops.
|
||||
|
||||
See [syntax caches](architecture.md#syntax-caches) for the current full-tree highlighting ceiling.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Diff hatching: two-column diagonal feasibility
|
||||
|
||||
## Finding
|
||||
|
||||
**Yes: Unicode has the exact two line segments needed.** Repeat the following pair, in this order, with each character occupying one terminal column:
|
||||
|
||||
| Position | Character | Code point | Official Unicode name |
|
||||
| --- | --- | --- | --- |
|
||||
| Left cell | | U+1FBD0 | BOX DRAWINGS LIGHT DIAGONAL MIDDLE RIGHT TO LOWER LEFT |
|
||||
| Right cell | | U+1FBD1 | BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO MIDDLE LEFT |
|
||||
|
||||
These are listed under **Character cell diagonals** on page 6 of the [official Unicode 17.0 Symbols for Legacy Computing chart](https://www.unicode.org/Public/17.0.0/charts/PDF/U1FB00.pdf); the exact names are also in [UnicodeData.txt](https://www.unicode.org/Public/17.0.0/ucd/UnicodeData.txt). They were introduced in **Unicode 16.0** (`1FBCB..1FBEF` in [DerivedAge.txt](https://www.unicode.org/Public/17.0.0/ucd/DerivedAge.txt)). The names specify endpoints, not a drawing direction: together they join the pair's bottom-left corner to the shared edge's midpoint, then to the pair's top-right corner.
|
||||
|
||||
Sample (glyphs may be missing or differently rendered in the Markdown viewer):
|
||||
|
||||
```text
|
||||
|
||||
|
||||
```
|
||||
|
||||
Equivalent escaped sequence: `\u{1FBD0}\u{1FBD1}`. This is two separate characters/cells, not one double-width character.
|
||||
|
||||
## Geometry
|
||||
|
||||
For physical cell width `W` and height `H`, the ideal joined stroke has horizontal run `2W` and vertical rise `H`, so its angle above horizontal is:
|
||||
|
||||
```text
|
||||
θ = atan(H / (2W))
|
||||
```
|
||||
|
||||
This is **45° iff `H = 2W`**. The current full-cell `╱` has ideal angle `atan(H / W)`; at `H = 2W`, that is approximately 63.4°. Thus the pair is shallower, but the actual angle depends on the terminal's cell dimensions, including line spacing. These are geometric deductions from the chart's endpoints, not measured rendering results.
|
||||
|
||||
Do not substitute U+1FBA0–U+1FBAE: their centre/cell-edge endpoints describe different segments (see page 5 of the same chart). In particular, a side midpoint to top/bottom centre has run `W/2` and rise `H/2`, preserving the full-cell diagonal's slope rather than halving it.
|
||||
|
||||
## Line segments, not filled mosaics
|
||||
|
||||
U+1FBD0/U+1FBD1 are **light box-drawing strokes**. The chart separately labels U+1FB3C–U+1FB6F as **Smooth mosaic terminal graphic characters**: their `BLOCK DIAGONAL` names describe filled regions bounded by diagonals, not thin lines. For example, U+1FB48 is LOWER RIGHT BLOCK DIAGONAL LOWER LEFT TO LOWER MIDDLE RIGHT and U+1FB42 is LOWER RIGHT BLOCK DIAGONAL UPPER MIDDLE LEFT TO UPPER RIGHT ([chart, pages 3–4](https://www.unicode.org/Public/17.0.0/charts/PDF/U1FB00.pdf), [UnicodeData.txt](https://www.unicode.org/Public/17.0.0/ucd/UnicodeData.txt)). Those are not equivalent replacements for light hatching.
|
||||
|
||||
## Support limits and current code
|
||||
|
||||
- Unicode 16.0 repertoire support is a prerequisite; the existence of these characters does not establish coverage in the selected terminal/font. Missing glyphs or fallback glyphs remain possible, and fallback geometry must be checked in the intended renderer. Unicode explicitly says its chart glyph shapes are **not prescriptive** and actual fonts may vary ([chart, page 1](https://www.unicode.org/Public/17.0.0/charts/PDF/U1FB00.pdf)). Pixel-perfect joins or 45° rendering cannot be promised.
|
||||
- The pair has East Asian Width **Neutral (`N`)**, from `1FB94..1FBEF` in [EastAsianWidth.txt](https://www.unicode.org/Public/17.0.0/ucd/EastAsianWidth.txt). This is not a terminal-width guarantee: [UAX #11, §2 and §4](https://www.unicode.org/reports/tr11/) explicitly requires terminal-specific tailoring and distinguishes font/layout width from the property. Both the application and terminal must agree on one column per glyph.
|
||||
- Current rendering writes one `╱` per column with `DarkGray` foreground and reset background in [src/tui.rs:3308–3316](../src/tui.rs#L3308-L3316); the documented behavior is [docs/editing.md:426](editing.md#L426). This note proposes no implementation change. Any later cutover would need a defined pair phase and odd-width clipping behavior, plus terminal/font evidence.
|
||||
|
||||
## Terminal support
|
||||
|
||||
- **Ghostty 1.3.1:** The [released drawing source](https://github.com/ghostty-org/ghostty/blob/v1.3.1/src/font/sprite/draw/symbols_for_legacy_computing.zig#L1007-L1031) explicitly implements both segments with the required endpoints. Ghostty's [codepoint resolver](https://github.com/ghostty-org/ghostty/blob/main/src/font/CodepointResolver.zig#L120-L145) normally selects procedural sprite rendering before ordinary font lookup, so this does not require font coverage; explicit codepoint font overrides take precedence.
|
||||
- **Kitty:** [Current font dispatch](https://github.com/kovidgoyal/kitty/blob/master/kitty/fonts.c#L838-L886) routes this range to native box drawing, and [drawing source](https://github.com/kovidgoyal/kitty/blob/master/kitty/decorations.c#L2759-L2774) explicitly implements the two segments. This establishes support in inspected upstream source, not a minimum released version.
|
||||
- The local environment reported Herdr 0.9.3; installed binaries reported Ghostty 1.3.1 and Kitty 0.45.0. Herdr [runs inside an outer terminal](https://github.com/herdrdev/herdr), so its presence and these installations do not prove which renderer displays this session. Visual verification through the actual terminal/multiplexer remains necessary.
|
||||
|
||||
**Recommendation:** Use the two-character text tile if it looks correct in the target terminal. No image protocol or new dependency is needed. Older/other terminals may lack glyph coverage; exact 45° remains conditional on cell geometry.
|
||||
|
||||
## Runtime evidence
|
||||
|
||||
An executed disposable `rustc` smoke program used the repository's actual compiled `ratatui` and `unicode-width` dependencies, a fixed viewport, `Terminal<CrosstermBackend<Vec<u8>>>`, and the same per-cell `set_symbol`/style logic as the current renderer. Both U+1FBD0 and U+1FBD1 returned width `Some(1)`. At three rows high, widths 1, 2, 3, and 12 emitted exactly 3, 6, 9, and 36 glyphs respectively: no dropped or double-width cells. This establishes application-side width/emission behavior, **not** actual terminal glyph coverage, pixel joins, or the visible angle; those were not visually verified. The disposable program and binary were removed.
|
||||
|
||||
Investigation only: no production code changed and no TODO marked complete.
|
||||
+527
-39
@@ -4,33 +4,84 @@
|
||||
|
||||
Default controls and editing behavior. For custom bindings, see [configuration](configuration.md); for language-server commands, see [native LSP](configuration.md#native-lsp).
|
||||
|
||||
Ordinary documents show repository changes beside their hybrid line numbers by default: green `▌` for additions, red for removals, and yellow for modifications. [Configure `git_gutter`](configuration.md) to use `+` / `-` / `~`, colored numbers, or no change indicators. Bar/symbol gutters keep the order **number, blank, marker, blank, text**; number-only modes use no extra column. Horizontal scrolling never moves indicators, and wrapped continuation rows do not repeat them.
|
||||
|
||||
The baseline is Git `HEAD` or Git-backed jj's parent `@-`, so indicators include unsaved edits and remain after saving until the repository baseline changes. A deletion marks the next surviving source row; at EOF it marks the last editor row, including the final empty row after a trailing newline. An empty file anchors removals on row 0. Replacements mark paired rows modified and extra current rows added. Historical snapshots do not show live changes. Eligible named files not yet on disk show nonempty unsaved text as added; tracked files missing on disk still compare their buffer text against the baseline. Non-repository/ignored/binary/symlink files, files over 16 MiB, and jj changes with multiple parents have no indicators.
|
||||
|
||||
Indicators refresh asynchronously. Typing and undo/redo retain the last completed indicators until the updated comparison arrives, avoiding flashes; indicator values and row positions can briefly lag edits.
|
||||
|
||||
## Default editing keys
|
||||
|
||||
| Mode | Keys |
|
||||
| --- | --- |
|
||||
| All modes | Ctrl+p opens the command palette; type to filter, Ctrl+j/k or arrows select, Enter accepts, Esc/Ctrl+p cancels |
|
||||
| Normal, Visual | Space Space opens the palette through the default leader |
|
||||
| Normal | Space w saves; Space b n/p/l/d switches next/previous, lists, or closes buffers |
|
||||
| Normal | Space w saves; Space b n/p/l/d switches next/previous, opens the buffer picker, or closes buffers |
|
||||
| Normal, Visual | Space o opens the floating tree in INSERT/filter mode; Space e opens/focuses the docked compact tree |
|
||||
| Normal | `i` insert before each caret; `a` insert after each caret; `o`/`O` open lines below/above |
|
||||
| Normal, Visual | `I` (Shift+i) / `A` (Shift+a) insert at first nonblank / line end; Visual splits each touched row into a caret first |
|
||||
| Normal | `h`/`j`/`k`/`l` or arrows move every caret; `0`/`$` or Home/End |
|
||||
| Normal | `_` splits above/below; `\|` splits left/right; the new pane inherits the current buffer and view |
|
||||
| Normal | Option/Alt+h/j/k/l focuses the neighboring pane left/down/up/right |
|
||||
| Normal | Ctrl+Option/Alt+h/l switches to the previous/next tab, wrapping at either end |
|
||||
| Normal | `w`/`b`/`e` move every caret to next word start, previous/current word start, word end; `W`/`B`/`E` for whitespace-delimited WORDs |
|
||||
| Normal, Visual | `f<char>` seeks forward on the current line; `F<char>` seeks backward; `2fx` finds the second `x` after each caret |
|
||||
| Normal | `gf` follows a Markdown file link or heading fragment at the primary caret |
|
||||
| Normal, Visual | `gt` goes to the first line; `gb` goes to the last line, at first nonblank; Visual extends every selection |
|
||||
| Normal, Visual | `<line>g` jumps immediately to that one-based source line at first nonblank (`42g`); clamps at EOF and extends Visual selections |
|
||||
| Normal | Ctrl+o goes to an older jump location; Ctrl+i goes forward (Tab too outside comparisons); counts select multiple locations |
|
||||
| Normal, Visual | Decimal prefixes repeat cursor/word/search motions: `5j`, `3k`, `2w`, `4e`, `2n`; Esc cancels a pending count |
|
||||
| Normal, Visual | Ctrl+u/Ctrl+d scroll up/down without moving carets or selections; half a viewport by default, configurable with `config.scroll_step_lines`; counts multiply the distance |
|
||||
| Normal | `J` (Shift+j) joins each targeted line with the next line |
|
||||
| Normal | `x`/Delete delete; `u` undo; `U` (Shift+u) redo; `:` enter command mode |
|
||||
| Normal | `x`/Delete cut the hovered grapheme at every caret; `u` undo; `U` (Shift+u) redo |
|
||||
| Normal, Visual | `:` enters command mode; Visual selections remain available to selection-aware commands |
|
||||
| Normal | `yy` copies whole lines without moving; `dd` deletes them; `cc` changes them and enters Insert; counts work (`3yy`, `2dd`, `2cc`) |
|
||||
| Normal | `D` deletes through line end; `C` changes that suffix and enters Insert; `Y` copies that suffix characterwise |
|
||||
| Normal, Visual | `r<char>` replaces the current grapheme in Normal or every selected grapheme in Visual |
|
||||
| Normal | `s` deletes the current grapheme and enters Insert |
|
||||
| Normal | `d<count>w` / `d<count>b` delete forward/backward word spans, e.g. `d2w` / `d2b` |
|
||||
| Normal | `c<count>w` / `c<count>b` cut the same line-local spans as `d` and enter Insert, e.g. `c2w` / `c2b` |
|
||||
| Normal, Visual | `.` repeats the last successful native edit against the current targets; one undo group |
|
||||
| Normal | `/` opens search; `n` finds the next match; `N` (Shift+n) finds the previous match |
|
||||
| Normal | `v` starts Visual selections; `p`/`P` paste the configured clipboard after/before each caret (system by default); Esc keeps only the primary caret |
|
||||
| Normal | `/` opens search; `*` searches the word under the primary caret; `n`/`N` find the next/previous match |
|
||||
| Normal | `v` starts characterwise Visual; `V` starts linewise Visual; `p`/`P` paste the configured clipboard after/before each caret or row for linewise fragments (system by default); Esc keeps only the primary caret |
|
||||
| Normal, Visual | Ctrl+k clones above; Ctrl+e clones below |
|
||||
| Visual | Cursor/word motions and `n`/`N` extend every selection; `y` copies; `d`/`x`/Delete cuts; `c` changes selections; `v`/Esc cancels highlighting |
|
||||
| Visual | Cursor/word motions and `n`/`N` extend every selection; `y` copies; `d`/`x`/Delete cuts; `c` changes; `v`/`V` switches shape, the same selector or Esc cancels |
|
||||
| Visual | `p` / `P` replaces each selection with the configured clipboard, without overwriting it |
|
||||
| Visual | Ctrl+l splits touched rows into Normal carets at first nonblank; Ctrl+n adds the next occurrence; Ctrl+s skips the primary occurrence; Ctrl+a selects all occurrences |
|
||||
| Insert | Type, Enter, Tab, Backspace/Delete, arrows, Home/End at every caret; Esc returns to Normal, retaining carets |
|
||||
| Command | Enter executes; Backspace edits; Esc cancels |
|
||||
| Search | Type a literal query; Enter finds the next match; Backspace edits; Esc cancels |
|
||||
| Insert | Type, Enter, Tab, Backspace/Delete, arrows, Home/End at every caret outside snippets; Esc returns to Normal, retaining carets |
|
||||
| Insert | Ctrl+n requests completion at the primary caret or cycles next; Ctrl+j/k cycles next/previous while completion is open |
|
||||
| Insert, active snippet | Type to replace the highlighted argument and its mirrors; Tab / Shift+Tab moves next/previous |
|
||||
| Command | Tab / Shift+Tab completes/cycles command names forward/backward; Enter executes; ↑/↓ or Ctrl+k/j browse history; Backspace edits; Esc cancels |
|
||||
| Search | Type a literal query; Enter accepts the current occurrence or finds the next match; ↑/↓ or Ctrl+k/j browse history; Backspace edits; Esc cancels |
|
||||
| Insert, Command, Search | Ctrl+u deletes backward to the logical line start |
|
||||
| Insert, Command, Search (macOS) | Option+Backspace deletes backward by word; Command+Backspace deletes backward to the logical line start |
|
||||
|
||||
Outside active snippets, Insert-mode Tab inserts a literal tab by default. Set [`config.tab_spaces` and `config.language_tab_spaces`](configuration.md#preferences) to insert a fixed number of spaces, with per-language overrides. The setting applies to every caret and editable diff text; existing tabs and pasted text are not converted.
|
||||
|
||||
`J` removes the next line's leading spaces/tabs and preserves existing trailing whitespace. It normally adds one space, two after `.`, `?`, or `!` (Vim's default), and none before `)` or when either side is empty. The cursor lands at the join point; the join is one undo action. On the last line, `J` does nothing.
|
||||
|
||||
`gt`/`gb` move every caret to the first nonblank grapheme on the first/last row, including the empty final row after a trailing newline. Duplicate carets and overlapping Visual selections normalize as usual. Both Visual shapes retain their anchors and extend to the destination. These motions do not edit text or add undo history; count prefixes are consumed rather than interpreted as line numbers. `g` waits for its second key, and Escape cancels only the pending prefix. In Insert and command/search prompts, `gt`/`gb` remain literal text.
|
||||
|
||||
On macOS, these modified Backspace defaults also edit prompt and filter queries, including file lists, the command palette, and revision selectors. Option+Backspace uses Unicode word boundaries, first skipping trailing whitespace; Command+Backspace removes only the prefix before the caret on the current logical line, preserving its suffix and newline. Buffer deletion runs at every caret, merges overlapping ranges, shares the Insert undo group, and dot repeats the boundary operation rather than the old deleted length. Within an active snippet, both operations stay confined to the current argument and update its mirrors. These modified Backspace defaults remain macOS-only; Ctrl+u invokes the same line-deletion action on every platform.
|
||||
|
||||
The terminal may deliver a native modifier or a conventional control sequence: Option may use legacy ESC+DEL, and Kitty CSI-u represents Command as **Super**, not Meta. Ghostty defaults to encoding Command+Backspace as Ctrl+u (`\x15`), which invokes the same backward line deletion without a Ghostty configuration override. Ctrl+u remains a separate, configurable binding; vamp cannot distinguish it from Command+Backspace when both send the same bytes. Vamp does not negotiate an enhanced keyboard protocol or support generic Command-modified character keys.
|
||||
|
||||
Viewport scrolling uses screen rows, including wrapped continuations and diff display rows. It affects the focused text pane (both sides share the diff's vertical offset), and the caret may leave the screen. The next cursor motion or edit resumes caret following. Ctrl+e retains its clone-below binding; single-row scrolling is available through `config.core.scroll_up` / `config.core.scroll_down`. Insert, Command, Search, and picker Ctrl+u behavior is unchanged.
|
||||
|
||||
## Manual LSP completion
|
||||
|
||||
With an enabled server that provides completion, Ctrl+n in Insert requests candidates at the **primary caret only**. The first candidate is inserted immediately and a small list appears near the caret; Ctrl+n or Ctrl+j cycles forward, Ctrl+k backward, with wraparound. There is no acceptance step. The **Original text** row restores the document and carets from before the result was shown, including any additional edits. Completion never broadcasts a candidate to secondary carets: they are preserved and translated through each chosen edit.
|
||||
|
||||
Every candidate is applied from that same immutable original document, not on top of the previous candidate. A candidate's primary replacement and additional text edits are one atomic change. Other keys close the list without accepting it: plain-text completion retains ordinary typing, newline, and configured Tab insertion; snippet completion keeps its argument navigation described below. Escape returns to Normal retaining the displayed text. There is no automatic popup. Empty, unsupported, or invalid results leave the document unchanged and report a message.
|
||||
|
||||
Cycling creates no separate undo entries. Only the final chosen edits join the existing Insert undo group; choosing Original text adds no completion edit. Undo restores that group, and dot repeats the final resolved completion edits rather than requests or intermediate candidates. The list stays inside the document text workspace, does not cover the gutter or explorer, and never takes the primary cursor. Wheel input over it is consumed without choosing a candidate.
|
||||
|
||||
Snippet candidates expand the full template immediately, including parentheses and argument defaults. The first numbered argument is highlighted; typing replaces it, then continues within that argument. Repeated occurrences of the same argument update together, without broadcasting to secondary carets. Backspace/Delete stay within the active argument; Enter can insert a newline there. **Tab** moves forward and **Shift+Tab** backward in ascending tabstop order. Replacing an enclosing argument removes its nested arguments, not adjacent independent ones. Reaching the final `$0` position ends navigation, so subsequent Tab uses the configured spaces-or-tab insertion. Escape, ordinary cursor motion, paste, commands, and focus/buffer changes also end navigation without removing the expanded text.
|
||||
|
||||
For example, `call(${1:argument}, ${2:count})$0` previews `call(argument, count)`. Type `value`, Tab, `3`, Tab to produce `call(value, 3)` with the caret after the closing parenthesis. Argument edits remain in the same Insert undo group, and dot repeats the resolved text and final caret rather than re-expanding placeholders.
|
||||
|
||||
Numbered tabstops, nested defaults, mirrors, escapes, variable defaults, and context variables are supported. Choices insert their first option, which remains editable. Regex transforms, unknown variables without defaults, repeated/nonempty final `$0`, and final stops nested inside arguments are omitted rather than inserted partly or literally. See [protocol limits](configuration.md#native-lsp).
|
||||
|
||||
## Word motions
|
||||
|
||||
Word motions separate runs of Unicode letters/numbers/underscore from runs of punctuation or emoji. Classification uses each grapheme's first character; combining sequences and ZWJ emoji stay intact. WORD motions treat any non-whitespace run as one WORD.
|
||||
@@ -39,33 +90,65 @@ Word motions separate runs of Unicode letters/numbers/underscore from runs of pu
|
||||
|
||||
These keys type literal text in Insert mode. The corresponding actions can also be bound in Insert mode to move all insertion carets without splitting their undo group. Motions never edit text, add history, or clear an active search highlight.
|
||||
|
||||
## Character seeks
|
||||
|
||||
`f<char>` / `F<char>` moves every caret to the next / previous matching grapheme on its current line, excluding the current position. A count seeks that occurrence independently for each caret: `2fx` finds the second following `x`, and `2Fx` the second preceding `x`. With too few matches, that caret stays unchanged. Seeks never wrap or cross lines, and Unicode targets land on whole graphemes, including combining sequences and ZWJ emoji.
|
||||
|
||||
Normal and both Visual shapes support these motions, including read-only diff panes. Visual keeps its anchors; native edit replay retains the seek's direction, target, and count rather than its original distance. The following character is literal even if it is a digit, leader key, remapped key, or diff expansion bracket. Escape cancels only the pending seek without moving or collapsing selections. `f`/`F` remain literal text in Insert and command/search prompts; `gf` retains its Markdown-link behavior.
|
||||
|
||||
Bind `config.core.seek_forward` / `config.core.seek_backward` to another Normal or Visual key or leader sequence to start the same target-character prompt.
|
||||
|
||||
## Motion counts
|
||||
|
||||
Counts apply to `h`/`j`/`k`/`l`, arrows, `w`/`b`/`e`, `W`/`B`/`E`, and `n`/`N`, including remapped keys for those actions. Every caret moves independently before duplicate/overlapping targets normalize. Vertical counts preserve the clamping behavior of repeated steps through short rows; horizontal and word motions stop at buffer boundaries. Search counts wrap through the available matches.
|
||||
Counts apply to `h`/`j`/`k`/`l`, arrows, `w`/`b`/`e`, `W`/`B`/`E`, `f<char>`/`F<char>`, and `n`/`N`, including remapped keys for those actions. Every caret moves independently before duplicate/overlapping targets normalize. Vertical counts preserve the clamping behavior of repeated steps through short rows; horizontal and word motions stop at buffer boundaries. Character seeks require the requested occurrence on the current line or leave that caret unchanged. Search counts wrap through the available matches.
|
||||
|
||||
Unbound ASCII digits `1`–`9` start a count in Normal/Visual; subsequent digits extend it. `0` retains line-start behavior without a count and extends an existing count when bound to line-start. Explicit digit bindings, including disabled keys, take precedence. Count arithmetic saturates rather than overflowing; large counts stop at motion boundaries or wrap for search, without executing an unbounded repeat loop.
|
||||
|
||||
The status bar displays a pending count. Esc cancels it without moving, collapsing carets, or leaving Visual; the next Esc performs its ordinary action. Leader prefixes retain the count until their leaf action resolves. Other commands consume the prefix and execute once, including line-start/end, edits, and plugins. Unknown/disabled keys and bracketed paste clear it; opening the palette clears it, so palette query digits remain literal. Digits also remain literal in Insert and command/search prompts. Counts add no history, and Vim operator grammar such as `3dw` is not supported.
|
||||
The status bar displays a pending count. Esc cancels it without moving, collapsing carets, or leaving Visual; the next Esc performs its ordinary action. Leader and editing prefixes retain the count until their action resolves. Line/word deletion, character replacement, and substitution use counts; suffix actions and other non-motion commands consume it and execute once. Unknown/disabled keys and bracketed paste clear it; opening the palette clears it, so palette query digits remain literal. Digits also remain literal in Insert and command/search prompts. Counts add no history; only the dedicated operators described below are supported.
|
||||
|
||||
## Normal editing actions
|
||||
|
||||
`dd` cuts the current line and its newline into the configured linewise clipboard, staying in Normal. `cc` cuts the same whole-row contents, leaves one empty replacement row, and enters Insert at column 0; indentation is not retained. Leading counts select rows downward from each caret, clamped at EOF: `3dd` cuts up to three rows and `2cc` changes up to two rows. Overlapping ranges merge before editing or clipboard publication; adjacent ranges remain separate targets. Deleting at EOF removes the preceding separator when needed, and the buffer always retains at least one row.
|
||||
|
||||
`yy` copies the entire current line into the configured linewise clipboard without moving any caret, changing text, or replacing undo/redo and dot-repeat history. Counts before and after `y` multiply (`2yy`, `y2y`, `2y3y`), selecting rows downward and clamping at EOF. Empty and unterminated final rows retain linewise shape. `p` pastes these complete rows below the current line; `P` pastes above it. The caret lands on the first nonblank of the first inserted row. Characterwise yanks still paste after/before the current grapheme. Bind `config.core.copy_line` for another Normal-mode route; historical read-only buffers permit yanking but reject paste.
|
||||
|
||||
The first `d`, `c`, or `y` waits for its second key and appears in the status bar. `d` accepts `d`, `w`, or `b`; `c` accepts `c`, `w`, or `b`; `y` accepts `y`. Counts before and after the operator multiply: `2d3w` deletes six forward word spans, `2c3b` cuts six backward spans and enters Insert, and `d2d` deletes two rows. Escape cancels only the pending prefix/count, preserving carets; an unmatched key cancels the prefix and then performs its ordinary action. Explicit bindings, disabled first keys, and a leader using that first key take precedence.
|
||||
|
||||
System clipboard publication must succeed before any deletion. Failure preserves text, carets, mode, undo/redo, and repeat intent. `dd` is one undo action; `cc` and subsequent replacement typing form one Insert undo group. Dot repeats the original requested row count at the current carets—even if the original action was clamped at EOF—and replays `cc` replacement text. Rebind the Normal-only `config.core.delete_line` / `config.core.change_line` actions to a single key or leader sequence without relying on the built-in doubled keys.
|
||||
|
||||
`D` cuts from each caret through its logical line end; `C` cuts the same suffix and enters Insert. `Y` copies that suffix characterwise without moving the carets. These actions leave line separators intact and ignore counts. `C` and subsequent typed replacement form one undo group.
|
||||
|
||||
`r<char>` replaces one grapheme per caret and stays in Normal; `s` cuts one grapheme and enters Insert. Counts select that many graphemes, clamped to the current line. Combining sequences and ZWJ emoji are never split. Replacement accepts a printable character or Tab literally; Escape or other non-character input cancels it without editing. Empty-line replacement is a no-op; substitution can still enter Insert. `s` and replacement typing form one undo group.
|
||||
|
||||
`dw` / `db` cut characterwise spans from each caret to the forward/backward word-start boundary, using the same Unicode word boundaries as `w` / `b`, but confined to that caret's current logical line. Counts repeat the boundary motion, stopping at the line end/start without deleting its newline or touching neighboring lines; ordinary `w` / `b` navigation still crosses lines. Backward spans exclude the original caret character. Empty spans do not edit text. These are dedicated actions, not arbitrary operator–motion grammar. Suffix, substitution, and word cuts share the configured clipboard's failure-before-edit protection; all native edits support undo and dot repeat.
|
||||
|
||||
`cw` / `cb` cut exactly the same line-local spans as `dw` / `db`, including intervening whitespace, then enter Insert at each cut's start. Counts before and after `c` multiply (`2cw`, `c2w`, `2c3b`); excess counts stop at the current line's boundary. Empty spans still enter Insert, including on empty lines and for `cb` at column zero. The cut and subsequent replacement typing form one undo group; dot repeat recomputes the requested spans at the current carets and replays the replacement text. Rebind the Normal-only `config.core.change_word_forward` / `config.core.change_word_backward` actions for another route.
|
||||
|
||||
## Selections and multi-caret editing
|
||||
|
||||
Editing uses an ordered selection set with one primary target. Cursor and word motions apply to every target; Visual motions keep each target's anchor and move its active endpoint. Whole combining sequences and ZWJ emoji remain intact. Visual selection is characterwise and inclusive of the endpoints; its read-only ranges are end-exclusive. `$`/End can select the newline after a non-final row; empty-line newlines are selectable too. Selected newlines appear as a blue blank cell after the line. Blue highlighting overrides yellow search highlighting; secondary carets are magenta, including on empty lines and at line ends. Only the primary owns the hardware cursor and viewport. The status line counts all targets, including offscreen targets.
|
||||
Editing uses an ordered selection set with one primary target. Cursor and word motions apply to every target; Visual motions keep each target's anchor and move its active endpoint. Whole combining sequences and ZWJ emoji remain intact. `v` selects characterwise, inclusive of endpoints; `V` selects every complete row touched by the endpoints, including blank and empty final rows. Switching between `v` and `V` retains endpoints; pressing the current shape's selector again cancels. Read-only ranges are end-exclusive. Characterwise `$`/End can select the newline after a non-final row; selected newlines appear as a blue blank cell after the line. Linewise highlighting covers the copied text, including trailing whitespace, plus one blank cell for each copied newline; unused viewport space and the gutter remain unhighlighted. The status reads VISUAL LINE. Blue highlighting overrides yellow search highlighting; secondary carets follow the mode palette (magenta in Visual), including on empty lines and at line ends. The primary software cursor overlays these text colors and alone drives the viewport; its shape and mode colors are [configurable](configuration.md#preferences). The status line counts all targets, including offscreen targets.
|
||||
|
||||
Ctrl+k/Ctrl+e clone each target to the adjacent row, preserving preferred terminal-cell columns (tabs use four-cell stops); Visual cloning preserves both endpoints. Duplicate carets and truly overlapping selections merge; adjacent ranges remain distinct. Visual Ctrl+l creates one Normal caret at the first nonblank of each touched row. Visual `I`/`A` similarly create one Insert caret per touched row at first nonblank/end. Occurrence actions use the primary selection as a literal, potentially multiline, grapheme-aligned query: Ctrl+n adds the next non-overlapping occurrence and wraps; Ctrl+s moves only the primary to that occurrence; Ctrl+a selects all occurrences.
|
||||
|
||||
Copy and cut return to Normal at each selection start; Visual cancellation keeps each active endpoint and removes highlighting. Normal Esc collapses to the primary. `p`/`P` paste after/before each current grapheme, including multiline text. Each caret lands on its last inserted grapheme, or the new row's start when its fragment ends in a newline. Every multi-target edit is planned against the original buffer and committed as one undo action, not one per target. Copy, movement, and cancellation do not add history or clear redo. Undo/redo restore text, the full caret set, and primary identity in Normal mode, not Visual highlighting or the clipboard.
|
||||
Copy and cut return to Normal at each selection start; Visual cancellation keeps each active endpoint and removes highlighting. Normal Esc collapses to the primary. Characterwise `p`/`P` paste after/before each current grapheme, including multiline text. Linewise clipboard fragments paste complete rows below/above each target row, including at end of file. Internal fragments retain their shape; system clipboard shape is retained only while its bytes match the editor's last publication, and unrelated external clipboard text is characterwise. Characterwise paste lands on its last inserted grapheme, or the new row's start when its fragment ends in a newline; linewise paste lands at the first nonblank of the first inserted row. Every multi-target edit is planned against the original buffer and committed as one undo action, not one per target. Copy, movement, and cancellation do not add history or clear redo. Undo/redo restore text, the full caret set, and primary identity in Normal mode, not Visual highlighting or the clipboard.
|
||||
|
||||
Visual `c` removes all selected text into the configured clipboard and enters Insert at each selection start. In the default System policy, clipboard publication must succeed before any deletion; failures leave text and selections intact. Deletion and replacement typing form one undo action when Insert mode is exited, including through explicit command execution. Esc without typing commits the deletion alone. An identical replacement creates no history entry and preserves redo. Changing only empty final-row selections enters Insert without overwriting either clipboard.
|
||||
In Visual and Visual Line, both `p` and `P` replace each complete selected range rather than inserting beside its caret. Clipboard fragments are inserted literally, including their newlines: a characterwise fragment replacing a whole-line selection does not gain a newline, and a linewise fragment replacing characters keeps its newline. The edit returns to Normal, is one undo group across all selections, and supports dot repeat with the captured clipboard and selection intent. Neither clipboard is overwritten by the replaced text. Failed clipboard reads, invalid text, empty clipboard, or mismatched fragment counts leave the selection and document intact.
|
||||
|
||||
Bracketed paste broadcasts the same literal text to all Insert carets in a separate undo group, distinct from typing before/after it. A rejected paste leaves the pending change intact. Normal-mode operator grammar such as `cw` is not supported; `c` types literal text in Insert mode.
|
||||
Visual `c` removes all selected text into the configured clipboard and enters Insert at each selection start. In the default System policy, clipboard publication must succeed before any deletion; failures leave text and selections intact. Deletion and replacement typing form one undo action when Insert mode is exited, including through explicit command execution. Esc without typing commits the deletion alone. An identical replacement creates no history entry and preserves redo. Changing only characterwise empty final-row selections enters Insert without overwriting either clipboard; linewise empty final rows are genuine rows and publish a newline.
|
||||
|
||||
Clipboard policy is session-wide and defaults to the system clipboard. Copy/cut store fragments in document order: one fragment broadcasts to every caret; matching fragment/caret counts pair in document order; any other count refuses paste without changing editing state. Empty clipboard paste does not edit text; copying/cutting only empty final-row selections does not overwrite either register. Open a new search or enter Ex commands after leaving Visual mode. Plugin commands execute once, not once per target: successful text effects collapse to the primary and apply once; rejected or message-only effects preserve the selection set. There is no selection-aware plugin API yet.
|
||||
Visual `r<char>` replaces every selected grapheme with the literal character, preserving newline separators and the clipboard. It returns to Normal at each selection start as one undo action and supports `.` repeat. Esc while waiting for the character cancels the replacement without clearing selections. Identical replacements and newline-only selections do not add history or discard redo.
|
||||
|
||||
Bracketed paste broadcasts the same literal text to all Insert carets in a separate undo group, distinct from typing before/after it. A rejected paste leaves the pending change intact. Normal supports counted `yy`, `dd`, `cc`, `dw`, `db`, `cw`, and `cb`, but not arbitrary operator–motion grammar; blockwise Visual is also unsupported. `c`, `d`, and `y` type literal text in Insert mode.
|
||||
|
||||
Clipboard policy is session-wide and defaults to the system clipboard. Copy/cut store fragments in document order: one fragment broadcasts to every caret; matching fragment/caret counts pair in document order; any other count refuses paste without changing editing state. Empty clipboard paste does not edit text; copying/cutting only characterwise empty final-row selections does not overwrite either register. Linewise copy/cut retain whole-row shape, including a newline fragment for an empty final row. Open a new search after leaving Visual mode; Ex commands can be entered directly with `:` while retaining the selection. Plugin commands execute once, not once per target: successful text effects collapse to the primary and apply once; rejected or message-only effects preserve the selection set. There is no selection-aware plugin API yet.
|
||||
|
||||
## Clipboard policy
|
||||
|
||||
`config.clipboard_mode = "system"` is the default: ordinary Visual `y`/`d`/`x`/`c` and Normal `p`/`P` use the OS clipboard. External clipboard changes are read on each paste. Set `"separate"` to keep ordinary operations on vamp's internal fragment register instead. Both registers remain independent across buffers; changing the policy does not overwrite either.
|
||||
Normal `x`/Delete (`config.core.delete`) copies each hovered grapheme to the configured clipboard before removing it. Combining sequences and emoji stay intact; empty lines are unchanged, and an entirely empty cut preserves the clipboard. Dot-repeat cuts and copies the current graphemes. Insert-mode Delete and its replay do not copy.
|
||||
|
||||
Explicit `config.core.copy_system` (Visual) and `config.core.paste_system_before` / `paste_system_after` (Normal) always use the system clipboard in either policy. They appear in the command palette and can be bound without replacing ordinary internal operations:
|
||||
`config.clipboard_mode = "system"` is the default: ordinary Visual `y`/`d`/`x`/`c` and Normal/Visual `p`/`P` use the OS clipboard. External clipboard changes are read on each paste. Set `"separate"` to keep ordinary operations on vamp's internal fragment register instead. Both registers remain independent across buffers; changing the policy does not overwrite either.
|
||||
|
||||
Explicit `config.core.copy_system` (Visual) and `config.core.paste_system_before` / `paste_system_after` (Normal/Visual) always use the system clipboard in either policy. They appear in the command palette and can be bound without replacing ordinary internal operations:
|
||||
|
||||
```ruby
|
||||
config.clipboard_mode = "separate"
|
||||
@@ -73,19 +156,19 @@ config.bind "ctrl+s", config.core.copy_system, mode: config.modes.visual
|
||||
config.bind "ctrl+g", config.core.paste_system_before
|
||||
```
|
||||
|
||||
For other applications, multi-selection exports join fragments with LF. Vamp retains their original boundaries privately while the OS text exactly matches its export, so its own copies still paste pairwise. Different external text invalidates that metadata and becomes one literal fragment—even when it contains newlines—broadcasting to all targets. Identical external replacement text is inherently indistinguishable from an unchanged export. No empty-system fallback to stale internal text occurs.
|
||||
For other applications, characterwise multi-selection exports join fragments with LF; linewise exports concatenate whole-row fragments without extra separators because each fragment already ends in LF. Vamp retains their original boundaries and shape privately while the OS text exactly matches its export, so its own copies still paste pairwise. Different external text invalidates that metadata and becomes one characterwise literal fragment—even when it contains newlines—broadcasting to all targets. Identical external replacement text is inherently indistinguishable from an unchanged export. No empty-system fallback to stale internal text occurs.
|
||||
|
||||
System paste validates UTF-8, unsupported controls, newlines, and a 4 MiB limit before editing; CRLF/CR normalize to LF. System exports also have a 4 MiB limit. Provider failures report an error without deleting/changing buffer text, caret/selection state, history, or repeat intent. No silent internal fallback occurs in System mode; choose Separate if clipboard access is unavailable. A native provider that fails after publishing may already have changed OS clipboard formats; vamp cannot roll that external side effect back.
|
||||
|
||||
System clipboard access supports macOS through `osascript`, Linux Wayland through `wl-paste`/`wl-copy`, and Linux X11 through `xclip`. Linux tools must be on PATH with the corresponding display environment. Other platforms report unsupported access; choose Separate mode when system clipboard access is unavailable.
|
||||
macOS copies publish UTF-8 plain text through the native pasteboard API, and pastes read text directly through AppKit, avoiding interpreter/process startup for every copy, cut, or paste. Linux Wayland uses `wl-paste`/`wl-copy`, and Linux X11 uses `xclip`. Linux tools must be on PATH with the corresponding display environment. Other platforms report unsupported access; choose Separate mode when system clipboard access is unavailable.
|
||||
|
||||
## Repeat last edit
|
||||
|
||||
`.` repeats the session's last successful native edit in Normal/Visual. Insertion placements (`i`/`I`/`a`/`A`/`o`/`O`), Insert typing and edit-context motions/newline/backspace/delete, Visual change/cut, Normal deletion, clipboard/literal paste, and line joining are recorded as resolved edit operations—not keystrokes, command invocations, or old byte offsets. Remapping keys afterward does not change the recorded operation. Insert `.` and popup query `.` remain literal. A count before dot is consumed and repeats once, consistent with other non-motion commands.
|
||||
`.` repeats the session's last successful native edit in Normal/Visual. Insertion placements (`i`/`I`/`a`/`A`/`o`/`O`), Insert typing and edit-context motions/newline/backspace/delete, Visual change/cut, counted Normal `dd`/`cc`, Normal character deletion, clipboard/literal paste, and line joining are recorded as resolved edit operations—not keystrokes, command invocations, or old byte offsets. Remapping keys afterward does not change the recorded operation. Insert `.` and popup query `.` remain literal. A count before dot is consumed and repeats once; a stored `dd`/`cc` recipe retains its own requested row count.
|
||||
|
||||
In Normal, Visual change/cut targeting replays its resolved motions and counts at each current caret: `vecitem` followed later by `.` changes a fresh whole word, even if its length differs. If targeting was rebuilt by cloning, occurrence gathering, search, or overlap merging, repeat uses relative whole-grapheme spans instead. Equal spans broadcast; unequal spans require matching target counts. In Visual, the current explicit ranges replace the stored targeting. Target-building commands themselves do not recreate old cursors.
|
||||
In Normal, characterwise Visual change/cut targeting replays its resolved motions and counts at each current caret: `vecitem` followed later by `.` changes a fresh whole word, even if its length differs. If characterwise targeting was rebuilt by cloning, occurrence gathering, search, or overlap merging, repeat uses relative whole-grapheme spans instead. Visual linewise targeting uses signed relative row spans, preserving whole-row shape rather than replaying motions. Equal spans broadcast; unequal spans require matching target counts. In Visual, current explicit ranges and selection shape replace stored Visual targeting. Native `dd`/`cc` recipes instead always select their requested rows from each current active caret. Target-building commands themselves do not recreate old cursors.
|
||||
|
||||
Clipboard paste captures the fragments actually pasted, so a later yank or external clipboard change does not change repeat's payload; dot paste never rereads the OS. One fragment broadcasts; equal fragment/target counts pair; mismatches refuse atomically. Other per-target edit data, such as partially effective Insert deletion, obeys the same conservative distribution policy. Dot cut/change follows the current clipboard policy and stages publication until replay validation finishes. A refusal or provider error preserves editor text, caret/primary state, register caches, history, and recipe; already-published OS data cannot be transactionally restored.
|
||||
Clipboard paste captures the fragments and their characterwise/linewise shape actually pasted, so a later yank or external clipboard change does not change repeat's payload; dot paste never rereads the OS. One fragment broadcasts; equal fragment/target counts pair; mismatches refuse atomically. Other per-target edit data, such as partially effective Insert deletion, obeys the same conservative distribution policy. Dot cut/change follows the current clipboard policy and stages publication until replay validation finishes. A refusal or provider error preserves editor text, caret/primary state, register caches, history, and recipe; already-published OS data cannot be transactionally restored.
|
||||
|
||||
Each repeat returns to Normal and creates one undo entry restoring the full caret set and primary. Original typing/paste/typing boundaries remain separate; dot replays the selected committed group as one transaction. Typed text retains scalar insertion boundaries, preserving combining/ZWJ interactions with surrounding graphemes; bracketed paste remains one bulk literal operation. Trailing Insert movement is not repeated.
|
||||
|
||||
@@ -93,47 +176,194 @@ The last recipe is session-wide across buffers, but pending Insert groups and un
|
||||
|
||||
## Search
|
||||
|
||||
Search is case-sensitive and single-line, with no regular expressions or Unicode normalization. Matches start and end on whole grapheme boundaries, including combining marks and emoji. Next/previous navigation skips the current position and wraps through the buffer; a sole match wraps back to itself. The active match is highlighted yellow.
|
||||
Search is case-sensitive and single-line, with no regular expressions or Unicode normalization. Matches start and end on whole grapheme boundaries, including combining marks and emoji. Next/previous navigation skips the current position and wraps through the buffer; a sole match wraps back to itself. All occurrences of the active query are highlighted yellow.
|
||||
|
||||
Submitting an empty search repeats the last query. Esc cancels without moving the cursor or replacing the previous query/match. A missing match reports the query, clears the highlight, and leaves the cursor unchanged; searching without a previous query also leaves the cursor unchanged. Search never edits text or adds undo history. Buffer edits and undo/redo clear the highlight but retain the query, so subsequent navigation searches the current text again.
|
||||
Submitting `/` keeps each caret in place if it is at or inside an occurrence of the query; otherwise, it moves that caret to the next match, wrapping as needed. This also applies to an empty submission repeating the previous query. Use `n`/`N` to explicitly move to the next/previous match.
|
||||
|
||||
Normal `*` highlights the primary caret's word when it selects a new query or changes the matching mode. Carets at or inside a matching occurrence stay put; carets outside one move to the next occurrence. Pressing `*` again for the same active word navigates forward; counts such as `2*` then skip to the requested occurrence, with every caret searching the primary word from its own position. Selecting a different word activates its search using the same positioning rules. It uses the same Unicode letters/digits/underscore boundaries as `w`, so `cat` skips `scatter`, `cat_cat`, and `cat2`. If the caret is not on a keyword, it takes the next keyword on that line; with none, it uses the punctuation run under or after the caret as a literal substring. A blank remainder reports no word and preserves the previous search. This also works in read-only diff text. Bind `config.core.search_word` to remap it.
|
||||
|
||||
`n`/`N` and an empty `/` submission retain the whole-word setting; a nonempty `/` query returns to literal substring search. Cancelling `/` preserves both the previous query and its matching behavior.
|
||||
|
||||
Normal-mode Escape hides search highlights without forgetting the query or matching mode. The next `*` reactivates highlighting, staying put only when at or inside a match; `n`/`N` or submitting `/` resumes navigation and restores highlighting. Escape used to cancel a prompt, selection, or pending motion keeps its existing behavior.
|
||||
|
||||
Submitting an empty search repeats the last query. Esc cancels without moving the cursor or replacing the previous query/match. A missing match reports the query and leaves the cursor unchanged; searching without a previous query also leaves the cursor unchanged. Search never edits text or adds undo history. Buffer edits and undo/redo retain the query and recompute its visible highlights, so subsequent navigation searches the current text again.
|
||||
|
||||
## Commands, saving, and pasted input
|
||||
|
||||
Commands: `:w [path]`, `:q`, `:q!`, `:wq [path]`, `:plugins`, and `:plugin-command [arguments]`.
|
||||
`:` opens compact floating command input titled **Command**; `/` opens input titled **Search** for buffer text search. Titles sit at the top-left border, replacing the displayed leading `:` / `/`. Both input fields have one column of padding on each side. Enter submits and Escape cancels using the existing modal rules. Long Unicode input scrolls horizontally without changing buffer text. Both windows default to the workspace's bottom-left edge, directly above the bottom bar when visible; their [anchors can be configured independently](configuration.md#command-and-search-popup-anchors). They temporarily hide operation notifications and never reserve a permanent prompt/footer row. Tiny windows omit borders/titles or padding when needed to keep input usable.
|
||||
|
||||
`:q` refuses unsaved changes in any open buffer; `:q!` exits without saving them. `:wq` saves the active buffer and quits only if every buffer is then clean. Saves use a same-directory temporary file and rename, preserve existing permissions, and reject target symlinks. Writing to a path owned by another loaded buffer refuses before modifying the file. UTF-8 text is edited by extended grapheme; tabs render at four-cell stops. LF and trailing-newline structure are preserved; CRLF and CR are normalized to LF. Binary/terminal-control-containing text is rejected. Bracketed paste inserts only in Insert mode and never executes pasted commands in Normal mode.
|
||||
Up/Ctrl+k recalls older entries; Down/Ctrl+j recalls newer entries and restores the unfinished input after the newest. Navigation stops at either end without executing a command or moving search targets. Recalled text is editable without changing stored entries. Command and search histories are separate, shared across buffers/panes/tabs, and retained only for this editor session, up to 100 entries each. Enter records nonempty submissions, including unknown commands and searches with no matches; consecutive duplicates are skipped. Empty submissions and cancelled drafts are not recorded. Ctrl+j no longer submits Command/Search input; use Enter.
|
||||
|
||||
Tab replaces the command-name prefix with the first case-sensitive match in alphabetical order; repeated presses cycle forward through the same matches and wrap. Shift+Tab cycles backward, starting at the last match when no cycle is active. Switching direction retains the original prefix. Candidates include canonical core commands, shorthand aliases, and commands from currently enabled plugins. Empty input cycles all command names. Typing, deleting, or browsing history starts a fresh completion cycle. Completion only changes the prompt: Enter still executes, and Escape cancels. Arguments (including paths) are not completed; Tab and Shift+Tab leave them unchanged. Search-mode Tab remains literal text. Rebind or disable forward/backward completion with `config.core.command_complete` / `config.core.command_complete_previous` in Command mode.
|
||||
|
||||
Command input works in both Normal and Visual modes, including read-only diff panes. The original selection stays highlighted while typing. Enter dispatches with its ranges, direction, and linewise shape intact; individual commands decide whether to consume or retain them. Escape returns to the original Visual selection without executing. For example, select lines with `V`, then type `:comment` and press Enter—no command palette is needed. `config.core.command` can also be bound in Visual mode.
|
||||
|
||||
Use `:!COMMAND` (for example `:!pwd` or `:!echo "$PATH"`) to run shell commands asynchronously while continuing to edit. Vamp runs `$SHELL -c COMMAND`, falling back to `/bin/sh`, in the editor's project directory with the inherited environment and closed stdin. Shell quoting, pipes, and redirection work normally; interactive terminal programs are not supported. Commands have the same permissions as Vamp, including file and network access. Submit additional `:!` commands while others are running to execute them concurrently.
|
||||
|
||||
While running, the default top bar uses one independently styled segment immediately left of the battery for all pending commands. Each entry shows the first three command graphemes, `...` when truncated, and an animated spinner after a 200 ms delay. Completion opens a read-only floating window with the command, exit status (or launch error), stdout, and separately marked stderr. Further completed results queue without replacing the visible window; Enter/Escape dismisses the current result and opens the next, or resumes the underlying editing mode when none remain. Arrows/Ctrl+h/j/k/l and the mouse wheel scroll; Home resets and End goes to the last line. Output is decoded as UTF-8 with replacements; controls are displayed as text, never interpreted as terminal escapes. Capture retains up to 4 MiB per stream with an explicit truncation notice. There is no command timeout; exiting Vamp kills all running command process groups, and background jobs in each group are also stopped when their command exits. Shell execution currently requires Unix.
|
||||
|
||||
In the shell output window, your configured `config.core.word_wrap.toggle` binding toggles soft wrapping, including leader and multi-key sequences. Bindings use Normal mode while the popup is focused; there is no additional default shortcut. This does not change output bytes or the source buffer's wrap setting. Wrapping starts off for each command; toggling resets scrolling to the start. With wrapping on, vertical scrolling follows visual rows and horizontal scrolling is disabled.
|
||||
|
||||
The latest reported operation result appears in a non-focusable popup at the workspace's bottom-right, just above the bottom bar when visible, with one column of inner padding on each side when space permits. It remains until dismissed or replaced, with no timer. In Normal mode, the first Escape dismisses it without collapsing carets; a subsequent Escape retains ordinary Normal behavior. Existing modal windows, focused explorers/diff selectors, and pending prefixes retain Escape priority. New operation messages reopen the popup; routine successful buffer switches do not duplicate the buffer/path information already shown in the bar.
|
||||
|
||||
Command-capable core actions derive canonical Ex names by removing `core.`: `core.quit` gives `:quit`, `core.save` gives `:save`, and `core.diff.close` gives `:diff.close`. Native editing and Insert-only completion/snippet actions remain action bindings, not additional Ex commands.
|
||||
|
||||
Commands: `:save [path]`, `:force_save [path]`, `:quit`, `:force_quit`, `:restart`, `:force_restart`, `:save_and_quit [path]`, `:force_save_and_quit [path]`, `:plugins`, and `:plugin-command [arguments]`. Short names remain aliases of these canonical commands, with identical argument and safety rules:
|
||||
|
||||
| Alias | Canonical command |
|
||||
| --- | --- |
|
||||
| `:w` | `:save` |
|
||||
| `:w!` | `:force_save` |
|
||||
| `:q` | `:quit` |
|
||||
| `:q!` | `:force_quit` |
|
||||
| `:restart!` | `:force_restart` |
|
||||
| `:wq` | `:save_and_quit` |
|
||||
| `:wq!` | `:force_save_and_quit` |
|
||||
| `:bnext` | `:buffer_next` |
|
||||
| `:bprev` | `:buffer_previous` |
|
||||
| `:bdelete` | `:buffer_delete` |
|
||||
| `:bdelete!` | `:buffer_force_delete` |
|
||||
|
||||
`:q` refuses unsaved changes in any open buffer; `:q!` exits without saving them. `:wq` saves the active buffer and quits only if every buffer is then clean; `:wq!` applies the same quit rule after a force save. The typed actions are `core.save`, `core.force_save`, `core.save_and_quit`, and `core.force_save_and_quit`. Normal saves re-read actual disk content and compare it with the saved baseline after CRLF/CR-to-LF normalization, independently of polling or timestamps. External changes or deletion refuse the write with a warning; a new buffer opened at a nonexistent path may save normally. Use `:w!` / `:force_save [path]` or `:wq!` / `:force_save_and_quit [path]` to explicitly overwrite external changes. Force bypasses only the external-change check: historical snapshots remain read-only, target symlinks are rejected, and another loaded buffer's path cannot be overwritten.
|
||||
|
||||
`:restart` closes clean buffers across all tabs, panes, and historical views. If any dirty buffer remains, it preserves that buffer's unsaved text and undo/redo history, warns, and keeps the editor interactive; clean buffers already closed stay closed. With no dirty buffers, it restarts the executable. `:force_restart` (alias `:restart!`) restarts regardless of dirty buffers, discarding unsaved text without writing it. Both commands take no arguments; their Normal-mode actions are `core.restart` and `core.force_restart`, with no default keybindings. Selecting force restart in the command palette requires confirmation; an explicitly configured force-restart binding executes directly.
|
||||
|
||||
Restart tears down the entire editor session, including workers and plugins, before relaunching the same executable with its original CLI arguments. It briefly resets raw mode and input reporting but retains the alternate screen across the process handoff; the new process resumes input modes and clears and repaints that screen atomically in its first frame. The new process rereads configuration and reopens the original startup file from disk, or starts with an unnamed buffer if no file was supplied. Current buffers, tabs, views, and other session state are not restored. Final quit, errors, and panics still restore normal input modes, the normal screen, cursor visibility, and the prior panic hook.
|
||||
|
||||
All saves use a same-directory temporary file and rename and preserve existing permissions. UTF-8 text is edited by extended grapheme; tabs render at four-cell stops. LF and trailing-newline structure are preserved; CRLF and CR are normalized to LF. Binary/terminal-control-containing text is rejected. Bracketed paste inserts only in Insert mode and never executes pasted commands in Normal mode.
|
||||
|
||||
Live file buffers automatically check disk metadata every 250 ms, including buffers in inactive tabs/panes and parked views; historical snapshots are excluded. Content is read only when metadata changes. A clean buffer reloads validated changed text, clears stale undo/redo, preserves caret/selection and view positions where possible, and clamps them to the new text. Reloads invalidate annotations and stale asynchronous requests and refresh live diffs. Dirty buffers retain their edits. Missing, unreadable, or invalid changed files preserve buffer text and report a warning rather than replacing it.
|
||||
|
||||
Paste is backend input: it is ignored in Normal, Command, Search, and Visual modes, and inserts literal text in Insert mode, with CRLF/CR normalization and a 4 MiB limit. Pasted text is one undo action, separate from typing before and after it. Rejected paste reports an error without changing text, cursor, mode, or pending insert history. Internal clipboard actions are separate from `Input::Paste` and use already-validated buffer text.
|
||||
|
||||
## Cursor-following scrolling
|
||||
|
||||
[Configure `scroll_distance`](configuration.md#preferences) to reserve space between the primary cursor or picker selection and the viewport edges. `0` (default) scrolls only to keep it visible; an integer reserves that many visual rows, and columns for unwrapped document text. `nil`, or a margin too large for the current viewport, centers it as far as the start of content permits. This policy applies to documents, historical/diff panes, file explorers, palettes, completion lists, and revision pickers. Reversing direction inside the margin does not move the viewport; resizing recalculates the usable margin.
|
||||
|
||||
## Mouse wheel scrolling
|
||||
|
||||
Mouse-wheel up/down scrolls the document view three display rows per event without moving the primary or secondary carets, changing selections, or editing text. The caret may scroll offscreen; its terminal cursor is hidden until visible again. Navigation (including a motion blocked at the document boundary), editing, or buffer navigation restores caret-following. Idle updates preserve a wheel-scrolled view, clamped to the document; resizing preserves unwrapped views and restores caret-following in ordinary wrapped buffers.
|
||||
|
||||
Mouse-wheel left/right scrolls three display columns per event when wrapping is off. **Shift+wheel up/down** provides the same left/right scrolling when the terminal does not send horizontal wheel events. Tabs and wide Unicode characters use terminal-cell widths; scrolling stops at the longest line and remains detached from the caret until navigation or editing resumes. Wrapped text consumes horizontal wheel input without panning.
|
||||
|
||||
Vertical wheel input over a hover popup or floating/docked file explorer scrolls that panel instead. Explorer scrolling preserves the selected file, filter, and keyboard focus; keyboard input resumes selection-following. An offscreen selected entry has no browsing cursor, while the filter input keeps its own cursor. Horizontal wheel input over these panels is consumed without panning the document. Completion lists, command palettes, and startup notices consume wheel input without scrolling the background or editing text. Mouse clicks and dragging are not editing actions.
|
||||
|
||||
## Word wrap
|
||||
|
||||
Use `:word_wrap.toggle`, the **Toggle word wrap** palette action, or `config.core.word_wrap.toggle` in a custom binding. Wrapping defaults to **off** for new source buffers and **on** for local review buffers, with **no default keybinding**. Each ordinary pane retains its own setting for each buffer; toggling does not edit text or enter undo history.
|
||||
|
||||
Toggling preserves the source caret and anchors a visible caret to its previous screen row in ordinary and diff buffers. File boundaries clamp the anchor when there are not enough preceding rows. Horizontal position follows the reflowed text.
|
||||
|
||||
Text wraps at word boundaries where possible, with grapheme-safe breaks for long words. Word-break opportunities require non-whitespace text on the visual row, so indentation alone does not push a long identifier onto a new row. Whitespace is preserved; tabs keep their source-column stops and wide/combining Unicode characters retain their geometry. Only the first display segment shows a line number. Syntax and semantic colors, diagnostics, search matches, selections, and cursors follow the wrapped text. Motions and counts still use source lines, so `j`/`k`, Home/End, and saved file contents are unchanged. Vertical wheel input scrolls continuation rows; switching wrapping off restores horizontal scrolling.
|
||||
|
||||
## Current-line Git blame
|
||||
|
||||
Inline blame is enabled by default in live file buffers and on the focused side of split/unified diffs. The primary caret's line shows its author, commit summary, and short commit ID after the document text; changed or newly inserted tracked-file lines show **Uncommitted**, including unsaved edits. Live Git-backed jj buffers use the working-copy revision's single parent, not a potentially stale Git HEAD. Merge working copies with multiple parents omit live attribution.
|
||||
|
||||
Loading happens in the background without network access or changing repository refs/checkouts. Attribution is loaded once for the active buffer's in-memory contents; navigation then selects cached lines immediately, and movement during a cold load does not restart it. Editing, saving, reloading, changing source buffers, regaining terminal focus, or toggling blame invalidates the cached attribution. Historical sides use their captured commit and side-specific path, including renamed or deleted files no longer on disk; historical tabs retain that source and any privately fetched objects after the comparison closes. Frozen Working sides use their captured parent baseline rather than a later checkout. Missing, untracked, unborn, and non-repository live files have no indicator. Long attribution labels clip to the spare cells after the source text instead of disappearing entirely. The indicator is hidden when the caret is offscreen or no inline space remains; wrapped lines use their final visible continuation without covering text, selections, or the caret. Popups retain their normal layering.
|
||||
|
||||
Use `:git_blame.toggle`, the palette action, or remappable `config.core.git_blame.toggle`; there is no default keybinding. Set `config.git_blame = false` to disable it at startup. Disabling stops the worker and clears the label without changing text or undo history.
|
||||
|
||||
## Panes and splits
|
||||
|
||||
Splits can be nested in either direction. The new pane receives focus. Panes showing the same buffer share text, saved state, diagnostics, and undo/redo history, but retain independent carets, selections, modes, searches, and vertical/horizontal viewports. Buffer navigation changes only the focused pane. A file is still loaded once, even when displayed in several panes.
|
||||
|
||||
| Canonical command | Typed action | Behavior |
|
||||
| --- | --- | --- |
|
||||
| `:pane.split_horizontal` | `config.core.pane.split_horizontal` | Split above/below (`_` in Normal) |
|
||||
| `:pane.split_vertical` | `config.core.pane.split_vertical` | Split left/right (`\|` in Normal) |
|
||||
| `:pane.focus_left` / `:pane.focus_down` / `:pane.focus_up` / `:pane.focus_right` | Corresponding `config.core.pane.focus_*` action | Directional focus (Option/Alt+h/j/k/l in Normal) |
|
||||
| `:pane.close` | `config.core.pane.close` | Close a focused docked file list, otherwise close the focused editor pane subject to unsaved-change protection |
|
||||
| `:pane.force_close` | `config.core.pane.force_close` | Close a focused docked list without discarding data; otherwise explicitly discard exclusively displayed edits and close the editor pane |
|
||||
|
||||
Closing a pane gives its space to its sibling:
|
||||
|
||||
| Situation | Close pane | Force close pane |
|
||||
| --- | --- | --- |
|
||||
| Focused docked explorer or diff file list | Close only the list and return document focus; retain buffers, edits, tabs, and comparison | Same |
|
||||
| Clean buffer displayed only here | Close pane and buffer | Same |
|
||||
| Dirty buffer displayed only here | Refuse; save or force-close explicitly | Discard edits and close pane and buffer |
|
||||
| Buffer also displayed in another pane or tab | Close only this pane; retain the buffer and edits | Same |
|
||||
| Last pane in a tab, with other tabs open | Close the tab using the same shared-buffer and unsaved-change rules | Same, discarding only exclusively displayed edits |
|
||||
| Last pane in the last tab | Quit only if every open buffer is clean, including hidden buffers | Quit without saving |
|
||||
|
||||
There is no default close-pane binding. Option must send Alt/Meta in the terminal; on macOS, configure the terminal's Option-key behavior if it instead produces special characters. These bindings do not replace existing Ctrl+j or uppercase motion/edit bindings.
|
||||
|
||||
A focused docked list is a close-action target even when it is the only visible side panel; closing it never quits or closes its buffer. A visible but unfocused dock does not intercept pane-close. The command palette remembers a dock that had focus when it opened for these two close actions, including force-close confirmation and whitespace edits to that command; cancelling or choosing another action clears that target.
|
||||
|
||||
Floating pickers are not pane-close targets. A resolved close/force-close action passes through to the underlying editor pane/tab with its existing dirty-buffer guards; it is not ignored and does not merely dismiss the picker. A surviving tab-owned floating picker remains open until its ordinary Escape/close behavior or owner closure removes it. Printable bindings remain query text while a filter owns input; control-key or control-prefix bindings can invoke pane-close without altering the query.
|
||||
|
||||
Pane-focus bindings also work while the ordinary file explorer or picker has focus. Moving to a neighboring pane returns keyboard focus to its document; a floating picker closes, while a docked explorer remains visible. Explicit `tree` or `selection` navigation overrides and disabled keys take precedence over pane-focus bindings.
|
||||
|
||||
Floating windows overlay the entire editor, above all workspace panes. File pickers, revision selectors, hover documentation, and completion lists are not clipped to the focused pane; completion remains anchored to its caret. Docked exploration reserves space at the editor edge before the remaining workspace is split into panes. The changed-file explorer follows the same layout, on the editor's right edge.
|
||||
|
||||
On light terminals that answer color queries, selected explorer rows use a pale shade of the terminal background, preserving filename, directory and repository-status foregrounds when focused or unfocused. Dark terminals and unavailable color reports retain the ANSI blue/dark-gray selection backgrounds. Theme changes update visible and parked panes.
|
||||
|
||||
|
||||
Diff comparisons reuse the split geometry and directional-focus engine. Option/Alt navigation moves between Before, After, and Files first, then to a neighboring workspace pane when there is no internal target in that direction. Splitting a diff text view creates an ordinary sibling showing the same buffer; historical snapshots remain read-only, including after the comparison closes.
|
||||
|
||||
## Tabs
|
||||
|
||||
Use `:tab.new` to open the current buffer in a new, focused tab with one pane. Each tab preserves its split layout, focused pane, explorer, and comparison. Buffers and undo/redo history remain shared; carets, selections, searches, wrapping, and scroll positions are independent views. Opening a historical diff buffer in a tab keeps it read-only, even after the source comparison closes.
|
||||
|
||||
| Canonical command | Typed action | Behavior |
|
||||
| --- | --- | --- |
|
||||
| `:tab.new` | `config.core.tab.new` | Open the current buffer in a new tab |
|
||||
| `:tab.previous` / `:tab.next` | `config.core.tab.previous` / `config.core.tab.next` | Switch tabs, wrapping at either end; Ctrl+Option/Alt+h/l in Normal |
|
||||
| `:tab.close` | `config.core.tab.close` | Close the current tab and all its panes, protecting unsaved changes |
|
||||
| `:tab.force_close` | `config.core.tab.force_close` | Explicitly discard exclusively displayed edits and close the tab |
|
||||
|
||||
By default, multiple tabs show a single top row with numbered filenames and dirty markers, with padding inside each tab's styling. The active tab has an accent-colored background fading into the terminal background through `░▓` / `▓░`, except the first tab has no left fade; inactive tabs remain unfilled. Narrow terminals keep the active title visible. New/close actions have no default keybinding; for example, `config.bind "leader t", config.core.tab.new`.
|
||||
|
||||
The [top and bottom bars](configuration.md#top-and-bottom-bars) accept the same builtin and custom segments, anchored left, truly centered on the full row, or anchored right. Either bar can show tabs or status information, with independent title templates, internal padding, and styled edge glyphs. Defaults keep tabs and battery above, with home-abbreviated paths on the bottom left and language/ready LSP names/position on the bottom right. Floating input and operation notifications overlay the workspace without reserving a footer. Empty content consumes no row, and a bar whose only visible content is tabs is hidden with a single tab in either position. Custom named values are session-wide and can update through plugins without editing buffers; empty values hide their segments. Both bars share collision handling: narrow layouts first omit inactive tabs, then optional segments from group ends to avoid overlap; the active tab drops decorations before its title is clipped.
|
||||
|
||||
At very small heights, both bars yield to a document row; floating input still accepts text on a one-row terminal. If only one bar row fits while both have content, the top bar receives it.
|
||||
|
||||
Closing a tab refuses dirty buffers whose final displayed owner would disappear, including a comparison's working and return buffers. Buffers displayed in another tab remain open with their edits, even on force-close. Other hidden buffers remain loaded. Closing the last tab quits only if every open buffer is clean; force-close quits without saving.
|
||||
|
||||
## Buffers
|
||||
|
||||
One buffer is visible at a time. Each retains its text, path, saved state, directed selections and primary, mode, search state, and undo/redo history. The TUI retains separate vertical/horizontal scroll offsets by stable buffer ID, adjusting them only as needed to keep the primary visible after resizing. Clipboard fragments, bindings, plugin hosts, and plugin retirement remain session-wide. Plugin context and effects refer to the active buffer.
|
||||
Each buffer retains its shared text, path, saved state, and undo/redo history. View state is retained separately for each pane and buffer. Caret-following adjusts that view's offsets as needed; mouse-wheel scrolling can temporarily detach it from the caret. Clipboard fragments, bindings, plugin hosts, and plugin retirement remain session-wide. Plugin context and effects refer to the focused pane's active buffer.
|
||||
|
||||
| Command | Behavior |
|
||||
| --- | --- |
|
||||
| `:edit PATH` | Switch to an already-loaded file, or read and validate a new buffer; a nonexistent file opens empty |
|
||||
| `:buffers` | List stable IDs and paths; `%` marks active, `+` marks dirty |
|
||||
| `:buffers` | Open the searchable buffer picker; stable IDs and paths, `*` before the active buffer ID, `+` dirty |
|
||||
| `:buffer N` | Switch to buffer ID `N` |
|
||||
| `:bnext` / `:bprev` | Switch in ascending-ID order, wrapping at either end |
|
||||
| `:bdelete [N]` | Close the active or named buffer; refuse unsaved changes |
|
||||
| `:bdelete! [N]` | Explicitly discard changes and close the active or named buffer |
|
||||
| `:buffer_next` / `:buffer_previous` | Switch in ascending-ID order, wrapping at either end |
|
||||
| `:buffer_delete [N]` | Close the active or named buffer; refuse unsaved changes |
|
||||
| `:buffer_force_delete [N]` | Explicitly discard changes and close the active or named buffer |
|
||||
|
||||
IDs start at 1 and are never renumbered or reused. Closing the last buffer creates a fresh unnamed clean buffer rather than quitting. Closing the active buffer selects the next remaining ID, with wraparound. Switching does not save, discard, or reload hidden edits. Existing-file aliases resolve to the same loaded buffer; the supplied path spelling remains the save/display path, so opening through a symlink does not bypass save rejection. Paths are relative to the process working directory; the entire `:edit` argument is the path, including spaces, with no shell expansion.
|
||||
IDs start at 1 and are never renumbered or reused. Closing the last buffer creates a fresh unnamed clean buffer rather than quitting. Closing the active buffer selects the next remaining ID, with wraparound. Switching does not save or discard hidden edits; automatic disk checks also cover hidden clean buffers. Existing-file aliases resolve to the same loaded buffer; the supplied path spelling remains the save/display path, so opening through a symlink does not bypass save rejection. Paths are relative to the process working directory; the entire `:edit` argument is the path, including spaces, with no shell expansion.
|
||||
|
||||
Switching from Insert commits its pending undo group and parks that buffer in Normal. Explicit buffer switching from Visual retains that buffer's directed ranges and Visual mode; switching back restores them. Command/search prompts, palette queries, and pending motion counts are transient, not restored per buffer. The new commands appear in the command palette and can be bound by exact command name in Normal mode. When several buffers are open, status shows the active ID and total count.
|
||||
Switching from Insert commits its pending undo group and parks that view in Normal. Explicit buffer switching from Visual retains the pane's directed ranges and Visual mode for that buffer; switching back restores them. Command/search prompts, palette queries, and pending motion counts are transient, not restored per buffer. Buffer commands appear in the command palette and can be bound by their typed core actions in Normal mode. When several buffers are open, status shows the active ID and total count.
|
||||
|
||||
**Space b l**, `:buffers`, or the **Buffers** command-palette action opens the picker. Type to filter IDs and paths with case-insensitive, whitespace-separated substring tokens; every token must match. Results retain ascending ID order. Ctrl+j/Ctrl+n/Down and Ctrl+k/Up select with wraparound, using the shared Selection bindings and overrides. Backspace edits the query; Ctrl+u clears it. Enter switches only the focused pane to the selected buffer without saving or discarding edits; no matches leave the picker open. Esc or Ctrl+p cancels without switching. Printable keys, including `:` and leader keys, belong to the query.
|
||||
|
||||
The picker uses the file explorer's centered floating-panel geometry, a cyan border, padded search input, and dimmed controls. Buffer IDs and status columns align across rows: IDs use the normal text foreground, a cyan `*` before the ID marks the active buffer, and a two-column gap separates the ID from the filename. Unsaved buffers show a yellow `+` in the first gap column; the selected row is blue. Paths under the home directory display as `~/…`, using the same component-aware abbreviation as the status bar; searching and file operations retain the original paths. Narrow or short terminals drop padding/borders as needed while keeping the query cursor and selected result visible whenever a result row fits.
|
||||
|
||||
The picker includes ordinary buffers from every tab and unnamed buffers as `[No Name]`; immutable diff snapshots are excluded. Labels sanitize path control characters, but selection uses stable buffer IDs, so displayed-name collisions still select the correct buffer. Switching out of a diff follows ordinary `:buffer N` behavior.
|
||||
|
||||
## File picker and explorer
|
||||
|
||||
Space o opens a floating **Tree** explorer directly in **INSERT/filter** mode, ready for typing; Space e opens or focuses the docked **Tree**, starting in **NORMAL/navigation** mode when new. Both use one catalog and instance. Invoking the other action applies that presentation's configured default while retaining query, selection identities, and surviving folder expansion. Floating Tree invocation enters filtering if not already filtering. These actions are available as `config.core.file_picker` and `config.core.file_explorer` in Normal/Visual and in the command palette.
|
||||
|
||||
Normal pickers and explorers show the same colored **A/M/D/R** markers as the diff file picker: green additions, yellow modifications, red deletions, and cyan renames (`old -> new`). Unchanged files remain visible. Status compares disk and unsaved buffer text with Git `HEAD` or Git-backed jj's single parent `@-`; it works in both Tree and List, even with `git_gutter = "none"`. Missing tracked files remain as deleted entries; opening one uses the usual missing-file behavior. Status loads asynchronously from startup and refreshes on edits/saves, focus regain, and once per second, even while the picker is closed. Opening or reopening a picker uses the latest completed project-wide result without restarting the status query. The marker column always reserves its width, so filenames do not shift while the initial result arrives or when the checkout becomes clean. Ctrl+r rescans the normal catalog and refreshes status; status polling alone does not rescan for newly created files.
|
||||
|
||||
While a docked Tree has focus in **NORMAL/navigation** mode, leader sequences work in ordinary and diff views: Space o replaces the dock with the floating picker, and Space e returns focus to the document like Escape while leaving the dock visible. Invoking Space e again from the document refocuses it. Tree/selection navigation overrides retain priority. In **INSERT/filter** mode and List query fields, printable leader keys remain literal query text rather than triggering editor actions; configured control-key action bindings remain available.
|
||||
|
||||
The floating explorer is centered, capped at 100 columns by 24 rows, and shrinks to fit smaller terminals. The tree mode appears in the title; the help row does not repeat it.
|
||||
|
||||
The dock defaults to the right of the editor workspace. See [configuration preferences](configuration.md#preferences) to choose another side. Status and command/search prompts remain full-width; editor text, gutter, highlights, and cursors use the remaining rectangle. Focused panes prioritize their query on tiny terminals; unfocused docks shrink or hide to preserve editing space.
|
||||
|
||||
The explorer root path wraps within the pane width in floating, docked, and diff file views; file rows and keybinding help do not wrap. The path header grows to fit where space permits, reserving at least one file row. Very short panes clip the remaining path rather than hiding file navigation.
|
||||
|
||||
Both presentations default to Tree; [configuration preferences](configuration.md#preferences) can select List independently for each. Ctrl+t toggles the current focused instance without rescanning. List retains searchable full relative paths. Tree shows folders first, two-cell indentation, and basename-only files. Folder names end in `/` and use cyan text; files use the normal foreground color. Fold-state arrows are omitted. Maximal single-child directory chains share one row, such as `src/client/http/`; a directory containing one file still gets its own row.
|
||||
|
||||
Floating Tree opens in explorer **INSERT** mode; a new docked Tree opens in **NORMAL**. Press `i` in NORMAL to resume editing the existing filter; the `i` itself is not added to the query. Typing and Backspace filter full relative paths by case-insensitive whitespace tokens. These are explorer-local modes, not changes to the file buffer's mode. Matching nodes appear with ancestor context, and query changes initially select a direct match. Escape in INSERT changes only to NORMAL: the filter, visible results, highlighted item, and explorer focus remain. NORMAL displays the active filter and navigates that filtered tree. Escape from NORMAL returns focus to the buffer (or closes floating search). List always accepts query typing immediately.
|
||||
|
||||
Search reuses the diff revision selector's fuzzy matcher in both Tree and List, including changed-file explorers. Each whitespace-separated token must match an ordered character subsequence of the full relative path; tokens can appear in any order. For example, `sr/fp RS` finds `src/fuzzy_parser.rs`. Catalog order and folder context stay unchanged rather than ranking the results.
|
||||
|
||||
| File-view input | Behavior |
|
||||
| --- | --- |
|
||||
| Type / Backspace | Type query text in List/explorer INSERT / remove one whole grapheme; explorer NORMAL uses hjkl for navigation |
|
||||
@@ -156,22 +386,280 @@ Clearing returns to the full catalog and reveals the selected file's ancestry in
|
||||
|
||||
The project root is the working directory captured at startup. Scanning uses the `ignore` crate for nested `.gitignore` rules and negation; parent/global Git ignore rules are disabled. Hidden regular files and directories are included unless ignored, `.git`/`.jj` metadata is always excluded, and symlink files/directories are not followed. Files open using their original OS paths, not sanitized display labels. Root scan failures report an error; descendant/ignore errors retain reachable entries with an explicit incomplete-scan warning. A failed refresh keeps the prior catalog. There is no background watcher: refresh explicitly after external file changes.
|
||||
|
||||
## Repository diff
|
||||
|
||||
Run `:diff` in Normal mode, choose **Before**, then **After**, and press Enter to compare. The command palette also exposes **Diff**; there is no default keybinding. Repository discovery starts at the active file's directory, or the startup project root for an unnamed buffer, and prefers jj over Git.
|
||||
|
||||
The floating selector has **Revisions / Bookmarks** tabs for jj, or **Commits / Branches / Tags** for Git. Both jj tabs use flat lists without ancestry lanes. **Revisions** puts the short change ID and commit description on the first line; bookmarks, author, date, commit ID, and textual **[checkout]** / **[immutable]** badges appear on a dimmed second line. **Bookmarks** puts the name first, with the commit description underneath. Local and remote-tracking bookmarks remain individually selectable, including multiple names on one revision, preserving their symbolic follow behavior. Narrow windows omit revision metadata and use compact single-line entries.
|
||||
|
||||
Both stages support case-insensitive fuzzy search by revision/change ID, commit ID, reference name, or description: `f1205pas` can find `sm/fin-1205-pilot-assignment-schema`. Space-separated tokens must all match, but can match different fields; a token cannot span unrelated fields. jj keeps catalogue order while filtering. Git ranks exact, prefix, and contiguous matches ahead of scattered subsequences, with names/IDs ahead of descriptions and catalogue order breaking ties. An empty query restores catalogue order. After choosing Before, its revision carries a **[Before]** badge instead of a separate summary row. It remains included through search and category changes, but scrolls normally.
|
||||
|
||||
The separate checkout choice stays first in every category regardless of the query. It is **Checkout snapshot** during Before selection: a frozen disk snapshot including eligible untracked files. During After selection it is **Follow checkout** when `config.diff_follow_working_copy` is enabled, otherwise **Checkout snapshot**. Either After choice includes unsaved regular-text buffers and enables live editing; opening a comparison never saves them. Unlike this live-files choice, selecting the recorded checkout revision in Revisions pins that revision.
|
||||
|
||||
New comparisons default to **Branch changes**: Before becomes the unique merge base of the selected Before and After revisions, and After stays the selected tip. Changes exclusive to the Before branch are excluded. The Before border identifies both selected names and the immutable merge-base commit ID. **Snapshots** compares the two selected snapshots directly. **Ctrl+b** toggles the mode, also available as **`:diff.mode.toggle`**, the palette action, and remappable **`config.core.diff.mode.toggle`**. Toggling an opened comparison recomputes using the original selected endpoints. Selecting **Checkout snapshot** or **Follow checkout** immediately forces **Snapshots**; Branch changes is unavailable while either is selected. Missing or multiple merge bases produce an explicit, recoverable selector error rather than silently falling back; choose Snapshots to compare such histories. jj's synthetic root is the empty ancestor of every jj history.
|
||||
|
||||
| Selector input | Effect |
|
||||
| --- | --- |
|
||||
| Tab / Shift+Tab | Next / previous category |
|
||||
| Up / Down, Ctrl+k / Ctrl+j | Previous / next entry |
|
||||
| Backspace / Ctrl+u | Remove a query grapheme / clear query |
|
||||
| Ctrl+b | Toggle Branch changes / Snapshots (checkout choices require Snapshots) |
|
||||
| Enter | Choose the entry |
|
||||
| Esc | Close either selector stage, cancel outstanding work, and restore the source buffer without discarding edits |
|
||||
|
||||
Printable input belongs to the focused query, including `:`, `_`, and `|`; Normal-mode command or pane bindings cannot steal it. Explicit selection-navigation bindings still take priority. Use Ctrl+p to select an action, or configure a control-key action binding, when you need an editor action while the selector is focused.
|
||||
|
||||
The selector initially lists local revisions and known tracking refs **without contacting remotes**. **Load refs from origin** (or another configured remote) in Bookmarks/Branches/Tags lists advertised references, including refs never fetched locally, without advancing the selection stage. Selecting a reference such as `some-bookmark@origin` reuses available content or fetches the missing selected reference into a temporary comparison repository. **Load history from origin** in Revisions/Commits explicitly imports searchable remote history. Network operations use the repository's existing credentials; errors stay in the selector. They do not update active refs, snapshot jj's working copy, or change the checkout.
|
||||
|
||||
**Pull requests:** run **`:pull_requests [remote]`**, use the palette's `pull_requests` action, or bind **`config.core.pull_requests`**. The floating picker has **Open / Closed / Drafts / All** tabs. Open excludes drafts; Drafts contains open draft requests; Closed includes merged requests and closed drafts. Tab/Shift+Tab changes category, typing fuzzy-searches its number, title, author, state, and branches, and Enter immediately opens the selected request in **Branch changes** mode using its immutable head and merge base. Escape restores the source buffer. A failed list can be retried with Enter. The default remote is `origin`, or the sole configured remote; specify a name when there are multiple remotes without `origin`.
|
||||
|
||||
Each pull request's metadata shows added/deleted line counts after its state, before the branch names: `author · open · +123 -45 · topic → main`. Zero counts are shown explicitly; missing, denied, or failed statistics show `size unavailable` without preventing selection. Counts come from one batched read-only statistics query per nonempty GitHub/GitLab page ([GitHub](https://docs.github.com/en/graphql/reference/pulls), [GitLab](https://docs.gitlab.com/api/graphql/reference/#diffstatssummary)); [Gitea](https://docs.gitea.com/api/operations/repo-list-pull-requests/) supplies them directly in its list response. GitHub statistics require API authentication even for public repositories. Listing does not fetch source diffs.
|
||||
|
||||
Immediately before `#number`, **🙏 marks an outstanding personal review request** and **👍 marks your active approval**, separately from the `>` selection arrow. A review request takes precedence when both apply, including a re-review request after an earlier approval. “You” means the account authenticated to that forge's API—not the repository's Git author or SSH identity. Other users' and team-only requests do not count; completed or removed requests lose 🙏.
|
||||
|
||||
A later request for changes or dismissal removes 👍; comment-only and pending reviews do not replace an existing approval. The mark is not the PR's overall approval decision or a guarantee that you reviewed its current head; the forge controls approval resets after new commits. Customize either symbol with [`config.pull_request_review_requested_symbol` and `config.pull_request_approved_symbol`](configuration.md); an empty string hides that symbol. Multi-cell symbols remain aligned, and decorations are not part of searchable PR labels.
|
||||
|
||||
**Ctrl+s** opens sorting settings in the floating picker. The default comparison order is **Requested from me → Updated at → Approved by me → Created at**, with true statuses and newest timestamps first. Up/Down or the configured selection bindings navigate. Press **1–4** to assign the highlighted criterion an absolute precedence; it moves to that position and stays highlighted. Occupied explicit ranks shift forward (wrapping to a free slot); unnumbered criteria fill the remaining slots in their default relative order. Only explicitly assigned ranks display numbers. **Backspace** clears an explicit rank; **Left/Right** toggles oldest/newest first for timestamp criteria. Comparisons are lexicographic, with higher PR number as the final tie-breaker. Fuzzy text still determines which requests match; these settings determine their order.
|
||||
|
||||
**Ctrl+f** opens review filter checkboxes. **Space** toggles the highlighted bucket: **Requested from me**, **Approved by me**, or **Other / unavailable**. Checked buckets combine with OR, then intersect with the category and text query. All checked includes every review state; none checked produces no matches. These are personal states, not the PR's team approval threshold: teammates' outstanding requests do not cancel your approval. A new request for your own review takes precedence over your earlier approval. Unavailable metadata remains Other, not a claim that the PR has never been reviewed.
|
||||
|
||||
**Enter** applies either settings view; **Escape** discards its draft and returns to the PR list. Applied settings preserve the selected request where possible and carry across tabs and picker reopenings. Sorting persists across sessions; filters are session-local and restart from `config.pull_request_filters` or all buckets when unset. Previously saved filters are ignored. The picker displays its active review buckets whenever any are excluded. Category counts remain loaded-category totals, and partial-search notices still apply. Settings use already-loaded metadata without additional API requests. Explicit [configuration overrides](configuration.md#preferences) win again at startup; the settings view indicates when this applies.
|
||||
|
||||
Review-state reads reuse the same API credentials as listing. GitHub matches the current list's [requested reviewers](https://docs.github.com/en/rest/pulls/review-requests#list-requested-reviewers-for-a-pull-request) and filters published [reviews by author and decision state](https://docs.github.com/en/graphql/reference/pulls#pullrequest). GitLab filters approvals by the authenticated approver and reads individual reviewer [interaction states](https://docs.gitlab.com/api/graphql/reference/) in separate bounded, paginated batches; unsupported or denied reviewer-state fields do not discard known approvals or size metadata. Gitea reuses [paginated review reads per PR](https://docs.gitea.com/api/operations/repo-list-pull-reviews/) for both states, so its pages can take longer to load.
|
||||
|
||||
Anonymous, denied, missing, or failed state lookups leave the corresponding indicator unavailable without preventing browsing. A blank is not proof that no request or approval exists. Reopen the picker to fetch current review state. No approval, review request, or other remote write is performed.
|
||||
|
||||
GitHub, GitLab merge requests, and Gitea are supported. API reads require `curl`; public repositories work anonymously. Authentication uses `GH_TOKEN`/`GITHUB_TOKEN` for github.com, `GH_ENTERPRISE_TOKEN`/`GITHUB_ENTERPRISE_TOKEN` for GitHub Enterprise, `GITLAB_TOKEN` for GitLab, and `GITEA_TOKEN` for Gitea. With no matching environment token, GitHub/GitLab reuse `gh auth token --hostname HOST` / `glab auth token --hostname HOST` when available. Tokens are supplied to curl on stdin, not in subprocess arguments, and sent only to the HTTPS API; redirects are not followed. Git object fetching uses the configured remote's existing Git/SSH credentials separately.
|
||||
|
||||
Standard GitHub/GitLab/Gitea hosts and Codeberg are detected from HTTPS or SSH remote URLs. For another host, set `remote.<remote>.vamp-forge` to `github`, `gitlab`, or `gitea` in the repository's Git configuration, for example `git config remote.origin.vamp-forge gitea`. For a non-colocated jj repository, use `git --git-dir .jj/repo/store/git config remote.origin.vamp-forge gitea`.
|
||||
|
||||
SSH aliases are resolved with `ssh -G` before provider detection and API authentication, honoring the effective `HostName` and user-specific `Match` settings. SSH ports do not become HTTPS API ports. Git fetches retain the original remote URL, alias, and SSH identity configuration. A failed API load shows its error without also claiming that the search has no matches; the empty-result message appears only after a successful load.
|
||||
|
||||
Open (including drafts) and Closed fetch their first pages concurrently, newest-first, and display each page immediately. Open and Drafts filter the same catalog, sharing its loading, completion, and retry state without extra requests. Subsequent pages load in the background, with the active category's stream dispatched first; loaded rows remain selectable. Pages request 50 entries. GitLab Closed combines separate closed and merged requests (up to 100 entries per batch). All includes open, draft, closed, and merged requests from the two streams, deduplicates requests, and sorts by creation time; background updates preserve the selected PR's identity.
|
||||
|
||||
Search filters loaded entries locally and explicitly indicates partial results while more pages remain. A later-page error retains loaded rows; **Ctrl+r** retries failed fetch streams (the active category's stream, or both from All). Enter selects a loaded row; in an empty failed category it retries loading. Escape cancels outstanding work. Selection stops listing and only then retrieves that PR's historical metadata and preserved head reference, so GitLab detail reads and Gitea ref lookups do not delay the catalog.
|
||||
|
||||
Fork heads are fetched through the target repository's PR refs into the existing private comparison store, without changing active refs, jj operations, or checkout files. Closed/merged requests retain historical bases and heads rather than comparing against today's branch tips. If the server no longer retains the required commits, opening the request reports an error instead of displaying a different diff. Review submission and comments are separate, not part of this picker.
|
||||
|
||||
Missing or unprepared historical metadata is reported when selecting the affected request; it does not block listing other requests or substitute a live branch tip.
|
||||
|
||||
Comparison discovery builds the changed-path/status catalog first. File text, notices, and hunks load asynchronously when a file is selected and remain cached for that comparison. Failed file loads can be retried by selecting the file again; cancelled or superseded results cannot replace the current selection. Working-checkout comparisons still capture working bytes and the historical content needed to identify changes, preserving the frozen Before snapshot and unsaved After buffers.
|
||||
|
||||
Conflicted jj revisions also discover files without reading every blob. Ordinary files and symbolic links retain their Git contents; selected conflicted files show jj's rendered conflict projection. Unchanged links and jj's internal merge-tree metadata do not appear as changes. Viewing a conflict does not resolve it or modify the revision.
|
||||
|
||||
**Follow checkout After follows descendant checkouts automatically**, checked asynchronously once per second, including inactive tabs. A descendant jj change or Git HEAD rebuilds the changed-file catalog and captures current working bytes plus eligible unsaved buffers, while keeping the original Before frozen. jj tracking uses change IDs, so snapshot/description rewrites of the same change do not advance the endpoint or prevent following its later descendants. Same, backward, and unrelated checkouts do not rebuild the catalog; live-buffer editing and external reload still work normally. Historical After never follows. Set `config.diff_follow_working_copy = false` to disable following; the picker then calls this choice **Checkout snapshot**.
|
||||
|
||||
**Selected jj bookmarks follow their locally known targets automatically**, checked on the same one-second interval, including inactive tabs and with `config.diff_follow_working_copy = false`. Local bookmarks and known remote-tracking bookmarks retain their names; explicit revision selections remain pinned. A changed commit ID, including an amendment of the same change ID, rebuilds the comparison. Branch changes also recomputes the merge base. Unrelated endpoints stay frozen, except for the existing Follow checkout After behavior. Deleted or conflicted bookmarks keep the last successful comparison visible with an error; a later successful check clears the error. These checks never fetch, contact remotes, or snapshot jj's working copy; privately loaded remote history and advertised remote selections remain frozen.
|
||||
|
||||
Deleted or conflicted bookmarks unrelated to the selected endpoints do not block opening or refreshing a comparison.
|
||||
|
||||
**Pinned After editability tracks the checkout without moving either endpoint**, checked asynchronously once per second, including inactive tabs and when `config.diff_follow_working_copy = false`. Git matches the selected commit to HEAD; jj matches its change ID so snapshot/description rewrites of the same change remain editable. A matching After uses the shared live buffer. Switching away restores the original read-only After snapshot; switching back reuses the live buffer's unsaved edits and undo history. A failed checkout check revokes pinned After editing until a successful check restores eligibility.
|
||||
|
||||
Refresh retains the selected path when still present, explorer query/view/visibility, logical text-side focus, and split/unified/orientation/wrap choices; moving a Working or bookmark endpoint clears review marks, while pinned checkout-only transitions retain them. Removed selections fall back to the first changed file. Bookmark replacements preserve/clamp cursor and scroll positions as replacement content loads. Failed refreshes keep the previous comparison visible. Superseded file loads and LSP navigation cannot apply to the new comparison; snapshots still displayed in other panes or tabs remain read-only.
|
||||
|
||||
The changed-file explorer is **docked on the right**. In the default split layout, modified files show Before on the left and After on the right. Added files show only After, using the full text workspace; deleted files show only Before. Rename-only files show one empty pane, with the old and new paths in the explorer; renames with text or final-newline changes retain both source sides. Before and unmatched pinned After snapshots are read-only. A **Follow checkout / Checkout snapshot After** or a checkout-matched pinned After binds eligible regular UTF-8 files to normal editor buffers, reusing already-open dirty buffers and their undo history. Editable After supports native edits, completion, undo/redo, and `:w`. Removed files, rename-only files, binary files, symlinks, and submodules remain read-only. Closing the diff keeps its buffers and unsaved edits.
|
||||
|
||||
Comparisons start in **split, vertical (left/right)** view by default. In Normal mode, **Space v** cycles split/unified; **Space s** switches a split between vertical (left/right) and horizontal (above/below, Before above After). Canonical commands are `:diff.view.toggle` and `:diff.orientation.toggle`; both are available in the palette and as remappable `config.core.diff.view.toggle` / `config.core.diff.orientation.toggle` actions. Configure new-comparison defaults with `config.diff_view_mode = "split"` or `"unified"` and `config.diff_split_orientation = "vertical"` or `"horizontal"`. Current choices survive file and tab switches; closing and reopening uses the configured defaults. Orientation stays unchanged while unified is active.
|
||||
|
||||
**Unified** uses one full-width text pane with both original line-number columns: context appears once, then each changed run shows removed (`-`) lines followed by added (`+`) lines, without alignment holes. Tab/Shift+Tab still switches logical Before/After focus, preserving native source coordinates, read-only protection, and writable After editing. The border shows the combined revisions and the focused side's editability. Word wrap, syntax/semantic and character highlighting, search, selections, excerpt expansion, and wheel scrolling work in either view.
|
||||
|
||||
Diff metadata lives in the text-pane borders instead of a separate info row: split panes show their own Before/After revision labels at the bottom-left; a single visible pane shows the combined `before → after` label there. Each pane shows its read-only/editable state at the top-right, independently of keyboard focus. Before is always read-only; After is editable only for an eligible Working-checkout or checkout-matched pinned file. The changed-file explorer and panes start directly below configured chrome, and there is no native-buffer help footer. Loading/error/file notices remain visible when applicable. Narrow borders prioritize state and clip titles without painting over the gutter or source text.
|
||||
|
||||
Default diff tab titles show `Diff · filename +N -M`, with added and removed line counts for the selected file. Replaced lines count on both sides; unchanged context does not count. Counts update with live edits and undo/redo, including when the diff tab is inactive. Revision selectors and files still loading omit per-file counts until their text diff is ready. Custom chrome templates use `{view}{name}{changes}` for this layout.
|
||||
|
||||
The default top-right `:diff` segment shows `Diff +N -M` across the entire active comparison, including unopened and filtered-out files. Unopened files use native Git text statistics from frozen snapshot blobs; loaded files use their displayed hunks, including live edits. Binary and mode-only changes contribute no text lines. Git's binary detection and diff algorithm can differ from the renderer for non-UTF-8 content, late NUL bytes, or difficult comparisons, so opening such a file can adjust totals. Oversized blobs, unmaterialized jj conflict projections, or failed statistics collection leave totals as `Diff …` until all counts are known; partial sums are never shown as complete totals.
|
||||
|
||||
For jj-managed repositories, revision entries and border labels display only the change ID; Git repositories keep commit-ID labels, and named bookmarks retain their names. The backing commit ID remains the exact comparison target and can still be used to filter revisions.
|
||||
|
||||
Text panes use normal buffer interaction regardless of writability: motions and counts, search, Visual/Visual Line selections, multiple carets, yank, remapped bindings, and non-mutating actions work in Before and After. Read-only snapshots reject insert/delete/change/paste, repeat edits, undo/redo, mutating plugin effects, and saves, including saves to another path. Their text retains the revision's final newline. Snapshots use separate virtual LSP document identities and do not appear in ordinary buffer lists or dirty-buffer comparisons. Closing the diff disposes unreferenced snapshots and restores the live or original buffer in its workspace pane; snapshots displayed by other panes or tabs remain read-only until closed. Explicit buffer commands and Markdown/plugin navigation retain their ordinary behavior; native LSP definitions use the routing below.
|
||||
|
||||
**LSP definition, hover, and diagnostics work normally in focused Before and After text panes**, including historical snapshots. Each snapshot is served with its immutable revision text and its own document URI, not the current disk contents. Completion and completion edits are available only in writable After; they use the shared buffer's normal undo history. Revision selectors and the changed-file explorer are not document-action targets.
|
||||
|
||||
Accepted LSP definitions center the selection's caret row once in the destination pane, including wrapped visual rows and revealed diff excerpts. Centering uses the focused pane's actual height in either split orientation or unified view. Subsequent motions resume the configured `scroll_distance` policy; failed or superseded definitions preserve the current logical viewport.
|
||||
|
||||
A definition whose source range **overlaps an actual added, removed, or replaced line** stays in the same comparison and selects the correct file and side, loading file details on demand. For a location link, the symbol's full target range determines overlap and its selection range determines the caret: an unchanged declaration with a changed body still belongs in the comparison. Source coordinates belong to that side, including old paths for renames; navigation reveals the exact selection row, even when previously omitted, never the nearest excerpt. A wholly unchanged target opens a **new ordinary tab**, even when it is visible context or omitted text in a changed file. Files outside the comparison's changes also open in a new tab. The original comparison, pane layout, source caret, excerpts, and dirty buffers remain intact. Loaded targets share their existing text and undo history rather than reloading disk; references to snapshot URIs retain the historical text and read-only identity in the new tab, even after the comparison closes. Unreadable files, invalid UTF-8, invalid source ranges, and unsupported remote URIs do not create a tab or disturb the source.
|
||||
|
||||
Use the ordinary **file-picker/file-explorer actions and bindings**: Space `o` opens a floating picker, Space `e` opens/focuses the docked explorer, and Ctrl+w closes the focused picker/explorer and reclaims its width. Remapped bindings work too; Ctrl+e is no longer reserved by the diff. The changed-path catalog retains A/M/D/R markers and the normal compact tree, filtering, folder expansion, and configurable `tree`/`selection` navigation. It includes removed and historical paths without scanning the working directory. Enter toggles a folder or opens the selected comparison file and focuses After when that pane exists; deleted files and other Before-only views focus Before. While the explorer is hidden, Tab/Shift+Tab cycles between visible text panes only; a single-pane view keeps its focus.
|
||||
|
||||
File rows show colored **A** (added, green), **M** (modified, yellow), **D** (removed, red), or **R** (renamed, cyan) markers in Tree and List views, including filtered results. Rename rows show `R old/path -> new/path`; directories have no file-status marker.
|
||||
|
||||
Mark or unmark a diff file with **`c` while browsing the changed-file tree**, **`:diff.review.toggle`**, or the command-palette action. With the changed-file explorer focused, it toggles the highlighted file without opening it; from a text pane, the command toggles the displayed file. Reviewed files show a green **`✓` immediately left of A/M/D/R, separated by one blank column**, in Tree and List views. The modification indicator keeps its existing indentation; the review marker uses the preceding gutter space instead of adding padding. Diff rows use the selection background and cursor rather than a `>` prefix. Directory review marks cannot be toggled directly, and ordinary filesystem pickers have no review marks. While filtering, including List view, `c` remains query text; use the palette or a control-key binding there. Explicit bindings take precedence over the default browsing shortcut.
|
||||
|
||||
Collapsed folders show a green **`✓`** when every changed file beneath them is reviewed, including nested files and descendants hidden by filtering. Expanded folders stay unmarked. Folder marks update automatically when a descendant's review mark or the changed-file catalog changes.
|
||||
|
||||
Review marks are saved with the selected local review and restored by immutable per-file Before/After identities and file paths. Changes to unrelated files or commit metadata do not clear them; changes to either side's bytes, final newline, file mode, or rename paths require re-review. They survive filtering, file navigation, lazy loading, tabs, split/unified/orientation changes, and pinned checkout-only transitions. Editing a writable After file clears only that file's mark and saves the removal; unchanged refreshes and saves preserve it. Marks on live text also retain its exact contents, including the final newline, so different unsaved text cannot inherit a checkmark. Marks do not change document text, undo history, or repository state. Without configured SQLite storage, use `:review.save path` to save them as JSON. Older revision-pair-scoped marks remain stored but must be marked again to acquire per-file identities; comments, summaries, and verdicts are unaffected.
|
||||
|
||||
**Local review comments** work in ordinary repository source buffers and diff text panes; they share storage with file-reviewed checkmarks and never publish to GitHub. Run **`:comment`** to comment on the current line. A characterwise Visual selection (`v`) anchors its exact text, including partial lines and multiline spans; Visual Line (`V`) anchors whole selected lines. Multiple independent carets/ranges must be reviewed separately.
|
||||
|
||||
Comments, summaries, and the review overview open in a focused floating editor over the source workspace, not a source-side split. The source layout, file explorer, and viewports stay unchanged. Normal editing, selections, and undo/redo work in editable review buffers. Escape in Normal mode or `:pane.close` dismisses the window and returns to the source, discarding that editor's unsaved text. An unsaved new comment is not attached to the review; an existing comment or summary reopens with its last saved text and no discarded undo history. Insert/Visual/Command Escape first retains its usual modal behavior. Source rows are never replaced with comment text. Magenta **`○`** gutter markers identify saved comment ranges; **`●`** identifies the selected comment. Its exact current text range has a magenta background, including wrapped continuations and selected newline cells; native Visual selections take precedence. Stale comments have neither markers nor text highlighting. Markers preserve addition/deletion signs, appear only on the first wrapped segment, and also work in unified view.
|
||||
|
||||
Local review buffers (comments, summaries, overview, and stored-review selector) soft-wrap by default without inserting newlines into saved text. Use `:word_wrap.toggle` to disable wrapping for the focused review buffer; reopening it retains that choice for the session. Source diff wrapping remains independent.
|
||||
|
||||
| Command | Effect |
|
||||
| --- | --- |
|
||||
| `:comment` | Add a comment on the current source line or exact selected text range |
|
||||
| `:review.edit [id]` | Edit an existing comment; defaults to the overview entry under the caret or selected comment |
|
||||
| `:review.delete [id]` | Delete that draft comment |
|
||||
| `:review.resolve [id]` / `:review.unresolve [id]` | Mark a comment resolved/unresolved; uses the same default selection as edit/delete |
|
||||
| `:review.next` / `:review.previous` | Cycle comments, opening their text and revealing a matching source anchor |
|
||||
| `:review.overview` | Refresh/open a read-only summary and comment list; Enter edits the entry under the caret |
|
||||
| `:review.copy` | Copy all saved comments in the selected review to the configured clipboard, using the CLI text format |
|
||||
| `:review.summary` | Compose the review summary |
|
||||
| `:review.verdict looks_good` | Record **Looks good** |
|
||||
| `:review.verdict changes_requested` | Record **Changes requested**; `none` clears the verdict |
|
||||
| `:review.save [path]` | Commit to SQLite; with a path, also export JSON for sharing |
|
||||
| `:review.open [id or path]` | Show reviews for the current scope, open a matching stored review ID, or import matching JSON as a new review |
|
||||
| `:review.new` | Create another stored review for the current comparison or ordinary-source scope |
|
||||
|
||||
File checkmarks remain diff-specific (`:diff.review.toggle`).
|
||||
|
||||
Comment and summary text is committed only by **`:w`** or **`:review.save`**, which saves the entire review, including hidden drafts. Dismissing an editor discards its unsaved text; switching between review editors can retain hidden drafts but does not save them. File checkmarks, verdicts, deletions, and manual resolution changes commit immediately to local SQLite without committing draft text. `:review.save path` or `:w path` additionally exports JSON; later metadata autosaves still go to SQLite and leave that export unchanged. Imports create a new stored review identity rather than overwriting another review.
|
||||
|
||||
`:review.copy` copies the same text as `vamp --review show ID --all`: repository, summary, verdict, counts, and every saved comment with its anchor and exact excerpt. Resolved and stale comments are included, across all files in the selected review. `clipboard_mode` chooses the system clipboard or Separate-mode internal register. Copying does not save or include unsaved comment/summary drafts. No comments or a clipboard write failure reports an error without replacing the register.
|
||||
|
||||
CLI text output and `:review.copy` wrap each source excerpt in a Markdown code block, with its detected language tag (`hon` for `.hon`, `rust` for `.rs`, and so on). Detection uses the frozen source path and first-line shebang, not current disk contents; unknown languages use an untagged block. Fences grow beyond any backtick run in the excerpt, so nested Markdown cannot end the block early. Feedback follows outside the code block. Exact excerpt text, including existing final newlines, is preserved; a missing final newline gains only the separator required before the closing fence. JSON excerpts and stored anchors remain raw and unchanged.
|
||||
|
||||
From the shell, use `vamp --review delete REVIEW_ID COMMENT_ID [--repo PATH] [--json]` to delete a stored comment immediately without opening the editor. Find IDs with `vamp --review list` and `vamp --review show REVIEW_ID --all`. The repository defaults to the current checkout. Both resolved and unresolved comments can be deleted; the review and any JSON exports remain intact. An editor holding the old review revision must reload before saving.
|
||||
|
||||
Use `vamp --review resolve REVIEW_ID COMMENT_ID [--repo PATH] [--json]` after addressing and verifying feedback to mark it resolved without changing its body or original anchor. The command prints the updated review's remaining unresolved comments and full counts; `show REVIEW_ID --all` still includes the resolved original. Repeating resolution succeeds without a write or revision bump. Both IDs must be positive and refer to the selected repository; invalid targets and absent storage fail without creating or changing stored data. Like deletion, resolution rejects stale saves from an editor holding the previous review revision.
|
||||
|
||||
Storage defaults to `$XDG_DATA_HOME/vamp/reviews/reviews.sqlite3`, or `~/.local/share/vamp/reviews/reviews.sqlite3` when XDG_DATA_HOME is unset or relative. Configure `review_directory` to override its directory; relative configuration paths resolve against the config file. Review scope is the canonical checkout root plus the ordered, resolved Before/After identities, not branch/bookmark labels. Opening a different pair selects its existing review or starts an empty one; reopening the same pair restores its feedback, verdict, and file progress. A sole matching review restores automatically; multiple reviews for that scope open a floating selector. Move to an entry and press Enter, or use `:review.open id`. `:review.new` creates another review within the same scope. Opening or importing a review from a different scope is rejected rather than reassigning its feedback.
|
||||
|
||||
Working edits and in-place checkout refreshes retain the comparison's initial review scope. Explicitly opening a comparison resolves its endpoints again: changed Working contents or moved bookmarks can therefore select a different review. Ordinary source-buffer comments use a separate repository-local source scope, never the last comparison's review. Unsaved review drafts block scope changes until saved or discarded. Opening an empty scope does not write storage until a review change is committed.
|
||||
|
||||
Write errors, locked databases, incompatible schemas, and conflicting edits from another editor instance retain dirty drafts and report the failure. Failed text saves leave the committed review unchanged; unrelated metadata autosaves cannot commit those drafts. Normal destructive closes remain guarded until drafts are explicitly saved or discarded. `:w!` does not bypass database revision conflicts; export your draft before reopening the current stored review. JSON exports retain external-file-change protection. Only the current database schema is accepted; existing incompatible databases are preserved rather than reset or migrated.
|
||||
|
||||
The current SQLite format is schema 4: typed `reviews`, `comments`, and `reviewed_files` tables, not serialized JSON documents. Review rows store nullable Before/After identities; both are null for source reviews. Older databases, including schema 3, are incompatible and are left untouched; there is no migration or automatic reset. JSON version 5 is the sharing format, independent of the database schema.
|
||||
|
||||
Version 5 JSON is the agent-readable sharing format: repository root, `comparison` (an ordered Before/After identity pair, or `null` for source reviews), summary, optional verdict, comments, and a required `reviewed_files` array. Each reviewed file stores its immutable per-file `revisions` pair (`file:` identities encoding mode, Git object ID or exact data, and notices), relative `path`, optional rename `old_path`, and optional exact live `after` text. Comments have stable IDs, bodies, required boolean `resolved` states, and anchors. New comments are unresolved. Database review IDs and optimistic storage revisions stay internal. Each anchor retains its immutable comparison revision, side, relative path (old path for renamed Before files), and exact whole-file text including the final newline. `start` and `end` contain zero-based source `row` and extended-grapheme `column` coordinates; `end` is exclusive. Columns count complete Unicode graphemes, not bytes, code points, UTF-16 units, or screen cells. Overview/window labels display one-based rows and columns. Older JSON formats are rejected and preserved without migration. Working comparisons use content-addressed snapshot IDs; captured text additionally freezes live unsaved edits. Stored reviews have a 64 MiB aggregate text budget including 64 bytes of overhead per comment and reviewed file; imported/exported JSON files have a separate 64 MiB serialized-size limit.
|
||||
|
||||
Reopening requires the same repository root. Unchanged comment ranges follow edits elsewhere in the file, including inserted/deleted lines above and column shifts before a partial-line selection. Working-snapshot refreshes can retain these attachments; unrelated immutable revisions and paths do not match. Mapping requires an unchanged, unambiguous text region containing the selection. Modified/deleted selections or ambiguous repeated regions are **stale**: comments remain available through the overview and next/previous navigation, with original snapshot coordinates and no current-source marker or jump. Saved anchors and exported excerpts remain unchanged. Unloaded files are shown as **not checked** until visited; refresh the overview to update its statuses. There is no server, authentication, or review-publishing operation.
|
||||
|
||||
Ordinary source comments use an immutable content snapshot identity and capture the current buffer, including unsaved text; they do not require a commit or a diff. They retain the same SQLite/JSON formats. Opening a source comment navigates to its file and mapped selection; if that text is stale or the file is unavailable, it opens the preserved original text read-only instead of attaching feedback to different code.
|
||||
|
||||
Resolution is an explicit reviewer or agent decision, independent of anchor freshness: a comment can be both resolved and stale. Overview entries and comment titles label resolved/unresolved status. Resolved comments remain in the overview and next/previous navigation, and can still be edited or reopened. Resolving never changes an anchor or deletes feedback.
|
||||
|
||||
|
||||
Text panes show change excerpts with **10 unchanged lines above and below** each change, preserving original file line numbers. Overlapping or touching excerpts merge; omitted stretches show an unchanged-line count in both panes. Files with only metadata changes show their notice or “No text changes” rather than unrelated source.
|
||||
|
||||
**Scope labels** identify named enclosing functions/classes and containers, such as `impl Review › run`. Muted, unnumbered rows supply context when the declaration is vertically outside that pane's viewport; scrolling it back into view removes the label and reclaims its row. If an unwrapped declaration remains vertically visible but its symbol is clipped horizontally, its label instead overlays the preceding content row. On the first visible row, that label is hidden so the pane border stays intact. Horizontal scrolling never inserts a row or shifts source text; scrolling the symbol back into view restores the covered row. Decorators alone do not count as the declaration name. Visibility follows source columns and wrapped segments independently for each side. Each split side uses its own source, so renamed functions keep distinct old/new names. Unified labels use `−` for Before, `+` for After, and `±` for shared names. Narrow panes prefer the innermost name. Labels are presentation only: motions, selections, copying, editing, and line jumps retain original source coordinates. Context comes from the existing Tree-sitter trees, including supported injected code, without requiring an LSP; unsupported syntax gets no guessed label.
|
||||
When the reserved sticky row can show the immediately preceding declaration with its name visible, it renders that declaration as ordinary numbered source instead. Scrolling farther into the body replaces it with the unnumbered label; scrolling back restores the declaration.
|
||||
Overlays never cover a visible declaration name on the preceding row, including a different Before/After declaration in unified view; the label is hidden instead.
|
||||
Within an excerpt, additional hunks and alignment gaps do not repeat an unchanged scope label. A new excerpt or an actual scope change gets a fresh label when needed; sticky context is retained independently for each side.
|
||||
|
||||
In **Normal mode** with a text pane focused, **`[` expands above** and **`]` expands below** the excerpt containing the caret, revealing up to **15 lines** per keypress in either pane. In editable After's Insert mode these keys insert literal text. Expansion clamps at file boundaries and merges excerpts when they meet. Existing visible source stays anchored. Opening a file resets its excerpts to the configured initial context. Live edits recompute changes while retaining expanded context; the caret stays visible even when the last text change is reverted.
|
||||
|
||||
Live typing highlights only the displayed source rows while retaining each snapshot's original syntax tree for multiline and injected-language context. Line-width caches and unchanged hunk layouts avoid repeated full-file work; edits that change line alignment or revert changes recompute the diff. Already-queued printable Insert keys share a redraw, but every key still passes through normal bindings, snippet handling, and undo history. Mode changes and other terminal events retain their order.
|
||||
|
||||
Text-pane navigation stays within the shown source lines. At an excerpt boundary, Up/Down or `j`/`k` jumps directly to the next/previous excerpt, and counts count visible lines rather than omitted lines. This also applies to remapped movement keys, Visual-mode movement, and editable After's Insert-mode arrows. Word motions, `gt`/`gb`, search, and occurrence selection use the visible excerpts; `gt`/`gb` target their first/last source line. Hidden short lines do not clamp the caret column. The shared vertical viewport and each pane's horizontal offset stay fixed when movement reverses, scrolling only when the caret crosses a visible edge, as in a normal buffer. Ordinary motions, search, and caret restoration do not reveal omitted context; Normal-mode `[`/`]` expands existing excerpts. LSP definition routing can additionally reveal the exact selection of a symbol whose range overlaps changes. Edits still recompute changed regions and retain previously expanded context.
|
||||
|
||||
Configure these counts in Ruby with `config.diff_context_lines = 10` (nonnegative; `0` shows changes only) and `config.diff_expand_lines = 15` (positive).
|
||||
|
||||
Diff views inherit the originating buffer's word-wrap setting. `word_wrap.toggle` switches both panes together, including read-only snapshots, without changing ordinary-buffer settings. Each aligned source row uses the taller side's wrapped height; shorter-side continuation padding stays blank so subsequent source lines remain aligned. Excerpts and explicit expansion still use source-line counts.
|
||||
|
||||
In split diffs, changed text rows use muted red backgrounds in Before and muted green backgrounds in After, including blank tails and real empty lines. Entirely added or deleted files retain the normal background; colored line numbers and `+`/`-` gutter markers indicate their changes. Foreground colors use the editor's bundled Tree-sitter syntax highlighting, parsed independently for each snapshot and its path (including the old path for renames). Native text panes also display their buffer's selections, search matches, semantic highlighting, and diagnostics. Unknown languages retain the normal foreground; historical snapshots do not borrow live-buffer LSP tokens.
|
||||
|
||||
The row tint also covers the line-number gutter on wrapped continuations and blank wrap-padding rows on the shorter side of an aligned pair. Empty source lines keep the same full-row tint; missing source counterparts retain their normal-background hatching.
|
||||
|
||||
Character-wise highlighting is enabled automatically within paired changed lines, with a stronger red/green background over changed grapheme spans. To reduce fragmented highlighting, changes separated by at most two unchanged graphemes are merged; short unchanged islands between large edits are also absorbed using VS Code-style size heuristics. Larger common regions retain the muted row tint. Combining sequences, wide characters, and expanded tabs keep their source geometry through horizontal scrolling and word wrap. Syntax/semantic foregrounds remain intact, and cursor/search/selection styles keep their normal precedence. Character ranges are cached with aligned rows; stable live edits refresh only the edited paired lines rather than computing character diffs during painting.
|
||||
|
||||
Diff backgrounds blend the terminal's default background with its red/green palette colors: an 18% accent for changed rows and a stronger 38% accent for changed characters, both computed from the original background. Read-only OSC 11/4 queries run after the initial paint, on focus regain, and whenever a subscribed DEC 2031 color-scheme notification arrives. While a diff is visible in any pane, a nonblocking one-second palette probe also catches external theme changes without a notification, including changes between two themes with the same light/dark preference. Ordinary editor views do not poll; cached colors apply across editor panes. If the complete palette is unavailable within 250 ms, change backgrounds remain normal and gutter colors/markers still identify changes.
|
||||
|
||||
Missing counterparts use adjacent muted `╱` diagonals (U+2571, box drawings light diagonal) on the normal terminal background, one per column, with the same terminal `DarkGray` foreground as ordinary gutter text. Unlike the text slash `/`, this glyph is designed to reach cell corners so diagonals can join end to end across successive rows. Pixel-perfect joins depend on the terminal's font and line-spacing rendering. Actual empty source lines retain their normal/change background and are not hatched.
|
||||
|
||||
In Normal mode, Tab/Shift+Tab cycles focus between Files and the visible text panes, skipping absent panes. Switching Before/After synchronizes the primary cursor by aligned diff row and display column. A missing counterpart uses the nearest visible source row; shorter lines clamp the column while retaining the preferred display column for the return trip. Vertical wheel input scrolls the visible panes without moving the focused text caret; switching sides by vertical wheel also synchronizes the cursor. Over Files it navigates visible tree rows without opening them. Horizontal wheel input in either split synchronizes the Before/After horizontal offsets, bounded by the longer side, without changing focus, cursor, or selections; over Files it is consumed. Added/deleted files retain single-pane scrolling. While a comparison is open, Escape cancels modes, prompts, or filtering, or returns picker focus to the last bound text pane; it leaves the comparison open. Use **`:diff.close`**, find `diff.close` in the palette, or bind **`config.core.diff.close`** to leave the comparison explicitly. The dotted command is intentional; there is no `:diffclose` alias.
|
||||
|
||||
Both diff panes apply available semantic tokens from their own buffer, independently of keyboard focus. Historical snapshots never borrow the working buffer's tokens. Typing and undo/redo retain semantic colors outside the edited range, shifting their positions to follow the text until a current LSP reply replaces them. Edited ranges fall back to Tree-sitter syntax colors while waiting; semantic roles elsewhere can briefly lag changes. Semantic colors and modifiers preserve the change backgrounds.
|
||||
|
||||
Binary data, missing final newlines, permission/type changes, symlink targets, and submodule pointers have explicit notices. Symlinks are not followed and submodule contents are not traversed. jj conflicts use jj's file-content projection and carry conflict notices; ordinary files remain readable. Identical-content moves are shown as renames; modified moves appear as an added and removed file.
|
||||
|
||||
Large comparisons load each selected side independently, up to 64 MiB and 4,000,000 source lines per side. Frozen Working snapshots have a 512 MiB aggregate budget. Exceeding a limit displays the actual error in the document pane. Large files use the normal plain-text syntax fallback; pathological comparisons may show broader replacement regions or whole-line highlights rather than block input searching for a minimal diff. Full source text remains available.
|
||||
|
||||
## Jujutsu conflict resolution
|
||||
|
||||
Run **`:resolve`** in Normal mode for the current jj working copy. It opens a dedicated tab and selects the current conflicted file (otherwise the first conflict). Historical comparisons remain read-only; resolving never implicitly checks out or creates another change.
|
||||
|
||||
The resolver shows the editable **Resolution** on the left and a read-only **Other version** on the right, with aligned rows, line/character highlighting, context folds and synchronized scrolling. Both are projected from the current working buffer, including pre-existing unsaved edits: only conflict-marker regions are replaced by their selected alternatives. Already-merged text and edits outside those regions appear on both sides. The initial output is seeded from the first side as a normal undoable buffer change; opening never writes it to disk. References remain frozen while later edits change only the output.
|
||||
|
||||
Both panes show their own changes **against the selected base**, not a left-to-right removal/addition comparison: removed base lines are red with `-`, and added candidate lines are green with `+`, on either side. Replacements show the removed base text followed by the candidate text; unchanged text stays neutral. Removed base lines are display-only, with no candidate line number, caret, or editable selection. With no base (an add/add conflict), both candidates are additions against empty text. The Resolution baseline uses the same frozen working-text projection as its alternatives, preserving already-merged text and pre-existing outside edits. `resolve.base` selects the baseline through History; returning to Resolution uses that selection. Hunk navigation and `resolve.use_source` still operate on differences between the actual Draft and Alternative.
|
||||
|
||||
Pane borders label the editable output **Resolution** and its frozen reference **Other version**. Paths and branch-comparison metadata are omitted from these titles; unsaved state belongs only to the output, and source identity appears with the reference. Explorer **C** marks files jj still considers conflicted, including while edited/checking or confirmation is unavailable; it clears only when jj confirms resolution.
|
||||
|
||||
| Command | Behavior |
|
||||
| --- | --- |
|
||||
| `resolve.next` / `resolve.previous` | Jump between differing decision hunks |
|
||||
| `resolve.source [N]` | Select/focus an Alternative; in History, select an outer input; without N, cycle |
|
||||
| `resolve.base [N]` | Open History and select a numbered base; default first base |
|
||||
| `resolve.use_source [N]` | Take the current differing hunk from that Alternative as one undoable edit |
|
||||
| `resolve.next_file` / `resolve.previous_file` | Open another retained file |
|
||||
| `resolve.files` / `resolve.draft` | Toggle/focus the file explorer / return to the editable Draft |
|
||||
| `resolve.history` / `resolve.view.toggle` | Show read-only input/base/input History / switch views |
|
||||
| `resolve.close` | Close the resolver without discarding dirty drafts |
|
||||
|
||||
**History** is separate from editing: it compares the original inputs and their base, with all sides and bases selectable for multi-sided conflicts. `config.resolve_history_layout = "columns"` (default) shows left/base/right; `"base_below"` shows left/right above a full-width base. Both layouts retain aligned changes and synchronized vertical scrolling. Tab/Shift+Tab cycles in layout order; directional pane actions follow the displayed geometry. Narrow History shows the focused source, as does base-below History when too short to display both rows of panes. Draft text, undo, caret and viewport survive view switches. Resolution uses the ordinary diff workspace, including its configured explorer, split/unified/orientation controls, source-line navigation, excerpts, focus and scrolling. Read-only Alternatives and History reject edits and saves.
|
||||
|
||||
Each outer History pane uses the same red-removal/green-addition presentation against the selected base. The base pane highlights original text changed by either input; addition-only rows leave a gap there. This applies to both History layouts.
|
||||
|
||||
Input indexes are one-based and include bases. Conflict-specific actions appear in the palette and through corresponding `config.core.resolve` methods. File navigation uses the existing picker/explorer actions: Space o opens floating search, Space e focuses the dock, Ctrl+t switches Tree/List, Ctrl+w closes it, and configured tree/selection bindings apply unchanged. Enter selects a relevant conflict file and focuses the editable Draft. Normal-mode Tab/Shift+Tab, native motions/search, context expansion and layout actions follow normal diff behavior. The complete seeded Draft can be saved even when intentional differences remain against the Alternative: those differences are not unresolved conflict markers. There is no automatic “accept both”.
|
||||
|
||||
**`:w` saves and checks jj**, asynchronously. Before writing, the resolver locks the working copy and validates the frozen checkout and exact on-disk file state. Checkout changes, external writes and unsafe filesystem ancestors refuse the write, including force-save. Successful writes trigger jj's normal snapshot operation, which may capture other on-disk changes. The list distinguishes unresolved, unsaved, checking, resolved and unconfirmed states. jj—not marker scanning or a manual checkbox—confirms resolution. A failed confirmation keeps saved contents and reports unconfirmed status. Resolved files remain in the session for review. Dirty drafts prevent destructive resolver/pane/tab closes.
|
||||
|
||||
Binary, symlink, deletion, executable-bit and file/directory conflicts use explicit whole-file input choices: choose an input with `resolve.use_source`, then save to apply its exact bytes and type. Symlinks are never followed. Directory replacement refuses unrelated/untracked or modified child data. Git submodule choices and legacy jj conflict storage without `jj:trees` metadata report unsupported errors instead of fabricating a resolution.
|
||||
|
||||
Opening, navigating and choosing draft resolutions do not snapshot jj; only saving does. If another jj operation changes the frozen checkout, retain your draft, close after preserving it, and reopen the resolver against the new state.
|
||||
|
||||
## Command palette
|
||||
|
||||
Ctrl+p opens a searchable overlay without leaving the current mode. It lists core actions and registered Ex/plugin commands with their owner, effective bindings in the current mode, and eligible modes. Disabled or overridden bindings are not advertised; actions with no key remain available through the palette. Mode-ineligible entries are dimmed and cannot execute. Retired plugin commands disappear.
|
||||
Ctrl+p opens a searchable overlay without leaving the current mode. It lists each core action once, plus registered plugin commands, with their owner, effective bindings in the current mode, and eligible modes. Disabled or overridden bindings are not advertised; actions with no key remain available through the palette. Mode-ineligible entries are dimmed and cannot execute. Retired plugin commands disappear.
|
||||
|
||||
Search is case-insensitive: every whitespace-separated query token must occur in the command name, human-readable label, or owner. Results have a stable label/name order. Ctrl+j/Down/Ctrl+n select the next result; Ctrl+k/Up select the previous, with wraparound. Backspace removes a whole grapheme. Enter with no match or an ineligible selection leaves the palette open. Bracketed paste is ignored while the palette is open.
|
||||
Search is case-insensitive: every whitespace-separated query token must occur in the action/command name, canonical Ex name, a shorthand alias, human-readable label, or owner. Aliases find the same action rather than creating duplicate entries. Results have a stable label/name order. Ctrl+j/Down/Ctrl+n select the next result; Ctrl+k/Up select the previous, with wraparound. Backspace removes a whole grapheme; Ctrl+u clears the query without editing the underlying buffer. Enter with no match or an ineligible selection leaves the palette open. Bracketed paste is ignored while the palette is open.
|
||||
|
||||
Accepting a core action executes it in the underlying mode, including Visual edits and Insert-mode actions. Accepting an Ex/plugin command is available only in Normal mode and opens a prefilled `:` prompt; add arguments if needed, then Enter executes through the usual session dispatch. Choosing `q!` therefore does not immediately discard changes.
|
||||
Accepting a core action executes it in the underlying mode, including Visual edits and Insert-mode actions. `core.edit` and `core.buffer` instead open prefilled Ex prompts for their required arguments. The destructive `core.force_quit`, `core.buffer_force_delete`, `core.pane.force_close`, `core.force_save`, and `core.force_save_and_quit` actions also open canonical Ex prompts, requiring another Enter before discarding or overwriting changes. Accepting a plugin command is available only in Normal mode and opens a prefilled `:` prompt; add arguments if needed, then Enter executes through the usual session dispatch.
|
||||
|
||||
Esc or Ctrl+p cancels without changing text, selections, the previous command/search prompt, or pending Insert history. The opening key can be remapped with `config.core.palette`; list navigation uses the shared configurable `selection` context. Other popup controls keep their defaults unless explicitly intercepted by a selection binding. The TUI uses a constraint-based modal panel, keeps the selected result visible, and prioritizes the query on tiny terminals.
|
||||
|
||||
## Leader sequences
|
||||
## Key sequences
|
||||
|
||||
Space begins a leader sequence in Normal/Visual by default. Press the suffix keys in order; nested prefixes wait without a timeout. The status bar shows the pending sequence. Esc cancels the sequence and pending count without leaving Visual or collapsing carets. See [leader configuration](configuration.md#leader-key) for remapping and declaration rules.
|
||||
Space begins a leader sequence in Normal/Visual by default. Explicit sequences such as `ctrl+w j` can coexist without changing that leader. Press the keys in order; nested prefixes wait without a timeout. The status bar shows the pending keys before the file path, without a prefix label. Esc cancels the sequence and pending count without leaving Visual or collapsing carets. See [sequence configuration](configuration.md#key-sequences-and-leader) for remapping and declaration rules.
|
||||
|
||||
## Jump history
|
||||
|
||||
Normal Ctrl+o moves back through previous locations; Ctrl+i moves forward, including in comparisons. Normal Tab also jumps forward outside comparisons, but cycles panes within comparisons; Shift+Tab cycles backward. The Unix TUI requests disambiguated keyboard events so supporting terminals preserve this distinction. Legacy terminals encode Ctrl+i as Tab and cannot distinguish them; there, use the **Jump forward** palette action or another configured key such as `config.bind "ctrl+y", config.core.jump_forward`. Counts work in either direction, such as `3` followed by Ctrl+o, and stop at the available history.
|
||||
|
||||
The session keeps up to 100 primary-caret locations with their tab, pane, and comparison context, not just buffer coordinates. Successful Markdown links, accepted LSP definitions, file-picker opens, `:edit`, `:buffer`, `:bnext`/`:bprev`, and search `/`/`n`/`N` jumps record locations. Back/forward restores the original view, including its comparison file and side; an external LSP definition round-trip does not replace the comparison with an ordinary buffer. Identical buffer/cursor positions in different views remain distinct. Ordinary cursor/word motion, edits, failed navigation, manual tab/pane selection, and jumps that do not change location do not add entries. Traversal itself does not record another jump.
|
||||
|
||||
Moving away from a visited point before traversing saves the actual departure position for the return trip. A successful new jump after going back discards the forward branch; failed/no-op jumps preserve it. Closed buffers are skipped rather than reopened. An unavailable or replaced comparison is never resurrected or overwritten: history uses a safe existing ordinary pane for an available buffer, retaining snapshot read-only identity, or skips the destination if none exists. It never creates a replacement tab. Stored row/grapheme coordinates clamp to current text after edits; text, dirty state, undo/redo, and file contents remain unchanged. History navigation returns to Normal with one primary caret.
|
||||
|
||||
The typed actions are `config.core.jump_back` and `config.core.jump_forward`; custom bindings can use any supported single key or leader sequence. History is in memory for this session only.
|
||||
|
||||
## Markdown links
|
||||
|
||||
Normal `gf` or `:follow_link` follows the link under the primary caret, without an LSP. Inline links and full/collapsed/shortcut reference links are supported; reference definitions can appear elsewhere in the document. The label or destination can be under the caret. Images, code blocks, and ordinary text are not file links.
|
||||
|
||||
Local paths resolve relative to the source file, not the working directory; percent-encoded UTF-8 paths and Markdown-escaped punctuation are decoded. Targets can be any supported text file. Existing buffers are reused, including unsaved text and files removed from disk. Missing files, undefined references, invalid destinations, or missing headings report an error without switching buffers or moving carets.
|
||||
|
||||
`[Section](#section)` stays in the current document; `[Section](other.md#section)` opens the target and moves to its heading. ATX and Setext headings use GitHub-style slugs derived from visible inline text: lowercase, punctuation removed, whitespace replaced by hyphens, and duplicate suffixes `-1`, `-2`, etc. Heading lookup uses unsaved target text. Relative file links require a named source; same-document fragments also work in unnamed buffers.
|
||||
|
||||
External URL schemes/network paths are rejected; this action never launches a browser or shell. Numeric HTML entities and common named entities (`amp`, `lt`, `gt`, `quot`, `apos`, `nbsp` and their supported aliases) are decoded; other recognized named entities report an unsupported-entity error rather than guessing. Unicode slugs/reference matching use standard-library case conversion, not a complete Unicode case-fold/category table.
|
||||
|
||||
`g` waits for `f` in Normal, or `t`/`b` in Normal and Visual, shows in status, and Escape cancels. Other input cancels the prefix and follows ordinary input handling. A configured `g` binding overrides this built-in prefix in its mode; choosing `g` as leader also takes precedence. Custom bindings use the generated action:
|
||||
|
||||
```ruby
|
||||
config.bind "leader f", config.core.follow_link
|
||||
```
|
||||
|
||||
## Syntax highlighting
|
||||
|
||||
Buffers highlight automatically using [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) and compiled-in grammar/query packages. The selected language set is Rust, Ruby, Python, JSON, Bash, Makefile, Markdown, JavaScript/JSX, TypeScript/TSX, HTML, CSS, YAML, TOML, C, C++, and Go. Detection uses filename/extension or the in-memory first-line shebang, including common special filenames such as Makefile, Gemfile, and Cargo.lock; no file reread occurs. Unsupported formats use the normal foreground. The detected language appears in status, and save-as redetects it.
|
||||
Buffers highlight automatically using [Tree-sitter](https://tree-sitter.github.io/tree-sitter/) and compiled-in grammar/query packages. The selected language set is Rust, Ruby, Python, JSON, Bash, Makefile, Markdown, JavaScript/JSX, TypeScript/TSX, HTML, CSS, YAML, TOML, C, C++, Go, Zig (`.zig`), Honey (`.hon`), and Typst (`.typ`). Detection uses filename/extension or the in-memory first-line shebang, including common special filenames such as Makefile, Gemfile, and Cargo.lock; no file reread occurs. Unsupported formats use the normal foreground. The detected language appears in status, and save-as redetects it.
|
||||
|
||||
Files remain editable above the syntax budget: sources over 1 MiB, or with any line over 64 KiB, use plain text and show the reason in the language status. Syntax highlighting resumes automatically after shrinking below both limits. This avoids building a full parse tree for huge generated files; navigation, search, selections, undo/redo, and saving remain available.
|
||||
|
||||
Colors retain the terminal palette: comments dark gray, strings green, keywords magenta, numbers yellow, types/markup cyan, and functions light blue. Grammar queries handle multiline/nested constructs, even when their opening is above the viewport. Markdown uses its inline grammar and named fenced-code injections; HTML script/style content uses JavaScript/CSS. Known tagged-template and raw-string injections use the same selected grammar registry; unknown injected languages retain host highlighting or plain text. Highlighting styles whole graphemes and expanded tab cells; partially clipped wide placeholders remain unchanged. Search, Visual selections, and secondary carets retain foreground/background precedence.
|
||||
|
||||
Honey uses its bundled grammar and highlight queries, including declarations, primitive types, literals, and comments. Markdown fences accept `honey`, `honeylang`, or `hon`; the language ID is `honey`.
|
||||
|
||||
Typst highlights headings, emphasis, references, raw code, comments, strings, numbers, keywords, and function calls without an LSP. Markdown fences accept `typst` or `typ`; named raw-code blocks inside Typst use the same bundled language registry. The language ID is `typst`. Native [Tinymist configuration](configuration.md#native-lsp) is opt-in.
|
||||
|
||||
Markdown heading markers (`#` through `######`, or Setext underlines) share the heading text's markup color. List markers (`-`, `+`, `*`, and ordered prefixes such as `1.` or `1)`) also use cyan markup, including nested and blockquoted lists. Plain-text hashes and other punctuation keep their existing styling.
|
||||
|
||||
An enabled supporting LSP server supplies semantic tokens automatically, overriding syntax colors only on recognized spans. Semantic colors also use the terminal palette: namespaces neutral gray, types cyan, variables/parameters light cyan, and properties blue. Readonly variables/parameters/properties keep those role colors and add italics; declarations/definitions are bold, documentation comments italic, and deprecated symbols struck through. Italic emphasis depends on terminal support. Edits retain semantic colors outside the changed range and shift them with the text until updated tokens arrive, avoiding whole-buffer flashes. Tree-sitter fills gaps, including edited ranges whose semantic tokens were discarded. Search, Visual selections, diagnostics, and carets keep their existing precedence. See [native LSP configuration](configuration.md#native-lsp) for provider support and server-stack routing.
|
||||
|
||||
+27
-3
@@ -22,7 +22,7 @@ Callbacks receive an immutable primary-only context snapshot: `editor.text`, `ed
|
||||
|
||||
The Ruby host and examples use [YARD types](https://solargraph.org/guides/yard) for Solargraph navigation and hover. `Vamp.command` declares typed block arguments (`Vamp::Editor`, `String`); the example also annotates them explicitly. Context readers and configuration methods are annotated in [`src/ruby_config.rb`](../src/ruby_config.rb); asynchronous callback/effect contracts live in [`src/ruby_plugin.rb`](../src/ruby_plugin.rb). These comments do not enforce types at runtime; existing boundary validation still does.
|
||||
|
||||
`editor.insert(text)`, `editor.replace(text)`, and `editor.message(text)` queue effects. The context remains the pre-command snapshot even after queuing an effect. All effects are validated before the backend changes anything; buffer changes from one successful invocation form one undo action. Exceptions, process exits, timeouts, malformed replies, and invalid effects disable that plugin and discard its effects. Other plugins and built-ins remain available. Plugin `puts`, explicit `STDOUT.write`, and stderr cannot overwrite the TUI; diagnostic output is discarded, while exceptions appear in the status message.
|
||||
`editor.insert(text)`, `editor.replace(text)`, `editor.message(text)`, and `editor.label(name, text)` queue effects. The context remains the pre-command snapshot even after queuing an effect. All effects are validated before the backend changes anything; buffer changes from one successful invocation form one undo action. Exceptions, process exits, timeouts, malformed replies, and invalid effects disable that plugin and discard its effects. Other plugins and built-ins remain available. Plugin `puts`, explicit `STDOUT.write`, and stderr cannot overwrite the TUI; diagnostic output is discarded, while exceptions appear in the status message.
|
||||
|
||||
This is crash isolation, **not a security sandbox**: Ruby configuration and plugins have your user account's filesystem/process permissions. Load only trusted scripts. On Unix, hosts run in their own process groups and their groups are killed on shutdown.
|
||||
|
||||
@@ -40,15 +40,39 @@ A feature declares all capabilities it needs. Registration is atomic: if any req
|
||||
|
||||
`Vamp.on_document { |event| ... }` receives a deeply frozen hash with `"event"` (`"open"`, `"change"`, `"save"`, or `"close"`) and `"document"` (`"id"`, `"revision"`, `"path"`, `"root"`, `"text"`). Already-open documents are delivered at registration; changes include hidden-buffer edits, undo/redo, and plugin edits. Save-as sends close/open for the changed path. `Vamp.on_shutdown { ... }` supplies a shutdown hook. Callbacks must enqueue slow work rather than blocking host input.
|
||||
|
||||
Worker threads call `Vamp.publish(effects, request_id: nil)`. Background effects are `message`, revision-tagged `diagnostics`, or request-correlated `navigate`/`hover`; they cannot edit text. Diagnostics carry `buffer_id`, `revision`, and `items`, each with end-exclusive `start`/`end` positions, `severity` (`error`, `warning`, `information`, `hint`), and `message`. Positions are **zero-based grapheme coordinates**, not bytes, terminal cells, or UTF-16. Empty item lists clear the owner's annotations.
|
||||
Worker threads call `Vamp.publish(effects, request_id: nil)`. Background effects are `message`, `label`, revision-tagged `diagnostics`, or request-correlated `navigate`/`hover`; they cannot edit text. Diagnostics carry `buffer_id`, `revision`, and `items`, each with end-exclusive `start`/`end` positions, `severity` (`error`, `warning`, `information`, `hint`), and `message`. Positions are **zero-based grapheme coordinates**, not bytes, terminal cells, or UTF-16. Empty item lists clear the owner's annotations.
|
||||
|
||||
Navigation carries the source `buffer_id`/`revision`, destination `path`/`row`/`column`, and the invocation's `editor.request_id` passed to `publish`. Only the latest still-current source request may move the primary. Closed/stale revisions are ignored; malformed current updates retire their owner. Failed navigation reports an error without discarding buffer edits. Hosts use bounded queues/frames; protocol failure or host exit retires commands, bindings, pending requests, and owned diagnostics.
|
||||
|
||||
`hover` carries source `buffer_id`/`revision` and multiline `text`, with the invocation's `editor.request_id` passed to `publish`. Only applicable current requests in Normal mode can show a popup; stale results and replies while another modal list is focused are ignored. Text validates before a batch changes state; empty text clears the popup, and owner retirement dismisses its content.
|
||||
|
||||
## Named label updates
|
||||
|
||||
`editor.label(name, text)` sets a session-wide named value initialized by `config.labels`. Place that name in a [top or bottom bar anchor group](configuration.md#top-and-bottom-bars) to display it. This presentation effect does not edit text, move carets, change undo history, or dismiss completion. It also works in read-only diff views.
|
||||
|
||||
```ruby
|
||||
Vamp.plugin "build_label"
|
||||
|
||||
# @param editor [Vamp::Editor]
|
||||
# @param args [String]
|
||||
Vamp.command "build_label" do |editor, args|
|
||||
editor.label("build_status", args)
|
||||
end
|
||||
```
|
||||
|
||||
Place `:build_status` in a bar and load this plugin with `config.plugin`, then use `:build_label passed`; `:build_label` clears the value and hides its segment. For asynchronous data, an `async: true` plugin's worker publishes a named value without a request ID:
|
||||
|
||||
```ruby
|
||||
Vamp.publish([{ type: "label", name: "build_status", text: "passed" }])
|
||||
```
|
||||
|
||||
Collect custom data and choose its refresh interval in the plugin; the builtin `:battery` already refreshes from native OS data. There are no render callbacks. Stop worker threads in `Vamp.on_shutdown`. Changed values redraw while idle and persist across tabs, without depending on the originating buffer or revision. Publishing an unchanged value does not request a redraw. The last value remains until overwritten or cleared, including after plugin retirement.
|
||||
|
||||
Names match `[A-Za-z_][A-Za-z0-9_]*` and text must be a string. Control characters become replacement glyphs; an empty string clears the value. Updates share the existing 4 MiB protocol/text bounds; a rejected batch cannot partially change labels or other state.
|
||||
|
||||
## Messaging
|
||||
|
||||
Rust and Ruby exchange UTF-8, newline-delimited JSON objects with `version: 1`. Startup returns `manifest` (name, required capabilities, commands, async opt-in) or `config` (plugin paths/options and bindings). `invoke` requests carry an ID, command, arguments, and context; `result` replies carry the matching ID and typed text effects (`insert`, `replace`, `message`). Async hosts also receive `document`/`shutdown` and send `update` frames with optional request IDs and typed presentation/navigation effects. Errors use `error` frames. Unknown fields, wrong versions, and mismatched replies are rejected. Frames and aggregate effect text are bounded to 4 MiB.
|
||||
Rust and Ruby exchange UTF-8, newline-delimited JSON objects with `version: 1`. Startup returns `manifest` (name, required capabilities, commands, async opt-in) or `config` (plugin paths/options, bindings, `top_bar` and `bottom_bar` chrome maps, `popup` anchor options, and named labels). `invoke` requests carry an ID, command, arguments, and context; `result` replies carry the matching ID and typed effects (`insert`, `replace`, `message`, `label`). A `label` effect carries `name` and `text` strings. Async hosts also receive `document`/`shutdown` and send `update` frames with optional request IDs and typed presentation/navigation effects. Errors use `error` frames. Unknown fields, wrong versions, and mismatched replies are rejected. Frames and aggregate effect text are bounded to 4 MiB.
|
||||
|
||||
Before loading a script, Rust supplies a bounded startup JSON envelope containing `core_actions` and `options`. The action catalog initializes the Ruby interface; only the separate user-options object is exposed through `Vamp.options`, including when user options contain a key named `core_actions`.
|
||||
|
||||
|
||||
@@ -4,15 +4,50 @@
|
||||
Vamp.configure do |config|
|
||||
config.leader = "space"
|
||||
config.clipboard_mode = "system" # "separate" keeps ordinary y/d/c/p/P internal
|
||||
config.git_blame = true # false disables current-line inline blame
|
||||
config.cursor = {} # mode colors enabled; block cursor in every mode
|
||||
# config.cursor = { mode_colors: false, insert: :bar, visual: :underline }
|
||||
config.scroll_distance = 0 # nonnegative edge distance, or nil to center
|
||||
config.scroll_step_lines = nil # Ctrl+u/d: half viewport, or a positive screen-row count
|
||||
config.highlight_trailing_whitespace = false # true marks line-end whitespace in red
|
||||
config.whitespace_characters = {} # opt in: { " " => "·", "\t" => "→", "\n" => "↵" }
|
||||
config.whitespace_scope = "all" # or "leading" for indentation only; newline markers remain independent
|
||||
config.tab_spaces = nil # opt in: 4 inserts four spaces per Tab
|
||||
# config.language_tab_spaces.merge!("ruby" => 2, "makefile" => nil)
|
||||
config.file_explorer_side = "right"
|
||||
config.file_explorer_view = "tree"
|
||||
config.file_picker_view = "tree"
|
||||
config.diff_view_mode = "split" # or "unified"
|
||||
config.diff_split_orientation = "vertical" # or "horizontal"
|
||||
config.diff_follow_working_copy = true # false keeps the selected Working After endpoint
|
||||
config.pull_request_review_requested_symbol = "🙏"
|
||||
config.pull_request_approved_symbol = "👍"
|
||||
config.resolve_history_layout = "columns" # or "base_below" for left/right above the base
|
||||
# config.popup.command = { anchor: :bottom_left }
|
||||
# config.popup.search = { anchor: :center }
|
||||
# Status above, tabs, live battery and pending shell command below.
|
||||
config.bar.top = {
|
||||
left: [:mode, :path, :diagnostics, :selections, :count, :pending, :buffer],
|
||||
center: [], right: [:language, :lsp, :position],
|
||||
mode: { padding: 1, leading_edge: "", trailing_edge: "▓░" },
|
||||
position: { padding: 1, leading_edge: "░▓", trailing_edge: "" }
|
||||
}
|
||||
config.bar.bottom = {
|
||||
left: [:tabs], center: [], right: [:diff, :shell, :battery],
|
||||
tabs: {
|
||||
title: "{index} {view}{name}{changes}{modified}", padding: 1,
|
||||
leading_edge: "░▓", trailing_edge: "▓░", first_leading_edge: ""
|
||||
},
|
||||
battery: { padding: 1, leading_edge: "░▓", trailing_edge: "" }
|
||||
}
|
||||
config.bind "ctrl+j", config.core.down, mode: config.modes.selection
|
||||
config.bind "ctrl+k", config.core.up, mode: config.modes.selection
|
||||
config.plugin "plugins/greeting.rb"
|
||||
# Native LSP is disabled by default; install a server and explicitly opt in.
|
||||
# config.lsp["rust"] = true # built-in rust-analyzer preset
|
||||
# config.lsp["ruby"] = true # built-in Solargraph stdio preset (gem install solargraph)
|
||||
# config.lsp["python"] = true # built-in ty + Ruff stack (install both separately)
|
||||
# config.lsp["typst"] = true # built-in Tinymist LSP preset (install tinymist separately)
|
||||
# config.lsp["my-language"] = {
|
||||
# command: ["my-language-server", "--stdio"], extensions: ["myl"],
|
||||
# initialization_options: {}, settings: {}
|
||||
@@ -22,6 +57,8 @@ Vamp.configure do |config|
|
||||
# config.bind "K", config.core.lsp.hover
|
||||
config.bind "g", "greet"
|
||||
config.bind "leader g", "greet"
|
||||
config.bind "leader q", config.core.quit
|
||||
config.bind "leader d", config.core.diff
|
||||
config.bind "ctrl+r", config.core.redo
|
||||
config.bind "leader r", config.core.repeat_last_edit
|
||||
config.bind "ctrl+c", config.core.normal, mode: config.modes.insert
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
sjdalkjdas dsasda sdklam dalkmsd adadkajsdlakj
|
||||
o
|
||||
aaklsjdad
|
||||
|
||||
ads dasdkaljdalkjsda
|
||||
swwdalksdjaldskjadkjsla
|
||||
@@ -0,0 +1,34 @@
|
||||
Greeting: Hello
|
||||
|
||||
Shared context 01
|
||||
Shared context 02
|
||||
Shared context 03
|
||||
Shared context 04
|
||||
Shared context 05
|
||||
Shared context 06
|
||||
Shared context 07
|
||||
Shared context 08
|
||||
Shared context 09
|
||||
Shared context 10
|
||||
Shared context 11
|
||||
Shared context 12
|
||||
Shared context 13
|
||||
Shared context 14
|
||||
Shared context 15
|
||||
Shared context 16
|
||||
Shared context 17
|
||||
Shared context 18
|
||||
Shared context 19
|
||||
Shared context 20
|
||||
Shared context 21
|
||||
Shared context 22
|
||||
Shared context 23
|
||||
Shared context 24
|
||||
Shared context 25
|
||||
Shared context 26
|
||||
Shared context 27
|
||||
Shared context 28
|
||||
Shared context 29
|
||||
Shared context 30
|
||||
|
||||
Farewell: Goodbye
|
||||
@@ -0,0 +1 @@
|
||||
Delivery: send the notification immediately
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
greeting.txt
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
use std::{
|
||||
io,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
mpsc::{self, Receiver, Sender},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
};
|
||||
#[cfg(not(test))]
|
||||
use std::{sync::mpsc::RecvTimeoutError, time::Duration};
|
||||
|
||||
pub(crate) struct Battery {
|
||||
results: Arc<AtomicU8>,
|
||||
wake: Option<Sender<()>>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Battery {
|
||||
#[cfg(not(test))]
|
||||
pub(crate) fn start() -> io::Result<Self> {
|
||||
Self::start_with(read_charge, |wake| {
|
||||
matches!(
|
||||
wake.recv_timeout(Duration::from_secs(30)),
|
||||
Ok(()) | Err(RecvTimeoutError::Timeout)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn start_with(
|
||||
mut read: impl FnMut() -> Option<u8> + Send + 'static,
|
||||
mut wait: impl FnMut(&Receiver<()>) -> bool + Send + 'static,
|
||||
) -> io::Result<Self> {
|
||||
let results = Arc::new(AtomicU8::new(0));
|
||||
let latest = Arc::clone(&results);
|
||||
let (wake, requests) = mpsc::channel();
|
||||
let thread = thread::Builder::new()
|
||||
.name("vamp-battery".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
let charge = read().filter(|charge| *charge <= 100);
|
||||
// A one-slot latest-result mailbox: 0 = no new sample,
|
||||
// 1 = no battery, 2..=102 = charge. Publishing never blocks.
|
||||
latest.store(charge.map_or(1, |charge| charge + 2), Ordering::Relaxed);
|
||||
if !wait(&requests) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
results,
|
||||
wake: Some(wake),
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self) -> Option<Option<u8>> {
|
||||
match self.results.swap(0, Ordering::Relaxed) {
|
||||
0 => None,
|
||||
1 => Some(None),
|
||||
charge => Some(Some(charge - 2)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Battery {
|
||||
fn drop(&mut self) {
|
||||
// Disconnecting interrupts recv_timeout instead of waiting for its deadline.
|
||||
self.wake.take();
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
pub(crate) fn read_charge() -> Option<u8> {
|
||||
// ponytail: first internal battery on macOS/Linux; aggregate compatible capacities for multi-battery systems.
|
||||
#[cfg(target_os = "macos")]
|
||||
return macos::read_charge();
|
||||
#[cfg(target_os = "linux")]
|
||||
return linux::read_charge(std::path::Path::new("/sys/class/power_supply"));
|
||||
#[cfg(windows)]
|
||||
return windows::read_charge();
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", test))]
|
||||
fn percentage(current: u64, full: u64) -> Option<u8> {
|
||||
if full == 0 || current > full {
|
||||
return None;
|
||||
}
|
||||
Some(((current as u128 * 100) / full as u128) as u8)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
type Object = *const c_void;
|
||||
|
||||
#[cfg(not(test))]
|
||||
#[link(name = "IOKit", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn IOPSCopyPowerSourcesInfo() -> Object;
|
||||
fn IOPSCopyPowerSourcesList(info: Object) -> Object;
|
||||
fn IOPSGetPowerSourceDescription(info: Object, source: Object) -> Object;
|
||||
}
|
||||
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CFRelease(object: Object);
|
||||
fn CFGetTypeID(object: Object) -> usize;
|
||||
#[cfg(not(test))]
|
||||
fn CFEqual(left: Object, right: Object) -> u8;
|
||||
#[cfg(not(test))]
|
||||
fn CFArrayGetTypeID() -> usize;
|
||||
#[cfg(not(test))]
|
||||
fn CFArrayGetCount(array: Object) -> isize;
|
||||
#[cfg(not(test))]
|
||||
fn CFArrayGetValueAtIndex(array: Object, index: isize) -> Object;
|
||||
#[cfg(not(test))]
|
||||
fn CFDictionaryGetTypeID() -> usize;
|
||||
#[cfg(not(test))]
|
||||
fn CFDictionaryGetValue(dictionary: Object, key: Object) -> Object;
|
||||
#[cfg(not(test))]
|
||||
fn CFStringGetTypeID() -> usize;
|
||||
fn CFStringCreateWithCString(
|
||||
allocator: Object,
|
||||
string: *const c_char,
|
||||
encoding: u32,
|
||||
) -> Object;
|
||||
#[cfg(not(test))]
|
||||
fn CFBooleanGetTypeID() -> usize;
|
||||
#[cfg(not(test))]
|
||||
fn CFBooleanGetValue(boolean: Object) -> u8;
|
||||
fn CFNumberGetTypeID() -> usize;
|
||||
fn CFNumberGetValue(number: Object, kind: isize, value: *mut c_void) -> u8;
|
||||
}
|
||||
|
||||
// Only Copy/Create results belong here; power source descriptions are borrowed.
|
||||
struct Owned(Object);
|
||||
|
||||
impl Owned {
|
||||
fn new(object: Object) -> Option<Self> {
|
||||
(!object.is_null()).then(|| Self(object))
|
||||
}
|
||||
|
||||
fn string(value: &CStr) -> Option<Self> {
|
||||
// kCFStringEncodingUTF8, from CFString.h; a null allocator is the default.
|
||||
Self::new(unsafe {
|
||||
CFStringCreateWithCString(std::ptr::null(), value.as_ptr(), 0x0800_0100)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Owned {
|
||||
fn drop(&mut self) {
|
||||
unsafe { CFRelease(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn is_type(object: Object, kind: usize) -> bool {
|
||||
!object.is_null() && unsafe { CFGetTypeID(object) == kind }
|
||||
}
|
||||
|
||||
unsafe fn number(object: Object) -> Option<u64> {
|
||||
if !unsafe { is_type(object, CFNumberGetTypeID()) } {
|
||||
return None;
|
||||
}
|
||||
let mut value: i64 = 0;
|
||||
// kCFNumberSInt64Type = 4. A lossy/out-of-range conversion returns false.
|
||||
let converted = unsafe { CFNumberGetValue(object, 4, (&mut value as *mut i64).cast()) };
|
||||
(converted != 0).then_some(value)?.try_into().ok()
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
pub(super) fn read_charge() -> Option<u8> {
|
||||
// The opaque snapshot is only passed to IOPS accessors. All owned values
|
||||
// are released on every return path, including failed type checks.
|
||||
unsafe {
|
||||
let info = Owned::new(IOPSCopyPowerSourcesInfo())?;
|
||||
let sources = Owned::new(IOPSCopyPowerSourcesList(info.0))?;
|
||||
if !is_type(sources.0, CFArrayGetTypeID()) {
|
||||
return None;
|
||||
}
|
||||
let type_key = Owned::string(c"Type")?;
|
||||
let internal = Owned::string(c"InternalBattery")?;
|
||||
let present_key = Owned::string(c"Is Present")?;
|
||||
let current_key = Owned::string(c"Current Capacity")?;
|
||||
let full_key = Owned::string(c"Max Capacity")?;
|
||||
for index in 0..CFArrayGetCount(sources.0) {
|
||||
let source = CFArrayGetValueAtIndex(sources.0, index);
|
||||
if source.is_null() {
|
||||
continue;
|
||||
}
|
||||
let description = IOPSGetPowerSourceDescription(info.0, source);
|
||||
if !is_type(description, CFDictionaryGetTypeID()) {
|
||||
continue;
|
||||
}
|
||||
let kind = CFDictionaryGetValue(description, type_key.0);
|
||||
if !is_type(kind, CFStringGetTypeID()) || CFEqual(kind, internal.0) == 0 {
|
||||
continue;
|
||||
}
|
||||
let present = CFDictionaryGetValue(description, present_key.0);
|
||||
if !is_type(present, CFBooleanGetTypeID()) || CFBooleanGetValue(present) == 0 {
|
||||
continue;
|
||||
}
|
||||
let current = number(CFDictionaryGetValue(description, current_key.0))?;
|
||||
let full = number(CFDictionaryGetValue(description, full_key.0))?;
|
||||
return super::percentage(current, full);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
include!("../tests/unit/battery_macos.rs");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux {
|
||||
use std::{fs, io, path::Path};
|
||||
|
||||
pub(super) fn read_charge(root: &Path) -> Option<u8> {
|
||||
for entry in fs::read_dir(root).ok()? {
|
||||
let path = entry.ok()?.path();
|
||||
if fs::read_to_string(path.join("type"))
|
||||
.ok()
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
!= Some("Battery")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match fs::read_to_string(path.join("scope")) {
|
||||
Ok(scope) if matches!(scope.trim(), "System" | "Unknown") => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
_ => continue,
|
||||
}
|
||||
if fs::read_to_string(path.join("present"))
|
||||
.ok()
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
!= Some("1")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return read_capacity(&path);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_capacity(path: &Path) -> Option<u8> {
|
||||
match fs::read_to_string(path.join("capacity")) {
|
||||
Ok(capacity) => {
|
||||
return capacity
|
||||
.trim()
|
||||
.parse::<u8>()
|
||||
.ok()
|
||||
.filter(|value| *value <= 100);
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(_) => return None,
|
||||
}
|
||||
// Never mix energy and charge units or use design capacity as full capacity.
|
||||
let (current, full) = match fs::read_to_string(path.join("energy_now")) {
|
||||
Ok(current) => (current, fs::read_to_string(path.join("energy_full")).ok()?),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => (
|
||||
fs::read_to_string(path.join("charge_now")).ok()?,
|
||||
fs::read_to_string(path.join("charge_full")).ok()?,
|
||||
),
|
||||
Err(_) => return None,
|
||||
};
|
||||
super::percentage(current.trim().parse().ok()?, full.trim().parse().ok()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn windows_charge(percent: u8, flags: u8) -> Option<u8> {
|
||||
(percent <= 100 && flags & 128 == 0).then_some(percent)
|
||||
}
|
||||
|
||||
#[cfg(all(windows, not(test)))]
|
||||
mod windows {
|
||||
#[repr(C)]
|
||||
struct SystemPowerStatus {
|
||||
ac_line_status: u8,
|
||||
battery_flag: u8,
|
||||
battery_life_percent: u8,
|
||||
system_status_flag: u8,
|
||||
battery_life_time: u32,
|
||||
battery_full_life_time: u32,
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetSystemPowerStatus(status: *mut SystemPowerStatus) -> i32;
|
||||
}
|
||||
|
||||
pub(super) fn read_charge() -> Option<u8> {
|
||||
let mut status = std::mem::MaybeUninit::uninit();
|
||||
if unsafe { GetSystemPowerStatus(status.as_mut_ptr()) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let status = unsafe { status.assume_init() };
|
||||
super::windows_charge(status.battery_life_percent, status.battery_flag)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/battery.rs"]
|
||||
mod tests;
|
||||
+574
@@ -0,0 +1,574 @@
|
||||
//! Read-only file attribution; repository commands never touch the editor thread.
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::{self, Read, Write},
|
||||
path::{Component, Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub(crate) const LIMIT: usize = 16 * 1024 * 1024;
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
|
||||
type ResultFile = Result<Option<Vec<Option<Arc<LineBlame>>>>, String>;
|
||||
type Request = (u64, u64, PathBuf, String, Option<RevisionSource>);
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LineBlame {
|
||||
pub(crate) commit: String,
|
||||
pub(crate) author: String,
|
||||
pub(crate) summary: String,
|
||||
pub(crate) uncommitted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct RevisionSource {
|
||||
pub(crate) store: PathBuf,
|
||||
pub(crate) commit: String,
|
||||
pub(crate) path: PathBuf,
|
||||
pub(crate) keepalive: Option<Arc<crate::repository::Temporary>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
request: Option<Request>,
|
||||
result: Option<(u64, ResultFile)>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
generation: AtomicU64,
|
||||
stopped: AtomicBool,
|
||||
}
|
||||
pub(crate) struct BlameWorker {
|
||||
shared: Arc<Shared>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
impl BlameWorker {
|
||||
pub(crate) fn start() -> io::Result<Self> {
|
||||
let shared = Arc::new(Shared::default());
|
||||
let worker = Arc::clone(&shared);
|
||||
let thread = thread::Builder::new()
|
||||
.name("vamp-blame".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
let Ok(mut state) = worker.state.lock() else {
|
||||
return;
|
||||
};
|
||||
while state.request.is_none() && !worker.stopped.load(Ordering::Acquire) {
|
||||
let Ok(next) = worker.wake.wait(state) else {
|
||||
return;
|
||||
};
|
||||
state = next;
|
||||
}
|
||||
if worker.stopped.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let (generation, id, path, contents, source) = state.request.take().unwrap();
|
||||
drop(state);
|
||||
let cancelled = || {
|
||||
worker.stopped.load(Ordering::Acquire)
|
||||
|| worker.generation.load(Ordering::Acquire) != generation
|
||||
};
|
||||
let result = match source {
|
||||
Some(source) => read_revision(&source, &contents, &cancelled),
|
||||
None => read_file(&path, &contents, &cancelled),
|
||||
};
|
||||
let Ok(mut state) = worker.state.lock() else {
|
||||
return;
|
||||
};
|
||||
if !cancelled() {
|
||||
state.result = Some((id, result));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
shared,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn request(
|
||||
&mut self,
|
||||
id: u64,
|
||||
path: PathBuf,
|
||||
contents: String,
|
||||
source: Option<RevisionSource>,
|
||||
) -> io::Result<()> {
|
||||
if contents.len() > LIMIT {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Blame input exceeds 16 MiB",
|
||||
));
|
||||
}
|
||||
let mut state = self
|
||||
.shared
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("Blame worker stopped"))?;
|
||||
let generation = self
|
||||
.shared
|
||||
.generation
|
||||
.fetch_add(1, Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
state.request = Some((generation, id, path, contents, source));
|
||||
state.result = None;
|
||||
self.shared.wake.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self) -> Option<(u64, ResultFile)> {
|
||||
self.shared.state.lock().ok()?.result.take()
|
||||
}
|
||||
}
|
||||
impl Drop for BlameWorker {
|
||||
fn drop(&mut self) {
|
||||
let state = self.shared.state.lock();
|
||||
self.shared.stopped.store(true, Ordering::Release);
|
||||
self.shared.wake.notify_one();
|
||||
drop(state);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Temporary(PathBuf);
|
||||
impl Temporary {
|
||||
fn new() -> Result<Self, String> {
|
||||
for _ in 0..100 {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-blame-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let mut builder = fs::DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o700);
|
||||
}
|
||||
match builder.create(&path) {
|
||||
Ok(()) => return Ok(Self(path)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(_) => return Err("Cannot create private blame directory".into()),
|
||||
}
|
||||
}
|
||||
Err("Cannot create private blame directory".into())
|
||||
}
|
||||
}
|
||||
impl Drop for Temporary {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Same process-group cancellation as repository comparisons, with a smaller output/time budget.
|
||||
pub(crate) fn run(
|
||||
command: Command,
|
||||
input: &[u8],
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Option<Vec<u8>>, String> {
|
||||
let (code, bytes) = run_status(command, input, cancelled)?;
|
||||
Ok((code == Some(0)).then_some(bytes))
|
||||
}
|
||||
|
||||
pub(crate) fn run_status(
|
||||
mut command: Command,
|
||||
input: &[u8],
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<(Option<i32>, Vec<u8>), String> {
|
||||
if cancelled() {
|
||||
return Err("Blame cancelled".into());
|
||||
}
|
||||
for key in [
|
||||
"GIT_DIR",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
] {
|
||||
command.env_remove(key);
|
||||
}
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.env("GIT_NO_REPLACE_OBJECTS", "1")
|
||||
.env("GIT_NO_LAZY_FETCH", "1")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
return Err("Blame requires Unix process-group cancellation".into());
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
let mut child = command.spawn().map_err(|_| "Cannot start blame command")?;
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
thread::scope(|scope| {
|
||||
let output = scope.spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
stdout
|
||||
.take(LIMIT as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "Cannot read blame output")?;
|
||||
if bytes.len() > LIMIT {
|
||||
return Err("Blame output exceeds 16 MiB");
|
||||
}
|
||||
Ok(bytes)
|
||||
});
|
||||
let writer = scope.spawn(move || stdin.write_all(input));
|
||||
let started = Instant::now();
|
||||
let mut status = None;
|
||||
let failure = loop {
|
||||
if cancelled() {
|
||||
break Some("Blame cancelled");
|
||||
}
|
||||
if started.elapsed() >= TIMEOUT {
|
||||
break Some("Blame command timed out");
|
||||
}
|
||||
if status.is_none() {
|
||||
match child.try_wait() {
|
||||
Ok(value) => status = value,
|
||||
Err(_) => break Some("Cannot wait for blame command"),
|
||||
}
|
||||
}
|
||||
if status.is_some() && output.is_finished() && writer.is_finished() {
|
||||
break None;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
if failure.is_some() {
|
||||
unsafe {
|
||||
unsafe extern "C" {
|
||||
fn kill(pid: i32, signal: i32) -> i32;
|
||||
}
|
||||
kill(-(child.id() as i32), 9);
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
let bytes = output.join().map_err(|_| "Blame reader stopped")?;
|
||||
let written = writer.join().map_err(|_| "Blame writer stopped")?;
|
||||
if let Some(error) = failure {
|
||||
return Err(error.into());
|
||||
}
|
||||
let bytes = bytes.map_err(str::to_owned)?;
|
||||
let status = status.unwrap();
|
||||
if status.success() {
|
||||
written.map_err(|_| "Cannot supply blame contents")?;
|
||||
}
|
||||
Ok((status.code(), bytes))
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(crate) fn git(root: &Path) -> Command {
|
||||
let mut command = git_without_literal_pathspecs(root);
|
||||
command.arg("--literal-pathspecs");
|
||||
command
|
||||
}
|
||||
pub(crate) fn git_without_literal_pathspecs(root: &Path) -> Command {
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.args([
|
||||
"--no-pager",
|
||||
"-c",
|
||||
"core.hooksPath=/dev/null",
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
])
|
||||
.arg("-C")
|
||||
.arg(root);
|
||||
command
|
||||
}
|
||||
fn oid(value: &str) -> bool {
|
||||
matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}
|
||||
fn read_revision(
|
||||
source: &RevisionSource,
|
||||
contents: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> ResultFile {
|
||||
if contents.len() > LIMIT {
|
||||
return Err("Blame input exceeds 16 MiB".into());
|
||||
}
|
||||
if !oid(&source.commit) {
|
||||
return Err("Invalid blame commit".into());
|
||||
}
|
||||
crate::repository::safe_path(&source.path)?;
|
||||
let rows = contents.split_inclusive('\n').count();
|
||||
if rows == 0 || source.commit.bytes().all(|byte| byte == b'0') {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut objects = git(&source.store);
|
||||
objects.arg("--git-dir").arg(&source.store).args([
|
||||
"rev-parse",
|
||||
"--path-format=absolute",
|
||||
"--git-path",
|
||||
"objects",
|
||||
]);
|
||||
let objects = run(objects, &[], cancelled)?.ok_or("Cannot resolve blame object store")?;
|
||||
let private = Temporary::new()?;
|
||||
fs::create_dir(private.0.join("refs"))
|
||||
.and_then(|()| fs::create_dir_all(private.0.join("objects/info")))
|
||||
.map_err(|_| "Cannot prepare private blame repository")?;
|
||||
// Keep relative alternates anchored in their original object directory.
|
||||
let mut alternate = vec![b'"'];
|
||||
for &byte in objects.strip_suffix(b"\n").unwrap_or(&objects) {
|
||||
if (b' '..=b'~').contains(&byte) && !matches!(byte, b'"' | b'\\') {
|
||||
alternate.push(byte);
|
||||
} else {
|
||||
write!(&mut alternate, "\\{byte:03o}").unwrap();
|
||||
}
|
||||
}
|
||||
alternate.extend_from_slice(b"\"\n");
|
||||
fs::write(private.0.join("objects/info/alternates"), alternate)
|
||||
.and_then(|()| fs::write(private.0.join("HEAD"), format!("{}\n", source.commit)))
|
||||
.map_err(|_| "Cannot prepare blame parent")?;
|
||||
if source.commit.len() == 64 {
|
||||
fs::write(
|
||||
private.0.join("config"),
|
||||
"[core]\nrepositoryformatversion = 1\n[extensions]\nobjectFormat = sha256\n",
|
||||
)
|
||||
.map_err(|_| "Cannot prepare blame object format")?;
|
||||
}
|
||||
let command = || {
|
||||
let mut command = git(&private.0);
|
||||
command
|
||||
.arg("--git-dir")
|
||||
.arg(&private.0)
|
||||
.arg("--work-tree")
|
||||
.arg(&private.0);
|
||||
command
|
||||
};
|
||||
let mut present = command();
|
||||
present
|
||||
.args(["ls-tree", "-r", "-z", "--full-tree", "HEAD", "--"])
|
||||
.arg(&source.path);
|
||||
let Some(entry) = run(present, &[], cancelled)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(tab) = entry.iter().position(|&byte| byte == b'\t') else {
|
||||
return Ok(None);
|
||||
};
|
||||
if (!entry.starts_with(b"100644 blob ") && !entry.starts_with(b"100755 blob "))
|
||||
|| entry[tab + 1..].strip_suffix(b"\0") != Some(source.path.as_os_str().as_encoded_bytes())
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut blame = command();
|
||||
blame
|
||||
.args([
|
||||
"blame",
|
||||
"--incremental",
|
||||
"--no-textconv",
|
||||
"--contents",
|
||||
"-",
|
||||
"--",
|
||||
])
|
||||
.arg(&source.path);
|
||||
let output = run(blame, contents.as_bytes(), cancelled)?.ok_or("Cannot read Git blame")?;
|
||||
parse(&output, rows).map(Some)
|
||||
}
|
||||
|
||||
fn read_file(path: &Path, contents: &str, cancelled: &dyn Fn() -> bool) -> ResultFile {
|
||||
if contents.len() > LIMIT {
|
||||
return Err("Blame input exceeds 16 MiB".into());
|
||||
}
|
||||
// The editor has a final empty row after a newline; Git has no corresponding source line.
|
||||
let rows = contents.split_inclusive('\n').count();
|
||||
if rows == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if !fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_file()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = fs::canonicalize(path).map_err(|_| "Cannot resolve blame file")?;
|
||||
let Some(root) = path.parent().and_then(|parent| {
|
||||
parent
|
||||
.ancestors()
|
||||
.find(|root| root.join(".jj").exists() || root.join(".git").exists())
|
||||
}) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let relative = path.strip_prefix(root).map_err(|_| "Invalid blame path")?;
|
||||
if relative.components().any(|part| {
|
||||
!matches!(part, Component::Normal(_))
|
||||
|| part.as_os_str() == ".git"
|
||||
|| part.as_os_str() == ".jj"
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut command = git(root);
|
||||
if root.join(".jj").exists() {
|
||||
let mut jj = Command::new("jj");
|
||||
jj.arg("--repository")
|
||||
.arg(root)
|
||||
.args([
|
||||
"--ignore-working-copy",
|
||||
"--at-operation=@",
|
||||
"--no-pager",
|
||||
"--color=never",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
"commit_id ++ \"\\n\"",
|
||||
])
|
||||
.current_dir(root);
|
||||
let bytes = run(jj, &[], cancelled)?.ok_or("Cannot resolve Jujutsu blame parent")?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|_| "Invalid Jujutsu blame metadata")?;
|
||||
let mut parents = text.lines();
|
||||
let Some(parent) = parents.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A merge has no single committed baseline; never pick an arbitrary parent.
|
||||
if parents.next().is_some() || parent.bytes().all(|byte| byte == b'0') {
|
||||
return Ok(None);
|
||||
}
|
||||
if !oid(parent) {
|
||||
return Err("Invalid Jujutsu blame metadata".into());
|
||||
}
|
||||
let store = crate::repository::store_for_jj(root)?;
|
||||
return read_revision(
|
||||
&RevisionSource {
|
||||
store,
|
||||
commit: parent.into(),
|
||||
path: relative.to_path_buf(),
|
||||
keepalive: None,
|
||||
},
|
||||
contents,
|
||||
cancelled,
|
||||
);
|
||||
}
|
||||
let mut present = git(root);
|
||||
let mut object = std::ffi::OsString::from("HEAD:");
|
||||
object.push(relative);
|
||||
present.args(["cat-file", "-e"]).arg(object);
|
||||
if run(present, &[], cancelled)?.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
command
|
||||
.args([
|
||||
"blame",
|
||||
"--incremental",
|
||||
"--no-textconv",
|
||||
"--contents",
|
||||
"-",
|
||||
"--",
|
||||
])
|
||||
.arg(relative);
|
||||
let output = run(command, contents.as_bytes(), cancelled)?.ok_or("Cannot read Git blame")?;
|
||||
parse(&output, rows).map(Some)
|
||||
}
|
||||
fn parse(bytes: &[u8], rows: usize) -> Result<Vec<Option<Arc<LineBlame>>>, String> {
|
||||
let malformed = || "Invalid Git blame metadata".to_owned();
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| malformed())?;
|
||||
let mut lines = text.lines();
|
||||
let mut commits = HashMap::<&str, Arc<LineBlame>>::new();
|
||||
let mut result = vec![None; rows];
|
||||
while let Some(line) = lines.next() {
|
||||
let mut header = line.split(' ');
|
||||
let commit = header.next().filter(|id| oid(id)).ok_or_else(malformed)?;
|
||||
let original = header.next().and_then(|n| n.parse::<usize>().ok());
|
||||
let start = header.next().and_then(|n| n.parse::<usize>().ok());
|
||||
let count = header.next().and_then(|n| n.parse::<usize>().ok());
|
||||
let (Some(original), Some(start), Some(count)) = (original, start, count) else {
|
||||
return Err(malformed());
|
||||
};
|
||||
if original == 0 || start == 0 || count == 0 || header.next().is_some() {
|
||||
return Err(malformed());
|
||||
}
|
||||
original.checked_add(count - 1).ok_or_else(malformed)?;
|
||||
let start = start - 1;
|
||||
let end = start
|
||||
.checked_add(count)
|
||||
.filter(|&end| end <= rows)
|
||||
.ok_or_else(malformed)?;
|
||||
let mut author = None;
|
||||
let mut summary = None;
|
||||
let mut filename = false;
|
||||
for line in lines.by_ref() {
|
||||
if let Some(value) = line.strip_prefix("filename ") {
|
||||
if value.is_empty() {
|
||||
return Err(malformed());
|
||||
}
|
||||
filename = true;
|
||||
break;
|
||||
}
|
||||
if line.is_empty() || line.starts_with('\t') || line.split(' ').next().is_some_and(oid)
|
||||
{
|
||||
return Err(malformed());
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("author ") {
|
||||
if author.replace(value).is_some() {
|
||||
return Err(malformed());
|
||||
}
|
||||
}
|
||||
if let Some(value) = line.strip_prefix("summary ") {
|
||||
if summary.replace(value).is_some() {
|
||||
return Err(malformed());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !filename {
|
||||
return Err(malformed());
|
||||
}
|
||||
let blame = if let Some(blame) = commits.get(commit) {
|
||||
if author.is_some() || summary.is_some() {
|
||||
return Err(malformed());
|
||||
}
|
||||
Arc::clone(blame)
|
||||
} else {
|
||||
let author = author.ok_or_else(malformed)?;
|
||||
let summary = summary.ok_or_else(malformed)?;
|
||||
let uncommitted = commit.bytes().all(|byte| byte == b'0');
|
||||
let blame = Arc::new(LineBlame {
|
||||
commit: if uncommitted {
|
||||
String::new()
|
||||
} else {
|
||||
commit.into()
|
||||
},
|
||||
author: if uncommitted {
|
||||
String::new()
|
||||
} else {
|
||||
author.into()
|
||||
},
|
||||
summary: if uncommitted {
|
||||
String::new()
|
||||
} else {
|
||||
summary.into()
|
||||
},
|
||||
uncommitted,
|
||||
});
|
||||
commits.insert(commit, Arc::clone(&blame));
|
||||
blame
|
||||
};
|
||||
for row in &mut result[start..end] {
|
||||
if row.replace(Arc::clone(&blame)).is_some() {
|
||||
return Err(malformed());
|
||||
}
|
||||
}
|
||||
}
|
||||
if result.iter().any(Option::is_none) {
|
||||
return Err(malformed());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "../tests/unit/blame.rs"]
|
||||
mod tests;
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PopupAnchor {
|
||||
TopLeft,
|
||||
TopCenter,
|
||||
TopRight,
|
||||
CenterLeft,
|
||||
Center,
|
||||
CenterRight,
|
||||
#[default]
|
||||
BottomLeft,
|
||||
BottomCenter,
|
||||
BottomRight,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PopupOptions {
|
||||
pub anchor: PopupAnchor,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PopupConfig {
|
||||
pub command: PopupOptions,
|
||||
pub search: PopupOptions,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PopupOptions {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Options {
|
||||
#[serde(default)]
|
||||
anchor: PopupAnchor,
|
||||
}
|
||||
let options: Options = deserialize_object(deserializer)?;
|
||||
Ok(Self {
|
||||
anchor: options.anchor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PopupConfig {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Options {
|
||||
#[serde(default)]
|
||||
command: PopupOptions,
|
||||
#[serde(default)]
|
||||
search: PopupOptions,
|
||||
}
|
||||
let options: Options = deserialize_object(deserializer)?;
|
||||
Ok(Self {
|
||||
command: options.command,
|
||||
search: options.search,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Struct derives also accept sequences; popup configuration accepts only objects.
|
||||
fn deserialize_object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<T, D::Error> {
|
||||
struct ObjectVisitor<T>(std::marker::PhantomData<T>);
|
||||
|
||||
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectVisitor<T> {
|
||||
type Value = T;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a popup configuration object")
|
||||
}
|
||||
|
||||
fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<T, M::Error> {
|
||||
T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_map(ObjectVisitor(std::marker::PhantomData))
|
||||
}
|
||||
|
||||
const DEFAULT_BOTTOM_SEGMENTS: &[&str] = &[
|
||||
"mode",
|
||||
"pending",
|
||||
"buffer",
|
||||
"diagnostics",
|
||||
"path",
|
||||
"selections",
|
||||
"count",
|
||||
"language",
|
||||
"lsp",
|
||||
"position",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ChromeLine {
|
||||
pub left: Vec<String>,
|
||||
pub center: Vec<String>,
|
||||
pub right: Vec<String>,
|
||||
pub segments: BTreeMap<String, SegmentConfig>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct SegmentConfig {
|
||||
pub title: String,
|
||||
pub padding: usize,
|
||||
pub margin: [usize; 2],
|
||||
pub leading_edge: String,
|
||||
pub trailing_edge: String,
|
||||
pub first_leading_edge: Option<String>,
|
||||
}
|
||||
|
||||
impl ChromeLine {
|
||||
pub fn top() -> Self {
|
||||
Self {
|
||||
left: vec!["tabs".into()],
|
||||
center: Vec::new(),
|
||||
right: vec!["diff".into(), "shell".into(), "battery".into()],
|
||||
segments: BTreeMap::from([
|
||||
("tabs".into(), default_segment("tabs")),
|
||||
("diff".into(), default_segment("diff")),
|
||||
("battery".into(), default_segment("battery")),
|
||||
("shell".into(), default_segment("shell")),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bottom() -> Self {
|
||||
Self {
|
||||
left: DEFAULT_BOTTOM_SEGMENTS[..DEFAULT_BOTTOM_SEGMENTS.len() - 3]
|
||||
.iter()
|
||||
.map(|name| (*name).into())
|
||||
.collect(),
|
||||
center: Vec::new(),
|
||||
right: vec!["language".into(), "lsp".into(), "position".into()],
|
||||
segments: DEFAULT_BOTTOM_SEGMENTS
|
||||
.iter()
|
||||
.map(|name| ((*name).into(), default_segment(name)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Styles are populated for every referenced name during configuration validation.
|
||||
pub fn segment(&self, name: &str) -> &SegmentConfig {
|
||||
self.segments.get(name).expect("validated chrome segment")
|
||||
}
|
||||
|
||||
pub fn validate(&mut self) -> Result<(), String> {
|
||||
for name in self
|
||||
.left
|
||||
.iter()
|
||||
.chain(&self.center)
|
||||
.chain(&self.right)
|
||||
.chain(self.segments.keys())
|
||||
{
|
||||
validate_name(name)?;
|
||||
}
|
||||
for (name, segment) in &self.segments {
|
||||
for (option, value) in [
|
||||
("padding", segment.padding),
|
||||
("leading_margin", segment.margin[0]),
|
||||
("trailing_margin", segment.margin[1]),
|
||||
] {
|
||||
if value > 64 {
|
||||
return Err(format!(
|
||||
"Chrome segment {name:?} {option} must be between 0 and 64"
|
||||
));
|
||||
}
|
||||
}
|
||||
for (option, text) in [
|
||||
("title", Some(&segment.title)),
|
||||
("leading_edge", Some(&segment.leading_edge)),
|
||||
("trailing_edge", Some(&segment.trailing_edge)),
|
||||
("first_leading_edge", segment.first_leading_edge.as_ref()),
|
||||
] {
|
||||
if text.is_some_and(|text| text.chars().any(char::is_control)) {
|
||||
return Err(format!(
|
||||
"Chrome segment {name:?} {option} must be single-line text without controls"
|
||||
));
|
||||
}
|
||||
}
|
||||
validate_title(&segment.title)
|
||||
.map_err(|error| format!("Chrome segment {name:?}: {error}"))?;
|
||||
}
|
||||
for name in self.left.iter().chain(&self.center).chain(&self.right) {
|
||||
if !self.segments.contains_key(name) {
|
||||
self.segments.insert(name.clone(), default_segment(name));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn default_segment(name: &str) -> SegmentConfig {
|
||||
let mut segment = SegmentConfig::default();
|
||||
if matches!(name, "tabs" | "position" | "battery" | "shell") {
|
||||
segment.leading_edge = "░▓".into();
|
||||
}
|
||||
if matches!(name, "tabs" | "mode" | "shell") {
|
||||
segment.trailing_edge = "▓░".into();
|
||||
}
|
||||
if matches!(
|
||||
name,
|
||||
"tabs" | "mode" | "position" | "battery" | "shell" | "lsp"
|
||||
) {
|
||||
segment.padding = 1;
|
||||
}
|
||||
if name == "tabs" {
|
||||
segment.title = "{index} {view}{name}{changes}{modified}".into();
|
||||
segment.first_leading_edge = Some(String::new());
|
||||
}
|
||||
segment
|
||||
}
|
||||
|
||||
pub fn validate_name(name: &str) -> Result<(), String> {
|
||||
let mut bytes = name.bytes();
|
||||
if !bytes
|
||||
.next()
|
||||
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
|
||||
|| !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
|
||||
{
|
||||
return Err(format!(
|
||||
"Label/segment name {name:?} must match [A-Za-z_][A-Za-z0-9_]*"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_title(title: &str) -> Result<(), String> {
|
||||
let mut rest = title;
|
||||
while let Some(index) = rest.find(['{', '}']) {
|
||||
rest = &rest[index..];
|
||||
if !rest.starts_with('{') {
|
||||
return Err("title contains an unmatched '}'".into());
|
||||
}
|
||||
let end = rest.find('}').ok_or("title contains an unmatched '{'")?;
|
||||
let placeholder = &rest[1..end];
|
||||
if !matches!(
|
||||
placeholder,
|
||||
"index" | "view" | "name" | "path" | "changes" | "modified"
|
||||
) {
|
||||
return Err(format!(
|
||||
"unknown title placeholder {{{placeholder}}}; expected index, view, name, path, changes, or modified"
|
||||
));
|
||||
}
|
||||
rest = &rest[end + 1..];
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LineOptions {
|
||||
left: Option<Vec<String>>,
|
||||
center: Option<Vec<String>>,
|
||||
right: Option<Vec<String>>,
|
||||
#[serde(flatten)]
|
||||
segments: BTreeMap<String, SegmentOptions>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SegmentOptions {
|
||||
title: Option<String>,
|
||||
padding: Option<usize>,
|
||||
margin: Option<usize>,
|
||||
leading_margin: Option<usize>,
|
||||
trailing_margin: Option<usize>,
|
||||
leading_edge: Option<String>,
|
||||
trailing_edge: Option<String>,
|
||||
first_leading_edge: Option<String>,
|
||||
}
|
||||
|
||||
fn deserialize_line<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
mut line: ChromeLine,
|
||||
) -> Result<ChromeLine, D::Error> {
|
||||
// Decode through a value so explicit null is rejected rather than treated as an omitted option.
|
||||
let value = serde_json::Value::deserialize(deserializer)?;
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or_else(|| serde::de::Error::custom("chrome line must be an object"))?;
|
||||
for (name, value) in object {
|
||||
if value.is_null()
|
||||
|| value
|
||||
.as_object()
|
||||
.is_some_and(|options| options.values().any(serde_json::Value::is_null))
|
||||
{
|
||||
return Err(serde::de::Error::custom(format!(
|
||||
"Chrome option {name:?} must not be null"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let options: LineOptions = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
|
||||
if let Some(left) = options.left {
|
||||
line.left = left;
|
||||
}
|
||||
if let Some(center) = options.center {
|
||||
line.center = center;
|
||||
}
|
||||
if let Some(right) = options.right {
|
||||
line.right = right;
|
||||
}
|
||||
for (name, options) in options.segments {
|
||||
let segment = line
|
||||
.segments
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| default_segment(&name));
|
||||
if let Some(title) = options.title {
|
||||
segment.title = title;
|
||||
}
|
||||
if let Some(padding) = options.padding {
|
||||
segment.padding = padding;
|
||||
}
|
||||
if let Some(margin) = options.margin {
|
||||
segment.margin = [margin; 2];
|
||||
}
|
||||
if let Some(margin) = options.leading_margin {
|
||||
segment.margin[0] = margin;
|
||||
}
|
||||
if let Some(margin) = options.trailing_margin {
|
||||
segment.margin[1] = margin;
|
||||
}
|
||||
if let Some(edge) = options.leading_edge {
|
||||
segment.leading_edge = edge;
|
||||
}
|
||||
if let Some(edge) = options.trailing_edge {
|
||||
segment.trailing_edge = edge;
|
||||
}
|
||||
if let Some(edge) = options.first_leading_edge {
|
||||
segment.first_leading_edge = Some(edge);
|
||||
}
|
||||
}
|
||||
line.validate().map_err(serde::de::Error::custom)?;
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
pub fn top<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ChromeLine, D::Error> {
|
||||
deserialize_line(deserializer, ChromeLine::top())
|
||||
}
|
||||
|
||||
pub fn bottom<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ChromeLine, D::Error> {
|
||||
deserialize_line(deserializer, ChromeLine::bottom())
|
||||
}
|
||||
|
||||
pub fn labels<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let labels = BTreeMap::<String, String>::deserialize(deserializer)?;
|
||||
for name in labels.keys() {
|
||||
validate_name(name).map_err(serde::de::Error::custom)?;
|
||||
}
|
||||
Ok(labels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/chrome.rs"]
|
||||
mod tests;
|
||||
+219
-250
@@ -4,31 +4,6 @@ use std::time::Duration;
|
||||
const MAX_CLIPBOARD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAC_READ: &str = r#"
|
||||
ObjC.import('AppKit');
|
||||
function run() {
|
||||
var text = $.NSPasteboard.generalPasteboard.stringForType($.NSPasteboardTypeString);
|
||||
if (text.isNil()) return;
|
||||
$.NSFileHandle.fileHandleWithStandardOutput.writeData(
|
||||
text.dataUsingEncoding($.NSUTF8StringEncoding));
|
||||
}
|
||||
"#;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAC_WRITE: &str = r#"
|
||||
ObjC.import('AppKit');
|
||||
function run() {
|
||||
var data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
|
||||
var text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);
|
||||
if (text.isNil()) throw Error('Clipboard input is not UTF-8');
|
||||
var pasteboard = $.NSPasteboard.generalPasteboard;
|
||||
pasteboard.clearContents;
|
||||
if (!pasteboard.setStringForType(text, $.NSPasteboardTypeString))
|
||||
throw Error('Cannot write plain-text clipboard');
|
||||
}
|
||||
"#;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ClipboardMode {
|
||||
System,
|
||||
@@ -41,8 +16,8 @@ struct ClipboardCommand {
|
||||
}
|
||||
|
||||
struct Commands {
|
||||
reader: ClipboardCommand,
|
||||
writer: ClipboardCommand,
|
||||
reader: Option<ClipboardCommand>,
|
||||
writer: Option<ClipboardCommand>,
|
||||
}
|
||||
|
||||
pub struct SystemClipboard {
|
||||
@@ -68,14 +43,14 @@ impl SystemClipboard {
|
||||
pub(crate) fn with_commands(reader: PathBuf, writer: PathBuf) -> Self {
|
||||
Self {
|
||||
commands: Some(Ok(Commands {
|
||||
reader: ClipboardCommand {
|
||||
reader: Some(ClipboardCommand {
|
||||
program: reader,
|
||||
args: &[],
|
||||
},
|
||||
writer: ClipboardCommand {
|
||||
}),
|
||||
writer: Some(ClipboardCommand {
|
||||
program: writer,
|
||||
args: &[],
|
||||
},
|
||||
}),
|
||||
})),
|
||||
timeout: COMMAND_TIMEOUT,
|
||||
}
|
||||
@@ -84,9 +59,16 @@ impl SystemClipboard {
|
||||
pub fn read(&mut self) -> Result<String, String> {
|
||||
let timeout = self.timeout;
|
||||
let commands = self.commands.get_or_insert_with(select_commands);
|
||||
let command = &commands.as_ref().map_err(Clone::clone)?.reader;
|
||||
let bytes = run(command, None, timeout)?;
|
||||
String::from_utf8(bytes).map_err(|_| "System clipboard is not valid UTF-8".into())
|
||||
match &commands.as_ref().map_err(Clone::clone)?.reader {
|
||||
Some(command) => {
|
||||
let bytes = run(command, None, timeout)?;
|
||||
String::from_utf8(bytes).map_err(|_| "System clipboard is not valid UTF-8".into())
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
None => macos::read(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
None => Err("System clipboard is unsupported on this platform".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&mut self, text: &str) -> Result<(), String> {
|
||||
@@ -95,12 +77,17 @@ impl SystemClipboard {
|
||||
}
|
||||
let timeout = self.timeout;
|
||||
let commands = self.commands.get_or_insert_with(select_commands);
|
||||
let command = &commands.as_ref().map_err(Clone::clone)?.writer;
|
||||
run(command, Some(text.as_bytes()), timeout).map(|_| ())
|
||||
match &commands.as_ref().map_err(Clone::clone)?.writer {
|
||||
Some(command) => run(command, Some(text.as_bytes()), timeout).map(|_| ()),
|
||||
#[cfg(target_os = "macos")]
|
||||
None => macos::write(text),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
None => Err("System clipboard is unsupported on this platform".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn executable(name: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
@@ -117,47 +104,38 @@ fn executable(name: &str) -> Option<PathBuf> {
|
||||
fn select_commands() -> Result<Commands, String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Some(program) = executable("osascript") {
|
||||
return Ok(Commands {
|
||||
reader: ClipboardCommand {
|
||||
program: program.clone(),
|
||||
args: &["-l", "JavaScript", "-e", MAC_READ],
|
||||
},
|
||||
writer: ClipboardCommand {
|
||||
program,
|
||||
args: &["-l", "JavaScript", "-e", MAC_WRITE],
|
||||
},
|
||||
});
|
||||
}
|
||||
Err("System clipboard requires osascript with JXA/AppKit on PATH".into())
|
||||
Ok(Commands {
|
||||
reader: None,
|
||||
writer: None,
|
||||
})
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty()) {
|
||||
if let (Some(reader), Some(writer)) = (executable("wl-paste"), executable("wl-copy")) {
|
||||
return Ok(Commands {
|
||||
reader: ClipboardCommand {
|
||||
reader: Some(ClipboardCommand {
|
||||
program: reader,
|
||||
args: &["--no-newline", "--type", "text"],
|
||||
},
|
||||
writer: ClipboardCommand {
|
||||
}),
|
||||
writer: Some(ClipboardCommand {
|
||||
program: writer,
|
||||
args: &["--type", "text/plain;charset=utf-8"],
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
if std::env::var_os("DISPLAY").is_some_and(|value| !value.is_empty()) {
|
||||
if let Some(program) = executable("xclip") {
|
||||
return Ok(Commands {
|
||||
reader: ClipboardCommand {
|
||||
reader: Some(ClipboardCommand {
|
||||
program: program.clone(),
|
||||
args: &["-selection", "clipboard", "-target", "UTF8_STRING", "-out"],
|
||||
},
|
||||
writer: ClipboardCommand {
|
||||
}),
|
||||
writer: Some(ClipboardCommand {
|
||||
program,
|
||||
args: &["-selection", "clipboard", "-target", "UTF8_STRING", "-in"],
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -169,6 +147,187 @@ fn select_commands() -> Result<Commands, String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::ptr;
|
||||
|
||||
type Object = *const c_void;
|
||||
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CFStringCreateWithCString(
|
||||
allocator: Object,
|
||||
bytes: *const c_char,
|
||||
encoding: u32,
|
||||
) -> Object;
|
||||
fn CFDataCreate(allocator: Object, bytes: *const u8, length: isize) -> Object;
|
||||
fn CFRelease(object: Object);
|
||||
}
|
||||
|
||||
#[link(name = "CoreServices", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static kUTTypeUTF8PlainText: Object;
|
||||
}
|
||||
|
||||
#[link(name = "ApplicationServices", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn PasteboardCreate(name: Object, pasteboard: *mut Object) -> i32;
|
||||
fn PasteboardClear(pasteboard: Object) -> i32;
|
||||
fn PasteboardPutItemFlavor(
|
||||
pasteboard: Object,
|
||||
item: usize,
|
||||
flavor: Object,
|
||||
data: Object,
|
||||
flags: u32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
struct Owned(Object);
|
||||
impl Owned {
|
||||
fn new(object: Object) -> Result<Self, String> {
|
||||
if object.is_null() {
|
||||
Err("Cannot allocate system clipboard data".into())
|
||||
} else {
|
||||
Ok(Self(object))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Owned {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: each handle owns one Core Foundation reference.
|
||||
unsafe { CFRelease(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn check(status: i32) -> Result<(), String> {
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("System clipboard publication failed ({status})"))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_to(name: Object, text: &str) -> Result<(), String> {
|
||||
// SAFETY: framework constants and byte slices live throughout the calls.
|
||||
unsafe {
|
||||
let data = Owned::new(CFDataCreate(
|
||||
ptr::null(),
|
||||
text.as_ptr(),
|
||||
text.len() as isize,
|
||||
))?;
|
||||
let mut board = ptr::null();
|
||||
check(PasteboardCreate(name, &mut board))?;
|
||||
let board = Owned::new(board)?;
|
||||
// Prepare all allocations before changing clipboard contents.
|
||||
check(PasteboardClear(board.0))?;
|
||||
check(PasteboardPutItemFlavor(
|
||||
board.0,
|
||||
1,
|
||||
kUTTypeUTF8PlainText,
|
||||
data.0,
|
||||
0,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write(text: &str) -> Result<(), String> {
|
||||
// SAFETY: the clipboard name is a process-lifetime, null-terminated literal.
|
||||
let name = unsafe {
|
||||
Owned::new(CFStringCreateWithCString(
|
||||
ptr::null(),
|
||||
c"com.apple.pasteboard.clipboard".as_ptr(),
|
||||
0x0800_0100,
|
||||
))?
|
||||
};
|
||||
write_to(name.0, text)
|
||||
}
|
||||
|
||||
#[link(name = "AppKit", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static NSPasteboardTypeString: Object;
|
||||
}
|
||||
|
||||
#[link(name = "objc")]
|
||||
unsafe extern "C" {
|
||||
fn objc_getClass(name: *const c_char) -> Object;
|
||||
fn sel_registerName(name: *const c_char) -> Object;
|
||||
fn objc_msgSend();
|
||||
fn objc_autoreleasePoolPush() -> Object;
|
||||
fn objc_autoreleasePoolPop(pool: Object);
|
||||
}
|
||||
|
||||
struct AutoreleasePool(Object);
|
||||
impl Drop for AutoreleasePool {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: this pool was pushed on the same thread.
|
||||
unsafe { objc_autoreleasePoolPop(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn read_from(board: Object) -> Result<String, String> {
|
||||
// SAFETY: receivers are live AppKit objects; each cast matches the
|
||||
// selected Objective-C method's ABI. The caller owns an autorelease pool.
|
||||
unsafe {
|
||||
let string: unsafe extern "C" fn(Object, Object, Object) -> Object =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
let text = string(
|
||||
board,
|
||||
sel_registerName(c"stringForType:".as_ptr()),
|
||||
NSPasteboardTypeString,
|
||||
);
|
||||
if text.is_null() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let encode: unsafe extern "C" fn(Object, Object, usize) -> Object =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
let data = encode(text, sel_registerName(c"dataUsingEncoding:".as_ptr()), 4);
|
||||
if data.is_null() {
|
||||
return Err("System clipboard is not valid UTF-8".into());
|
||||
}
|
||||
let length: unsafe extern "C" fn(Object, Object) -> usize =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
let length = length(data, sel_registerName(c"length".as_ptr()));
|
||||
if length > super::MAX_CLIPBOARD_BYTES {
|
||||
return Err("System clipboard text exceeds 4 MiB".into());
|
||||
}
|
||||
if length == 0 {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let bytes: unsafe extern "C" fn(Object, Object) -> *const u8 =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
let bytes = std::slice::from_raw_parts(
|
||||
bytes(data, sel_registerName(c"bytes".as_ptr())),
|
||||
length,
|
||||
);
|
||||
String::from_utf8(bytes.to_vec())
|
||||
.map_err(|_| "System clipboard is not valid UTF-8".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn read() -> Result<String, String> {
|
||||
// SAFETY: AppKit class and selector names are static C strings.
|
||||
unsafe {
|
||||
let _pool = AutoreleasePool(objc_autoreleasePoolPush());
|
||||
let send: unsafe extern "C" fn(Object, Object) -> Object =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
let board = send(
|
||||
objc_getClass(c"NSPasteboard".as_ptr()),
|
||||
sel_registerName(c"generalPasteboard".as_ptr()),
|
||||
);
|
||||
if board.is_null() {
|
||||
return Err("Cannot open system clipboard".into());
|
||||
}
|
||||
read_from(board)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
include!("../tests/unit/clipboard_macos.rs");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
fn run(_: &ClipboardCommand, _: Option<&[u8]>, _: Duration) -> Result<Vec<u8>, String> {
|
||||
Err("System clipboard is unsupported on this platform".into())
|
||||
@@ -382,195 +541,5 @@ unsafe extern "C" {
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "macos", target_os = "linux")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static FIXTURE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-clipboard-{}-{}",
|
||||
std::process::id(),
|
||||
FIXTURE_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn command(&self, name: &str, body: &str) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn clipboard(&self, text: &[u8]) -> SystemClipboard {
|
||||
let state = self.0.join("state");
|
||||
fs::write(&state, text).unwrap();
|
||||
let state = format!("'{}'", state.to_str().unwrap().replace('\'', "'\\''"));
|
||||
SystemClipboard::with_commands(
|
||||
self.command("read", &format!("exec /bin/cat {state}")),
|
||||
self.command("write", &format!("exec /bin/cat > {state}")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_does_not_probe_or_spawn() {
|
||||
assert!(SystemClipboard::new().commands.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_unicode_whitespace_and_large_pipes_exactly() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(b"");
|
||||
for text in ["", " héllo\t世界🙂\r\n\n", &"é\n".repeat(300_000)] {
|
||||
clipboard.write(text).unwrap();
|
||||
assert_eq!(fs::read(fixture.0.join("state")).unwrap(), text.as_bytes());
|
||||
assert_eq!(clipboard.read().unwrap(), text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversize_and_invalid_utf8_without_leaking_contents() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(&[0xff, b'\n']);
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard is not valid UTF-8"
|
||||
);
|
||||
let maximum = "é".repeat(MAX_CLIPBOARD_BYTES / 2);
|
||||
clipboard.write(&maximum).unwrap();
|
||||
assert_eq!(clipboard.read().unwrap(), maximum);
|
||||
let too_large = format!("{maximum}x");
|
||||
assert_eq!(
|
||||
clipboard.write(&too_large).unwrap_err(),
|
||||
"System clipboard text exceeds 4 MiB"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("state")).unwrap(),
|
||||
maximum.as_bytes()
|
||||
);
|
||||
fs::write(fixture.0.join("state"), &too_large).unwrap();
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard text exceeds 4 MiB"
|
||||
);
|
||||
let mut incomplete = vec![b'x'; MAX_CLIPBOARD_BYTES - 1];
|
||||
incomplete.push(0xc3);
|
||||
fs::write(fixture.0.join("state"), incomplete).unwrap();
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard is not valid UTF-8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_failures_and_stderr_cannot_leak_clipboard_text() {
|
||||
let fixture = Fixture::new();
|
||||
let failed = fixture.command(
|
||||
"failed",
|
||||
"printf 'private clipboard payload' >&2\nprintf 'private clipboard payload'\nexit 23",
|
||||
);
|
||||
let mut clipboard = SystemClipboard::with_commands(failed.clone(), failed);
|
||||
let error = clipboard.read().unwrap_err();
|
||||
assert!(error.contains("failed"));
|
||||
assert!(!error.contains("private clipboard payload"));
|
||||
let error = clipboard.write("private clipboard payload").unwrap_err();
|
||||
assert!(!error.contains("private clipboard payload"));
|
||||
let missing = fixture.0.join("not-an-executable");
|
||||
let mut clipboard = SystemClipboard::with_commands(missing.clone(), missing);
|
||||
assert!(clipboard.read().unwrap_err().contains("Cannot start"));
|
||||
assert!(
|
||||
clipboard
|
||||
.write("secret")
|
||||
.unwrap_err()
|
||||
.contains("Cannot start")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_stderr_does_not_block_large_writes() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(b"");
|
||||
let state = fixture.0.join("state");
|
||||
let state = format!("'{}'", state.to_str().unwrap().replace('\'', "'\\''"));
|
||||
clipboard
|
||||
.commands
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.writer
|
||||
.program = fixture.command(
|
||||
"noisy",
|
||||
&format!("/bin/dd if=/dev/zero bs=65536 count=8 >&2\nexec /bin/cat > {state}"),
|
||||
);
|
||||
let text = "λ\n".repeat(300_000);
|
||||
clipboard.write(&text).unwrap();
|
||||
assert_eq!(clipboard.read().unwrap(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_process_cleanup_kills_and_reaps_a_running_child() {
|
||||
use std::io::Read;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32;
|
||||
}
|
||||
|
||||
let fixture = Fixture::new();
|
||||
let hung = fixture.command("running", "printf R\nwhile :; do :; done");
|
||||
let mut command = Command::new(hung);
|
||||
command
|
||||
.process_group(0)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let mut child = command.spawn().unwrap();
|
||||
let pid = child.id() as i32;
|
||||
let mut ready = [0];
|
||||
child
|
||||
.stdout
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_exact(&mut ready)
|
||||
.unwrap();
|
||||
assert_eq!(ready, [b'R']);
|
||||
drop(ClipboardProcess(Some(child)));
|
||||
let mut status = 0;
|
||||
// SAFETY: waitpid's output pointer is valid; WNOHANG cannot block this check.
|
||||
assert_eq!(unsafe { waitpid(pid, &mut status, 1) }, -1);
|
||||
assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_injected_timeout_terminates_nonterminating_commands() {
|
||||
let fixture = Fixture::new();
|
||||
let hung = fixture.command("hung", "while :; do :; done");
|
||||
let mut clipboard = SystemClipboard::with_commands(hung.clone(), hung);
|
||||
// No assertion depends on wall-clock speed or a deadline remaining in the future.
|
||||
clipboard.timeout = Duration::ZERO;
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard command timed out"
|
||||
);
|
||||
assert_eq!(
|
||||
clipboard.write("text").unwrap_err(),
|
||||
"System clipboard command timed out"
|
||||
);
|
||||
}
|
||||
}
|
||||
#[path = "../tests/unit/clipboard.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
use crate::editor::Mode;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct CursorConfig {
|
||||
pub(crate) mode_colors: bool,
|
||||
pub(crate) normal: CursorShape,
|
||||
pub(crate) insert: CursorShape,
|
||||
pub(crate) command: CursorShape,
|
||||
pub(crate) search: CursorShape,
|
||||
pub(crate) visual: CursorShape,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum CursorShape {
|
||||
Block,
|
||||
Bar,
|
||||
Underline,
|
||||
}
|
||||
|
||||
impl Default for CursorConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode_colors: true,
|
||||
normal: CursorShape::Block,
|
||||
insert: CursorShape::Block,
|
||||
command: CursorShape::Block,
|
||||
search: CursorShape::Block,
|
||||
visual: CursorShape::Block,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CursorConfig {
|
||||
pub(crate) fn shape(self, mode: Mode) -> CursorShape {
|
||||
match mode {
|
||||
Mode::Normal => self.normal,
|
||||
Mode::Insert => self.insert,
|
||||
Mode::Command => self.command,
|
||||
Mode::Search => self.search,
|
||||
Mode::Visual => self.visual,
|
||||
}
|
||||
}
|
||||
}
|
||||
+3660
File diff suppressed because it is too large
Load Diff
+10314
-6582
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+435
-699
File diff suppressed because it is too large
Load Diff
+1268
File diff suppressed because it is too large
Load Diff
+460
@@ -0,0 +1,460 @@
|
||||
//! Read-only source-line changes against Git HEAD or a single Jujutsu @- parent.
|
||||
use crate::{
|
||||
blame::{git, git_without_literal_pathspecs, run, run_status},
|
||||
diff::line_hunks,
|
||||
editor::normalize_newlines,
|
||||
repository::{
|
||||
WorkingFileChange, WorkingFileReader, jj_command, jj_file_pattern, safe_path, store_for_jj,
|
||||
},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
};
|
||||
|
||||
pub(crate) const FILE_LIMIT: usize = 16 * 1024 * 1024;
|
||||
const BATCH_LIMIT: usize = 64 * 1024 * 1024;
|
||||
const FILE_COUNT_LIMIT: usize = 1024;
|
||||
type Files = Vec<(usize, PathBuf, Arc<str>)>;
|
||||
type FileResult = Result<Vec<Option<Change>>, String>;
|
||||
pub(crate) type ResultBatch = Vec<(usize, FileResult)>;
|
||||
type PickerRequest = (PathBuf, Vec<(PathBuf, Arc<str>)>);
|
||||
type Request = (u64, u64, Files, Option<PickerRequest>);
|
||||
|
||||
pub(crate) struct PickerChanges {
|
||||
pub(crate) root: PathBuf,
|
||||
pub(crate) result: Result<Vec<WorkingFileChange>, String>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GutterStyle {
|
||||
#[default]
|
||||
Bar,
|
||||
Symbols,
|
||||
LineNumbers,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum Change {
|
||||
Added,
|
||||
Removed,
|
||||
Modified,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
request: Option<Request>,
|
||||
result: Option<(u64, ResultBatch, Option<PickerChanges>)>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
generation: AtomicU64,
|
||||
stopped: AtomicBool,
|
||||
}
|
||||
pub(crate) struct Worker {
|
||||
shared: Arc<Shared>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
impl Worker {
|
||||
pub(crate) fn start() -> io::Result<Self> {
|
||||
let shared = Arc::new(Shared::default());
|
||||
let worker = Arc::clone(&shared);
|
||||
let thread = thread::Builder::new()
|
||||
.name("vamp-gutter".into())
|
||||
.spawn(move || {
|
||||
let mut picker_reader = WorkingFileReader::default();
|
||||
loop {
|
||||
let Ok(mut state) = worker.state.lock() else {
|
||||
return;
|
||||
};
|
||||
while state.request.is_none() && !worker.stopped.load(Ordering::Acquire) {
|
||||
let Ok(next) = worker.wake.wait(state) else {
|
||||
return;
|
||||
};
|
||||
state = next;
|
||||
}
|
||||
if worker.stopped.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let (generation, id, files, picker) = state.request.take().unwrap();
|
||||
drop(state);
|
||||
let cancelled = || {
|
||||
worker.stopped.load(Ordering::Acquire)
|
||||
|| worker.generation.load(Ordering::Acquire) != generation
|
||||
};
|
||||
let mut results = Vec::with_capacity(files.len());
|
||||
for (buffer, path, contents) in files {
|
||||
if cancelled() {
|
||||
break;
|
||||
}
|
||||
results.push((buffer, read_file(&path, &contents, &cancelled)));
|
||||
}
|
||||
let picker = picker.map(|(root, buffers)| PickerChanges {
|
||||
result: picker_reader.read(&root, &buffers, &cancelled),
|
||||
root,
|
||||
});
|
||||
let Ok(mut state) = worker.state.lock() else {
|
||||
return;
|
||||
};
|
||||
if !cancelled() {
|
||||
state.result = Some((id, results, picker));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
shared,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn request(
|
||||
&mut self,
|
||||
id: u64,
|
||||
files: Files,
|
||||
picker: Option<PickerRequest>,
|
||||
) -> io::Result<()> {
|
||||
let size = files.iter().try_fold(0usize, |size, (_, path, text)| {
|
||||
size.checked_add(text.len())?
|
||||
.checked_add(path.as_os_str().len())
|
||||
});
|
||||
let picker_size = picker.as_ref().map_or(Some(0), |(root, buffers)| {
|
||||
buffers
|
||||
.iter()
|
||||
.try_fold(root.as_os_str().len(), |size, (path, text)| {
|
||||
size.checked_add(text.len())?
|
||||
.checked_add(path.as_os_str().len())
|
||||
})
|
||||
});
|
||||
let count = files.len() + picker.as_ref().map_or(0, |(_, buffers)| buffers.len());
|
||||
if count > FILE_COUNT_LIMIT
|
||||
|| size
|
||||
.zip(picker_size)
|
||||
.and_then(|(files, picker)| files.checked_add(picker))
|
||||
.is_none_or(|size| size > BATCH_LIMIT)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Gutter batch exceeds 64 MiB or 1024 files",
|
||||
));
|
||||
}
|
||||
let mut state = self
|
||||
.shared
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("Gutter worker stopped"))?;
|
||||
let generation = self
|
||||
.shared
|
||||
.generation
|
||||
.fetch_add(1, Ordering::AcqRel)
|
||||
.wrapping_add(1);
|
||||
state.request = Some((generation, id, files, picker));
|
||||
state.result = None;
|
||||
self.shared.wake.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self) -> Option<(u64, ResultBatch, Option<PickerChanges>)> {
|
||||
self.shared.state.lock().ok()?.result.take()
|
||||
}
|
||||
}
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
let state = self.shared.state.lock();
|
||||
self.shared.stopped.store(true, Ordering::Release);
|
||||
self.shared.wake.notify_one();
|
||||
drop(state);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn checked(command: Command, cancelled: &dyn Fn() -> bool) -> Result<Vec<u8>, String> {
|
||||
run(command, &[], cancelled)?.ok_or_else(|| "Cannot read gutter repository metadata".into())
|
||||
}
|
||||
|
||||
fn read_file(path: &Path, contents: &str, cancelled: &dyn Fn() -> bool) -> FileResult {
|
||||
if contents.len() > FILE_LIMIT {
|
||||
return Err("Gutter file exceeds 16 MiB".into());
|
||||
}
|
||||
if contents.as_bytes().contains(&0) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) if !metadata.file_type().is_file() => return Ok(vec![]),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
// Check the lexical path before canonicalizing: metadata files and symlinked parents
|
||||
// must not acquire the markers of their target outside the checkout.
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|e| e.to_string())?
|
||||
.join(path)
|
||||
};
|
||||
if absolute
|
||||
.components()
|
||||
.any(|part| part.as_os_str() == ".git" || part.as_os_str() == ".jj")
|
||||
{
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let Some(root) = absolute.parent().and_then(|parent| {
|
||||
parent
|
||||
.ancestors()
|
||||
.find(|root| root.join(".jj").exists() || root.join(".git").exists())
|
||||
}) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
if absolute
|
||||
.ancestors()
|
||||
.take_while(|part| *part != root)
|
||||
.any(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| metadata.file_type().is_symlink())
|
||||
})
|
||||
{
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let relative = absolute.strip_prefix(root).map_err(|e| e.to_string())?;
|
||||
if safe_path(relative).is_err() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
// Resolve ancestors above the checkout, preserving a missing named-buffer tail.
|
||||
let root = fs::canonicalize(root).map_err(|e| e.to_string())?;
|
||||
let baseline = if root.join(".jj").exists() {
|
||||
jj_baseline(&root, relative, cancelled)?
|
||||
} else {
|
||||
git_baseline(&root, relative, cancelled)?
|
||||
};
|
||||
let Some(baseline) = baseline else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
if baseline.contains(&0) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let Ok(baseline) = std::str::from_utf8(&baseline) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
if cancelled() {
|
||||
return Err("Gutter cancelled".into());
|
||||
}
|
||||
Ok(changes(baseline, contents))
|
||||
}
|
||||
|
||||
fn eligible(
|
||||
root: &Path,
|
||||
relative: &Path,
|
||||
store: Option<&Path>,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<bool, String> {
|
||||
let command = |literal_pathspecs| {
|
||||
let mut command = if literal_pathspecs {
|
||||
git(root)
|
||||
} else {
|
||||
git_without_literal_pathspecs(root)
|
||||
};
|
||||
if let Some(store) = store {
|
||||
command
|
||||
.arg("--git-dir")
|
||||
.arg(store)
|
||||
.arg("--work-tree")
|
||||
.arg(root);
|
||||
}
|
||||
command
|
||||
};
|
||||
let mut tracked = command(true);
|
||||
tracked
|
||||
.args(["ls-files", "--cached", "-z", "--"])
|
||||
.arg(relative);
|
||||
let bytes = checked(tracked, cancelled)?;
|
||||
if bytes
|
||||
.split(|byte| *byte == 0)
|
||||
.any(|entry| entry == relative.as_os_str().as_encoded_bytes())
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let mut ignored = command(false);
|
||||
ignored
|
||||
.args(["check-ignore", "--no-index", "-q", "--"])
|
||||
.arg(relative);
|
||||
match run_status(ignored, &[], cancelled)?.0 {
|
||||
Some(0) => Ok(false),
|
||||
Some(1) => Ok(true),
|
||||
_ => Err("Cannot read gutter ignore rules".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn git_baseline(
|
||||
root: &Path,
|
||||
relative: &Path,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Option<Vec<u8>>, String> {
|
||||
let mut head = git(root);
|
||||
head.args(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
|
||||
let (code, head) = run_status(head, &[], cancelled)?;
|
||||
if code == Some(1) {
|
||||
// An unborn repository still has an index and ignore rules.
|
||||
return Ok(eligible(root, relative, None, cancelled)?.then(Vec::new));
|
||||
}
|
||||
if code != Some(0) {
|
||||
return Err("Cannot resolve Git gutter HEAD".into());
|
||||
}
|
||||
let head = std::str::from_utf8(&head)
|
||||
.map_err(|_| "Invalid Git gutter HEAD")?
|
||||
.trim();
|
||||
let mut tree = git(root);
|
||||
tree.args(["ls-tree", "-z", "--full-tree", head, "--"])
|
||||
.arg(relative);
|
||||
let entries = checked(tree, cancelled)?;
|
||||
let Some(entry) = entries
|
||||
.split(|byte| *byte == 0)
|
||||
.find(|entry| !entry.is_empty())
|
||||
else {
|
||||
return Ok(eligible(root, relative, None, cancelled)?.then(Vec::new));
|
||||
};
|
||||
let tab = entry
|
||||
.iter()
|
||||
.position(|byte| *byte == b'\t')
|
||||
.ok_or("Invalid Git gutter tree")?;
|
||||
if &entry[tab + 1..] != relative.as_os_str().as_encoded_bytes() {
|
||||
return Err("Unexpected Git gutter path".into());
|
||||
}
|
||||
let fields = std::str::from_utf8(&entry[..tab]).map_err(|_| "Invalid Git gutter tree")?;
|
||||
let mut fields = fields.split(' ');
|
||||
if !matches!(fields.next(), Some("100644" | "100755")) || fields.next() != Some("blob") {
|
||||
return Ok(None);
|
||||
}
|
||||
let object = fields.next().ok_or("Missing Git gutter blob")?;
|
||||
let mut cat = git(root);
|
||||
cat.args(["cat-file", "blob", object]);
|
||||
checked(cat, cancelled).map(Some)
|
||||
}
|
||||
|
||||
fn jj_file_kind(
|
||||
root: &Path,
|
||||
revision: &str,
|
||||
pattern: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Option<String>, String> {
|
||||
let mut command = jj_command(root);
|
||||
command.args([
|
||||
"file",
|
||||
"list",
|
||||
"-r",
|
||||
revision,
|
||||
"-T",
|
||||
"json(file_type) ++ \"\\n\"",
|
||||
"--",
|
||||
pattern,
|
||||
]);
|
||||
let bytes = checked(command, cancelled)?;
|
||||
if bytes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let kind =
|
||||
serde_json::from_slice(&bytes).map_err(|_| "Invalid Jujutsu gutter file metadata")?;
|
||||
Ok(Some(kind))
|
||||
}
|
||||
|
||||
fn jj_baseline(
|
||||
root: &Path,
|
||||
relative: &Path,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Option<Vec<u8>>, String> {
|
||||
let Ok(store) = store_for_jj(root) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(path) = relative.to_str() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut parents = jj_command(root);
|
||||
parents.args([
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
"commit_id ++ \"\\n\"",
|
||||
]);
|
||||
let bytes = checked(parents, cancelled)?;
|
||||
let ids = std::str::from_utf8(&bytes).map_err(|_| "Invalid Jujutsu gutter parents")?;
|
||||
let mut ids = ids.lines();
|
||||
let Some(parent) = ids.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// ponytail: no merged-parent materializer exists here; hide markers on merges
|
||||
// rather than report changes against an arbitrary first parent.
|
||||
if ids.next().is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let pattern = jj_file_pattern(path);
|
||||
let baseline_kind = if parent.bytes().all(|byte| byte == b'0') {
|
||||
None
|
||||
} else {
|
||||
jj_file_kind(root, parent, &pattern, cancelled)?
|
||||
};
|
||||
if let Some(kind) = baseline_kind {
|
||||
if !matches!(kind.as_str(), "file" | "conflict") {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut show = jj_command(root);
|
||||
show.args(["file", "show", "-r", parent, "-T", "", "--", &pattern]);
|
||||
return checked(show, cancelled).map(Some);
|
||||
}
|
||||
if let Some(kind) = jj_file_kind(root, "@", &pattern, cancelled)? {
|
||||
return Ok(matches!(kind.as_str(), "file" | "conflict").then(Vec::new));
|
||||
}
|
||||
Ok(eligible(root, relative, Some(&store), cancelled)?.then(Vec::new))
|
||||
}
|
||||
|
||||
fn changes(before: &str, after: &str) -> Vec<Option<Change>> {
|
||||
fn source(text: &str) -> (Vec<String>, bool) {
|
||||
(
|
||||
text.split_terminator('\n').map(str::to_owned).collect(),
|
||||
text.ends_with('\n'),
|
||||
)
|
||||
}
|
||||
let before = normalize_newlines(before);
|
||||
let after = normalize_newlines(after);
|
||||
if before == after {
|
||||
return vec![None; after.split('\n').count()];
|
||||
}
|
||||
let (before, before_eof) = source(&before);
|
||||
let (after_lines, after_eof) = source(&after);
|
||||
let mut markers = vec![None; after.split('\n').count()];
|
||||
for hunk in line_hunks(&before, before_eof, &after_lines, after_eof) {
|
||||
if hunk.after_len == 0 {
|
||||
let anchor = hunk.after_start.min(markers.len() - 1);
|
||||
// A deletion sharing a row with a replacement remains modified.
|
||||
if markers[anchor].is_none() {
|
||||
markers[anchor] = Some(Change::Removed);
|
||||
}
|
||||
} else {
|
||||
for offset in 0..hunk.after_len {
|
||||
markers[hunk.after_start + offset] = Some(if offset < hunk.before_len {
|
||||
Change::Modified
|
||||
} else {
|
||||
Change::Added
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
markers
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "../tests/unit/gutter.rs"]
|
||||
mod tests;
|
||||
+18
@@ -1,10 +1,28 @@
|
||||
mod battery;
|
||||
mod blame;
|
||||
pub mod chrome;
|
||||
pub mod clipboard;
|
||||
pub(crate) mod cursor;
|
||||
pub mod diff;
|
||||
pub mod editor;
|
||||
pub mod files;
|
||||
mod forge;
|
||||
pub mod gutter;
|
||||
pub mod lsp;
|
||||
mod lsp_config;
|
||||
mod markdown;
|
||||
pub mod panes;
|
||||
pub mod plugin;
|
||||
mod pull_request_preferences;
|
||||
mod pull_requests;
|
||||
pub mod repository;
|
||||
pub mod resolve;
|
||||
pub mod review;
|
||||
pub mod ruby;
|
||||
pub mod session;
|
||||
mod shell;
|
||||
mod snippet;
|
||||
pub mod syntax;
|
||||
mod terminal_colors;
|
||||
pub mod tui;
|
||||
mod wrap;
|
||||
|
||||
+1219
-246
File diff suppressed because it is too large
Load Diff
+116
-38
@@ -10,10 +10,11 @@ pub fn resolve(value: Value) -> Result<Vec<ServerConfig>, String> {
|
||||
if language_id.is_empty() || language_id.chars().any(char::is_control) {
|
||||
return Err("LSP language keys must not be empty or contain control characters".into());
|
||||
}
|
||||
let preset: Option<(&[&str], &str)> = match language_id.as_str() {
|
||||
"rust" => Some((&["rust-analyzer"], "rs")),
|
||||
"python" => Some((&["pylsp"], "py")),
|
||||
"ruby" => Some((&["solargraph", "stdio"], "rb")),
|
||||
let preset: Option<(&[&[&str]], &str)> = match language_id.as_str() {
|
||||
crate::syntax::RUST_ID => Some((&[&["rust-analyzer"]], "rs")),
|
||||
crate::syntax::PYTHON_ID => Some((&[&["ty", "server"], &["ruff", "server"]], "py")),
|
||||
crate::syntax::RUBY_ID => Some((&[&["solargraph", "stdio"]], "rb")),
|
||||
crate::syntax::TYPST_ID => Some((&[&["tinymist", "lsp"]], "typ")),
|
||||
_ => None,
|
||||
};
|
||||
let mut options = match value {
|
||||
@@ -36,55 +37,134 @@ pub fn resolve(value: Value) -> Result<Vec<ServerConfig>, String> {
|
||||
for key in options.keys() {
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"command" | "extensions" | "initialization_options" | "settings"
|
||||
"command" | "extensions" | "initialization_options" | "settings" | "servers"
|
||||
) {
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} has unknown option {key:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
let command = match options.remove("command") {
|
||||
Some(value) => command(value, &language_id)?,
|
||||
None => match preset {
|
||||
Some((command, _)) => command.iter().map(|argument| (*argument).into()).collect(),
|
||||
None => {
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} requires command argv"
|
||||
));
|
||||
}
|
||||
},
|
||||
};
|
||||
let extensions = match options.remove("extensions") {
|
||||
let mut extensions = match options.remove("extensions") {
|
||||
Some(value) => extensions(value, &language_id)?,
|
||||
None => match preset {
|
||||
Some((_, extension)) => vec![extension.into()],
|
||||
None => return Err(format!("LSP language {language_id:?} requires extensions")),
|
||||
},
|
||||
};
|
||||
let initialization_options = object(
|
||||
options.remove("initialization_options"),
|
||||
&language_id,
|
||||
"initialization_options",
|
||||
)?;
|
||||
let settings = object(options.remove("settings"), &language_id, "settings")?;
|
||||
servers.push(ServerConfig {
|
||||
language_id,
|
||||
command,
|
||||
extensions,
|
||||
initialization_options,
|
||||
settings,
|
||||
});
|
||||
if servers.len() > 16 {
|
||||
return Err("LSP configuration supports at most 16 enabled languages".into());
|
||||
let explicit_servers = options.contains_key("servers");
|
||||
let configurations = match options.remove("servers") {
|
||||
Some(value) => {
|
||||
if ["command", "initialization_options", "settings"]
|
||||
.iter()
|
||||
.any(|key| options.contains_key(*key))
|
||||
{
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} servers cannot be combined with command, initialization_options, or settings"
|
||||
));
|
||||
}
|
||||
let Value::Array(configurations) = value else {
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} servers must be a nonempty array of configuration objects"
|
||||
));
|
||||
};
|
||||
if configurations.is_empty() {
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} servers must be a nonempty array of configuration objects"
|
||||
));
|
||||
}
|
||||
configurations
|
||||
}
|
||||
None if options.contains_key("command") => vec![Value::Object(options)],
|
||||
None => {
|
||||
let Some((commands, _)) = preset else {
|
||||
return Err(format!(
|
||||
"LSP language {language_id:?} requires command argv or servers"
|
||||
));
|
||||
};
|
||||
let mut configurations = Vec::with_capacity(commands.len());
|
||||
for (index, command) in commands.iter().enumerate() {
|
||||
let mut configuration = if index + 1 == commands.len() {
|
||||
std::mem::take(&mut options)
|
||||
} else {
|
||||
options.clone()
|
||||
};
|
||||
configuration.insert(
|
||||
"command".into(),
|
||||
Value::Array(
|
||||
command
|
||||
.iter()
|
||||
.map(|argument| Value::from(*argument))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
if language_id == "python" && index == 0 {
|
||||
configuration
|
||||
.entry("initialization_options")
|
||||
.or_insert_with(
|
||||
|| serde_json::json!({"experimental": {"useUv": "off"}}),
|
||||
);
|
||||
}
|
||||
configurations.push(Value::Object(configuration));
|
||||
}
|
||||
configurations
|
||||
}
|
||||
};
|
||||
if servers.len() + configurations.len() > 16 {
|
||||
return Err("LSP configuration supports at most 16 configured servers".into());
|
||||
}
|
||||
let configuration_count = configurations.len();
|
||||
let mut language_id = language_id;
|
||||
for (index, configuration) in configurations.into_iter().enumerate() {
|
||||
let context = if explicit_servers {
|
||||
format!("LSP language {language_id:?} servers[{index}]")
|
||||
} else {
|
||||
format!("LSP language {language_id:?}")
|
||||
};
|
||||
let Value::Object(mut configuration) = configuration else {
|
||||
return Err(format!("{context} must be a configuration object"));
|
||||
};
|
||||
for key in configuration.keys() {
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"command" | "initialization_options" | "settings"
|
||||
) {
|
||||
return Err(format!("{context} has unknown option {key:?}"));
|
||||
}
|
||||
}
|
||||
let command = match configuration.remove("command") {
|
||||
Some(value) => command(value, &context)?,
|
||||
None => return Err(format!("{context} requires command argv")),
|
||||
};
|
||||
let initialization_options = object(
|
||||
configuration.remove("initialization_options"),
|
||||
&context,
|
||||
"initialization_options",
|
||||
)?;
|
||||
let settings = object(configuration.remove("settings"), &context, "settings")?;
|
||||
servers.push(ServerConfig {
|
||||
language_id: if index + 1 == configuration_count {
|
||||
std::mem::take(&mut language_id)
|
||||
} else {
|
||||
language_id.clone()
|
||||
},
|
||||
command,
|
||||
extensions: if index + 1 == configuration_count {
|
||||
std::mem::take(&mut extensions)
|
||||
} else {
|
||||
extensions.clone()
|
||||
},
|
||||
initialization_options,
|
||||
settings,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(servers)
|
||||
}
|
||||
|
||||
fn command(value: Value, language: &str) -> Result<Vec<String>, String> {
|
||||
fn command(value: Value, context: &str) -> Result<Vec<String>, String> {
|
||||
let error = || {
|
||||
format!(
|
||||
"LSP language {language:?} command must be nonempty argv with a nonempty executable and no NUL bytes"
|
||||
"{context} command must be nonempty argv with a nonempty executable and no NUL bytes"
|
||||
)
|
||||
};
|
||||
let Value::Array(values) = value else {
|
||||
@@ -137,12 +217,10 @@ fn extensions(value: Value, language: &str) -> Result<Vec<String>, String> {
|
||||
Ok(extensions)
|
||||
}
|
||||
|
||||
fn object(value: Option<Value>, language: &str, option: &str) -> Result<Value, String> {
|
||||
fn object(value: Option<Value>, context: &str, option: &str) -> Result<Value, String> {
|
||||
match value {
|
||||
None => Ok(Value::Object(serde_json::Map::new())),
|
||||
Some(value) if value.is_object() => Ok(value),
|
||||
Some(_) => Err(format!(
|
||||
"LSP language {language:?} {option} must be a JSON object"
|
||||
)),
|
||||
Some(_) => Err(format!("{context} {option} must be a JSON object")),
|
||||
}
|
||||
}
|
||||
|
||||
+185
-20
@@ -1,64 +1,171 @@
|
||||
use std::{env, path::PathBuf};
|
||||
use std::{env, io, path::PathBuf};
|
||||
|
||||
use vamp::{session::EditorSession, tui};
|
||||
|
||||
mod review_cli;
|
||||
|
||||
// Only the first argument can be this process-to-process terminal handoff marker.
|
||||
const INHERITED_SCREEN: &str = "--vamp-inherit-alternate-screen";
|
||||
|
||||
const HELP: &str = "vamp — modal editor with isolated Ruby plugins
|
||||
|
||||
Usage: vamp [--config PATH | --no-config] [FILE]
|
||||
vamp [--config PATH | --no-config] --review list [--repo PATH] [--json]
|
||||
vamp [--config PATH | --no-config] --review show ID [--repo PATH] [--json] [--all]
|
||||
vamp [--config PATH | --no-config] --review delete REVIEW_ID COMMENT_ID [--repo PATH] [--json]
|
||||
vamp [--config PATH | --no-config] --review resolve REVIEW_ID COMMENT_ID [--repo PATH] [--json]
|
||||
|
||||
Review CLI: list/show are read-only; delete/resolve commit one comment change immediately.
|
||||
Show defaults to unresolved comments; --all includes resolved.
|
||||
Use vamp -- --review to edit a file named --review.
|
||||
|
||||
Default keys (configurable with config.bind):
|
||||
All modes: Ctrl+p command palette; type to filter, Ctrl+j/k or arrows select, Enter accept, Esc cancel
|
||||
Normal/Visual: Space is leader; Space Space opens palette; Esc cancels prefix
|
||||
Normal leader: Space w saves; Space b n/p/l/d next/previous/list/close buffer
|
||||
Normal leader: Space w saves; Space b n/p/l/d next/previous/pick/close buffer
|
||||
Files: Space o floating tree INSERT; Space e docked tree NORMAL (right by default)
|
||||
tree NORMAL: hjkl navigate; INSERT: type to filter, Ctrl+hjkl navigate; Enter toggles/opens
|
||||
i filters; Esc retains filter and returns NORMAL, then editor; Ctrl+u clears in either mode
|
||||
Ctrl+t view, Ctrl+w close, Ctrl+r refresh
|
||||
Normal: i/a insert, I/A insert at first nonblank/end, o/O new line
|
||||
h/j/k/l move, 0/$ line ends, x delete, J join lines
|
||||
h/j/k/l move, 0/$ line ends, x/Delete cut hovered graphemes, J join lines
|
||||
w/b/e word next/previous/end, W/B/E whitespace-delimited WORDs
|
||||
Normal/Visual: f<char>/F<char> seek next/previous on current line; 2fx seeks second x
|
||||
gf follows Markdown file links/reference links and heading fragments (no LSP)
|
||||
Normal/Visual: gt first line, gb last line, at first nonblank; Esc cancels g
|
||||
Normal/Visual: <line>g jumps to that one-based source line at first nonblank, clamped at EOF
|
||||
Ctrl+o older jump location; Ctrl+i newer (Tab too outside comparisons; counts supported)
|
||||
_ splits above/below, | left/right; Option/Alt+h/j/k/l focuses neighboring panes
|
||||
Ctrl+Option/Alt+h/l previous/next tab; :tab.new opens current buffer in another tab
|
||||
Normal/Visual: prefix motions with counts (5j, 2w, 3n); Esc cancels count
|
||||
u undo, U redo, : command, / search, n/N next/previous match
|
||||
Normal/Visual: Ctrl+u/d scroll up/down without moving carets; configurable distance (default half viewport), counts supported
|
||||
u undo, U redo, : command, / search, * search word, n/N next/previous match
|
||||
yy copies whole lines; dd deletes them; cc changes them and enters Insert; counts: 3yy, 2dd, 2cc
|
||||
dw/db cut forward/backward words on the current line; cw/cb cut the same spans and enter Insert
|
||||
Word counts before/after the operator multiply: d2w, 2cw, 2c3b; newlines are preserved
|
||||
Linewise p/P paste below/above the current row; characterwise p/P paste after/before the grapheme
|
||||
Normal/Visual: . repeats last native edit at current targets (one undo group)
|
||||
v select, p/P paste fragments, Ctrl+k/Ctrl+e clone above/below
|
||||
y/d/c/p/P use the system clipboard by default; config.clipboard_mode = \"separate\" isolates it
|
||||
v characterwise select, V linewise select, p/P paste fragments, Ctrl+k/Ctrl+e clone above/below
|
||||
y/d/x/c/p/P use the system clipboard by default; config.clipboard_mode = \"separate\" isolates it
|
||||
Esc keeps only the primary caret
|
||||
Visual: motions extend selections, y copy, d/x/Delete cut, c change
|
||||
Visual: motions extend selections, y copy, d/x/Delete cut, c change, p/P replace selections
|
||||
: opens command input with the selection preserved; Esc returns to that selection
|
||||
r<char> replaces every selected grapheme, preserving newlines; one undo action
|
||||
I/A insert at each selected line's first nonblank/end
|
||||
Ctrl+l split rows, Ctrl+n add occurrence, Ctrl+s skip, Ctrl+a all
|
||||
v/Esc returns to Normal retaining carets
|
||||
Insert: Esc returns to Normal retaining carets
|
||||
Search: Enter finds next literal match, Esc cancels (case-sensitive, wraps)
|
||||
Commands: :w [PATH], :q, :q!, :wq [PATH], :plugins, :PLUGIN [ARGS]
|
||||
Buffers: :edit PATH, :buffers, :buffer N, :bnext, :bprev, :bdelete[!] [N]
|
||||
:q refuses any dirty buffer; :wq saves active and quits only if all are clean
|
||||
v/V switches selection shape; same selector or Esc cancels retaining carets
|
||||
Insert: Ctrl+n requests LSP completion at primary caret, then cycles next; Ctrl+j/k next/previous
|
||||
Candidates replace text live; Original text restores it; other keys close and act normally
|
||||
Snippets expand fully: type replaces argument, Tab/Shift+Tab next/previous, final $0 ends
|
||||
Outside snippets Enter inserts newline, Tab inserts a tab or configured spaces; Esc returns to Normal
|
||||
Insert/Command/Search: Ctrl+u deletes backward to the logical line start
|
||||
Command/Search: Up/Ctrl+k older history; Down/Ctrl+j newer history or unfinished input; Enter submits
|
||||
Command: Tab/Shift+Tab completes command names and cycles forward/backward with wraparound (not arguments)
|
||||
Search: Enter accepts current/next literal match, Esc cancels (case-sensitive, wraps)
|
||||
Commands: :save [PATH], :force_save [PATH], :quit, :force_quit,
|
||||
:save_and_quit [PATH], :force_save_and_quit [PATH], :plugins, :PLUGIN [ARGS]
|
||||
Shell: :!COMMAND runs asynchronously in the project directory using $SHELL (or /bin/sh)
|
||||
Pending command/spinner in top bar; output/exit status in floating window; Enter/Esc closes
|
||||
Aliases: :w=save, :w!=force_save, :q=quit, :q!=force_quit,
|
||||
:wq=save_and_quit, :wq!=force_save_and_quit
|
||||
Save actions: core.save, core.force_save, core.save_and_quit, core.force_save_and_quit
|
||||
Normal saves recheck LF-normalized disk text; external changes/deletion require force
|
||||
Force never bypasses snapshot read-only, symlink, or another-buffer path protection
|
||||
Clean live buffers reload on 250ms metadata checks, including inactive tabs/panes
|
||||
Reload preserves/clamps views and clears stale undo/redo; snapshots never reload
|
||||
Dirty buffers keep edits; missing/unreadable/invalid changed files keep text and warn
|
||||
Buffers: :edit PATH, :buffers, :buffer N, :buffer_next, :buffer_previous, :buffer_delete [N], :buffer_force_delete [N]
|
||||
:buffers / Space b l searches IDs/paths; Enter switches, Esc/Ctrl+p cancels, Ctrl+u clears
|
||||
Aliases: bnext, bprev, bdelete, bdelete!; arguments and safety rules are unchanged
|
||||
:quit refuses any dirty buffer; both save-and-quit commands require all buffers clean
|
||||
Restart: :restart closes clean buffers; unsaved buffers remain open and block restart with a warning
|
||||
:force_restart / :restart! discards unsaved text without writing
|
||||
Actions: core.restart, core.force_restart (no default binding)
|
||||
Relaunches the executable with original CLI args/config/startup file; tabs/views reset
|
||||
Tabs: :tab.new, :tab.previous, :tab.next, :tab.close, :tab.force_close
|
||||
Tabs retain pane layouts and independent views; close protects exclusively displayed unsaved edits
|
||||
Markdown links: :follow_link (primary caret; local files only)
|
||||
Diff: :diff (Normal); floating revision/bookmark lists; choose Before then After; Before marked inline
|
||||
Before and historical/remote After stay read-only; Tab/Shift+Tab categories/Normal focus
|
||||
All text panes use native motions, selections and copy; read-only panes reject edits/saves
|
||||
Switching Before/After preserves the aligned cursor row and display column
|
||||
Selector queries own printable keys, including :; text navigation skips omitted lines
|
||||
Normal [/] explicitly expands context; Insert brackets remain literal text
|
||||
Normal Space v cycles split/unified; Space s flips left/right vs above/below split
|
||||
Defaults: config.diff_view_mode = \"split\"; config.diff_split_orientation = \"vertical\"
|
||||
Follow checkout After edits live buffers and follows descendants; config.diff_follow_working_copy = false disables following
|
||||
Esc closes Before/After selectors; :diff.close exits an opened comparison explicitly
|
||||
Remote refs/history load into temporary comparison repos without changing active refs/checkout
|
||||
Changed files: normal picker/explorer bindings, Ctrl+w close; A/M/D/R status and rename paths
|
||||
Local reviews: :comment anchors exact Visual text, Visual Line rows, or the current line
|
||||
Works in ordinary repository source buffers and diff text panes
|
||||
Different resolved Before/After pairs select separate reviews; reopening a pair resumes its review
|
||||
Working refreshes retain the active review; ordinary source reviews stay separate
|
||||
Selected comments highlight their precise text
|
||||
:review.edit/delete [ID], :review.next/previous, :review.overview
|
||||
:review.summary; :review.verdict looks_good|changes_requested|none
|
||||
:review.copy copies all saved comments in CLI format using the configured clipboard
|
||||
:w saves comment/summary text, including hidden drafts; verdicts/deletions commit immediately
|
||||
:review.save PATH exports JSON; :review.open [ID|PATH] selects/imports; :review.new
|
||||
Normal Esc or :pane.close discards unsaved text and dismisses the floating editor
|
||||
Snapshot anchors stay immutable; stale comments lose gutter markers; no publishing
|
||||
Pull requests: :pull_requests [REMOTE]; GitHub/GitLab/Gitea Open/Closed/Drafts/All tabs, type to search
|
||||
Enter opens the immutable PR head against its merge base; API auth uses provider tokens or gh/glab
|
||||
🙏 marks a personal review request; 👍 marks your active approval (API account)
|
||||
Ctrl+s sort menu: 1-4 precedence, Backspace clear, Left/Right date direction
|
||||
Ctrl+f filter menu: Space includes/excludes personal review states; Enter applies, Esc cancels
|
||||
Sorting persists; filters last for this session; config.pull_request_sort / config.pull_request_filters set startup choices
|
||||
Symbols: config.pull_request_review_requested_symbol / config.pull_request_approved_symbol
|
||||
Resolve jj conflicts: :resolve opens the current working-copy conflicts in a dedicated workspace
|
||||
Editable marker-free Draft vs readonly Alternative; :resolve.history shows inputs/base
|
||||
config.resolve_history_layout = \"columns\" (left/base/right) or \"base_below\" (left/right above base)
|
||||
:resolve.next/previous navigates differing hunks; :resolve.use_source [N] takes a hunk
|
||||
:resolve.source N selects Alternative; :resolve.base N selects History base
|
||||
:resolve.draft returns to Draft; :resolve.view.toggle switches Resolution/History
|
||||
:w saves and checks jj; :resolve.files toggles the explorer; :resolve.close closes cleanly
|
||||
|
||||
Ruby config: $XDG_CONFIG_HOME/vamp/config.rb or ~/.config/vamp/config.rb
|
||||
Set VAMP_RUBY to choose the Ruby executable.
|
||||
|
||||
Native LSP is disabled by default: config.lsp[\"rust\"] = true enables a preset
|
||||
Presets: rust -> rust-analyzer, python -> pylsp, ruby -> solargraph stdio
|
||||
Presets: rust -> rust-analyzer, python -> ty server + ruff server, ruby -> solargraph stdio
|
||||
typst -> tinymist lsp
|
||||
Custom languages: config.lsp[\"my-language\"] = { command: [...], extensions: [...] }
|
||||
Server stacks: config.lsp[\"python\"] = { servers: [{ command: [...] }, { command: [...] }] }
|
||||
LSP commands: :lsp.definition, :lsp.diagnostics, :lsp.hover
|
||||
Semantic highlighting: automatic when the first enabled server supports semantic tokens
|
||||
Hover binding: config.bind \"K\", config.core.lsp.hover (no default key)";
|
||||
|
||||
struct Options {
|
||||
file: Option<PathBuf>,
|
||||
config: Option<PathBuf>,
|
||||
review: Option<review_cli::Request>,
|
||||
}
|
||||
|
||||
fn options() -> Result<Option<Options>, String> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
fn options(inherited_screen: bool) -> Result<Option<Options>, String> {
|
||||
parse_options(env::args_os().skip(1 + usize::from(inherited_screen)))
|
||||
}
|
||||
|
||||
fn parse_options(
|
||||
args: impl IntoIterator<Item = std::ffi::OsString>,
|
||||
) -> Result<Option<Options>, String> {
|
||||
let mut args = args.into_iter();
|
||||
let mut file = None;
|
||||
let mut config = None;
|
||||
let mut config_selected = false;
|
||||
let mut positional = false;
|
||||
let mut review = None;
|
||||
while let Some(arg) = args.next() {
|
||||
if !positional && (arg == "--help" || arg == "-h") {
|
||||
println!("{HELP}");
|
||||
return Ok(None);
|
||||
} else if !positional && arg == "--" {
|
||||
if review.is_some() {
|
||||
return Err("unexpected review argument: --".into());
|
||||
}
|
||||
positional = true;
|
||||
} else if !positional && arg == "--review" && file.is_none() && review.is_none() {
|
||||
review = Some(review_cli::Request::parse(&mut args)?);
|
||||
} else if !positional && arg == "--config" {
|
||||
if config_selected {
|
||||
return Err("use only one of --config and --no-config".into());
|
||||
@@ -72,6 +179,8 @@ fn options() -> Result<Option<Options>, String> {
|
||||
return Err("use only one of --config and --no-config".into());
|
||||
}
|
||||
config_selected = true;
|
||||
} else if !positional && review.is_some() {
|
||||
review.as_mut().unwrap().option(&arg, &mut args)?;
|
||||
} else if !positional && arg.to_string_lossy().starts_with('-') {
|
||||
return Err(format!("unknown option: {}", arg.to_string_lossy()));
|
||||
} else if file.replace(PathBuf::from(arg)).is_some() {
|
||||
@@ -86,11 +195,32 @@ fn options() -> Result<Option<Options>, String> {
|
||||
.map(|home| home.join("vamp/config.rb"))
|
||||
.filter(|path| path.exists());
|
||||
}
|
||||
Ok(Some(Options { file, config }))
|
||||
Ok(Some(Options {
|
||||
file,
|
||||
config,
|
||||
review,
|
||||
}))
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let Some(options) = options()? else {
|
||||
let inherited_screen = env::args_os()
|
||||
.nth(1)
|
||||
.is_some_and(|arg| arg == INHERITED_SCREEN);
|
||||
let options = options(inherited_screen)?;
|
||||
if let Some(options) = &options {
|
||||
if let Some(request) = &options.review {
|
||||
return review_cli::run(request, options.config.as_deref());
|
||||
}
|
||||
}
|
||||
if options.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
tui::TerminalSession::run(inherited_screen, || run_editor(options, inherited_screen))
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn run_editor(options: Option<Options>, inherited_screen: bool) -> io::Result<()> {
|
||||
let Some(options) = options else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut session = EditorSession::open(
|
||||
@@ -98,8 +228,39 @@ fn run() -> Result<(), String> {
|
||||
tui::CAPABILITIES.iter().map(|s| (*s).to_owned()).collect(),
|
||||
options.config.as_deref(),
|
||||
)
|
||||
.map_err(|error| format!("cannot open file: {error}"))?;
|
||||
tui::run(&mut session).map_err(|error| format!("terminal error: {error}"))
|
||||
.map_err(|error| io::Error::other(format!("cannot open file: {error}")))?;
|
||||
tui::run(&mut session, inherited_screen)?;
|
||||
let restart = session.editor().should_restart();
|
||||
drop(session);
|
||||
if restart {
|
||||
tui::TerminalSession::prepare_restart()?;
|
||||
restart_editor(inherited_screen)
|
||||
.map_err(|error| io::Error::other(format!("Restart failed: {error}")))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restart_editor(inherited_screen: bool) -> io::Result<()> {
|
||||
let executable = env::current_exe()?;
|
||||
let mut command = std::process::Command::new(executable);
|
||||
command.arg(INHERITED_SCREEN);
|
||||
command.args(env::args_os().skip(1 + usize::from(inherited_screen)));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
Err(command.exec())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let status = command.status()?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(format!(
|
||||
"Restarted editor exited with {status}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -108,3 +269,7 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/cli_args.rs"]
|
||||
mod tests;
|
||||
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tree_sitter::{Node, Parser, Range, Tree};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::plugin::TextPosition;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) struct LinkTarget {
|
||||
pub path: Option<PathBuf>,
|
||||
pub fragment: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn link_at(text: &str, position: TextPosition) -> Result<LinkTarget, String> {
|
||||
let byte = position_byte(text, position)?;
|
||||
let blocks = block_tree(text)?;
|
||||
let mut node = blocks
|
||||
.root_node()
|
||||
.descendant_for_byte_range(byte, byte)
|
||||
.ok_or_else(no_link)?;
|
||||
loop {
|
||||
if node.kind() == "link_reference_definition" {
|
||||
return destination(child(node, "link_destination"), text);
|
||||
}
|
||||
if matches!(node.kind(), "inline" | "pipe_table_cell") {
|
||||
break;
|
||||
}
|
||||
node = node.parent().ok_or_else(no_link)?;
|
||||
}
|
||||
let (inline, ranges) = inline_tree(text, node)?;
|
||||
let mut node = inline
|
||||
.root_node()
|
||||
.descendant_for_byte_range(byte, byte)
|
||||
.ok_or_else(no_link)?;
|
||||
let mut link = None;
|
||||
loop {
|
||||
if !(node.start_byte() <= byte && byte < node.end_byte()) {
|
||||
return Err(no_link());
|
||||
}
|
||||
match node.kind() {
|
||||
"image" => return Err("Markdown images are not navigation links".into()),
|
||||
"uri_autolink" | "email_autolink" => {
|
||||
return Err("External Markdown URLs are not supported".into());
|
||||
}
|
||||
"inline_link"
|
||||
| "full_reference_link"
|
||||
| "collapsed_reference_link"
|
||||
| "shortcut_link" => {
|
||||
link = Some(node);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(parent) = node.parent() else { break };
|
||||
node = parent;
|
||||
}
|
||||
let link = link.ok_or_else(no_link)?;
|
||||
if link.kind() == "inline_link" {
|
||||
return destination(child(link, "link_destination"), text);
|
||||
}
|
||||
let label = reference_label(link, text, &ranges).ok_or_else(no_link)?;
|
||||
let definitions = definitions(blocks.root_node(), text);
|
||||
let target = definitions
|
||||
.get(&label)
|
||||
.ok_or_else(|| format!("Markdown reference [{label}] is not defined"))?;
|
||||
destination(Some(*target), text)
|
||||
}
|
||||
|
||||
pub(crate) fn heading_row(text: &str, fragment: &str) -> Result<usize, String> {
|
||||
if fragment.is_empty() {
|
||||
return Err("Markdown heading fragment is empty".into());
|
||||
}
|
||||
let blocks = block_tree(text)?;
|
||||
let definitions = definitions(blocks.root_node(), text);
|
||||
let mut slugs = HashMap::<String, usize>::new();
|
||||
let mut result = None;
|
||||
let mut error = None;
|
||||
walk(blocks.root_node(), |heading| {
|
||||
if result.is_some() || !matches!(heading.kind(), "atx_heading" | "setext_heading") {
|
||||
return;
|
||||
}
|
||||
let mut title = String::new();
|
||||
let mut heading_error = None;
|
||||
walk(heading, |node| {
|
||||
if node.kind() != "inline" {
|
||||
return;
|
||||
}
|
||||
match inline_tree(text, node) {
|
||||
Ok((tree, ranges)) => {
|
||||
if let Err(err) =
|
||||
visible_text(tree.root_node(), text, &ranges, &definitions, &mut title)
|
||||
{
|
||||
heading_error = Some(err);
|
||||
}
|
||||
}
|
||||
Err(err) => heading_error = Some(err),
|
||||
}
|
||||
});
|
||||
if let Some(err) = heading_error {
|
||||
error = Some(err);
|
||||
return;
|
||||
}
|
||||
// The block grammar leaves optional closing ATX hashes in the inline node.
|
||||
if heading.kind() == "atx_heading"
|
||||
&& let Some(content) = heading.child_by_field_name("heading_content")
|
||||
{
|
||||
let raw = source(content, text).trim_end();
|
||||
let without_hashes = raw.trim_end_matches('#');
|
||||
if without_hashes.len() < raw.len()
|
||||
&& without_hashes
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(char::is_whitespace)
|
||||
{
|
||||
let hashes = raw.len() - without_hashes.len();
|
||||
title.truncate(title.trim_end().len().saturating_sub(hashes));
|
||||
}
|
||||
}
|
||||
let base = slug(title.trim());
|
||||
let mut suffix = *slugs.get(&base).unwrap_or(&0);
|
||||
let mut candidate = base.clone();
|
||||
while slugs.contains_key(&candidate) {
|
||||
suffix += 1;
|
||||
candidate = format!("{base}-{suffix}");
|
||||
}
|
||||
slugs.insert(base, suffix);
|
||||
slugs.entry(candidate.clone()).or_insert(0);
|
||||
if candidate == fragment {
|
||||
result = Some(heading.start_position().row);
|
||||
}
|
||||
});
|
||||
if let Some(row) = result {
|
||||
return Ok(row);
|
||||
}
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
Err(format!("Markdown heading #{fragment} was not found"))
|
||||
}
|
||||
|
||||
fn no_link() -> String {
|
||||
"No Markdown link under the cursor".into()
|
||||
}
|
||||
|
||||
fn position_byte(text: &str, position: TextPosition) -> Result<usize, String> {
|
||||
let mut start = 0;
|
||||
for (row, line) in text.split_inclusive('\n').enumerate() {
|
||||
if row == position.row {
|
||||
let line = line.trim_end_matches(['\r', '\n']);
|
||||
return line
|
||||
.grapheme_indices(true)
|
||||
.nth(position.column)
|
||||
.map(|(offset, _)| start + offset)
|
||||
.ok_or_else(no_link);
|
||||
}
|
||||
start += line.len();
|
||||
}
|
||||
Err(no_link())
|
||||
}
|
||||
|
||||
fn block_tree(text: &str) -> Result<Tree, String> {
|
||||
let mut parser = Parser::new();
|
||||
parser
|
||||
.set_language(&tree_sitter_md::LANGUAGE.into())
|
||||
.map_err(|error| format!("Cannot load Markdown grammar: {error}"))?;
|
||||
parser
|
||||
.parse(text, None)
|
||||
.ok_or_else(|| "Cannot parse Markdown document".into())
|
||||
}
|
||||
|
||||
fn inline_tree(text: &str, node: Node<'_>) -> Result<(Tree, Vec<Range>), String> {
|
||||
let mut ranges = Vec::new();
|
||||
let mut remaining = node.range();
|
||||
let mut cursor = node.walk();
|
||||
for continuation in node.named_children(&mut cursor) {
|
||||
if continuation.kind() != "block_continuation" {
|
||||
continue;
|
||||
}
|
||||
if remaining.start_byte < continuation.start_byte() {
|
||||
ranges.push(Range {
|
||||
end_byte: continuation.start_byte(),
|
||||
end_point: continuation.start_position(),
|
||||
..remaining
|
||||
});
|
||||
}
|
||||
remaining.start_byte = continuation.end_byte();
|
||||
remaining.start_point = continuation.end_position();
|
||||
}
|
||||
if remaining.start_byte < remaining.end_byte {
|
||||
ranges.push(remaining);
|
||||
}
|
||||
let mut parser = Parser::new();
|
||||
parser
|
||||
.set_language(&tree_sitter_md::INLINE_LANGUAGE.into())
|
||||
.map_err(|error| format!("Cannot load Markdown inline grammar: {error}"))?;
|
||||
parser
|
||||
.set_included_ranges(&ranges)
|
||||
.map_err(|error| format!("Cannot parse Markdown inline ranges: {error}"))?;
|
||||
let tree = parser
|
||||
.parse(text, None)
|
||||
.ok_or_else(|| "Cannot parse Markdown inline content".to_string())?;
|
||||
Ok((tree, ranges))
|
||||
}
|
||||
|
||||
fn walk<'a>(root: Node<'a>, mut visit: impl FnMut(Node<'a>)) {
|
||||
let mut cursor = root.walk();
|
||||
loop {
|
||||
visit(cursor.node());
|
||||
if cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
while !cursor.goto_next_sibling() {
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn source<'a>(node: Node<'_>, text: &'a str) -> &'a str {
|
||||
&text[node.byte_range()]
|
||||
}
|
||||
|
||||
fn child<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
|
||||
let mut cursor = node.walk();
|
||||
node.named_children(&mut cursor)
|
||||
.find(|child| child.kind() == kind)
|
||||
}
|
||||
|
||||
fn definitions<'a>(root: Node<'a>, text: &str) -> HashMap<String, Node<'a>> {
|
||||
let mut definitions = HashMap::new();
|
||||
walk(root, |node| {
|
||||
if node.kind() == "link_reference_definition"
|
||||
&& let (Some(label), Some(destination)) =
|
||||
(child(node, "link_label"), child(node, "link_destination"))
|
||||
{
|
||||
let raw = source(label, text);
|
||||
let mut label_text = String::with_capacity(raw.len());
|
||||
let mut offset = label.start_byte() + 1;
|
||||
let mut cursor = label.walk();
|
||||
for continuation in label.named_children(&mut cursor) {
|
||||
if continuation.kind() == "block_continuation" {
|
||||
label_text.push_str(&text[offset..continuation.start_byte()]);
|
||||
offset = continuation.end_byte();
|
||||
}
|
||||
}
|
||||
label_text.push_str(&text[offset..label.end_byte() - 1]);
|
||||
definitions
|
||||
.entry(normalize_label(&label_text))
|
||||
.or_insert(destination);
|
||||
}
|
||||
});
|
||||
definitions
|
||||
}
|
||||
|
||||
fn normalize_label(label: &str) -> String {
|
||||
// Normalize Unicode case, including ß/ẞ/SS and final sigma.
|
||||
let mut normalized = String::with_capacity(label.len());
|
||||
for word in label.split_whitespace() {
|
||||
if !normalized.is_empty() {
|
||||
normalized.push(' ');
|
||||
}
|
||||
normalized.extend(
|
||||
word.chars()
|
||||
.flat_map(char::to_lowercase)
|
||||
.flat_map(char::to_uppercase),
|
||||
);
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
fn reference_label(node: Node<'_>, text: &str, ranges: &[Range]) -> Option<String> {
|
||||
let label = child(
|
||||
node,
|
||||
if node.kind() == "full_reference_link" {
|
||||
"link_label"
|
||||
} else {
|
||||
"link_text"
|
||||
},
|
||||
)?;
|
||||
let mut raw = String::new();
|
||||
let range = if node.kind() == "full_reference_link" {
|
||||
label.start_byte() + 1..label.end_byte() - 1
|
||||
} else {
|
||||
label.byte_range()
|
||||
};
|
||||
append_source(text, ranges, range, &mut raw);
|
||||
Some(normalize_label(&raw))
|
||||
}
|
||||
|
||||
fn append_source(
|
||||
text: &str,
|
||||
ranges: &[Range],
|
||||
source: std::ops::Range<usize>,
|
||||
output: &mut String,
|
||||
) {
|
||||
for range in ranges {
|
||||
let start = range.start_byte.max(source.start);
|
||||
let end = range.end_byte.min(source.end);
|
||||
if start < end {
|
||||
output.push_str(&text[start..end]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn destination(node: Option<Node<'_>>, text: &str) -> Result<LinkTarget, String> {
|
||||
let raw = node
|
||||
.map(|node| decoded_text(node, text))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let angled = node.is_some_and(|node| source(node, text).starts_with('<'));
|
||||
let raw = if angled {
|
||||
&raw[1..raw.len() - 1]
|
||||
} else {
|
||||
raw.as_str()
|
||||
};
|
||||
let (path, fragment) = raw
|
||||
.split_once('#')
|
||||
.map_or((raw, None), |(path, fragment)| (path, Some(fragment)));
|
||||
let path = percent_decode(path)?;
|
||||
let fragment = fragment.map(percent_decode).transpose()?;
|
||||
if path.starts_with("//") || path.starts_with("\\\\") || has_scheme(&path) {
|
||||
return Err("External Markdown URLs are not supported; use a local file path".into());
|
||||
}
|
||||
if path.contains('\0')
|
||||
|| fragment
|
||||
.as_ref()
|
||||
.is_some_and(|fragment| fragment.contains('\0'))
|
||||
{
|
||||
return Err("Markdown link contains a NUL character".into());
|
||||
}
|
||||
if fragment.as_deref() == Some("") {
|
||||
return Err("Markdown heading fragment is empty".into());
|
||||
}
|
||||
Ok(LinkTarget {
|
||||
path: (!path.is_empty()).then(|| PathBuf::from(path)),
|
||||
fragment,
|
||||
})
|
||||
}
|
||||
|
||||
fn has_scheme(path: &str) -> bool {
|
||||
let Some((scheme, _)) = path.split_once(':') else {
|
||||
return false;
|
||||
};
|
||||
scheme
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphabetic)
|
||||
&& scheme
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
|
||||
}
|
||||
|
||||
fn percent_decode(value: &str) -> Result<String, String> {
|
||||
if !value.contains('%') {
|
||||
return Ok(value.to_owned());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(value.len());
|
||||
let raw = value.as_bytes();
|
||||
let mut index = 0;
|
||||
while index < raw.len() {
|
||||
if raw[index] == b'%' {
|
||||
let hex = raw
|
||||
.get(index + 1..index + 3)
|
||||
.and_then(|hex| std::str::from_utf8(hex).ok())
|
||||
.and_then(|hex| u8::from_str_radix(hex, 16).ok())
|
||||
.ok_or_else(|| "Invalid percent escape in Markdown link".to_string())?;
|
||||
bytes.push(hex);
|
||||
index += 3;
|
||||
} else {
|
||||
bytes.push(raw[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| "Markdown link percent escapes are not valid UTF-8".into())
|
||||
}
|
||||
|
||||
fn append_unescaped(value: &str, result: &mut String) {
|
||||
let mut chars = value.chars().peekable();
|
||||
while let Some(character) = chars.next() {
|
||||
if character == '\\' && chars.peek().is_some_and(char::is_ascii_punctuation) {
|
||||
result.push(chars.next().unwrap());
|
||||
} else {
|
||||
result.push(character);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decoded_text(node: Node<'_>, text: &str) -> Result<String, String> {
|
||||
let mut output = String::with_capacity(node.end_byte() - node.start_byte());
|
||||
append_decoded(node, text, &mut output)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn append_decoded(node: Node<'_>, text: &str, output: &mut String) -> Result<(), String> {
|
||||
if matches!(
|
||||
node.kind(),
|
||||
"entity_reference" | "numeric_character_reference"
|
||||
) {
|
||||
return decode_entity(source(node, text), output);
|
||||
}
|
||||
let mut offset = node.start_byte();
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
append_unescaped(&text[offset..child.start_byte()], output);
|
||||
append_decoded(child, text, output)?;
|
||||
offset = child.end_byte();
|
||||
}
|
||||
append_unescaped(&text[offset..node.end_byte()], output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_entity(entity: &str, output: &mut String) -> Result<(), String> {
|
||||
let name = &entity[1..entity.len() - 1];
|
||||
let value = match name {
|
||||
"amp" | "AMP" => "&",
|
||||
"lt" | "LT" => "<",
|
||||
"gt" | "GT" => ">",
|
||||
"quot" | "QUOT" => "\"",
|
||||
"apos" => "'",
|
||||
"nbsp" | "NonBreakingSpace" => "\u{a0}",
|
||||
_ => {
|
||||
if let Some(number) = name.strip_prefix('#') {
|
||||
let (number, radix) = number
|
||||
.strip_prefix(['x', 'X'])
|
||||
.map_or((number, 10), |number| (number, 16));
|
||||
let value = u32::from_str_radix(number, radix)
|
||||
.ok()
|
||||
.filter(|value| *value != 0)
|
||||
.and_then(char::from_u32)
|
||||
.unwrap_or('\u{fffd}');
|
||||
output.push(value);
|
||||
return Ok(());
|
||||
}
|
||||
return Err(format!(
|
||||
"Unsupported Markdown HTML entity {entity}; use literal Unicode or a numeric entity"
|
||||
));
|
||||
}
|
||||
};
|
||||
output.push_str(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visible_text(
|
||||
node: Node<'_>,
|
||||
text: &str,
|
||||
ranges: &[Range],
|
||||
definitions: &HashMap<String, Node<'_>>,
|
||||
output: &mut String,
|
||||
) -> Result<(), String> {
|
||||
match node.kind() {
|
||||
"html_tag" | "link_destination" | "link_title" | "block_continuation" => return Ok(()),
|
||||
kind if kind.ends_with("_delimiter") => return Ok(()),
|
||||
"entity_reference" | "numeric_character_reference" => {
|
||||
return decode_entity(source(node, text), output);
|
||||
}
|
||||
"backslash_escape" => {
|
||||
output.push_str(
|
||||
source(node, text)
|
||||
.strip_prefix('\\')
|
||||
.unwrap_or(source(node, text)),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
"code_span" => {
|
||||
let mut raw = String::new();
|
||||
append_source(text, ranges, node.byte_range(), &mut raw);
|
||||
let delimiter = raw.bytes().take_while(|byte| *byte == b'`').count();
|
||||
let mut code = String::with_capacity(raw.len() - delimiter * 2);
|
||||
let mut chars = raw[delimiter..raw.len() - delimiter].chars().peekable();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '\r' {
|
||||
if chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
code.push(' ');
|
||||
} else {
|
||||
code.push(if ch == '\n' { ' ' } else { ch });
|
||||
}
|
||||
}
|
||||
if code.starts_with(' ') && code.ends_with(' ') && code.chars().any(|ch| ch != ' ') {
|
||||
output.push_str(&code[1..code.len() - 1]);
|
||||
} else {
|
||||
output.push_str(&code);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"inline_link" => {
|
||||
if let Some(label) = child(node, "link_text") {
|
||||
visible_text(label, text, ranges, definitions, output)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"image" => {
|
||||
let mut cursor = node.walk();
|
||||
let inline_image = node.children(&mut cursor).any(|child| child.kind() == "(");
|
||||
let label = child(node, "image_description");
|
||||
if inline_image {
|
||||
if let Some(label) = label {
|
||||
visible_text(label, text, ranges, definitions, output)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let reference = if let Some(reference) = child(node, "link_label") {
|
||||
let raw = source(reference, text);
|
||||
Some(normalize_label(&raw[1..raw.len() - 1]))
|
||||
} else {
|
||||
label.map(|label| {
|
||||
let mut raw = String::new();
|
||||
append_source(text, ranges, label.byte_range(), &mut raw);
|
||||
normalize_label(&raw)
|
||||
})
|
||||
};
|
||||
if reference.is_some_and(|label| definitions.contains_key(&label)) {
|
||||
if let Some(label) = label {
|
||||
visible_text(label, text, ranges, definitions, output)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
"full_reference_link" | "collapsed_reference_link" | "shortcut_link" => {
|
||||
if reference_label(node, text, ranges)
|
||||
.is_some_and(|label| definitions.contains_key(&label))
|
||||
{
|
||||
if let Some(label) = child(node, "link_text") {
|
||||
visible_text(label, text, ranges, definitions, output)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut offset = node.start_byte();
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
append_source(text, ranges, offset..child.start_byte(), output);
|
||||
visible_text(child, text, ranges, definitions, output)?;
|
||||
offset = child.end_byte();
|
||||
}
|
||||
append_source(text, ranges, offset..node.end_byte(), output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn slug(title: &str) -> String {
|
||||
let lower = title.to_lowercase();
|
||||
let mut slug = String::with_capacity(lower.len());
|
||||
for grapheme in lower.graphemes(true) {
|
||||
if grapheme.chars().next().is_some_and(char::is_whitespace) {
|
||||
slug.push('-');
|
||||
} else if grapheme
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|ch| ch.is_alphanumeric() || ch == '-' || ch == '_')
|
||||
{
|
||||
// Keep combining marks attached to Unicode letters, not just ASCII words.
|
||||
slug.push_str(grapheme);
|
||||
}
|
||||
}
|
||||
slug
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/markdown.rs"]
|
||||
mod tests;
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
//! Frontend-independent binary pane layout and spatial focus navigation.
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SplitAxis {
|
||||
/// Above/below.
|
||||
Horizontal,
|
||||
/// Left/right.
|
||||
Vertical,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum PaneDirection {
|
||||
Left,
|
||||
Down,
|
||||
Up,
|
||||
Right,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct PaneRect {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
pub width: u16,
|
||||
pub height: u16,
|
||||
}
|
||||
|
||||
impl PaneRect {
|
||||
fn is_empty(self) -> bool {
|
||||
self.width == 0 || self.height == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Partition a rectangle into balanced halves, with the odd cell in the second.
|
||||
pub fn split_rect(bounds: PaneRect, axis: SplitAxis) -> [PaneRect; 2] {
|
||||
let mut first = bounds;
|
||||
let mut second = bounds;
|
||||
match axis {
|
||||
SplitAxis::Horizontal => {
|
||||
first.height = bounds.height / 2;
|
||||
second.y = bounds.y.saturating_add(first.height);
|
||||
second.height -= first.height;
|
||||
}
|
||||
SplitAxis::Vertical => {
|
||||
first.width = bounds.width / 2;
|
||||
second.x = bounds.x.saturating_add(first.width);
|
||||
second.width -= first.width;
|
||||
}
|
||||
}
|
||||
[first, second]
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Node {
|
||||
Leaf(usize),
|
||||
Split {
|
||||
axis: SplitAxis,
|
||||
children: Box<[Node; 2]>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Node {
|
||||
fn contains(&self, id: usize) -> bool {
|
||||
match self {
|
||||
Self::Leaf(leaf) => *leaf == id,
|
||||
Self::Split { children, .. } => children.iter().any(|child| child.contains(id)),
|
||||
}
|
||||
}
|
||||
|
||||
fn first_id(&self) -> usize {
|
||||
match self {
|
||||
Self::Leaf(id) => *id,
|
||||
Self::Split { children, .. } => children[0].first_id(),
|
||||
}
|
||||
}
|
||||
|
||||
fn split(&mut self, id: usize, new_id: usize, axis: SplitAxis) -> bool {
|
||||
match self {
|
||||
Self::Leaf(leaf) if *leaf == id => {
|
||||
*self = Self::Split {
|
||||
axis,
|
||||
children: Box::new([Self::Leaf(id), Self::Leaf(new_id)]),
|
||||
};
|
||||
true
|
||||
}
|
||||
Self::Leaf(_) => false,
|
||||
Self::Split { children, .. } => children
|
||||
.iter_mut()
|
||||
.any(|child| child.split(id, new_id, axis)),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self, id: usize) -> Option<usize> {
|
||||
let Self::Split { children, .. } = self else {
|
||||
return None;
|
||||
};
|
||||
for index in 0..2 {
|
||||
if matches!(children[index], Self::Leaf(leaf) if leaf == id) {
|
||||
let sibling = 1 - index;
|
||||
let focus = children[sibling].first_id();
|
||||
*self = std::mem::replace(&mut children[sibling], Self::Leaf(id));
|
||||
return Some(focus);
|
||||
}
|
||||
}
|
||||
children.iter_mut().find_map(|child| child.close(id))
|
||||
}
|
||||
|
||||
fn visit_rects(&self, bounds: PaneRect, visitor: &mut impl FnMut(usize, PaneRect)) {
|
||||
if bounds.is_empty() {
|
||||
return;
|
||||
}
|
||||
match self {
|
||||
Self::Leaf(id) => visitor(*id, bounds),
|
||||
Self::Split { axis, children } => {
|
||||
let halves = split_rect(bounds, *axis);
|
||||
children[0].visit_rects(halves[0], visitor);
|
||||
children[1].visit_rects(halves[1], visitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PaneTree {
|
||||
root: Node,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl PaneTree {
|
||||
pub fn new(id: usize) -> Self {
|
||||
Self {
|
||||
root: Node::Leaf(id),
|
||||
len: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `id` first and insert `new_id` second. IDs must be unique.
|
||||
pub fn split(&mut self, id: usize, new_id: usize, axis: SplitAxis) -> bool {
|
||||
if self.contains(new_id) || !self.root.split(id, new_id, axis) {
|
||||
return false;
|
||||
}
|
||||
self.len += 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// Close a leaf and expand its sibling; return the sibling's first leaf.
|
||||
/// Unknown IDs and closing the last leaf leave the tree unchanged.
|
||||
pub fn close(&mut self, id: usize) -> Option<usize> {
|
||||
let focus = self.root.close(id)?;
|
||||
self.len -= 1;
|
||||
Some(focus)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn contains(&self, id: usize) -> bool {
|
||||
self.root.contains(id)
|
||||
}
|
||||
|
||||
/// Visit nonempty leaves in tree order, without allocating.
|
||||
pub fn visit_rects(&self, bounds: PaneRect, mut visitor: impl FnMut(usize, PaneRect)) {
|
||||
self.root.visit_rects(bounds, &mut visitor);
|
||||
}
|
||||
|
||||
pub fn neighbor(&self, id: usize, direction: PaneDirection, bounds: PaneRect) -> Option<usize> {
|
||||
let mut current = None;
|
||||
self.visit_rects(bounds, |leaf, rect| {
|
||||
if leaf == id {
|
||||
current = Some(rect);
|
||||
}
|
||||
});
|
||||
let current = current?;
|
||||
let mut best = None;
|
||||
self.visit_rects(bounds, |leaf, rect| {
|
||||
if leaf != id {
|
||||
consider_neighbor(current, direction, leaf, rect, &mut best);
|
||||
}
|
||||
});
|
||||
best.map(|(_, leaf)| leaf)
|
||||
}
|
||||
}
|
||||
|
||||
// Score: prefer perpendicular overlap, then the nearest forward edge,
|
||||
// perpendicular gap, center alignment, and finally the stable ID.
|
||||
type NeighborScore = (bool, u32, u32, u32, usize);
|
||||
|
||||
fn neighbor_score(
|
||||
current: PaneRect,
|
||||
direction: PaneDirection,
|
||||
id: usize,
|
||||
candidate: PaneRect,
|
||||
) -> Option<NeighborScore> {
|
||||
if current.is_empty() || candidate.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let edges = |rect: PaneRect| {
|
||||
let x = u32::from(rect.x);
|
||||
let y = u32::from(rect.y);
|
||||
(x, y, x + u32::from(rect.width), y + u32::from(rect.height))
|
||||
};
|
||||
let (x, y, right, bottom) = edges(current);
|
||||
let (cx, cy, cright, cbottom) = edges(candidate);
|
||||
let (distance, start, end, cstart, cend) = match direction {
|
||||
PaneDirection::Left if cright <= x => (x - cright, y, bottom, cy, cbottom),
|
||||
PaneDirection::Right if cx >= right => (cx - right, y, bottom, cy, cbottom),
|
||||
PaneDirection::Up if cbottom <= y => (y - cbottom, x, right, cx, cright),
|
||||
PaneDirection::Down if cy >= bottom => (cy - bottom, x, right, cx, cright),
|
||||
_ => return None,
|
||||
};
|
||||
let overlap = start.max(cstart) < end.min(cend);
|
||||
let gap = start.max(cstart).saturating_sub(end.min(cend));
|
||||
let alignment = (start + end).abs_diff(cstart + cend);
|
||||
Some((!overlap, distance, gap, alignment, id))
|
||||
}
|
||||
|
||||
fn consider_neighbor(
|
||||
current: PaneRect,
|
||||
direction: PaneDirection,
|
||||
id: usize,
|
||||
candidate: PaneRect,
|
||||
best: &mut Option<(NeighborScore, usize)>,
|
||||
) {
|
||||
if let Some(score) = neighbor_score(current, direction, id, candidate)
|
||||
&& best.as_ref().is_none_or(|(previous, _)| score < *previous)
|
||||
{
|
||||
*best = Some((score, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Find a forward rectangle, favoring overlap and the closest edge.
|
||||
/// Empty rectangles are ignored; ties are independent of iterator order.
|
||||
pub fn directional_neighbor(
|
||||
current: PaneRect,
|
||||
direction: PaneDirection,
|
||||
candidates: impl Iterator<Item = (usize, PaneRect)>,
|
||||
) -> Option<usize> {
|
||||
let mut best = None;
|
||||
for (id, candidate) in candidates {
|
||||
consider_neighbor(current, direction, id, candidate, &mut best);
|
||||
}
|
||||
best.map(|(_, id)| id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/panes.rs"]
|
||||
mod tests;
|
||||
+123
-2
@@ -1,4 +1,4 @@
|
||||
use std::path::PathBuf;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -36,7 +36,7 @@ pub enum DiagnosticSeverity {
|
||||
}
|
||||
|
||||
/// Zero-based extended-grapheme positions, independent of any server encoding.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, Ord, PartialEq, PartialOrd)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TextPosition {
|
||||
pub row: usize,
|
||||
@@ -52,6 +52,101 @@ pub struct Diagnostic {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Standard LSP semantic token categories, independent of frontend colors.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SemanticTokenKind {
|
||||
Namespace,
|
||||
Type,
|
||||
Class,
|
||||
Enum,
|
||||
Interface,
|
||||
Struct,
|
||||
TypeParameter,
|
||||
Parameter,
|
||||
Variable,
|
||||
Property,
|
||||
EnumMember,
|
||||
Event,
|
||||
Function,
|
||||
Method,
|
||||
Macro,
|
||||
Keyword,
|
||||
Modifier,
|
||||
Comment,
|
||||
String,
|
||||
Number,
|
||||
Regexp,
|
||||
Operator,
|
||||
Decorator,
|
||||
}
|
||||
|
||||
/// Canonical modifier bits; server legend bit positions are translated by LSP.
|
||||
#[repr(u16)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SemanticTokenModifier {
|
||||
Declaration = 1,
|
||||
Definition = 1 << 1,
|
||||
Readonly = 1 << 2,
|
||||
Static = 1 << 3,
|
||||
Deprecated = 1 << 4,
|
||||
Abstract = 1 << 5,
|
||||
Async = 1 << 6,
|
||||
Modification = 1 << 7,
|
||||
Documentation = 1 << 8,
|
||||
DefaultLibrary = 1 << 9,
|
||||
}
|
||||
|
||||
/// A single-line foreground annotation using whole extended-grapheme positions.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SemanticToken {
|
||||
pub start: TextPosition,
|
||||
pub end: TextPosition,
|
||||
pub kind: SemanticTokenKind,
|
||||
pub modifiers: u16,
|
||||
}
|
||||
|
||||
/// A completion replacement in zero-based, end-exclusive grapheme coordinates.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct CompletionEdit {
|
||||
pub start: TextPosition,
|
||||
pub end: TextPosition,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Expanded snippet tabstops, in byte offsets relative to the primary edit text.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct CompletionSnippet {
|
||||
/// Positive tabstops in ascending order, followed by the final zero tabstop.
|
||||
pub tabstops: Vec<SnippetTabstop>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct SnippetTabstop {
|
||||
pub index: u32,
|
||||
/// Repeated occurrences of the same tabstop are edited together.
|
||||
pub ranges: Vec<std::ops::Range<usize>>,
|
||||
/// Enclosing numbered stops per occurrence, outermost first; parallel to ranges.
|
||||
pub ancestors: Vec<Vec<u32>>,
|
||||
}
|
||||
|
||||
/// Protocol-independent completion text and its atomic document edits.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct CompletionItem {
|
||||
pub label: String,
|
||||
pub detail: Option<String>,
|
||||
/// Index of the primary replacement; other edits never determine caret placement.
|
||||
pub primary_edit: usize,
|
||||
pub edits: Vec<CompletionEdit>,
|
||||
pub snippet: Option<CompletionSnippet>,
|
||||
}
|
||||
|
||||
/// Native LSP range; each coordinate is (zero-based row, UTF-16 column).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Utf16Range {
|
||||
pub start: (usize, usize),
|
||||
pub end: (usize, usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum UpdateEffect {
|
||||
@@ -60,6 +155,13 @@ pub enum UpdateEffect {
|
||||
revision: u64,
|
||||
items: Vec<Diagnostic>,
|
||||
},
|
||||
#[serde(skip_deserializing)]
|
||||
SemanticTokens {
|
||||
buffer_id: usize,
|
||||
revision: u64,
|
||||
/// None clears the overlay. Immutable slices are shared without copying.
|
||||
tokens: Option<Arc<[SemanticToken]>>,
|
||||
},
|
||||
Navigate {
|
||||
buffer_id: usize,
|
||||
revision: u64,
|
||||
@@ -67,14 +169,33 @@ pub enum UpdateEffect {
|
||||
row: usize,
|
||||
column: usize,
|
||||
},
|
||||
/// Native LSP targets retain UTF-16 coordinates until their source text is resolved.
|
||||
#[serde(skip_deserializing)]
|
||||
NavigateUtf16 {
|
||||
buffer_id: usize,
|
||||
revision: u64,
|
||||
path: PathBuf,
|
||||
range: Utf16Range,
|
||||
target_range: Option<Utf16Range>,
|
||||
},
|
||||
Hover {
|
||||
buffer_id: usize,
|
||||
revision: u64,
|
||||
text: String,
|
||||
},
|
||||
#[serde(skip_deserializing)]
|
||||
Completion {
|
||||
buffer_id: usize,
|
||||
revision: u64,
|
||||
items: Vec<CompletionItem>,
|
||||
},
|
||||
Message {
|
||||
text: String,
|
||||
},
|
||||
Label {
|
||||
name: String,
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
use crate::pull_requests::{Preferences, SortSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
fs::{self, OpenOptions},
|
||||
io::{self, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
static NEXT_TEMP: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StoredPreferences<T> {
|
||||
version: u8,
|
||||
preferences: T,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StoredSort<T> {
|
||||
#[serde(default)]
|
||||
sort: T,
|
||||
// Previously saved filters are deliberately ignored, including invalid values.
|
||||
#[serde(default, rename = "filters", skip_serializing)]
|
||||
_filters: serde::de::IgnoredAny,
|
||||
}
|
||||
|
||||
pub(crate) fn default_path() -> Result<PathBuf, String> {
|
||||
path_from(
|
||||
std::env::var_os("XDG_STATE_HOME").as_deref(),
|
||||
std::env::var_os("HOME").as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
fn path_from(xdg: Option<&OsStr>, home: Option<&OsStr>) -> Result<PathBuf, String> {
|
||||
if let Some(path) = xdg.map(Path::new).filter(|path| path.is_absolute()) {
|
||||
return Ok(path.join("vamp/pull_requests.json"));
|
||||
}
|
||||
home.map(Path::new)
|
||||
.filter(|path| path.is_absolute())
|
||||
.map(|path| path.join(".local/state/vamp/pull_requests.json"))
|
||||
.ok_or_else(|| {
|
||||
"Cannot locate pull request preferences: HOME must be an absolute directory".into()
|
||||
})
|
||||
}
|
||||
|
||||
fn read_preferences(path: &Path) -> Result<Option<Preferences>, String> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.to_string()),
|
||||
Ok(metadata) if !metadata.is_file() => {
|
||||
return Err("preferences must be a regular file (not a symlink)".into());
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
let bytes = fs::read(path).map_err(|error| error.to_string())?;
|
||||
let stored: StoredPreferences<StoredSort<SortSettings>> =
|
||||
serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
|
||||
if stored.version != 1 {
|
||||
return Err(format!(
|
||||
"unsupported preferences version {}",
|
||||
stored.version
|
||||
));
|
||||
}
|
||||
let preferences = Preferences {
|
||||
sort: stored.preferences.sort,
|
||||
..Preferences::default()
|
||||
};
|
||||
preferences.validate()?;
|
||||
Ok(Some(preferences))
|
||||
}
|
||||
|
||||
pub(crate) struct Store {
|
||||
path: Option<PathBuf>,
|
||||
blocked: Option<String>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub(crate) fn load(path: Result<PathBuf, String>) -> (Self, Preferences, Option<String>) {
|
||||
let result = match &path {
|
||||
Ok(path) => read_preferences(path),
|
||||
Err(error) => Err(error.clone()),
|
||||
};
|
||||
let (preferences, blocked) = match result {
|
||||
Ok(preferences) => (preferences.unwrap_or_default(), None),
|
||||
Err(error) => (Preferences::default(), Some(error)),
|
||||
};
|
||||
let store = Self {
|
||||
path: path.ok(),
|
||||
blocked,
|
||||
};
|
||||
let notice = store.blocked.as_ref().map(|error| store.notice(error));
|
||||
(store, preferences, notice)
|
||||
}
|
||||
|
||||
pub(crate) fn disabled() -> Self {
|
||||
Self {
|
||||
path: None,
|
||||
blocked: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn notice(&self, error: &str) -> String {
|
||||
let location = self.path.as_ref().map_or_else(
|
||||
|| "Pull request preferences".to_owned(),
|
||||
|path| format!("Pull request preferences ({})", path.display()),
|
||||
);
|
||||
format!("{location}: {error}. Changes are session-only; existing data was preserved.")
|
||||
}
|
||||
|
||||
pub(crate) fn save(&self, preferences: &Preferences) -> Result<(), String> {
|
||||
self.save_inner(preferences)
|
||||
.map_err(|error| self.notice(&error))
|
||||
}
|
||||
|
||||
fn save_inner(&self, preferences: &Preferences) -> Result<(), String> {
|
||||
if let Some(error) = &self.blocked {
|
||||
return Err(error.clone());
|
||||
}
|
||||
preferences.validate()?;
|
||||
let Some(path) = &self.path else {
|
||||
return Ok(());
|
||||
};
|
||||
// Refuse to overwrite data that became corrupt or incompatible after startup.
|
||||
read_preferences(path)?;
|
||||
let bytes = serde_json::to_vec_pretty(&StoredPreferences {
|
||||
version: 1,
|
||||
preferences: StoredSort {
|
||||
sort: &preferences.sort,
|
||||
_filters: serde::de::IgnoredAny,
|
||||
},
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
let parent = path.parent().ok_or("preferences path has no parent")?;
|
||||
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
let (temporary, mut file) = loop {
|
||||
let id = NEXT_TEMP.fetch_add(1, Ordering::Relaxed);
|
||||
let temporary = parent.join(format!(".pull-requests-{}-{id}.tmp", std::process::id()));
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
match options.open(&temporary) {
|
||||
Ok(file) => break (temporary, file),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
};
|
||||
let result = (|| {
|
||||
file.write_all(&bytes).and_then(|_| file.sync_all())?;
|
||||
drop(file);
|
||||
read_preferences(path).map_err(io::Error::other)?;
|
||||
// ponytail: optimistic validation; OS compare-and-swap if concurrent writers matter.
|
||||
fs::rename(&temporary, path)
|
||||
})();
|
||||
let _ = fs::remove_file(temporary);
|
||||
result.map_err(|error| error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/pull_request_preferences.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,144 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct Preferences {
|
||||
pub sort: SortSettings,
|
||||
pub filters: Vec<ReviewFilter>,
|
||||
}
|
||||
|
||||
impl Default for Preferences {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sort: BTreeMap::new(),
|
||||
filters: ReviewFilter::ALL.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type SortSettings = BTreeMap<SortField, SortRule>;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum SortField {
|
||||
Requested,
|
||||
UpdatedAt,
|
||||
Approved,
|
||||
CreatedAt,
|
||||
}
|
||||
|
||||
impl SortField {
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Requested,
|
||||
Self::UpdatedAt,
|
||||
Self::Approved,
|
||||
Self::CreatedAt,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Requested => "Requested from me",
|
||||
Self::UpdatedAt => "Updated at",
|
||||
Self::Approved => "Approved by me",
|
||||
Self::CreatedAt => "Created at",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_date(self) -> bool {
|
||||
matches!(self, Self::UpdatedAt | Self::CreatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub(crate) struct SortRule {
|
||||
pub precedence: Option<u8>,
|
||||
pub direction: Direction,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum Direction {
|
||||
Asc,
|
||||
#[default]
|
||||
Desc,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum ReviewFilter {
|
||||
Requested,
|
||||
Approved,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ReviewFilter {
|
||||
pub const ALL: [Self; 3] = [Self::Requested, Self::Approved, Self::Other];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Requested => "Requested from me",
|
||||
Self::Approved => "Approved by me",
|
||||
Self::Other => "Other / unavailable",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Preferences {
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
let mut ranks = [false; 4];
|
||||
for rule in self.sort.values() {
|
||||
if let Some(rank) = rule.precedence {
|
||||
if !(1..=4).contains(&rank) {
|
||||
return Err("Sort precedence must be between 1 and 4".into());
|
||||
}
|
||||
if std::mem::replace(&mut ranks[usize::from(rank - 1)], true) {
|
||||
return Err("Sort precedence must be unique".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index, filter) in self.filters.iter().enumerate() {
|
||||
if self.filters[..index].contains(filter) {
|
||||
return Err("Review filters must be unique".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ordered_fields(&self) -> [SortField; 4] {
|
||||
let mut slots = [None; 4];
|
||||
for (&field, rule) in &self.sort {
|
||||
if let Some(rank) = rule.precedence {
|
||||
slots[usize::from(rank - 1)] = Some(field);
|
||||
}
|
||||
}
|
||||
let mut unranked = SortField::ALL.into_iter().filter(|field| {
|
||||
self.sort
|
||||
.get(field)
|
||||
.is_none_or(|rule| rule.precedence.is_none())
|
||||
});
|
||||
slots.map(|field| field.unwrap_or_else(|| unranked.next().expect("four sort fields")))
|
||||
}
|
||||
|
||||
pub fn set_rank(&mut self, field: SortField, rank: Option<u8>) {
|
||||
self.sort.entry(field).or_default().precedence = None;
|
||||
let Some(mut rank) = rank else {
|
||||
return;
|
||||
};
|
||||
let mut field = field;
|
||||
loop {
|
||||
let displaced = self
|
||||
.sort
|
||||
.iter()
|
||||
.find_map(|(&other, rule)| (rule.precedence == Some(rank)).then_some(other));
|
||||
self.sort.entry(field).or_default().precedence = Some(rank);
|
||||
let Some(other) = displaced else {
|
||||
break;
|
||||
};
|
||||
self.sort.get_mut(&other).expect("ranked field").precedence = None;
|
||||
field = other;
|
||||
rank = rank % 4 + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3363
File diff suppressed because it is too large
Load Diff
+1058
File diff suppressed because it is too large
Load Diff
+1101
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,215 @@
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
ffi::{OsStr, OsString},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use vamp::{
|
||||
repository,
|
||||
review::{Review, Store},
|
||||
ruby,
|
||||
};
|
||||
|
||||
enum CommentAction {
|
||||
Delete,
|
||||
Resolve,
|
||||
}
|
||||
|
||||
pub struct Request {
|
||||
id: Option<i64>,
|
||||
comment: Option<(CommentAction, u64)>,
|
||||
repo: Option<PathBuf>,
|
||||
json: bool,
|
||||
all: bool,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn parse(args: &mut impl Iterator<Item = OsString>) -> Result<Self, String> {
|
||||
let usage = "--review requires list, show ID, delete REVIEW_ID COMMENT_ID, or resolve REVIEW_ID COMMENT_ID";
|
||||
let command = args.next().ok_or(usage)?;
|
||||
let id = if command == "list" {
|
||||
None
|
||||
} else if command == "show" || command == "delete" || command == "resolve" {
|
||||
let error = if command == "show" {
|
||||
"`show` requires a positive review ID.\nUsage: vamp --review show ID [--all]\n`--all` includes resolved comments; it does not select all reviews."
|
||||
} else if command == "delete" {
|
||||
"`delete` requires a positive review ID.\nUsage: vamp --review delete REVIEW_ID COMMENT_ID"
|
||||
} else {
|
||||
"`resolve` requires a positive review ID.\nUsage: vamp --review resolve REVIEW_ID COMMENT_ID"
|
||||
};
|
||||
let id = args.next().ok_or(error)?;
|
||||
Some(
|
||||
id.to_str()
|
||||
.and_then(|id| id.parse::<i64>().ok())
|
||||
.filter(|id| *id > 0)
|
||||
.ok_or(error)?,
|
||||
)
|
||||
} else {
|
||||
return Err(usage.into());
|
||||
};
|
||||
let comment = if command == "delete" || command == "resolve" {
|
||||
let error = if command == "delete" {
|
||||
"delete requires a positive comment ID"
|
||||
} else {
|
||||
"resolve requires a positive comment ID"
|
||||
};
|
||||
let id = args.next().ok_or(error)?;
|
||||
let id = id
|
||||
.to_str()
|
||||
.and_then(|id| id.parse::<u64>().ok())
|
||||
.filter(|id| *id > 0)
|
||||
.ok_or(error)?;
|
||||
Some((
|
||||
if command == "delete" {
|
||||
CommentAction::Delete
|
||||
} else {
|
||||
CommentAction::Resolve
|
||||
},
|
||||
id,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self {
|
||||
id,
|
||||
comment,
|
||||
repo: None,
|
||||
json: false,
|
||||
all: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn option(
|
||||
&mut self,
|
||||
arg: &OsStr,
|
||||
args: &mut impl Iterator<Item = OsString>,
|
||||
) -> Result<(), String> {
|
||||
if arg == "--repo" && self.repo.is_none() {
|
||||
self.repo = Some(PathBuf::from(args.next().ok_or("--repo requires a path")?));
|
||||
} else if arg == "--json" && !self.json {
|
||||
self.json = true;
|
||||
} else if arg == "--all" && self.id.is_some() && self.comment.is_none() && !self.all {
|
||||
self.all = true;
|
||||
} else {
|
||||
return Err(format!(
|
||||
"unexpected review argument: {}",
|
||||
arg.to_string_lossy()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn envelope(review: &Review, all: bool, comments: bool) -> Value {
|
||||
let resolved = review
|
||||
.comments
|
||||
.iter()
|
||||
.filter(|comment| comment.resolved)
|
||||
.count();
|
||||
let mut value = json!({
|
||||
"repository": review.root,
|
||||
"id": review.storage_id,
|
||||
"revision": review.storage_revision,
|
||||
"comparison": review.comparison,
|
||||
"summary": review.summary,
|
||||
"verdict": review.verdict,
|
||||
"counts": { "total": review.comments.len(), "resolved": resolved, "unresolved": review.comments.len() - resolved },
|
||||
});
|
||||
if comments {
|
||||
value["comments"] = review.comments.iter().filter(|comment| all || !comment.resolved).map(|comment| {
|
||||
json!({"id": comment.id, "body": comment.body, "resolved": comment.resolved,
|
||||
"anchor": { "revision": comment.anchor.revision, "path": comment.anchor.path,
|
||||
"side": comment.anchor.side, "start": comment.anchor.start, "end": comment.anchor.end },
|
||||
"excerpt": comment.anchor.excerpt()})
|
||||
}).collect();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
pub fn run(request: &Request, config: Option<&Path>) -> Result<(), String> {
|
||||
let directory = config
|
||||
.map(ruby::load_config)
|
||||
.transpose()?
|
||||
.and_then(|config| config.review_directory)
|
||||
.map_or_else(vamp::review::default_directory, Ok)?;
|
||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
||||
let root = repository::discover_root(request.repo.as_deref().unwrap_or(&cwd))?;
|
||||
let store = Store::open_read_only(&directory)?;
|
||||
let reviews = if let Some(id) = request.id {
|
||||
let mut review = store
|
||||
.as_ref()
|
||||
.ok_or_else(|| format!(
|
||||
"Review ID {id} not found in {}.\nRun `vamp --review list` to find review IDs for this repository.",
|
||||
root.display()
|
||||
))?
|
||||
.load(&root, id)?;
|
||||
if let Some((action, comment_id)) = &request.comment {
|
||||
let index = review
|
||||
.comments
|
||||
.iter()
|
||||
.position(|comment| comment.id == *comment_id)
|
||||
.ok_or_else(|| format!("Comment {comment_id} does not exist in review {id}"))?;
|
||||
let changed = match action {
|
||||
CommentAction::Delete => {
|
||||
review.comments.remove(index);
|
||||
true
|
||||
}
|
||||
CommentAction::Resolve => {
|
||||
let comment = &mut review.comments[index];
|
||||
let changed = !comment.resolved;
|
||||
comment.resolved = true;
|
||||
changed
|
||||
}
|
||||
};
|
||||
if changed {
|
||||
Store::open(&directory)?.save(&mut review)?;
|
||||
}
|
||||
}
|
||||
vec![review]
|
||||
} else {
|
||||
match store {
|
||||
Some(store) => store
|
||||
.list(&root)?
|
||||
.into_iter()
|
||||
.filter(|review| !review.comments.is_empty())
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
};
|
||||
if request.json {
|
||||
let output = if request.id.is_some() {
|
||||
envelope(&reviews[0], request.all, true)
|
||||
} else {
|
||||
let reviews = reviews
|
||||
.iter()
|
||||
.map(|review| envelope(review, true, false))
|
||||
.collect::<Vec<_>>();
|
||||
json!({"repository": root, "reviews": reviews})
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&output).map_err(|error| error.to_string())?
|
||||
);
|
||||
} else if request.id.is_some() {
|
||||
print!("{}", reviews[0].format_text(request.all));
|
||||
} else {
|
||||
println!("Repository: {}", root.display());
|
||||
if reviews.is_empty() {
|
||||
println!("No stored reviews.");
|
||||
}
|
||||
for review in &reviews {
|
||||
print!("{}", review.summary_text());
|
||||
println!(
|
||||
"\nShow comments: vamp --review show {}",
|
||||
review.storage_id.unwrap()
|
||||
);
|
||||
}
|
||||
if !reviews.is_empty() {
|
||||
println!("Include resolved comments: add --all");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/review_cli.rs"]
|
||||
mod tests;
|
||||
+284
-1058
File diff suppressed because it is too large
Load Diff
+456
-7
@@ -1,21 +1,168 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Vamp
|
||||
# @param name [String, Symbol]
|
||||
# @return [String]
|
||||
def self.chrome_name!(name)
|
||||
name = name.to_s if name.is_a?(Symbol)
|
||||
name = string!(name, "label/segment name")
|
||||
unless /\A[A-Za-z_][A-Za-z0-9_]*\z/.match?(name)
|
||||
raise ArgumentError, "label/segment name must match [A-Za-z_][A-Za-z0-9_]*"
|
||||
end
|
||||
name
|
||||
end
|
||||
|
||||
# @param value [Hash{String, Symbol => Object}]
|
||||
# @return [Hash{String => Object}]
|
||||
def self.chrome_hash!(value)
|
||||
raise TypeError, "chrome options must be a Hash" unless value.is_a?(Hash)
|
||||
value.each_with_object({}) do |(key, item), result|
|
||||
key = key.to_s if key.is_a?(Symbol)
|
||||
key = string!(key, "chrome key")
|
||||
raise ArgumentError, "duplicate chrome key: #{key}" if result.key?(key)
|
||||
result[key] = item
|
||||
end
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => Object}]
|
||||
# @return [Hash{String => Object}]
|
||||
def self.chrome_line!(options)
|
||||
chrome_hash!(options).to_h do |name, value|
|
||||
if %w[left center right].include?(name)
|
||||
raise TypeError, "#{name} must be an Array" unless value.is_a?(Array)
|
||||
[name, value.map { |item| chrome_name!(item) }]
|
||||
else
|
||||
chrome_name!(name)
|
||||
style = chrome_hash!(value).to_h do |option, item|
|
||||
case option
|
||||
when "padding", "margin", "leading_margin", "trailing_margin"
|
||||
unless item.is_a?(Integer) && item.between?(0, 64)
|
||||
raise ArgumentError, "#{option} must be an Integer between 0 and 64"
|
||||
end
|
||||
when "title", "leading_edge", "trailing_edge", "first_leading_edge"
|
||||
item = string!(item, option)
|
||||
else
|
||||
raise ArgumentError, "unknown chrome style option: #{option}"
|
||||
end
|
||||
[option, item]
|
||||
end
|
||||
[name, style]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Collects options for the independently configured top and bottom bars.
|
||||
class BarConfig
|
||||
# @return [Hash{String => Object}]
|
||||
attr_reader :top, :bottom
|
||||
|
||||
# @return [void]
|
||||
def initialize
|
||||
@top = {}
|
||||
@bottom = {}
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => Object}]
|
||||
# @return [Hash{String => Object}]
|
||||
def top=(options)
|
||||
@top = Vamp.chrome_line!(options)
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => Object}]
|
||||
# @return [Hash{String => Object}]
|
||||
def bottom=(options)
|
||||
@bottom = Vamp.chrome_line!(options)
|
||||
end
|
||||
end
|
||||
|
||||
# Collects anchor options for the independently positioned command and search popups.
|
||||
class PopupConfig
|
||||
# @return [Hash{String => String}]
|
||||
attr_reader :command, :search
|
||||
|
||||
# @return [void]
|
||||
def initialize
|
||||
@command = {}
|
||||
@search = {}
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => String, Symbol}] anchor in the workspace's 3x3 grid
|
||||
# @return [Hash{String => String}]
|
||||
def command=(options)
|
||||
@command = options!(options)
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => String, Symbol}] anchor in the workspace's 3x3 grid
|
||||
# @return [Hash{String => String}]
|
||||
def search=(options)
|
||||
@search = options!(options)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @param options [Hash{String, Symbol => String, Symbol}]
|
||||
# @return [Hash{String => String}]
|
||||
def options!(options)
|
||||
Vamp.chrome_hash!(options).to_h do |option, value|
|
||||
raise ArgumentError, "unknown popup option: #{option}" unless option == "anchor"
|
||||
value = value.to_s if value.is_a?(Symbol)
|
||||
value = Vamp.string!(value, "popup anchor")
|
||||
unless %w[top_left top_center top_right center_left center center_right bottom_left bottom_center bottom_right].include?(value)
|
||||
raise ArgumentError, "unknown popup anchor: #{value}"
|
||||
end
|
||||
[option, value]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Collects and validates the Ruby startup configuration DSL.
|
||||
class Config
|
||||
# @return [Hash{String => Boolean, Hash{String, Symbol => Object}}] language presets/options
|
||||
attr_reader :lsp
|
||||
|
||||
# @return [Hash{String => Integer, nil}] LSP-style language IDs to Tab widths
|
||||
attr_reader :language_tab_spaces
|
||||
|
||||
# @return [Vamp::BarConfig]
|
||||
attr_reader :bar
|
||||
|
||||
# @return [Vamp::PopupConfig]
|
||||
attr_reader :popup
|
||||
|
||||
# @return [void]
|
||||
def initialize
|
||||
@plugins = []
|
||||
@lsp = {}
|
||||
@review_directory = nil
|
||||
@bindings = []
|
||||
@leader = "space"
|
||||
@file_explorer_side = "right"
|
||||
@file_picker_view = "tree"
|
||||
@file_explorer_view = "tree"
|
||||
@clipboard_mode = "system"
|
||||
@git_blame = true
|
||||
@git_gutter = "bar"
|
||||
@cursor = {}
|
||||
@bar = BarConfig.new
|
||||
@popup = PopupConfig.new
|
||||
@labels = {}
|
||||
@scroll_distance = 0
|
||||
@scroll_step_lines = nil
|
||||
@highlight_trailing_whitespace = false
|
||||
@whitespace_characters = {}
|
||||
@whitespace_scope = "all"
|
||||
@tab_spaces = nil
|
||||
@language_tab_spaces = {}
|
||||
@diff_context_lines = 10
|
||||
@diff_expand_lines = 15
|
||||
@diff_view_mode = "split"
|
||||
@diff_split_orientation = "vertical"
|
||||
@diff_follow_working_copy = true
|
||||
@pull_request_review_requested_symbol = "🙏"
|
||||
@pull_request_approved_symbol = "👍"
|
||||
@pull_request_sort = nil
|
||||
@pull_request_filters = nil
|
||||
@resolve_history_layout = "columns"
|
||||
end
|
||||
|
||||
# @param path [String] relative to the configuration file
|
||||
@@ -30,6 +177,15 @@ module Vamp
|
||||
nil
|
||||
end
|
||||
|
||||
# @param path [String, nil] relative to the configuration file; nil uses the XDG data directory
|
||||
# @return [String, nil]
|
||||
def review_directory=(path)
|
||||
path = nonempty_string!(path, "review_directory") unless path.nil?
|
||||
raise ArgumentError, "review_directory must not contain NUL" if path&.include?("\0")
|
||||
|
||||
@review_directory = path
|
||||
end
|
||||
|
||||
# @param key [String]
|
||||
# @return [String]
|
||||
def leader=(key)
|
||||
@@ -60,6 +216,224 @@ module Vamp
|
||||
@clipboard_mode = nonempty_string!(mode, "clipboard mode")
|
||||
end
|
||||
|
||||
# @param enabled [Boolean]
|
||||
# @return [Boolean]
|
||||
def git_blame=(enabled)
|
||||
raise TypeError, "git_blame must be true or false" unless [true, false].include?(enabled)
|
||||
|
||||
@git_blame = enabled
|
||||
end
|
||||
|
||||
# @param style [String] "bar", "symbols", "line_numbers", or "none"
|
||||
def git_gutter=(style)
|
||||
style = nonempty_string!(style, "git gutter")
|
||||
raise ArgumentError, "git gutter must be bar, symbols, line_numbers, or none" unless %w[bar symbols line_numbers none].include?(style)
|
||||
|
||||
@git_gutter = style
|
||||
end
|
||||
|
||||
# @param options [Hash{String, Symbol => Boolean, String, Symbol}] mode_colors defaults to true; mode shapes default to block
|
||||
# @return [Hash{String => Boolean, String}]
|
||||
def cursor=(options)
|
||||
raise TypeError, "cursor options must be a Hash" unless options.is_a?(Hash)
|
||||
|
||||
@cursor = options.each_with_object({}) do |(option, value), result|
|
||||
option = option.to_s if option.is_a?(Symbol)
|
||||
option = Vamp.string!(option, "cursor option")
|
||||
raise ArgumentError, "duplicate cursor option: #{option}" if result.key?(option)
|
||||
|
||||
case option
|
||||
when "mode_colors"
|
||||
raise TypeError, "cursor mode_colors must be true or false" unless [true, false].include?(value)
|
||||
when "normal", "insert", "command", "search", "visual"
|
||||
value = value.to_s if value.is_a?(Symbol)
|
||||
value = Vamp.string!(value, "cursor shape")
|
||||
unless %w[block bar underline].include?(value)
|
||||
raise ArgumentError, "cursor shape must be block, bar, or underline"
|
||||
end
|
||||
else
|
||||
raise ArgumentError, "unknown cursor option: #{option}"
|
||||
end
|
||||
result[option] = value
|
||||
end
|
||||
end
|
||||
|
||||
# @param values [Hash{String, Symbol => String}]
|
||||
# @return [Hash]
|
||||
def labels=(values)
|
||||
@labels = Vamp.chrome_hash!(values).to_h do |name, text|
|
||||
[Vamp.chrome_name!(name), Vamp.string!(text, "label text")]
|
||||
end
|
||||
end
|
||||
|
||||
# @param distance [Integer, nil] nonnegative cursor margin, or nil to center
|
||||
# @return [Integer, nil]
|
||||
def scroll_distance=(distance)
|
||||
@scroll_distance = distance.nil? ? nil : diff_line_count!(distance, "scroll_distance", 0)
|
||||
end
|
||||
|
||||
# @param lines [Integer, nil] positive screen rows, or nil for half the viewport
|
||||
# @return [Integer, nil]
|
||||
def scroll_step_lines=(lines)
|
||||
@scroll_step_lines = lines.nil? ? nil : diff_line_count!(lines, "scroll_step_lines", 1)
|
||||
end
|
||||
|
||||
# @param enabled [Boolean]
|
||||
# @return [Boolean]
|
||||
def highlight_trailing_whitespace=(enabled)
|
||||
raise TypeError, "highlight_trailing_whitespace must be true or false" unless [true, false].include?(enabled)
|
||||
|
||||
@highlight_trailing_whitespace = enabled
|
||||
end
|
||||
|
||||
# @param characters [Hash{String => String}] whitespace character to single-cell marker
|
||||
# @return [Hash{String => String}]
|
||||
def whitespace_characters=(characters)
|
||||
raise TypeError, "whitespace_characters must be a Hash" unless characters.is_a?(Hash)
|
||||
|
||||
characters.each do |whitespace, marker|
|
||||
unless [whitespace, marker].all? { |value| value.is_a?(String) && value.length == 1 }
|
||||
raise TypeError, "whitespace_characters keys and values must be single-character Strings"
|
||||
end
|
||||
end
|
||||
@whitespace_characters = characters.dup
|
||||
end
|
||||
|
||||
# @param scope [String] "all" or "leading"
|
||||
# @return [String]
|
||||
def whitespace_scope=(scope)
|
||||
scope = Vamp.string!(scope, "whitespace_scope")
|
||||
raise ArgumentError, "whitespace_scope must be all or leading" unless %w[all leading].include?(scope)
|
||||
|
||||
@whitespace_scope = scope
|
||||
end
|
||||
|
||||
# @param spaces [Integer, nil] spaces per Tab, or nil for a literal tab
|
||||
# @return [Integer, nil]
|
||||
def tab_spaces=(spaces)
|
||||
@tab_spaces = tab_spaces!(spaces)
|
||||
end
|
||||
|
||||
# @param languages [Hash{String => Integer, nil}] LSP-style language IDs to Tab widths
|
||||
# @return [Hash{String => Integer, nil}]
|
||||
def language_tab_spaces=(languages)
|
||||
@language_tab_spaces = language_tab_spaces!(languages)
|
||||
end
|
||||
|
||||
# @param lines [Integer] nonnegative context lines around each diff change
|
||||
# @return [Integer]
|
||||
def diff_context_lines=(lines)
|
||||
@diff_context_lines = diff_line_count!(lines, "diff_context_lines", 0)
|
||||
end
|
||||
|
||||
# @param lines [Integer] positive lines revealed per diff expansion
|
||||
# @return [Integer]
|
||||
def diff_expand_lines=(lines)
|
||||
@diff_expand_lines = diff_line_count!(lines, "diff_expand_lines", 1)
|
||||
end
|
||||
|
||||
# @param mode [String] "split" or "unified"
|
||||
# @return [String]
|
||||
def diff_view_mode=(mode)
|
||||
mode = nonempty_string!(mode, "diff view mode")
|
||||
raise ArgumentError, "diff view mode must be split or unified" unless %w[split unified].include?(mode)
|
||||
@diff_view_mode = mode
|
||||
end
|
||||
|
||||
# @param orientation [String] "vertical" or "horizontal"
|
||||
# @return [String]
|
||||
def diff_split_orientation=(orientation)
|
||||
orientation = nonempty_string!(orientation, "diff split orientation")
|
||||
unless %w[vertical horizontal].include?(orientation)
|
||||
raise ArgumentError, "diff split orientation must be vertical or horizontal"
|
||||
end
|
||||
@diff_split_orientation = orientation
|
||||
end
|
||||
|
||||
# @param enabled [Boolean]
|
||||
# @return [Boolean]
|
||||
def diff_follow_working_copy=(enabled)
|
||||
raise TypeError, "diff_follow_working_copy must be true or false" unless [true, false].include?(enabled)
|
||||
|
||||
@diff_follow_working_copy = enabled
|
||||
end
|
||||
|
||||
# @param symbol [String] empty to hide the review-request indicator
|
||||
# @return [String]
|
||||
def pull_request_review_requested_symbol=(symbol)
|
||||
@pull_request_review_requested_symbol = pull_request_symbol!(symbol, "pull_request_review_requested_symbol")
|
||||
end
|
||||
|
||||
# @param symbol [String] empty to hide the approval indicator
|
||||
# @return [String]
|
||||
def pull_request_approved_symbol=(symbol)
|
||||
@pull_request_approved_symbol = pull_request_symbol!(symbol, "pull_request_approved_symbol")
|
||||
end
|
||||
|
||||
# @param fields [Hash{String, Symbol => Hash}, nil] explicit ranks and sort directions
|
||||
# @return [Hash, nil]
|
||||
def pull_request_sort=(fields)
|
||||
return @pull_request_sort = nil if fields.nil?
|
||||
raise TypeError, "pull_request_sort must be a Hash or nil" unless fields.is_a?(Hash)
|
||||
|
||||
ranks = []
|
||||
normalized = Vamp.chrome_hash!(fields).to_h do |field, options|
|
||||
unless %w[requested updated_at approved created_at].include?(field)
|
||||
raise ArgumentError, "unknown pull_request_sort field: #{field}"
|
||||
end
|
||||
raise TypeError, "pull_request_sort #{field} must be a Hash" unless options.is_a?(Hash)
|
||||
|
||||
options = Vamp.chrome_hash!(options)
|
||||
unknown = options.keys - %w[precedence direction]
|
||||
raise ArgumentError, "unknown pull_request_sort option: #{unknown.first}" unless unknown.empty?
|
||||
rank = options["precedence"]
|
||||
unless rank.nil? || (rank.is_a?(Integer) && rank.between?(1, 4))
|
||||
raise ArgumentError, "pull_request_sort precedence must be between 1 and 4"
|
||||
end
|
||||
raise ArgumentError, "duplicate pull_request_sort precedence: #{rank}" if rank && ranks.include?(rank)
|
||||
ranks << rank if rank
|
||||
if options.key?("direction")
|
||||
direction = options["direction"]
|
||||
direction = direction.to_s if direction.is_a?(Symbol)
|
||||
unless %w[asc desc].include?(direction)
|
||||
raise ArgumentError, "pull_request_sort direction must be asc or desc"
|
||||
end
|
||||
options["direction"] = direction
|
||||
end
|
||||
[field, options]
|
||||
end
|
||||
@pull_request_sort = normalized
|
||||
end
|
||||
|
||||
# @param filters [Array<String, Symbol>, nil] selected personal review buckets
|
||||
# @return [Array<String>, nil]
|
||||
def pull_request_filters=(filters)
|
||||
return @pull_request_filters = nil if filters.nil?
|
||||
raise TypeError, "pull_request_filters must be an Array or nil" unless filters.is_a?(Array)
|
||||
|
||||
normalized = filters.map do |filter|
|
||||
filter = filter.to_s if filter.is_a?(Symbol)
|
||||
unless %w[requested approved other].include?(filter)
|
||||
raise ArgumentError, "unknown pull_request_filters value: #{filter.inspect}"
|
||||
end
|
||||
filter
|
||||
end
|
||||
unless normalized.uniq.length == normalized.length
|
||||
raise ArgumentError, "duplicate pull_request_filters value"
|
||||
end
|
||||
@pull_request_filters = normalized
|
||||
end
|
||||
|
||||
# @param layout [String] "columns" or "base_below"
|
||||
# @return [String]
|
||||
def resolve_history_layout=(layout)
|
||||
layout = nonempty_string!(layout, "resolve history layout")
|
||||
unless %w[columns base_below].include?(layout)
|
||||
raise ArgumentError, "resolve history layout must be columns or base_below"
|
||||
end
|
||||
@resolve_history_layout = layout
|
||||
end
|
||||
|
||||
# @return [Module<Vamp::Core>] frozen namespace with catalog-generated Action methods
|
||||
def core
|
||||
Core
|
||||
@@ -89,12 +463,74 @@ module Vamp
|
||||
# @return [Hash{String => Object}] validated startup configuration frame
|
||||
def response
|
||||
{ "version" => 1, "type" => "config", "plugins" => @plugins, "lsp" => lsp_options, "bindings" => @bindings,
|
||||
"review_directory" => @review_directory,
|
||||
"leader" => @leader, "file_explorer_side" => @file_explorer_side, "file_picker_view" => @file_picker_view,
|
||||
"file_explorer_view" => @file_explorer_view, "clipboard_mode" => @clipboard_mode }
|
||||
"file_explorer_view" => @file_explorer_view, "clipboard_mode" => @clipboard_mode,
|
||||
"git_blame" => @git_blame,
|
||||
"git_gutter" => @git_gutter,
|
||||
"cursor" => @cursor,
|
||||
"scroll_distance" => @scroll_distance,
|
||||
"scroll_step_lines" => @scroll_step_lines,
|
||||
"highlight_trailing_whitespace" => @highlight_trailing_whitespace,
|
||||
"whitespace_characters" => @whitespace_characters,
|
||||
"whitespace_scope" => @whitespace_scope,
|
||||
"tab_spaces" => @tab_spaces, "language_tab_spaces" => language_tab_spaces!(@language_tab_spaces),
|
||||
"top_bar" => @bar.top, "bottom_bar" => @bar.bottom, "labels" => @labels,
|
||||
"popup" => { "command" => @popup.command, "search" => @popup.search },
|
||||
"diff_context_lines" => @diff_context_lines, "diff_expand_lines" => @diff_expand_lines,
|
||||
"diff_view_mode" => @diff_view_mode, "diff_split_orientation" => @diff_split_orientation,
|
||||
"diff_follow_working_copy" => @diff_follow_working_copy,
|
||||
"pull_request_review_requested_symbol" => @pull_request_review_requested_symbol,
|
||||
"pull_request_approved_symbol" => @pull_request_approved_symbol,
|
||||
"pull_request_sort" => @pull_request_sort, "pull_request_filters" => @pull_request_filters,
|
||||
"resolve_history_layout" => @resolve_history_layout }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def pull_request_symbol!(symbol, label)
|
||||
symbol = Vamp.string!(symbol, label)
|
||||
raise ArgumentError, "#{label} must not contain control characters" if symbol.match?(/[[:cntrl:]]/)
|
||||
|
||||
symbol
|
||||
end
|
||||
# @param spaces [Integer, nil]
|
||||
# @return [Integer, nil]
|
||||
def tab_spaces!(spaces)
|
||||
unless spaces.nil? || (spaces.is_a?(Integer) && spaces.between?(1, 255))
|
||||
raise ArgumentError, "tab_spaces must be nil or an Integer between 1 and 255"
|
||||
end
|
||||
|
||||
spaces
|
||||
end
|
||||
|
||||
# @param languages [Hash{String => Integer, nil}]
|
||||
# @return [Hash{String => Integer, nil}]
|
||||
def language_tab_spaces!(languages)
|
||||
raise TypeError, "language_tab_spaces must be a Hash" unless languages.is_a?(Hash)
|
||||
|
||||
languages.to_h do |language, spaces|
|
||||
language = nonempty_string!(language, "Tab language")
|
||||
raise ArgumentError, "Tab language must not contain control characters" if language.match?(/[[:cntrl:]]/)
|
||||
|
||||
[language, tab_spaces!(spaces)]
|
||||
end
|
||||
end
|
||||
|
||||
# @param value [Integer]
|
||||
# @param label [String]
|
||||
# @param minimum [Integer]
|
||||
# @return [Integer]
|
||||
def diff_line_count!(value, label, minimum)
|
||||
raise TypeError, "#{label} must be an Integer" unless value.is_a?(Integer)
|
||||
maximum = (1 << 64) - 1
|
||||
unless value.between?(minimum, maximum)
|
||||
raise ArgumentError, "#{label} must be between #{minimum} and #{maximum}"
|
||||
end
|
||||
|
||||
value
|
||||
end
|
||||
|
||||
# @param value [String]
|
||||
# @param label [String]
|
||||
# @return [String]
|
||||
@@ -124,7 +560,9 @@ module Vamp
|
||||
# @return [String]
|
||||
def external_command(command)
|
||||
name = Vamp.string!(command, "binding command")
|
||||
raise TypeError, "use config.core for built-in actions" if name.start_with?("core.")
|
||||
if name.start_with?("core.") || Vamp.builtin_command?(name)
|
||||
raise TypeError, "use config.core for built-in actions"
|
||||
end
|
||||
|
||||
name
|
||||
end
|
||||
@@ -172,7 +610,7 @@ module Vamp
|
||||
attr_reader :path
|
||||
# @return [Integer] positive invocation ID
|
||||
attr_reader :request_id
|
||||
# @return [Array<Hash{String => String}>] queued insert/replace/message effects
|
||||
# @return [Array<Hash{String => String}>] queued text and presentation effects
|
||||
attr_reader :effects
|
||||
|
||||
# @param context [Hash{String => String, Integer, nil}] primary caret/document snapshot
|
||||
@@ -206,6 +644,14 @@ module Vamp
|
||||
queue("message", text)
|
||||
end
|
||||
|
||||
# @param name [String, Symbol]
|
||||
# @param text [String] named session-wide plain text; empty clears it
|
||||
# @return [nil]
|
||||
def label(name, text)
|
||||
name = Vamp.chrome_name!(name)
|
||||
queue("label", text, name)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# @param context [Hash{String => String, Integer, nil}]
|
||||
@@ -250,15 +696,18 @@ module Vamp
|
||||
raise ArgumentError, "context buffer_id and revision must be nonnegative integers"
|
||||
end
|
||||
|
||||
# @param type [String] insert, replace, or message
|
||||
# @param type [String] insert, replace, message, or label
|
||||
# @param text [String]
|
||||
# @param name [String, nil]
|
||||
# @return [nil]
|
||||
def queue(type, text)
|
||||
def queue(type, text, name = nil)
|
||||
text = Vamp.string!(text, "effect text")
|
||||
@effect_bytes += text.bytesize
|
||||
@effect_bytes += text.bytesize + (name ? name.bytesize : 0)
|
||||
raise ArgumentError, "effects exceed 4 MiB" if @effect_bytes > MAX_FRAME
|
||||
|
||||
@effects << { "type" => type, "text" => text }
|
||||
effect = { "type" => type, "text" => text }
|
||||
effect["name"] = name if name
|
||||
@effects << effect
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
+3
-2
@@ -7,7 +7,7 @@ module Vamp
|
||||
# @param startup [Object] action catalog and options
|
||||
# @return [void]
|
||||
def self.startup!(startup)
|
||||
return if hash_shape?(startup, %w[core_actions options]) && startup["options"].is_a?(Hash)
|
||||
return if hash_shape?(startup, %w[command_aliases core_actions options]) && startup["options"].is_a?(Hash)
|
||||
|
||||
raise TypeError, "invalid Ruby startup catalog/options"
|
||||
end
|
||||
@@ -100,7 +100,7 @@ module Vamp
|
||||
# @return [Proc, Method] the installed sender
|
||||
def self.setup(mode, startup, sender)
|
||||
FrameValidation.startup!(startup)
|
||||
install_actions(startup["core_actions"])
|
||||
install_actions(startup["core_actions"], startup["command_aliases"])
|
||||
@mode = mode
|
||||
reset_registrations
|
||||
@options = deep_freeze(json_value!(startup["options"]))
|
||||
@@ -168,6 +168,7 @@ module Vamp
|
||||
raise ArgumentError, "declare a plugin before its commands" unless @mode == "plugin" && @name
|
||||
|
||||
name = registration_name!(name, "command")
|
||||
raise ArgumentError, "built-in command #{name} cannot be replaced" if Vamp.builtin_command?(name)
|
||||
raise ArgumentError, "command requires a block" unless callback
|
||||
raise ArgumentError, "duplicate command #{name}" if @commands.key?(name)
|
||||
|
||||
|
||||
+40
-14
@@ -58,16 +58,41 @@ module Vamp
|
||||
# @type [Module<Vamp::Core>]
|
||||
Core = Module.new
|
||||
|
||||
# @param names [Array<String>] dotted core action names
|
||||
# @return [Array<Module>] frozen action namespaces
|
||||
def self.install_actions(names)
|
||||
raise TypeError, "core action catalog must be an Array" unless names.is_a?(Array)
|
||||
# @param entries [Array<Hash{String => String, nil}>] action name and optional canonical Ex name
|
||||
# @param command_aliases [Hash{String => String}] shorthand to canonical commands
|
||||
# @return [Array<Module, Vamp::Action>] frozen action namespaces and leaves
|
||||
def self.install_actions(entries, command_aliases)
|
||||
raise TypeError, "core action catalog must be an Array" unless entries.is_a?(Array)
|
||||
raise TypeError, "command aliases must be a Hash" unless command_aliases.is_a?(Hash)
|
||||
|
||||
namespaces = [Core]
|
||||
names.each { |name| install_action(name, namespaces) }
|
||||
commands = {}
|
||||
entries.sort_by { |entry| entry.fetch("name").count(".") }.each do |entry|
|
||||
raise TypeError, "core action descriptor must be a Hash" unless entry.is_a?(Hash)
|
||||
|
||||
install_action(entry.fetch("name"), namespaces)
|
||||
ex = entry.fetch("ex")
|
||||
canonical = string!(ex, "core Ex command").freeze unless ex.nil?
|
||||
commands[canonical] = canonical unless ex.nil?
|
||||
end
|
||||
canonical_commands = commands.keys
|
||||
command_aliases.each do |name, canonical|
|
||||
name = string!(name, "command alias").freeze
|
||||
canonical = string!(canonical, "canonical command").freeze
|
||||
raise ArgumentError, "unknown canonical command: #{canonical}" unless canonical_commands.include?(canonical)
|
||||
|
||||
commands[name] = canonical
|
||||
end
|
||||
@builtin_commands = commands.freeze
|
||||
namespaces.each(&:freeze)
|
||||
end
|
||||
|
||||
# @param name [String] binding command name
|
||||
# @return [Boolean] whether the catalog owns this canonical command or shorthand
|
||||
def self.builtin_command?(name)
|
||||
@builtin_commands.key?(name)
|
||||
end
|
||||
|
||||
# Frozen binding mode values, distinct from a buffer's editing state.
|
||||
module Modes
|
||||
# @!method self.normal
|
||||
@@ -125,7 +150,7 @@ module Vamp
|
||||
end
|
||||
|
||||
# @param name [String]
|
||||
# @param namespaces [Array<Module>]
|
||||
# @param namespaces [Array<Module, Vamp::Action>]
|
||||
# @return [Symbol] the installed action method name
|
||||
def self.install_action(name, namespaces)
|
||||
name = action_name(name)
|
||||
@@ -133,7 +158,8 @@ module Vamp
|
||||
namespace = parts[0...-1].reduce(Core) { |parent, part| action_namespace(parent, part, namespaces, name) }
|
||||
leaf = parts.last
|
||||
available_action!(namespace, leaf, name)
|
||||
action = Action.send(:new, name.freeze).freeze
|
||||
action = Action.send(:new, name.freeze)
|
||||
namespaces << action
|
||||
namespace.define_singleton_method(leaf) { action }
|
||||
end
|
||||
|
||||
@@ -146,23 +172,23 @@ module Vamp
|
||||
name
|
||||
end
|
||||
|
||||
# @param parent [Module]
|
||||
# @param parent [Module, Vamp::Action]
|
||||
# @param part [String]
|
||||
# @param namespaces [Array<Module>]
|
||||
# @param namespaces [Array<Module, Vamp::Action>]
|
||||
# @param name [String]
|
||||
# @return [Module]
|
||||
# @return [Module, Vamp::Action]
|
||||
def self.action_namespace(parent, part, namespaces, name)
|
||||
return new_action_namespace(parent, part, namespaces) unless parent.singleton_methods(false).include?(part.to_sym)
|
||||
|
||||
child = parent.public_send(part)
|
||||
raise ArgumentError, "conflicting core action namespace: #{name}" unless child.is_a?(Module)
|
||||
raise ArgumentError, "conflicting core action namespace: #{name}" unless child.is_a?(Module) || child.is_a?(Action)
|
||||
|
||||
child
|
||||
end
|
||||
|
||||
# @param parent [Module]
|
||||
# @param parent [Module, Vamp::Action]
|
||||
# @param part [String]
|
||||
# @param namespaces [Array<Module>]
|
||||
# @param namespaces [Array<Module, Vamp::Action>]
|
||||
# @return [Module]
|
||||
def self.new_action_namespace(parent, part, namespaces)
|
||||
child = Module.new
|
||||
@@ -171,7 +197,7 @@ module Vamp
|
||||
child
|
||||
end
|
||||
|
||||
# @param namespace [Module]
|
||||
# @param namespace [Module, Vamp::Action]
|
||||
# @param leaf [String]
|
||||
# @param name [String]
|
||||
# @return [nil]
|
||||
|
||||
+1458
-2330
File diff suppressed because it is too large
Load Diff
+240
@@ -0,0 +1,240 @@
|
||||
#[cfg(unix)]
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
io::{self, Read},
|
||||
os::{
|
||||
fd::OwnedFd,
|
||||
unix::{net::UnixStream, process::CommandExt},
|
||||
},
|
||||
process::{Child, Command, Stdio},
|
||||
sync::mpsc::{self, RecvTimeoutError},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::mpsc::{Receiver, Sender, TryRecvError},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
const OUTPUT_LIMIT: usize = 4 * 1024 * 1024;
|
||||
#[cfg(unix)]
|
||||
const TRUNCATION_NOTE: &[u8] = b"\n[vamp: output truncated after 4 MiB]\n";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Output {
|
||||
pub(crate) code: Option<i32>,
|
||||
pub(crate) stdout: Vec<u8>,
|
||||
pub(crate) stderr: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(crate) struct Worker {
|
||||
cancel: Sender<()>,
|
||||
results: Receiver<Result<Output, String>>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
pub(crate) fn start(command: String, root: PathBuf) -> Result<Self, String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let shell = std::env::var_os("SHELL")
|
||||
.filter(|shell| !shell.is_empty())
|
||||
.unwrap_or_else(|| "/bin/sh".into());
|
||||
Self::start_with_shell(command, root, shell)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (command, root);
|
||||
Err("Shell commands require Unix process-group cancellation on this platform".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn start_with_shell(command: String, root: PathBuf, shell: OsString) -> Result<Self, String> {
|
||||
let (cancel, cancelled) = mpsc::channel();
|
||||
let (send, results) = mpsc::channel();
|
||||
let thread = thread::Builder::new()
|
||||
.name("vamp-shell".into())
|
||||
.spawn(move || {
|
||||
let _ = send.send(run(command, root, shell, cancelled));
|
||||
})
|
||||
.map_err(|error| format!("Cannot start shell worker: {error}"))?;
|
||||
Ok(Self {
|
||||
cancel,
|
||||
results,
|
||||
thread: Some(thread),
|
||||
finished: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self) -> Option<Result<Output, String>> {
|
||||
if self.finished {
|
||||
return None;
|
||||
}
|
||||
let result = match self.results.try_recv() {
|
||||
Ok(output) => output,
|
||||
Err(TryRecvError::Empty) => return None,
|
||||
Err(TryRecvError::Disconnected) => Err("Shell worker stopped unexpectedly".into()),
|
||||
};
|
||||
self.finished = true;
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.cancel.send(());
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct Process(Child);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for Process {
|
||||
fn drop(&mut self) {
|
||||
unsafe extern "C" {
|
||||
fn kill(pid: i32, signal: i32) -> i32;
|
||||
}
|
||||
// The shell and its descendants share a private process group; killing
|
||||
// only the leader would leave children holding the output descriptors.
|
||||
unsafe { kill(-(self.0.id() as i32), 9) };
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct Capture {
|
||||
reader: UnixStream,
|
||||
bytes: Vec<u8>,
|
||||
truncated: bool,
|
||||
eof: bool,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Capture {
|
||||
fn new() -> Result<(Self, Stdio), String> {
|
||||
let (reader, writer) = UnixStream::pair()
|
||||
.map_err(|error| format!("Cannot create shell output stream: {error}"))?;
|
||||
reader
|
||||
.set_nonblocking(true)
|
||||
.map_err(|error| format!("Cannot configure shell output stream: {error}"))?;
|
||||
Ok((
|
||||
Self {
|
||||
reader,
|
||||
bytes: Vec::new(),
|
||||
truncated: false,
|
||||
eof: false,
|
||||
},
|
||||
Stdio::from(OwnedFd::from(writer)),
|
||||
))
|
||||
}
|
||||
|
||||
fn read(&mut self) -> io::Result<bool> {
|
||||
if self.eof {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut chunk = [0; 16 * 1024];
|
||||
match self.reader.read(&mut chunk) {
|
||||
Ok(0) => {
|
||||
self.eof = true;
|
||||
Ok(false)
|
||||
}
|
||||
Ok(count) => {
|
||||
let keep = count.min(OUTPUT_LIMIT.saturating_sub(self.bytes.len()));
|
||||
self.bytes.extend_from_slice(&chunk[..keep]);
|
||||
self.truncated |= keep != count;
|
||||
Ok(true)
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(false),
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => Ok(true),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
if self.truncated {
|
||||
self.bytes.extend_from_slice(TRUNCATION_NOTE);
|
||||
}
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run(
|
||||
command: String,
|
||||
root: PathBuf,
|
||||
shell: OsString,
|
||||
cancelled: Receiver<()>,
|
||||
) -> Result<Output, String> {
|
||||
if cancelled.try_recv().is_ok() {
|
||||
return Err("Shell command cancelled".into());
|
||||
}
|
||||
let (mut stdout, stdout_writer) = Capture::new()?;
|
||||
let (mut stderr, stderr_writer) = Capture::new()?;
|
||||
let child = Command::new(shell)
|
||||
.arg("-c")
|
||||
.arg(command)
|
||||
.current_dir(root)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(stdout_writer)
|
||||
.stderr(stderr_writer)
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.map_err(|error| format!("Cannot start shell command: {error}"))?;
|
||||
let mut process = Some(Process(child));
|
||||
let mut status = None;
|
||||
loop {
|
||||
if cancelled.try_recv().is_ok() {
|
||||
return Err("Shell command cancelled".into());
|
||||
}
|
||||
// Read each stream once per turn so a busy writer cannot starve the
|
||||
// other stream or cancellation. Overflow is still drained, not retained.
|
||||
let out = stdout
|
||||
.read()
|
||||
.map_err(|error| format!("Cannot read shell stdout: {error}"))?;
|
||||
let err = stderr
|
||||
.read()
|
||||
.map_err(|error| format!("Cannot read shell stderr: {error}"))?;
|
||||
if let Some(child) = process.as_mut() {
|
||||
status = child
|
||||
.0
|
||||
.try_wait()
|
||||
.map_err(|error| format!("Cannot wait for shell command: {error}"))?;
|
||||
if status.is_some() {
|
||||
// Background jobs must not outlive the command. Killing the
|
||||
// remaining group also closes inherited output descriptors.
|
||||
drop(process.take());
|
||||
}
|
||||
}
|
||||
if let Some(status) = status
|
||||
&& stdout.eof
|
||||
&& stderr.eof
|
||||
{
|
||||
return Ok(Output {
|
||||
code: status.code(),
|
||||
stdout: stdout.finish(),
|
||||
stderr: stderr.finish(),
|
||||
});
|
||||
}
|
||||
if !out && !err {
|
||||
match cancelled.recv_timeout(Duration::from_millis(10)) {
|
||||
Ok(()) | Err(RecvTimeoutError::Disconnected) => {
|
||||
return Err("Shell command cancelled".into());
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "../tests/unit/shell.rs"]
|
||||
mod tests;
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
use std::{collections::BTreeMap, ops::Range};
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::plugin::{CompletionSnippet, SnippetTabstop};
|
||||
|
||||
const MAX_BYTES: usize = 256 * 1024;
|
||||
const MAX_NODES: usize = 4096;
|
||||
const MAX_STOPS: usize = 1024;
|
||||
const MAX_DEPTH: usize = 32;
|
||||
const MAX_WORK: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) enum Error {
|
||||
Invalid,
|
||||
Unsupported,
|
||||
Limit,
|
||||
}
|
||||
|
||||
enum Node<'a> {
|
||||
Text(&'a str),
|
||||
Value(String),
|
||||
Stop(u32, Option<Vec<usize>>),
|
||||
Default(Vec<usize>),
|
||||
}
|
||||
|
||||
struct Parser<'a, F> {
|
||||
text: &'a str,
|
||||
cursor: usize,
|
||||
nodes: Vec<Node<'a>>,
|
||||
value_bytes: usize,
|
||||
variable: F,
|
||||
}
|
||||
|
||||
/// Parse normalized snippet text before assigning any byte offsets. Unsupported
|
||||
/// constructs omit the entire candidate, never leaking template syntax into text.
|
||||
pub(crate) fn expand(
|
||||
text: &str,
|
||||
variable: impl Fn(&str) -> Option<String>,
|
||||
) -> Result<(String, CompletionSnippet), Error> {
|
||||
if text.len() > MAX_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let normalized = if text.contains('\r') {
|
||||
std::borrow::Cow::Owned(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
} else {
|
||||
std::borrow::Cow::Borrowed(text)
|
||||
};
|
||||
let mut parser = Parser {
|
||||
text: &normalized,
|
||||
cursor: 0,
|
||||
nodes: Vec::new(),
|
||||
value_bytes: 0,
|
||||
variable,
|
||||
};
|
||||
let roots = parser.sequence(false, 0)?;
|
||||
let mut definitions = BTreeMap::new();
|
||||
let mut pending: Vec<_> = roots.iter().rev().copied().collect();
|
||||
while let Some(id) = pending.pop() {
|
||||
match &parser.nodes[id] {
|
||||
Node::Stop(index, Some(children)) => {
|
||||
definitions.entry(*index).or_insert(id);
|
||||
pending.extend(children.iter().rev().copied());
|
||||
}
|
||||
Node::Default(children) => pending.extend(children.iter().rev().copied()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut rendered = Render {
|
||||
nodes: &parser.nodes,
|
||||
definitions: &definitions,
|
||||
text: String::new(),
|
||||
stops: BTreeMap::new(),
|
||||
ancestors: Vec::new(),
|
||||
occurrences: 0,
|
||||
work: 0,
|
||||
};
|
||||
rendered.sequence(&roots, 0)?;
|
||||
if !rendered.stops.contains_key(&0) {
|
||||
if rendered.occurrences == MAX_STOPS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
rendered.stops.insert(
|
||||
0,
|
||||
SnippetTabstop {
|
||||
index: 0,
|
||||
ranges: std::iter::once(rendered.text.len()..rendered.text.len()).collect(),
|
||||
ancestors: vec![Vec::new()],
|
||||
},
|
||||
);
|
||||
}
|
||||
let final_stop = rendered.stops.get(&0).unwrap();
|
||||
if final_stop.ranges.len() != 1
|
||||
|| !final_stop.ranges[0].is_empty()
|
||||
|| !final_stop.ancestors[0].is_empty()
|
||||
|| rendered.stops.values().any(|stop| {
|
||||
stop.ancestors
|
||||
.iter()
|
||||
.any(|ancestors| ancestors.contains(&0))
|
||||
})
|
||||
{
|
||||
return Err(Error::Unsupported);
|
||||
}
|
||||
let boundaries: Vec<_> = rendered
|
||||
.text
|
||||
.grapheme_indices(true)
|
||||
.map(|(offset, _)| offset)
|
||||
.chain(std::iter::once(rendered.text.len()))
|
||||
.collect();
|
||||
for stop in rendered.stops.values() {
|
||||
let mut previous: Option<&Range<usize>> = None;
|
||||
for range in &stop.ranges {
|
||||
if boundaries.binary_search(&range.start).is_err()
|
||||
|| boundaries.binary_search(&range.end).is_err()
|
||||
|| previous.is_some_and(|old| {
|
||||
old.end > range.start
|
||||
|| (old.start == range.start && !(old.is_empty() && range.is_empty()))
|
||||
})
|
||||
{
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
previous = Some(range);
|
||||
}
|
||||
}
|
||||
let final_stop = rendered.stops.remove(&0).unwrap();
|
||||
let mut tabstops: Vec<_> = rendered.stops.into_values().collect();
|
||||
tabstops.push(final_stop);
|
||||
Ok((rendered.text, CompletionSnippet { tabstops }))
|
||||
}
|
||||
|
||||
impl<'a, F: Fn(&str) -> Option<String>> Parser<'a, F> {
|
||||
fn node(&mut self, mut node: Node<'a>) -> Result<usize, Error> {
|
||||
if self.nodes.len() == MAX_NODES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
if let Node::Value(value) = &mut node {
|
||||
if value.len() > MAX_BYTES {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
if value.contains('\r') {
|
||||
*value = value.replace("\r\n", "\n").replace('\r', "\n");
|
||||
}
|
||||
self.value_bytes = self
|
||||
.value_bytes
|
||||
.checked_add(value.len())
|
||||
.filter(|size| *size <= MAX_BYTES)
|
||||
.ok_or(Error::Limit)?;
|
||||
}
|
||||
let id = self.nodes.len();
|
||||
self.nodes.push(node);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn byte(&self) -> Option<u8> {
|
||||
self.text.as_bytes().get(self.cursor).copied()
|
||||
}
|
||||
|
||||
fn sequence(&mut self, nested: bool, depth: usize) -> Result<Vec<usize>, Error> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
while let Some(byte) = self.byte() {
|
||||
if nested && byte == b'}' {
|
||||
self.cursor += 1;
|
||||
return Ok(nodes);
|
||||
}
|
||||
if byte == b'$' {
|
||||
nodes.push(self.construct(depth)?);
|
||||
} else if byte == b'\\' {
|
||||
self.cursor += 1;
|
||||
let start = self.cursor;
|
||||
if !matches!(self.byte(), Some(b'$' | b'}' | b'\\')) {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
self.cursor += 1;
|
||||
nodes.push(self.node(Node::Text(&self.text[start..self.cursor]))?);
|
||||
} else {
|
||||
let start = self.cursor;
|
||||
while let Some(next) = self.byte() {
|
||||
if next == b'$' || next == b'\\' || (nested && next == b'}') {
|
||||
break;
|
||||
}
|
||||
self.cursor += 1;
|
||||
}
|
||||
nodes.push(self.node(Node::Text(&self.text[start..self.cursor]))?);
|
||||
}
|
||||
}
|
||||
if nested {
|
||||
Err(Error::Invalid)
|
||||
} else {
|
||||
Ok(nodes)
|
||||
}
|
||||
}
|
||||
|
||||
fn construct(&mut self, depth: usize) -> Result<usize, Error> {
|
||||
self.cursor += 1;
|
||||
let braced = self.byte() == Some(b'{');
|
||||
self.cursor += usize::from(braced);
|
||||
let start = self.cursor;
|
||||
let numbered = self.byte().is_some_and(|byte| byte.is_ascii_digit());
|
||||
if numbered {
|
||||
while self.byte().is_some_and(|byte| byte.is_ascii_digit()) {
|
||||
self.cursor += 1;
|
||||
}
|
||||
} else {
|
||||
if !self
|
||||
.byte()
|
||||
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
|
||||
{
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
self.cursor += 1;
|
||||
while self
|
||||
.byte()
|
||||
.is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
|
||||
{
|
||||
self.cursor += 1;
|
||||
}
|
||||
}
|
||||
let name = &self.text[start..self.cursor];
|
||||
let mut children = None;
|
||||
if braced {
|
||||
match self.byte() {
|
||||
Some(b'}') => self.cursor += 1,
|
||||
Some(b':') => {
|
||||
self.cursor += 1;
|
||||
children = Some(self.sequence(true, depth + 1)?);
|
||||
}
|
||||
Some(b'|') if numbered => {
|
||||
self.cursor += 1;
|
||||
children = Some(self.choice()?);
|
||||
}
|
||||
Some(b'/') => return Err(Error::Unsupported),
|
||||
_ => return Err(Error::Invalid),
|
||||
}
|
||||
}
|
||||
if numbered {
|
||||
let index = name.parse::<u32>().map_err(|_| Error::Limit)?;
|
||||
self.node(Node::Stop(index, children))
|
||||
} else {
|
||||
match (self.variable)(name) {
|
||||
Some(value) if !value.is_empty() => self.node(Node::Value(value)),
|
||||
value => match children {
|
||||
Some(children) => self.node(Node::Default(children)),
|
||||
None if value.is_some() => self.node(Node::Text("")),
|
||||
None => Err(Error::Unsupported),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn choice(&mut self) -> Result<Vec<usize>, Error> {
|
||||
let mut first = String::new();
|
||||
let mut keep = true;
|
||||
loop {
|
||||
match self.byte().ok_or(Error::Invalid)? {
|
||||
b'|' => {
|
||||
self.cursor += 1;
|
||||
if self.byte() != Some(b'}') {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
self.cursor += 1;
|
||||
return Ok(vec![self.node(Node::Value(first))?]);
|
||||
}
|
||||
b',' => {
|
||||
keep = false;
|
||||
self.cursor += 1;
|
||||
}
|
||||
b'\\' => {
|
||||
self.cursor += 1;
|
||||
let byte = self.byte().ok_or(Error::Invalid)?;
|
||||
if !matches!(byte, b'$' | b'}' | b'\\' | b',' | b'|') {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
if keep {
|
||||
first.push(byte as char);
|
||||
}
|
||||
self.cursor += 1;
|
||||
}
|
||||
_ => {
|
||||
let ch = self.text[self.cursor..].chars().next().unwrap();
|
||||
if keep {
|
||||
first.push(ch);
|
||||
}
|
||||
self.cursor += ch.len_utf8();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Render<'a> {
|
||||
nodes: &'a [Node<'a>],
|
||||
definitions: &'a BTreeMap<u32, usize>,
|
||||
text: String,
|
||||
stops: BTreeMap<u32, SnippetTabstop>,
|
||||
ancestors: Vec<u32>,
|
||||
occurrences: usize,
|
||||
work: usize,
|
||||
}
|
||||
|
||||
impl Render<'_> {
|
||||
fn sequence(&mut self, nodes: &[usize], depth: usize) -> Result<(), Error> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
let arena = self.nodes;
|
||||
for &id in nodes {
|
||||
self.work += 1;
|
||||
if self.work > MAX_WORK {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
match &arena[id] {
|
||||
Node::Text(text) => self.append(text)?,
|
||||
Node::Value(text) => self.append(text)?,
|
||||
Node::Default(children) => self.sequence(children, depth + 1)?,
|
||||
Node::Stop(index, _) => {
|
||||
if self.occurrences == MAX_STOPS {
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
self.occurrences += 1;
|
||||
let start = self.text.len();
|
||||
let ancestors = self.ancestors.clone();
|
||||
if let Some(&definition) = self.definitions.get(index) {
|
||||
if self.ancestors.contains(index) {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
self.ancestors.push(*index);
|
||||
if let Node::Stop(_, Some(children)) = &arena[definition] {
|
||||
self.sequence(children, depth + 1)?;
|
||||
}
|
||||
self.ancestors.pop();
|
||||
}
|
||||
let stop = self.stops.entry(*index).or_insert_with(|| SnippetTabstop {
|
||||
index: *index,
|
||||
ranges: Vec::new(),
|
||||
ancestors: Vec::new(),
|
||||
});
|
||||
stop.ranges.push(start..self.text.len());
|
||||
stop.ancestors.push(ancestors);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append(&mut self, text: &str) -> Result<(), Error> {
|
||||
if self
|
||||
.text
|
||||
.len()
|
||||
.checked_add(text.len())
|
||||
.is_none_or(|size| size > MAX_BYTES)
|
||||
{
|
||||
return Err(Error::Limit);
|
||||
}
|
||||
self.text.push_str(text);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
// These fixtures intentionally contain ranges, not lists of indices.
|
||||
#[allow(clippy::single_range_in_vec_init)]
|
||||
#[path = "../tests/unit/snippet.rs"]
|
||||
mod tests;
|
||||
+887
-756
File diff suppressed because it is too large
Load Diff
+114
-78
@@ -3,6 +3,7 @@ use std::path::Path;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub(super) struct LanguageSpec {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
pub language: tree_sitter::Language,
|
||||
pub highlights: &'static str,
|
||||
@@ -46,6 +47,39 @@ static CPP_HIGHLIGHTS: LazyLock<String> = LazyLock::new(|| {
|
||||
]
|
||||
.join("\n")
|
||||
});
|
||||
static MD_HIGHLIGHTS: LazyLock<String> = LazyLock::new(|| {
|
||||
[
|
||||
tree_sitter_md::HIGHLIGHT_QUERY_BLOCK,
|
||||
"
|
||||
[
|
||||
(atx_h1_marker)
|
||||
(atx_h2_marker)
|
||||
(atx_h3_marker)
|
||||
(atx_h4_marker)
|
||||
(atx_h5_marker)
|
||||
(atx_h6_marker)
|
||||
(setext_h1_underline)
|
||||
(setext_h2_underline)
|
||||
] @text.title
|
||||
|
||||
[
|
||||
(list_marker_minus)
|
||||
(list_marker_plus)
|
||||
(list_marker_star)
|
||||
(list_marker_dot)
|
||||
(list_marker_parenthesis)
|
||||
] @markup.list
|
||||
",
|
||||
]
|
||||
.join("\n")
|
||||
});
|
||||
|
||||
// Upstream's Lua patterns are regex-compatible; spell-check metadata is not a color.
|
||||
static ZIG_HIGHLIGHTS: LazyLock<String> = LazyLock::new(|| {
|
||||
tree_sitter_zig::HIGHLIGHTS_QUERY
|
||||
.replace("#lua-match?", "#match?")
|
||||
.replace(" @spell", "")
|
||||
});
|
||||
|
||||
// The MIT-licensed upstream C++ crate bundles, but does not export, injections.scm.
|
||||
// This minimal AST query uses its raw-string delimiter/content nodes:
|
||||
@@ -56,6 +90,32 @@ const CPP_INJECTIONS: &str = "
|
||||
(raw_string_content) @injection.content)
|
||||
";
|
||||
|
||||
// The Typst crate exports its grammar but not queries. Use its AST nodes with
|
||||
// Vamp's supported capture roles, and standard captures for raw-code injections.
|
||||
const TYPST_HIGHLIGHTS: &str = r#"
|
||||
(comment) @comment
|
||||
(string) @string
|
||||
(number) @number
|
||||
[(bool) (none) (auto)] @keyword
|
||||
[
|
||||
"let" "if" "else" "while" "for" "in" "import" "as" "include"
|
||||
"show" "set" "return" "break" "continue" "context" "and" "or" "not"
|
||||
] @keyword
|
||||
(call item: (ident) @function)
|
||||
(call item: (field field: (ident) @function))
|
||||
[
|
||||
(heading) (emph) (strong) (url) (label) (ref) (symbol)
|
||||
(raw_blck) (raw_span)
|
||||
] @markup
|
||||
(item "-" @markup.list)
|
||||
(term ["/" ":"] @markup.list)
|
||||
"#;
|
||||
const TYPST_INJECTIONS: &str = "
|
||||
(raw_blck
|
||||
lang: (ident) @injection.language
|
||||
(blob) @injection.content)
|
||||
";
|
||||
|
||||
fn javascript_injections() -> &'static str {
|
||||
// The trailing upstream hbs/@glimmer rule uses a nonstandard #offset! directive,
|
||||
// not injection.* captures. Glimmer is outside the selected language set;
|
||||
@@ -67,6 +127,7 @@ fn javascript_injections() -> &'static str {
|
||||
}
|
||||
|
||||
fn spec(
|
||||
id: &'static str,
|
||||
name: &'static str,
|
||||
language: tree_sitter::Language,
|
||||
highlights: &'static str,
|
||||
@@ -74,6 +135,7 @@ fn spec(
|
||||
locals: &'static str,
|
||||
) -> LanguageSpec {
|
||||
LanguageSpec {
|
||||
id,
|
||||
name,
|
||||
language,
|
||||
highlights,
|
||||
@@ -82,9 +144,10 @@ fn spec(
|
||||
}
|
||||
}
|
||||
|
||||
static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
static LANGUAGES: LazyLock<[LanguageSpec; 21]> = LazyLock::new(|| {
|
||||
[
|
||||
spec(
|
||||
super::RUST_ID,
|
||||
"Rust",
|
||||
tree_sitter_rust::LANGUAGE.into(),
|
||||
tree_sitter_rust::HIGHLIGHTS_QUERY,
|
||||
@@ -92,6 +155,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
super::RUBY_ID,
|
||||
"Ruby",
|
||||
tree_sitter_ruby::LANGUAGE.into(),
|
||||
tree_sitter_ruby::HIGHLIGHTS_QUERY,
|
||||
@@ -99,6 +163,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
tree_sitter_ruby::LOCALS_QUERY,
|
||||
),
|
||||
spec(
|
||||
super::PYTHON_ID,
|
||||
"Python",
|
||||
tree_sitter_python::LANGUAGE.into(),
|
||||
tree_sitter_python::HIGHLIGHTS_QUERY,
|
||||
@@ -106,6 +171,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"json",
|
||||
"JSON",
|
||||
tree_sitter_json::LANGUAGE.into(),
|
||||
tree_sitter_json::HIGHLIGHTS_QUERY,
|
||||
@@ -113,6 +179,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"shellscript",
|
||||
"Bash",
|
||||
tree_sitter_bash::LANGUAGE.into(),
|
||||
tree_sitter_bash::HIGHLIGHT_QUERY,
|
||||
@@ -120,6 +187,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"makefile",
|
||||
"Makefile",
|
||||
tree_sitter_make::LANGUAGE.into(),
|
||||
tree_sitter_make::HIGHLIGHTS_QUERY,
|
||||
@@ -127,13 +195,15 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"markdown",
|
||||
"Markdown",
|
||||
tree_sitter_md::LANGUAGE.into(),
|
||||
tree_sitter_md::HIGHLIGHT_QUERY_BLOCK,
|
||||
MD_HIGHLIGHTS.as_str(),
|
||||
tree_sitter_md::INJECTION_QUERY_BLOCK,
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"javascript",
|
||||
"JavaScript",
|
||||
tree_sitter_javascript::LANGUAGE.into(),
|
||||
JS_HIGHLIGHTS.as_str(),
|
||||
@@ -141,6 +211,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
tree_sitter_javascript::LOCALS_QUERY,
|
||||
),
|
||||
spec(
|
||||
"typescript",
|
||||
"TypeScript",
|
||||
tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
|
||||
TS_HIGHLIGHTS.as_str(),
|
||||
@@ -148,6 +219,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
TS_LOCALS.as_str(),
|
||||
),
|
||||
spec(
|
||||
"html",
|
||||
"HTML",
|
||||
tree_sitter_html::LANGUAGE.into(),
|
||||
tree_sitter_html::HIGHLIGHTS_QUERY,
|
||||
@@ -155,6 +227,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"css",
|
||||
"CSS",
|
||||
tree_sitter_css::LANGUAGE.into(),
|
||||
tree_sitter_css::HIGHLIGHTS_QUERY,
|
||||
@@ -162,6 +235,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"yaml",
|
||||
"YAML",
|
||||
tree_sitter_yaml::LANGUAGE.into(),
|
||||
tree_sitter_yaml::HIGHLIGHTS_QUERY,
|
||||
@@ -169,6 +243,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"toml",
|
||||
"TOML",
|
||||
tree_sitter_toml_ng::LANGUAGE.into(),
|
||||
tree_sitter_toml_ng::HIGHLIGHTS_QUERY,
|
||||
@@ -176,6 +251,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"c",
|
||||
"C",
|
||||
tree_sitter_c::LANGUAGE.into(),
|
||||
tree_sitter_c::HIGHLIGHT_QUERY,
|
||||
@@ -183,6 +259,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"cpp",
|
||||
"C++",
|
||||
tree_sitter_cpp::LANGUAGE.into(),
|
||||
CPP_HIGHLIGHTS.as_str(),
|
||||
@@ -190,6 +267,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"go",
|
||||
"Go",
|
||||
tree_sitter_go::LANGUAGE.into(),
|
||||
tree_sitter_go::HIGHLIGHTS_QUERY,
|
||||
@@ -197,6 +275,7 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"typescriptreact",
|
||||
"TypeScript",
|
||||
tree_sitter_typescript::LANGUAGE_TSX.into(),
|
||||
TSX_HIGHLIGHTS.as_str(),
|
||||
@@ -204,12 +283,37 @@ static LANGUAGES: LazyLock<[LanguageSpec; 18]> = LazyLock::new(|| {
|
||||
TS_LOCALS.as_str(),
|
||||
),
|
||||
spec(
|
||||
"markdown",
|
||||
"Markdown inline",
|
||||
tree_sitter_md::INLINE_LANGUAGE.into(),
|
||||
tree_sitter_md::HIGHLIGHT_QUERY_INLINE,
|
||||
tree_sitter_md::INJECTION_QUERY_INLINE,
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"zig",
|
||||
"Zig",
|
||||
tree_sitter_zig::LANGUAGE.into(),
|
||||
ZIG_HIGHLIGHTS.as_str(),
|
||||
tree_sitter_zig::INJECTIONS_QUERY,
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
"honey",
|
||||
"Honey",
|
||||
tree_sitter_honey::LANGUAGE.into(),
|
||||
tree_sitter_honey::HIGHLIGHTS_QUERY,
|
||||
"",
|
||||
"",
|
||||
),
|
||||
spec(
|
||||
super::TYPST_ID,
|
||||
"Typst",
|
||||
tree_sitter_typst::LANGUAGE.into(),
|
||||
TYPST_HIGHLIGHTS,
|
||||
TYPST_INJECTIONS,
|
||||
"",
|
||||
),
|
||||
]
|
||||
});
|
||||
|
||||
@@ -248,6 +352,9 @@ pub(super) fn by_name(name: &str) -> Option<&'static LanguageSpec> {
|
||||
("cpp", "C++"),
|
||||
("cxx", "C++"),
|
||||
("golang", "Go"),
|
||||
("hon", "Honey"),
|
||||
("honeylang", "Honey"),
|
||||
("typ", "Typst"),
|
||||
];
|
||||
let name = ALIASES
|
||||
.iter()
|
||||
@@ -302,6 +409,9 @@ fn detect_path(path: &Path) -> Option<&'static LanguageSpec> {
|
||||
"cc" | "cpp" | "cxx" | "c++" | "hh" | "hpp" | "hxx" | "h++" | "ipp" | "inl"
|
||||
| "tpp" => "C++",
|
||||
"go" => "Go",
|
||||
"zig" => "Zig",
|
||||
"hon" => "Honey",
|
||||
"typ" => "Typst",
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
@@ -344,79 +454,5 @@ fn detect_shebang(line: &str) -> Option<&'static LanguageSpec> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selected_files_and_auxiliary_grammars_are_registered() {
|
||||
assert_eq!(all().count(), 18);
|
||||
assert!(all().all(|spec| !spec.highlights.is_empty()));
|
||||
for (filename, language) in [
|
||||
("main.rs", "Rust"),
|
||||
("Gemfile", "Ruby"),
|
||||
("main.py", "Python"),
|
||||
("package.json", "JSON"),
|
||||
(".bashrc", "Bash"),
|
||||
("GNUmakefile", "Makefile"),
|
||||
("README.md", "Markdown"),
|
||||
("main.jsx", "JavaScript"),
|
||||
("main.ts", "TypeScript"),
|
||||
("index.html", "HTML"),
|
||||
("style.css", "CSS"),
|
||||
("config.yml", "YAML"),
|
||||
("Cargo.toml", "TOML"),
|
||||
("Cargo.lock", "TOML"),
|
||||
("main.c", "C"),
|
||||
("main.cpp", "C++"),
|
||||
("main.C", "C++"),
|
||||
("main.go", "Go"),
|
||||
] {
|
||||
assert_eq!(
|
||||
detect(Some(Path::new(filename)), None).map(|spec| spec.name),
|
||||
Some(language)
|
||||
);
|
||||
}
|
||||
let ts = detect(Some(Path::new("main.ts")), None).unwrap();
|
||||
let tsx = detect(Some(Path::new("main.tsx")), None).unwrap();
|
||||
assert_eq!(ts.name, tsx.name);
|
||||
assert!(!std::ptr::eq(ts, tsx));
|
||||
assert_ne!(ts.language, tsx.language);
|
||||
assert!(std::ptr::eq(tsx, by_name("TSX").unwrap()));
|
||||
assert!(by_name("markdown_inline").is_some());
|
||||
for filename in [
|
||||
"notes.txt",
|
||||
"main.hs",
|
||||
"main.scala",
|
||||
"main.lua",
|
||||
"Dockerfile",
|
||||
] {
|
||||
assert!(detect(Some(Path::new(filename)), None).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shebangs_support_bom_env_options_and_filename_precedence() {
|
||||
for (line, language) in [
|
||||
("#!/usr/bin/python3", "Python"),
|
||||
("\u{feff}#!/usr/bin/env -S python3.12 -u", "Python"),
|
||||
("#!/usr/bin/env -u PYTHONHOME FOO=bar python3", "Python"),
|
||||
("#!/usr/bin/ruby3.3", "Ruby"),
|
||||
("#!/bin/bash", "Bash"),
|
||||
("#! /usr/bin/env node", "JavaScript"),
|
||||
] {
|
||||
assert_eq!(
|
||||
detect(None, Some(line)).map(|spec| spec.name),
|
||||
Some(language)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
detect(Some(Path::new("main.rs")), Some("#!/bin/bash"))
|
||||
.unwrap()
|
||||
.name,
|
||||
"Rust"
|
||||
);
|
||||
assert!(detect(None, Some("#!/usr/bin/python-not-real")).is_none());
|
||||
assert!(detect(None, Some("#!/usr/bin/perl")).is_none());
|
||||
assert!(detect(None, Some("plain text")).is_none());
|
||||
}
|
||||
}
|
||||
#[path = "../../tests/unit/syntax_languages.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::{self, Write},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyEventState, KeyModifiers};
|
||||
|
||||
const QUERY_TIMEOUT: Duration = Duration::from_millis(250);
|
||||
// TODO: Remove periodic polling once a released Herdr fix reliably delivers palette-ready
|
||||
// DEC 2031 notifications, including changes with unchanged light/dark preference.
|
||||
// Verify notification-triggered queries return fresh colors before removing this fallback.
|
||||
// Upstream: https://github.com/herdrdev/herdr/issues/4183
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const ESCAPE_TIMEOUT: Duration = Duration::from_millis(25);
|
||||
const HEADERS: [&[u8]; 3] = [b"11;", b"4;1;", b"4;2;"];
|
||||
const MAX_BODY: usize = 32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ThemeColors {
|
||||
pub background: [u8; 3],
|
||||
pub red: [u8; 3],
|
||||
pub green: [u8; 3],
|
||||
}
|
||||
|
||||
struct Query {
|
||||
deadline: Instant,
|
||||
colors: [Option<[u8; 3]>; 3],
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum Capture {
|
||||
#[default]
|
||||
Idle,
|
||||
Escape(Instant),
|
||||
Report(Instant),
|
||||
Terminator,
|
||||
}
|
||||
|
||||
/// Adapts crossterm's key-shaped OSC replies without reading from stdin itself.
|
||||
/// Only complete color reports are consumed; rejected candidates retain their
|
||||
/// original events, including modifiers, kind, and state.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TerminalColors {
|
||||
pub colors: Option<ThemeColors>,
|
||||
query: Option<Query>,
|
||||
refresh_at: Option<Instant>,
|
||||
capture: Capture,
|
||||
original: Vec<Event>,
|
||||
body: [u8; MAX_BODY],
|
||||
len: usize,
|
||||
ready: VecDeque<Event>,
|
||||
}
|
||||
|
||||
impl TerminalColors {
|
||||
pub fn refresh_due(&self, now: Instant) -> bool {
|
||||
self.query.is_none() && self.refresh_at.is_none_or(|deadline| now >= deadline)
|
||||
}
|
||||
|
||||
pub fn query(&mut self, output: &mut impl Write, now: Instant) -> io::Result<()> {
|
||||
self.expire(now);
|
||||
self.refresh_at = Some(now + REFRESH_INTERVAL);
|
||||
self.query = None;
|
||||
if let Err(error) = output
|
||||
.write_all(b"\x1b]11;?\x1b\\\x1b]4;1;?;2;?\x1b\\")
|
||||
.and_then(|()| output.flush())
|
||||
{
|
||||
self.colors = None;
|
||||
return Err(error);
|
||||
}
|
||||
self.query = Some(Query {
|
||||
deadline: now + QUERY_TIMEOUT,
|
||||
colors: [None; 3],
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn push(&mut self, event: Event, now: Instant) {
|
||||
self.expire(now);
|
||||
self.accept(event, now);
|
||||
}
|
||||
|
||||
pub fn expire(&mut self, now: Instant) {
|
||||
if self
|
||||
.query
|
||||
.as_ref()
|
||||
.is_some_and(|query| now >= query.deadline)
|
||||
{
|
||||
self.query = None;
|
||||
self.colors = None;
|
||||
}
|
||||
let ambiguous_expired = match self.capture {
|
||||
Capture::Escape(deadline) => now >= deadline,
|
||||
Capture::Report(deadline) => {
|
||||
now >= deadline
|
||||
&& !HEADERS
|
||||
.iter()
|
||||
.any(|header| self.body[..self.len].starts_with(header))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if ambiguous_expired {
|
||||
self.replay();
|
||||
}
|
||||
// Retain a bounded, recognized OSC candidate across query expiry: a
|
||||
// late remainder must still be swallowed, not inserted into the editor.
|
||||
// Neither late replies nor partial triples can update the palette.
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Option<Event> {
|
||||
self.ready.pop_front()
|
||||
}
|
||||
|
||||
fn accept(&mut self, event: Event, now: Instant) {
|
||||
let token = token(&event);
|
||||
match self.capture {
|
||||
Capture::Idle => match token {
|
||||
Token::Start => {
|
||||
self.original.push(event);
|
||||
self.capture = Capture::Report(now + QUERY_TIMEOUT);
|
||||
}
|
||||
Token::Escape => {
|
||||
self.original.push(event);
|
||||
self.capture = Capture::Escape(now + ESCAPE_TIMEOUT);
|
||||
}
|
||||
_ => self.ready.push_back(event),
|
||||
},
|
||||
Capture::Escape(_) if matches!(token, Token::Byte(b']')) => {
|
||||
self.original.push(event);
|
||||
self.capture = Capture::Report(now + QUERY_TIMEOUT);
|
||||
}
|
||||
Capture::Report(_) if matches!(token, Token::Escape) => {
|
||||
self.original.push(event);
|
||||
self.capture = Capture::Terminator;
|
||||
}
|
||||
Capture::Report(_) if matches!(token, Token::End) => {
|
||||
self.original.push(event);
|
||||
self.finish();
|
||||
}
|
||||
Capture::Terminator if matches!(token, Token::Byte(b'\\')) => {
|
||||
self.original.push(event);
|
||||
self.finish();
|
||||
}
|
||||
Capture::Report(_) => {
|
||||
if let Token::Byte(byte) = token
|
||||
&& self.len < MAX_BODY
|
||||
{
|
||||
self.body[self.len] = byte;
|
||||
if report_prefix(&self.body[..self.len + 1]) {
|
||||
self.len += 1;
|
||||
self.original.push(event);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.replay();
|
||||
self.accept(event, now);
|
||||
}
|
||||
_ => {
|
||||
self.replay();
|
||||
self.accept(event, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
let Some((slot, color)) = parse_report(&self.body[..self.len]) else {
|
||||
self.replay();
|
||||
return;
|
||||
};
|
||||
self.original.clear();
|
||||
self.len = 0;
|
||||
self.capture = Capture::Idle;
|
||||
let Some(query) = self.query.as_mut() else {
|
||||
return;
|
||||
};
|
||||
query.colors[slot] = Some(color);
|
||||
if let [Some(background), Some(red), Some(green)] = query.colors {
|
||||
self.colors = Some(ThemeColors {
|
||||
background,
|
||||
red,
|
||||
green,
|
||||
});
|
||||
self.query = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn replay(&mut self) {
|
||||
self.ready.extend(self.original.drain(..));
|
||||
self.len = 0;
|
||||
self.capture = Capture::Idle;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Token {
|
||||
Start,
|
||||
End,
|
||||
Escape,
|
||||
Byte(u8),
|
||||
Other,
|
||||
}
|
||||
|
||||
fn token(event: &Event) -> Token {
|
||||
let Event::Key(key) = event else {
|
||||
return Token::Other;
|
||||
};
|
||||
if key.kind != KeyEventKind::Press || key.state != KeyEventState::NONE {
|
||||
return Token::Other;
|
||||
}
|
||||
match (key.code, key.modifiers) {
|
||||
(KeyCode::Char(']'), KeyModifiers::ALT) => Token::Start,
|
||||
(KeyCode::Char('\\'), KeyModifiers::ALT) | (KeyCode::Char('g'), KeyModifiers::CONTROL) => {
|
||||
Token::End
|
||||
}
|
||||
(KeyCode::Esc, KeyModifiers::NONE) => Token::Escape,
|
||||
(KeyCode::Char(ch), modifiers)
|
||||
if ch.is_ascii()
|
||||
&& (modifiers == KeyModifiers::NONE
|
||||
|| (ch.is_ascii_uppercase() && modifiers == KeyModifiers::SHIFT)) =>
|
||||
{
|
||||
Token::Byte(ch as u8)
|
||||
}
|
||||
_ => Token::Other,
|
||||
}
|
||||
}
|
||||
|
||||
fn report_prefix(body: &[u8]) -> bool {
|
||||
HEADERS.iter().any(|header| {
|
||||
header.starts_with(body) || body.strip_prefix(*header).is_some_and(color_prefix)
|
||||
})
|
||||
}
|
||||
|
||||
fn color_prefix(color: &[u8]) -> bool {
|
||||
if b"rgb:".starts_with(color) {
|
||||
return true;
|
||||
}
|
||||
if let Some(hex) = color.strip_prefix(b"#") {
|
||||
return hex.len() <= 6 && hex.iter().all(u8::is_ascii_hexdigit);
|
||||
}
|
||||
let Some(rgb) = color.strip_prefix(b"rgb:") else {
|
||||
return false;
|
||||
};
|
||||
let mut components = rgb.split(|&byte| byte == b'/');
|
||||
for index in 0..3 {
|
||||
let Some(component) = components.next() else {
|
||||
return true;
|
||||
};
|
||||
if component.len() > 4 || !component.iter().all(u8::is_ascii_hexdigit) {
|
||||
return false;
|
||||
}
|
||||
if component.is_empty() && (index < 2 && components.clone().next().is_some()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
components.next().is_none()
|
||||
}
|
||||
|
||||
fn parse_report(body: &[u8]) -> Option<(usize, [u8; 3])> {
|
||||
for (slot, header) in HEADERS.iter().enumerate() {
|
||||
if let Some(color) = body.strip_prefix(*header) {
|
||||
return parse_color(color).map(|color| (slot, color));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_color(color: &[u8]) -> Option<[u8; 3]> {
|
||||
let mut result = [0; 3];
|
||||
if let Some(hex) = color.strip_prefix(b"#") {
|
||||
if hex.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
for (channel, component) in result.iter_mut().zip(hex.chunks_exact(2)) {
|
||||
*channel = hex_value(component)? as u8;
|
||||
}
|
||||
return Some(result);
|
||||
}
|
||||
let mut components = color.strip_prefix(b"rgb:")?.split(|&byte| byte == b'/');
|
||||
for channel in &mut result {
|
||||
let component = components.next()?;
|
||||
if component.is_empty() || component.len() > 4 {
|
||||
return None;
|
||||
}
|
||||
let value = hex_value(component)?;
|
||||
let maximum = (1_u32 << (component.len() * 4)) - 1;
|
||||
*channel = ((value * 255 + maximum / 2) / maximum) as u8;
|
||||
}
|
||||
components.next().is_none().then_some(result)
|
||||
}
|
||||
|
||||
fn hex_value(component: &[u8]) -> Option<u32> {
|
||||
component.iter().try_fold(0, |value, &byte| {
|
||||
(byte as char).to_digit(16).map(|digit| value * 16 + digit)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/terminal_colors.rs"]
|
||||
mod tests;
|
||||
+6383
-3477
File diff suppressed because it is too large
Load Diff
+96
@@ -0,0 +1,96 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
use crate::tui::TAB_WIDTH;
|
||||
|
||||
/// Terminal-cell coordinates in the original source line, including its tab stops.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct Segment {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WrapCache {
|
||||
key: Option<(usize, u64)>,
|
||||
width: usize,
|
||||
rows: BTreeMap<usize, Vec<Segment>>,
|
||||
}
|
||||
|
||||
impl WrapCache {
|
||||
pub(crate) fn prepare(&mut self, key: (usize, u64), width: usize) {
|
||||
let width = width.max(1);
|
||||
if self.key != Some(key) || self.width != width {
|
||||
self.rows.clear();
|
||||
self.key = Some(key);
|
||||
self.width = width;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn segments(&mut self, row: usize, text: &str) -> &[Segment] {
|
||||
let width = self.width.max(1);
|
||||
self.rows.entry(row).or_insert_with(|| {
|
||||
let mut segments = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut column = 0;
|
||||
let mut word_boundary = 0;
|
||||
let mut content_end = 0;
|
||||
for grapheme in text.graphemes(true) {
|
||||
let cells = if grapheme == "\t" {
|
||||
TAB_WIDTH - column % TAB_WIDTH
|
||||
} else {
|
||||
UnicodeWidthStr::width(grapheme)
|
||||
};
|
||||
if column + cells - start > width && column > start {
|
||||
let end = if word_boundary > start {
|
||||
word_boundary
|
||||
} else {
|
||||
column
|
||||
};
|
||||
segments.push(Segment { start, end });
|
||||
start = end;
|
||||
if column + cells - start > width && column > start {
|
||||
segments.push(Segment { start, end: column });
|
||||
start = column;
|
||||
}
|
||||
}
|
||||
if grapheme == "\t" {
|
||||
// Tabs are expanded cells, so even a one-column pane preserves them.
|
||||
while column + cells - start > width {
|
||||
let end = start + width;
|
||||
segments.push(Segment { start, end });
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
column += cells;
|
||||
if !grapheme.chars().all(char::is_whitespace) {
|
||||
content_end = column;
|
||||
} else if content_end > start {
|
||||
// A word break must not leave only whitespace on this visual row.
|
||||
word_boundary = column;
|
||||
}
|
||||
}
|
||||
segments.push(Segment { start, end: column });
|
||||
// A full final segment has no spare cell for the insertion caret.
|
||||
if column - start >= width {
|
||||
segments.push(Segment {
|
||||
start: column,
|
||||
end: column,
|
||||
});
|
||||
}
|
||||
segments
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn caret_segment(segments: &[Segment], column: usize) -> usize {
|
||||
segments
|
||||
.partition_point(|segment| segment.start <= column)
|
||||
.saturating_sub(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/wrap.rs"]
|
||||
mod tests;
|
||||
@@ -1 +0,0 @@
|
||||
hello
|
||||
@@ -0,0 +1,437 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use vamp::editor::{Editor, Feature, Input};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-commands-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
fn editor(&self, name: &str, text: &str) -> Editor {
|
||||
let path = self.0.join(name);
|
||||
fs::write(&path, text).unwrap();
|
||||
Editor::open(Some(path), vec!["text".into()]).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(editor: &mut Editor, text: &str) {
|
||||
for input in [Input::Char('i'), Input::Paste(text.into()), Input::Escape] {
|
||||
editor.handle(input);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_w_preserve_spaced_path_arguments_and_write_current_contents() {
|
||||
for command in ["save", "w"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("original file.txt", "original\n");
|
||||
insert(&mut editor, "changed ");
|
||||
let destination = fixture.0.join("saved file with spaces.txt");
|
||||
|
||||
editor.execute(&format!(":{command} {}", destination.display()));
|
||||
|
||||
assert_eq!(editor.path(), Some(destination.as_path()), "{command}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(&destination).unwrap(),
|
||||
"changed original\n"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("original file.txt")).unwrap(),
|
||||
"original\n"
|
||||
);
|
||||
assert!(!editor.dirty(), "{command}");
|
||||
assert!(!editor.should_quit(), "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_and_q_refuse_dirty_buffers_then_exit_when_clean() {
|
||||
for command in ["quit", "q"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("file.txt", "original\n");
|
||||
insert(&mut editor, "changed ");
|
||||
|
||||
editor.execute(command);
|
||||
|
||||
assert!(!editor.should_quit(), "{command}");
|
||||
assert!(editor.dirty(), "{command}");
|
||||
assert_eq!(editor.context().text, "changed original\n");
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("file.txt")).unwrap(),
|
||||
"original\n"
|
||||
);
|
||||
|
||||
editor.handle(Input::Char('u'));
|
||||
assert!(!editor.dirty(), "{command}");
|
||||
editor.execute(command);
|
||||
assert!(editor.should_quit(), "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_quit_and_q_bang_validate_arguments_before_discarding_changes() {
|
||||
for command in ["force_quit", "q!"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("file.txt", "original\n");
|
||||
insert(&mut editor, "changed ");
|
||||
|
||||
editor.execute(&format!("{command} unexpected argument"));
|
||||
|
||||
assert!(!editor.should_quit(), "{command}");
|
||||
assert!(editor.dirty(), "{command}");
|
||||
assert_eq!(editor.context().text, "changed original\n");
|
||||
|
||||
editor.execute(command);
|
||||
assert!(editor.should_quit(), "{command}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("file.txt")).unwrap(),
|
||||
"original\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_next_and_bnext_preserve_each_buffers_dirty_text_and_undo() {
|
||||
for command in ["buffer_next", "bnext"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("first.txt", "first\n");
|
||||
let first_id = editor.buffer_id();
|
||||
insert(&mut editor, "changed ");
|
||||
let second_path = fixture.0.join("second file.txt");
|
||||
fs::write(&second_path, "second\n").unwrap();
|
||||
editor.execute(&format!("edit {}", second_path.display()));
|
||||
let second_id = editor.buffer_id();
|
||||
assert_ne!(first_id, second_id);
|
||||
insert(&mut editor, "edited ");
|
||||
|
||||
editor.execute(command);
|
||||
|
||||
assert_eq!(editor.buffer_id(), first_id, "{command}");
|
||||
assert_eq!(editor.context().text, "changed first\n");
|
||||
assert!(editor.dirty(), "{command}");
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "first\n");
|
||||
assert!(!editor.dirty(), "{command}");
|
||||
|
||||
editor.execute(command);
|
||||
|
||||
assert_eq!(editor.buffer_id(), second_id, "{command}");
|
||||
assert_eq!(editor.context().text, "edited second\n");
|
||||
assert!(editor.dirty(), "{command}");
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "second\n");
|
||||
assert!(!editor.dirty(), "{command}");
|
||||
assert_eq!(editor.buffer_count(), 2);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("first.txt")).unwrap(),
|
||||
"first\n"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&second_path).unwrap(), "second\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_closes_clean_buffers_across_tabs_and_panes_but_preserves_dirty_history() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("first.txt", "first\n");
|
||||
let first_id = editor.buffer_id();
|
||||
insert(&mut editor, "changed ");
|
||||
editor.handle(Input::Char('0'));
|
||||
insert(&mut editor, "extra ");
|
||||
let first_redo_text = editor.context().text;
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "changed first\n");
|
||||
|
||||
editor.execute("pane.split_vertical");
|
||||
let clean_path = fixture.0.join("clean.txt");
|
||||
fs::write(&clean_path, "clean\n").unwrap();
|
||||
editor.execute(&format!("edit {}", clean_path.display()));
|
||||
let clean_id = editor.buffer_id();
|
||||
editor.execute("tab.new");
|
||||
let second_path = fixture.0.join("second.txt");
|
||||
fs::write(&second_path, "second\n").unwrap();
|
||||
editor.execute(&format!("edit {}", second_path.display()));
|
||||
let second_id = editor.buffer_id();
|
||||
insert(&mut editor, "edited ");
|
||||
editor.execute("pane.split_horizontal");
|
||||
let active_clean_path = fixture.0.join("active-clean.txt");
|
||||
fs::write(&active_clean_path, "active clean\n").unwrap();
|
||||
editor.execute(&format!("edit {}", active_clean_path.display()));
|
||||
let active_clean_id = editor.buffer_id();
|
||||
assert_eq!(editor.tab_count(), 2);
|
||||
assert_eq!(editor.pane_layout().len(), 2);
|
||||
|
||||
editor.execute(":restart");
|
||||
|
||||
assert!(!editor.should_restart());
|
||||
assert!(!editor.should_quit());
|
||||
assert!(editor.message().to_lowercase().contains("unsaved"));
|
||||
assert_eq!(editor.buffer_count(), 2);
|
||||
assert!(!editor.has_buffer(clean_id));
|
||||
assert!(!editor.has_buffer(active_clean_id));
|
||||
assert!(editor.has_buffer(first_id));
|
||||
assert!(editor.has_buffer(second_id));
|
||||
editor.execute(&format!("buffer {first_id}"));
|
||||
assert_eq!(editor.buffer_id(), first_id);
|
||||
assert_eq!(editor.context().text, "changed first\n");
|
||||
assert!(editor.dirty());
|
||||
editor.handle(Input::Char('U'));
|
||||
assert_eq!(editor.context().text, first_redo_text);
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "changed first\n");
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "first\n");
|
||||
editor.handle(Input::Char('U'));
|
||||
assert_eq!(editor.context().text, "changed first\n");
|
||||
editor.execute("save");
|
||||
editor.execute(&format!("buffer {second_id}"));
|
||||
assert_eq!(editor.buffer_id(), second_id);
|
||||
assert_eq!(editor.context().text, "edited second\n");
|
||||
assert!(editor.dirty());
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "second\n");
|
||||
editor.handle(Input::Char('U'));
|
||||
assert_eq!(editor.context().text, "edited second\n");
|
||||
editor.execute("save");
|
||||
|
||||
editor.execute(":restart");
|
||||
|
||||
assert!(editor.should_restart());
|
||||
assert!(editor.should_quit());
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("first.txt")).unwrap(),
|
||||
"changed first\n"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(second_path).unwrap(), "edited second\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_commands_validate_arguments_before_closing_or_discarding_buffers() {
|
||||
for command in ["restart", "force_restart", "restart!"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("dirty.txt", "original\n");
|
||||
let dirty_id = editor.buffer_id();
|
||||
insert(&mut editor, "changed ");
|
||||
let clean_path = fixture.0.join("clean.txt");
|
||||
fs::write(&clean_path, "clean\n").unwrap();
|
||||
editor.execute(&format!("edit {}", clean_path.display()));
|
||||
let clean_id = editor.buffer_id();
|
||||
|
||||
editor.execute(&format!(":{command} unexpected argument"));
|
||||
|
||||
assert!(!editor.should_restart(), "{command}");
|
||||
assert!(!editor.should_quit(), "{command}");
|
||||
assert_eq!(editor.buffer_count(), 2, "{command}");
|
||||
assert_eq!(editor.buffer_id(), clean_id, "{command}");
|
||||
assert!(editor.has_buffer(dirty_id), "{command}");
|
||||
editor.execute(&format!("buffer {dirty_id}"));
|
||||
assert_eq!(editor.context().text, "changed original\n", "{command}");
|
||||
assert!(editor.dirty(), "{command}");
|
||||
editor.handle(Input::Char('u'));
|
||||
assert_eq!(editor.context().text, "original\n", "{command}");
|
||||
editor.handle(Input::Char('U'));
|
||||
assert_eq!(editor.context().text, "changed original\n", "{command}");
|
||||
|
||||
if command != "restart" {
|
||||
editor.execute(&format!(":{command}"));
|
||||
assert!(editor.should_restart(), "{command}");
|
||||
assert!(editor.should_quit(), "{command}");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("dirty.txt")).unwrap(),
|
||||
"original\n",
|
||||
"{command}"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(clean_path).unwrap(), "clean\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_restart_bindings_execute_directly_without_force_confirmation() {
|
||||
for action in ["core.restart", "core.force_restart"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("file.txt", "original\n");
|
||||
editor.bind("normal", "x", Some(action.into())).unwrap();
|
||||
if action == "core.force_restart" {
|
||||
insert(&mut editor, "changed ");
|
||||
}
|
||||
|
||||
editor.handle(Input::Char('x'));
|
||||
|
||||
assert!(editor.should_restart(), "{action}");
|
||||
assert!(editor.should_quit(), "{action}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("file.txt")).unwrap(),
|
||||
"original\n",
|
||||
"{action}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_canonical_and_alias_collisions_reject_the_entire_feature() {
|
||||
for reserved in ["save", "w", "quit", "q"] {
|
||||
let mut editor = Editor::open(None, vec!["text".into()]).unwrap();
|
||||
let feature = |commands: Vec<String>| Feature {
|
||||
name: "example".into(),
|
||||
required_capabilities: vec!["text".into()],
|
||||
commands,
|
||||
core: false,
|
||||
};
|
||||
|
||||
assert!(
|
||||
editor
|
||||
.register(feature(vec!["example.run".into(), reserved.into()]))
|
||||
.is_err(),
|
||||
"{reserved}"
|
||||
);
|
||||
assert!(editor.execute("example.run").is_none(), "{reserved}");
|
||||
|
||||
editor
|
||||
.register(feature(vec!["example.run".into()]))
|
||||
.unwrap();
|
||||
let invocation = editor.execute("example.run remaining args").unwrap();
|
||||
assert_eq!(invocation.plugin, "example");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn executable_restart_keeps_the_alternate_screen_and_restores_terminal_on_exit() {
|
||||
for scenario in ["quit", "startup-error"] {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.0.join("startup file.txt");
|
||||
fs::write(&path, "SCREEN_HANDOFF_DOCUMENT\n").unwrap();
|
||||
let output =
|
||||
std::process::Command::new(std::env::var_os("VAMP_RUBY").unwrap_or_else(|| "ruby".into()))
|
||||
.args([
|
||||
"-rpty",
|
||||
"-rtimeout",
|
||||
"-rio/console",
|
||||
"-e",
|
||||
r#"
|
||||
scenario, binary, path = ARGV
|
||||
captured = +"".b
|
||||
status = nil
|
||||
PTY.spawn({"TERM" => "xterm-256color"}, binary, "--no-config", "--", path) do |output, input, pid|
|
||||
phase = 0
|
||||
begin
|
||||
input.winsize = [24, 100]
|
||||
Timeout.timeout(20) do
|
||||
loop do
|
||||
if IO.select([output], nil, nil, 0.05)
|
||||
begin
|
||||
chunk = output.read_nonblock(65536)
|
||||
captured << chunk
|
||||
STDOUT.write(chunk)
|
||||
rescue IO::WaitReadable
|
||||
rescue EOFError, Errno::EIO
|
||||
end
|
||||
end
|
||||
unless status
|
||||
waited = Process.waitpid2(pid, Process::WNOHANG)
|
||||
status = waited[1] if waited
|
||||
end
|
||||
if status
|
||||
# waitpid can win the race with the final output read.
|
||||
loop do
|
||||
begin
|
||||
chunk = output.read_nonblock(65536)
|
||||
captured << chunk
|
||||
STDOUT.write(chunk)
|
||||
rescue IO::WaitReadable, EOFError, Errno::EIO
|
||||
break
|
||||
end
|
||||
end
|
||||
break
|
||||
end
|
||||
|
||||
# A fresh process re-enables input reporting before its first repaint.
|
||||
# Command-overlay frames must not be mistaken for a relaunched editor.
|
||||
sessions = captured.split("\e[?2004h", -1)
|
||||
next unless sessions.length == phase + 2
|
||||
frame = sessions.last
|
||||
next unless frame.include?("\e[?2026l")
|
||||
visible = frame.gsub(/\e\[[0-?]*[ -\/]*[@-~]/, "")
|
||||
next unless visible.include?("SCREEN_HANDOFF_DOCUMENT")
|
||||
raise "alternate screen re-entered during restart" unless captured.scan("\e[?1049h").length == 1
|
||||
raise "normal screen exposed during restart" if captured.include?("\e[?1049l")
|
||||
|
||||
if scenario == "startup-error"
|
||||
File.binwrite(path, "\xff".b)
|
||||
input.write(":restart\r")
|
||||
else
|
||||
input.write([":restart\r", ":restart!\r", ":q\r"].fetch(phase))
|
||||
end
|
||||
input.flush
|
||||
phase += 1
|
||||
end
|
||||
|
||||
expected_phases = scenario == "quit" ? 3 : 1
|
||||
raise "exited before requested restart/quit" unless phase == expected_phases
|
||||
raise "unexpected exit status: #{status.inspect}" unless status.success? == (scenario == "quit")
|
||||
# Inspect the master: macOS revokes slave descriptors when their session exits.
|
||||
raise "terminal echo was not restored" unless input.echo?
|
||||
settings = IO.popen(["stty", "-a"], in: input, &:read)
|
||||
raise "terminal remained noncanonical: #{settings}" unless settings.match?(/(?:^|[;\s])icanon(?:[;\s]|$)/)
|
||||
end
|
||||
ensure
|
||||
unless status
|
||||
begin
|
||||
Process.kill("KILL", pid)
|
||||
rescue Errno::ESRCH
|
||||
end
|
||||
begin
|
||||
Process.waitpid(pid)
|
||||
rescue Errno::ECHILD
|
||||
end
|
||||
end
|
||||
input.close
|
||||
end
|
||||
end
|
||||
"#,
|
||||
"--",
|
||||
scenario,
|
||||
env!("CARGO_BIN_EXE_vamp"),
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("Ruby with stdlib PTY and io/console is required (set VAMP_RUBY)");
|
||||
let captured = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{scenario}: {}\nterminal output: {captured:?}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
assert_eq!(
|
||||
captured.matches("\x1b[?1049h").count(),
|
||||
1,
|
||||
"{scenario}: {captured:?}",
|
||||
);
|
||||
assert_eq!(
|
||||
captured.matches("\x1b[?1049l").count(),
|
||||
1,
|
||||
"{scenario}: {captured:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use vamp::{
|
||||
diff::{ComparisonMode, Phase},
|
||||
editor::Input,
|
||||
session::EditorSession,
|
||||
};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-diff-session-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(root.join("repo")).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
fn git(&self, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(self.0.join("repo"))
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_AUTHOR_NAME", "Diff Fixture")
|
||||
.env("GIT_AUTHOR_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_COMMITTER_NAME", "Diff Fixture")
|
||||
.env("GIT_COMMITTER_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_AUTHOR_DATE", "2000-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2000-01-01T00:00:00Z")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
|
||||
fn jj(&self, args: &[&str]) -> String {
|
||||
let output = Command::new("jj")
|
||||
.args(args)
|
||||
.current_dir(self.0.join("repo"))
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.env("JJ_USER", "Diff Fixture")
|
||||
.env("JJ_EMAIL", "fixture@example.invalid")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_until(session: &mut EditorSession, ready: impl Fn(&EditorSession) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !ready(session) {
|
||||
session.poll();
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"diff state: {:?}",
|
||||
session.editor().diff()
|
||||
);
|
||||
if let Some(diff) = session.editor().diff() {
|
||||
assert!(diff.error.is_none(), "{:?}", diff.error);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn type_query(session: &mut EditorSession, text: &str) {
|
||||
for ch in text.chars() {
|
||||
session.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_diff_edits_unsaved_working_after_and_preserves_undo_on_explicit_close() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.git(&["init", "-q"]);
|
||||
let source = fixture.0.join("repo/buffer.rs");
|
||||
fs::write(&source, "before\n").unwrap();
|
||||
fixture.git(&["add", "buffer.rs"]);
|
||||
fixture.git(&["commit", "-qm", "base"]);
|
||||
let base = fixture.git(&["rev-parse", "HEAD"]);
|
||||
fs::write(&source, "after\n").unwrap();
|
||||
let config = fixture.0.join("config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.clipboard_mode = 'separate'\n config.bind 'leader d', config.core.diff\nend\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut session =
|
||||
EditorSession::open(Some(source.clone()), vec!["text".into()], Some(&config)).unwrap();
|
||||
assert!(session.editor().startup_diagnostic().is_none());
|
||||
for input in [Input::Char('i'), Input::Char('u'), Input::Escape] {
|
||||
session.handle(input);
|
||||
}
|
||||
let cursor = session.editor().cursor();
|
||||
session.handle(Input::Char(' '));
|
||||
session.handle(Input::Char('d'));
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
type_query(&mut session, &base);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
assert_eq!(session.editor().diff().unwrap().phase, Phase::After);
|
||||
session.handle(Input::Enter);
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().comparison_mode,
|
||||
ComparisonMode::Snapshots
|
||||
);
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
let comparison = session
|
||||
.editor()
|
||||
.diff()
|
||||
.unwrap()
|
||||
.comparison
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert_eq!(comparison.files.len(), 1);
|
||||
let file = &comparison.files[0];
|
||||
assert_eq!(file.path, Path::new("buffer.rs"));
|
||||
assert_eq!(file.before, ["before"]);
|
||||
assert_eq!(file.after, ["uafter", ""]);
|
||||
session.handle(Input::Char('\t'));
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().focus,
|
||||
vamp::diff::Focus::Before
|
||||
);
|
||||
for input in [
|
||||
Input::Char('i'),
|
||||
Input::Char('x'),
|
||||
Input::Paste("overwrite".into()),
|
||||
] {
|
||||
session.handle(input);
|
||||
}
|
||||
session.handle(Input::Escape);
|
||||
assert!(session.editor().diff().is_some());
|
||||
assert_eq!(session.editor().context().text, "before\n");
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), "after\n");
|
||||
|
||||
session.handle(Input::Char('\t'));
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().focus,
|
||||
vamp::diff::Focus::After
|
||||
);
|
||||
assert_eq!(session.editor().context().text, "uafter\n");
|
||||
assert_eq!(session.editor().cursor(), cursor);
|
||||
for input in [Input::Char('i'), Input::Char('x'), Input::Escape] {
|
||||
session.handle(input);
|
||||
}
|
||||
assert_eq!(session.editor().context().text, "xuafter\n");
|
||||
assert!(session.editor().diff().is_some());
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(session.editor().context().text, "uafter\n");
|
||||
session.handle(Input::Char('U'));
|
||||
assert_eq!(session.editor().context().text, "xuafter\n");
|
||||
session.execute("w");
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), "xuafter\n");
|
||||
assert!(!session.editor().dirty());
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(session.editor().context().text, "uafter\n");
|
||||
assert!(session.editor().dirty());
|
||||
|
||||
session.execute("diff.close");
|
||||
assert!(session.editor().diff().is_none());
|
||||
assert_eq!(session.editor().context().text, "uafter\n");
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(session.editor().context().text, "after\n");
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), "xuafter\n");
|
||||
session.execute(":diff");
|
||||
assert!(session.editor().diff().is_some());
|
||||
session.execute("diff.close");
|
||||
session.poll();
|
||||
assert!(session.editor().diff().is_none());
|
||||
assert_eq!(fixture.git(&["rev-parse", "HEAD"]), base);
|
||||
assert_eq!(fixture.git(&["status", "--porcelain"]), "M buffer.rs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_keep_repository_workers_and_hidden_comparisons_independent() {
|
||||
let first = Fixture::new();
|
||||
let second = Fixture::new();
|
||||
for (fixture, before, after) in [
|
||||
(&first, "first before\n", "first after\n"),
|
||||
(&second, "second before\n", "second after\n"),
|
||||
] {
|
||||
fixture.git(&["init", "-q"]);
|
||||
fs::write(fixture.0.join("repo/source.txt"), before).unwrap();
|
||||
fixture.git(&["add", "source.txt"]);
|
||||
fixture.git(&["commit", "-qm", "base"]);
|
||||
fs::write(fixture.0.join("repo/source.txt"), after).unwrap();
|
||||
}
|
||||
let first_path = first.0.join("repo/source.txt");
|
||||
let second_path = second.0.join("repo/source.txt");
|
||||
let config = first.0.join("config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.bind 'ctrl+option+n', config.core.tab.new\n config.bind 'ctrl+option+w', config.core.tab.close\nend\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut session =
|
||||
EditorSession::open(Some(first_path.clone()), vec!["text".into()], Some(&config)).unwrap();
|
||||
assert!(session.editor().startup_diagnostic().is_none());
|
||||
session.execute("diff");
|
||||
session.handle(Input::CtrlAlt('n'));
|
||||
session.execute(&format!("edit {}", second_path.display()));
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
session.handle(Input::CtrlAlt('h'));
|
||||
assert_eq!(session.editor().tab_index(), 0);
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
type_query(&mut session, &first.git(&["rev-parse", "HEAD"]));
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::CtrlAlt('l'));
|
||||
assert_eq!(session.editor().tab_index(), 1);
|
||||
type_query(&mut session, &second.git(&["rev-parse", "HEAD"]));
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::Enter);
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
let comparison = session
|
||||
.editor()
|
||||
.diff()
|
||||
.unwrap()
|
||||
.comparison
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
comparison.root,
|
||||
second.0.join("repo").canonicalize().unwrap()
|
||||
);
|
||||
assert_eq!(comparison.files[0].before, ["second before"]);
|
||||
assert_eq!(comparison.files[0].after, ["second after", ""]);
|
||||
session.handle(Input::CtrlAlt('h'));
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
let comparison = session
|
||||
.editor()
|
||||
.diff()
|
||||
.unwrap()
|
||||
.comparison
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
comparison.root,
|
||||
first.0.join("repo").canonicalize().unwrap()
|
||||
);
|
||||
assert_eq!(comparison.files[0].before, ["first before"]);
|
||||
assert_eq!(comparison.files[0].after, ["first after", ""]);
|
||||
session.handle(Input::CtrlAlt('l'));
|
||||
session.handle(Input::CtrlAlt('w'));
|
||||
assert_eq!(session.editor().tab_count(), 1);
|
||||
assert!(session.editor().diff().is_some());
|
||||
session.execute("diff.close");
|
||||
assert_eq!(session.editor().path(), Some(first_path.as_path()));
|
||||
assert_eq!(session.editor().lines(), ["first after", ""]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editable_diff_navigation_skips_omitted_lines_without_expanding_excerpts() {
|
||||
use vamp::diff::DisplayRow;
|
||||
|
||||
let fixture = Fixture::new();
|
||||
fixture.git(&["init", "-q"]);
|
||||
let source = fixture.0.join("repo/context.txt");
|
||||
let mut lines = (1..=100)
|
||||
.map(|line| format!("line_{line:03} words"))
|
||||
.collect::<Vec<_>>();
|
||||
lines[49].clear(); // Hidden short lines must not clamp the visible caret column.
|
||||
fs::write(&source, format!("{}\n", lines.join("\n"))).unwrap();
|
||||
fixture.git(&["add", "context.txt"]);
|
||||
fixture.git(&["commit", "-qm", "base"]);
|
||||
let base = fixture.git(&["rev-parse", "HEAD"]);
|
||||
lines[19] = "changed_020 words".into();
|
||||
lines[79] = "changed_080 words".into();
|
||||
let text = format!("{}\n", lines.join("\n"));
|
||||
fs::write(&source, &text).unwrap();
|
||||
let config = fixture.0.join("config.rb");
|
||||
fs::write(&config, "Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.clipboard_mode = 'separate'\n config.diff_context_lines = 1\n config.diff_expand_lines = 2\n config.bind 'ctrl+f', config.core.down\n config.bind 'ctrl+b', config.core.up\nend\n").unwrap();
|
||||
let mut session =
|
||||
EditorSession::open(Some(source.clone()), vec!["text".into()], Some(&config)).unwrap();
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
type_query(&mut session, &base);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::Enter);
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
session.handle(Input::BackTab);
|
||||
let shown = |session: &EditorSession| {
|
||||
let diff = session.editor().diff().unwrap();
|
||||
diff.display_rows
|
||||
.iter()
|
||||
.filter_map(|row| match *row {
|
||||
DisplayRow::Line(index) => diff.rows[index].after,
|
||||
DisplayRow::Fold { .. } => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let excerpts = vec![18, 19, 20, 78, 79, 80];
|
||||
assert_eq!(shown(&session), excerpts);
|
||||
assert_eq!(session.editor().cursor().row, 18);
|
||||
type_query(&mut session, "5l");
|
||||
for (keys, row) in [("2j", 20), ("j", 78), ("k", 20), ("3j", 80), ("5k", 18)] {
|
||||
type_query(&mut session, keys);
|
||||
assert_eq!(session.editor().cursor().row, row, "{keys}");
|
||||
assert_eq!(session.editor().cursor().column, 5, "{keys}");
|
||||
assert_eq!(shown(&session), excerpts, "{keys}");
|
||||
}
|
||||
for (keys, row) in [
|
||||
("gb", 80),
|
||||
("gt", 18),
|
||||
("2j$w", 78),
|
||||
("b", 20),
|
||||
("$2w", 78),
|
||||
("0B", 20),
|
||||
] {
|
||||
type_query(&mut session, keys);
|
||||
assert_eq!(session.editor().cursor().row, row, "{keys}");
|
||||
assert_eq!(shown(&session), excerpts, "{keys}");
|
||||
}
|
||||
session.handle(Input::Ctrl('f'));
|
||||
assert_eq!(session.editor().cursor().row, 78);
|
||||
session.handle(Input::Ctrl('b'));
|
||||
assert_eq!(session.editor().cursor().row, 20);
|
||||
type_query(&mut session, "Vj");
|
||||
assert_eq!(session.editor().cursor().row, 78);
|
||||
session.handle(Input::Escape);
|
||||
session.handle(Input::Ctrl('k'));
|
||||
assert_eq!(
|
||||
session
|
||||
.editor()
|
||||
.carets()
|
||||
.iter()
|
||||
.map(|caret| caret.row)
|
||||
.collect::<Vec<_>>(),
|
||||
[20, 78]
|
||||
);
|
||||
type_query(&mut session, "j");
|
||||
assert_eq!(
|
||||
session
|
||||
.editor()
|
||||
.carets()
|
||||
.iter()
|
||||
.map(|caret| caret.row)
|
||||
.collect::<Vec<_>>(),
|
||||
[78, 79]
|
||||
);
|
||||
session.handle(Input::Escape);
|
||||
type_query(&mut session, "gt2j$v");
|
||||
session.handle(Input::Ctrl('a'));
|
||||
assert_eq!(
|
||||
session
|
||||
.editor()
|
||||
.carets()
|
||||
.iter()
|
||||
.map(|caret| caret.row)
|
||||
.collect::<Vec<_>>(),
|
||||
excerpts
|
||||
);
|
||||
assert_eq!(shown(&session), excerpts);
|
||||
session.handle(Input::Escape);
|
||||
session.handle(Input::Escape);
|
||||
type_query(&mut session, "/line_040");
|
||||
session.handle(Input::Enter);
|
||||
assert_eq!(session.editor().cursor().row, 20);
|
||||
type_query(&mut session, "/line_079");
|
||||
session.handle(Input::Enter);
|
||||
assert_eq!(session.editor().cursor().row, 78);
|
||||
assert_eq!(shown(&session), excerpts);
|
||||
type_query(&mut session, "gt2ji");
|
||||
session.handle(Input::Down);
|
||||
assert_eq!(session.editor().cursor().row, 78);
|
||||
session.handle(Input::Up);
|
||||
assert_eq!(session.editor().cursor().row, 20);
|
||||
session.handle(Input::Escape);
|
||||
assert_eq!(shown(&session), excerpts);
|
||||
assert_eq!(session.editor().context().text, text);
|
||||
assert!(!session.editor().dirty());
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), text);
|
||||
type_query(&mut session, "[");
|
||||
assert_eq!(shown(&session), [16, 17, 18, 19, 20, 78, 79, 80]);
|
||||
type_query(&mut session, "]");
|
||||
assert_eq!(shown(&session), [16, 17, 18, 19, 20, 21, 22, 78, 79, 80]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_jump_history_restores_the_comparison_file_and_source_cursor() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.git(&["init", "-q"]);
|
||||
let root = fixture.0.join("repo");
|
||||
for name in ["first", "second"] {
|
||||
let mut lines = (1..=40)
|
||||
.map(|row| format!("// {name}_stable_{row:03}"))
|
||||
.collect::<Vec<_>>();
|
||||
lines[19] = format!("// {name}_before");
|
||||
fs::write(root.join(format!("{name}.rs")), lines.join("\n") + "\n").unwrap();
|
||||
}
|
||||
fixture.git(&["add", "."]);
|
||||
fixture.git(&["commit", "-qm", "base"]);
|
||||
for name in ["first", "second"] {
|
||||
let path = root.join(format!("{name}.rs"));
|
||||
let text = fs::read_to_string(&path).unwrap();
|
||||
fs::write(path, text.replace("_before", "_after")).unwrap();
|
||||
}
|
||||
let config = fixture.0.join("review-config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure { |config| config.review_directory = 'reviews' }",
|
||||
)
|
||||
.unwrap();
|
||||
let mut session =
|
||||
EditorSession::open(Some(root.join("first.rs")), vec![], Some(&config)).unwrap();
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
!session.editor().diff().unwrap().loading
|
||||
});
|
||||
for input in [Input::Down, Input::Enter, Input::Enter] {
|
||||
session.handle(input);
|
||||
}
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
session.handle(Input::Char('\t'));
|
||||
let first_origin = session.editor().cursor();
|
||||
type_query(&mut session, "/first_before");
|
||||
session.handle(Input::Enter);
|
||||
for input in [
|
||||
Input::Char(' '),
|
||||
Input::Char('e'),
|
||||
Input::Home,
|
||||
Input::Down,
|
||||
Input::Enter,
|
||||
] {
|
||||
session.handle(input);
|
||||
}
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
let second_origin = session.editor().cursor();
|
||||
type_query(&mut session, "/second_before");
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::Ctrl('o'));
|
||||
assert_eq!(session.editor().cursor(), second_origin);
|
||||
session.handle(Input::Ctrl('o'));
|
||||
assert_eq!(session.editor().diff().unwrap().file, 0);
|
||||
assert_eq!(session.editor().cursor(), first_origin);
|
||||
assert!(session.editor().context().text.contains("first_before"));
|
||||
assert!(!session.editor().context().text.contains("second_before"));
|
||||
session.execute("diff.close");
|
||||
assert_eq!(
|
||||
session.editor().context().text,
|
||||
fs::read_to_string(root.join("first.rs")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_changes_default_and_mode_switches_compare_the_selected_divergent_tips() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.0.join("repo");
|
||||
fixture.git(&["init", "-q"]);
|
||||
fs::write(root.join("common"), "common\n").unwrap();
|
||||
fixture.git(&["add", "."]);
|
||||
fixture.git(&["commit", "-qm", "common"]);
|
||||
let base = fixture.git(&["rev-parse", "HEAD"]);
|
||||
fs::write(root.join("base-only"), "base branch\n").unwrap();
|
||||
fixture.git(&["add", "."]);
|
||||
fixture.git(&["commit", "-qm", "base only"]);
|
||||
let before = fixture.git(&["rev-parse", "HEAD"]);
|
||||
fixture.git(&["checkout", "-qb", "feature", &base]);
|
||||
fs::write(root.join("feature-only"), "feature branch\n").unwrap();
|
||||
fixture.git(&["add", "."]);
|
||||
fixture.git(&["commit", "-qm", "feature only"]);
|
||||
let after = fixture.git(&["rev-parse", "HEAD"]);
|
||||
let config = fixture.0.join("config.rb");
|
||||
fs::write(&config, "Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.clipboard_mode = 'separate'\n config.bind 'ctrl+b', config.core.diff.mode.toggle\nend\n").unwrap();
|
||||
let mut session =
|
||||
EditorSession::open(Some(root.join("common")), vec![], Some(&config)).unwrap();
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
!session.editor().diff().unwrap().loading
|
||||
});
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().comparison_mode,
|
||||
ComparisonMode::BranchChanges
|
||||
);
|
||||
session.handle(Input::Ctrl('b'));
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().comparison_mode,
|
||||
ComparisonMode::Snapshots
|
||||
);
|
||||
session.handle(Input::Ctrl('p'));
|
||||
type_query(&mut session, "diff.mode.toggle");
|
||||
session.handle(Input::Enter);
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().comparison_mode,
|
||||
ComparisonMode::BranchChanges
|
||||
);
|
||||
for id in [&before, &after] {
|
||||
type_query(&mut session, id);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
let diff = session.editor().diff().unwrap();
|
||||
let comparison = diff.comparison.as_ref().unwrap();
|
||||
assert_eq!(comparison.files.len(), 1);
|
||||
assert_eq!(comparison.files[0].path, Path::new("feature-only"));
|
||||
assert_eq!(session.editor().context().text, "feature branch\n");
|
||||
assert!(diff.after_editable());
|
||||
assert_eq!(
|
||||
comparison.before,
|
||||
format!("merge base of {before} and {after} · {base}")
|
||||
);
|
||||
assert_eq!(diff.before.as_ref().unwrap().label, before);
|
||||
|
||||
session.execute("diff.mode.toggle");
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
let comparison = session
|
||||
.editor()
|
||||
.diff()
|
||||
.unwrap()
|
||||
.comparison
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert_eq!(comparison.before, before);
|
||||
assert_eq!(comparison.after, after);
|
||||
assert_eq!(
|
||||
comparison
|
||||
.files
|
||||
.iter()
|
||||
.map(|file| file.path.as_path())
|
||||
.collect::<Vec<_>>(),
|
||||
[Path::new("base-only"), Path::new("feature-only")]
|
||||
);
|
||||
|
||||
// Superseding an in-flight recomparison must not restore the old mode's result.
|
||||
session.execute("diff.mode.toggle");
|
||||
session.execute("diff.mode.toggle");
|
||||
session.execute("diff.mode.toggle");
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
let diff = session.editor().diff().unwrap();
|
||||
assert_eq!(diff.comparison_mode, ComparisonMode::BranchChanges);
|
||||
assert_eq!(diff.comparison.as_ref().unwrap().files.len(), 1);
|
||||
assert_eq!(diff.before.as_ref().unwrap().label, before);
|
||||
assert_eq!(diff.after.as_ref().unwrap().label, after);
|
||||
session.execute("diff.close");
|
||||
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
!session.editor().diff().unwrap().loading
|
||||
});
|
||||
session.handle(Input::Enter);
|
||||
let diff = session.editor().diff().unwrap();
|
||||
assert_eq!(diff.phase, Phase::After);
|
||||
assert_eq!(diff.comparison_mode, ComparisonMode::Snapshots);
|
||||
session.execute("diff.mode.toggle");
|
||||
assert_eq!(
|
||||
session.editor().diff().unwrap().comparison_mode,
|
||||
ComparisonMode::Snapshots
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jj_bookmark_picker_keeps_symbolic_targets_searchable_by_resolved_commit_id() {
|
||||
use vamp::diff::RevisionTarget;
|
||||
let fixture = Fixture::new();
|
||||
fixture.jj(&["git", "init", "--no-colocate"]);
|
||||
let source = fixture.0.join("repo/source.txt");
|
||||
fs::write(&source, "base\n").unwrap();
|
||||
fixture.jj(&["describe", "-m", "base"]);
|
||||
let before = fixture.jj(&["log", "--no-graph", "-r", "@", "-T", "commit_id"]);
|
||||
fixture.jj(&["new"]);
|
||||
fs::write(&source, "topic\n").unwrap();
|
||||
fixture.jj(&["describe", "-m", "topic"]);
|
||||
fixture.jj(&["bookmark", "create", "topic"]);
|
||||
let after = fixture.jj(&["log", "--no-graph", "-r", "@", "-T", "commit_id"]);
|
||||
fixture.jj(&["new"]);
|
||||
let config = fixture.0.join("review-config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure { |config| config.review_directory = 'reviews' }",
|
||||
)
|
||||
.unwrap();
|
||||
let mut session = EditorSession::open(Some(source), vec![], Some(&config)).unwrap();
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
!session.editor().diff().unwrap().loading
|
||||
});
|
||||
type_query(&mut session, &before);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
session.handle(Input::Char('\t'));
|
||||
type_query(&mut session, &after);
|
||||
let target = RevisionTarget::Bookmark {
|
||||
name: "topic".into(),
|
||||
remote: None,
|
||||
};
|
||||
assert_eq!(
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.unwrap()
|
||||
.entries()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.target,
|
||||
target
|
||||
);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
wait_until(&mut session, |session| {
|
||||
session.editor().diff().unwrap().selected_file_loaded()
|
||||
});
|
||||
let diff = session.editor().diff().unwrap();
|
||||
assert_eq!(
|
||||
diff.before.as_ref().unwrap().target,
|
||||
RevisionTarget::Commit(before)
|
||||
);
|
||||
assert_eq!(diff.after.as_ref().unwrap().target, target);
|
||||
assert_eq!(diff.comparison.as_ref().unwrap().files[0].after, ["topic"]);
|
||||
assert!(!diff.after_editable());
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use vamp::{
|
||||
diff::{Category, Phase, RevisionTarget},
|
||||
editor::Input,
|
||||
session::EditorSession,
|
||||
};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
target: String,
|
||||
decoy: String,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-diff-search-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(root.join("repo")).unwrap();
|
||||
let mut fixture = Self {
|
||||
root,
|
||||
target: String::new(),
|
||||
decoy: String::new(),
|
||||
};
|
||||
fixture.git(&["init", "-q", "--initial-branch=fixture-main"]);
|
||||
fixture.commit("foundation", "base");
|
||||
fixture.target = fixture.commit("Über parser target", "target");
|
||||
fixture.decoy = fixture.commit(
|
||||
&format!("release archaeology mentioning {}", fixture.target),
|
||||
"decoy",
|
||||
);
|
||||
for name in [
|
||||
"a-r_e_l_e_a_s_e",
|
||||
"release-candidate",
|
||||
"zrelease",
|
||||
"tie-a",
|
||||
"tie-b",
|
||||
] {
|
||||
fixture.git(&["branch", name, &fixture.decoy]);
|
||||
fixture.git(&["tag", name, &fixture.decoy]);
|
||||
}
|
||||
for name in ["release", "feature/parser-rewrite", "feature/Über-parser"] {
|
||||
fixture.git(&["branch", name, &fixture.target]);
|
||||
fixture.git(&["tag", name, &fixture.target]);
|
||||
}
|
||||
fixture
|
||||
}
|
||||
|
||||
fn git(&self, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(self.root.join("repo"))
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.env("GIT_AUTHOR_NAME", "Diff Search Fixture")
|
||||
.env("GIT_AUTHOR_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_COMMITTER_NAME", "Diff Search Fixture")
|
||||
.env("GIT_COMMITTER_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_AUTHOR_DATE", "2000-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2000-01-01T00:00:00Z")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
|
||||
fn commit(&self, message: &str, content: &str) -> String {
|
||||
fs::write(self.root.join("repo/source.txt"), content).unwrap();
|
||||
self.git(&["add", "source.txt"]);
|
||||
self.git(&["commit", "-qm", message]);
|
||||
self.git(&["rev-parse", "HEAD"])
|
||||
}
|
||||
|
||||
fn session(&self) -> EditorSession {
|
||||
let config = self.root.join("config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure do |config|\n config.clipboard_mode = 'separate'\nend\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut session = EditorSession::open(
|
||||
Some(self.root.join("repo/source.txt")),
|
||||
vec![],
|
||||
Some(&config),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(session.editor().startup_diagnostic().is_none());
|
||||
session.execute(":diff");
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
session
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_until(session: &mut EditorSession, ready: impl Fn(&EditorSession) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !ready(session) {
|
||||
session.poll();
|
||||
assert!(Instant::now() < deadline, "{:?}", session.editor().diff());
|
||||
if let Some(diff) = session.editor().diff() {
|
||||
assert!(diff.error.is_none(), "{:?}", diff.error);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn query(session: &mut EditorSession, text: &str) {
|
||||
session.handle(Input::Ctrl('u'));
|
||||
for ch in text.chars() {
|
||||
session.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
fn category(session: &mut EditorSession, category: Category) {
|
||||
query(session, "");
|
||||
for _ in 0..3 {
|
||||
let diff = session.editor().diff().unwrap();
|
||||
if diff.catalog.as_ref().unwrap().kind.categories()[diff.category] == category {
|
||||
return;
|
||||
}
|
||||
session.handle(Input::Char('\t'));
|
||||
}
|
||||
panic!("category unavailable: {category:?}");
|
||||
}
|
||||
|
||||
fn labels(session: &EditorSession) -> Vec<String> {
|
||||
let diff = session.editor().diff().unwrap();
|
||||
assert_eq!(
|
||||
diff.entries().next().unwrap().target,
|
||||
RevisionTarget::Working
|
||||
);
|
||||
diff.entries()
|
||||
.skip(1)
|
||||
.map(|entry| entry.label.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_and_tag_fuzzy_ranking_and_empty_order_match_in_both_selectors() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.session();
|
||||
for phase in [Phase::Before, Phase::After] {
|
||||
assert_eq!(session.editor().diff().unwrap().phase, phase);
|
||||
for kind in [Category::Branches, Category::Tags] {
|
||||
category(&mut session, kind);
|
||||
let catalogue_order = labels(&session);
|
||||
query(&mut session, " ");
|
||||
assert_eq!(labels(&session), catalogue_order);
|
||||
|
||||
query(&mut session, "release");
|
||||
assert_eq!(
|
||||
labels(&session),
|
||||
[
|
||||
"release",
|
||||
"release-candidate",
|
||||
"zrelease",
|
||||
"a-r_e_l_e_a_s_e"
|
||||
]
|
||||
);
|
||||
query(&mut session, "ftprw");
|
||||
assert_eq!(labels(&session), ["feature/parser-rewrite"]);
|
||||
query(&mut session, "tie");
|
||||
let ties: Vec<_> = catalogue_order
|
||||
.iter()
|
||||
.filter(|label| label.starts_with("tie-"))
|
||||
.cloned()
|
||||
.collect();
|
||||
assert_eq!(&labels(&session)[..ties.len()], ties);
|
||||
query(&mut session, "no-such-reference-anywhere");
|
||||
assert!(labels(&session).is_empty());
|
||||
assert_eq!(session.editor().diff().unwrap().selected, 0);
|
||||
}
|
||||
if phase == Phase::Before {
|
||||
// Even an unmatched query leaves Working selectable and pinned first.
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_tokens_and_commit_ids_search_fields_without_cross_field_subsequences() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.session();
|
||||
for phase in [Phase::Before, Phase::After] {
|
||||
assert_eq!(session.editor().diff().unwrap().phase, phase);
|
||||
category(&mut session, Category::Branches);
|
||||
for text in [
|
||||
format!("{} ÜBPR", &fixture.target[..10]),
|
||||
format!("übpr {}", &fixture.target[..10]),
|
||||
] {
|
||||
query(&mut session, &text);
|
||||
assert_eq!(labels(&session), ["feature/Über-parser"]);
|
||||
}
|
||||
|
||||
category(&mut session, Category::Commits);
|
||||
for text in [&fixture.target[..], &fixture.target[..10]] {
|
||||
query(&mut session, text);
|
||||
assert_eq!(
|
||||
labels(&session),
|
||||
[fixture.target.clone(), fixture.decoy.clone()]
|
||||
);
|
||||
}
|
||||
query(&mut session, "ÜB PRSR");
|
||||
assert_eq!(labels(&session), [fixture.target.clone()]);
|
||||
// The ID and description can satisfy separate tokens, but not one token
|
||||
// that would require a subsequence crossing between unrelated fields.
|
||||
query(&mut session, &format!("{} übpr", &fixture.target[..10]));
|
||||
assert_eq!(labels(&session), [fixture.target.clone()]);
|
||||
query(&mut session, &format!("{}über", fixture.target));
|
||||
assert!(labels(&session).is_empty());
|
||||
if phase == Phase::Before {
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_ranked_branch_uses_its_actual_commit_in_before_and_after() {
|
||||
let fixture = Fixture::new();
|
||||
for ranked_phase in [Phase::Before, Phase::After] {
|
||||
let mut session = fixture.session();
|
||||
if ranked_phase == Phase::After {
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
category(&mut session, Category::Branches);
|
||||
query(&mut session, "release");
|
||||
assert_eq!(labels(&session)[0], "release");
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
if ranked_phase == Phase::Before {
|
||||
// Working selects snapshot mode rather than merge-base mode.
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
let diff = session.editor().diff().unwrap();
|
||||
let ranked = if ranked_phase == Phase::Before {
|
||||
diff.before.as_ref().unwrap()
|
||||
} else {
|
||||
diff.after.as_ref().unwrap()
|
||||
};
|
||||
assert_eq!(ranked.label, "release");
|
||||
assert_eq!(
|
||||
ranked.target,
|
||||
RevisionTarget::Commit(fixture.target.clone())
|
||||
);
|
||||
let comparison = diff.comparison.as_ref().unwrap();
|
||||
assert_eq!(comparison.files.len(), 1);
|
||||
assert_eq!(comparison.files[0].path, Path::new("source.txt"));
|
||||
let (before, after) = if ranked_phase == Phase::Before {
|
||||
(["target"], ["decoy"])
|
||||
} else {
|
||||
(["decoy"], ["target"])
|
||||
};
|
||||
assert_eq!(comparison.files[0].before, before);
|
||||
assert_eq!(comparison.files[0].after, after);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use vamp::editor::{Cursor, Editor, Effect, Input, Mode};
|
||||
fn editor() -> Editor {
|
||||
let mut editor = Editor::open(None, vec![]).unwrap();
|
||||
editor
|
||||
.apply(vec![Effect::Replace(
|
||||
"first\n e\u{301}second\n\tthird".into(),
|
||||
)])
|
||||
.unwrap();
|
||||
editor
|
||||
}
|
||||
fn keys(editor: &mut Editor, text: &str) {
|
||||
for key in text.chars() {
|
||||
editor.handle(Input::Char(key));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn counted_g_is_one_based_clamps_and_leaves_bare_prefixes_intact() {
|
||||
let mut editor = editor();
|
||||
let revision = editor.text_revision();
|
||||
keys(&mut editor, "2g");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 1, column: 2 });
|
||||
assert_eq!(editor.count(), None);
|
||||
keys(&mut editor, "999999999999999999999999999999999g");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 2, column: 1 });
|
||||
keys(&mut editor, "1g");
|
||||
assert_eq!(editor.cursor().row, 0);
|
||||
keys(&mut editor, "gb");
|
||||
assert_eq!(editor.cursor().row, 2);
|
||||
keys(&mut editor, "gt");
|
||||
assert_eq!(editor.cursor().row, 0);
|
||||
assert_eq!(editor.text_revision(), revision);
|
||||
}
|
||||
#[test]
|
||||
fn counted_g_extends_visual_selection_and_respects_g_overrides() {
|
||||
let mut editor = editor();
|
||||
keys(&mut editor, "v3g");
|
||||
assert_eq!(editor.mode(), Mode::Visual);
|
||||
assert_eq!(editor.cursor(), Cursor { row: 2, column: 1 });
|
||||
assert_eq!(editor.selections()[0].start, Cursor { row: 0, column: 0 });
|
||||
editor.handle(Input::Escape);
|
||||
keys(&mut editor, "gt");
|
||||
editor.bind("normal", "g", None).unwrap();
|
||||
keys(&mut editor, "2g");
|
||||
assert_eq!(editor.cursor().row, 0);
|
||||
editor
|
||||
.bind("normal", "g", Some("core.down".into()))
|
||||
.unwrap();
|
||||
keys(&mut editor, "2g");
|
||||
assert_eq!(editor.cursor().row, 2);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use vamp::editor::{Editor, Effect, Input};
|
||||
#[test]
|
||||
fn yy_copies_current_whole_line_for_paste_below_it() {
|
||||
let mut editor = Editor::open(None, vec![]).unwrap();
|
||||
editor.set_clipboard_mode("separate").unwrap();
|
||||
editor
|
||||
.apply(vec![Effect::Replace("first\nsecond\n".into())])
|
||||
.unwrap();
|
||||
for key in "llyy".chars() {
|
||||
editor.handle(Input::Char(key));
|
||||
}
|
||||
assert_eq!(editor.cursor().column, 2);
|
||||
assert_eq!(editor.context().text, "first\nsecond\n");
|
||||
editor.handle(Input::Char('p'));
|
||||
assert_eq!(editor.context().text, "first\nfirst\nsecond\n");
|
||||
}
|
||||
+3749
-11
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,631 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
process::Command,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use vamp::{
|
||||
diff::{DisplayRow, Focus, Phase},
|
||||
editor::{Cursor, Editor, Input, Mode, Selection},
|
||||
session::EditorSession,
|
||||
};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-navigation-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
fn file(&self, name: &str, text: &str) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
fs::write(&path, text).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn editor(&self, text: &str) -> Editor {
|
||||
let mut editor =
|
||||
Editor::open(Some(self.file("buffer.txt", text)), vec!["text".into()]).unwrap();
|
||||
editor.set_clipboard_mode("separate").unwrap();
|
||||
editor
|
||||
}
|
||||
|
||||
fn session(&self, text: &str, bindings: &str) -> EditorSession {
|
||||
let source = self.file("buffer.txt", text);
|
||||
let config = self.file(
|
||||
"config.rb",
|
||||
&format!(
|
||||
"Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.clipboard_mode = 'separate'\n{bindings}\nend\n"
|
||||
),
|
||||
);
|
||||
let session =
|
||||
EditorSession::open(Some(source), vec!["text".into()], Some(&config)).unwrap();
|
||||
assert!(session.editor().startup_diagnostic().is_none());
|
||||
session
|
||||
}
|
||||
|
||||
fn git(&self, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(self.0.join("repo"))
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_AUTHOR_NAME", "Navigation Fixture")
|
||||
.env("GIT_AUTHOR_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_COMMITTER_NAME", "Navigation Fixture")
|
||||
.env("GIT_COMMITTER_EMAIL", "fixture@example.invalid")
|
||||
.env("GIT_AUTHOR_DATE", "2000-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2000-01-01T00:00:00Z")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(editor: &mut Editor, text: &str) {
|
||||
for ch in text.chars() {
|
||||
editor.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
fn session_keys(session: &mut EditorSession, text: &str) {
|
||||
for ch in text.chars() {
|
||||
session.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
fn palette_seek(session: &mut EditorSession, action: &str, target: char) {
|
||||
session.handle(Input::Ctrl('p'));
|
||||
session_keys(session, action);
|
||||
session.handle(Input::Enter);
|
||||
assert!(session.editor().palette().is_none());
|
||||
session.handle(Input::Char(target));
|
||||
}
|
||||
|
||||
fn wait_until(session: &mut EditorSession, ready: impl Fn(&EditorSession) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while !ready(session) {
|
||||
session.poll();
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"diff state: {:?}",
|
||||
session.editor().diff()
|
||||
);
|
||||
if let Some(diff) = session.editor().diff() {
|
||||
assert!(diff.error.is_none(), "{:?}", diff.error);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_activation_moves_onto_the_selected_word_only_when_outside_it() {
|
||||
let fixture = Fixture::new();
|
||||
for (text, column, expected) in [
|
||||
(" word word", 0, 2),
|
||||
(" word word", 1, 2),
|
||||
(" word word", 2, 2),
|
||||
(" word word", 4, 4),
|
||||
("-- word word", 0, 3),
|
||||
("\t界e\u{301} 界e\u{301}", 0, 1),
|
||||
(" .* .*", 0, 1),
|
||||
] {
|
||||
let mut editor = fixture.editor(text);
|
||||
keys(&mut editor, &"l".repeat(column));
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(
|
||||
editor.cursor(),
|
||||
Cursor {
|
||||
row: 0,
|
||||
column: expected
|
||||
},
|
||||
"{text:?}"
|
||||
);
|
||||
let first = editor.search_match().unwrap().start;
|
||||
keys(&mut editor, "*");
|
||||
assert!(editor.cursor().column > first.column, "{text:?}");
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submitting_search_keeps_each_caret_inside_a_current_match() {
|
||||
let fixture = Fixture::new();
|
||||
for (text, query, column, end) in [
|
||||
("jj next jj", "jj", 0, 2),
|
||||
("jj next jj", "jj", 1, 2),
|
||||
("界e\u{301} next 界e\u{301}", "界e\u{301}", 1, 2),
|
||||
("aaaa next aa", "aa", 1, 3),
|
||||
] {
|
||||
let mut editor = fixture.editor(text);
|
||||
keys(&mut editor, &"l".repeat(column));
|
||||
let cursor = editor.cursor();
|
||||
keys(&mut editor, &format!("/{query}"));
|
||||
editor.handle(Input::Enter);
|
||||
assert_eq!(editor.cursor(), cursor, "{text:?}");
|
||||
assert_eq!(editor.search_match().unwrap().end_column, end);
|
||||
keys(&mut editor, "n");
|
||||
assert_ne!(editor.cursor(), cursor);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
let mut editor = fixture.editor("jj next jj\n-- next jj");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
keys(&mut editor, "/jj");
|
||||
editor.handle(Input::Enter);
|
||||
assert_eq!(
|
||||
editor.carets(),
|
||||
[Cursor::default(), Cursor { row: 1, column: 8 }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_escape_hides_highlights_but_retains_search_and_rearms_star() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("cat cat");
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 2);
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 0);
|
||||
assert_eq!(editor.search_match(), None);
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 2);
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 4 });
|
||||
editor.handle(Input::Escape);
|
||||
keys(&mut editor, "n");
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 2);
|
||||
keys(&mut editor, "/missing");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 2);
|
||||
editor.handle(Input::Escape);
|
||||
editor.handle(Input::Char('/'));
|
||||
editor.handle(Input::Enter);
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
assert_eq!(editor.search_matches_on_row(0).count(), 2);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_search_arms_without_moving_then_navigates_and_rearms_for_a_new_word_or_mode() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("cat dog cat dog");
|
||||
keys(&mut editor, "l2*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 1 });
|
||||
assert_eq!(editor.search_match().unwrap().start, Cursor::default());
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 8 });
|
||||
keys(&mut editor, "w*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 12 });
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 4 });
|
||||
|
||||
keys(&mut editor, "/cat");
|
||||
editor.handle(Input::Enter);
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 8 });
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 8 });
|
||||
keys(&mut editor, "*");
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_search_keeps_whole_word_counts_history_and_literal_search_distinct() {
|
||||
let fixture = Fixture::new();
|
||||
let text = "cat\nscatter\ncat_cat\ncat2\n2cat\nCat\ncat\ncat\n\n";
|
||||
let mut editor = fixture.editor(text);
|
||||
keys(&mut editor, "l**");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 6, column: 0 });
|
||||
assert_eq!(editor.search_match().unwrap().end_column, 3);
|
||||
keys(&mut editor, "nN2*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 0 });
|
||||
editor.handle(Input::Ctrl('o'));
|
||||
assert_eq!(editor.cursor(), Cursor { row: 6, column: 0 });
|
||||
editor.handle(Input::Char('\t'));
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 0 });
|
||||
|
||||
keys(&mut editor, "/scatter");
|
||||
editor.handle(Input::Escape);
|
||||
editor.handle(Input::Char('/'));
|
||||
editor.handle(Input::Enter);
|
||||
assert_eq!(editor.cursor(), Cursor::default());
|
||||
keys(&mut editor, "gb*");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 9, column: 0 });
|
||||
keys(&mut editor, "n");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 0 });
|
||||
|
||||
keys(&mut editor, "/cat");
|
||||
editor.handle(Input::Enter);
|
||||
keys(&mut editor, "n");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 1, column: 1 });
|
||||
assert_eq!(editor.search_match().unwrap().end_column, 4);
|
||||
assert_eq!(editor.context().text, text);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_search_uses_unicode_words_and_vim_same_line_fallbacks() {
|
||||
let fixture = Fixture::new();
|
||||
for (text, positioning, row, length) in [
|
||||
("e\u{301}lan\ne\u{301}lanx\ne\u{301}lan", "l", 2, 4),
|
||||
("世界\n世界中\n世界", "l", 2, 2),
|
||||
("snake_case\nsnake_case2\nsnake_case", "3l", 2, 10),
|
||||
("\t-- word\nword", "", 1, 4),
|
||||
("-- word\nword", "", 1, 4),
|
||||
("word --\n--", "$", 1, 2),
|
||||
(" .* \n.*", "", 1, 2),
|
||||
("👩🚀\n👩\n👩🚀", "", 2, 1),
|
||||
("only", "l", 0, 4),
|
||||
] {
|
||||
let mut editor = fixture.editor(text);
|
||||
keys(&mut editor, positioning);
|
||||
editor.handle(Input::Char('*'));
|
||||
editor.handle(Input::Char('*'));
|
||||
assert_eq!(editor.cursor(), Cursor { row, column: 0 }, "{text:?}");
|
||||
assert_eq!(
|
||||
editor.search_match().unwrap().end_column,
|
||||
length,
|
||||
"{text:?}"
|
||||
);
|
||||
keys(&mut editor, "Nn");
|
||||
assert_eq!(editor.cursor(), Cursor { row, column: 0 }, "{text:?}");
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_search_rebinding_moves_all_carets_and_remains_view_local() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.session(
|
||||
"cat cat_cat cat cat\ncat cat_cat cat cat",
|
||||
" config.bind '*', nil\n config.bind 'q', config.core.search_word",
|
||||
);
|
||||
session.handle(Input::Ctrl('e'));
|
||||
session_keys(&mut session, "2q");
|
||||
assert_eq!(
|
||||
session.editor().carets(),
|
||||
[Cursor::default(), Cursor { row: 1, column: 0 }]
|
||||
);
|
||||
session_keys(&mut session, "2q");
|
||||
assert_eq!(
|
||||
session.editor().carets(),
|
||||
[Cursor { row: 0, column: 16 }, Cursor { row: 1, column: 16 }]
|
||||
);
|
||||
session_keys(&mut session, "|2N");
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 1, column: 0 });
|
||||
session_keys(&mut session, "/cat");
|
||||
session.handle(Input::Enter);
|
||||
session_keys(&mut session, "n");
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 1, column: 4 });
|
||||
session.handle(Input::Alt('h'));
|
||||
session_keys(&mut session, "2N");
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 1, column: 0 });
|
||||
assert!(!session.editor().dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counted_character_seeks_move_every_native_caret_independently() {
|
||||
let fixture = Fixture::new();
|
||||
let text = "xaxbx tail\nx---x----x tail\nx only\n";
|
||||
let mut editor = fixture.editor(text);
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
assert_eq!(editor.selection_count(), 3);
|
||||
|
||||
keys(&mut editor, "2fx");
|
||||
assert_eq!(
|
||||
editor.carets(),
|
||||
[
|
||||
Cursor { row: 0, column: 4 },
|
||||
Cursor { row: 1, column: 9 },
|
||||
Cursor { row: 2, column: 0 },
|
||||
]
|
||||
);
|
||||
keys(&mut editor, "2Fx");
|
||||
assert_eq!(
|
||||
editor.carets(),
|
||||
[
|
||||
Cursor { row: 0, column: 0 },
|
||||
Cursor { row: 1, column: 0 },
|
||||
Cursor { row: 2, column: 0 },
|
||||
]
|
||||
);
|
||||
assert_eq!(editor.context().text, text);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_character_and_line_seeks_yank_the_selected_text_into_another_buffer() {
|
||||
for (mode, expected) in [('v', "a x x"), ('V', "a x xx tail\n")] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("a x xx tail\n");
|
||||
editor.handle(Input::Char(mode));
|
||||
keys(&mut editor, "2fx");
|
||||
assert_eq!(editor.mode(), Mode::Visual);
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 4 });
|
||||
assert_eq!(editor.visual_linewise(), mode == 'V');
|
||||
assert_eq!(
|
||||
editor.selections(),
|
||||
[Selection {
|
||||
start: Cursor { row: 0, column: 0 },
|
||||
end: if mode == 'V' {
|
||||
Cursor { row: 1, column: 0 }
|
||||
} else {
|
||||
Cursor { row: 0, column: 5 }
|
||||
},
|
||||
}]
|
||||
);
|
||||
editor.handle(Input::Char('y'));
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
|
||||
let destination = fixture.file("destination.txt", "");
|
||||
editor.execute(&format!("edit {}", destination.display()));
|
||||
editor.handle(Input::Char('P'));
|
||||
assert_eq!(editor.context().text, expected, "{mode}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("buffer.txt")).unwrap(),
|
||||
"a x xx tail\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_ruby_seek_remaps_and_palette_actions_preserve_normal_and_visual_navigation() {
|
||||
let fixture = Fixture::new();
|
||||
let text = "a x x tail\n";
|
||||
let mut session = fixture.session(
|
||||
text,
|
||||
r#" config.bind 'leader s', config.core.seek_forward
|
||||
config.bind 'leader r', config.core.seek_backward
|
||||
config.bind 'leader s', config.core.seek_forward, mode: config.modes.visual
|
||||
config.bind 'leader r', config.core.seek_backward, mode: config.modes.visual"#,
|
||||
);
|
||||
session_keys(&mut session, "2 sx");
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 0, column: 4 });
|
||||
session_keys(&mut session, " rx");
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 0, column: 2 });
|
||||
|
||||
session_keys(&mut session, "v sx");
|
||||
let expanded = [Selection {
|
||||
start: Cursor { row: 0, column: 2 },
|
||||
end: Cursor { row: 0, column: 5 },
|
||||
}];
|
||||
assert_eq!(session.editor().selections(), expanded);
|
||||
session_keys(&mut session, " rx");
|
||||
let contracted = [Selection {
|
||||
start: Cursor { row: 0, column: 2 },
|
||||
end: Cursor { row: 0, column: 3 },
|
||||
}];
|
||||
assert_eq!(session.editor().selections(), contracted);
|
||||
palette_seek(&mut session, "core.seek_forward", 'x');
|
||||
assert_eq!(session.editor().mode(), Mode::Visual);
|
||||
assert_eq!(session.editor().selections(), expanded);
|
||||
palette_seek(&mut session, "core.seek_backward", 'x');
|
||||
assert_eq!(session.editor().selections(), contracted);
|
||||
|
||||
session.handle(Input::Escape);
|
||||
palette_seek(&mut session, "core.seek_forward", 'x');
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 0, column: 4 });
|
||||
palette_seek(&mut session, "core.seek_backward", 'x');
|
||||
assert_eq!(session.editor().cursor(), Cursor { row: 0, column: 2 });
|
||||
assert_eq!(session.editor().mode(), Mode::Normal);
|
||||
assert_eq!(session.editor().context().text, text);
|
||||
assert!(!session.editor().dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeating_a_visual_seek_change_resolves_the_counted_character_on_the_new_line() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.session(
|
||||
"a x x tail\nlong x gap x tail\n",
|
||||
" config.bind 'leader s', config.core.seek_forward, mode: config.modes.visual",
|
||||
);
|
||||
session_keys(&mut session, "v2 sxc!");
|
||||
session.handle(Input::Escape);
|
||||
assert_eq!(
|
||||
session.editor().context().text,
|
||||
"! tail\nlong x gap x tail\n"
|
||||
);
|
||||
|
||||
session_keys(&mut session, "j0.");
|
||||
assert_eq!(session.editor().context().text, "! tail\n! tail\n");
|
||||
assert_eq!(session.editor().mode(), Mode::Normal);
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(
|
||||
session.editor().context().text,
|
||||
"! tail\nlong x gap x tail\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_before_and_historical_after_seeks_preserve_snapshots_and_folded_excerpts() {
|
||||
let fixture = Fixture::new();
|
||||
fs::create_dir_all(fixture.0.join("repo")).unwrap();
|
||||
fixture.git(&["init", "-q"]);
|
||||
let source = fixture.0.join("repo/context.txt");
|
||||
let mut lines = (1..=40)
|
||||
.map(|row| format!("stable_{row:03} [x] [x]"))
|
||||
.collect::<Vec<_>>();
|
||||
lines[19] = "before x x tail".into();
|
||||
let before_text = lines.join("\n") + "\n";
|
||||
fs::write(&source, &before_text).unwrap();
|
||||
fixture.git(&["add", "context.txt"]);
|
||||
fixture.git(&["commit", "-qm", "before"]);
|
||||
let before = fixture.git(&["rev-parse", "HEAD"]);
|
||||
lines[19] = "after x x tail".into();
|
||||
let after_text = lines.join("\n") + "\n";
|
||||
fs::write(&source, &after_text).unwrap();
|
||||
fixture.git(&["commit", "-qam", "after"]);
|
||||
let after = fixture.git(&["rev-parse", "HEAD"]);
|
||||
fixture.git(&["checkout", "--detach", &before]);
|
||||
lines[19] = "working x x tail".into();
|
||||
let working_text = lines.join("\n") + "\n";
|
||||
fs::write(&source, &working_text).unwrap();
|
||||
let config = fixture.file(
|
||||
"config.rb",
|
||||
"Vamp.configure do |config|\n config.review_directory = 'reviews'\n config.clipboard_mode = 'separate'\n config.diff_context_lines = 1\n config.diff_expand_lines = 2\nend\n",
|
||||
);
|
||||
let mut session =
|
||||
EditorSession::open(Some(source.clone()), vec!["text".into()], Some(&config)).unwrap();
|
||||
assert!(session.editor().startup_diagnostic().is_none());
|
||||
session_keys(&mut session, "iunsaved ");
|
||||
session.handle(Input::Escape);
|
||||
let unsaved_text = session.editor().context().text;
|
||||
let original_cursor = session.editor().cursor();
|
||||
|
||||
session.execute("diff");
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.catalog.is_some() && !diff.loading)
|
||||
});
|
||||
for revision in [&before, &after] {
|
||||
session_keys(&mut session, revision);
|
||||
session.handle(Input::Down);
|
||||
session.handle(Input::Enter);
|
||||
}
|
||||
wait_until(&mut session, |session| {
|
||||
session
|
||||
.editor()
|
||||
.diff()
|
||||
.is_some_and(|diff| diff.phase == Phase::View && diff.selected_file_loaded())
|
||||
});
|
||||
let excerpts = session.editor().diff().unwrap().display_rows.clone();
|
||||
assert!(
|
||||
excerpts
|
||||
.iter()
|
||||
.any(|row| matches!(row, DisplayRow::Fold { .. }))
|
||||
);
|
||||
|
||||
for (focus, text, first_x, second_x) in [
|
||||
(Focus::Before, &before_text, 7, 9),
|
||||
(Focus::After, &after_text, 6, 8),
|
||||
] {
|
||||
for _ in 0..3 {
|
||||
if session.editor().diff().unwrap().focus == focus {
|
||||
break;
|
||||
}
|
||||
session.handle(Input::Char('\t'));
|
||||
}
|
||||
assert_eq!(session.editor().diff().unwrap().focus, focus);
|
||||
let revision = session.editor().text_revision();
|
||||
session_keys(&mut session, "gt02f[");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 18,
|
||||
column: 15
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "F[f]");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 18,
|
||||
column: 13
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "j02fx");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 19,
|
||||
column: second_x
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "*");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 19,
|
||||
column: second_x
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "*");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 20,
|
||||
column: 12
|
||||
}
|
||||
);
|
||||
assert_eq!(session.editor().search_match().unwrap().end_column, 13);
|
||||
session_keys(&mut session, "3*N");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 18,
|
||||
column: 12
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "3n");
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 19,
|
||||
column: second_x
|
||||
}
|
||||
);
|
||||
session_keys(&mut session, "Fxvfx");
|
||||
assert_eq!(
|
||||
session.editor().selections(),
|
||||
[Selection {
|
||||
start: Cursor {
|
||||
row: 19,
|
||||
column: first_x
|
||||
},
|
||||
end: Cursor {
|
||||
row: 19,
|
||||
column: second_x + 1
|
||||
},
|
||||
}]
|
||||
);
|
||||
session_keys(&mut session, "yVfx");
|
||||
assert!(session.editor().visual_linewise());
|
||||
assert_eq!(
|
||||
session.editor().cursor(),
|
||||
Cursor {
|
||||
row: 19,
|
||||
column: second_x
|
||||
}
|
||||
);
|
||||
session.handle(Input::Escape);
|
||||
assert_eq!(session.editor().context().text, *text);
|
||||
assert_eq!(session.editor().text_revision(), revision);
|
||||
assert!(!session.editor().dirty());
|
||||
assert_eq!(session.editor().diff().unwrap().display_rows, excerpts);
|
||||
}
|
||||
|
||||
session.execute("diff.close");
|
||||
assert_eq!(session.editor().context().text, unsaved_text);
|
||||
assert_eq!(session.editor().cursor(), original_cursor);
|
||||
assert!(session.editor().dirty());
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), working_text);
|
||||
assert_eq!(fixture.git(&["rev-parse", "HEAD"]), before);
|
||||
}
|
||||
@@ -0,0 +1,772 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use vamp::editor::{Cursor, Editor, Input, Mode};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-normal-editing-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
fn editor(&self, text: &str) -> Editor {
|
||||
let path = self.0.join("buffer.txt");
|
||||
fs::write(&path, text).unwrap();
|
||||
let mut editor = Editor::open(Some(path), vec!["text".into()]).unwrap();
|
||||
editor.set_clipboard_mode("separate").unwrap();
|
||||
editor
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(editor: &mut Editor, text: &str) {
|
||||
for ch in text.chars() {
|
||||
editor.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_x_cuts_the_hovered_grapheme_for_paste() {
|
||||
for grapheme in ["b", "e\u{301}", "👩🚀"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(&format!("a{grapheme}z\n"));
|
||||
keys(&mut editor, "lx");
|
||||
assert_eq!(editor.context().text, "az\n");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, format!("a{grapheme}z\n"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_delete_and_remapped_action_copy_characterwise() {
|
||||
for input in [Input::Delete, Input::Char('q')] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abz\n");
|
||||
editor
|
||||
.bind("normal", "q", Some("core.delete".into()))
|
||||
.unwrap();
|
||||
keys(&mut editor, "yyl");
|
||||
editor.handle(input);
|
||||
assert_eq!(editor.context().text, "az\n");
|
||||
keys(&mut editor, "uUP");
|
||||
assert_eq!(editor.context().text, "abz\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_x_repeat_copies_current_graphemes_and_preserves_empty_line_clipboard() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc\n\nxyz\n");
|
||||
keys(&mut editor, "x.");
|
||||
assert_eq!(editor.context().text, "c\n\nxyz\n");
|
||||
keys(&mut editor, "jxjP");
|
||||
assert_eq!(editor.context().text, "c\n\nbxyz\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_x_cuts_at_every_caret_without_crossing_empty_lines() {
|
||||
let fixture = Fixture::new();
|
||||
let source = "a👩🚀z\n\nbe\u{301}y\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
keys(&mut editor, "x");
|
||||
assert_eq!(editor.context().text, "az\n\nby\n");
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_delete_and_its_repeat_do_not_overwrite_clipboard() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc\nxyz\n");
|
||||
keys(&mut editor, "vyi");
|
||||
editor.handle(Input::Delete);
|
||||
editor.handle(Input::Escape);
|
||||
keys(&mut editor, "j.");
|
||||
assert_eq!(editor.context().text, "bc\nyz\n");
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, "bc\nayz\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_r_replaces_selected_graphemes_as_one_undo_edit() {
|
||||
let fixture = Fixture::new();
|
||||
let source = "ae\u{301}👩🚀z\nrest\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "lv2l");
|
||||
assert_eq!(editor.mode(), Mode::Visual);
|
||||
keys(&mut editor, "r界");
|
||||
assert_eq!(editor.context().text, "a界界界\nrest\n");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "U");
|
||||
assert_eq!(editor.context().text, "a界界界\nrest\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_r_preserves_selected_newlines_in_both_directions_and_shapes() {
|
||||
for (source, selection, expected) in [
|
||||
("ae\u{301}👩🚀z\n\nbc\nlast\n", "v2j", "QQQQ\n\nQc\nlast\n"),
|
||||
("ae\u{301}👩🚀z\n\nbc\nlast\n", "2jv2k", "QQQQ\n\nQc\nlast\n"),
|
||||
("ae\u{301}👩🚀z\n\nbc\nlast\n", "V2j", "QQQQ\n\nQQ\nlast\n"),
|
||||
("ab\ncd", "Vj", "QQ\nQQ"),
|
||||
("\n\n", "Vj", "\n\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, selection);
|
||||
keys(&mut editor, "rQ");
|
||||
assert_eq!(editor.context().text, expected, "{selection}");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert_eq!(editor.dirty(), source != expected);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_r_replaces_every_selection_and_restores_carets_on_undo() {
|
||||
let fixture = Fixture::new();
|
||||
let source = "abcd\nwxyz\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "vl");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
let carets = editor.carets();
|
||||
assert_eq!(editor.selection_count(), 2);
|
||||
keys(&mut editor, "r界");
|
||||
assert_eq!(editor.context().text, "界界cd\n界界yz\n");
|
||||
assert_eq!(editor.selection_count(), 2);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.carets(), carets);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_r_repeats_selection_intent_without_overwriting_the_clipboard() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc\nuvwxyz\n");
|
||||
keys(&mut editor, "yyvlrQj0.");
|
||||
assert_eq!(editor.context().text, "QQc\nQQwxyz\n");
|
||||
keys(&mut editor, "4lv.");
|
||||
assert_eq!(editor.context().text, "QQc\nQQwxQz\n");
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, "QQc\nabc\nQQwxQz\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_and_identical_visual_replacements_preserve_redo() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc\n");
|
||||
keys(&mut editor, "rQulvr");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.mode(), Mode::Visual);
|
||||
assert_eq!(editor.line_operator_pending(), None);
|
||||
keys(&mut editor, "rb");
|
||||
assert_eq!(editor.context().text, "abc\n");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "U");
|
||||
assert_eq!(editor.context().text, "Qbc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_and_delete_line_suffix_preserve_newlines_and_group_insert_undo() {
|
||||
for operation in ["C", "D", "9C", "9D"] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "ae\u{301}👩🚀tail\nnext\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "2l");
|
||||
let caret = editor.cursor();
|
||||
keys(&mut editor, operation);
|
||||
assert_eq!(editor.context().text, "ae\u{301}\nnext\n", "{operation}");
|
||||
if operation.ends_with('C') {
|
||||
assert_eq!(editor.mode(), Mode::Insert);
|
||||
keys(&mut editor, "replacement");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.context().text, "ae\u{301}replacement\nnext\n");
|
||||
} else {
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
}
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suffix_commands_at_last_grapheme_and_empty_lines_never_remove_newlines() {
|
||||
for operation in ["C", "D"] {
|
||||
for source in ["a👩🚀\nnext\n", "a👩🚀\nnext"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "$");
|
||||
keys(&mut editor, operation);
|
||||
assert_eq!(editor.context().text, source.replacen("a👩🚀", "a", 1));
|
||||
if editor.mode() == Mode::Insert {
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
}
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("\nnext\n");
|
||||
keys(&mut editor, operation);
|
||||
assert_eq!(editor.context().text, "\nnext\n");
|
||||
assert_eq!(
|
||||
editor.mode(),
|
||||
if operation == "C" {
|
||||
Mode::Insert
|
||||
} else {
|
||||
Mode::Normal
|
||||
}
|
||||
);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yank_line_suffix_is_characterwise_and_does_not_create_an_undo_entry() {
|
||||
for operation in ["Y", "8Y"] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "a👩🚀e\u{301}tail\nnext\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
let caret = editor.cursor();
|
||||
keys(&mut editor, operation);
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "j0P");
|
||||
assert_eq!(
|
||||
editor.context().text,
|
||||
"a👩🚀e\u{301}tail\n👩🚀e\u{301}tailnext\n"
|
||||
);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yank_and_cancelled_replace_preserve_the_previous_repeatable_edit() {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc\nxyz\n");
|
||||
keys(&mut editor, "xY3r");
|
||||
editor.handle(Input::Escape);
|
||||
keys(&mut editor, "j0.");
|
||||
assert_eq!(editor.context().text, "bc\nyz\n");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, "bc\nxyz\n");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, "abc\nxyz\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_consumes_a_literal_character_and_replaces_whole_counted_graphemes() {
|
||||
for (command, expected) in [
|
||||
("rx", "ax👩🚀z\nnext\n"),
|
||||
("r2", "a2👩🚀z\nnext\n"),
|
||||
("r界", "a界👩🚀z\nnext\n"),
|
||||
("r\t", "a\t👩🚀z\nnext\n"),
|
||||
("2rQ", "aQQz\nnext\n"),
|
||||
("9rQ", "aQQQ\nnext\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "ae\u{301}👩🚀z\nnext\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, expected, "{command:?}");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 1 });
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("\nnext\n");
|
||||
keys(&mut editor, "rQ");
|
||||
assert_eq!(editor.context().text, "\nnext\n");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitute_deletes_counted_whole_graphemes_and_groups_replacement_with_undo() {
|
||||
for (command, after_delete, expected) in [
|
||||
("s", "a👩🚀z\nnext\n", "aQ👩🚀z\nnext\n"),
|
||||
("2s", "az\nnext\n", "aQz\nnext\n"),
|
||||
("9s", "a\nnext\n", "aQ\nnext\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "ae\u{301}👩🚀z\nnext\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, after_delete, "{command}");
|
||||
assert_eq!(editor.mode(), Mode::Insert);
|
||||
keys(&mut editor, "Q");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.context().text, expected);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 1 });
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_cut_counts_before_and_after_operator_multiply_in_both_directions() {
|
||||
let source = "one two three four five six seven eight nine\n";
|
||||
for (position, command, expected) in [
|
||||
("", "dw", "two three four five six seven eight nine\n"),
|
||||
("", "d2w", "three four five six seven eight nine\n"),
|
||||
("", "2dw", "three four five six seven eight nine\n"),
|
||||
("", "2d3w", "seven eight nine\n"),
|
||||
("2w", "db", "one three four five six seven eight nine\n"),
|
||||
("4w", "d2b", "one two five six seven eight nine\n"),
|
||||
("4w", "2db", "one two five six seven eight nine\n"),
|
||||
("6w", "2d3b", "seven eight nine\n"),
|
||||
] {
|
||||
for operator in ["d", "c"] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, position);
|
||||
let caret = editor.cursor();
|
||||
let command = command.replacen('d', operator, 1);
|
||||
keys(&mut editor, &command);
|
||||
assert_eq!(editor.context().text, expected, "{position} {command}");
|
||||
assert_eq!(
|
||||
editor.mode(),
|
||||
if operator == "c" {
|
||||
Mode::Insert
|
||||
} else {
|
||||
Mode::Normal
|
||||
}
|
||||
);
|
||||
if operator == "c" {
|
||||
keys(&mut editor, "Q");
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_changes_preserve_line_boundaries_and_group_replacement_with_undo() {
|
||||
for (source, position, command, after_cut, expected) in [
|
||||
("one two\nnext\n", "", "cw", "two\nnext\n", "Qtwo\nnext\n"),
|
||||
("one two\nnext\n", "w", "cb", "two\nnext\n", "Qtwo\nnext\n"),
|
||||
("one\ntwo\n", "", "c9w", "\ntwo\n", "Q\ntwo\n"),
|
||||
("one\ntwo\n", "j0", "c9b", "one\ntwo\n", "one\nQtwo\n"),
|
||||
("one\n\ntwo\n", "j", "cw", "one\n\ntwo\n", "one\nQ\ntwo\n"),
|
||||
("one\n\ntwo\n", "j", "cb", "one\n\ntwo\n", "one\nQ\ntwo\n"),
|
||||
("one\n \ntwo\n", "j", "cw", "one\n\ntwo\n", "one\nQ\ntwo\n"),
|
||||
("one \nnext\n", "", "cw", "\nnext\n", "Q\nnext\n"),
|
||||
("e\u{301}lan 世界 fin\n", "", "c2w", "fin\n", "Qfin\n"),
|
||||
("e\u{301}lan 世界", "$", "c9b", "界", "Q界"),
|
||||
("👩🚀!!! next\n", "", "cw", "next\n", "Qnext\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, position);
|
||||
let caret = editor.cursor();
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, after_cut, "{position} {command}");
|
||||
assert_eq!(editor.mode(), Mode::Insert);
|
||||
keys(&mut editor, "Q");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.context().text, expected, "{position} {command}");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "U");
|
||||
assert_eq!(editor.context().text, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_delete_uses_unicode_word_motion_boundaries_across_punctuation() {
|
||||
for (source, command, expected) in [
|
||||
("e\u{301}lan 世界 fin\n", "d2w", "fin\n"),
|
||||
("e\u{301}lan 世界 fin\n", "2wd2b", "fin\n"),
|
||||
("alpha... beta gamma\n", "d2w", "beta gamma\n"),
|
||||
("alpha... beta gamma\n", "2wd2b", "beta gamma\n"),
|
||||
("👩🚀!!! next\n", "dw", "next\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, expected, "{command} on {source:?}");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_delete_stops_at_current_line_boundaries() {
|
||||
for (source, position, command, expected) in [
|
||||
("one\ntwo three\n", "", "dw", "\ntwo three\n"),
|
||||
("one\ntwo three\n", "", "d2w", "\ntwo three\n"),
|
||||
("one two\nthree four\n", "w", "2d3w", "one \nthree four\n"),
|
||||
("one\ntwo three\n", "2w", "d2b", "one\nthree\n"),
|
||||
("one\n two three\n", "jw", "2d3b", "one\ntwo three\n"),
|
||||
("one \ntwo\n", "", "d9w", "\ntwo\n"),
|
||||
("one\n \ntwo\n", "j", "dw", "one\n\ntwo\n"),
|
||||
("one\n\ntwo\n", "j", "d9w", "one\n\ntwo\n"),
|
||||
("one\n\ntwo\n", "j", "d9b", "one\n\ntwo\n"),
|
||||
("one\ntwo\n", "j0", "db", "one\ntwo\n"),
|
||||
("one\n two\n", "jl", "db", "one\n two\n"),
|
||||
(
|
||||
"one\ne\u{301}lan 世界\nnext\n",
|
||||
"j0",
|
||||
"d9w",
|
||||
"one\n\nnext\n",
|
||||
),
|
||||
(
|
||||
"one\ne\u{301}lan 世界\nnext\n",
|
||||
"j$",
|
||||
"d9b",
|
||||
"one\n界\nnext\n",
|
||||
),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, position);
|
||||
let caret = editor.cursor();
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(
|
||||
editor.context().text,
|
||||
expected,
|
||||
"{position} {command} on {source:?}"
|
||||
);
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
if source == expected {
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
} else {
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_delete_handles_eof_and_saturating_counts_without_splitting_graphemes() {
|
||||
let source = "e\u{301}lan 世界";
|
||||
for (command, expected) in [
|
||||
("d2w".to_owned(), ""),
|
||||
(format!("{}d2w", usize::MAX), ""),
|
||||
("$d3b".to_owned(), "界"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, &command);
|
||||
assert_eq!(editor.context().text, expected, "{command}");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_operator_and_replace_cancellation_clear_counts_without_editing() {
|
||||
for prefix in ["3d", "d2", "2d3", "3c", "c2", "2c3", "3r"] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "abcd\nnext\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, prefix);
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.context().text, source, "{prefix}");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 0, column: 0 });
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "x");
|
||||
assert_eq!(editor.context().text, "bcd\nnext\n", "{prefix}");
|
||||
}
|
||||
for input in [
|
||||
Input::Enter,
|
||||
Input::Char('\n'),
|
||||
Input::Paste("ignored".into()),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abcd\nnext\n");
|
||||
keys(&mut editor, "3r");
|
||||
editor.handle(input);
|
||||
keys(&mut editor, "lx");
|
||||
assert_eq!(editor.context().text, "acd\nnext\n");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_edit_recipes_repeat_against_the_current_text_and_undo_as_single_changes() {
|
||||
for (source, first, after_first, position, expected) in [
|
||||
(
|
||||
"prefix one\nlongprefix two\n",
|
||||
"7lCnew",
|
||||
"prefix new\nlongprefix two\n",
|
||||
"j011l",
|
||||
"prefix new\nlongprefix new\n",
|
||||
),
|
||||
(
|
||||
"prefix one\nlongprefix two\n",
|
||||
"7lD",
|
||||
"prefix \nlongprefix two\n",
|
||||
"j011l",
|
||||
"prefix \nlongprefix \n",
|
||||
),
|
||||
(
|
||||
"e\u{301}abc\n👩🚀xyz\n",
|
||||
"rQ",
|
||||
"Qabc\n👩🚀xyz\n",
|
||||
"j0",
|
||||
"Qabc\nQxyz\n",
|
||||
),
|
||||
(
|
||||
"e\u{301}abc\n👩🚀xyz\n",
|
||||
"sQ",
|
||||
"Qabc\n👩🚀xyz\n",
|
||||
"j0",
|
||||
"Qabc\nQxyz\n",
|
||||
),
|
||||
(
|
||||
"one two keep\nthree four stay\n",
|
||||
"d2w",
|
||||
"keep\nthree four stay\n",
|
||||
"j0",
|
||||
"keep\nstay\n",
|
||||
),
|
||||
(
|
||||
"one two keep\nthree four stay\n",
|
||||
"2wd2b",
|
||||
"keep\nthree four stay\n",
|
||||
"j02w",
|
||||
"keep\nstay\n",
|
||||
),
|
||||
("one\nthree four\n", "d9w", "\nthree four\n", "j0", "\n\n"),
|
||||
(
|
||||
"one keep\nthree four stay\n",
|
||||
"wd9b",
|
||||
"keep\nthree four stay\n",
|
||||
"j02w",
|
||||
"keep\nstay\n",
|
||||
),
|
||||
(
|
||||
"one two keep\nthree four stay\n",
|
||||
"c2wQ",
|
||||
"Qkeep\nthree four stay\n",
|
||||
"j0",
|
||||
"Qkeep\nQstay\n",
|
||||
),
|
||||
(
|
||||
"one two keep\nthree four stay\n",
|
||||
"2wc2bQ",
|
||||
"Qkeep\nthree four stay\n",
|
||||
"j02w",
|
||||
"Qkeep\nQstay\n",
|
||||
),
|
||||
(
|
||||
"one\nthree four\n",
|
||||
"c9wQ",
|
||||
"Q\nthree four\n",
|
||||
"j0",
|
||||
"Q\nQ\n",
|
||||
),
|
||||
(
|
||||
"one keep\nthree four stay\n",
|
||||
"wc9bQ",
|
||||
"Qkeep\nthree four stay\n",
|
||||
"j02w",
|
||||
"Qkeep\nQstay\n",
|
||||
),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, first);
|
||||
if editor.mode() == Mode::Insert {
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
assert_eq!(editor.context().text, after_first, "{first}");
|
||||
keys(&mut editor, position);
|
||||
keys(&mut editor, ".");
|
||||
assert_eq!(editor.context().text, expected, "{first} then {position}.");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, after_first);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dd_and_cc_keep_linewise_behavior_with_counts_after_the_operator() {
|
||||
let source = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
for (command, remaining) in [
|
||||
("dd", "2\n3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("2dd", "3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("d2d", "3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("2d3d", "7\n8\n9\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, remaining, "{command}");
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, source, "{command} linewise paste");
|
||||
}
|
||||
for (command, remaining) in [
|
||||
("cc", "2\n3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("2cc", "3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("c2c", "3\n4\n5\n6\n7\n8\n9\n"),
|
||||
("2c3c", "7\n8\n9\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.mode(), Mode::Insert);
|
||||
assert_eq!(editor.context().text, format!("\n{remaining}"), "{command}");
|
||||
keys(&mut editor, "Q");
|
||||
editor.handle(Input::Escape);
|
||||
assert_eq!(editor.context().text, format!("Q\n{remaining}"));
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_multicarets_edit_whole_graphemes_and_yank_matching_suffix_fragments() {
|
||||
let source = "a👩🚀tail\nbe\u{301}rest\n";
|
||||
for (command, expected) in [
|
||||
("D", "a\nb\n"),
|
||||
("CQ", "aQ\nbQ\n"),
|
||||
("rQ", "aQtail\nbQrest\n"),
|
||||
("sQ", "aQtail\nbQrest\n"),
|
||||
("YP", "a👩🚀tail👩🚀tail\nbe\u{301}reste\u{301}rest\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
let carets = editor.carets();
|
||||
assert_eq!(carets.len(), 2);
|
||||
keys(&mut editor, command);
|
||||
if editor.mode() == Mode::Insert {
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
assert_eq!(editor.context().text, expected, "{command}");
|
||||
assert_eq!(editor.selection_count(), 2);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.carets(), carets);
|
||||
}
|
||||
for (command, expected) in [
|
||||
("d2w", "keep\nstay\n"),
|
||||
("2wd2b", "keep\nstay\n"),
|
||||
("d9w", "\n\n"),
|
||||
("2wd9b", "keep\nstay\n"),
|
||||
("c2wQ", "Qkeep\nQstay\n"),
|
||||
("2wc2bQ", "Qkeep\nQstay\n"),
|
||||
("c9wQ", "Q\nQ\n"),
|
||||
("2wc9bQ", "Qkeep\nQstay\n"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "one two keep\nthree four stay\n";
|
||||
let mut editor = fixture.editor(source);
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
keys(&mut editor, command);
|
||||
if editor.mode() == Mode::Insert {
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
assert_eq!(editor.context().text, expected, "{command}");
|
||||
assert_eq!(editor.selection_count(), 2);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.selection_count(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remapped_core_edit_actions_keep_counts_pending_input_and_clipboard_semantics() {
|
||||
for (action, original_key, position, command, expected) in [
|
||||
("core.change_to_line_end", "C", "l", "qX", "aX\nnext\n"),
|
||||
("core.delete_to_line_end", "D", "l", "q", "a\nnext\n"),
|
||||
(
|
||||
"core.copy_to_line_end",
|
||||
"Y",
|
||||
"l",
|
||||
"qj0P",
|
||||
"abc def ghi\nbc def ghinext\n",
|
||||
),
|
||||
(
|
||||
"core.replace_character",
|
||||
"r",
|
||||
"l",
|
||||
"qZ",
|
||||
"aZc def ghi\nnext\n",
|
||||
),
|
||||
(
|
||||
"core.substitute_character",
|
||||
"s",
|
||||
"l",
|
||||
"qZ",
|
||||
"aZc def ghi\nnext\n",
|
||||
),
|
||||
("core.delete_word_forward", "d", "", "2q", "ghi\nnext\n"),
|
||||
("core.delete_word_backward", "d", "2w", "2q", "ghi\nnext\n"),
|
||||
("core.change_word_forward", "c", "", "2qQ", "Qghi\nnext\n"),
|
||||
(
|
||||
"core.change_word_backward",
|
||||
"c",
|
||||
"2w",
|
||||
"2qQ",
|
||||
"Qghi\nnext\n",
|
||||
),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor("abc def ghi\nnext\n");
|
||||
editor.bind("normal", original_key, None).unwrap();
|
||||
editor.bind("normal", "q", Some(action.into())).unwrap();
|
||||
keys(&mut editor, position);
|
||||
keys(&mut editor, command);
|
||||
if editor.mode() == Mode::Insert {
|
||||
editor.handle(Input::Escape);
|
||||
}
|
||||
assert_eq!(editor.context().text, expected, "{action}");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use vamp::editor::{Cursor, Editor, Input, Mode};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-paste-shapes-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
fn editor(&self, text: &str) -> Editor {
|
||||
let path = self.0.join("buffer.txt");
|
||||
fs::write(&path, text).unwrap();
|
||||
let mut editor = Editor::open(Some(path), vec!["text".into()]).unwrap();
|
||||
editor.set_clipboard_mode("separate").unwrap();
|
||||
editor
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(editor: &mut Editor, text: &str) {
|
||||
for ch in text.chars() {
|
||||
editor.handle(Input::Char(ch));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_paste_replaces_selection_and_preserves_clipboard_and_undo() {
|
||||
for paste in ['p', 'P'] {
|
||||
for (yank, select, expected) in [
|
||||
("vly", "j0vl", "XY\nXYc\nend"),
|
||||
("vly", "j0lvh", "XY\nXYc\nend"),
|
||||
("yy", "j0vl", "XY\nXY\nc\nend"),
|
||||
("yy", "jV", "XY\nXY\nend"),
|
||||
("vly", "jV", "XY\nXYend"),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let source = "XY\nabc\nend";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, yank);
|
||||
keys(&mut editor, select);
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(editor.context().text, expected, "{yank} {select} {paste}");
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
keys(&mut editor, "U");
|
||||
assert_eq!(editor.context().text, expected);
|
||||
keys(
|
||||
&mut editor,
|
||||
if select.ends_with("vh") {
|
||||
"u0l."
|
||||
} else {
|
||||
"u0."
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
editor.context().text,
|
||||
expected,
|
||||
"repeat: {yank} {select} {paste}"
|
||||
);
|
||||
keys(&mut editor, "u");
|
||||
keys(&mut editor, select.trim_start_matches('j'));
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(editor.context().text, expected, "clipboard stays unchanged");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_paste_replaces_every_selected_range_in_one_undo_group() {
|
||||
let fixture = Fixture::new();
|
||||
let source = "XY\n界e\u{301}\n👩🚀z";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "vlyj0vl");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
keys(&mut editor, "p");
|
||||
assert_eq!(editor.context().text, "XY\nXY\nXY");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_line_yank_pastes_above_or_below_the_target_and_keeps_indentation() {
|
||||
let source = " \t界e\u{301}👩🚀\nother\nlast\n";
|
||||
for (paste, expected, row) in [
|
||||
('p', " \t界e\u{301}👩🚀\nother\n \t界e\u{301}👩🚀\nlast\n", 2),
|
||||
('P', " \t界e\u{301}👩🚀\n \t界e\u{301}👩🚀\nother\nlast\n", 1),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "3l");
|
||||
let yank_caret = editor.cursor();
|
||||
keys(&mut editor, "yy");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), yank_caret);
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "j2l");
|
||||
let paste_caret = editor.cursor();
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(editor.context().text, expected, "{paste}");
|
||||
assert_eq!(editor.cursor(), Cursor { row, column: 2 });
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), paste_caret);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_line_paste_handles_unterminated_rows_empty_rows_and_the_final_empty_row() {
|
||||
for (source, position, paste, expected, row) in [
|
||||
("top\n last", "j2l", 'p', "top\n last\n last", 2),
|
||||
("top\n last", "j2l", 'P', "top\n last\n last", 1),
|
||||
("top\n last\n", "j2l", 'p', "top\n last\n last\n", 2),
|
||||
("top\n last\n", "j2l", 'P', "top\n last\n last\n", 1),
|
||||
("top\n\nend", "j", 'p', "top\n\n\nend", 2),
|
||||
("top\n\nend", "j", 'P', "top\n\n\nend", 1),
|
||||
("top\n", "j", 'p', "top\n\n", 2),
|
||||
("top\n", "j", 'P', "top\n\n", 1),
|
||||
("", "", 'p', "\n", 1),
|
||||
("", "", 'P', "\n", 0),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, position);
|
||||
let caret = editor.cursor();
|
||||
keys(&mut editor, "yy");
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(
|
||||
editor.context().text,
|
||||
expected,
|
||||
"{source:?} {position}yy{paste}"
|
||||
);
|
||||
assert_eq!(
|
||||
editor.cursor(),
|
||||
Cursor {
|
||||
row,
|
||||
column: caret.column
|
||||
}
|
||||
);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counted_line_yanks_multiply_prefixes_and_clamp_at_the_last_row() {
|
||||
let source = "one\ntwo\nthree\nfour\nfive\nsix\nseven";
|
||||
for (command, expected) in [
|
||||
("2yy", "one\none\ntwo\ntwo\nthree\nfour\nfive\nsix\nseven"),
|
||||
("y2y", "one\none\ntwo\ntwo\nthree\nfour\nfive\nsix\nseven"),
|
||||
(
|
||||
"2y3y",
|
||||
"one\none\ntwo\nthree\nfour\nfive\nsix\ntwo\nthree\nfour\nfive\nsix\nseven",
|
||||
),
|
||||
(
|
||||
"9yy",
|
||||
"one\none\ntwo\nthree\nfour\nfive\nsix\nseven\ntwo\nthree\nfour\nfive\nsix\nseven",
|
||||
),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, command);
|
||||
assert_eq!(editor.context().text, source, "{command}");
|
||||
keys(&mut editor, "p");
|
||||
assert_eq!(editor.context().text, expected, "{command}p");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_character_yank_pastes_before_or_after_whole_extended_graphemes() {
|
||||
let source = "ae\u{301}👩🚀z\nx👨👩👧👦q\n";
|
||||
for (paste, expected, column) in [
|
||||
('p', "ae\u{301}👩🚀z\nx👨👩👧👦e\u{301}👩🚀q\n", 3),
|
||||
('P', "ae\u{301}👩🚀z\nxe\u{301}👩🚀👨👩👧👦q\n", 2),
|
||||
] {
|
||||
let fixture = Fixture::new();
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "lvly");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "j0l");
|
||||
let caret = editor.cursor();
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(editor.context().text, expected, "{paste}");
|
||||
assert_eq!(editor.cursor(), Cursor { row: 1, column });
|
||||
assert_eq!(editor.mode(), Mode::Normal);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.cursor(), caret);
|
||||
editor.handle(Input::Char(paste));
|
||||
assert_eq!(
|
||||
editor.context().text,
|
||||
expected,
|
||||
"register survives undo and paste"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_keeps_the_pasted_line_shape_without_replacing_the_new_yank_register() {
|
||||
let fixture = Fixture::new();
|
||||
let source = " a\nb\nc";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "yyp");
|
||||
assert_eq!(editor.context().text, " a\n a\nb\nc");
|
||||
keys(&mut editor, "jyy.");
|
||||
assert_eq!(editor.context().text, " a\n a\nb\n a\nc");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, " a\n a\nb\nc");
|
||||
keys(&mut editor, "p");
|
||||
assert_eq!(editor.context().text, " a\n a\nb\nb\nc");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, " a\n a\nb\nc");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_multicarets_yank_matching_whole_lines_and_paste_in_one_undo_step() {
|
||||
let fixture = Fixture::new();
|
||||
let source = " a\n\tb\nc";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "l");
|
||||
editor.handle(Input::Ctrl('e'));
|
||||
let carets = editor.carets();
|
||||
assert_eq!(carets.len(), 2);
|
||||
keys(&mut editor, "yy");
|
||||
assert_eq!(editor.carets(), carets);
|
||||
keys(&mut editor, "p");
|
||||
assert_eq!(editor.context().text, " a\n a\n\tb\n\tb\nc");
|
||||
assert_eq!(
|
||||
editor.carets(),
|
||||
vec![Cursor { row: 1, column: 1 }, Cursor { row: 3, column: 1 }],
|
||||
);
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert_eq!(editor.carets(), carets);
|
||||
assert!(!editor.dirty());
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, " a\n a\n\tb\n\tb\nc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visual_yank_ending_in_a_newline_stays_characterwise() {
|
||||
let fixture = Fixture::new();
|
||||
let source = "\nxy";
|
||||
let mut editor = fixture.editor(source);
|
||||
keys(&mut editor, "vyj0p");
|
||||
assert_eq!(editor.context().text, "\nx\ny");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
keys(&mut editor, "P");
|
||||
assert_eq!(editor.context().text, "\n\nxy");
|
||||
keys(&mut editor, "u");
|
||||
assert_eq!(editor.context().text, source);
|
||||
assert!(!editor.dirty());
|
||||
}
|
||||
+3054
File diff suppressed because it is too large
Load Diff
Executable
+275
@@ -0,0 +1,275 @@
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
process::Command,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use vamp::{
|
||||
editor::{Input, ResolverStatus},
|
||||
session::EditorSession,
|
||||
};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
base: String,
|
||||
}
|
||||
impl Fixture {
|
||||
fn jj(&self, args: &[&str]) -> String {
|
||||
let result = Command::new("jj")
|
||||
.args(["--no-pager", "--color=never"])
|
||||
.args(args)
|
||||
.current_dir(&self.root)
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.env("JJ_USER", "Resolver Test")
|
||||
.env("JJ_EMAIL", "resolver@example.invalid")
|
||||
.env("JJ_TIMESTAMP", "2000-01-01T00:00:00Z")
|
||||
.env("GIT_CONFIG_NOSYSTEM", "1")
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
String::from_utf8(result.stdout).unwrap().trim().into()
|
||||
}
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-resolve-session-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let mut fixture = Self {
|
||||
root,
|
||||
base: String::new(),
|
||||
};
|
||||
fixture.jj(&["git", "init", "--no-colocate", "."]);
|
||||
for name in ["first.txt", "second.txt"] {
|
||||
fs::write(fixture.root.join(name), Self::text("base")).unwrap();
|
||||
}
|
||||
fixture.jj(&["describe", "-m", "base"]);
|
||||
fixture.base = fixture.jj(&["log", "--no-graph", "-r", "@", "-T", "commit_id"]);
|
||||
fixture.jj(&["new", &fixture.base]);
|
||||
for name in ["first.txt", "second.txt"] {
|
||||
fs::write(fixture.root.join(name), Self::text("left")).unwrap();
|
||||
}
|
||||
fixture.jj(&["describe", "-m", "left"]);
|
||||
let left = fixture.jj(&["log", "--no-graph", "-r", "@", "-T", "commit_id"]);
|
||||
fixture.jj(&["new", &fixture.base]);
|
||||
for name in ["first.txt", "second.txt"] {
|
||||
fs::write(fixture.root.join(name), Self::text("right")).unwrap();
|
||||
}
|
||||
fixture.jj(&["describe", "-m", "right"]);
|
||||
let right = fixture.jj(&["log", "--no-graph", "-r", "@", "-T", "commit_id"]);
|
||||
fixture.jj(&["new", &left, &right, "-m", "conflicted result"]);
|
||||
fixture
|
||||
}
|
||||
fn text(side: &str) -> String {
|
||||
format!(
|
||||
"{side} first\n{}{side} last\n",
|
||||
(0..30)
|
||||
.map(|n| format!("context_{n}\n"))
|
||||
.collect::<String>()
|
||||
)
|
||||
}
|
||||
fn open(&self) -> EditorSession {
|
||||
let config = self.root.join("test-config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure do |config|\n config.clipboard_mode = 'separate'\nend\n",
|
||||
)
|
||||
.unwrap();
|
||||
EditorSession::open(
|
||||
Some(self.root.join("first.txt")),
|
||||
vec!["text".into()],
|
||||
Some(&config),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
fn ready(session: &mut EditorSession) {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
loop {
|
||||
session.poll();
|
||||
if session.editor().resolver().is_some_and(|resolver| {
|
||||
!resolver.loading
|
||||
&& resolver
|
||||
.files
|
||||
.iter()
|
||||
.all(|file| file.status != ResolverStatus::Checking)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"resolver did not settle: {}",
|
||||
session.editor().message()
|
||||
);
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_keeps_unsaved_result_and_undo_then_saves_and_retains_resolved_file() {
|
||||
let fixture = Fixture::new();
|
||||
let original_disk = fs::read_to_string(fixture.root.join("first.txt")).unwrap();
|
||||
let mut session = fixture.open();
|
||||
for input in [
|
||||
Input::Char('i'),
|
||||
Input::Paste("draft\n".into()),
|
||||
Input::Escape,
|
||||
] {
|
||||
session.handle(input);
|
||||
}
|
||||
let draft = session.editor().context().text;
|
||||
let operation = fixture.jj(&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"--limit",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
]);
|
||||
session.execute("resolve");
|
||||
ready(&mut session);
|
||||
let seeded = format!("draft\n{}", Fixture::text("left"));
|
||||
assert_eq!(session.editor().context().text, seeded);
|
||||
assert_ne!(seeded, draft);
|
||||
assert!(session.editor().dirty());
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.root.join("first.txt")).unwrap(),
|
||||
original_disk
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.jj(&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"--limit",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
]),
|
||||
operation
|
||||
);
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(session.editor().context().text, draft);
|
||||
session.handle(Input::Char('U'));
|
||||
assert_eq!(session.editor().context().text, seeded);
|
||||
let source = session.editor().resolver().unwrap().files[0]
|
||||
.sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, source)| !source.base)
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.0
|
||||
+ 1;
|
||||
session.execute(&format!("resolve.use_source {source}"));
|
||||
let chosen = session.editor().context().text;
|
||||
assert_ne!(chosen, seeded);
|
||||
assert!(chosen.starts_with("draft\n"));
|
||||
assert!(chosen.contains("context_15\n"));
|
||||
session.handle(Input::Char('u'));
|
||||
assert_eq!(session.editor().context().text, seeded);
|
||||
session.execute(&format!("resolve.use_source {source}"));
|
||||
let cursor = session.editor().cursor();
|
||||
let resolved_text = session.editor().context().text;
|
||||
session.execute("resolve.view.toggle");
|
||||
session.execute("resolve.view.toggle");
|
||||
assert_eq!(session.editor().context().text, resolved_text);
|
||||
assert_eq!(session.editor().cursor(), cursor);
|
||||
session.execute("w");
|
||||
ready(&mut session);
|
||||
let resolver = session.editor().resolver().unwrap();
|
||||
assert_eq!(resolver.files.len(), 2);
|
||||
assert_eq!(
|
||||
resolver.files[resolver.current_file].status,
|
||||
ResolverStatus::Resolved
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.root.join("first.txt")).unwrap(),
|
||||
resolved_text
|
||||
);
|
||||
assert!(
|
||||
!fixture
|
||||
.jj(&["--ignore-working-copy", "resolve", "--list"])
|
||||
.contains("first.txt")
|
||||
);
|
||||
assert!(
|
||||
fixture
|
||||
.jj(&["--ignore-working-copy", "resolve", "--list"])
|
||||
.contains("second.txt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_refuses_save_after_checkout_change_even_when_forced_and_preserves_draft() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.open();
|
||||
session.execute("resolve");
|
||||
ready(&mut session);
|
||||
for input in [
|
||||
Input::Char('i'),
|
||||
Input::Paste("keep my draft\n".into()),
|
||||
Input::Escape,
|
||||
] {
|
||||
session.handle(input);
|
||||
}
|
||||
let draft = session.editor().context().text;
|
||||
fixture.jj(&["new", &fixture.base]);
|
||||
let checkout_disk = fs::read_to_string(fixture.root.join("first.txt")).unwrap();
|
||||
for save in ["w", "w!"] {
|
||||
session.execute(save);
|
||||
ready(&mut session);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.root.join("first.txt")).unwrap(),
|
||||
checkout_disk
|
||||
);
|
||||
assert_eq!(session.editor().context().text, draft);
|
||||
assert!(session.editor().dirty());
|
||||
}
|
||||
session.execute("resolve.close");
|
||||
assert_eq!(session.editor().context().text, draft);
|
||||
assert!(session.editor().dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_save_preserves_external_writes_and_keeps_the_unsaved_result() {
|
||||
let fixture = Fixture::new();
|
||||
let mut session = fixture.open();
|
||||
session.execute("resolve");
|
||||
ready(&mut session);
|
||||
for input in [
|
||||
Input::Char('i'),
|
||||
Input::Paste("local draft\n".into()),
|
||||
Input::Escape,
|
||||
] {
|
||||
session.handle(input);
|
||||
}
|
||||
let draft = session.editor().context().text;
|
||||
fs::write(fixture.root.join("first.txt"), "external edit\n").unwrap();
|
||||
session.execute("w");
|
||||
ready(&mut session);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.root.join("first.txt")).unwrap(),
|
||||
"external edit\n"
|
||||
);
|
||||
assert_eq!(session.editor().context().text, draft);
|
||||
assert!(session.editor().dirty());
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
use std::{fs, path::PathBuf, process::Command};
|
||||
use vamp::{
|
||||
plugin::TextPosition,
|
||||
review::{Anchor, Comment, Review, Side, Store, Verdict},
|
||||
};
|
||||
|
||||
struct Directory(PathBuf);
|
||||
impl Drop for Directory {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_deletes_only_the_requested_comment_and_preserves_failed_targets() {
|
||||
let directory = Directory(
|
||||
std::env::temp_dir().join(format!("vamp-review-cli-delete-{}", std::process::id())),
|
||||
);
|
||||
fs::create_dir(&directory.0).unwrap();
|
||||
let root = directory.0.canonicalize().unwrap();
|
||||
for name in ["repo", "other"] {
|
||||
let output = Command::new("jj")
|
||||
.args(["git", "init"])
|
||||
.arg(root.join(name))
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
}
|
||||
let config = root.join("config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure { |config| config.review_directory = 'reviews' }",
|
||||
)
|
||||
.unwrap();
|
||||
let storage = root.join("reviews");
|
||||
let mut store = Store::open(&storage).unwrap();
|
||||
let mut review = Review::new(root.join("repo"));
|
||||
review.summary = "Keep summary".into();
|
||||
review.verdict = Some(Verdict::ChangesRequested);
|
||||
review.comments = [1, u64::MAX]
|
||||
.into_iter()
|
||||
.map(|id| Comment {
|
||||
id,
|
||||
body: format!("Feedback {id}"),
|
||||
resolved: id == u64::MAX,
|
||||
anchor: Anchor {
|
||||
revision: "snapshot".into(),
|
||||
path: "file.rs".into(),
|
||||
side: Side::After,
|
||||
start: TextPosition { row: 0, column: 0 },
|
||||
end: TextPosition { row: 0, column: 1 },
|
||||
content: "界\n".into(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
store.save(&mut review).unwrap();
|
||||
let mut other = Review::new(root.join("other"));
|
||||
other.comments = review.comments.clone();
|
||||
store.save(&mut other).unwrap();
|
||||
let id = review.storage_id.unwrap();
|
||||
let cli = |repo: &str, args: &[&str]| {
|
||||
Command::new(env!("CARGO_BIN_EXE_vamp"))
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("--review")
|
||||
.args(args)
|
||||
.current_dir(root.join(repo))
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let id_text = id.to_string();
|
||||
for (repo, args) in [
|
||||
("repo", vec!["delete", "999", "1"]),
|
||||
("repo", vec!["delete", &id_text, "2"]),
|
||||
("other", vec!["delete", &id_text, "1"]),
|
||||
] {
|
||||
let output = cli(repo, &args);
|
||||
assert!(!output.status.success(), "{:?}", output);
|
||||
let loaded = store.load(&review.root, id).unwrap();
|
||||
assert_eq!(loaded.storage_revision, review.storage_revision);
|
||||
assert_eq!(loaded.comments, review.comments);
|
||||
}
|
||||
let output = cli(
|
||||
"repo",
|
||||
&["delete", &id_text, "18446744073709551615", "--json"],
|
||||
);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(json["id"], id);
|
||||
assert_eq!(
|
||||
json["counts"],
|
||||
serde_json::json!({"total": 1, "resolved": 0, "unresolved": 1})
|
||||
);
|
||||
let loaded = store.load(&review.root, id).unwrap();
|
||||
assert_eq!(loaded.storage_revision, review.storage_revision + 1);
|
||||
assert_eq!(loaded.comments, review.comments[..1]);
|
||||
assert_eq!(loaded.summary, review.summary);
|
||||
assert_eq!(loaded.verdict, review.verdict);
|
||||
assert!(store.save(&mut review).is_err()); // Stale editors cannot resurrect the deletion.
|
||||
let output = cli("repo", &["delete", &id_text, "18446744073709551615"]);
|
||||
assert!(!output.status.success());
|
||||
assert_eq!(
|
||||
store.load(&review.root, id).unwrap().storage_revision,
|
||||
loaded.storage_revision
|
||||
);
|
||||
let output = cli("repo", &["delete", &id_text, "1"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
assert!(
|
||||
String::from_utf8(output.stdout)
|
||||
.unwrap()
|
||||
.contains("0 total")
|
||||
);
|
||||
let empty = store.load(&review.root, id).unwrap();
|
||||
assert!(empty.comments.is_empty());
|
||||
assert_eq!(empty.storage_revision, loaded.storage_revision + 1);
|
||||
assert_eq!(empty.summary, review.summary);
|
||||
let output = cli("repo", &["list", "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let list: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(list["reviews"], serde_json::json!([]));
|
||||
let output = cli("repo", &["list"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
assert!(
|
||||
String::from_utf8(output.stdout)
|
||||
.unwrap()
|
||||
.contains("No stored reviews.")
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.load(&other.root, other.storage_id.unwrap())
|
||||
.unwrap()
|
||||
.comments,
|
||||
other.comments
|
||||
);
|
||||
drop(store);
|
||||
fs::remove_dir_all(&storage).unwrap();
|
||||
let output = cli("repo", &["delete", &id_text, "1"]);
|
||||
assert!(!output.status.success());
|
||||
assert!(!storage.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_resolves_only_the_requested_comment_and_preserves_original_feedback() {
|
||||
let directory = Directory(
|
||||
std::env::temp_dir().join(format!("vamp-review-cli-resolve-{}", std::process::id())),
|
||||
);
|
||||
fs::create_dir(&directory.0).unwrap();
|
||||
let root = directory.0.canonicalize().unwrap();
|
||||
for name in ["repo", "other"] {
|
||||
let output = Command::new("jj")
|
||||
.args(["git", "init"])
|
||||
.arg(root.join(name))
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
}
|
||||
let config = root.join("config.rb");
|
||||
fs::write(
|
||||
&config,
|
||||
"Vamp.configure { |config| config.review_directory = 'reviews' }",
|
||||
)
|
||||
.unwrap();
|
||||
let storage = root.join("reviews");
|
||||
let mut store = Store::open(&storage).unwrap();
|
||||
let mut review = Review::new(root.join("repo"));
|
||||
review.comparison = Some(["frozen-base".into(), "working:frozen-tip".into()]);
|
||||
review.summary = "Keep summary".into();
|
||||
review.verdict = Some(Verdict::ChangesRequested);
|
||||
review.comments = [u64::MAX, 2, 3]
|
||||
.into_iter()
|
||||
.map(|id| Comment {
|
||||
id,
|
||||
body: format!("Original feedback {id}\nKeep this history."),
|
||||
resolved: id == 3,
|
||||
anchor: Anchor {
|
||||
revision: "original-snapshot".into(),
|
||||
path: "old/file.rs".into(),
|
||||
side: Side::Before,
|
||||
start: TextPosition { row: 0, column: 1 },
|
||||
end: TextPosition { row: 1, column: 1 },
|
||||
content: "xe\u{301}👩💻\n界z\n".into(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
store.save(&mut review).unwrap();
|
||||
let mut other = Review::new(root.join("other"));
|
||||
other.comments = review.comments.clone();
|
||||
store.save(&mut other).unwrap();
|
||||
let mut source = Review::new(review.root.clone());
|
||||
source.summary = "Progress without comments".into();
|
||||
source.verdict = Some(Verdict::LooksGood);
|
||||
store.save(&mut source).unwrap();
|
||||
let mut reversed = Review::new(review.root.clone());
|
||||
reversed.comparison = Some(["working:frozen-tip".into(), "frozen-base".into()]);
|
||||
store.save(&mut reversed).unwrap();
|
||||
let id = review.storage_id.unwrap();
|
||||
let id_text = id.to_string();
|
||||
let cli = |repo: &str, args: &[&str]| {
|
||||
Command::new(env!("CARGO_BIN_EXE_vamp"))
|
||||
.arg("--config")
|
||||
.arg(&config)
|
||||
.arg("--review")
|
||||
.args(args)
|
||||
.arg("--repo")
|
||||
.arg(root.join(repo))
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let path = storage.join("reviews.sqlite3");
|
||||
let before = fs::read(&path).unwrap();
|
||||
for (repo, args) in [
|
||||
("repo", vec!["resolve"]),
|
||||
("repo", vec!["resolve", &id_text]),
|
||||
("repo", vec!["resolve", "0", "1"]),
|
||||
("repo", vec!["resolve", &id_text, "0"]),
|
||||
("repo", vec!["resolve", "999", "1"]),
|
||||
("repo", vec!["resolve", &id_text, "1"]),
|
||||
("other", vec!["resolve", &id_text, "2"]),
|
||||
("repo", vec!["resolve", &id_text, "2", "--all"]),
|
||||
] {
|
||||
let output = cli(repo, &args);
|
||||
assert!(!output.status.success(), "{:?}", output);
|
||||
assert_eq!(fs::read(&path).unwrap(), before);
|
||||
}
|
||||
let output = cli(
|
||||
"repo",
|
||||
&["resolve", &id_text, "18446744073709551615", "--json"],
|
||||
);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(json["id"], id);
|
||||
assert_eq!(json["revision"], review.storage_revision + 1);
|
||||
assert_eq!(json["comparison"], serde_json::json!(review.comparison));
|
||||
assert_eq!(
|
||||
json["counts"],
|
||||
serde_json::json!({"total": 3, "resolved": 2, "unresolved": 1})
|
||||
);
|
||||
assert_eq!(json["comments"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(json["comments"][0]["id"], 2);
|
||||
let loaded = store.load(&review.root, id).unwrap();
|
||||
let mut expected = review.comments.clone();
|
||||
expected[0].resolved = true;
|
||||
assert_eq!(loaded.comments, expected);
|
||||
assert_eq!(loaded.summary, review.summary);
|
||||
assert_eq!(loaded.verdict, review.verdict);
|
||||
assert_eq!(loaded.reviewed_files, review.reviewed_files);
|
||||
assert_eq!(loaded.comparison, review.comparison);
|
||||
assert!(store.save(&mut review).is_err()); // Stale editors cannot undo resolution.
|
||||
assert_eq!(store.load(&review.root, id).unwrap().comments, expected);
|
||||
|
||||
let output = cli("repo", &["show", &id_text, "--all", "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let all: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(all["comments"].as_array().unwrap().len(), 3);
|
||||
let original = &all["comments"][0];
|
||||
assert_eq!(original["id"], u64::MAX);
|
||||
assert_eq!(original["body"], review.comments[0].body);
|
||||
assert_eq!(original["resolved"], true);
|
||||
assert_eq!(original["anchor"]["revision"], "original-snapshot");
|
||||
assert_eq!(original["anchor"]["path"], "old/file.rs");
|
||||
assert_eq!(
|
||||
original["anchor"]["start"],
|
||||
serde_json::json!({"row": 0, "column": 1})
|
||||
);
|
||||
assert_eq!(original["excerpt"], "e\u{301}👩💻\n界");
|
||||
let output = cli("repo", &["show", &id_text, "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap(),
|
||||
json
|
||||
);
|
||||
let before = fs::read(&path).unwrap();
|
||||
for comment in ["18446744073709551615", "3"] {
|
||||
let output = cli("repo", &["resolve", &id_text, comment, "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap(),
|
||||
json
|
||||
);
|
||||
assert_eq!(fs::read(&path).unwrap(), before);
|
||||
}
|
||||
let output = cli("repo", &["list", "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let list: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(
|
||||
list["reviews"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|review| review["id"].as_i64().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![id]
|
||||
);
|
||||
assert_eq!(list["reviews"][0]["comparison"], json["comparison"]);
|
||||
assert_eq!(list["reviews"][0]["counts"], json["counts"]);
|
||||
let output = cli("repo", &["list"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let text = String::from_utf8(output.stdout).unwrap();
|
||||
assert!(!text.contains("Progress without comments"));
|
||||
assert!(text.contains("Scope: comparison frozen-base → working:frozen-tip"));
|
||||
assert!(!text.contains("Scope: comparison working:frozen-tip → frozen-base"));
|
||||
assert_eq!(fs::read(&path).unwrap(), before);
|
||||
let output = cli(
|
||||
"repo",
|
||||
&["show", &source.storage_id.unwrap().to_string(), "--json"],
|
||||
);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let shown: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(shown["summary"], source.summary);
|
||||
assert_eq!(shown["verdict"], "looks_good");
|
||||
let output = cli("repo", &["resolve", &id_text, "2"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let text = String::from_utf8(output.stdout).unwrap();
|
||||
assert!(!text.contains("Original feedback"));
|
||||
let loaded = store.load(&review.root, id).unwrap();
|
||||
assert_eq!(loaded.storage_revision, review.storage_revision + 2);
|
||||
assert!(loaded.comments.iter().all(|comment| comment.resolved));
|
||||
let output = cli("repo", &["list", "--json"]);
|
||||
assert!(output.status.success(), "{:?}", output);
|
||||
let list: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(list["reviews"][0]["id"], id);
|
||||
assert_eq!(
|
||||
list["reviews"][0]["counts"],
|
||||
serde_json::json!({"total": 3, "resolved": 3, "unresolved": 0})
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.load(&other.root, other.storage_id.unwrap())
|
||||
.unwrap()
|
||||
.comments,
|
||||
other.comments
|
||||
);
|
||||
drop(store);
|
||||
fs::remove_dir_all(&storage).unwrap();
|
||||
let output = cli("repo", &["resolve", &id_text, "2"]);
|
||||
assert!(!output.status.success(), "{:?}", output);
|
||||
assert!(!storage.exists());
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use super::*;
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn percentages_reject_invalid_data_and_include_both_endpoints() {
|
||||
assert_eq!(percentage(0, 100), Some(0));
|
||||
assert_eq!(percentage(100, 100), Some(100));
|
||||
assert_eq!(percentage(1, 3), Some(33));
|
||||
assert_eq!(percentage(u64::MAX, u64::MAX), Some(100));
|
||||
assert_eq!(percentage(0, 0), None);
|
||||
assert_eq!(percentage(101, 100), None);
|
||||
assert_eq!(windows_charge(0, 4), Some(0));
|
||||
assert_eq!(windows_charge(100, 8), Some(100));
|
||||
assert_eq!(windows_charge(101, 0), None);
|
||||
assert_eq!(windows_charge(255, 0), None);
|
||||
assert_eq!(windows_charge(50, 128), None);
|
||||
assert_eq!(windows_charge(50, 255), None);
|
||||
}
|
||||
|
||||
fn worker(samples: Vec<Option<u8>>) -> (Battery, Receiver<()>, Arc<AtomicBool>) {
|
||||
struct ReaderDropped(Arc<AtomicBool>);
|
||||
impl Drop for ReaderDropped {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let reader = ReaderDropped(Arc::clone(&dropped));
|
||||
let mut samples = samples.into_iter();
|
||||
let (ready, published) = mpsc::channel();
|
||||
let battery = Battery::start_with(
|
||||
move || {
|
||||
let _ = &reader;
|
||||
samples
|
||||
.next()
|
||||
.expect("test provides every requested sample")
|
||||
},
|
||||
move |wake| {
|
||||
ready.send(()).unwrap();
|
||||
// Explicit channel messages replace the production clock entirely.
|
||||
wake.recv().is_ok()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
(battery, published, dropped)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_reads_immediately_replaces_stale_samples_and_clears_invalid_data() {
|
||||
let (mut battery, published, dropped) = worker(vec![Some(0), Some(100), None, Some(101)]);
|
||||
published.recv().unwrap();
|
||||
assert_eq!(battery.poll(), Some(Some(0)));
|
||||
assert_eq!(battery.poll(), None);
|
||||
battery.wake.as_ref().unwrap().send(()).unwrap();
|
||||
published.recv().unwrap();
|
||||
battery.wake.as_ref().unwrap().send(()).unwrap();
|
||||
published.recv().unwrap();
|
||||
assert_eq!(battery.poll(), Some(None));
|
||||
assert_eq!(battery.poll(), None);
|
||||
battery.wake.as_ref().unwrap().send(()).unwrap();
|
||||
published.recv().unwrap();
|
||||
assert_eq!(battery.poll(), Some(None));
|
||||
drop(battery);
|
||||
assert!(dropped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_interrupts_wait_and_joins_even_with_an_unread_sample() {
|
||||
let (battery, published, dropped) = worker(vec![Some(50)]);
|
||||
published.recv().unwrap();
|
||||
drop(battery);
|
||||
assert!(dropped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
static FIXTURE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-battery-{}-{}",
|
||||
std::process::id(),
|
||||
FIXTURE_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn source(&self, name: &str, fields: &[(&str, &str)]) {
|
||||
let path = self.0.join(name);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
for (key, value) in fields {
|
||||
fs::write(path.join(key), value).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&self) -> Option<u8> {
|
||||
linux::read_charge(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysfs_reads_present_system_batteries_but_not_external_or_absent_sources() {
|
||||
let fixture = Fixture::new();
|
||||
assert_eq!(fixture.read(), None);
|
||||
fixture.source("AC", &[("type", "Mains"), ("capacity", "100")]);
|
||||
fixture.source(
|
||||
"mouse",
|
||||
&[
|
||||
("type", "Battery"),
|
||||
("scope", "Device"),
|
||||
("present", "1"),
|
||||
("capacity", "100"),
|
||||
],
|
||||
);
|
||||
fixture.source(
|
||||
"absent",
|
||||
&[("type", "Battery"), ("present", "0"), ("capacity", "100")],
|
||||
);
|
||||
assert_eq!(fixture.read(), None);
|
||||
fixture.source(
|
||||
"BAT0",
|
||||
&[
|
||||
("type", "Battery\n"),
|
||||
("scope", "System\n"),
|
||||
("present", "1\n"),
|
||||
("capacity", "27\n"),
|
||||
],
|
||||
);
|
||||
assert_eq!(fixture.read(), Some(27));
|
||||
fixture.source("BAT0", &[("capacity", "0")]);
|
||||
assert_eq!(fixture.read(), Some(0));
|
||||
fixture.source("BAT0", &[("capacity", "100")]);
|
||||
assert_eq!(fixture.read(), Some(100));
|
||||
for invalid in ["101", "-1", "255", "garbage", ""] {
|
||||
fixture.source("BAT0", &[("capacity", invalid)]);
|
||||
assert_eq!(fixture.read(), None);
|
||||
}
|
||||
fs::remove_file(fixture.0.join("BAT0/capacity")).unwrap();
|
||||
assert_eq!(fixture.read(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysfs_uses_matching_actual_energy_or_charge_totals_only() {
|
||||
let energy = Fixture::new();
|
||||
energy.source(
|
||||
"BAT0",
|
||||
&[
|
||||
("type", "Battery"),
|
||||
("present", "1"),
|
||||
("energy_now", "27"),
|
||||
("energy_full", "100"),
|
||||
],
|
||||
);
|
||||
assert_eq!(energy.read(), Some(27));
|
||||
energy.source("BAT0", &[("energy_full", "0")]);
|
||||
assert_eq!(energy.read(), None);
|
||||
energy.source("BAT0", &[("energy_full", "26")]);
|
||||
assert_eq!(energy.read(), None);
|
||||
energy.source("BAT0", &[("energy_full", "garbage")]);
|
||||
assert_eq!(energy.read(), None);
|
||||
let charge = Fixture::new();
|
||||
charge.source(
|
||||
"BAT0",
|
||||
&[
|
||||
("type", "Battery"),
|
||||
("present", "1"),
|
||||
("charge_now", "15"),
|
||||
("charge_full", "20"),
|
||||
],
|
||||
);
|
||||
assert_eq!(charge.read(), Some(75));
|
||||
charge.source("BAT0", &[("energy_now", "5")]);
|
||||
assert_eq!(charge.read(), None);
|
||||
let design = Fixture::new();
|
||||
design.source(
|
||||
"BAT0",
|
||||
&[
|
||||
("type", "Battery"),
|
||||
("present", "1"),
|
||||
("energy_now", "20"),
|
||||
("energy_full_design", "100"),
|
||||
],
|
||||
);
|
||||
assert_eq!(design.read(), None);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
unsafe extern "C" {
|
||||
fn CFNumberCreate(allocator: Object, kind: isize, value: Object) -> Object;
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_values_are_type_checked_and_numbers_must_be_exact_and_nonnegative() {
|
||||
assert!(Owned::new(std::ptr::null()).is_none());
|
||||
unsafe {
|
||||
assert_eq!(number(std::ptr::null()), None);
|
||||
let text = Owned::string(c"27").unwrap();
|
||||
assert_eq!(number(text.0), None);
|
||||
for value in [-1_i64, 0, 100] {
|
||||
let object = Owned::new(CFNumberCreate(
|
||||
std::ptr::null(),
|
||||
4,
|
||||
(&value as *const i64).cast(),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(number(object.0), u64::try_from(value).ok());
|
||||
}
|
||||
let fraction = 1.5_f64;
|
||||
let object = Owned::new(CFNumberCreate(
|
||||
std::ptr::null(),
|
||||
6,
|
||||
(&fraction as *const f64).cast(),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(number(object.0), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
use super::*;
|
||||
|
||||
fn command(root: &Path, program: &str, args: &[&str]) -> String {
|
||||
let mut command = Command::new(program);
|
||||
if program == "jj" {
|
||||
command.args([
|
||||
"--config=user.name=\"Jj Author\"",
|
||||
"--config=user.email=\"jj@example.test\"",
|
||||
]);
|
||||
command.args([
|
||||
"--config=debug.commit-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
"--config=debug.operation-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
]);
|
||||
}
|
||||
let output = command
|
||||
.args(args)
|
||||
.current_dir(root)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_CONFIG_SYSTEM", "/dev/null")
|
||||
.env("GIT_AUTHOR_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().into()
|
||||
}
|
||||
fn disk_state(root: &Path) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {
|
||||
fn visit(root: &Path, path: &Path, state: &mut std::collections::BTreeMap<PathBuf, Vec<u8>>) {
|
||||
for entry in fs::read_dir(path).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let metadata = fs::symlink_metadata(&path).unwrap();
|
||||
if metadata.is_dir() {
|
||||
visit(root, &path, state);
|
||||
} else if metadata.is_file() {
|
||||
state.insert(
|
||||
path.strip_prefix(root).unwrap().to_path_buf(),
|
||||
fs::read(path).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut state = std::collections::BTreeMap::new();
|
||||
visit(root, root, &mut state);
|
||||
state
|
||||
}
|
||||
|
||||
fn fixture() -> (Temporary, PathBuf, String) {
|
||||
let temp = Temporary::new().unwrap();
|
||||
command(&temp.0, "git", &["init", "--quiet", "--template="]);
|
||||
command(&temp.0, "git", &["config", "user.name", "Blame Author"]);
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["config", "user.email", "blame@example.test"],
|
||||
);
|
||||
let path = temp.0.join("-literal [file].txt");
|
||||
fs::write(&path, "first\nsecond\n").unwrap();
|
||||
command(&temp.0, "git", &["add", "--", "-literal [file].txt"]);
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["commit", "--quiet", "-m", "Original summary"],
|
||||
);
|
||||
let commit = command(&temp.0, "git", &["rev-parse", "HEAD"]);
|
||||
(temp, path, commit)
|
||||
}
|
||||
#[test]
|
||||
fn committed_line_has_native_author_summary_and_commit() {
|
||||
let (_temp, path, commit) = fixture();
|
||||
let rows = read_file(&path, "first\nsecond\n", &|| false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[0].as_ref().unwrap(),
|
||||
rows[1].as_ref().unwrap()
|
||||
));
|
||||
assert_eq!(
|
||||
**rows[1].as_ref().unwrap(),
|
||||
LineBlame {
|
||||
commit,
|
||||
author: "Blame Author".into(),
|
||||
summary: "Original summary".into(),
|
||||
uncommitted: false
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn unsaved_changed_line_is_uncommitted_without_metadata() {
|
||||
let (_temp, path, _) = fixture();
|
||||
let rows = read_file(&path, "changed\nsecond\n", &|| false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
**rows[0].as_ref().unwrap(),
|
||||
LineBlame {
|
||||
commit: String::new(),
|
||||
author: String::new(),
|
||||
summary: String::new(),
|
||||
uncommitted: true
|
||||
}
|
||||
);
|
||||
assert_eq!(fs::read_to_string(path).unwrap(), "first\nsecond\n");
|
||||
}
|
||||
#[test]
|
||||
fn inserted_line_preserves_following_original_attribution() {
|
||||
let (_temp, path, commit) = fixture();
|
||||
let contents = "inserted\nfirst\nsecond\n";
|
||||
let rows = read_file(&path, contents, &|| false).unwrap().unwrap();
|
||||
assert!(rows[0].as_ref().unwrap().uncommitted);
|
||||
assert_eq!(rows[2].as_ref().unwrap().commit, commit);
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!(read_file(&path, "", &|| false).unwrap(), None);
|
||||
}
|
||||
#[test]
|
||||
fn unsaved_insertions_and_deletions_keep_shifted_commit_attribution() {
|
||||
let (temp, path, original) = fixture();
|
||||
fs::write(&path, "first\nmiddle\nsecond\ntail\n").unwrap();
|
||||
command(&temp.0, "git", &["add", "--", "-literal [file].txt"]);
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Added lines"]);
|
||||
let added = command(&temp.0, "git", &["rev-parse", "HEAD"]);
|
||||
let rows = read_file(
|
||||
&path,
|
||||
"unsaved\nfirst\nsecond\nunsaved tail\ntail\n",
|
||||
&|| false,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(rows[0].as_ref().unwrap().uncommitted);
|
||||
assert_eq!(rows[1].as_ref().unwrap().commit, original);
|
||||
assert_eq!(rows[2].as_ref().unwrap().commit, original);
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[1].as_ref().unwrap(),
|
||||
rows[2].as_ref().unwrap()
|
||||
));
|
||||
assert!(rows[3].as_ref().unwrap().uncommitted);
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[0].as_ref().unwrap(),
|
||||
rows[3].as_ref().unwrap()
|
||||
));
|
||||
assert_eq!(rows[4].as_ref().unwrap().commit, added);
|
||||
assert_eq!(rows[4].as_ref().unwrap().summary, "Added lines");
|
||||
assert_eq!(
|
||||
fs::read_to_string(path).unwrap(),
|
||||
"first\nmiddle\nsecond\ntail\n"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn missing_untracked_unborn_nonrepo_and_symlink_have_no_blame() {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let path = temp.0.join("file");
|
||||
assert_eq!(read_file(&path, "text", &|| false).unwrap(), None);
|
||||
fs::write(&path, "text").unwrap();
|
||||
assert_eq!(read_file(&path, "text", &|| false).unwrap(), None);
|
||||
command(&temp.0, "git", &["init", "--quiet", "--template="]);
|
||||
assert_eq!(read_file(&path, "text", &|| false).unwrap(), None);
|
||||
let (_committed, tracked, _) = fixture();
|
||||
let untracked = tracked.parent().unwrap().join("untracked");
|
||||
fs::write(&untracked, "text").unwrap();
|
||||
assert_eq!(read_file(&untracked, "text", &|| false).unwrap(), None);
|
||||
let link = temp.0.join("link");
|
||||
std::os::unix::fs::symlink(tracked, &link).unwrap();
|
||||
assert_eq!(
|
||||
read_file(&link, "first\nsecond\n", &|| false).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn historical_git_and_jj_blame_survives_renamed_and_deleted_paths() {
|
||||
for is_jj in [false, true] {
|
||||
let (temp, old_path, original) = fixture();
|
||||
if is_jj {
|
||||
command(&temp.0, "jj", &["git", "init", "--colocate", "."]);
|
||||
command(&temp.0, "jj", &["new", &original]);
|
||||
}
|
||||
fs::write(&old_path, "historical\nsecond\n").unwrap();
|
||||
let selected = if is_jj {
|
||||
command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&["describe", "-m", "Selected historical lines"],
|
||||
);
|
||||
let id = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&["log", "--no-graph", "-r", "@", "-T", "commit_id"],
|
||||
);
|
||||
command(&temp.0, "jj", &["new"]);
|
||||
id
|
||||
} else {
|
||||
command(&temp.0, "git", &["add", "."]);
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["commit", "--quiet", "-m", "Selected historical lines"],
|
||||
);
|
||||
command(&temp.0, "git", &["rev-parse", "HEAD"])
|
||||
};
|
||||
let renamed = temp.0.join("renamed.txt");
|
||||
fs::rename(&old_path, &renamed).unwrap();
|
||||
let renamed_commit = if is_jj {
|
||||
command(&temp.0, "jj", &["describe", "-m", "Rename"]);
|
||||
let id = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&["log", "--no-graph", "-r", "@", "-T", "commit_id"],
|
||||
);
|
||||
command(&temp.0, "jj", &["new"]);
|
||||
id
|
||||
} else {
|
||||
command(&temp.0, "git", &["add", "-A"]);
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Rename"]);
|
||||
command(&temp.0, "git", &["rev-parse", "HEAD"])
|
||||
};
|
||||
fs::remove_file(&renamed).unwrap();
|
||||
if is_jj {
|
||||
command(&temp.0, "jj", &["describe", "-m", "Delete"]);
|
||||
command(&temp.0, "jj", &["new"]);
|
||||
} else {
|
||||
command(&temp.0, "git", &["add", "-A"]);
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Delete"]);
|
||||
}
|
||||
let store = if is_jj {
|
||||
crate::repository::store_for_jj(&temp.0).unwrap()
|
||||
} else {
|
||||
temp.0.join(".git")
|
||||
};
|
||||
let state = disk_state(&temp.0);
|
||||
for (commit, path) in [
|
||||
(
|
||||
selected.clone(),
|
||||
old_path.strip_prefix(&temp.0).unwrap().to_path_buf(),
|
||||
),
|
||||
(renamed_commit, PathBuf::from("renamed.txt")),
|
||||
] {
|
||||
let source = RevisionSource {
|
||||
store: store.clone(),
|
||||
commit,
|
||||
path,
|
||||
keepalive: None,
|
||||
};
|
||||
let mut worker = BlameWorker::start().unwrap();
|
||||
worker
|
||||
.request(
|
||||
1,
|
||||
old_path.clone(),
|
||||
"historical\nsecond\n".into(),
|
||||
Some(source),
|
||||
)
|
||||
.unwrap();
|
||||
let started = Instant::now();
|
||||
let rows = loop {
|
||||
if let Some((id, result)) = worker.poll() {
|
||||
assert_eq!(id, 1);
|
||||
break result.unwrap().unwrap();
|
||||
}
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(20),
|
||||
"Historical blame stalled"
|
||||
);
|
||||
thread::yield_now();
|
||||
};
|
||||
assert_eq!(rows[0].as_ref().unwrap().commit, selected);
|
||||
assert_eq!(
|
||||
rows[0].as_ref().unwrap().summary,
|
||||
"Selected historical lines"
|
||||
);
|
||||
assert!(!rows[0].as_ref().unwrap().uncommitted);
|
||||
assert_eq!(rows[1].as_ref().unwrap().commit, original);
|
||||
}
|
||||
assert!(!old_path.exists() && !renamed.exists());
|
||||
assert_eq!(disk_state(&temp.0), state);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn privately_fetched_git_and_noncolocated_jj_sources_keep_selected_attribution() {
|
||||
use crate::diff::{Category, ComparisonMode, Revision, RevisionTarget};
|
||||
let (remote, remote_path, original) = fixture();
|
||||
fs::write(&remote_path, "private historical\nsecond\n").unwrap();
|
||||
command(&remote.0, "git", &["add", "."]);
|
||||
command(
|
||||
&remote.0,
|
||||
"git",
|
||||
&["commit", "--quiet", "-m", "Private selected"],
|
||||
);
|
||||
let selected = command(&remote.0, "git", &["rev-parse", "HEAD"]);
|
||||
let reference = command(&remote.0, "git", &["symbolic-ref", "HEAD"]);
|
||||
for is_jj in [false, true] {
|
||||
let (active, active_path, _) = fixture();
|
||||
fs::remove_file(&active_path).unwrap();
|
||||
if is_jj {
|
||||
fs::remove_dir_all(active.0.join(".git")).unwrap();
|
||||
command(&active.0, "jj", &["git", "init", "--no-colocate", "."]);
|
||||
command(
|
||||
&active.0,
|
||||
"jj",
|
||||
&["git", "remote", "add", "origin", remote.0.to_str().unwrap()],
|
||||
);
|
||||
} else {
|
||||
command(
|
||||
&active.0,
|
||||
"git",
|
||||
&["remote", "add", "origin", remote.0.to_str().unwrap()],
|
||||
);
|
||||
}
|
||||
let revision = |id: &str| Revision {
|
||||
target: RevisionTarget::RemoteCommit {
|
||||
remote: "origin".into(),
|
||||
reference: reference.clone(),
|
||||
id: id.into(),
|
||||
},
|
||||
label: id.into(),
|
||||
description: String::new(),
|
||||
category: Category::Commits,
|
||||
};
|
||||
let state = disk_state(&active.0);
|
||||
let mut repository =
|
||||
crate::repository::Repository::open(&active.0, Arc::new(AtomicBool::new(false)))
|
||||
.unwrap();
|
||||
let comparison = repository
|
||||
.compare(
|
||||
1,
|
||||
&revision(&original),
|
||||
&revision(&selected),
|
||||
ComparisonMode::Snapshots,
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let baseline = comparison.blame[1].as_ref().unwrap();
|
||||
assert_eq!(baseline.commit, selected);
|
||||
assert!(!baseline.store.starts_with(&active.0));
|
||||
let source = RevisionSource {
|
||||
store: baseline.store.clone(),
|
||||
commit: baseline.commit.clone(),
|
||||
path: remote_path.strip_prefix(&remote.0).unwrap().to_path_buf(),
|
||||
keepalive: baseline.keepalive.clone(),
|
||||
};
|
||||
let store = source.store.clone();
|
||||
drop(comparison);
|
||||
drop(repository);
|
||||
assert!(
|
||||
store.exists(),
|
||||
"Snapshot provenance must retain private fetched objects"
|
||||
);
|
||||
let rows = read_revision(&source, "private historical\nsecond\n", &|| false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(rows[0].as_ref().unwrap().commit, selected);
|
||||
assert_eq!(rows[1].as_ref().unwrap().commit, original);
|
||||
assert!(!rows[0].as_ref().unwrap().uncommitted);
|
||||
assert_eq!(disk_state(&active.0), state);
|
||||
drop(source);
|
||||
assert!(
|
||||
!store.exists(),
|
||||
"Last snapshot release must remove private objects"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revision_sources_reject_unsafe_paths_and_skip_missing_or_nonregular_baselines() {
|
||||
let (temp, path, commit) = fixture();
|
||||
let mut source = RevisionSource {
|
||||
store: temp.0.join(".git"),
|
||||
commit,
|
||||
path: "not-in-baseline".into(),
|
||||
keepalive: None,
|
||||
};
|
||||
assert_eq!(read_revision(&source, "new\n", &|| false).unwrap(), None);
|
||||
for path in ["", "../file", "/outside", ".git/config", ".jj/repo"] {
|
||||
source.path = path.into();
|
||||
assert!(read_revision(&source, "new\n", &|| false).is_err());
|
||||
}
|
||||
std::os::unix::fs::symlink(&path, temp.0.join("link")).unwrap();
|
||||
fs::create_dir(temp.0.join("nested")).unwrap();
|
||||
fs::write(temp.0.join("nested/file"), "nested\n").unwrap();
|
||||
command(&temp.0, "git", &["add", "link", "nested/file"]);
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Link"]);
|
||||
source.commit = command(&temp.0, "git", &["rev-parse", "HEAD"]);
|
||||
source.path = "link".into();
|
||||
assert_eq!(read_revision(&source, "target\n", &|| false).unwrap(), None);
|
||||
source.path = "nested".into();
|
||||
assert_eq!(read_revision(&source, "nested\n", &|| false).unwrap(), None);
|
||||
source.path = "nested/file".into();
|
||||
let nested = read_revision(&source, "nested\n", &|| false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(nested[0].as_ref().unwrap().commit, source.commit);
|
||||
source.path = path.strip_prefix(&temp.0).unwrap().into();
|
||||
assert_eq!(
|
||||
read_revision(&source, "first\n", &|| true).unwrap_err(),
|
||||
"Blame cancelled"
|
||||
);
|
||||
assert_eq!(
|
||||
read_revision(&source, &"x".repeat(LIMIT + 1), &|| false).unwrap_err(),
|
||||
"Blame input exceeds 16 MiB"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noncolocated_jj_uses_parent_without_snapshotting_or_changing_refs() {
|
||||
let temp = Temporary::new().unwrap();
|
||||
command(&temp.0, "jj", &["git", "init", "--no-colocate", "."]);
|
||||
let path = temp.0.join("file");
|
||||
fs::write(&path, "original\n").unwrap();
|
||||
assert_eq!(read_file(&path, "original\n", &|| false).unwrap(), None);
|
||||
command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--config=user.name=\"Jj Author\"",
|
||||
"--config=user.email=\"jj@example.test\"",
|
||||
"describe",
|
||||
"-m",
|
||||
"Jj summary",
|
||||
],
|
||||
);
|
||||
command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--config=user.name=\"Jj Author\"",
|
||||
"--config=user.email=\"jj@example.test\"",
|
||||
"new",
|
||||
],
|
||||
);
|
||||
let parent = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
let operation = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
],
|
||||
);
|
||||
let rows = read_file(&path, "original\n", &|| false).unwrap().unwrap();
|
||||
let line = rows[0].as_ref().unwrap();
|
||||
assert_eq!(line.commit, parent);
|
||||
assert_eq!(line.author, "Jj Author");
|
||||
assert_eq!(line.summary, "Jj summary");
|
||||
fs::write(&path, "dirty on disk\n").unwrap();
|
||||
let shifted = read_file(&path, "inserted\noriginal\n", &|| false)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(shifted[0].as_ref().unwrap().uncommitted);
|
||||
assert_eq!(shifted[1].as_ref().unwrap().commit, parent);
|
||||
assert!(
|
||||
read_file(&path, "unsaved\n", &|| false).unwrap().unwrap()[0]
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.uncommitted
|
||||
);
|
||||
assert_eq!(
|
||||
command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
]
|
||||
),
|
||||
operation
|
||||
);
|
||||
assert!(!temp.0.join(".git").exists());
|
||||
command(&temp.0, "jj", &["new", "root()"]);
|
||||
fs::write(temp.0.join("other"), "sibling\n").unwrap();
|
||||
command(&temp.0, "jj", &["describe", "-m", "Sibling"]);
|
||||
command(&temp.0, "jj", &["new", &parent, "@"]);
|
||||
assert_eq!(read_file(&path, "original\n", &|| false).unwrap(), None);
|
||||
}
|
||||
#[test]
|
||||
fn incremental_groups_share_metadata_across_ranges_and_repeated_commits() {
|
||||
let first = "1111111111111111111111111111111111111111";
|
||||
let second = "2222222222222222222222222222222222222222";
|
||||
let output = format!(
|
||||
"{first} 5 3 2\nauthor First\nsummary First summary\nfilename file\n\
|
||||
{second} 8 2 1\nauthor Second\nsummary Second summary\nfilename file\n\
|
||||
{first} 1 1 1\nfilename old-file\n"
|
||||
);
|
||||
let rows = parse(output.as_bytes(), 4).unwrap();
|
||||
assert_eq!(rows[0].as_ref().unwrap().commit, first);
|
||||
assert_eq!(rows[1].as_ref().unwrap().author, "Second");
|
||||
assert_eq!(rows[1].as_ref().unwrap().commit, second);
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[0].as_ref().unwrap(),
|
||||
rows[2].as_ref().unwrap()
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[2].as_ref().unwrap(),
|
||||
rows[3].as_ref().unwrap()
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn malformed_incremental_groups_never_echo_metadata() {
|
||||
let commit = "1111111111111111111111111111111111111111";
|
||||
let metadata = "author secret\nsummary secret\nfilename secret\n";
|
||||
let valid = format!("{commit} 1 1 1\n{metadata}");
|
||||
for output in [
|
||||
"secret metadata".into(),
|
||||
"\u{fffd}secret metadata".into(),
|
||||
format!("{commit} 1 2 1\n{metadata}"),
|
||||
format!("{commit} 1 1 2\n{metadata}"),
|
||||
format!("{commit} 0 1 1\n{metadata}"),
|
||||
format!("{commit} 1 1 0\n{metadata}"),
|
||||
format!("{commit} 1 1 1 extra\n{metadata}"),
|
||||
format!("{commit} 1 1 1\nauthor secret\nfilename secret\n"),
|
||||
format!("{commit} 1 1 1\nauthor secret\nauthor secret\nsummary secret\nfilename secret\n"),
|
||||
format!("{commit} 1 1 1\nauthor secret\nsummary secret\n\tsecret source\n"),
|
||||
format!("{valid}{commit} 2 1 1\nfilename secret\n"),
|
||||
format!("{commit} 1 1 1\nauthor secret\nsummary secret\n{commit} 2 1 1\nfilename secret\n"),
|
||||
format!("{commit} {} 1 2\n{metadata}", usize::MAX),
|
||||
] {
|
||||
assert_eq!(
|
||||
parse(output.as_bytes(), 1).unwrap_err(),
|
||||
"Invalid Git blame metadata"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
parse(valid.as_bytes(), 2).unwrap_err(),
|
||||
"Invalid Git blame metadata"
|
||||
);
|
||||
assert_eq!(
|
||||
parse(b"\xffsecret metadata", 1).unwrap_err(),
|
||||
"Invalid Git blame metadata"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn cancelled_commands_kill_and_reap_pipe_holding_children() {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let ready = temp.0.join("ready");
|
||||
let cancellation = Arc::new(AtomicBool::new(false));
|
||||
let stop = Arc::clone(&cancellation);
|
||||
let gate = ready.clone();
|
||||
let worker = thread::spawn(move || {
|
||||
let mut command = Command::new("sh");
|
||||
command
|
||||
.args([
|
||||
"-c",
|
||||
"sleep 600 & printf ready > \"$1\"; wait",
|
||||
"vamp-blame-test",
|
||||
])
|
||||
.arg(gate);
|
||||
run(command, &[], &|| stop.load(Ordering::Acquire))
|
||||
});
|
||||
while !ready.exists() && !worker.is_finished() {
|
||||
thread::yield_now();
|
||||
}
|
||||
assert!(ready.exists());
|
||||
cancellation.store(true, Ordering::Release);
|
||||
assert_eq!(worker.join().unwrap().unwrap_err(), "Blame cancelled");
|
||||
}
|
||||
#[test]
|
||||
fn worker_keeps_only_latest_request_and_bounds_input() {
|
||||
let (_temp, path, commit) = fixture();
|
||||
let mut worker = BlameWorker::start().unwrap();
|
||||
for id in 0..20 {
|
||||
worker
|
||||
.request(id, path.clone(), "first\nsecond\n".into(), None)
|
||||
.unwrap();
|
||||
}
|
||||
loop {
|
||||
if let Some((id, result)) = worker.poll() {
|
||||
assert_eq!(id, 19);
|
||||
let rows = result.unwrap().unwrap();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[1].as_ref().unwrap().commit, commit);
|
||||
assert!(Arc::ptr_eq(
|
||||
rows[0].as_ref().unwrap(),
|
||||
rows[1].as_ref().unwrap()
|
||||
));
|
||||
break;
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
worker
|
||||
.request(20, path, "x".repeat(LIMIT + 1), None)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidInput
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn subprocess_output_is_bounded() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "dd if=/dev/zero bs=1048576 count=17 2>/dev/null"]);
|
||||
assert_eq!(
|
||||
run(command, &[], &|| false).unwrap_err(),
|
||||
"Blame output exceeds 16 MiB"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn popup_partial_options_keep_command_and_search_independent() {
|
||||
let popup: PopupConfig = serde_json::from_value(serde_json::json!({
|
||||
"command": {"anchor": "top_right"}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(popup.command.anchor, PopupAnchor::TopRight);
|
||||
assert_eq!(popup.search.anchor, PopupAnchor::BottomLeft);
|
||||
let popup: PopupConfig = serde_json::from_value(serde_json::json!({
|
||||
"command": {}, "search": {"anchor": "center_left"}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(popup.command.anchor, PopupAnchor::BottomLeft);
|
||||
assert_eq!(popup.search.anchor, PopupAnchor::CenterLeft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_popup_options_are_rejected_at_the_boundary() {
|
||||
for value in [
|
||||
serde_json::json!(null),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!(7),
|
||||
serde_json::json!({"selector": {}}),
|
||||
] {
|
||||
assert!(
|
||||
serde_json::from_value::<PopupConfig>(value.clone()).is_err(),
|
||||
"{value}"
|
||||
);
|
||||
}
|
||||
for options in [
|
||||
serde_json::json!(null),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!("center"),
|
||||
serde_json::json!({"anchor": null}),
|
||||
serde_json::json!({"anchor": 7}),
|
||||
serde_json::json!({"anchor": true}),
|
||||
serde_json::json!({"anchor": []}),
|
||||
serde_json::json!({"anchor": {}}),
|
||||
serde_json::json!({"anchor": "middle"}),
|
||||
serde_json::json!({"anchor": "TopLeft"}),
|
||||
serde_json::json!({"width": 72}),
|
||||
serde_json::json!({"anchor": "center", "callback": "run"}),
|
||||
] {
|
||||
for mode in ["command", "search"] {
|
||||
let mut popup = serde_json::json!({});
|
||||
popup[mode] = options.clone();
|
||||
assert!(
|
||||
serde_json::from_value::<PopupConfig>(popup).is_err(),
|
||||
"{mode}: {options}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Lines {
|
||||
#[serde(deserialize_with = "top")]
|
||||
top: ChromeLine,
|
||||
#[serde(deserialize_with = "bottom")]
|
||||
bottom: ChromeLine,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_options_inherit_and_explicit_groups_replace_defaults() {
|
||||
let lines: Lines = serde_json::from_value(serde_json::json!({
|
||||
"top": {"right": ["battery"], "tabs": {"title": "T{index}:{path}{modified}"}, "battery": {"padding": 0}},
|
||||
"bottom": {"left": [], "center": ["workspace"]}
|
||||
})).unwrap();
|
||||
assert_eq!(lines.top.left, ["tabs"]);
|
||||
assert_eq!(lines.top.segment("battery").padding, 0);
|
||||
assert!(lines.bottom.left.is_empty());
|
||||
assert_eq!(lines.bottom.right, ["language", "lsp", "position"]);
|
||||
assert_eq!(lines.bottom.segment("workspace"), &SegmentConfig::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_positions_accept_all_builtins_and_custom_styles() {
|
||||
let defaults = ChromeLine::top();
|
||||
assert_eq!(defaults.right, ["diff", "shell", "battery"]);
|
||||
let names = [
|
||||
"tabs",
|
||||
"mode",
|
||||
"pending",
|
||||
"buffer",
|
||||
"diagnostics",
|
||||
"path",
|
||||
"selections",
|
||||
"count",
|
||||
"language",
|
||||
"lsp",
|
||||
"position",
|
||||
"battery",
|
||||
"diff",
|
||||
"workspace",
|
||||
];
|
||||
let options = serde_json::json!({
|
||||
"left": names,
|
||||
"center": ["language"],
|
||||
"right": ["tabs"],
|
||||
"tabs": {"title": "{index}:{name}:{path}{modified}", "padding": 0},
|
||||
"mode": {"leading_edge": "<", "trailing_edge": ">"},
|
||||
"workspace": {"first_leading_edge": ""}
|
||||
});
|
||||
let lines: Lines = serde_json::from_value(serde_json::json!({
|
||||
"top": options,
|
||||
"bottom": options,
|
||||
}))
|
||||
.unwrap();
|
||||
for line in [&lines.top, &lines.bottom] {
|
||||
assert_eq!(line.left, names);
|
||||
assert_eq!(line.center, ["language"]);
|
||||
assert_eq!(line.right, ["tabs"]);
|
||||
assert_eq!(line.segment("tabs").padding, 0);
|
||||
assert_eq!(line.segment("mode").leading_edge, "<");
|
||||
assert_eq!(
|
||||
line.segment("workspace").first_leading_edge.as_deref(),
|
||||
Some("")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_placeholders_are_valid_in_every_segment_and_bar() {
|
||||
for name in [
|
||||
"tabs",
|
||||
"mode",
|
||||
"pending",
|
||||
"buffer",
|
||||
"diagnostics",
|
||||
"path",
|
||||
"selections",
|
||||
"count",
|
||||
"language",
|
||||
"lsp",
|
||||
"position",
|
||||
"battery",
|
||||
"diff",
|
||||
"workspace",
|
||||
] {
|
||||
let options = serde_json::json!({
|
||||
"left": [name],
|
||||
(name): {"title": "{index}:{view}{name}{changes}:{path}{modified}"}
|
||||
});
|
||||
let lines: Lines = serde_json::from_value(serde_json::json!({
|
||||
"top": options,
|
||||
"bottom": options,
|
||||
}))
|
||||
.unwrap();
|
||||
for line in [&lines.top, &lines.bottom] {
|
||||
assert_eq!(
|
||||
line.segment(name).title,
|
||||
"{index}:{view}{name}{changes}:{path}{modified}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_chrome_is_rejected_at_the_boundary() {
|
||||
for options in [
|
||||
serde_json::json!({"left": ["bad-name"]}),
|
||||
serde_json::json!({"left": null}),
|
||||
serde_json::json!({"tabs": {"padding": 65}}),
|
||||
serde_json::json!({"tabs": {"padding": null}}),
|
||||
serde_json::json!({"tabs": {"margin": 65}}),
|
||||
serde_json::json!({"tabs": {"margin": -1}}),
|
||||
serde_json::json!({"tabs": {"margin": null}}),
|
||||
serde_json::json!({"tabs": {"margin": "1"}}),
|
||||
serde_json::json!({"tabs": {"margin": 1.5}}),
|
||||
serde_json::json!({"tabs": {"leading_edge": "\n"}}),
|
||||
serde_json::json!({"tabs": {"title": "{unknown}"}}),
|
||||
serde_json::json!({"tabs": {"title": "{name"}}),
|
||||
serde_json::json!({"tabs": {"title": "name}"}}),
|
||||
serde_json::json!({"tabs": {"colour": "red"}}),
|
||||
] {
|
||||
for position in ["top", "bottom"] {
|
||||
let mut frame = serde_json::json!({"top": {}, "bottom": {}});
|
||||
frame[position] = options.clone();
|
||||
assert!(serde_json::from_value::<Lines>(frame).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Option<Options>, String> {
|
||||
parse_options(args.iter().map(std::ffi::OsString::from))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_commands_preserve_filenames_and_validate_arguments() {
|
||||
assert_eq!(
|
||||
parse(&["review"]).unwrap().unwrap().file,
|
||||
Some("review".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--", "--review"]).unwrap().unwrap().file,
|
||||
Some("--review".into())
|
||||
);
|
||||
assert!(
|
||||
parse(&["--no-config", "--review", "list", "--repo", ".", "--json"])
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.review
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
parse(&["--review", "show", "1", "--all", "--no-config"])
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.review
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
parse(&[
|
||||
"--review",
|
||||
"delete",
|
||||
"1",
|
||||
"2",
|
||||
"--repo",
|
||||
".",
|
||||
"--json",
|
||||
"--no-config"
|
||||
])
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.review
|
||||
.is_some()
|
||||
);
|
||||
for args in [
|
||||
vec!["--review"],
|
||||
vec!["--review", "show"],
|
||||
vec!["--review", "show", "0"],
|
||||
vec!["--review", "show", "-1"],
|
||||
vec!["--review", "show", "abc"],
|
||||
vec!["--review", "delete"],
|
||||
vec!["--review", "delete", "1"],
|
||||
vec!["--review", "delete", "0", "1"],
|
||||
vec!["--review", "delete", "9223372036854775808", "1"],
|
||||
vec!["--review", "delete", "1", "0"],
|
||||
vec!["--review", "delete", "1", "-1"],
|
||||
vec!["--review", "delete", "1", "abc"],
|
||||
vec!["--review", "delete", "1", "18446744073709551616"],
|
||||
vec!["--review", "delete", "1", "2", "--all"],
|
||||
vec!["--review", "delete", "1", "2", "3"],
|
||||
vec!["--review", "list", "--all"],
|
||||
vec!["--review", "list", "--repo"],
|
||||
vec!["--review", "list", "--repo", ".", "--repo", "."],
|
||||
vec!["--review", "list", "extra"],
|
||||
vec!["--review", "list", "--", "extra"],
|
||||
vec!["--review", "list", "--config", "x", "--no-config"],
|
||||
] {
|
||||
assert!(parse(&args).is_err(), "{args:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static FIXTURE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-clipboard-{}-{}",
|
||||
std::process::id(),
|
||||
FIXTURE_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn command(&self, name: &str, body: &str) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn clipboard(&self, text: &[u8]) -> SystemClipboard {
|
||||
let state = self.0.join("state");
|
||||
fs::write(&state, text).unwrap();
|
||||
let state = format!("'{}'", state.to_str().unwrap().replace('\'', "'\\''"));
|
||||
SystemClipboard::with_commands(
|
||||
self.command("read", &format!("exec /bin/cat {state}")),
|
||||
self.command("write", &format!("exec /bin/cat > {state}")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_does_not_probe_or_spawn() {
|
||||
assert!(SystemClipboard::new().commands.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_unicode_whitespace_and_large_pipes_exactly() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(b"");
|
||||
for text in ["", " héllo\t世界🙂\r\n\n", &"é\n".repeat(300_000)] {
|
||||
clipboard.write(text).unwrap();
|
||||
assert_eq!(fs::read(fixture.0.join("state")).unwrap(), text.as_bytes());
|
||||
assert_eq!(clipboard.read().unwrap(), text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversize_and_invalid_utf8_without_leaking_contents() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(&[0xff, b'\n']);
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard is not valid UTF-8"
|
||||
);
|
||||
let maximum = "é".repeat(MAX_CLIPBOARD_BYTES / 2);
|
||||
clipboard.write(&maximum).unwrap();
|
||||
assert_eq!(clipboard.read().unwrap(), maximum);
|
||||
let too_large = format!("{maximum}x");
|
||||
assert_eq!(
|
||||
clipboard.write(&too_large).unwrap_err(),
|
||||
"System clipboard text exceeds 4 MiB"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("state")).unwrap(),
|
||||
maximum.as_bytes()
|
||||
);
|
||||
fs::write(fixture.0.join("state"), &too_large).unwrap();
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard text exceeds 4 MiB"
|
||||
);
|
||||
let mut incomplete = vec![b'x'; MAX_CLIPBOARD_BYTES - 1];
|
||||
incomplete.push(0xc3);
|
||||
fs::write(fixture.0.join("state"), incomplete).unwrap();
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard is not valid UTF-8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_failures_and_stderr_cannot_leak_clipboard_text() {
|
||||
let fixture = Fixture::new();
|
||||
let failed = fixture.command(
|
||||
"failed",
|
||||
"printf 'private clipboard payload' >&2\nprintf 'private clipboard payload'\nexit 23",
|
||||
);
|
||||
let mut clipboard = SystemClipboard::with_commands(failed.clone(), failed);
|
||||
let error = clipboard.read().unwrap_err();
|
||||
assert!(error.contains("failed"));
|
||||
assert!(!error.contains("private clipboard payload"));
|
||||
let error = clipboard.write("private clipboard payload").unwrap_err();
|
||||
assert!(!error.contains("private clipboard payload"));
|
||||
let missing = fixture.0.join("not-an-executable");
|
||||
let mut clipboard = SystemClipboard::with_commands(missing.clone(), missing);
|
||||
assert!(clipboard.read().unwrap_err().contains("Cannot start"));
|
||||
assert!(
|
||||
clipboard
|
||||
.write("secret")
|
||||
.unwrap_err()
|
||||
.contains("Cannot start")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_stderr_does_not_block_large_writes() {
|
||||
let fixture = Fixture::new();
|
||||
let mut clipboard = fixture.clipboard(b"");
|
||||
let state = fixture.0.join("state");
|
||||
let state = format!("'{}'", state.to_str().unwrap().replace('\'', "'\\''"));
|
||||
clipboard
|
||||
.commands
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.writer
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.program = fixture.command(
|
||||
"noisy",
|
||||
&format!("/bin/dd if=/dev/zero bs=65536 count=8 >&2\nexec /bin/cat > {state}"),
|
||||
);
|
||||
let text = "λ\n".repeat(300_000);
|
||||
clipboard.write(&text).unwrap();
|
||||
assert_eq!(clipboard.read().unwrap(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_process_cleanup_kills_and_reaps_a_running_child() {
|
||||
use std::io::Read;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32;
|
||||
}
|
||||
|
||||
let fixture = Fixture::new();
|
||||
let hung = fixture.command("running", "printf R\nwhile :; do :; done");
|
||||
let mut command = Command::new(hung);
|
||||
command
|
||||
.process_group(0)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let mut child = command.spawn().unwrap();
|
||||
let pid = child.id() as i32;
|
||||
let mut ready = [0];
|
||||
child
|
||||
.stdout
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_exact(&mut ready)
|
||||
.unwrap();
|
||||
assert_eq!(ready, [b'R']);
|
||||
drop(ClipboardProcess(Some(child)));
|
||||
let mut status = 0;
|
||||
// SAFETY: waitpid's output pointer is valid; WNOHANG cannot block this check.
|
||||
assert_eq!(unsafe { waitpid(pid, &mut status, 1) }, -1);
|
||||
assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_injected_timeout_terminates_nonterminating_commands() {
|
||||
let fixture = Fixture::new();
|
||||
let hung = fixture.command("hung", "while :; do :; done");
|
||||
let mut clipboard = SystemClipboard::with_commands(hung.clone(), hung);
|
||||
// No assertion depends on wall-clock speed or a deadline remaining in the future.
|
||||
clipboard.timeout = Duration::ZERO;
|
||||
assert_eq!(
|
||||
clipboard.read().unwrap_err(),
|
||||
"System clipboard command timed out"
|
||||
);
|
||||
assert_eq!(
|
||||
clipboard.write("text").unwrap_err(),
|
||||
"System clipboard command timed out"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use super::*;
|
||||
unsafe extern "C" {
|
||||
fn PasteboardSynchronize(pasteboard: Object) -> u32;
|
||||
fn PasteboardGetItemIdentifier(pasteboard: Object, index: isize, item: *mut usize) -> i32;
|
||||
fn PasteboardCopyItemFlavorData(
|
||||
pasteboard: Object,
|
||||
item: usize,
|
||||
flavor: Object,
|
||||
data: *mut Object,
|
||||
) -> i32;
|
||||
fn CFDataGetBytePtr(data: Object) -> *const u8;
|
||||
fn CFDataGetLength(data: Object) -> isize;
|
||||
}
|
||||
#[test]
|
||||
fn native_publication_preserves_plain_utf8_bytes_on_an_isolated_pasteboard() {
|
||||
// A private pasteboard leaves the user's clipboard untouched.
|
||||
let _pool = unsafe { AutoreleasePool(objc_autoreleasePoolPush()) };
|
||||
let name = unsafe {
|
||||
Owned::new(CFStringCreateWithCString(
|
||||
ptr::null(),
|
||||
c"vamp-native-clipboard-regression".as_ptr(),
|
||||
0x0800_0100,
|
||||
))
|
||||
.unwrap()
|
||||
};
|
||||
let board = unsafe {
|
||||
let mut board = ptr::null();
|
||||
check(PasteboardCreate(name.0, &mut board)).unwrap();
|
||||
Owned::new(board).unwrap()
|
||||
};
|
||||
let reader = unsafe {
|
||||
let send: unsafe extern "C" fn(Object, Object, Object) -> Object =
|
||||
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
|
||||
send(
|
||||
objc_getClass(c"NSPasteboard".as_ptr()),
|
||||
sel_registerName(c"pasteboardWithName:".as_ptr()),
|
||||
name.0,
|
||||
)
|
||||
};
|
||||
for text in [
|
||||
"",
|
||||
"é e\u{301} 👨💻\n\0tail",
|
||||
"{\\rtf1 plain text}",
|
||||
"%!PS-Adobe-3.0\nplain",
|
||||
] {
|
||||
write_to(name.0, text).unwrap();
|
||||
assert_eq!(read_from(reader).unwrap(), text);
|
||||
unsafe {
|
||||
PasteboardSynchronize(board.0);
|
||||
let mut item = 0;
|
||||
check(PasteboardGetItemIdentifier(board.0, 1, &mut item)).unwrap();
|
||||
let flavor = Owned::new(CFStringCreateWithCString(
|
||||
ptr::null(),
|
||||
c"public.utf8-plain-text".as_ptr(),
|
||||
0x0800_0100,
|
||||
))
|
||||
.unwrap();
|
||||
let mut data = ptr::null();
|
||||
check(PasteboardCopyItemFlavorData(
|
||||
board.0, item, flavor.0, &mut data,
|
||||
))
|
||||
.unwrap();
|
||||
let data = Owned::new(data).unwrap();
|
||||
let length = CFDataGetLength(data.0) as usize;
|
||||
let bytes = if length == 0 {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(CFDataGetBytePtr(data.0), length)
|
||||
};
|
||||
assert_eq!(bytes, text.as_bytes());
|
||||
}
|
||||
}
|
||||
let maximum = "x".repeat(super::super::MAX_CLIPBOARD_BYTES);
|
||||
write_to(name.0, &maximum).unwrap();
|
||||
assert_eq!(read_from(reader).unwrap(), maximum);
|
||||
write_to(name.0, &(maximum + "x")).unwrap();
|
||||
assert_eq!(
|
||||
read_from(reader).unwrap_err(),
|
||||
"System clipboard text exceeds 4 MiB"
|
||||
);
|
||||
}
|
||||
+3853
File diff suppressed because it is too large
Load Diff
+16442
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,982 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn virtual_catalog_compacts_and_retains_file_directory_collisions() {
|
||||
let mut picker = FilePicker::from_paths(
|
||||
PathBuf::new(),
|
||||
["x", "x/y", "src/deep/deleted.rs", "src/deep/deleted.rs"]
|
||||
.map(PathBuf::from)
|
||||
.into_iter()
|
||||
.enumerate(),
|
||||
);
|
||||
assert_eq!(
|
||||
picker
|
||||
.entries()
|
||||
.map(|row| row.label.to_owned())
|
||||
.collect::<Vec<_>>(),
|
||||
["src/deep", "x", "x"]
|
||||
);
|
||||
picker.reveal_path(Path::new("x"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().is_dir);
|
||||
assert_eq!(picker.accept(), Some(PathBuf::from("x")));
|
||||
picker.reveal_path(Path::new("x/y"));
|
||||
assert_eq!(picker.accept(), Some(PathBuf::from("x/y")));
|
||||
picker.reveal_path(Path::new("src/deep/deleted.rs"));
|
||||
assert_eq!(picker.accept(), Some(PathBuf::from("src/deep/deleted.rs")));
|
||||
assert_eq!(picker.entries().filter(|row| !row.is_dir).count(), 3);
|
||||
let expected_index = |row: &FileRow<'_>| {
|
||||
if row.is_dir {
|
||||
None
|
||||
} else {
|
||||
Some(match row.path.to_str().unwrap() {
|
||||
"x" => 0,
|
||||
"x/y" => 1,
|
||||
"src/deep/deleted.rs" => 2,
|
||||
path => panic!("unexpected path {path}"),
|
||||
})
|
||||
}
|
||||
};
|
||||
for view in [FileView::List, FileView::Tree] {
|
||||
picker.set_view(view);
|
||||
for query in ["", "x", "deleted"] {
|
||||
picker.query = query.into();
|
||||
picker.refilter();
|
||||
let rows: Vec<_> = picker.entries().collect();
|
||||
assert!(!rows.is_empty());
|
||||
for row in rows {
|
||||
assert_eq!(row.catalog_index, expected_index(&row));
|
||||
assert!(row.status.is_none() && row.old_path.is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static TEMP_ID: AtomicU64 = AtomicU64::new(0);
|
||||
struct Directory(PathBuf);
|
||||
impl Directory {
|
||||
fn new() -> Self {
|
||||
let id = TEMP_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("vamp-files-test-{}-{id}", std::process::id()));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn put(&self, name: &str, text: &str) {
|
||||
let path = self.0.join(name);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
fn scan(&self) -> FilePicker {
|
||||
FilePicker::scan(self.0.clone(), FilePresentation::Floating, FileView::List).unwrap()
|
||||
}
|
||||
}
|
||||
impl Drop for Directory {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
fn paths(picker: &FilePicker) -> Vec<PathBuf> {
|
||||
picker
|
||||
.entries()
|
||||
.map(|entry| entry.path.to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fuzzy_path_tokens_preserve_tree_context_selection_and_open_paths() {
|
||||
let directory = Directory::new();
|
||||
let names = [
|
||||
"src/fuzzy_parser.rs",
|
||||
"src/über_parser.rs",
|
||||
"src/other.rs",
|
||||
"tests/fuzzy_parser.rs",
|
||||
];
|
||||
for name in names {
|
||||
directory.put(name, "");
|
||||
}
|
||||
for mut picker in [
|
||||
directory.scan(),
|
||||
FilePicker::from_paths(
|
||||
directory.0.clone(),
|
||||
names.map(PathBuf::from).into_iter().enumerate(),
|
||||
),
|
||||
] {
|
||||
for view in [FileView::Tree, FileView::List] {
|
||||
picker.set_view(view);
|
||||
for (query, expected) in [
|
||||
("sr/fp RS", "src/fuzzy_parser.rs"),
|
||||
("ÜPR SRC", "src/über_parser.rs"),
|
||||
] {
|
||||
picker.query = query.into();
|
||||
picker.refilter();
|
||||
assert_eq!(
|
||||
picker
|
||||
.entries()
|
||||
.filter(|row| !row.is_dir)
|
||||
.map(|row| row.path)
|
||||
.collect::<Vec<_>>(),
|
||||
[Path::new(expected)]
|
||||
);
|
||||
assert_eq!(selected_path(&picker), Path::new(expected));
|
||||
assert_eq!(picker.accept(), Some(directory.0.join(expected)));
|
||||
if view == FileView::Tree {
|
||||
assert_eq!(paths(&picker), [Path::new("src"), Path::new(expected)]);
|
||||
}
|
||||
}
|
||||
picker.query = "rs/ü".into();
|
||||
picker.refilter();
|
||||
assert!(picker.entries().next().is_none());
|
||||
picker.clear_filter();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/über_parser.rs"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanned_files_and_directories_have_no_catalog_index() {
|
||||
let directory = Directory::new();
|
||||
directory.put("nested/file.txt", "");
|
||||
let mut picker = directory.scan();
|
||||
for view in [FileView::List, FileView::Tree] {
|
||||
picker.set_view(view);
|
||||
picker.reveal_path(Path::new("nested/file.txt"));
|
||||
assert!(picker.entries().all(|row| row.catalog_index.is_none()));
|
||||
assert!(
|
||||
picker
|
||||
.entries()
|
||||
.all(|row| row.status.is_none() && row.old_path.is_none())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn repository_change(path: &str, status: FileStatus, old_path: Option<&str>) -> WorkingFileChange {
|
||||
WorkingFileChange {
|
||||
path: path.into(),
|
||||
status,
|
||||
old_path: old_path.map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_metadata_keeps_clean_files_selection_and_filtered_views() {
|
||||
let directory = Directory::new();
|
||||
for name in ["src/clean.rs", "src/modified.rs", "added.rs", "renamed.rs"] {
|
||||
directory.put(name, "");
|
||||
}
|
||||
let mut picker = directory.scan();
|
||||
picker.presentation = FilePresentation::Docked;
|
||||
picker.set_view(FileView::Tree);
|
||||
picker.reveal_path(Path::new("src/clean.rs"));
|
||||
picker.query = "src".into();
|
||||
picker.refilter();
|
||||
picker.focused = false;
|
||||
let changes = vec![
|
||||
repository_change("src/modified.rs", FileStatus::Modified, None),
|
||||
repository_change("added.rs", FileStatus::Added, None),
|
||||
repository_change("renamed.rs", FileStatus::Renamed, Some("old.rs")),
|
||||
repository_change("vanished/deep/deleted.rs", FileStatus::Removed, None),
|
||||
];
|
||||
assert!(picker.set_repository_changes(changes.clone()));
|
||||
assert!(!picker.set_repository_changes(changes));
|
||||
assert_eq!(selected_path(&picker), Path::new("src/clean.rs"));
|
||||
assert_eq!(picker.query, "src");
|
||||
assert!(!picker.focused);
|
||||
assert_eq!(picker.presentation, FilePresentation::Docked);
|
||||
for view in [FileView::List, FileView::Tree] {
|
||||
picker.set_view(view);
|
||||
for query in ["", "src", "modified.rs", "deleted.rs"] {
|
||||
picker.query = query.into();
|
||||
picker.refilter();
|
||||
let rows: Vec<_> = picker.entries().collect();
|
||||
assert!(!rows.is_empty());
|
||||
for row in rows {
|
||||
assert!(row.catalog_index.is_none());
|
||||
if row.is_dir || row.path == Path::new("src/clean.rs") {
|
||||
assert!(row.status.is_none() && row.old_path.is_none());
|
||||
} else {
|
||||
let status = match row.path.to_str().unwrap() {
|
||||
"src/modified.rs" => FileStatus::Modified,
|
||||
"added.rs" => FileStatus::Added,
|
||||
"renamed.rs" => FileStatus::Renamed,
|
||||
"vanished/deep/deleted.rs" => FileStatus::Removed,
|
||||
other => panic!("unexpected {other}"),
|
||||
};
|
||||
assert_eq!(row.status, Some(status));
|
||||
assert_eq!(
|
||||
row.old_path,
|
||||
(status == FileStatus::Renamed).then(|| Path::new("old.rs"))
|
||||
);
|
||||
}
|
||||
}
|
||||
if query.is_empty() || query == "src" {
|
||||
assert!(
|
||||
picker
|
||||
.entries()
|
||||
.any(|row| row.path == Path::new("src/clean.rs"))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
picker.set_view(FileView::List);
|
||||
picker.clear_filter();
|
||||
picker.reveal_path(Path::new("src/clean.rs"));
|
||||
assert!(picker.set_repository_changes(Vec::new()));
|
||||
assert_eq!(selected_path(&picker), Path::new("src/clean.rs"));
|
||||
assert_eq!(picker.entries().len(), 4);
|
||||
assert!(picker.nodes.iter().all(|node| !node.virtual_entry));
|
||||
assert!(
|
||||
picker
|
||||
.entries()
|
||||
.all(|row| row.status.is_none() && row.old_path.is_none())
|
||||
);
|
||||
assert!(!picker.set_repository_changes(Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_catalog_leaves_survive_refresh_and_restored_files_survive_clear() {
|
||||
let directory = Directory::new();
|
||||
directory.put("keep.txt", "");
|
||||
let mut picker = directory.scan();
|
||||
let deleted = Path::new("lost/deep/deleted.txt");
|
||||
picker.set_repository_changes(vec![repository_change(
|
||||
"lost/deep/deleted.txt",
|
||||
FileStatus::Removed,
|
||||
None,
|
||||
)]);
|
||||
picker.set_view(FileView::Tree);
|
||||
assert_eq!(
|
||||
picker.entries().find(|row| row.is_dir).unwrap().label,
|
||||
"lost/deep"
|
||||
);
|
||||
picker.reveal_path(deleted);
|
||||
picker.query = "deleted".into();
|
||||
picker.refilter();
|
||||
picker.start_search();
|
||||
picker.focused = false;
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), deleted);
|
||||
assert!(picker.searching && !picker.focused);
|
||||
assert_eq!(picker.query, "deleted");
|
||||
assert_eq!(picker.accept(), Some(directory.0.join(deleted)));
|
||||
assert!(!directory.0.join(deleted).exists());
|
||||
assert_eq!(
|
||||
picker.entries().find(|row| !row.is_dir).unwrap().status,
|
||||
Some(FileStatus::Removed)
|
||||
);
|
||||
directory.put("lost/deep/deleted.txt", "restored");
|
||||
assert!(picker.set_repository_changes(vec![repository_change(
|
||||
"lost/deep/deleted.txt",
|
||||
FileStatus::Removed,
|
||||
None,
|
||||
)]));
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), deleted);
|
||||
assert!(picker.nodes.iter().all(|node| !node.virtual_entry));
|
||||
assert!(picker.set_repository_changes(Vec::new()));
|
||||
assert_eq!(selected_path(&picker), deleted);
|
||||
assert_eq!(picker.accept(), Some(directory.0.join(deleted)));
|
||||
assert_eq!(
|
||||
fs::read_to_string(directory.0.join(deleted)).unwrap(),
|
||||
"restored"
|
||||
);
|
||||
assert!(picker.entries().all(|row| row.status.is_none()));
|
||||
fs::remove_dir_all(directory.0.join("lost")).unwrap();
|
||||
picker.refresh();
|
||||
picker.set_repository_changes(vec![repository_change(
|
||||
"lost/deep/deleted.txt",
|
||||
FileStatus::Removed,
|
||||
None,
|
||||
)]);
|
||||
picker.reveal_path(deleted);
|
||||
picker.set_repository_changes(Vec::new());
|
||||
assert!(picker.entries().len() == 0);
|
||||
picker.clear_filter();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("keep.txt")]);
|
||||
assert!(picker.nodes.iter().all(|node| !node.virtual_entry));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_metadata_cannot_introduce_unsafe_or_existing_excluded_paths() {
|
||||
let directory = Directory::new();
|
||||
directory.put(".gitignore", "ignored/\n");
|
||||
directory.put("ignored/hidden.txt", "");
|
||||
directory.put("directory/keep.txt", "");
|
||||
let mut picker = directory.scan();
|
||||
let mut changes: Vec<_> = [
|
||||
"",
|
||||
".",
|
||||
"../outside.txt",
|
||||
"directory/../../outside.txt",
|
||||
".git/secret",
|
||||
"nested/.jj/secret",
|
||||
"/outside.txt",
|
||||
"directory",
|
||||
"ignored/hidden.txt",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|path| repository_change(path, FileStatus::Removed, None))
|
||||
.collect();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&directory.0, directory.0.join("link")).unwrap();
|
||||
changes.push(repository_change(
|
||||
"link/missing.txt",
|
||||
FileStatus::Removed,
|
||||
None,
|
||||
));
|
||||
}
|
||||
changes.push(repository_change("missing.txt", FileStatus::Removed, None));
|
||||
picker.set_repository_changes(changes);
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
[".gitignore", "directory/keep.txt", "missing.txt"].map(PathBuf::from)
|
||||
);
|
||||
assert_eq!(
|
||||
picker.entries().filter(|row| row.status.is_some()).count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
picker.entries().last().unwrap().status,
|
||||
Some(FileStatus::Removed)
|
||||
);
|
||||
assert!(!directory.0.join("missing.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_ignore_negation_hidden_files_and_vcs_metadata() {
|
||||
let directory = Directory::new();
|
||||
directory.put(".gitignore", "*.log\nignored/\n");
|
||||
directory.put("nested/.gitignore", "!keep.log\nlocal.txt\n");
|
||||
for name in [
|
||||
"gone.log",
|
||||
"nested/gone.log",
|
||||
"nested/keep.log",
|
||||
"nested/local.txt",
|
||||
"nested/ok.txt",
|
||||
"ignored/hidden.txt",
|
||||
".hidden",
|
||||
".git/objects/secret",
|
||||
"nested/.git/secret",
|
||||
".jj/secret",
|
||||
"nested/.jj/secret",
|
||||
] {
|
||||
directory.put(name, "text");
|
||||
}
|
||||
let picker = directory.scan();
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
[
|
||||
".gitignore",
|
||||
".hidden",
|
||||
"nested/.gitignore",
|
||||
"nested/keep.log",
|
||||
"nested/ok.txt"
|
||||
]
|
||||
.map(PathBuf::from)
|
||||
);
|
||||
assert!(picker.error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_unicode_tokens_grapheme_deletion_and_navigation() {
|
||||
let directory = Directory::new();
|
||||
for name in ["a space 界[e\u{301}].txt", "b.txt", "c.txt"] {
|
||||
directory.put(name, "text");
|
||||
}
|
||||
let mut picker = directory.scan();
|
||||
picker.navigate(false);
|
||||
assert_eq!(picker.selected, 2);
|
||||
picker.navigate(true);
|
||||
assert_eq!(picker.selected, 0);
|
||||
picker.query = "界 SPACE [E\u{301}]".into();
|
||||
picker.refilter();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("a space 界[e\u{301}].txt")]);
|
||||
picker.query = "e\u{301}👩💻".into();
|
||||
assert!(picker.handle_filter_input(&crate::editor::Input::Backspace));
|
||||
assert_eq!(picker.query, "e\u{301}");
|
||||
assert!(picker.handle_filter_input(&crate::editor::Input::Backspace));
|
||||
assert_eq!(picker.query, "");
|
||||
assert!(picker.handle_filter_input(&crate::editor::Input::Backspace));
|
||||
assert_eq!(picker.entries().len(), 3);
|
||||
picker.query = "no match".into();
|
||||
picker.refilter();
|
||||
for forward in [true, false] {
|
||||
picker.navigate(forward);
|
||||
assert_eq!(picker.selected, 0);
|
||||
assert_eq!(picker.entries().len(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_and_line_deletion_refilter_only_editable_queries() {
|
||||
use crate::editor::Input;
|
||||
|
||||
for view in [FileView::List, FileView::Tree] {
|
||||
let mut picker = FilePicker::from_paths(
|
||||
PathBuf::new(),
|
||||
["alpha one.txt", "alpha two.txt", "beta.txt"]
|
||||
.map(PathBuf::from)
|
||||
.into_iter()
|
||||
.enumerate(),
|
||||
);
|
||||
picker.set_view(view);
|
||||
picker.query = "alpha missing".into();
|
||||
picker.refilter();
|
||||
assert_eq!(picker.entries().len(), 0);
|
||||
if view == FileView::Tree {
|
||||
for input in [Input::Backspace, Input::AltBackspace, Input::SuperBackspace] {
|
||||
assert!(!picker.handle_filter_input(&input));
|
||||
assert_eq!(picker.query, "alpha missing");
|
||||
}
|
||||
picker.start_search();
|
||||
}
|
||||
assert!(picker.handle_filter_input(&Input::AltBackspace));
|
||||
assert_eq!(picker.query, "alpha ");
|
||||
assert_eq!(picker.entries().len(), 2);
|
||||
assert!(picker.handle_filter_input(&Input::SuperBackspace));
|
||||
assert_eq!(picker.query, "");
|
||||
assert_eq!(picker.entries().len(), 3);
|
||||
for input in [Input::Backspace, Input::AltBackspace, Input::SuperBackspace] {
|
||||
assert!(picker.handle_filter_input(&input));
|
||||
assert_eq!(picker.entries().len(), 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_scan_refresh_and_failure_preserve_reachable_state() {
|
||||
let directory = Directory::new();
|
||||
let mut picker = directory.scan();
|
||||
picker.navigate(false);
|
||||
assert!(picker.handle_filter_input(&crate::editor::Input::Backspace));
|
||||
assert_eq!(picker.entries().len(), 0);
|
||||
directory.put("new.txt", "text");
|
||||
picker.query = "new".into();
|
||||
picker.refresh();
|
||||
assert_eq!(picker.query, "new");
|
||||
assert_eq!(paths(&picker), [PathBuf::from("new.txt")]);
|
||||
fs::remove_dir_all(&directory.0).unwrap();
|
||||
picker.refresh();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("new.txt")]);
|
||||
assert!(picker.error.as_ref().unwrap().contains("Refresh failed"));
|
||||
assert!(
|
||||
FilePicker::scan(
|
||||
directory.0.clone(),
|
||||
FilePresentation::Docked,
|
||||
FileView::Tree
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_ignore_warning_survives_query_and_navigation() {
|
||||
let directory = Directory::new();
|
||||
directory.put(".gitignore", "[z-a]\n");
|
||||
directory.put("ok.txt", "text");
|
||||
let mut picker = directory.scan();
|
||||
assert!(picker.error.as_ref().unwrap().contains("Incomplete scan"));
|
||||
picker.query = "ok".into();
|
||||
picker.refilter();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("ok.txt")]);
|
||||
picker.navigate(true);
|
||||
assert!(picker.error.as_ref().unwrap().contains("Incomplete scan"));
|
||||
directory.put(".gitignore", "");
|
||||
picker.refresh();
|
||||
assert!(picker.error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_project_ignore_rules_apply_and_non_directory_roots_fail() {
|
||||
let directory = Directory::new();
|
||||
directory.put(".gitignore", "*.txt\n");
|
||||
directory.put("project/visible.txt", "text");
|
||||
let root = directory.0.join("project");
|
||||
let picker = FilePicker::scan(root, FilePresentation::Floating, FileView::List).unwrap();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("visible.txt")]);
|
||||
assert!(
|
||||
FilePicker::scan(
|
||||
directory.0.join("project/visible.txt"),
|
||||
FilePresentation::Docked,
|
||||
FileView::Tree,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_loops_and_file_links_are_not_followed_and_raw_paths_survive() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let directory = Directory::new();
|
||||
directory.put("real.txt", "text");
|
||||
symlink(&directory.0, directory.0.join("loop")).unwrap();
|
||||
symlink(directory.0.join("real.txt"), directory.0.join("alias.txt")).unwrap();
|
||||
let raw = PathBuf::from("raw界\n.txt");
|
||||
fs::write(directory.0.join(&raw), "text").unwrap();
|
||||
let picker = directory.scan();
|
||||
assert_eq!(picker.entries().len(), 2);
|
||||
let entry = picker
|
||||
.entries()
|
||||
.find(|entry| entry.path == raw.as_path())
|
||||
.unwrap();
|
||||
assert!(!entry.label.chars().any(char::is_control));
|
||||
assert_eq!(
|
||||
fs::read_to_string(directory.0.join(entry.path)).unwrap(),
|
||||
"text"
|
||||
);
|
||||
}
|
||||
|
||||
fn tree(directory: &Directory) -> FilePicker {
|
||||
FilePicker::scan(
|
||||
directory.0.clone(),
|
||||
FilePresentation::Docked,
|
||||
FileView::Tree,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn select(picker: &mut FilePicker, path: &str) {
|
||||
let selected = picker
|
||||
.entries()
|
||||
.position(|row| row.path == Path::new(path))
|
||||
.unwrap();
|
||||
picker.selected = selected;
|
||||
}
|
||||
|
||||
fn selected_path(picker: &FilePicker) -> &Path {
|
||||
picker.entries().nth(picker.selected).unwrap().path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_orders_folders_first_keeps_empty_dirs_and_compacts_only_directory_chains() {
|
||||
let directory = Directory::new();
|
||||
directory.put("a.txt", "");
|
||||
directory.put("folder/only.txt", "");
|
||||
directory.put("chain/one/two/a.txt", "");
|
||||
directory.put("chain/one/two/z.txt", "");
|
||||
fs::create_dir(directory.0.join("empty")).unwrap();
|
||||
let mut picker = tree(&directory);
|
||||
assert_eq!(picker.view, FileView::Tree);
|
||||
assert!(!picker.searching);
|
||||
assert_eq!(
|
||||
picker
|
||||
.entries()
|
||||
.map(|row| (row.label, row.is_dir, row.depth))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
("chain/one/two", true, 0),
|
||||
("empty", true, 0),
|
||||
("folder", true, 0),
|
||||
("a.txt", false, 0)
|
||||
]
|
||||
);
|
||||
assert_eq!(selected_path(&picker), Path::new("chain/one/two"));
|
||||
picker.right();
|
||||
assert_eq!(
|
||||
picker
|
||||
.entries()
|
||||
.map(|row| (row.label, row.depth))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
("chain/one/two", 0),
|
||||
("a.txt", 1),
|
||||
("z.txt", 1),
|
||||
("empty", 0),
|
||||
("folder", 0),
|
||||
("a.txt", 0)
|
||||
]
|
||||
);
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("chain/one/two/a.txt"));
|
||||
let rows = paths(&picker);
|
||||
picker.right();
|
||||
assert_eq!(paths(&picker), rows);
|
||||
picker.left();
|
||||
assert_eq!(selected_path(&picker), Path::new("chain/one/two"));
|
||||
picker.left();
|
||||
assert!(!picker.entries().next().unwrap().expanded);
|
||||
picker.left();
|
||||
assert_eq!(picker.selected, 0);
|
||||
select(&mut picker, "folder");
|
||||
assert!(picker.accept().is_none());
|
||||
assert_eq!(
|
||||
picker.entries().nth(picker.selected + 1).unwrap().label,
|
||||
"only.txt"
|
||||
);
|
||||
picker.right();
|
||||
assert_eq!(picker.accept(), Some(directory.0.join("folder/only.txt")));
|
||||
select(&mut picker, "empty");
|
||||
picker.right();
|
||||
assert!(picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_search_reveals_ancestors_without_mutating_saved_expansion_or_compaction() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/module/deep/needle.txt", "");
|
||||
directory.put("src/module/sibling.txt", "");
|
||||
directory.put("src/root.txt", "");
|
||||
directory.put("other/keep.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
select(&mut picker, "other");
|
||||
picker.right();
|
||||
select(&mut picker, "src");
|
||||
let expanded = picker.expanded.clone();
|
||||
picker.start_search();
|
||||
picker.query = "NEEDLE".into();
|
||||
picker.refilter();
|
||||
assert_eq!(
|
||||
picker
|
||||
.entries()
|
||||
.map(|row| (row.label, row.depth))
|
||||
.collect::<Vec<_>>(),
|
||||
[("src", 0), ("module", 1), ("deep", 2), ("needle.txt", 3)]
|
||||
);
|
||||
assert_eq!(
|
||||
selected_path(&picker),
|
||||
Path::new("src/module/deep/needle.txt")
|
||||
);
|
||||
assert_eq!(picker.expanded, expanded);
|
||||
picker.left();
|
||||
let filtered = paths(&picker);
|
||||
picker.finish_search();
|
||||
assert_eq!(picker.query, "NEEDLE");
|
||||
assert_eq!(paths(&picker), filtered);
|
||||
assert_eq!(selected_path(&picker), Path::new("src/module/deep"));
|
||||
assert_eq!(picker.expanded, expanded);
|
||||
picker.start_search();
|
||||
picker.query = "deep".into();
|
||||
picker.refilter();
|
||||
select(&mut picker, "src/module/deep");
|
||||
assert!(picker.accept().is_none());
|
||||
assert!(!picker.searching);
|
||||
assert_eq!(picker.query, "deep");
|
||||
assert_eq!(selected_path(&picker), Path::new("src/module/deep"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
assert_eq!(picker.expanded, expanded);
|
||||
picker.right();
|
||||
assert!(picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
assert_eq!(picker.query, "deep");
|
||||
|
||||
let chain = Directory::new();
|
||||
chain.put("one/two/three/a.txt", "");
|
||||
chain.put("one/two/three/b.txt", "");
|
||||
let mut picker = tree(&chain);
|
||||
picker.start_search();
|
||||
picker.query = "a.txt".into();
|
||||
picker.refilter();
|
||||
assert_eq!(
|
||||
picker.entries().map(|row| row.label).collect::<Vec<_>>(),
|
||||
["one/two/three", "a.txt"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_switches_restore_directory_choices_and_reveal_explicit_file_choices() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/a.txt", "");
|
||||
directory.put("src/b.txt", "");
|
||||
directory.put("z.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
picker.right();
|
||||
let open = paths(&picker);
|
||||
picker.set_view(FileView::List);
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
["src/a.txt", "src/b.txt", "z.txt"].map(PathBuf::from)
|
||||
);
|
||||
picker.set_view(FileView::Tree);
|
||||
assert_eq!(selected_path(&picker), Path::new("src"));
|
||||
assert_eq!(paths(&picker), open);
|
||||
picker.left();
|
||||
picker.toggle_view();
|
||||
picker.navigate(true);
|
||||
assert_eq!(selected_path(&picker), Path::new("src/b.txt"));
|
||||
picker.toggle_view();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/b.txt"));
|
||||
assert!(picker.entries().next().unwrap().expanded);
|
||||
picker.left();
|
||||
picker.toggle_view();
|
||||
picker.toggle_view();
|
||||
assert_eq!(selected_path(&picker), Path::new("src"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_and_refresh_preserve_raw_selection_and_surviving_expansion() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/a.txt", "");
|
||||
directory.put("src/b.txt", "");
|
||||
directory.put("z.txt", "");
|
||||
let mut picker = directory.scan();
|
||||
select(&mut picker, "src/b.txt");
|
||||
picker.query = "absent".into();
|
||||
picker.refilter();
|
||||
assert_eq!(picker.entries().len(), 0);
|
||||
picker.query.clear();
|
||||
picker.refilter();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/b.txt"));
|
||||
picker.set_view(FileView::Tree);
|
||||
assert_eq!(selected_path(&picker), Path::new("src/b.txt"));
|
||||
fs::remove_file(directory.0.join("src/b.txt")).unwrap();
|
||||
directory.put("src/c.txt", "");
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("src"));
|
||||
assert!(picker.entries().next().unwrap().expanded);
|
||||
assert!(paths(&picker).contains(&PathBuf::from("src/c.txt")));
|
||||
fs::remove_dir_all(directory.0.join("src")).unwrap();
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("z.txt"));
|
||||
assert!(picker.expanded.is_empty());
|
||||
picker.toggle_view();
|
||||
picker.toggle_view();
|
||||
assert_eq!(selected_path(&picker), Path::new("z.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_search_subfocus_and_expansion_survive_view_toggles_and_refresh() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/deep/a.txt", "");
|
||||
directory.put("src/other.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
picker.start_search();
|
||||
assert!(picker.searching);
|
||||
assert_eq!(picker.entries().len(), 4);
|
||||
assert!(picker.expanded.is_empty());
|
||||
picker.toggle_view();
|
||||
assert_eq!(picker.view, FileView::List);
|
||||
picker.toggle_view();
|
||||
assert!(picker.searching);
|
||||
assert!(picker.expanded.is_empty());
|
||||
picker.query = "a.txt".into();
|
||||
picker.refilter();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/a.txt"));
|
||||
picker.refresh();
|
||||
assert!(picker.searching);
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/a.txt"));
|
||||
let filtered = paths(&picker);
|
||||
picker.finish_search();
|
||||
assert!(!picker.searching);
|
||||
assert_eq!(picker.query, "a.txt");
|
||||
assert_eq!(paths(&picker), filtered);
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/a.txt"));
|
||||
assert!(picker.expanded.is_empty());
|
||||
picker.toggle_view();
|
||||
picker.refresh();
|
||||
picker.toggle_view();
|
||||
assert!(!picker.searching);
|
||||
assert_eq!(picker.query, "a.txt");
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/a.txt"));
|
||||
picker.start_search();
|
||||
assert!(picker.searching);
|
||||
assert_eq!(picker.query, "a.txt");
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/a.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_filter_preserves_mode_focus_current_path_and_empty_result_fallback() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/deep/needle.txt", "");
|
||||
directory.put("src/other.txt", "");
|
||||
directory.put("other/keep.txt", "");
|
||||
for (view, searching) in [
|
||||
(FileView::Tree, false),
|
||||
(FileView::Tree, true),
|
||||
(FileView::List, false),
|
||||
] {
|
||||
let mut picker = tree(&directory);
|
||||
select(&mut picker, "other");
|
||||
picker.right();
|
||||
let expanded = picker.expanded.clone();
|
||||
picker.set_view(view);
|
||||
if view == FileView::Tree {
|
||||
picker.start_search();
|
||||
}
|
||||
picker.query = "needle".into();
|
||||
picker.refilter();
|
||||
if !searching && view == FileView::Tree {
|
||||
picker.finish_search();
|
||||
}
|
||||
let expected = Path::new("src/deep/needle.txt");
|
||||
assert_eq!(selected_path(&picker), expected);
|
||||
picker.clear_filter();
|
||||
assert!(picker.query.is_empty());
|
||||
assert_eq!(picker.searching, searching);
|
||||
assert!(picker.focused);
|
||||
assert_eq!(selected_path(&picker), expected);
|
||||
assert!(picker.expanded.is_superset(&expanded));
|
||||
assert!(paths(&picker).contains(&PathBuf::from("other/keep.txt")));
|
||||
let rows = paths(&picker);
|
||||
let expanded = picker.expanded.clone();
|
||||
picker.clear_filter();
|
||||
assert_eq!(paths(&picker), rows);
|
||||
assert_eq!(picker.expanded, expanded);
|
||||
assert_eq!(selected_path(&picker), expected);
|
||||
assert_eq!(picker.searching, searching);
|
||||
|
||||
picker.query = "absent".into();
|
||||
picker.refilter();
|
||||
picker.navigate(true);
|
||||
picker.navigate(false);
|
||||
assert!(picker.rows.is_empty());
|
||||
picker.refresh();
|
||||
assert!(picker.rows.is_empty());
|
||||
picker.clear_filter();
|
||||
assert_eq!(selected_path(&picker), expected);
|
||||
assert_eq!(picker.searching, searching);
|
||||
assert!(picker.focused);
|
||||
}
|
||||
|
||||
let empty = Directory::new();
|
||||
let mut picker = tree(&empty);
|
||||
picker.start_search();
|
||||
picker.query = "absent".into();
|
||||
picker.refilter();
|
||||
picker.finish_search();
|
||||
picker.clear_filter();
|
||||
assert!(picker.rows.is_empty());
|
||||
assert_eq!(picker.selected, 0);
|
||||
assert!(!picker.searching);
|
||||
assert!(picker.focused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_navigation_toggles_context_folders_and_query_edits_reveal_matches() {
|
||||
let directory = Directory::new();
|
||||
directory.put("src/deep/needle.txt", "");
|
||||
directory.put("src/other.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
picker.start_search();
|
||||
picker.query = "needle".into();
|
||||
picker.refilter();
|
||||
let expanded = picker.expanded.clone();
|
||||
picker.left();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep"));
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/needle.txt"));
|
||||
assert_eq!(picker.expanded, expanded);
|
||||
picker.finish_search();
|
||||
picker.left();
|
||||
picker.left();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
assert_eq!(picker.query, "needle");
|
||||
assert!(!paths(&picker).contains(&PathBuf::from("src/deep/needle.txt")));
|
||||
picker.start_search();
|
||||
picker.finish_search();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.right();
|
||||
assert!(picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/needle.txt"));
|
||||
picker.left();
|
||||
assert!(picker.accept().is_none());
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
assert!(picker.accept().is_none());
|
||||
assert!(picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.start_search();
|
||||
assert!(picker.accept().is_none());
|
||||
assert!(!picker.searching);
|
||||
assert_eq!(picker.query, "needle");
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.start_search();
|
||||
picker.query.push_str(".txt");
|
||||
picker.refilter();
|
||||
assert!(picker.filter_collapsed.is_empty());
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/needle.txt"));
|
||||
picker.query.clear();
|
||||
picker.refilter();
|
||||
picker.finish_search();
|
||||
assert_eq!(selected_path(&picker), Path::new("src/deep/needle.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_collapse_survives_refresh_compaction_and_view_switching_by_raw_path() {
|
||||
let directory = Directory::new();
|
||||
directory.put("one/a.txt", "");
|
||||
directory.put("one/two/needle.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
picker.start_search();
|
||||
picker.query = "needle".into();
|
||||
picker.refilter();
|
||||
picker.finish_search();
|
||||
picker.left();
|
||||
picker.left();
|
||||
picker.left();
|
||||
picker.left();
|
||||
assert_eq!(selected_path(&picker), Path::new("one"));
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one")]);
|
||||
picker.toggle_view();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two/needle.txt"));
|
||||
picker.toggle_view();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one")]);
|
||||
assert!(!picker.searching);
|
||||
fs::remove_file(directory.0.join("one/a.txt")).unwrap();
|
||||
picker.focused = false;
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two"));
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one/two")]);
|
||||
assert!(!picker.searching && !picker.focused);
|
||||
assert_eq!(picker.query, "needle");
|
||||
directory.put("one/a.txt", "");
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("one"));
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one")]);
|
||||
picker.right();
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two"));
|
||||
assert!(!picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.right();
|
||||
assert!(picker.entries().nth(picker.selected).unwrap().expanded);
|
||||
picker.right();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two/needle.txt"));
|
||||
fs::remove_file(directory.0.join("one/two/needle.txt")).unwrap();
|
||||
picker.refresh();
|
||||
assert!(picker.entries().len() == 0);
|
||||
picker.clear_filter();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two"));
|
||||
assert!(!picker.searching && !picker.focused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_preserves_expansion_when_directory_chains_merge_and_split() {
|
||||
let directory = Directory::new();
|
||||
directory.put("one/a.txt", "");
|
||||
directory.put("one/two/b.txt", "");
|
||||
let mut picker = tree(&directory);
|
||||
picker.right();
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
["one", "one/two", "one/a.txt"].map(PathBuf::from)
|
||||
);
|
||||
fs::remove_file(directory.0.join("one/a.txt")).unwrap();
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two"));
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
["one/two", "one/two/b.txt"].map(PathBuf::from)
|
||||
);
|
||||
assert!(picker.entries().next().unwrap().expanded);
|
||||
directory.put("one/a.txt", "");
|
||||
picker.refresh();
|
||||
assert_eq!(selected_path(&picker), Path::new("one/two"));
|
||||
assert_eq!(
|
||||
paths(&picker),
|
||||
["one", "one/two", "one/a.txt"].map(PathBuf::from)
|
||||
);
|
||||
assert!(picker.entries().next().unwrap().expanded);
|
||||
assert!(!picker.entries().nth(1).unwrap().expanded);
|
||||
fs::remove_file(directory.0.join("one/a.txt")).unwrap();
|
||||
picker.refresh();
|
||||
picker.left();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one/two")]);
|
||||
directory.put("one/a.txt", "");
|
||||
picker.refresh();
|
||||
assert_eq!(paths(&picker), [PathBuf::from("one")]);
|
||||
assert!(!picker.entries().next().unwrap().expanded);
|
||||
}
|
||||
+1066
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,425 @@
|
||||
use super::*;
|
||||
use std::ffi::OsString;
|
||||
|
||||
static NEXT_TEST: AtomicU64 = AtomicU64::new(0);
|
||||
struct Temporary(PathBuf);
|
||||
impl Temporary {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-gutter-test-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_TEST.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
impl Drop for Temporary {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
fn command(root: &Path, program: &str, args: &[&str]) -> String {
|
||||
let mut command = Command::new(program);
|
||||
if program == "jj" {
|
||||
command.args([
|
||||
"--config=user.name=\"Gutter Author\"",
|
||||
"--config=user.email=\"gutter@example.test\"",
|
||||
"--config=debug.commit-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
"--config=debug.operation-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
]);
|
||||
}
|
||||
let output = command
|
||||
.args(args)
|
||||
.current_dir(root)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_CONFIG_SYSTEM", "/dev/null")
|
||||
.env("GIT_AUTHOR_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().into()
|
||||
}
|
||||
fn git_fixture() -> (Temporary, PathBuf) {
|
||||
let temp = Temporary::new();
|
||||
command(&temp.0, "git", &["init", "--quiet", "--template="]);
|
||||
command(&temp.0, "git", &["config", "user.name", "Gutter Author"]);
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["config", "user.email", "gutter@example.test"],
|
||||
);
|
||||
let path = temp.0.join("-literal [file]\n\t\".txt");
|
||||
fs::write(&path, "first\nsecond\nthird\n").unwrap();
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["add", "--", path.file_name().unwrap().to_str().unwrap()],
|
||||
);
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Baseline"]);
|
||||
(temp, path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_replacements_surplus_deletions_empty_and_eof_rows() {
|
||||
use Change::*;
|
||||
for (before, after, expected) in [
|
||||
("first\nsecond\n", "first\nsecond\n", vec![None, None, None]),
|
||||
(
|
||||
"first\r\nsecond\r\n",
|
||||
"first\nsecond\n",
|
||||
vec![None, None, None],
|
||||
),
|
||||
("first\rsecond\r", "first\nsecond\n", vec![None, None, None]),
|
||||
(
|
||||
"first\r\nsecond\r\nthird\r\n",
|
||||
"first\nchanged\nthird\n",
|
||||
vec![None, Some(Modified), None, None],
|
||||
),
|
||||
(
|
||||
"first\nsecond\nthird\n",
|
||||
"first\rchanged\rthird\r",
|
||||
vec![None, Some(Modified), None, None],
|
||||
),
|
||||
("first\n", "first\nnew\n", vec![None, Some(Added), None]),
|
||||
(
|
||||
"old\n",
|
||||
"changed\nsurplus\n",
|
||||
vec![Some(Modified), Some(Added), None],
|
||||
),
|
||||
(
|
||||
"old\nextra\nlast\n",
|
||||
"changed\nlast\n",
|
||||
vec![Some(Modified), None, None],
|
||||
),
|
||||
(
|
||||
"first\nremoved\nlast\n",
|
||||
"first\nlast\n",
|
||||
vec![None, Some(Removed), None],
|
||||
),
|
||||
("first\nremoved\n", "first\n", vec![None, Some(Removed)]),
|
||||
("first\nremoved", "first", vec![Some(Modified)]),
|
||||
("first\nremoved", "first\n", vec![None, Some(Removed)]),
|
||||
("removed\n", "", vec![Some(Removed)]),
|
||||
("", "new\n", vec![Some(Added), None]),
|
||||
("", "", vec![None]),
|
||||
("same", "same\n", vec![Some(Modified), None]),
|
||||
] {
|
||||
assert_eq!(changes(before, after), expected, "{before:?} -> {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_crlf_baseline_matches_normalized_editor_rows() {
|
||||
let (temp, _) = git_fixture();
|
||||
let path = temp.0.join("crlf");
|
||||
fs::write(&path, "first\r\nsecond\r\nthird\r\n").unwrap();
|
||||
command(&temp.0, "git", &["add", "--", "crlf"]);
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["commit", "--quiet", "-m", "CRLF baseline"],
|
||||
);
|
||||
assert_eq!(
|
||||
read_file(&path, "first\nsecond\nthird\n", &|| false).unwrap(),
|
||||
vec![None, None, None, None]
|
||||
);
|
||||
assert_eq!(
|
||||
read_file(&path, "first\nchanged\nthird\n", &|| false).unwrap(),
|
||||
vec![None, Some(Change::Modified), None, None]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_head_includes_staged_disk_and_unsaved_edits_without_writes() {
|
||||
let (temp, path) = git_fixture();
|
||||
fs::write(&path, "staged\nsecond\nthird\n").unwrap();
|
||||
command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["add", "--", path.file_name().unwrap().to_str().unwrap()],
|
||||
);
|
||||
fs::write(&path, "staged\ndisk\nthird\n").unwrap();
|
||||
let index = fs::read(temp.0.join(".git/index")).unwrap();
|
||||
let head = command(&temp.0, "git", &["rev-parse", "HEAD"]);
|
||||
assert_eq!(
|
||||
read_file(&path, "staged\ndisk\nunsaved\n", &|| false).unwrap(),
|
||||
vec![
|
||||
Some(Change::Modified),
|
||||
Some(Change::Modified),
|
||||
Some(Change::Modified),
|
||||
None
|
||||
]
|
||||
);
|
||||
assert_eq!(fs::read(temp.0.join(".git/index")).unwrap(), index);
|
||||
assert_eq!(command(&temp.0, "git", &["rev-parse", "HEAD"]), head);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "staged\ndisk\nthird\n");
|
||||
fs::remove_file(&path).unwrap();
|
||||
assert_eq!(
|
||||
read_file(&path, "first\nsecond\nthird\n", &|| false).unwrap(),
|
||||
vec![None, None, None, None]
|
||||
);
|
||||
assert_eq!(
|
||||
read_file(&temp.0.join("new/named"), "unsaved\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None]
|
||||
);
|
||||
let untracked = temp.0.join("untracked");
|
||||
fs::write(&untracked, "unsaved\n").unwrap();
|
||||
assert_eq!(
|
||||
read_file(&untracked, "unsaved\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unborn_untracked_missing_ignored_metadata_binary_and_symlink_paths() {
|
||||
let temp = Temporary::new();
|
||||
let path = temp.0.join("new/named");
|
||||
assert!(read_file(&path, "unsaved\n", &|| false).unwrap().is_empty());
|
||||
command(&temp.0, "git", &["init", "--quiet", "--template="]);
|
||||
assert_eq!(
|
||||
read_file(&path, "unsaved\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None]
|
||||
);
|
||||
let disk = temp.0.join("untracked");
|
||||
fs::write(&disk, "disk\n").unwrap();
|
||||
assert_eq!(
|
||||
read_file(&disk, "unsaved\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None]
|
||||
);
|
||||
fs::write(temp.0.join(".gitignore"), "new/\nuntracked\n").unwrap();
|
||||
assert!(read_file(&path, "unsaved\n", &|| false).unwrap().is_empty());
|
||||
assert!(read_file(&disk, "unsaved\n", &|| false).unwrap().is_empty());
|
||||
assert!(
|
||||
read_file(&temp.0.join(".git/config"), "text\n", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
read_file(&disk, "binary\0text", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
std::os::unix::fs::symlink(&disk, temp.0.join("link")).unwrap();
|
||||
assert!(
|
||||
read_file(&temp.0.join("link"), "text\n", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
std::os::unix::fs::symlink(&temp.0, temp.0.join("linked")).unwrap();
|
||||
assert!(
|
||||
read_file(&temp.0.join("linked/untracked"), "text\n", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_non_utf8_filename_is_literal() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let (temp, _) = git_fixture();
|
||||
let name = OsString::from_vec(b"non-utf8-\xff".to_vec());
|
||||
let path = temp.0.join(&name);
|
||||
match fs::write(&path, "old\n") {
|
||||
Ok(()) => {}
|
||||
// APFS rejects non-UTF-8 names before repository code can read them.
|
||||
Err(error) if cfg!(target_os = "macos") && error.raw_os_error() == Some(92) => return,
|
||||
Err(error) => panic!("Cannot create non-UTF-8 fixture: {error}"),
|
||||
}
|
||||
let mut add = git(&temp.0);
|
||||
add.args(["add", "--"]).arg(&name);
|
||||
checked(add, &|| false).unwrap();
|
||||
command(&temp.0, "git", &["commit", "--quiet", "-m", "Byte path"]);
|
||||
assert_eq!(
|
||||
read_file(&path, "changed\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Modified), None]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jj_parent_root_colocation_ignore_and_merge_queries_are_read_only() {
|
||||
for colocate in ["--colocate", "--no-colocate"] {
|
||||
let temp = Temporary::new();
|
||||
command(&temp.0, "jj", &["git", "init", colocate, "."]);
|
||||
let name = "-literal [file]\n\t\".txt";
|
||||
let path = temp.0.join(name);
|
||||
fs::write(&path, "original\n").unwrap();
|
||||
assert_eq!(
|
||||
read_file(&path, "unsaved\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None]
|
||||
);
|
||||
fs::write(temp.0.join(".gitignore"), "ignored\n").unwrap();
|
||||
assert!(
|
||||
read_file(&temp.0.join("ignored"), "text\n", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
command(&temp.0, "jj", &["describe", "-m", "Baseline"]);
|
||||
command(&temp.0, "jj", &["new"]);
|
||||
let operation = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
],
|
||||
);
|
||||
let store = store_for_jj(&temp.0).unwrap();
|
||||
let refs = fs::read(store.join("HEAD")).unwrap();
|
||||
fs::write(&path, "disk edit\n").unwrap();
|
||||
assert_eq!(
|
||||
read_file(&path, "inserted\noriginal\n", &|| false).unwrap(),
|
||||
vec![Some(Change::Added), None, None]
|
||||
);
|
||||
assert_eq!(fs::read(store.join("HEAD")).unwrap(), refs);
|
||||
assert_eq!(
|
||||
command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
]
|
||||
),
|
||||
operation
|
||||
);
|
||||
let parent = command(
|
||||
&temp.0,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
command(&temp.0, "jj", &["new", "root()"]);
|
||||
fs::write(temp.0.join("sibling"), "sibling\n").unwrap();
|
||||
command(&temp.0, "jj", &["describe", "-m", "Sibling"]);
|
||||
command(&temp.0, "jj", &["new", &parent, "@"]);
|
||||
assert!(
|
||||
read_file(&path, "original\n", &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_retains_only_latest_batch_and_file_errors_keep_good_siblings() {
|
||||
let (_temp, path) = git_fixture();
|
||||
let mut worker = Worker::start().unwrap();
|
||||
let oversized: Arc<str> = "x".repeat(FILE_LIMIT + 1).into();
|
||||
for id in 0..20 {
|
||||
worker
|
||||
.request(
|
||||
id,
|
||||
vec![
|
||||
(5, path.clone(), "first\nchanged\nthird\n".into()),
|
||||
(8, path.clone(), Arc::clone(&oversized)),
|
||||
],
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
loop {
|
||||
if let Some((id, result, picker)) = worker.poll() {
|
||||
assert!(picker.is_none());
|
||||
assert_eq!(id, 19);
|
||||
assert_eq!(result[0].0, 5);
|
||||
assert_eq!(
|
||||
result[0].1.as_ref().unwrap(),
|
||||
&vec![None, Some(Change::Modified), None, None]
|
||||
);
|
||||
assert_eq!(result[1].0, 8);
|
||||
assert_eq!(
|
||||
result[1].1.as_ref().unwrap_err(),
|
||||
"Gutter file exceeds 16 MiB"
|
||||
);
|
||||
break;
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
worker
|
||||
.request(
|
||||
20,
|
||||
vec![(0, path, "x".repeat(BATCH_LIMIT + 1).into())],
|
||||
None
|
||||
)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidInput
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_status_is_optional_and_errors_do_not_discard_line_results() {
|
||||
let (temp, path) = git_fixture();
|
||||
let mut worker = Worker::start().unwrap();
|
||||
worker
|
||||
.request(
|
||||
1,
|
||||
vec![],
|
||||
Some((
|
||||
temp.0.clone(),
|
||||
vec![(path.clone(), "dirty buffer\n".into())],
|
||||
)),
|
||||
)
|
||||
.unwrap();
|
||||
loop {
|
||||
if let Some((id, lines, picker)) = worker.poll() {
|
||||
assert_eq!(id, 1);
|
||||
assert!(lines.is_empty());
|
||||
let picker = picker.unwrap();
|
||||
assert_eq!(picker.root, temp.0);
|
||||
let changes = picker.result.unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0].path, path.strip_prefix(&temp.0).unwrap());
|
||||
assert_eq!(changes[0].status, crate::diff::FileStatus::Modified);
|
||||
break;
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
worker
|
||||
.request(
|
||||
2,
|
||||
vec![(4, path.clone(), "first\nchanged\nthird\n".into())],
|
||||
Some((
|
||||
temp.0.clone(),
|
||||
vec![(path, "x".repeat(FILE_LIMIT + 1).into())],
|
||||
)),
|
||||
)
|
||||
.unwrap();
|
||||
loop {
|
||||
if let Some((id, lines, picker)) = worker.poll() {
|
||||
assert_eq!(id, 2);
|
||||
assert_eq!(lines[0].0, 4);
|
||||
assert!(lines[0].1.is_ok());
|
||||
assert!(picker.unwrap().result.unwrap_err().contains("16 MiB"));
|
||||
break;
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_definitions_preserve_snapshot_identity_and_utf16_until_navigation() {
|
||||
let source = Source {
|
||||
buffer_id: 7,
|
||||
revision: 3,
|
||||
row: 0,
|
||||
column: 0,
|
||||
request_id: 11,
|
||||
};
|
||||
let path = Path::new("/vamp-immutable-snapshot/Before/renamed/λ.rs");
|
||||
let span = json!({
|
||||
"start": {"line": 4, "character": 5},
|
||||
"end": {"line": 4, "character": 8}
|
||||
});
|
||||
for location in [
|
||||
json!({"uri": file_uri(path).unwrap(), "range": span}),
|
||||
json!({"targetUri": file_uri(path).unwrap(),
|
||||
"targetRange": span, "targetSelectionRange": span}),
|
||||
] {
|
||||
let effects = Runtime::definition_effects(&source, &location).unwrap();
|
||||
let expected_target_range = location.get("targetUri").map(|_| Utf16Range {
|
||||
start: (4, 5),
|
||||
end: (4, 8),
|
||||
});
|
||||
assert!(matches!(
|
||||
effects.as_slice(),
|
||||
[UpdateEffect::NavigateUtf16 {
|
||||
buffer_id: 7, revision: 3, path: target,
|
||||
range: Utf16Range { start: (4, 5), end: (4, 8) }, target_range,
|
||||
}] if target == path && *target_range == expected_target_range
|
||||
));
|
||||
}
|
||||
for invalid in [
|
||||
json!({"start": {"line": 4, "character": 8},
|
||||
"end": {"line": 4, "character": 5}}),
|
||||
json!({"start": {"line": -1, "character": 0},
|
||||
"end": {"line": 0, "character": 0}}),
|
||||
] {
|
||||
for location in [
|
||||
json!({"uri": file_uri(path).unwrap(), "range": invalid}),
|
||||
json!({"targetUri": file_uri(path).unwrap(),
|
||||
"targetRange": invalid, "targetSelectionRange": span}),
|
||||
json!({"targetUri": file_uri(path).unwrap(),
|
||||
"targetRange": span, "targetSelectionRange": invalid}),
|
||||
] {
|
||||
assert!(Runtime::definition_effects(&source, &location).is_err());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_value::<UpdateEffect>(json!({
|
||||
"type": "navigate_utf16", "buffer_id": 7, "revision": 3,
|
||||
"path": path, "range": {"start": [4,5], "end": [4,8]},
|
||||
"target_range": null
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_decoder_validates_raw_coordinates_before_grapheme_rounding() {
|
||||
let options = semantic_options(Some(&json!({
|
||||
"full": true,
|
||||
"legend": {"tokenTypes": ["custom", "function"],
|
||||
"tokenModifiers": ["custom", "readonly", "declaration", "async"]}
|
||||
})))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let tokens = decode_semantic_tokens(
|
||||
"A😀e\u{301}Z\r\n\r\nx",
|
||||
&json!({"data": [
|
||||
0, 1, 2, 1, 2,
|
||||
0, 2, 1, 1, 12,
|
||||
0, 1, 1, 1, 0,
|
||||
0, 1, 999, 0, 0,
|
||||
1, 0, 1, 1, 0,
|
||||
1, 0, 0, 1, 0,
|
||||
0, 0, 100, 1, 0
|
||||
]}),
|
||||
&options,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(tokens.len(), 4);
|
||||
assert_eq!(tokens[0].start, TextPosition { row: 0, column: 1 });
|
||||
assert_eq!(tokens[0].end, TextPosition { row: 0, column: 2 });
|
||||
assert_eq!(tokens[0].modifiers, SemanticTokenModifier::Readonly as u16);
|
||||
assert_eq!(tokens[1].start, TextPosition { row: 0, column: 2 });
|
||||
assert_eq!(tokens[1].end, TextPosition { row: 0, column: 3 });
|
||||
assert_eq!(
|
||||
tokens[1].modifiers,
|
||||
SemanticTokenModifier::Declaration as u16 | SemanticTokenModifier::Async as u16
|
||||
);
|
||||
assert_eq!(tokens[2].start, tokens[1].start);
|
||||
assert_eq!(tokens[3].end, TextPosition { row: 2, column: 1 });
|
||||
for data in [
|
||||
json!([0, 0, 1, 1]),
|
||||
json!([-1, 0, 1, 1, 0]),
|
||||
json!([0, 0.5, 1, 1, 0]),
|
||||
json!([0, 0, 1, 1, 2147483648u64]),
|
||||
json!([0, 0, 1, 65536, 0]),
|
||||
json!([0, 0, 1, 2, 0]),
|
||||
json!([0, 0, 1, 1, 16]),
|
||||
json!([0, 2, 1, 0, 0]),
|
||||
json!([0, 1, 1, 1, 0]),
|
||||
json!([0, 7, 1, 1, 0]),
|
||||
json!([2, 0, 1, 1, 0]),
|
||||
json!([0, 1, 2, 1, 0, 0, 1, 1, 1, 0]),
|
||||
] {
|
||||
assert!(
|
||||
decode_semantic_tokens("A😀e\u{301}Z\n", &json!({"data": data}), &options).is_err(),
|
||||
"{data}"
|
||||
);
|
||||
}
|
||||
let count = MAX_BODY / std::mem::size_of::<SemanticToken>() + 1;
|
||||
assert!(decode_semantic_tokens("x", &json!({"data": vec![0; count * 5]}), &options).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_positions_and_local_uri_boundaries() {
|
||||
let text = "A😀e\u{301}Z\n";
|
||||
let (start, end) = range(
|
||||
text,
|
||||
&json!({"start": {"line": 0, "character": 2}, "end": {"line": 0, "character": 4}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(start, TextPosition { row: 0, column: 1 });
|
||||
assert_eq!(end, TextPosition { row: 0, column: 3 });
|
||||
assert_eq!(
|
||||
outbound_position(text, 0, 3).unwrap(),
|
||||
json!({"line": 0, "character": 5})
|
||||
);
|
||||
assert_eq!(
|
||||
position(text, &json!({"line": 1, "character": 999}), false).unwrap(),
|
||||
TextPosition { row: 1, column: 0 }
|
||||
);
|
||||
assert!(
|
||||
range(
|
||||
text,
|
||||
&json!({"start": {"line": 0, "character": 3}, "end": {"line": 0, "character": 2}})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let path = Path::new("/tmp/source space λ😀.rs");
|
||||
assert_eq!(uri_path(&file_uri(path).unwrap()).unwrap(), path);
|
||||
assert_eq!(
|
||||
uri_path("file://localhost/tmp/a%23b").unwrap(),
|
||||
Path::new("/tmp/a#b")
|
||||
);
|
||||
for uri in [
|
||||
"https://example.invalid/a",
|
||||
"file://remote/tmp/a",
|
||||
"file:///tmp/%",
|
||||
"file:///tmp/%00",
|
||||
"file:///tmp/%FF",
|
||||
"file:///tmp/a?query",
|
||||
] {
|
||||
assert!(uri_path(uri).is_err(), "{uri}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_contents_keep_lines_and_reject_malformed_values() {
|
||||
let source = "A😀e\u{301}Z\r\n";
|
||||
for kind in ["plaintext", "markdown"] {
|
||||
assert_eq!(
|
||||
hover_text(
|
||||
&json!({
|
||||
"contents": {"kind": kind, "value": "😀e\u{301}\r\n\tcode\rnext\u{1b}\u{85}"},
|
||||
"range": {"start": {"line": 0, "character": 2},
|
||||
"end": {"line": 0, "character": 4}}
|
||||
}),
|
||||
source,
|
||||
)
|
||||
.unwrap(),
|
||||
Some("😀e\u{301}\n code\nnext ".into()),
|
||||
);
|
||||
}
|
||||
for contents in [
|
||||
json!("line\ncode"),
|
||||
json!({"language": "rust", "value": "line\ncode"}),
|
||||
] {
|
||||
assert_eq!(
|
||||
hover_text(&json!({"contents": contents}), source).unwrap(),
|
||||
Some("line\ncode".into()),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
hover_text(
|
||||
&json!({"contents": ["first", {"language": "rust", "value": "fn main() {\n}"}]}),
|
||||
source,
|
||||
)
|
||||
.unwrap(),
|
||||
Some("first\n\nfn main() {\n}".into()),
|
||||
);
|
||||
for value in [
|
||||
Value::Null,
|
||||
json!({"contents": ""}),
|
||||
json!({"contents": []}),
|
||||
] {
|
||||
assert_eq!(hover_text(&value, source).unwrap(), None);
|
||||
}
|
||||
for value in [
|
||||
json!({}),
|
||||
json!({"contents": {"kind": "html", "value": "x"}}),
|
||||
json!({"contents": {"language": "rust", "value": false}}),
|
||||
json!({"contents": [{"kind": "markdown", "value": "x"}]}),
|
||||
json!({"contents": "x", "range": {"start": {"line": 1, "character": 0},
|
||||
"end": {"line": 0, "character": 0}}}),
|
||||
json!({"contents": "\t".repeat(MAX_BODY / 4 + 1)}),
|
||||
] {
|
||||
assert!(hover_text(&value, source).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_text_limit_counts_the_atomic_batch_not_sort_metadata() {
|
||||
let source = Source {
|
||||
buffer_id: 1,
|
||||
revision: 0,
|
||||
row: 0,
|
||||
column: 0,
|
||||
request_id: 1,
|
||||
};
|
||||
let at_limit = json!([{"label": "x", "insertText": "x".repeat(MAX_BODY - 1)}]);
|
||||
assert_eq!(
|
||||
decode_completion("", &at_limit, &source, None).unwrap()[0].edits[0]
|
||||
.text
|
||||
.len(),
|
||||
MAX_BODY - 1
|
||||
);
|
||||
let over_limit = json!([
|
||||
{"label": "x", "insertText": "x".repeat(MAX_BODY - 1)},
|
||||
{"label": "y"}
|
||||
]);
|
||||
assert!(
|
||||
decode_completion("", &over_limit, &source, None)
|
||||
.unwrap_err()
|
||||
.contains("4 MiB")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
fn at(text: &str, needle: &str) -> Result<LinkTarget, String> {
|
||||
let byte = text.find(needle).unwrap();
|
||||
let prefix = &text[..byte];
|
||||
let row = prefix.bytes().filter(|byte| *byte == b'\n').count();
|
||||
let column = prefix.rsplit('\n').next().unwrap().graphemes(true).count();
|
||||
link_at(text, TextPosition { row, column })
|
||||
}
|
||||
|
||||
fn target(path: Option<&str>, fragment: Option<&str>) -> LinkTarget {
|
||||
LinkTarget {
|
||||
path: path.map(PathBuf::from),
|
||||
fragment: fragment.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_inline_labels_destinations_and_grapheme_columns() {
|
||||
let text = "👩💻 [go **there**](<../My%20Notes/%E6%97%A5%E6%9C%AC\\(1\\).md#caf%C3%A9>)";
|
||||
let expected = target(Some("../My Notes/日本(1).md"), Some("café"));
|
||||
assert_eq!(at(text, "there").unwrap(), expected);
|
||||
assert_eq!(at(text, "My%20").unwrap(), expected);
|
||||
assert_eq!(
|
||||
at("[absolute](/Tmp/Note.md)", "absolute").unwrap(),
|
||||
target(Some("/Tmp/Note.md"), None)
|
||||
);
|
||||
assert_eq!(
|
||||
at("[here](#title)", "here").unwrap(),
|
||||
target(None, Some("title"))
|
||||
);
|
||||
assert_eq!(at("[top]()", "top").unwrap(), target(None, None));
|
||||
assert_eq!(
|
||||
at("[here](#title)", "[here").unwrap(),
|
||||
target(None, Some("title"))
|
||||
);
|
||||
assert_eq!(
|
||||
at("[file](literal%23name.md)", "file").unwrap(),
|
||||
target(Some("literal#name.md"), None)
|
||||
);
|
||||
assert_eq!(
|
||||
at("[file](My\\[Notes\\].md)", "file").unwrap(),
|
||||
target(Some("My[Notes].md"), None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_all_reference_forms_and_multiline_block_definitions() {
|
||||
let text = "[full][ A B ] [a b][] [A B]\n\n> [a b]:\n> <My%20Notes.md#title>\n> \"A title\"\n\n[a b]: ignored.md\n";
|
||||
let expected = target(Some("My Notes.md"), Some("title"));
|
||||
for needle in ["full", " A B ", "a b][]", "A B]"] {
|
||||
assert_eq!(at(text, needle).unwrap(), expected);
|
||||
}
|
||||
assert_eq!(
|
||||
at("[Straße]\n\n[STRASSE]: file.md", "Straße").unwrap(),
|
||||
target(Some("file.md"), None)
|
||||
);
|
||||
let text = "> [multi\n> line][target]\n\n[target]: other.md\n";
|
||||
assert_eq!(at(text, "line]").unwrap(), target(Some("other.md"), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_images_code_plaintext_and_external_urls() {
|
||||
for (text, needle) in [
|
||||
("", "image"),
|
||||
("`[code](file.md)`", "code"),
|
||||
("```md\n[code](file.md)\n```", "file"),
|
||||
(" [code](file.md)", "code"),
|
||||
("plain file.md text", "file"),
|
||||
("[web](https://example.com)", "web"),
|
||||
("[web](//example.com/a)", "web"),
|
||||
("[web](mailto:a@example.com)", "web"),
|
||||
("<https://example.com>", "example"),
|
||||
] {
|
||||
assert!(at(text, needle).is_err(), "{text}");
|
||||
}
|
||||
assert!(
|
||||
at("[missing]", "missing")
|
||||
.unwrap_err()
|
||||
.contains("not defined")
|
||||
);
|
||||
assert!(
|
||||
at("[bad](file%ZZ.md)", "bad")
|
||||
.unwrap_err()
|
||||
.contains("percent")
|
||||
);
|
||||
assert!(
|
||||
at("[bad](file%FF.md)", "bad")
|
||||
.unwrap_err()
|
||||
.contains("UTF-8")
|
||||
);
|
||||
assert!(at("[bad](#)", "bad").unwrap_err().contains("empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locates_visible_unicode_headings_setext_and_unique_slugs() {
|
||||
let text = "# **Café** [日本](destination.md) `code` ###\n\n> ## Café 日本 code\n\nCafé 日本 code\n====\n\n# Café 日本 code-1\n\n# Cafe\u{301} _name_ \n\n```md\n# Hidden\n```\n";
|
||||
assert_eq!(heading_row(text, "café-日本-code").unwrap(), 0);
|
||||
assert_eq!(heading_row(text, "café-日本-code-1").unwrap(), 2);
|
||||
assert_eq!(heading_row(text, "café-日本-code-2").unwrap(), 4);
|
||||
assert_eq!(heading_row(text, "café-日本-code-1-1").unwrap(), 7);
|
||||
assert_eq!(heading_row(text, "cafe\u{301}-name-alt").unwrap(), 9);
|
||||
assert!(heading_row(text, "hidden").is_err());
|
||||
assert!(heading_row(text, "destinationmd").is_err());
|
||||
assert!(heading_row(text, "").is_err());
|
||||
assert_eq!(
|
||||
heading_row("# [Heading][ref]\n\n[ref]: ignored.md", "heading").unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
heading_row("# ![Alt][ref]\n\n[ref]: ignored.md", "alt").unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(heading_row("# ![Alt][missing]", "altmissing").unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_entities_or_reports_the_explicit_entity_ceiling() {
|
||||
assert_eq!(
|
||||
at("[file](a&b c.md)", "file").unwrap(),
|
||||
target(Some("a&b c.md"), None)
|
||||
);
|
||||
assert_eq!(
|
||||
at("[file](<name>)", "file").unwrap(),
|
||||
target(Some("<name>"), None)
|
||||
);
|
||||
assert!(
|
||||
at("[file](a©b.md)", "file")
|
||||
.unwrap_err()
|
||||
.contains("Unsupported Markdown HTML entity")
|
||||
);
|
||||
assert_eq!(heading_row("# A & B é\n", "a--b-é").unwrap(), 0);
|
||||
assert!(
|
||||
heading_row("# ©\n", "copy")
|
||||
.unwrap_err()
|
||||
.contains("Unsupported Markdown HTML entity")
|
||||
);
|
||||
assert_eq!(heading_row("# ©\n# Valid\n", "valid").unwrap(), 1);
|
||||
assert_eq!(
|
||||
heading_row("> First\n> Second\n> ------\n", "first-second").unwrap(),
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use super::*;
|
||||
|
||||
fn rect(x: u16, y: u16, width: u16, height: u16) -> PaneRect {
|
||||
PaneRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
fn leaves(tree: &PaneTree, bounds: PaneRect) -> Vec<(usize, PaneRect)> {
|
||||
let mut leaves = Vec::new();
|
||||
tree.visit_rects(bounds, |id, rect| leaves.push((id, rect)));
|
||||
leaves
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_layout_partitions_bounds_and_preserves_ids() {
|
||||
let bounds = rect(3, 5, 11, 9);
|
||||
let mut tree = PaneTree::new(10);
|
||||
assert!(tree.split(10, 20, SplitAxis::Vertical));
|
||||
assert!(tree.split(20, 30, SplitAxis::Horizontal));
|
||||
assert!(!tree.split(99, 40, SplitAxis::Horizontal));
|
||||
assert!(!tree.split(10, 30, SplitAxis::Horizontal));
|
||||
assert!(!tree.split(10, 10, SplitAxis::Horizontal));
|
||||
assert_eq!(tree.len(), 3);
|
||||
let panes = leaves(&tree, bounds);
|
||||
assert_eq!(
|
||||
panes,
|
||||
vec![
|
||||
(10, rect(3, 5, 5, 9)),
|
||||
(20, rect(8, 5, 6, 4)),
|
||||
(30, rect(8, 9, 6, 5))
|
||||
]
|
||||
);
|
||||
let mut cells = std::collections::HashSet::new();
|
||||
for (_, pane) in panes {
|
||||
for y in pane.y..pane.y + pane.height {
|
||||
for x in pane.x..pane.x + pane.width {
|
||||
assert!(cells.insert((x, y)), "overlapping pane cell");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
cells.len(),
|
||||
usize::from(bounds.width) * usize::from(bounds.height)
|
||||
);
|
||||
assert!(leaves(&tree, rect(0, 0, 0, 10)).is_empty());
|
||||
assert!(leaves(&tree, rect(0, 0, 10, 0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_expands_nested_sibling_and_refuses_last() {
|
||||
let bounds = rect(0, 0, 20, 12);
|
||||
let mut tree = PaneTree::new(1);
|
||||
tree.split(1, 2, SplitAxis::Vertical);
|
||||
tree.split(2, 3, SplitAxis::Horizontal);
|
||||
assert_eq!(tree.close(1), Some(2));
|
||||
assert_eq!(
|
||||
leaves(&tree, bounds),
|
||||
vec![(2, rect(0, 0, 20, 6)), (3, rect(0, 6, 20, 6))]
|
||||
);
|
||||
assert_eq!(tree.close(99), None);
|
||||
assert_eq!(tree.close(2), Some(3));
|
||||
assert_eq!(leaves(&tree, bounds), vec![(3, bounds)]);
|
||||
assert_eq!(tree.close(3), None);
|
||||
assert_eq!(tree.len(), 1);
|
||||
assert!(!tree.contains(1));
|
||||
assert!(tree.contains(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directional_focus_handles_unequal_nested_regions() {
|
||||
let bounds = rect(0, 0, 20, 12);
|
||||
let mut tree = PaneTree::new(1);
|
||||
tree.split(1, 2, SplitAxis::Vertical);
|
||||
tree.split(2, 3, SplitAxis::Horizontal);
|
||||
tree.split(3, 4, SplitAxis::Horizontal);
|
||||
assert_eq!(tree.neighbor(1, PaneDirection::Right, bounds), Some(3));
|
||||
assert_eq!(tree.neighbor(2, PaneDirection::Down, bounds), Some(3));
|
||||
assert_eq!(tree.neighbor(3, PaneDirection::Down, bounds), Some(4));
|
||||
assert_eq!(tree.neighbor(4, PaneDirection::Up, bounds), Some(3));
|
||||
assert_eq!(tree.neighbor(4, PaneDirection::Left, bounds), Some(1));
|
||||
assert_eq!(tree.neighbor(1, PaneDirection::Left, bounds), None);
|
||||
assert_eq!(tree.neighbor(99, PaneDirection::Right, bounds), None);
|
||||
assert_eq!(
|
||||
tree.neighbor(1, PaneDirection::Right, rect(0, 0, 0, 0)),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigation_prefers_overlap_then_edge_and_breaks_ties_by_id() {
|
||||
let current = rect(10, 10, 10, 10);
|
||||
let candidates = [
|
||||
(1, rect(20, 0, 5, 5)),
|
||||
(2, rect(25, 10, 5, 10)),
|
||||
(4, rect(22, 10, 5, 10)),
|
||||
(3, rect(22, 10, 5, 10)),
|
||||
(0, rect(20, 10, 0, 10)),
|
||||
];
|
||||
assert_eq!(
|
||||
directional_neighbor(current, PaneDirection::Right, candidates.into_iter()),
|
||||
Some(3)
|
||||
);
|
||||
assert_eq!(
|
||||
directional_neighbor(current, PaneDirection::Right, candidates.into_iter().rev()),
|
||||
Some(3)
|
||||
);
|
||||
assert_eq!(
|
||||
directional_neighbor(
|
||||
current,
|
||||
PaneDirection::Up,
|
||||
[(7, rect(10, 0, 10, 5))].into_iter()
|
||||
),
|
||||
Some(7)
|
||||
);
|
||||
assert_eq!(
|
||||
directional_neighbor(current, PaneDirection::Left, candidates.into_iter()),
|
||||
None
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
use super::*;
|
||||
use crate::pull_requests::{Direction, ReviewFilter, SortField, SortRule};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-pr-preferences-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> PathBuf {
|
||||
self.0.join("state/vamp/pull_requests.json")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_use_absolute_xdg_state_or_home_without_reading_environment() {
|
||||
assert_eq!(
|
||||
path_from(Some(OsStr::new("/state")), Some(OsStr::new("/home"))).unwrap(),
|
||||
PathBuf::from("/state/vamp/pull_requests.json")
|
||||
);
|
||||
for xdg in [None, Some(OsStr::new("")), Some(OsStr::new("relative"))] {
|
||||
assert_eq!(
|
||||
path_from(xdg, Some(OsStr::new("/home"))).unwrap(),
|
||||
PathBuf::from("/home/.local/state/vamp/pull_requests.json")
|
||||
);
|
||||
}
|
||||
assert!(path_from(None, None).is_err());
|
||||
assert!(path_from(None, Some(OsStr::new("relative"))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_is_lazy_and_applied_preferences_round_trip_atomically() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.path();
|
||||
let (store, mut preferences, notice) = Store::load(Ok(path.clone()));
|
||||
assert_eq!(preferences, Preferences::default());
|
||||
assert!(notice.is_none());
|
||||
assert!(!path.parent().unwrap().exists());
|
||||
preferences.filters = vec![ReviewFilter::Approved];
|
||||
preferences.sort.insert(
|
||||
SortField::UpdatedAt,
|
||||
SortRule {
|
||||
precedence: Some(1),
|
||||
direction: Direction::Asc,
|
||||
},
|
||||
);
|
||||
store.save(&preferences).unwrap();
|
||||
let (_, loaded, notice) = Store::load(Ok(path.clone()));
|
||||
assert_eq!(loaded.sort, preferences.sort);
|
||||
assert_eq!(loaded.filters, Preferences::default().filters);
|
||||
assert!(!fs::read_to_string(&path).unwrap().contains("filters"));
|
||||
assert!(notice.is_none());
|
||||
preferences.filters.clear();
|
||||
preferences.sort.clear();
|
||||
store.save(&preferences).unwrap();
|
||||
assert_eq!(Store::load(Ok(path)).1, Preferences::default());
|
||||
assert_eq!(
|
||||
fs::read_dir(fixture.0.join("state/vamp")).unwrap().count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previously_saved_filters_are_ignored_without_changing_sort_or_file() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.path();
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
for filters in [
|
||||
r#"[]"#,
|
||||
r#"["approved"]"#,
|
||||
r#"["unknown"]"#,
|
||||
r#"{"invalid":true}"#,
|
||||
] {
|
||||
let bytes = format!(
|
||||
r#"{{"version":1,"preferences":{{"sort":{{"created_at":{{"precedence":1,"direction":"asc"}}}},"filters":{filters}}}}}"#
|
||||
);
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
let (_, loaded, notice) = Store::load(Ok(path.clone()));
|
||||
assert!(notice.is_none());
|
||||
assert_eq!(loaded.filters, Preferences::default().filters);
|
||||
assert_eq!(loaded.sort[&SortField::CreatedAt].direction, Direction::Asc);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_incompatible_and_invalid_data_is_preserved_even_after_apply() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.path();
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
for bytes in [
|
||||
"not json",
|
||||
r#"{"version":2,"preferences":{}}"#,
|
||||
r#"{"version":1,"preferences":{"sort":{"unknown":{}}}}"#,
|
||||
r#"{"version":1,"preferences":{"sort":{"updated_at":{"direction":"up"}}}}"#,
|
||||
r#"{"version":1,"preferences":{"sort":{"updated_at":{"precedence":0}}}}"#,
|
||||
r#"{"version":1,"preferences":{"sort":{"updated_at":{"precedence":1},"created_at":{"precedence":1}}}}"#,
|
||||
] {
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let (store, loaded, notice) = Store::load(Ok(path.clone()));
|
||||
assert_eq!(loaded, Preferences::default());
|
||||
assert!(notice.unwrap().contains("session-only"));
|
||||
assert!(store.save(&loaded).unwrap_err().contains("preserved"));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_writes_and_newly_incompatible_data_are_reported_without_replacement() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.path();
|
||||
let (store, preferences, _) = Store::load(Ok(path.clone()));
|
||||
fs::write(fixture.0.join("state"), "keep this file").unwrap();
|
||||
assert!(
|
||||
store
|
||||
.save(&preferences)
|
||||
.unwrap_err()
|
||||
.contains("session-only")
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("state")).unwrap(),
|
||||
"keep this file"
|
||||
);
|
||||
fs::remove_file(fixture.0.join("state")).unwrap();
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let incompatible = r#"{"version":9,"preferences":{}}"#;
|
||||
fs::write(&path, incompatible).unwrap();
|
||||
assert!(
|
||||
store
|
||||
.save(&preferences)
|
||||
.unwrap_err()
|
||||
.contains("unsupported")
|
||||
);
|
||||
assert_eq!(fs::read_to_string(path).unwrap(), incompatible);
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
fn working_file_changes(
|
||||
root: &Path,
|
||||
buffers: &[(PathBuf, Arc<str>)],
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> Result<Vec<WorkingFileChange>, String> {
|
||||
WorkingFileReader::default().read(root, buffers, cancelled)
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
fn fixture_command(root: &Path, program: &str, args: &[&str]) -> String {
|
||||
let mut command = Command::new(program);
|
||||
if program == "jj" {
|
||||
command.args([
|
||||
"--config=user.name=\"Picker Author\"",
|
||||
"--config=user.email=\"picker@example.test\"",
|
||||
"--config=debug.commit-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
"--config=debug.operation-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
]);
|
||||
}
|
||||
let output = command
|
||||
.args(args)
|
||||
.current_dir(root)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_CONFIG_SYSTEM", "/dev/null")
|
||||
.env("GIT_AUTHOR_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("GIT_COMMITTER_DATE", "2001-01-01T00:00:00Z")
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap().trim().into()
|
||||
}
|
||||
|
||||
fn picker_git_fixture() -> Temporary {
|
||||
let temp = Temporary::new().unwrap();
|
||||
fixture_command(&temp.0, "git", &["init", "--quiet", "--template="]);
|
||||
fixture_command(&temp.0, "git", &["config", "user.name", "Picker Author"]);
|
||||
fixture_command(
|
||||
&temp.0,
|
||||
"git",
|
||||
&["config", "user.email", "picker@example.test"],
|
||||
);
|
||||
temp
|
||||
}
|
||||
|
||||
fn changes_by_path(
|
||||
root: &Path,
|
||||
buffers: &[(PathBuf, Arc<str>)],
|
||||
) -> BTreeMap<PathBuf, WorkingFileChange> {
|
||||
working_file_changes(root, buffers, &|| false)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|change| (change.path.clone(), change))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_git_changes_cover_disk_index_buffers_binary_exact_renames_and_read_only_queries() {
|
||||
use std::os::unix::{ffi::OsStringExt, fs::PermissionsExt};
|
||||
let temp = picker_git_fixture();
|
||||
let root = &temp.0;
|
||||
for (name, contents) in [
|
||||
(".gitignore", "ignored*\n"),
|
||||
("modified", "original\r\n"),
|
||||
("unchanged", "same\n"),
|
||||
("removed", "deleted\n"),
|
||||
("old", "rename content\n"),
|
||||
("duplicate-one", "duplicate\n"),
|
||||
("duplicate-two", "duplicate\n"),
|
||||
("mode", "mode\n"),
|
||||
("binary", "before\0binary"),
|
||||
] {
|
||||
fs::write(root.join(name), contents).unwrap();
|
||||
}
|
||||
let non_utf8 = PathBuf::from(OsString::from_vec(b"non-utf8-\xff".to_vec()));
|
||||
let non_utf8 = match fs::write(root.join(&non_utf8), "before\n") {
|
||||
Ok(()) => Some(non_utf8),
|
||||
Err(error) if cfg!(target_os = "macos") && error.raw_os_error() == Some(92) => None,
|
||||
Err(error) => panic!("cannot create byte filename: {error}"),
|
||||
};
|
||||
fixture_command(root, "git", &["add", "--all"]);
|
||||
fixture_command(root, "git", &["commit", "--quiet", "-m", "Baseline"]);
|
||||
fs::write(root.join("modified"), "staged\n").unwrap();
|
||||
fixture_command(root, "git", &["add", "--", "modified"]);
|
||||
fs::write(root.join("modified"), "unstaged\n").unwrap();
|
||||
fs::write(root.join("binary"), "after\0binary").unwrap();
|
||||
if let Some(name) = &non_utf8 {
|
||||
fs::write(root.join(name), "after\n").unwrap();
|
||||
}
|
||||
fs::remove_file(root.join("removed")).unwrap();
|
||||
let renamed = "-new [file]\n\t\".txt";
|
||||
fs::rename(root.join("old"), root.join(renamed)).unwrap();
|
||||
fs::remove_file(root.join("duplicate-one")).unwrap();
|
||||
fs::remove_file(root.join("duplicate-two")).unwrap();
|
||||
fs::write(root.join("new-duplicate-one"), "duplicate\n").unwrap();
|
||||
fs::write(root.join("new-duplicate-two"), "duplicate\n").unwrap();
|
||||
fs::set_permissions(root.join("mode"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::write(root.join("added"), "added\n").unwrap();
|
||||
fs::write(root.join("ignored"), "ignored\n").unwrap();
|
||||
fs::write(root.join("ignored-tracked"), "forced\n").unwrap();
|
||||
fixture_command(root, "git", &["add", "-f", "--", "ignored-tracked"]);
|
||||
std::os::unix::fs::symlink(root.join("modified"), root.join("link")).unwrap();
|
||||
let index = fs::read(root.join(".git/index")).unwrap();
|
||||
let head = fs::read(root.join(".git/HEAD")).unwrap();
|
||||
let disk = changes_by_path(root, &[]);
|
||||
for name in ["modified", "binary", "mode"] {
|
||||
assert_eq!(disk[Path::new(name)].status, FileStatus::Modified);
|
||||
}
|
||||
if let Some(name) = &non_utf8 {
|
||||
assert_eq!(disk[name].status, FileStatus::Modified);
|
||||
}
|
||||
assert_eq!(disk[Path::new("removed")].status, FileStatus::Removed);
|
||||
assert_eq!(disk[Path::new(renamed)].status, FileStatus::Renamed);
|
||||
assert_eq!(
|
||||
disk[Path::new(renamed)].old_path.as_deref(),
|
||||
Some(Path::new("old"))
|
||||
);
|
||||
for name in [
|
||||
"added",
|
||||
"ignored-tracked",
|
||||
"new-duplicate-one",
|
||||
"new-duplicate-two",
|
||||
] {
|
||||
assert_eq!(disk[Path::new(name)].status, FileStatus::Added);
|
||||
}
|
||||
for name in ["duplicate-one", "duplicate-two"] {
|
||||
assert_eq!(disk[Path::new(name)].status, FileStatus::Removed);
|
||||
}
|
||||
for name in ["unchanged", "old", "ignored", "link"] {
|
||||
assert!(!disk.contains_key(Path::new(name)), "{name}");
|
||||
}
|
||||
let overlays = changes_by_path(
|
||||
root,
|
||||
&[
|
||||
(root.join("modified"), "original\n".into()),
|
||||
(root.join("unchanged"), "dirty\n".into()),
|
||||
(root.join("removed"), "deleted\n".into()),
|
||||
(root.join(renamed), "dirty renamed\n".into()),
|
||||
(root.join("mode"), "mode\n".into()),
|
||||
(root.join("ignored-buffer"), "ignored\n".into()),
|
||||
],
|
||||
);
|
||||
assert!(!overlays.contains_key(Path::new("modified")));
|
||||
assert!(!overlays.contains_key(Path::new("ignored-buffer")));
|
||||
assert_eq!(
|
||||
overlays[Path::new("unchanged")].status,
|
||||
FileStatus::Modified
|
||||
);
|
||||
assert_eq!(overlays[Path::new("removed")].status, FileStatus::Removed);
|
||||
assert_eq!(overlays[Path::new(renamed)].status, FileStatus::Renamed);
|
||||
assert_eq!(overlays[Path::new("mode")].status, FileStatus::Modified);
|
||||
let aliases = Temporary::new().unwrap();
|
||||
let alias = aliases.0.join("checkout");
|
||||
std::os::unix::fs::symlink(root, &alias).unwrap();
|
||||
let aliased = changes_by_path(root, &[(alias.join("unchanged"), "dirty\n".into())]);
|
||||
assert_eq!(aliased[Path::new("unchanged")].status, FileStatus::Modified);
|
||||
fixture_command(root, "git", &["config", "core.filemode", "0"]);
|
||||
assert!(
|
||||
!changes_by_path(root, &[(root.join("mode"), "mode\n".into())])
|
||||
.contains_key(Path::new("mode"))
|
||||
);
|
||||
fixture_command(root, "git", &["config", "core.autocrlf", "1"]);
|
||||
fs::write(root.join("unchanged"), "same\r\n").unwrap();
|
||||
assert!(!changes_by_path(root, &[]).contains_key(Path::new("unchanged")));
|
||||
fixture_command(root, "git", &["config", "--unset", "core.autocrlf"]);
|
||||
fixture_command(root, "git", &["config", "core.filemode", "true"]);
|
||||
fs::write(root.join("unchanged"), "same\n").unwrap();
|
||||
assert_eq!(fs::read(root.join(".git/index")).unwrap(), index);
|
||||
assert_eq!(fs::read(root.join(".git/HEAD")).unwrap(), head);
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("modified")).unwrap(),
|
||||
"unstaged\n"
|
||||
);
|
||||
assert!(!root.join("removed").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_git_subdirectory_cross_boundary_moves_worktrees_and_unsafe_roots() {
|
||||
let temp = picker_git_fixture();
|
||||
let root = &temp.0;
|
||||
fs::create_dir(root.join("sub")).unwrap();
|
||||
fs::write(root.join("sub/outgoing"), "out\n").unwrap();
|
||||
fs::write(root.join("incoming"), "in\n").unwrap();
|
||||
fixture_command(root, "git", &["add", "--all"]);
|
||||
fixture_command(root, "git", &["commit", "--quiet", "-m", "Baseline"]);
|
||||
fs::rename(root.join("sub/outgoing"), root.join("outgoing")).unwrap();
|
||||
fs::rename(root.join("incoming"), root.join("sub/incoming")).unwrap();
|
||||
let changes = changes_by_path(&root.join("sub"), &[]);
|
||||
assert_eq!(changes.len(), 2);
|
||||
assert_eq!(changes[Path::new("outgoing")].status, FileStatus::Removed);
|
||||
assert_eq!(changes[Path::new("incoming")].status, FileStatus::Added);
|
||||
assert_eq!(changes[Path::new("incoming")].old_path, None);
|
||||
std::os::unix::fs::symlink(root.join("sub"), root.join("linked")).unwrap();
|
||||
assert!(changes_by_path(&root.join("linked"), &[]).is_empty());
|
||||
assert!(changes_by_path(&root.join(".git"), &[]).is_empty());
|
||||
let unrelated = Temporary::new().unwrap();
|
||||
assert!(changes_by_path(&unrelated.0, &[]).is_empty());
|
||||
let worktree = temp.0.join("worktree");
|
||||
fixture_command(
|
||||
root,
|
||||
"git",
|
||||
&["worktree", "add", "--quiet", "--detach", "worktree", "HEAD"],
|
||||
);
|
||||
fs::write(worktree.join("sub/outgoing"), "worktree edit\n").unwrap();
|
||||
let changes = changes_by_path(&worktree.join("sub"), &[]);
|
||||
assert_eq!(changes[Path::new("outgoing")].status, FileStatus::Modified);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_unborn_git_never_runs_filters_external_diff_textconv_or_hooks() {
|
||||
let temp = picker_git_fixture();
|
||||
let root = &temp.0;
|
||||
fs::write(root.join(".gitignore"), "ignored\n").unwrap();
|
||||
fs::write(root.join("tracked"), "tracked\n").unwrap();
|
||||
fs::write(root.join("untracked"), "untracked\n").unwrap();
|
||||
fs::write(root.join("ignored"), "ignored\n").unwrap();
|
||||
fixture_command(root, "git", &["add", "--", ".gitignore", "tracked"]);
|
||||
let changes = changes_by_path(root, &[(root.join("named"), "not saved\n".into())]);
|
||||
for name in [".gitignore", "tracked", "untracked", "named"] {
|
||||
assert_eq!(changes[Path::new(name)].status, FileStatus::Added);
|
||||
}
|
||||
assert!(!changes.contains_key(Path::new("ignored")));
|
||||
assert!(!root.join("named").exists());
|
||||
fixture_command(root, "git", &["commit", "--quiet", "-m", "Baseline"]);
|
||||
fs::write(
|
||||
root.join(".gitattributes"),
|
||||
"tracked filter=evil diff=evil\n",
|
||||
)
|
||||
.unwrap();
|
||||
let evil = "sh -c 'touch executed; cat'";
|
||||
for key in [
|
||||
"filter.evil.clean",
|
||||
"filter.evil.process",
|
||||
"diff.evil.command",
|
||||
"diff.evil.textconv",
|
||||
] {
|
||||
fixture_command(root, "git", &["config", key, evil]);
|
||||
}
|
||||
fixture_command(root, "git", &["config", "filter.evil.required", "true"]);
|
||||
fs::write(root.join("tracked"), "changed\n").unwrap();
|
||||
assert_eq!(
|
||||
changes_by_path(root, &[])[Path::new("tracked")].status,
|
||||
FileStatus::Modified
|
||||
);
|
||||
assert_eq!(
|
||||
changes_by_path(root, &[(root.join("tracked"), "tracked\n".into())])
|
||||
.get(Path::new("tracked")),
|
||||
None
|
||||
);
|
||||
assert!(!root.join("executed").exists());
|
||||
assert!(
|
||||
working_file_changes(root, &[], &|| true)
|
||||
.unwrap_err()
|
||||
.contains("cancelled")
|
||||
);
|
||||
assert!(
|
||||
working_file_changes(
|
||||
root,
|
||||
&[(root.join("tracked"), "x".repeat(FILE_LIMIT + 1).into())],
|
||||
&|| false
|
||||
)
|
||||
.unwrap_err()
|
||||
.contains("16 MiB")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_jj_root_parent_colocation_and_merge_queries_do_not_snapshot() {
|
||||
for colocate in ["--colocate", "--no-colocate"] {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let root = &temp.0;
|
||||
fixture_command(root, "jj", &["git", "init", colocate, "."]);
|
||||
fs::write(root.join("file"), "baseline\n").unwrap();
|
||||
assert_eq!(
|
||||
changes_by_path(root, &[])[Path::new("file")].status,
|
||||
FileStatus::Added
|
||||
);
|
||||
fs::write(root.join(".gitignore"), "ignored\n").unwrap();
|
||||
fixture_command(root, "jj", &["describe", "-m", "Baseline"]);
|
||||
fixture_command(root, "jj", &["new"]);
|
||||
let operation = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
],
|
||||
);
|
||||
let parent = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@-",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
let store = store_for_jj(root).unwrap();
|
||||
let head = fs::read(store.join("HEAD")).unwrap();
|
||||
let index = fs::read(store.join("index")).ok();
|
||||
fs::write(root.join("file"), "disk\n").unwrap();
|
||||
fs::write(root.join("new"), "new\n").unwrap();
|
||||
fs::write(root.join("ignored"), "ignored\n").unwrap();
|
||||
let changes = changes_by_path(root, &[]);
|
||||
assert_eq!(changes[Path::new("file")].status, FileStatus::Modified);
|
||||
assert_eq!(changes[Path::new("new")].status, FileStatus::Added);
|
||||
assert!(!changes.contains_key(Path::new("ignored")));
|
||||
assert!(
|
||||
!changes_by_path(root, &[(root.join("file"), "baseline\n".into())])
|
||||
.contains_key(Path::new("file"))
|
||||
);
|
||||
assert_eq!(fs::read(store.join("HEAD")).unwrap(), head);
|
||||
assert_eq!(fs::read(store.join("index")).ok(), index);
|
||||
assert_eq!(
|
||||
fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
]
|
||||
),
|
||||
operation
|
||||
);
|
||||
fixture_command(root, "jj", &["new", "root()"]);
|
||||
fs::write(root.join("sibling"), "sibling\n").unwrap();
|
||||
fixture_command(root, "jj", &["describe", "-m", "Sibling"]);
|
||||
fixture_command(root, "jj", &["new", &parent, "@"]);
|
||||
assert!(changes_by_path(root, &[]).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_jj_conflicted_parent_uses_cli_projection_without_snapshotting() {
|
||||
for colocate in ["--colocate", "--no-colocate"] {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let root = &temp.0;
|
||||
fixture_command(root, "jj", &["git", "init", colocate, "."]);
|
||||
fs::write(root.join("conflicted"), "base\n").unwrap();
|
||||
fixture_command(root, "jj", &["describe", "-m", "Base"]);
|
||||
let base = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
fixture_command(root, "jj", &["new"]);
|
||||
fs::write(root.join("conflicted"), "left\n").unwrap();
|
||||
fixture_command(root, "jj", &["describe", "-m", "Left"]);
|
||||
let left = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
fixture_command(root, "jj", &["new", &base]);
|
||||
fs::write(root.join("conflicted"), "right\n").unwrap();
|
||||
fixture_command(root, "jj", &["describe", "-m", "Right"]);
|
||||
let right = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
);
|
||||
fixture_command(root, "jj", &["new", &left, &right]);
|
||||
fixture_command(root, "jj", &["new"]);
|
||||
let projected = fs::read_to_string(root.join("conflicted")).unwrap();
|
||||
assert!(projected.contains("<<<<<<<"));
|
||||
let operation = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
],
|
||||
);
|
||||
let mut reader = WorkingFileReader::default();
|
||||
assert!(reader.read(root, &[], &|| false).unwrap().is_empty());
|
||||
fs::write(root.join("conflicted"), "resolved in working file\n").unwrap();
|
||||
let changes = reader.read(root, &[], &|| false).unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0].path, Path::new("conflicted"));
|
||||
assert_eq!(changes[0].status, FileStatus::Modified);
|
||||
assert!(
|
||||
reader
|
||||
.read(
|
||||
root,
|
||||
&[(root.join("conflicted"), projected.into())],
|
||||
&|| false
|
||||
)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("conflicted")).unwrap(),
|
||||
"resolved in working file\n"
|
||||
);
|
||||
assert_eq!(
|
||||
fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
]
|
||||
),
|
||||
operation
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jj_catalog_exposes_fixed_metadata_and_merge_parents_without_snapshotting() {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let root = &temp.0;
|
||||
fixture_command(root, "jj", &["git", "init", "--no-colocate", "."]);
|
||||
fixture_command(root, "jj", &["describe", "-m", "Base"]);
|
||||
let id = |root: &Path| {
|
||||
fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-r",
|
||||
"@",
|
||||
"-T",
|
||||
"commit_id",
|
||||
],
|
||||
)
|
||||
};
|
||||
let base = id(root);
|
||||
fixture_command(root, "jj", &["bookmark", "create", "base"]);
|
||||
fixture_command(root, "jj", &["new", &base, "-m", "Left"]);
|
||||
let left = id(root);
|
||||
fixture_command(root, "jj", &["new", &base, "-m", "Right"]);
|
||||
let right = id(root);
|
||||
fixture_command(root, "jj", &["new", &left, &right, "-m", "Merge"]);
|
||||
let current = id(root);
|
||||
let operation = fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
],
|
||||
);
|
||||
let mut repository = Repository::open(root, Arc::new(AtomicBool::new(false))).unwrap();
|
||||
let catalog = repository.catalog().unwrap();
|
||||
let merge = &catalog.graph[¤t];
|
||||
assert_eq!(merge.parents, [left, right]);
|
||||
assert_eq!(merge.author, "Picker Author");
|
||||
assert_eq!(merge.timestamp, "2001-01-01 00:00");
|
||||
assert_eq!(merge.description, "Merge");
|
||||
assert!(!merge.change_id.is_empty());
|
||||
assert!(merge.current);
|
||||
assert_eq!(catalog.graph[&base].bookmarks, "base");
|
||||
assert!(!catalog.graph[&base].current);
|
||||
assert!(catalog.graph[&"0".repeat(40)].immutable);
|
||||
assert_eq!(
|
||||
fixture_command(
|
||||
root,
|
||||
"jj",
|
||||
&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
]
|
||||
),
|
||||
operation
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_kills_pipe_holding_children_and_drains_both_streams() {
|
||||
let temp = Temporary::new().unwrap();
|
||||
let ready = temp.0.join("ready");
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let worker_cancelled = Arc::clone(&cancelled);
|
||||
let gate = ready.clone();
|
||||
let (sent, received) = mpsc::channel();
|
||||
let worker = thread::spawn(move || {
|
||||
let mut command = Command::new("sh");
|
||||
command
|
||||
.args([
|
||||
"-c",
|
||||
"sleep 600 & printf ready > \"$1\"; wait",
|
||||
"vamp-diff-test",
|
||||
])
|
||||
.arg(gate);
|
||||
let result = run(command, vec![], &worker_cancelled).map(|_| ());
|
||||
sent.send(result).unwrap();
|
||||
});
|
||||
// File handshake, not a wall-clock scheduling assumption.
|
||||
while !ready.exists() {
|
||||
if let Ok(result) = received.try_recv() {
|
||||
panic!("Process exited before the child was ready: {result:?}");
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
cancelled.store(true, Ordering::Release);
|
||||
assert!(received.recv().unwrap().unwrap_err().contains("cancelled"));
|
||||
worker.join().unwrap();
|
||||
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "i=0; while [ \"$i\" -lt 10000 ]; do printf 'line\\n'; printf 'error\\n' >&2; i=$((i+1)); done"]);
|
||||
let result = run(command, vec![], &AtomicBool::new(false)).unwrap();
|
||||
assert_eq!(result.code, Some(0));
|
||||
assert_eq!(result.stdout.len(), 50_000);
|
||||
assert_eq!(result.stderr.len(), 60_000);
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
use super::*;
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"vamp-resolver-test-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn jj(&self, args: &[&str]) -> String {
|
||||
let output = Command::new("jj")
|
||||
.current_dir(&self.0)
|
||||
.env("JJ_CONFIG", "/dev/null")
|
||||
.args([
|
||||
"--config=user.name=Resolver",
|
||||
"--config=user.email=resolver@example.test",
|
||||
"--config=debug.commit-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
"--config=debug.operation-timestamp=\"2001-01-01T00:00:00Z\"",
|
||||
])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap()
|
||||
}
|
||||
fn conflict(&self) {
|
||||
self.jj(&["git", "init", "--no-colocate", "."]);
|
||||
self.jj(&["config", "set", "--repo", "user.name", "Resolver"]);
|
||||
self.jj(&[
|
||||
"config",
|
||||
"set",
|
||||
"--repo",
|
||||
"user.email",
|
||||
"resolver@example.test",
|
||||
]);
|
||||
self.jj(&[
|
||||
"config",
|
||||
"set",
|
||||
"--repo",
|
||||
"debug.commit-timestamp",
|
||||
"\"2001-01-01T00:00:00Z\"",
|
||||
]);
|
||||
self.jj(&[
|
||||
"config",
|
||||
"set",
|
||||
"--repo",
|
||||
"debug.operation-timestamp",
|
||||
"\"2001-01-01T00:00:00Z\"",
|
||||
]);
|
||||
fs::write(self.0.join("file"), "base\n").unwrap();
|
||||
self.jj(&["bookmark", "create", "base"]);
|
||||
self.jj(&["new", "base"]);
|
||||
fs::write(self.0.join("file"), "left\n").unwrap();
|
||||
self.jj(&["bookmark", "create", "left"]);
|
||||
self.jj(&["new", "base"]);
|
||||
fs::write(self.0.join("file"), "right\n").unwrap();
|
||||
self.jj(&["bookmark", "create", "right"]);
|
||||
self.jj(&["new", "left", "right"]);
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn discovery_is_readonly_and_save_uses_jj_authority_and_stale_guards() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.conflict();
|
||||
let operation = fixture.jj(&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id",
|
||||
]);
|
||||
let workspace = load(&fixture.0, &|| false).unwrap();
|
||||
assert_eq!(workspace.files.len(), 1);
|
||||
let file = &workspace.files[0];
|
||||
assert!(file.sources.iter().any(|s| s.base && s.bytes == b"base\n"));
|
||||
assert!(file.sources.iter().any(|s| !s.base && s.bytes == b"left\n"));
|
||||
assert!(
|
||||
file.sources
|
||||
.iter()
|
||||
.any(|s| !s.base && s.bytes == b"right\n")
|
||||
);
|
||||
for bookmark in ["base", "left", "right"] {
|
||||
assert!(
|
||||
file.sources
|
||||
.iter()
|
||||
.any(|s| s.label.contains(&format!("[{bookmark}]")))
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
operation,
|
||||
fixture.jj(&[
|
||||
"--ignore-working-copy",
|
||||
"op",
|
||||
"log",
|
||||
"--no-graph",
|
||||
"-n",
|
||||
"1",
|
||||
"-T",
|
||||
"id"
|
||||
])
|
||||
);
|
||||
let blocks = regions(file.result.as_ref().unwrap());
|
||||
assert_eq!(blocks.len(), 1);
|
||||
for source in &file.sources {
|
||||
assert_eq!(blocks[0].choose(source).unwrap().as_bytes(), source.bytes);
|
||||
}
|
||||
let mut changed = blocks[0].clone();
|
||||
changed.sides.pop();
|
||||
assert!(changed.choose(&file.sources[0]).is_err());
|
||||
fs::write(fixture.0.join("file"), "external\n").unwrap();
|
||||
assert!(
|
||||
save(&workspace, 0, Resolution::Text("lost\n".into()), &|| false)
|
||||
.unwrap_err()
|
||||
.contains("externally")
|
||||
);
|
||||
fs::write(fixture.0.join("file"), file.result.as_ref().unwrap()).unwrap();
|
||||
fixture.jj(&["new", "base"]);
|
||||
let before = fs::read(fixture.0.join("file")).unwrap();
|
||||
assert!(
|
||||
save(
|
||||
&workspace,
|
||||
0,
|
||||
Resolution::Text("wrong checkout\n".into()),
|
||||
&|| false
|
||||
)
|
||||
.unwrap_err()
|
||||
.contains("checkout changed")
|
||||
);
|
||||
assert_eq!(fs::read(fixture.0.join("file")).unwrap(), before);
|
||||
}
|
||||
#[test]
|
||||
fn text_choice_is_confirmed_by_jj() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.conflict();
|
||||
let mut workspace = load(&fixture.0, &|| false).unwrap();
|
||||
let cancelled_after_write =
|
||||
|| fs::read(fixture.0.join("file")).is_ok_and(|bytes| bytes == b"draft\n");
|
||||
let saved = save(
|
||||
&workspace,
|
||||
0,
|
||||
Resolution::Text("draft\n".into()),
|
||||
&cancelled_after_write,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(saved.file.status, Status::Unconfirmed);
|
||||
assert!(saved.confirmation.is_some());
|
||||
assert_eq!(fs::read(fixture.0.join("file")).unwrap(), b"draft\n");
|
||||
assert_eq!(
|
||||
entries(&fixture.0, &workspace.checkout.commit, &|| false).unwrap(),
|
||||
[PathBuf::from("file")]
|
||||
);
|
||||
workspace.checkout = saved.checkout;
|
||||
workspace.files[0] = saved.file;
|
||||
let outcome = save(
|
||||
&workspace,
|
||||
0,
|
||||
Resolution::Text("resolved\n".into()),
|
||||
&|| false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
outcome.file.status,
|
||||
Status::Resolved,
|
||||
"{:?}",
|
||||
outcome.confirmation
|
||||
);
|
||||
assert_eq!(fs::read(fixture.0.join("file")).unwrap(), b"resolved\n");
|
||||
assert!(
|
||||
entries(&fixture.0, &outcome.checkout.commit, &|| false)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn all_three_sides_and_bases_are_loaded_and_directory_children_are_protected() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.conflict();
|
||||
fixture.jj(&["new", "base"]);
|
||||
fs::write(fixture.0.join("file"), "third\n").unwrap();
|
||||
fixture.jj(&["bookmark", "create", "third"]);
|
||||
fixture.jj(&["new", "left", "right", "third"]);
|
||||
let workspace = load(&fixture.0, &|| false).unwrap();
|
||||
let file = &workspace.files[0];
|
||||
assert_eq!(file.sources.iter().filter(|s| !s.base).count(), 3);
|
||||
assert_eq!(file.sources.iter().filter(|s| s.base).count(), 2);
|
||||
assert!(file.sources.iter().any(|s| s.bytes == b"third\n"));
|
||||
let blocks = regions(file.result.as_ref().unwrap());
|
||||
for source in &file.sources {
|
||||
assert_eq!(blocks[0].choose(source).unwrap().as_bytes(), source.bytes);
|
||||
}
|
||||
fs::remove_file(fixture.0.join("file")).unwrap();
|
||||
fs::create_dir(fixture.0.join("file")).unwrap();
|
||||
fs::write(fixture.0.join("file/untracked"), b"keep my draft").unwrap();
|
||||
let workspace = load(&fixture.0, &|| false).unwrap();
|
||||
assert!(
|
||||
save(&workspace, 0, Resolution::Source(0), &|| false)
|
||||
.unwrap_err()
|
||||
.contains("untracked or modified children")
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("file/untracked")).unwrap(),
|
||||
b"keep my draft"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn binary_symlink_and_deleted_file_choices_preserve_types_and_bytes() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.conflict();
|
||||
fixture.jj(&["edit", "left"]);
|
||||
fs::write(fixture.0.join("binary"), b"left\0\xff").unwrap();
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(fixture.0.join("binary"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink("left-target", fixture.0.join("link")).unwrap();
|
||||
fixture.jj(&["new", "right"]);
|
||||
fs::write(fixture.0.join("binary"), b"right\0\xfe").unwrap();
|
||||
std::os::unix::fs::symlink("right-target", fixture.0.join("link")).unwrap();
|
||||
fixture.jj(&["bookmark", "create", "right-extra"]);
|
||||
fixture.jj(&["new", "left", "right-extra"]);
|
||||
let mut workspace = load(&fixture.0, &|| false).unwrap();
|
||||
for (name, kind, bytes) in [
|
||||
("binary", FileKind::Binary, b"left\0\xff".as_slice()),
|
||||
("link", FileKind::Symlink, b"left-target".as_slice()),
|
||||
] {
|
||||
let file = workspace
|
||||
.files
|
||||
.iter()
|
||||
.position(|f| f.path == Path::new(name))
|
||||
.unwrap();
|
||||
assert!(workspace.files[file].result.is_none());
|
||||
let source = workspace.files[file]
|
||||
.sources
|
||||
.iter()
|
||||
.position(|s| !s.base && s.kind == kind && s.bytes == bytes)
|
||||
.unwrap();
|
||||
assert!(
|
||||
save(
|
||||
&workspace,
|
||||
file,
|
||||
Resolution::Text("not allowed".into()),
|
||||
&|| false
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let outcome = save(&workspace, file, Resolution::Source(source), &|| false).unwrap();
|
||||
assert_eq!(
|
||||
outcome.file.status,
|
||||
Status::Resolved,
|
||||
"{:?}",
|
||||
outcome.confirmation
|
||||
);
|
||||
workspace.checkout = outcome.checkout;
|
||||
workspace.files[file] = outcome.file;
|
||||
if kind == FileKind::Symlink {
|
||||
assert_eq!(
|
||||
fs::read_link(fixture.0.join(name)).unwrap(),
|
||||
Path::new("left-target")
|
||||
);
|
||||
} else {
|
||||
assert_eq!(fs::read(fixture.0.join(name)).unwrap(), bytes);
|
||||
}
|
||||
if kind == FileKind::Binary {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
fs::metadata(fixture.0.join(name))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o111,
|
||||
0o111
|
||||
);
|
||||
}
|
||||
}
|
||||
// add/add conflicts retain an absent base as an explicit deletion choice.
|
||||
let file = workspace
|
||||
.files
|
||||
.iter()
|
||||
.position(|f| f.path == Path::new("binary"))
|
||||
.unwrap();
|
||||
let source = workspace.files[file]
|
||||
.sources
|
||||
.iter()
|
||||
.position(|s| s.kind == FileKind::Deleted)
|
||||
.unwrap();
|
||||
let outcome = save(&workspace, file, Resolution::Source(source), &|| false).unwrap();
|
||||
assert_eq!(
|
||||
outcome.file.status,
|
||||
Status::Resolved,
|
||||
"{:?}",
|
||||
outcome.confirmation
|
||||
);
|
||||
assert!(!fixture.0.join("binary").exists());
|
||||
}
|
||||
#[test]
|
||||
fn marker_styles_widths_multisides_and_missing_eol() {
|
||||
let snapshot = "before\n<<<<<<<<<<< conflict 1 of 1\n+++++++++++ a\nleft\n----------- base\nold\n+++++++++++ b\nright\n----------- base2\nold2\n+++++++++++ c\nthird\n>>>>>>>>>>> conflict 1 of 1 ends\nafter\n";
|
||||
let parsed = regions(snapshot);
|
||||
assert_eq!(parsed[0].lines, 1..13);
|
||||
assert_eq!(parsed[0].sides, ["left\n", "right\n", "third\n"]);
|
||||
assert_eq!(parsed[0].bases, ["old\n", "old2\n"]);
|
||||
let prefixed = format!("<<<<<<< literal marker\n{snapshot}");
|
||||
assert_eq!(regions(&prefixed).len(), 1);
|
||||
assert_eq!(regions(&prefixed)[0].lines, 2..14);
|
||||
let diff = "<<<<<<< conflict 1 of 1\n%%%%%%% diff from: base\n^^^^^^^ to: left\n-old\n+left\n+++++++ right\nright\n>>>>>>> conflict 1 of 1 ends\n";
|
||||
assert_eq!(regions(diff)[0].sides, ["left\n", "right\n"]);
|
||||
let git = "<<<<<<< left\nleft\n||||||| base\nold\n=======\nright\n>>>>>>> right";
|
||||
assert_eq!(regions(git)[0].sides, ["left", "right"]);
|
||||
assert!(regions("<<<<<<< unfinished\nleft\n").is_empty());
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
fn test_sources(sides: usize) -> Vec<Source> {
|
||||
(0..sides * 2 - 1)
|
||||
.map(|index| Source {
|
||||
label: format!("source {index}"),
|
||||
base: index % 2 == 1,
|
||||
kind: FileKind::Text,
|
||||
bytes: b"historical full file; must never replace working text\n".to_vec(),
|
||||
tree_id: String::new(),
|
||||
term: index / 2,
|
||||
sides,
|
||||
bases: sides - 1,
|
||||
node: Node::Absent,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn snapshot(left: &str, base: &str, right: &str) -> String {
|
||||
format!(
|
||||
"<<<<<<< conflict\n+++++++ side 1\n{left}------- base\n{base}+++++++ side 2\n{right}>>>>>>> conflict ends\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_working_projections_keep_partial_resolutions_and_multiple_regions() {
|
||||
let sources = test_sources(2);
|
||||
let raw = format!(
|
||||
"unsaved heading\nalready manually resolved\n{}auto-merged middle\n<<<<<<< conflict\n%%%%%%% Changes from base to side 1\n\\\\\\\\\\\\\\ continuation\n-old two\n+left two\n+++++++ side 2\nright two\n>>>>>>> conflict ends\nunsaved tail",
|
||||
snapshot("left one\n", "old one\n", "right one\n")
|
||||
);
|
||||
for (index, first, second) in [
|
||||
(0, "left one", "left two"),
|
||||
(1, "old one", "old two"),
|
||||
(2, "right one", "right two"),
|
||||
] {
|
||||
assert_eq!(
|
||||
project(&raw, &sources[index]).unwrap(),
|
||||
format!(
|
||||
"unsaved heading\nalready manually resolved\n{first}\nauto-merged middle\n{second}\nunsaved tail"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternatives_are_frozen_from_the_same_working_text_as_the_seed() {
|
||||
let sources = test_sources(2);
|
||||
let raw = format!(
|
||||
"unsaved heading\n{}auto-merged middle\n{}unsaved tail",
|
||||
snapshot("left-one\n", "old-one\n", "right-one\n"),
|
||||
snapshot("left-two\n", "old-two\n", "right-two\n")
|
||||
);
|
||||
let projection = Projection::new(&raw, &sources, 0).unwrap();
|
||||
let mut draft = projection.seed().to_owned();
|
||||
draft = draft.replace("unsaved heading", "later draft edit");
|
||||
draft.push_str("\nnew draft ending\n");
|
||||
assert_eq!(
|
||||
projection.alternative(2).unwrap(),
|
||||
"unsaved heading\nright-one\nauto-merged middle\nright-two\nunsaved tail"
|
||||
);
|
||||
assert_eq!(
|
||||
projection.alternative(1).unwrap(),
|
||||
"unsaved heading\nold-one\nauto-merged middle\nold-two\nunsaved tail"
|
||||
);
|
||||
assert_eq!(
|
||||
projection.seed(),
|
||||
"unsaved heading\nleft-one\nauto-merged middle\nleft-two\nunsaved tail"
|
||||
);
|
||||
assert_eq!(
|
||||
draft,
|
||||
"later draft edit\nleft-one\nauto-merged middle\nleft-two\nunsaved tail\nnew draft ending\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_multiway_sides_and_bases_project_the_same_current_context() {
|
||||
let sources = test_sources(3);
|
||||
let raw = "unsaved α\n<<<<<<<<<<< conflict\n+++++++++++ side 1\none\n----------- base 1\nold one\n+++++++++++ side 2\ntwo\n----------- base 2\nold two\n+++++++++++ side 3\nthree\n>>>>>>>>>>> conflict ends\nunsaved ω";
|
||||
let projection = Projection::new(raw, &sources, 0).unwrap();
|
||||
for (index, choice) in ["one", "old one", "two", "old two", "three"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let expected = format!("unsaved α\n{choice}\nunsaved ω");
|
||||
assert_eq!(project(raw, &sources[index]).unwrap(), expected);
|
||||
assert_eq!(projection.alternative(index).unwrap(), expected);
|
||||
}
|
||||
assert_eq!(
|
||||
Projection::new(raw, &sources, 4).unwrap().seed(),
|
||||
"unsaved α\nthree\nunsaved ω"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projections_preserve_mixed_eof_and_crlf_terms() {
|
||||
let sources = test_sources(2);
|
||||
for eol in ["\n", "\r\n"] {
|
||||
let choices = [
|
||||
format!("left{eol}"),
|
||||
"old".to_owned(),
|
||||
format!("right{eol}{eol}"),
|
||||
];
|
||||
// jj appends one separator EOL to *each* term when any lacks an EOL,
|
||||
// and omits the EOL on the final marker. Existing term EOLs remain.
|
||||
let raw = format!(
|
||||
"heading{eol}<<<<<<< conflict{eol}+++++++ side 1{eol}{}{eol}------- base{eol}{}{eol}+++++++ side 2{eol}{}{eol}>>>>>>> conflict ends",
|
||||
choices[0], choices[1], choices[2]
|
||||
);
|
||||
let projection = Projection::new(&raw, &sources, 0).unwrap();
|
||||
for (index, choice) in choices.iter().enumerate() {
|
||||
assert_eq!(
|
||||
project(&raw, &sources[index]).unwrap(),
|
||||
format!("heading{eol}{choice}")
|
||||
);
|
||||
assert_eq!(
|
||||
projection.alternative(index).unwrap(),
|
||||
format!("heading{eol}{choice}")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_choices_markerfree_text_and_invalid_choices_are_handled() {
|
||||
let mut sources = test_sources(2);
|
||||
sources[1].kind = FileKind::Deleted;
|
||||
let raw = format!("before\n{}after\n", snapshot("", "", "new\n"));
|
||||
let projection = Projection::new(&raw, &sources, 0).unwrap();
|
||||
assert_eq!(projection.seed(), "before\nafter\n");
|
||||
assert_eq!(projection.alternative(1).unwrap(), "before\nafter\n");
|
||||
assert_eq!(projection.alternative(2).unwrap(), "before\nnew\nafter\n");
|
||||
let resolved = Projection::new("manually resolved, no final EOL", &sources, 0).unwrap();
|
||||
assert_eq!(
|
||||
resolved.alternative(2).unwrap(),
|
||||
"manually resolved, no final EOL"
|
||||
);
|
||||
assert!(resolved.alternative(sources.len()).is_err());
|
||||
assert!(Projection::new(&raw, &sources, sources.len()).is_err());
|
||||
assert!(Projection::new(&raw, &test_sources(3), 0).is_err());
|
||||
sources[0].kind = FileKind::Binary;
|
||||
assert!(project(&raw, &sources[0]).is_err());
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,145 @@
|
||||
use super::*;
|
||||
use vamp::{
|
||||
plugin::TextPosition,
|
||||
review::{Anchor, Comment, Side},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn output_filters_resolution_and_extracts_exact_graphemes() {
|
||||
let mut review = Review::new(PathBuf::new());
|
||||
review.storage_id = Some(7);
|
||||
review.storage_revision = 2;
|
||||
review.comments = [false, true]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, resolved)| Comment {
|
||||
id: id as u64 + 1,
|
||||
body: "fix".into(),
|
||||
resolved,
|
||||
anchor: Anchor {
|
||||
revision: "commit".into(),
|
||||
path: "a.rs".into(),
|
||||
side: Side::After,
|
||||
start: TextPosition { row: 0, column: 1 },
|
||||
end: TextPosition { row: 1, column: 1 },
|
||||
content: "xe\u{301}👩💻\n界z\n".into(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let output = envelope(&review, false, true);
|
||||
assert_eq!(output["comments"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(output["comments"][0]["excerpt"], "e\u{301}👩💻\n界");
|
||||
assert!(output["comments"][0]["anchor"].get("content").is_none());
|
||||
assert_eq!(output["counts"]["resolved"], 1);
|
||||
assert_eq!(
|
||||
envelope(&review, true, true)["comments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_storage_is_not_created_and_incompatible_storage_is_preserved() {
|
||||
let directory = std::env::temp_dir().join(format!("vamp-review-cli-{}", std::process::id()));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let absent = directory.join("absent");
|
||||
assert!(Store::open_read_only(&absent).unwrap().is_none());
|
||||
assert!(!absent.exists());
|
||||
let path = directory.join("reviews.sqlite3");
|
||||
std::fs::write(&path, b"incompatible").unwrap();
|
||||
assert!(Store::open_read_only(&directory).is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"incompatible");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let connection = rusqlite::Connection::open(&path).unwrap();
|
||||
connection
|
||||
.execute_batch("CREATE TABLE incompatible (value TEXT); PRAGMA user_version = 42")
|
||||
.unwrap();
|
||||
drop(connection);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert!(
|
||||
Store::open_read_only(&directory)
|
||||
.err()
|
||||
.unwrap()
|
||||
.contains("schema")
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_storage_is_read_only_and_unchanged() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("vamp-review-cli-existing-{}", std::process::id()));
|
||||
let mut store = Store::open(&directory).unwrap();
|
||||
let mut review = Review::new(directory.clone());
|
||||
review.summary = "stored".into();
|
||||
store.save(&mut review).unwrap();
|
||||
drop(store);
|
||||
let path = directory.join("reviews.sqlite3");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
|
||||
}
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
let mut store = Store::open_read_only(&directory).unwrap().unwrap();
|
||||
let mut loaded = store.load(&directory, review.storage_id.unwrap()).unwrap();
|
||||
assert_eq!(loaded.summary, "stored");
|
||||
loaded.summary = "changed".into();
|
||||
assert!(store.save(&mut loaded).is_err());
|
||||
drop(store);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o640
|
||||
);
|
||||
let links = directory.join("links");
|
||||
std::fs::create_dir(&links).unwrap();
|
||||
std::os::unix::fs::symlink(&path, links.join("reviews.sqlite3")).unwrap();
|
||||
assert!(Store::open_read_only(&links).is_err());
|
||||
}
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_mutations_require_positive_explicit_ids_and_reject_all() {
|
||||
for command in ["delete", "resolve"] {
|
||||
for ids in [
|
||||
vec![],
|
||||
vec!["1"],
|
||||
vec!["0", "1"],
|
||||
vec!["-1", "1"],
|
||||
vec!["9223372036854775808", "1"],
|
||||
vec!["all", "1"],
|
||||
vec!["1", "0"],
|
||||
vec!["1", "-1"],
|
||||
vec!["1", "18446744073709551616"],
|
||||
vec!["1", "--json"],
|
||||
] {
|
||||
let mut args = std::iter::once(command).chain(ids).map(OsString::from);
|
||||
assert!(Request::parse(&mut args).is_err());
|
||||
}
|
||||
let mut args = [command, "9223372036854775807", "18446744073709551615"]
|
||||
.into_iter()
|
||||
.map(OsString::from);
|
||||
let mut request = Request::parse(&mut args).unwrap();
|
||||
assert_eq!(request.id, Some(i64::MAX));
|
||||
let (action, id) = request.comment.as_ref().unwrap();
|
||||
assert_eq!(*id, u64::MAX);
|
||||
assert!(matches!(
|
||||
(command, action),
|
||||
("delete", CommentAction::Delete) | ("resolve", CommentAction::Resolve)
|
||||
));
|
||||
assert!(request.option(OsStr::new("--all"), &mut args).is_err());
|
||||
request.option(OsStr::new("--json"), &mut args).unwrap();
|
||||
let mut repo = [OsString::from("checkout")].into_iter();
|
||||
request.option(OsStr::new("--repo"), &mut repo).unwrap();
|
||||
assert!(request.json);
|
||||
assert_eq!(request.repo, Some(PathBuf::from("checkout")));
|
||||
}
|
||||
}
|
||||
+2501
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
use super::*;
|
||||
use std::{
|
||||
fs,
|
||||
path::Path,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
loop {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"vamp-shell-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
match fs::create_dir(&root) {
|
||||
Ok(()) => return Self(fs::canonicalize(root).unwrap()),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("Cannot create shell fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn start(command: &str, root: &Path) -> Worker {
|
||||
Worker::start_with_shell(command.into(), root.into(), "/bin/sh".into()).unwrap()
|
||||
}
|
||||
|
||||
fn wait_for<T>(mut ready: impl FnMut() -> Option<T>) -> T {
|
||||
// File gates determine ordering; this deadline only bounds a stuck test.
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
if let Some(value) = ready() {
|
||||
return value;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "Shell fixture did not progress");
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn process_running(pid: &str) -> bool {
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-o", "stat=", "-p", pid])
|
||||
.output()
|
||||
.unwrap();
|
||||
let state = String::from_utf8(output.stdout).unwrap();
|
||||
let state = state.trim();
|
||||
// An orphan may await the system reaper, but a zombie cannot keep running
|
||||
// or retain the inherited output descriptors.
|
||||
!state.is_empty() && !state.starts_with('Z')
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_is_pending_until_gate_and_preserves_cwd_streams_status_and_null_stdin() {
|
||||
let fixture = Fixture::new();
|
||||
let mut worker = start(
|
||||
"printf '%s\\n' \"$PWD\"; : > ready; \
|
||||
while [ ! -e release ]; do :; done; \
|
||||
if read value; then exit 99; fi; \
|
||||
printf 'out\\000bytes'; printf 'err\\000bytes' >&2; exit 7",
|
||||
&fixture.0,
|
||||
);
|
||||
wait_for(|| fixture.0.join("ready").exists().then_some(()));
|
||||
assert!(worker.poll().is_none());
|
||||
fs::write(fixture.0.join("release"), b"").unwrap();
|
||||
let output = wait_for(|| worker.poll()).unwrap();
|
||||
let mut expected = fixture.0.as_os_str().as_encoded_bytes().to_vec();
|
||||
expected.extend_from_slice(b"\nout\0bytes");
|
||||
assert_eq!(output.stdout, expected);
|
||||
assert_eq!(output.stderr, b"err\0bytes");
|
||||
assert_eq!(output.code, Some(7));
|
||||
assert!(worker.poll().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_reports_spawn_failure() {
|
||||
let fixture = Fixture::new();
|
||||
let mut worker = start("exit 0", &fixture.0.join("missing"));
|
||||
let error = wait_for(|| worker.poll()).unwrap_err();
|
||||
assert!(error.starts_with("Cannot start shell command:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_shell_worker_reports_one_failure() {
|
||||
let (cancel, _cancelled) = mpsc::channel();
|
||||
let (send, results) = mpsc::channel();
|
||||
drop(send);
|
||||
let mut worker = Worker {
|
||||
cancel,
|
||||
results,
|
||||
thread: None,
|
||||
finished: false,
|
||||
};
|
||||
assert_eq!(
|
||||
worker.poll().unwrap().unwrap_err(),
|
||||
"Shell worker stopped unexpectedly"
|
||||
);
|
||||
assert!(worker.poll().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_drains_both_streams_concurrently_with_explicit_bounded_capture() {
|
||||
let fixture = Fixture::new();
|
||||
let mut worker = start(
|
||||
"(dd if=/dev/zero bs=1024 count=4097 2>/dev/null) & \
|
||||
(dd if=/dev/zero bs=1024 count=4097 2>/dev/null) >&2 & wait",
|
||||
&fixture.0,
|
||||
);
|
||||
let output = wait_for(|| worker.poll()).unwrap();
|
||||
assert_eq!(output.code, Some(0));
|
||||
for bytes in [output.stdout, output.stderr] {
|
||||
assert_eq!(bytes.len(), OUTPUT_LIMIT + TRUNCATION_NOTE.len());
|
||||
assert!(bytes[..OUTPUT_LIMIT].iter().all(|byte| *byte == 0));
|
||||
assert_eq!(&bytes[OUTPUT_LIMIT..], TRUNCATION_NOTE);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_shell_kills_and_reaps_group_with_pipe_inheriting_descendant() {
|
||||
let fixture = Fixture::new();
|
||||
let worker = start(
|
||||
"/bin/sh -c 'printf \"%s\" \"$$\" > descendant; : > ready; \
|
||||
while [ ! -e release ]; do :; done' & \
|
||||
printf '%s' \"$$\" > leader; wait",
|
||||
&fixture.0,
|
||||
);
|
||||
wait_for(|| fixture.0.join("ready").exists().then_some(()));
|
||||
let descendant = fs::read_to_string(fixture.0.join("descendant")).unwrap();
|
||||
let leader = wait_for(|| {
|
||||
fs::read_to_string(fixture.0.join("leader"))
|
||||
.ok()
|
||||
.filter(|pid| !pid.is_empty())
|
||||
});
|
||||
let (done, dropped) = mpsc::channel();
|
||||
let dropper = thread::spawn(move || {
|
||||
drop(worker);
|
||||
done.send(()).unwrap();
|
||||
});
|
||||
dropped.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
dropper.join().unwrap();
|
||||
wait_for(|| (!process_running(&descendant)).then_some(()));
|
||||
let leader_status = Command::new("/bin/ps")
|
||||
.args(["-o", "stat=", "-p", &leader])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
leader_status.stdout.is_empty(),
|
||||
"Shell leader was not reaped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_shell_does_not_leave_background_jobs_holding_output_open() {
|
||||
let fixture = Fixture::new();
|
||||
let mut worker = start(
|
||||
"/bin/sh -c 'printf \"%s\" \"$$\" > descendant; : > ready; \
|
||||
while [ ! -e release ]; do :; done' & \
|
||||
while [ ! -e ready ]; do :; done; printf done",
|
||||
&fixture.0,
|
||||
);
|
||||
let output = wait_for(|| worker.poll()).unwrap();
|
||||
assert_eq!(output.code, Some(0));
|
||||
assert_eq!(output.stdout, b"done");
|
||||
let descendant = fs::read_to_string(fixture.0.join("descendant")).unwrap();
|
||||
wait_for(|| (!process_running(&descendant)).then_some(()));
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grammar_expands_nested_mirrors_choices_variables_and_normalized_offsets() {
|
||||
let (text, snippet) = expand(
|
||||
"call($1, ${1:λ${2:x}}, ${3|a\\,b,c|}, ${UNKNOWN:${TM_LINE_NUMBER}})\r\n$0\\$",
|
||||
|name| (name == "TM_LINE_NUMBER").then(|| "4".to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(text, "call(λx, λx, a,b, 4)\n$");
|
||||
assert_eq!(
|
||||
snippet.tabstops,
|
||||
vec![
|
||||
SnippetTabstop {
|
||||
index: 1,
|
||||
ranges: vec![5..8, 10..13],
|
||||
ancestors: vec![vec![], vec![]]
|
||||
},
|
||||
SnippetTabstop {
|
||||
index: 2,
|
||||
ranges: vec![7..8, 12..13],
|
||||
ancestors: vec![vec![1], vec![1]]
|
||||
},
|
||||
SnippetTabstop {
|
||||
index: 3,
|
||||
ranges: vec![15..18],
|
||||
ancestors: vec![vec![]]
|
||||
},
|
||||
SnippetTabstop {
|
||||
index: 0,
|
||||
ranges: vec![23..23],
|
||||
ancestors: vec![vec![]]
|
||||
},
|
||||
]
|
||||
);
|
||||
let (text, snippet) = expand("call($1, ${2})", |_| None).unwrap();
|
||||
assert_eq!(text, "call(, )");
|
||||
assert_eq!(
|
||||
snippet.tabstops,
|
||||
vec![
|
||||
SnippetTabstop {
|
||||
index: 1,
|
||||
ranges: vec![5..5],
|
||||
ancestors: vec![vec![]]
|
||||
},
|
||||
SnippetTabstop {
|
||||
index: 2,
|
||||
ranges: vec![7..7],
|
||||
ancestors: vec![vec![]]
|
||||
},
|
||||
SnippetTabstop {
|
||||
index: 0,
|
||||
ranges: vec![8..8],
|
||||
ancestors: vec![vec![]]
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
expand("${KNOWN:${1:hidden}}$1", |name| {
|
||||
(name == "KNOWN").then(|| "shown".to_owned())
|
||||
})
|
||||
.unwrap()
|
||||
.0,
|
||||
"shown"
|
||||
);
|
||||
let (text, snippet) = expand("call(${CTX})$1", |name| {
|
||||
(name == "CTX").then(|| "a\r\nb\rc".to_owned())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(text, "call(a\nb\nc)");
|
||||
assert_eq!(snippet.tabstops[0].ranges, [11..11]);
|
||||
assert_eq!(
|
||||
expand("${1|a\\|b,c|}\\}\\\\", |_| None).unwrap().0,
|
||||
"a|b}\\"
|
||||
);
|
||||
for input in ["${1", "${1:$1}", "${1:a}${1:b}$1", "${1:e}\u{301}"] {
|
||||
if input == "${1:a}${1:b}$1" {
|
||||
assert_eq!(expand(input, |_| None).unwrap().0, "aaa");
|
||||
} else {
|
||||
assert_eq!(expand(input, |_| None), Err(Error::Invalid));
|
||||
}
|
||||
}
|
||||
let (text, snippet) = expand("${1}$1", |_| None).unwrap();
|
||||
assert!(text.is_empty());
|
||||
assert_eq!(
|
||||
snippet.tabstops[0],
|
||||
SnippetTabstop {
|
||||
index: 1,
|
||||
ranges: vec![0..0, 0..0],
|
||||
ancestors: vec![vec![], vec![]],
|
||||
}
|
||||
);
|
||||
for input in [
|
||||
"$UNKNOWN",
|
||||
"${TM_FILENAME/(.*)/$1/}",
|
||||
"${1/a/b/}",
|
||||
"${1:a$0b}",
|
||||
"$0$0",
|
||||
"${0:arg}",
|
||||
"${0:$1}",
|
||||
] {
|
||||
assert_eq!(expand(input, |_| None), Err(Error::Unsupported));
|
||||
}
|
||||
assert_eq!(
|
||||
expand(&"$1".repeat(MAX_STOPS + 1), |_| None),
|
||||
Err(Error::Limit)
|
||||
);
|
||||
assert_eq!(
|
||||
expand(
|
||||
&format!(
|
||||
"{}x{}",
|
||||
"${1:".repeat(MAX_DEPTH + 1),
|
||||
"}".repeat(MAX_DEPTH + 1)
|
||||
),
|
||||
|_| None
|
||||
),
|
||||
Err(Error::Limit)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,75 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selected_files_and_auxiliary_grammars_are_registered() {
|
||||
for (filename, language) in [
|
||||
("main.rs", "Rust"),
|
||||
("Gemfile", "Ruby"),
|
||||
("main.py", "Python"),
|
||||
("package.json", "JSON"),
|
||||
(".bashrc", "Bash"),
|
||||
("GNUmakefile", "Makefile"),
|
||||
("README.md", "Markdown"),
|
||||
("main.jsx", "JavaScript"),
|
||||
("main.ts", "TypeScript"),
|
||||
("index.html", "HTML"),
|
||||
("style.css", "CSS"),
|
||||
("config.yml", "YAML"),
|
||||
("Cargo.toml", "TOML"),
|
||||
("Cargo.lock", "TOML"),
|
||||
("main.c", "C"),
|
||||
("main.cpp", "C++"),
|
||||
("main.C", "C++"),
|
||||
("main.go", "Go"),
|
||||
("main.zig", "Zig"),
|
||||
("main.typ", "Typst"),
|
||||
("main.TYP", "Typst"),
|
||||
] {
|
||||
assert_eq!(
|
||||
detect(Some(Path::new(filename)), None).map(|spec| spec.name),
|
||||
Some(language)
|
||||
);
|
||||
}
|
||||
let ts = detect(Some(Path::new("main.ts")), None).unwrap();
|
||||
let tsx = detect(Some(Path::new("main.tsx")), None).unwrap();
|
||||
assert_eq!(ts.name, tsx.name);
|
||||
assert!(!std::ptr::eq(ts, tsx));
|
||||
assert_ne!(ts.language, tsx.language);
|
||||
assert!(std::ptr::eq(tsx, by_name("TSX").unwrap()));
|
||||
assert!(by_name("markdown_inline").is_some());
|
||||
for filename in [
|
||||
"notes.txt",
|
||||
"main.hs",
|
||||
"main.scala",
|
||||
"main.lua",
|
||||
"Dockerfile",
|
||||
] {
|
||||
assert!(detect(Some(Path::new(filename)), None).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shebangs_support_bom_env_options_and_filename_precedence() {
|
||||
for (line, language) in [
|
||||
("#!/usr/bin/python3", "Python"),
|
||||
("\u{feff}#!/usr/bin/env -S python3.12 -u", "Python"),
|
||||
("#!/usr/bin/env -u PYTHONHOME FOO=bar python3", "Python"),
|
||||
("#!/usr/bin/ruby3.3", "Ruby"),
|
||||
("#!/bin/bash", "Bash"),
|
||||
("#! /usr/bin/env node", "JavaScript"),
|
||||
] {
|
||||
assert_eq!(
|
||||
detect(None, Some(line)).map(|spec| spec.name),
|
||||
Some(language)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
detect(Some(Path::new("main.rs")), Some("#!/bin/bash"))
|
||||
.unwrap()
|
||||
.name,
|
||||
"Rust"
|
||||
);
|
||||
assert!(detect(None, Some("#!/usr/bin/python-not-real")).is_none());
|
||||
assert!(detect(None, Some("#!/usr/bin/perl")).is_none());
|
||||
assert!(detect(None, Some("plain text")).is_none());
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
use super::*;
|
||||
use crossterm::event::{KeyEvent, MouseEvent, MouseEventKind};
|
||||
|
||||
fn key(code: KeyCode, modifiers: KeyModifiers) -> Event {
|
||||
Event::Key(KeyEvent::new(code, modifiers))
|
||||
}
|
||||
|
||||
fn bytes(collector: &mut TerminalColors, text: &str, now: Instant) {
|
||||
for ch in text.chars() {
|
||||
let modifiers = if ch.is_ascii_uppercase() {
|
||||
KeyModifiers::SHIFT
|
||||
} else {
|
||||
KeyModifiers::NONE
|
||||
};
|
||||
collector.push(key(KeyCode::Char(ch), modifiers), now);
|
||||
}
|
||||
}
|
||||
|
||||
fn report(collector: &mut TerminalColors, body: &str, now: Instant) {
|
||||
collector.push(key(KeyCode::Char(']'), KeyModifiers::ALT), now);
|
||||
bytes(collector, body, now);
|
||||
collector.push(key(KeyCode::Char('g'), KeyModifiers::CONTROL), now);
|
||||
}
|
||||
|
||||
fn drain(collector: &mut TerminalColors) -> Vec<Event> {
|
||||
std::iter::from_fn(|| collector.pop()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragmented_triple_accepts_bel_and_both_st_encodings() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
collector.query(&mut Vec::new(), now).unwrap();
|
||||
collector.push(key(KeyCode::Esc, KeyModifiers::NONE), now);
|
||||
collector.push(
|
||||
key(KeyCode::Char(']'), KeyModifiers::NONE),
|
||||
now + Duration::from_millis(1),
|
||||
);
|
||||
bytes(
|
||||
&mut collector,
|
||||
"11;rgb:0/12/345",
|
||||
now + Duration::from_millis(2),
|
||||
);
|
||||
collector.push(
|
||||
key(KeyCode::Esc, KeyModifiers::NONE),
|
||||
now + Duration::from_millis(3),
|
||||
);
|
||||
collector.push(
|
||||
key(KeyCode::Char('\\'), KeyModifiers::NONE),
|
||||
now + Duration::from_millis(4),
|
||||
);
|
||||
assert_eq!(collector.colors, None);
|
||||
report(
|
||||
&mut collector,
|
||||
"4;2;rgb:f/ffff/ABCD",
|
||||
now + Duration::from_millis(5),
|
||||
);
|
||||
collector.push(
|
||||
key(KeyCode::Char(']'), KeyModifiers::ALT),
|
||||
now + Duration::from_millis(6),
|
||||
);
|
||||
bytes(
|
||||
&mut collector,
|
||||
"4;1;#FF1234",
|
||||
now + Duration::from_millis(7),
|
||||
);
|
||||
collector.push(
|
||||
key(KeyCode::Char('\\'), KeyModifiers::ALT),
|
||||
now + Duration::from_millis(8),
|
||||
);
|
||||
assert_eq!(
|
||||
collector.colors,
|
||||
Some(ThemeColors {
|
||||
background: [0, 18, 52],
|
||||
red: [255, 18, 52],
|
||||
green: [255, 255, 171],
|
||||
})
|
||||
);
|
||||
assert!(drain(&mut collector).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_refresh_atomically_replaces_light_and_dark_triples() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
let palettes = [
|
||||
("11;#FDF6E3", [253, 246, 227]),
|
||||
("11;rgb:0000/0000/0000", [0, 0, 0]),
|
||||
];
|
||||
for (cycle, (background, expected)) in palettes.into_iter().enumerate() {
|
||||
let time = now + Duration::from_secs(cycle as u64);
|
||||
let focus = Event::FocusGained;
|
||||
collector.push(focus.clone(), time);
|
||||
assert_eq!(collector.pop(), Some(focus));
|
||||
let previous = collector.colors;
|
||||
collector.query(&mut Vec::new(), time).unwrap();
|
||||
report(&mut collector, "4;1;rgb:ff/00/00", time);
|
||||
report(&mut collector, background, time);
|
||||
assert_eq!(collector.colors, previous);
|
||||
report(&mut collector, "4;2;rgb:00/ff/00", time);
|
||||
assert_eq!(
|
||||
collector.colors,
|
||||
Some(ThemeColors {
|
||||
background: expected,
|
||||
red: [255, 0, 0],
|
||||
green: [0, 255, 0],
|
||||
})
|
||||
);
|
||||
assert!(drain(&mut collector).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_refresh_detects_silent_change_without_overlapping_queries() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
let mut output = Vec::new();
|
||||
assert!(collector.refresh_due(now));
|
||||
collector.query(&mut output, now).unwrap();
|
||||
report(&mut collector, "11;#101010", now);
|
||||
report(&mut collector, "4;1;#FF0000", now);
|
||||
report(&mut collector, "4;2;#00FF00", now);
|
||||
let previous = collector.colors;
|
||||
assert!(previous.is_some());
|
||||
|
||||
// The terminal changes its palette without emitting a notification.
|
||||
let refresh = now + Duration::from_secs(1);
|
||||
assert!(!collector.refresh_due(refresh - Duration::from_nanos(1)));
|
||||
assert!(collector.refresh_due(refresh));
|
||||
collector.query(&mut output, refresh).unwrap();
|
||||
report(&mut collector, "11;#EEEEEE", refresh);
|
||||
report(&mut collector, "4;1;#AA1122", refresh);
|
||||
assert_eq!(collector.colors, previous);
|
||||
let typed = key(KeyCode::Char('i'), KeyModifiers::NONE);
|
||||
collector.push(typed.clone(), refresh);
|
||||
assert_eq!(drain(&mut collector), vec![typed]);
|
||||
|
||||
// Even an overdue probe must wait until the incomplete query expires.
|
||||
let retry = refresh + Duration::from_secs(1);
|
||||
assert!(!collector.refresh_due(retry));
|
||||
collector.expire(retry);
|
||||
assert_eq!(collector.colors, None);
|
||||
assert!(collector.refresh_due(retry));
|
||||
collector.query(&mut output, retry).unwrap();
|
||||
report(&mut collector, "11;#EEEEEE", retry);
|
||||
report(&mut collector, "4;1;#AA1122", retry);
|
||||
assert_eq!(collector.colors, None);
|
||||
report(&mut collector, "4;2;#22BB33", retry);
|
||||
assert_eq!(
|
||||
collector.colors,
|
||||
Some(ThemeColors {
|
||||
background: [238, 238, 238],
|
||||
red: [170, 17, 34],
|
||||
green: [34, 187, 51],
|
||||
})
|
||||
);
|
||||
assert!(drain(&mut collector).is_empty());
|
||||
assert!(!collector.refresh_due(retry + Duration::from_millis(999)));
|
||||
assert!(collector.refresh_due(retry + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_refresh_clears_stale_colors_and_consumes_late_partial_reply() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
collector.query(&mut Vec::new(), now).unwrap();
|
||||
report(&mut collector, "11;#101010", now);
|
||||
report(&mut collector, "4;1;#FF0000", now);
|
||||
report(&mut collector, "4;2;#00FF00", now);
|
||||
assert!(collector.colors.is_some());
|
||||
let refresh = now + Duration::from_secs(1);
|
||||
collector.query(&mut Vec::new(), refresh).unwrap();
|
||||
report(&mut collector, "11;#EEEEEE", refresh);
|
||||
collector.push(key(KeyCode::Char(']'), KeyModifiers::ALT), refresh);
|
||||
bytes(&mut collector, "4;1;rgb:ffff/", refresh);
|
||||
collector.expire(refresh + QUERY_TIMEOUT);
|
||||
assert_eq!(collector.colors, None);
|
||||
let late = refresh + Duration::from_secs(1);
|
||||
bytes(&mut collector, "0000/0000", late);
|
||||
collector.push(key(KeyCode::Esc, KeyModifiers::NONE), late);
|
||||
collector.expire(late + Duration::from_secs(1));
|
||||
collector.push(
|
||||
key(KeyCode::Char('\\'), KeyModifiers::NONE),
|
||||
late + Duration::from_secs(1),
|
||||
);
|
||||
report(&mut collector, "4;2;#00FF00", late + Duration::from_secs(1));
|
||||
assert_eq!(collector.colors, None);
|
||||
assert!(drain(&mut collector).is_empty());
|
||||
let typed = key(KeyCode::Char('i'), KeyModifiers::NONE);
|
||||
collector.push(typed.clone(), late + Duration::from_secs(2));
|
||||
assert_eq!(collector.pop(), Some(typed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_events_and_rejected_candidates_replay_exactly() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
collector.query(&mut Vec::new(), now).unwrap();
|
||||
let events = vec![
|
||||
key(KeyCode::Char(']'), KeyModifiers::ALT),
|
||||
key(KeyCode::Char('4'), KeyModifiers::NONE),
|
||||
key(KeyCode::Char(';'), KeyModifiers::NONE),
|
||||
key(KeyCode::Char('3'), KeyModifiers::NONE),
|
||||
key(KeyCode::Char('g'), KeyModifiers::CONTROL),
|
||||
key(KeyCode::Char(']'), KeyModifiers::ALT | KeyModifiers::SHIFT),
|
||||
Event::Key(KeyEvent::new_with_kind(
|
||||
KeyCode::Char(']'),
|
||||
KeyModifiers::ALT,
|
||||
KeyEventKind::Release,
|
||||
)),
|
||||
Event::Key(KeyEvent::new_with_kind(
|
||||
KeyCode::Char('A'),
|
||||
KeyModifiers::SHIFT,
|
||||
KeyEventKind::Repeat,
|
||||
)),
|
||||
Event::Key(KeyEvent {
|
||||
code: KeyCode::Char('a'),
|
||||
modifiers: KeyModifiers::CONTROL,
|
||||
kind: KeyEventKind::Press,
|
||||
state: KeyEventState::CAPS_LOCK,
|
||||
}),
|
||||
Event::Mouse(MouseEvent {
|
||||
kind: MouseEventKind::Moved,
|
||||
column: 2,
|
||||
row: 3,
|
||||
modifiers: KeyModifiers::CONTROL,
|
||||
}),
|
||||
Event::FocusLost,
|
||||
Event::Resize(80, 24),
|
||||
key(KeyCode::Char(']'), KeyModifiers::ALT),
|
||||
Event::Paste("\x1b]11;rgb:ff/ff/ff\x07".into()),
|
||||
Event::FocusGained,
|
||||
];
|
||||
for event in &events {
|
||||
collector.push(event.clone(), now);
|
||||
}
|
||||
assert_eq!(drain(&mut collector), events);
|
||||
assert_eq!(collector.colors, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_oversized_reports_and_lone_escape_do_not_eat_input() {
|
||||
let now = Instant::now();
|
||||
let mut collector = TerminalColors::default();
|
||||
for body in [
|
||||
"11;rgb:12345/0/0",
|
||||
"11;rgb:1//3",
|
||||
"11;#12345",
|
||||
"11;rgb:1/2/3/4",
|
||||
] {
|
||||
let mut expected = vec![key(KeyCode::Char(']'), KeyModifiers::ALT)];
|
||||
expected.extend(
|
||||
body.chars()
|
||||
.map(|ch| key(KeyCode::Char(ch), KeyModifiers::NONE)),
|
||||
);
|
||||
expected.push(key(KeyCode::Char('g'), KeyModifiers::CONTROL));
|
||||
for event in &expected {
|
||||
collector.push(event.clone(), now);
|
||||
}
|
||||
assert_eq!(drain(&mut collector), expected);
|
||||
}
|
||||
let escape = key(KeyCode::Esc, KeyModifiers::NONE);
|
||||
collector.push(escape.clone(), now);
|
||||
assert_eq!(collector.pop(), None);
|
||||
collector.expire(now + ESCAPE_TIMEOUT);
|
||||
assert_eq!(collector.pop(), Some(escape));
|
||||
assert_eq!(collector.pop(), None);
|
||||
let start = key(KeyCode::Char(']'), KeyModifiers::ALT);
|
||||
collector.push(start.clone(), now + Duration::from_secs(1));
|
||||
collector.expire(now + Duration::from_secs(1) + QUERY_TIMEOUT);
|
||||
assert_eq!(collector.pop(), Some(start));
|
||||
assert_eq!(collector.pop(), None);
|
||||
}
|
||||
+16567
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
use super::*;
|
||||
|
||||
fn layout(text: &str, width: usize) -> Vec<Segment> {
|
||||
let mut cache = WrapCache::default();
|
||||
cache.prepare((1, 0), width);
|
||||
cache.segments(0, text).to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_and_long_words_preserve_every_source_cell() {
|
||||
assert_eq!(
|
||||
layout("one two three", 8),
|
||||
vec![Segment { start: 0, end: 8 }, Segment { start: 8, end: 13 },]
|
||||
);
|
||||
let segments = layout("abcdefgh", 3);
|
||||
assert_eq!(
|
||||
segments,
|
||||
vec![
|
||||
Segment { start: 0, end: 3 },
|
||||
Segment { start: 3, end: 6 },
|
||||
Segment { start: 6, end: 8 },
|
||||
]
|
||||
);
|
||||
assert_eq!(caret_segment(&segments, 3), 1);
|
||||
assert_eq!(caret_segment(&segments, 8), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_words_do_not_wrap_indentation_onto_an_empty_visual_row() {
|
||||
for source in [
|
||||
" abcdefghijk",
|
||||
"\tabcdefghijk",
|
||||
"head abcdefghijk",
|
||||
] {
|
||||
let expanded = source.replace('\t', " ");
|
||||
let segments = layout(source, 8);
|
||||
assert_eq!(segments.first().unwrap().start, 0);
|
||||
assert_eq!(segments.last().unwrap().end, expanded.len());
|
||||
assert!(segments.windows(2).all(|pair| pair[0].end == pair[1].start));
|
||||
for segment in segments
|
||||
.iter()
|
||||
.filter(|segment| segment.start < segment.end)
|
||||
{
|
||||
assert!(
|
||||
!expanded[segment.start..segment.end].trim().is_empty(),
|
||||
"whitespace-only visual row {segment:?} in {source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_use_source_stops_and_unicode_graphemes_remain_intact() {
|
||||
assert_eq!(
|
||||
layout("ab\t界e\u{301} z", 4),
|
||||
vec![
|
||||
Segment { start: 0, end: 4 },
|
||||
Segment { start: 4, end: 8 },
|
||||
Segment { start: 8, end: 9 },
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
layout("界界界", 3),
|
||||
vec![
|
||||
Segment { start: 0, end: 2 },
|
||||
Segment { start: 2, end: 4 },
|
||||
Segment { start: 4, end: 6 },
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
layout(" \t ", 3),
|
||||
vec![Segment { start: 0, end: 3 }, Segment { start: 3, end: 5 },]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_tabs_preserve_all_expanded_cells_at_original_stops() {
|
||||
assert_eq!(
|
||||
layout("\tX", 2),
|
||||
[
|
||||
Segment { start: 0, end: 2 },
|
||||
Segment { start: 2, end: 4 },
|
||||
Segment { start: 4, end: 5 },
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
layout("a\tX", 2),
|
||||
[
|
||||
Segment { start: 0, end: 1 },
|
||||
Segment { start: 1, end: 3 },
|
||||
Segment { start: 3, end: 5 },
|
||||
Segment { start: 5, end: 5 },
|
||||
]
|
||||
);
|
||||
for source in ["\t", "a\t", "ab\tX", "\t\tX"] {
|
||||
let segments = layout(source, 1);
|
||||
assert!(
|
||||
segments
|
||||
.iter()
|
||||
.all(|segment| segment.end - segment.start <= 1)
|
||||
);
|
||||
assert!(segments.windows(2).all(|pair| pair[0].end == pair[1].start));
|
||||
let end = source.graphemes(true).fold(0, |column, grapheme| {
|
||||
column
|
||||
+ if grapheme == "\t" {
|
||||
TAB_WIDTH - column % TAB_WIDTH
|
||||
} else {
|
||||
1
|
||||
}
|
||||
});
|
||||
assert_eq!(segments.last().unwrap(), &Segment { start: end, end });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_lines_have_an_insertion_cell_and_cache_invalidation_is_lazy() {
|
||||
let mut cache = WrapCache::default();
|
||||
cache.prepare((7, 2), 4);
|
||||
assert_eq!(
|
||||
cache.segments(90, "abcd"),
|
||||
[Segment { start: 0, end: 4 }, Segment { start: 4, end: 4 },]
|
||||
);
|
||||
assert_eq!(caret_segment(cache.segments(90, "abcd"), 4), 1);
|
||||
assert_eq!(cache.rows.len(), 1);
|
||||
cache.prepare((7, 2), 4);
|
||||
assert_eq!(cache.rows.len(), 1);
|
||||
cache.prepare((7, 2), 8);
|
||||
assert!(cache.rows.is_empty());
|
||||
cache.segments(90, "abcd");
|
||||
cache.prepare((7, 3), 8);
|
||||
assert!(cache.rows.is_empty());
|
||||
assert_eq!(layout("", 0), [Segment { start: 0, end: 0 }]);
|
||||
}
|
||||
Vendored
+82
@@ -0,0 +1,82 @@
|
||||
[package]
|
||||
name = "crossterm"
|
||||
version = "0.29.0"
|
||||
authors = ["T. Post"]
|
||||
description = "A crossplatform terminal library for manipulating terminals."
|
||||
repository = "https://github.com/crossterm-rs/crossterm"
|
||||
documentation = "https://docs.rs/crossterm/"
|
||||
license = "MIT"
|
||||
keywords = ["event", "color", "cli", "input", "terminal"]
|
||||
exclude = ["target", "Cargo.lock"]
|
||||
readme = false
|
||||
edition = "2021"
|
||||
rust-version = "1.63.0"
|
||||
categories = ["command-line-interface", "command-line-utilities"]
|
||||
|
||||
[lib]
|
||||
name = "crossterm"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[features]
|
||||
default = ["bracketed-paste", "events", "windows", "derive-more"]
|
||||
|
||||
#! ### Default features
|
||||
## Enables triggering [`Event::Paste`](event::Event::Paste) when pasting text into the terminal.
|
||||
bracketed-paste = []
|
||||
|
||||
## Enables reading input/events from the system using the [`event`] module.
|
||||
events = ["dep:mio", "dep:signal-hook", "dep:signal-hook-mio"]
|
||||
|
||||
## Enables windows specific crates.
|
||||
windows = ["dep:winapi", "dep:crossterm_winapi"]
|
||||
|
||||
#! ### Optional Features
|
||||
|
||||
## Enables the [EventStream](event::EventStream) struct for async event reading.
|
||||
event-stream = ["dep:futures-core", "events"]
|
||||
|
||||
## Enables [`serde`] for various types.
|
||||
serde = ["dep:serde", "bitflags/serde"]
|
||||
|
||||
## Enables raw file descriptor polling / selecting instead of mio.
|
||||
use-dev-tty = ["filedescriptor", "rustix/process"]
|
||||
|
||||
## Enables `is_*` helper functions for event enums.
|
||||
derive-more = ["dep:derive_more"]
|
||||
|
||||
## Enables interacting with a host clipboard via [`clipboard`](clipboard/index.html)
|
||||
osc52 = ["dep:base64"]
|
||||
|
||||
[dependencies]
|
||||
base64 = { version = "0.22", optional = true }
|
||||
bitflags = { version = "2.9" }
|
||||
derive_more = { version = "2.0.0", features = ["is_variant"], optional = true }
|
||||
document-features = "0.2.11"
|
||||
futures-core = { version = "0.3", optional = true, default-features = false }
|
||||
parking_lot = "0.12"
|
||||
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||
|
||||
# Windows dependencies
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
crossterm_winapi = { version = "0.9.1", optional = true }
|
||||
winapi = { version = "0.3.9", optional = true, features = ["winuser", "winerror"] }
|
||||
|
||||
# UNIX dependencies
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
filedescriptor = { version = "0.8", optional = true }
|
||||
# Default to using rustix for UNIX systems, but provide an option to use libc for backwards
|
||||
# compatibility.
|
||||
libc = { version = "0.2", default-features = false, optional = true }
|
||||
mio = { version = "1.0", features = ["os-poll"], optional = true }
|
||||
rustix = { version = "1", default-features = false, features = ["std", "stdio", "termios"] }
|
||||
signal-hook = { version = "0.3.17", optional = true }
|
||||
signal-hook-mio = { version = "0.2.4", features = ["support-v1_0"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0"
|
||||
serial_test = "3.0.0"
|
||||
temp-env = "0.3.6"
|
||||
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Timon
|
||||
|
||||
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.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user