Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

chore: Format the codebase with oxfmt and check formatting in CI (#135)

Jaw55836e1b4961
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 958afa288..5aed379ea 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -81,6 +81,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
+ - run: pnpm format:check
- run: pnpm test
- run: pnpm build
diff --git a/.oxfmtrc.json b/.oxfmtrc.json
index e80c8f349..758635b69 100644
--- a/.oxfmtrc.json
+++ b/.oxfmtrc.json
@@ -5,5 +5,22 @@
"singleQuote": false,
"trailingComma": "all",
"sortPackageJson": false,
- "ignorePatterns": ["dist", "target", "src/bindings.ts", "pnpm-lock.yaml", "**/*.toml"]
+ "ignorePatterns": [
+ "dist",
+ "target",
+ "src/bindings.ts",
+ "docs/plugins/themes.md",
+ "pnpm-lock.yaml",
+ "**/*.toml",
+ "fixtures",
+ "crates/**/tests/fixtures"
+ ],
+ "overrides": [
+ {
+ "files": ["**/*.md"],
+ "options": {
+ "embeddedLanguageFormatting": "off"
+ }
+ }
+ ]
}
diff --git a/README.md b/README.md
index 0a424820c..af53c1de2 100644
--- a/README.md
+++ b/README.md
@@ -30,14 +30,14 @@ for 60+ languages. Builds for macOS, Windows and Linux.
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
with warm caches, median of 5 runs:
-| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
-|---|---|---|
-| Window with the project | **0.9 s** | 3.1 s |
-| Ready (CPU settled) | **1.1 s** | 13.2 s |
-| Memory (USS, all processes) | **169 MB** | 2011 MB |
-| CPU time until ready | **2.4 s** | 47.9 s |
-| Idle CPU | **4 %** of a core | 7 % of a core |
-| Quit | **0.3 s** | 5.9 s |
+| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
+| --------------------------- | ----------------- | ---------------------- |
+| Window with the project | **0.9 s** | 3.1 s |
+| Ready (CPU settled) | **1.1 s** | 13.2 s |
+| Memory (USS, all processes) | **169 MB** | 2011 MB |
+| CPU time until ready | **2.4 s** | 47.9 s |
+| Idle CPU | **4 %** of a core | 7 % of a core |
+| Quit | **0.3 s** | 5.9 s |
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
Windows 11, 32-core AMD, 62 GB RAM.
diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md
index 202e475bc..df0396a90 100644
--- a/THIRD_PARTY_LICENSES.md
+++ b/THIRD_PARTY_LICENSES.md
@@ -116,7 +116,7 @@ Apache License
Version 2.0, January 2004
-http://www.apache.org/licenses/
+http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
@@ -251,7 +251,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
-
## Chinese UI terminology from Visual Studio Code
Some Simplified Chinese terms in `src/platform/locales/text/zh.json` follow the
diff --git a/docs/themes.md b/docs/themes.md
index 55b0531b0..b4420ad9e 100644
--- a/docs/themes.md
+++ b/docs/themes.md
@@ -87,12 +87,12 @@ terminal is a real xterm renderer, without a native PTY or shell. These images
cover the shell, sidebar, editor, gutter, find matches, terminal, Settings,
focused controls, disabled settings and the selected theme popup.
-| Theme | Workbench, editor and terminal | Settings and theme popup |
-|---|---|---|
+| Theme | Workbench, editor and terminal | Settings and theme popup |
+| --------------- | -------------------------------------------------------- | ---------------------------------------------------- |
| Solarized Light | [Screenshot](media/themes/solarized-light-workbench.png) | [Screenshot](media/themes/solarized-light-popup.png) |
-| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
-| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
-| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
+| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
+| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
+| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
The browser regression also checks refresh / startup cache restoration,
selection visibility, same-kind switches, the quick menu, existing themes,
diff --git a/index.html b/index.html
index 30e7b9125..845b697da 100644
--- a/index.html
+++ b/index.html
@@ -11,11 +11,20 @@
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg class="splash-logo" viewBox="22 24 56 56" aria-hidden="true">
- <rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" /><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" /><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" /><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" /><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" /><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" /><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
+ <rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" />
+ <rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" />
+ <circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" />
+ <rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" />
+ <rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" />
+ <rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" />
+ <circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
</svg>
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
- <path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
+ <path
+ fill="currentColor"
+ d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z"
+ />
</svg>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
diff --git a/package.json b/package.json
index d51e0f5ea..e2a928ac9 100644
--- a/package.json
+++ b/package.json
@@ -14,6 +14,7 @@
"test:watch": "vitest",
"lint": "oxlint",
"format": "oxfmt",
+ "format:check": "oxfmt --check",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
diff --git a/perf/compare/README.md b/perf/compare/README.md
index 304a57926..4d5099fe4 100644
--- a/perf/compare/README.md
+++ b/perf/compare/README.md
@@ -13,15 +13,15 @@ python perf/compare/bench.py ~/src/spring-petclinic --runs 5 --wipe-caches # c
Each run launches the app on the project, waits until it is ready, idles,
closes it, and records:
-| Metric | How |
-|---|---|
-| `window_s` | first visible window whose title matches `window_title` (the project name) |
-| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
-| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
-| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
-| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
-| `exit_s` | until every process has exited |
-| `cache_mb`, install size | `cache_dirs`, `install_dir` |
+| Metric | How |
+| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
+| `window_s` | first visible window whose title matches `window_title` (the project name) |
+| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
+| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
+| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
+| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
+| `exit_s` | until every process has exited |
+| `cache_mb`, install size | `cache_dirs`, `install_dir` |
Apps run interleaved, rotating the order, after `--warmup` discarded runs.
Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
@@ -31,8 +31,8 @@ Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
- Release builds only; a running instance of the same executable (a
`pnpm tauri dev` build too) would take over the launch, so the script refuses.
-- IDEA: open the project once by hand and trust it; turn off *Reopen projects
- on startup* and *Confirm before exiting*; note the version, `-Xmx` and whether
+- IDEA: open the project once by hand and trust it; turn off _Reopen projects
+ on startup_ and _Confirm before exiting_; note the version, `-Xmx` and whether
Shared Indexes were on.
- Same machine, power plan and plugged in; exclude the project and caches from
antivirus scanning, or neither.
diff --git a/plugins/README.md b/plugins/README.md
index 530f116d8..02a2f175c 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -48,11 +48,11 @@ All paths are relative to the package directory and may not leave it.
### Permissions
-| Permission | Unlocks |
-|----------------|-------------------------------------------------|
+| Permission | Unlocks |
+| -------------- | ------------------------------------------------- |
| `project-read` | `workspace-root`, `read-file` (project root only) |
-| `editor-read` | `active-file` |
-| `editor-write` | `insert-text`, `replace-selection` |
+| `editor-read` | `active-file` |
+| `editor-write` | `insert-text`, `replace-selection` |
`log`, `register-command`, `show-notification`, `register-language` and
`register-theme` are always available. Calling a gated function without its
@@ -133,22 +133,22 @@ Any language with component-model tooling works (e.g. `componentize-py`,
### Host functions
-| Function | Notes |
-|---|---|
-| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
-| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
-| `show-notification(level, title, body)` | Balloon in the invoking window. |
-| `workspace-root()` | Root of the project the command runs in. |
-| `active-file()` | Absolute path of the focused editor's file. |
-| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
-| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
-| `replace-selection(text)` | Replaces every selection and selects the new text. |
-| `register-language(toml)` | Same format as `languages/<id>.toml`. |
-| `register-theme(json)` | See *Themes* below. |
+| Function | Notes |
+| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
+| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
+| `show-notification(level, title, body)` | Balloon in the invoking window. |
+| `workspace-root()` | Root of the project the command runs in. |
+| `active-file()` | Absolute path of the focused editor's file. |
+| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
+| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
+| `replace-selection(text)` | Replaces every selection and selects the new text. |
+| `register-language(toml)` | Same format as `languages/<id>.toml`. |
+| `register-theme(json)` | See _Themes_ below. |
`run-command` receives an optional string argument: `executeAction("plugin.hello.insert-date", "arg")`
from another feature, or nothing when run from Search Everywhere / a shortcut.
-Returning `Err(msg)` shows *"<title> failed: msg"*; the plugin keeps running.
+Returning `Err(msg)` shows _"<title> failed: msg"_; the plugin keeps running.
### Sandbox and limits
@@ -156,13 +156,13 @@ Each plugin gets its own wasmtime `Store`: no preopened directories, no
environment, no network, no inherited stdio — only clocks and randomness from
WASI, plus the host functions above. Every call into the plugin is bounded:
-* **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
-* **time:** 5 s wall clock per call (epoch interruption);
-* **memory:** 256 MiB of linear memory.
+- **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
+- **time:** 5 s wall clock per call (epoch interruption);
+- **memory:** 256 MiB of linear memory.
A panic, trap, permission violation or exceeded limit stops the plugin and
-marks it *Failed* for the session (with the reason in Settings › Plugins);
-toggling it off and on, or *Reload*, starts a fresh instance. The IDE itself is
+marks it _Failed_ for the session (with the reason in Settings › Plugins);
+toggling it off and on, or _Reload_, starts a fresh instance. The IDE itself is
never affected.
## 3. Themes
@@ -181,7 +181,7 @@ Tokens are the CSS variables of `src/styles/tokens.css` (`--bg-*`, `--fg-*`,
keep the values of the built-in base named by `kind`. Values must be plain CSS
values (no `url()`, `;`, braces); `//` and `/* */` comments are allowed. A
manifest theme entry may add `editor-scheme = "themes/x.scheme.json"` (editor
-colours, merged over the theme). Pick a theme in Settings › Plugins › *Apply*.
+colours, merged over the theme). Pick a theme in Settings › Plugins › _Apply_.
Start from [`templates/theme-plugin`](../templates/theme-plugin); the full guide,
token reference and IntelliJ / VS Code porting tables are in
@@ -196,14 +196,14 @@ token reference and IntelliJ / VS Code porting tables are in
## 5. Installing and developing
-* **Install:** Settings › Plugins › *Install Plugin from Disk…* (or the action
- *Install Plugin from Disk…*) and pick the package folder. The manifest and the
+- **Install:** Settings › Plugins › _Install Plugin from Disk…_ (or the action
+ _Install Plugin from Disk…_) and pick the package folder. The manifest and the
files it references are copied to `<app-data>/plugins/<id>/`.
-* **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
- It loads when the project is opened, is listed with a *dev* tag, and *Reload*
- (or the *Reload Plugins* action) picks up a rebuilt `plugin.wasm` without
+- **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
+ It loads when the project is opened, is listed with a _dev_ tag, and _Reload_
+ (or the _Reload Plugins_ action) picks up a rebuilt `plugin.wasm` without
restarting the IDE.
-* Commands appear in Search Everywhere › Actions under their category, and can
+- Commands appear in Search Everywhere › Actions under their category, and can
be bound in Settings › Keymap like any other action.
## 6. Testing
diff --git a/public/splash.css b/public/splash.css
index 9b0232591..2414c529e 100644
--- a/public/splash.css
+++ b/public/splash.css
@@ -4,8 +4,13 @@
Until tokens load, the colours are the last theme's --bg-frame / --fg-muted that boot.js
restored as --boot-*, else these built-in ones; the bar keeps the last --accent throughout. */
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
-body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
-:root[data-theme="dark"] :is(body, .splash) { background: var(--bg-frame, var(--boot-frame, #26282c)); }
+body,
+.splash {
+ background: var(--bg-frame, var(--boot-frame, #e9eaee));
+}
+:root[data-theme="dark"] :is(body, .splash) {
+ background: var(--bg-frame, var(--boot-frame, #26282c));
+}
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) {
background: var(--bg-frame, var(--boot-frame, #1a1b1e));
}
@@ -27,12 +32,29 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
animation: splash-in 240ms ease-out 120ms both;
transition: opacity 160ms ease-out;
}
-.splash.splash-out { opacity: 0; pointer-events: none; }
-:root[data-theme^="dark"] .splash { color: var(--fg-muted, var(--boot-fg, #8c8f95)); }
-.splash-logo { width: 56px; height: 56px; }
+.splash.splash-out {
+ opacity: 0;
+ pointer-events: none;
+}
+:root[data-theme^="dark"] .splash {
+ color: var(--fg-muted, var(--boot-fg, #8c8f95));
+}
+.splash-logo {
+ width: 56px;
+ height: 56px;
+}
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
-.splash-wordmark { width: 73.2px; height: 18.15px; }
-.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
+.splash-wordmark {
+ width: 73.2px;
+ height: 18.15px;
+}
+.splash-bar {
+ width: 120px;
+ height: 2px;
+ border-radius: 1px;
+ overflow: hidden;
+ background: rgb(127 127 127 / 0.18);
+}
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out.
The remembered accent comes first: tokens.css brings the theme's default --accent before
settings restore a custom one, which would flash the default mid-load. */
@@ -44,11 +66,28 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
}
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
-:root[data-window="settings"] .splash { animation-delay: 400ms; }
-:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
-@keyframes splash-in { from { opacity: 0; } }
-@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
+:root[data-window="settings"] .splash {
+ animation-delay: 400ms;
+}
+:root[data-window="settings"] .splash > :not(.splash-bar) {
+ display: none;
+}
+@keyframes splash-in {
+ from {
+ opacity: 0;
+ }
+}
+@keyframes splash-fill {
+ from {
+ transform: scaleX(0.04);
+ }
+ to {
+ transform: scaleX(0.92);
+ }
+}
/* The fill stays: it grows in place, which reduced motion allows. */
@media (prefers-reduced-motion: reduce) {
- .splash { animation: none; }
+ .splash {
+ animation: none;
+ }
}
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index ec680d716..bb12e5ccb 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -2,11 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
- "windows": [
- "main",
- "project-*",
- "settings-*"
- ],
+ "windows": ["main", "project-*", "settings-*"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
diff --git a/src-tauri/capabilities/e2e.json b/src-tauri/capabilities/e2e.json
index e1cfc5ef4..2e1cd42c5 100644
--- a/src-tauri/capabilities/e2e.json
+++ b/src-tauri/capabilities/e2e.json
@@ -2,12 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "e2e-bridge",
"description": "Debug-only automation bridge",
- "windows": [
- "main",
- "project-*",
- "settings-*"
- ],
- "permissions": [
- "mcp-bridge:default"
- ]
-}
\ No newline at end of file
+ "windows": ["main", "project-*", "settings-*"],
+ "permissions": ["mcp-bridge:default"]
+}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 51120f5f5..459071ee6 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -37,13 +37,7 @@
"active": true,
"targets": "all",
"createUpdaterArtifacts": true,
- "icon": [
- "icons/32x32.png",
- "icons/128x128.png",
- "icons/icon.icns",
- "icons/icon.ico"
- ],
+ "icon": ["icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.icns", "icons/icon.ico"],
"category": "DeveloperTool",
"copyright": "Copyright © 2026 OpenIDEA contributors",
"license": "Apache-2.0",
diff --git a/src-tauri/tauri.dev.conf.json b/src-tauri/tauri.dev.conf.json
index 006eb1a66..6efc33f98 100644
--- a/src-tauri/tauri.dev.conf.json
+++ b/src-tauri/tauri.dev.conf.json
@@ -2,4 +2,4 @@
"app": {
"withGlobalTauri": true
}
-}
\ No newline at end of file
+}
diff --git a/src/editor/api.ts b/src/editor/api.ts
index 83bd11925..488782e11 100644
--- a/src/editor/api.ts
+++ b/src/editor/api.ts
@@ -17,7 +17,15 @@
* - Right-hand overview marks: `scrollbarMarks`; save hooks:
* `registerSaveParticipant`; Back/Forward history: `getNavigationHistory`.
*/
-import { Annotation, Compartment, Facet, type EditorState, type Extension, type RangeSet, type Transaction } from "@codemirror/state";
+import {
+ Annotation,
+ Compartment,
+ Facet,
+ type EditorState,
+ type Extension,
+ type RangeSet,
+ type Transaction,
+} from "@codemirror/state";
import { GutterMarker, ViewPlugin, type EditorView } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import { create } from "zustand";
@@ -252,7 +260,12 @@ export class LaneMarker extends GutterMarker {
super();
}
override eq(other: GutterMarker): boolean {
- return other instanceof LaneMarker && other.color === this.color && other.kind === this.kind && other.title === this.title;
+ return (
+ other instanceof LaneMarker &&
+ other.color === this.color &&
+ other.kind === this.kind &&
+ other.title === this.title
+ );
}
override toDOM(): Node {
const el = document.createElement("div");
@@ -283,7 +296,10 @@ export type ContributedFormatter = (
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. */
export type ContributedDefinition = (view: EditorView, pos: number) => boolean;
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
-export type ContributedHover = (state: EditorState, pos: number) => { from: number; to: number; markdown: string } | null;
+export type ContributedHover = (
+ state: EditorState,
+ pos: number,
+) => { from: number; to: number; markdown: string } | null;
export function contributedAt<T>(state: EditorState, key: string, pos: number): T | undefined {
return state.languageDataAt<T>(key, pos)[0];
diff --git a/src/editor/core/actions.ts b/src/editor/core/actions.ts
index cbfa16f6a..01c4b920f 100644
--- a/src/editor/core/actions.ts
+++ b/src/editor/core/actions.ts
@@ -23,12 +23,32 @@ import {
toggleCase,
unselectOccurrence,
} from "./cm/editing";
-import { emptyStack, extendSelection, shrinkSelection, type SelectionStack, type SimpleRange } from "./model/selectionStack";
+import {
+ emptyStack,
+ extendSelection,
+ shrinkSelection,
+ type SelectionStack,
+ type SimpleRange,
+} from "./model/selectionStack";
import type { EditorSlot } from "./model/slot";
import { findAgain, openFindBar } from "./view/FindBar";
-import { collapseAll, collapseRecursively, expandAll, expandRecursively, foldAtCaret, foldSelection, unfoldAtCaret } from "./cm/folding";
+import {
+ collapseAll,
+ collapseRecursively,
+ expandAll,
+ expandRecursively,
+ foldAtCaret,
+ foldSelection,
+ unfoldAtCaret,
+} from "./cm/folding";
import { reverseLines, sortLines } from "./cm/lines";
-import { cursorCodeBlockEnd, cursorCodeBlockStart, cursorMatchBrace, scrollToCenter, splitLine } from "./cm/caretCommands";
+import {
+ cursorCodeBlockEnd,
+ cursorCodeBlockStart,
+ cursorMatchBrace,
+ scrollToCenter,
+ splitLine,
+} from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
@@ -86,19 +106,32 @@ export function syntaxCandidates(state: EditorState, sel: SimpleRange): SimpleRa
const word = state.wordAt(sel.from);
if (word) out.push({ from: word.from, to: word.to });
const tree = syntaxTree(state);
- for (let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(sel.from, 1); node; node = node.parent) {
+ for (
+ let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(sel.from, 1);
+ node;
+ node = node.parent
+ ) {
out.push({ from: node.from, to: node.to });
- const text = state.sliceDoc(node.from, Math.min(node.to, node.from + 1)) + state.sliceDoc(Math.max(node.from, node.to - 1), node.to);
+ const text =
+ state.sliceDoc(node.from, Math.min(node.to, node.from + 1)) +
+ state.sliceDoc(Math.max(node.from, node.to - 1), node.to);
if (/^[([{"'`][)\]}"'`]$/.test(text) && node.to - node.from > 2) out.push({ from: node.from + 1, to: node.to - 1 });
}
const line = state.doc.lineAt(sel.from);
const endLine = state.doc.lineAt(sel.to);
const indent = /^\s*/.exec(line.text)![0].length;
- out.push({ from: line.from + indent, to: endLine.to }, { from: line.from, to: endLine.to }, { from: 0, to: state.doc.length });
+ out.push(
+ { from: line.from + indent, to: endLine.to },
+ { from: line.from, to: endLine.to },
+ { from: 0, to: state.doc.length },
+ );
return out;
}
-function rangesFromBackend(state: EditorState, ranges: Array<{ start: { line: number; col: number }; end: { line: number; col: number } }>): SimpleRange[] {
+function rangesFromBackend(
+ state: EditorState,
+ ranges: Array<{ start: { line: number; col: number }; end: { line: number; col: number } }>,
+): SimpleRange[] {
const off = (p: { line: number; col: number }) => {
if (p.line + 1 > state.doc.lines) return state.doc.length;
const l = state.doc.line(p.line + 1);
@@ -120,8 +153,14 @@ export interface BackendChain {
* unchanged and the selection still covers its position: every node around
* the selection is around that position too. Repeated ⌥↑ then needs no IPC.
*/
-export function reusableChain(chain: BackendChain | undefined, counter: number, current: SimpleRange): SimpleRange[] | null {
- return chain && chain.counter === counter && chain.pos >= current.from && chain.pos <= current.to ? chain.ranges : null;
+export function reusableChain(
+ chain: BackendChain | undefined,
+ counter: number,
+ current: SimpleRange,
+): SimpleRange[] | null {
+ return chain && chain.counter === counter && chain.pos >= current.from && chain.pos <= current.to
+ ? chain.ranges
+ : null;
}
const chains = new WeakMap<EditorSlot, BackendChain>();
@@ -156,10 +195,17 @@ async function extend(slot: EditorSlot) {
const results = currents.map((c, i) =>
extendSelection(prev[i] ?? emptyStack(), c, [...candidates[i]!, ...syntaxCandidates(v.state, c)]),
);
- stacks.set(slot, results.map((r) => r.state));
+ stacks.set(
+ slot,
+ results.map((r) => r.state),
+ );
if (!results.some((r) => r.next)) return;
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : before.ranges[i]!));
- v.dispatch({ selection: EditorSelection.create(ranges, before.mainIndex), scrollIntoView: true, userEvent: "select.extend" });
+ v.dispatch({
+ selection: EditorSelection.create(ranges, before.mainIndex),
+ scrollIntoView: true,
+ userEvent: "select.extend",
+ });
}
/** Extend / shrink run in order: a quick ⌥↑⌥↑ extends twice although extending waits for the backend. */
@@ -177,10 +223,17 @@ function shrink(slot: EditorSlot) {
const sel = view.state.selection;
const prev = stacks.get(slot) ?? [];
const results = sel.ranges.map((r, i) => shrinkSelection(prev[i] ?? emptyStack(), { from: r.from, to: r.to }));
- stacks.set(slot, results.map((r) => r.state));
+ stacks.set(
+ slot,
+ results.map((r) => r.state),
+ );
if (!results.some((r) => r.next)) return;
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : sel.ranges[i]!));
- view.dispatch({ selection: EditorSelection.create(ranges, sel.mainIndex), scrollIntoView: true, userEvent: "select.shrink" });
+ view.dispatch({
+ selection: EditorSelection.create(ranges, sel.mainIndex),
+ scrollIntoView: true,
+ userEvent: "select.shrink",
+ });
}
// --- structural editing without a Lezer tree ------------------------------------------
@@ -231,7 +284,8 @@ function moveStatement(view: EditorView, slot: EditorSlot, up: boolean) {
const v = slot.view;
if (!v) return;
const language = slot.model.getMeta().language;
- if ((await hasStructure(language)) && (await moveStatementStructural(v, up, queriesFor(slot.model))) !== "fallback") return;
+ if ((await hasStructure(language)) && (await moveStatementStructural(v, up, queriesFor(slot.model))) !== "fallback")
+ return;
if (slot.view === v) (up ? moveLineUp : moveLineDown)(v);
});
}
@@ -246,11 +300,16 @@ function completeCurrentStatement(view: EditorView, slot: EditorSlot) {
if (completionStatus(view.state) === "active") acceptCompletion(view);
const language = slot.model.getMeta().language;
const sel = view.state.selection;
- if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1) return completeStatement(language)(view);
+ if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1)
+ return completeStatement(language)(view);
void queueEdit(slot, async () => {
const v = slot.view;
if (!v || v.state.readOnly) return;
- if ((await hasStructure(language)) && (await completeStatementStructural(v, language, queriesFor(slot.model))) !== "fallback") return;
+ if (
+ (await hasStructure(language)) &&
+ (await completeStatementStructural(v, language, queriesFor(slot.model))) !== "fallback"
+ )
+ return;
if (slot.view === v) completeStatement(language)(v);
});
}
@@ -299,7 +358,8 @@ function copyReference(view: EditorView, slot: EditorSlot) {
/** ⌃G; when nothing more is found, a hint first and the search from the top on the next press (IDEA). */
function addNextOccurrence(view: EditorView) {
- if (nextOccurrence(view) === "notFound") void executeAction("editor.showHint", { text: "Not found, press again to search from the top" });
+ if (nextOccurrence(view) === "notFound")
+ void executeAction("editor.showHint", { text: "Not found, press again to search from the top" });
}
/** Settings › Editor › Color Scheme switches that are also toggle actions. */
@@ -309,7 +369,11 @@ export async function toggleSchemeSwitch(key: SchemeSwitch, on = !editorPrefs()[
try {
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(on))) });
} catch (e) {
- notifications().notify({ level: "error", title: "Cannot change the setting", body: e instanceof Error ? e.message : String(e) });
+ notifications().notify({
+ level: "error",
+ title: "Cannot change the setting",
+ body: e instanceof Error ? e.message : String(e),
+ });
}
}
@@ -326,7 +390,12 @@ const schemeSwitch = (id: string, title: string, key: SchemeSwitch, keywords: st
export function registerEditorActions(): () => void {
const ctrl = editorController();
- const text = (id: string, title: string, run: (view: EditorView, slot: EditorSlot) => unknown, extra: Partial<Action> = {}): Action => ({
+ const text = (
+ id: string,
+ title: string,
+ run: (view: EditorView, slot: EditorSlot) => unknown,
+ extra: Partial<Action> = {},
+ ): Action => ({
id,
title,
category: "Code",
@@ -358,22 +427,34 @@ export function registerEditorActions(): () => void {
text("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)),
text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)),
text("code.moveStatementDown", "Move Statement Down", (v, slot) => moveStatement(v, slot, false)),
- text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), { category: "Edit" }),
- text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), { category: "Edit" }),
+ text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), {
+ category: "Edit",
+ }),
+ text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), {
+ category: "Edit",
+ }),
text("code.fold", "Collapse", (v) => foldAtCaret(v), { category: "Folding", keywords: ["fold"] }),
text("code.unfold", "Expand", (v) => unfoldAtCaret(v), { category: "Folding", keywords: ["unfold"] }),
text("code.foldToggle", "Toggle Fold", (v) => toggleFold(v), { category: "Folding" }),
text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => expandWord(v, slot, "backward"), {
keywords: ["hippie", "complete word", "dabbrev"],
}),
- text("code.cyclicExpandWordBackward", "Cyclic Expand Word (Backward)", (v, slot) => expandWord(v, slot, "forward"), {
- keywords: ["hippie", "complete word", "dabbrev"],
- }),
+ text(
+ "code.cyclicExpandWordBackward",
+ "Cyclic Expand Word (Backward)",
+ (v, slot) => expandWord(v, slot, "forward"),
+ {
+ keywords: ["hippie", "complete word", "dabbrev"],
+ },
+ ),
text("editor.copyReference", "Copy Reference", (v, slot) => copyReference(v, slot), {
category: "Edit",
keywords: ["fully qualified name", "fqn", "copy path"],
}),
- text("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), { category: "Edit", icon: "paste" }),
+ text("code.pasteAsPlainText", "Paste as Plain Text", (v) => pasteAsPlainText(v), {
+ category: "Edit",
+ icon: "paste",
+ }),
{
id: "editor.toggleSoftWrap",
title: "Soft-Wrap",
@@ -386,17 +467,29 @@ export function registerEditorActions(): () => void {
},
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
- text("code.collapseRecursively", "Collapse Recursively", (v) => collapseRecursively(v), { category: "Folding", keywords: ["fold"] }),
- text("code.expandRecursively", "Expand Recursively", (v) => expandRecursively(v), { category: "Folding", keywords: ["unfold"] }),
- text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addNextOccurrence(v), { category: "Edit" }),
+ text("code.collapseRecursively", "Collapse Recursively", (v) => collapseRecursively(v), {
+ category: "Folding",
+ keywords: ["fold"],
+ }),
+ text("code.expandRecursively", "Expand Recursively", (v) => expandRecursively(v), {
+ category: "Folding",
+ keywords: ["unfold"],
+ }),
+ text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addNextOccurrence(v), {
+ category: "Edit",
+ }),
text("code.selectAllOccurrences", "Select All Occurrences", (v) => selectAllOccurrences(v), { category: "Edit" }),
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
text("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
text("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
text("code.splitLine", "Split Line", (v) => splitLine(v)),
text("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
- text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), { category: "Editor Actions" }),
- text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), { category: "Editor Actions" }),
+ text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), {
+ category: "Editor Actions",
+ }),
+ text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), {
+ category: "Editor Actions",
+ }),
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => addCursorAbove(v), { category: "Editor Actions" }),
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => addCursorBelow(v), { category: "Editor Actions" }),
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
@@ -414,12 +507,19 @@ export function registerEditorActions(): () => void {
}),
text("code.joinLines", "Join Lines", (v) => joinLines(v)),
text("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
- text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), { category: "Edit" }),
+ text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), {
+ category: "Edit",
+ }),
text("code.unselectOccurrence", "Unselect Occurrence", (v) => unselectOccurrence(v), { category: "Edit" }),
- text("code.pasteFromHistory", "Paste from History…", (v) => pasteFromHistory(v), { category: "Edit", keywords: ["clipboard", "paste multiple"] }),
+ text("code.pasteFromHistory", "Paste from History…", (v) => pasteFromHistory(v), {
+ category: "Edit",
+ keywords: ["clipboard", "paste multiple"],
+ }),
text("code.sortLines", "Sort Lines", (v) => sortLines(v), { category: "Edit" }),
text("code.reverseLines", "Reverse Lines", (v) => reverseLines(v), { category: "Edit" }),
- text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), { keywords: ["unwrap", "remove if"] }),
+ text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
+ keywords: ["unwrap", "remove if"],
+ }),
text("code.foldSelection", "Fold Selection / Remove Region", (v) => foldSelection(v), { category: "Folding" }),
{
id: "editor.toggleColumnSelection",
@@ -441,7 +541,12 @@ export function registerEditorActions(): () => void {
when: "projectOpen",
keywords: ["synchronize", "refresh", "revert"],
run: ({ arg }) => {
- const paths = typeof arg === "string" ? [arg] : Array.isArray(arg) ? arg.filter((p): p is string => typeof p === "string") : [];
+ const paths =
+ typeof arg === "string"
+ ? [arg]
+ : Array.isArray(arg)
+ ? arg.filter((p): p is string => typeof p === "string")
+ : [];
const active = ctrl.activePath();
return ctrl.reloadFromDisk(paths.length ? paths : active ? [active] : []);
},
@@ -622,7 +727,13 @@ export function registerEditorActions(): () => void {
run: () => ctrl.reopenClosed(),
},
{ id: "editor.nextTab", title: "Select Next Tab", category: "Window", when: TABS_WHEN, run: () => ctrl.cycle(1) },
- { id: "editor.prevTab", title: "Select Previous Tab", category: "Window", when: TABS_WHEN, run: () => ctrl.cycle(-1) },
+ {
+ id: "editor.prevTab",
+ title: "Select Previous Tab",
+ category: "Window",
+ when: TABS_WHEN,
+ run: () => ctrl.cycle(-1),
+ },
{
id: "editor.splitRight",
title: "Split Right",
diff --git a/src/editor/core/backend.ts b/src/editor/core/backend.ts
index 6ac951d5a..9cb3a4d51 100644
--- a/src/editor/core/backend.ts
+++ b/src/editor/core/backend.ts
@@ -93,23 +93,131 @@ interface MemDoc {
}
const EXT_LANG: Record<string, string> = {
- ts: "typescript", tsx: "typescriptreact", js: "javascript", jsx: "javascriptreact", rs: "rust", kt: "kotlin",
- kts: "kotlin", java: "java", py: "python", go: "go", json: "json", md: "markdown", css: "css", html: "html",
- yml: "yaml", yaml: "yaml", toml: "toml", c: "c", cpp: "cpp", h: "c", sh: "shellscript", sql: "sql", xml: "xml",
+ ts: "typescript",
+ tsx: "typescriptreact",
+ js: "javascript",
+ jsx: "javascriptreact",
+ rs: "rust",
+ kt: "kotlin",
+ kts: "kotlin",
+ java: "java",
+ py: "python",
+ go: "go",
+ json: "json",
+ md: "markdown",
+ css: "css",
+ html: "html",
+ yml: "yaml",
+ yaml: "yaml",
+ toml: "toml",
+ c: "c",
+ cpp: "cpp",
+ h: "c",
+ sh: "shellscript",
+ sql: "sql",
+ xml: "xml",
};
const MEM_LANGUAGES: LanguageInfo[] = [
- { id: "typescript", name: "TypeScript", extensions: ["ts"], uiMode: "TypeScript", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
- { id: "typescriptreact", name: "TypeScript JSX", extensions: ["tsx"], uiMode: "TSX", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
- { id: "javascript", name: "JavaScript", extensions: ["js"], uiMode: "JavaScript", lineComment: "//", blockComment: ["/*", "*/"], indent: { tabSize: 2, insertSpaces: true } },
- { id: "rust", name: "Rust", extensions: ["rs"], uiMode: "Rust", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
- { id: "kotlin", name: "Kotlin", extensions: ["kt", "kts"], uiMode: "Kotlin", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
- { id: "java", name: "Java", extensions: ["java"], uiMode: "Java", lineComment: "//", blockComment: ["/*", "*/"], indent: null },
- { id: "python", name: "Python", extensions: ["py"], uiMode: "Python", lineComment: "#", blockComment: null, indent: null },
- { id: "json", name: "JSON", extensions: ["json"], uiMode: "JSON", lineComment: null, blockComment: null, indent: { tabSize: 2, insertSpaces: true } },
- { id: "markdown", name: "Markdown", extensions: ["md"], uiMode: "Markdown", lineComment: null, blockComment: ["<!--", "-->"], indent: null },
- { id: "yaml", name: "YAML", extensions: ["yml", "yaml"], uiMode: "YAML", lineComment: "#", blockComment: null, indent: { tabSize: 2, insertSpaces: true } },
- { id: "plaintext", name: "Plain Text", extensions: ["txt"], uiMode: null, lineComment: null, blockComment: null, indent: null },
+ {
+ id: "typescript",
+ name: "TypeScript",
+ extensions: ["ts"],
+ uiMode: "TypeScript",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: { tabSize: 2, insertSpaces: true },
+ },
+ {
+ id: "typescriptreact",
+ name: "TypeScript JSX",
+ extensions: ["tsx"],
+ uiMode: "TSX",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: { tabSize: 2, insertSpaces: true },
+ },
+ {
+ id: "javascript",
+ name: "JavaScript",
+ extensions: ["js"],
+ uiMode: "JavaScript",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: { tabSize: 2, insertSpaces: true },
+ },
+ {
+ id: "rust",
+ name: "Rust",
+ extensions: ["rs"],
+ uiMode: "Rust",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: null,
+ },
+ {
+ id: "kotlin",
+ name: "Kotlin",
+ extensions: ["kt", "kts"],
+ uiMode: "Kotlin",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: null,
+ },
+ {
+ id: "java",
+ name: "Java",
+ extensions: ["java"],
+ uiMode: "Java",
+ lineComment: "//",
+ blockComment: ["/*", "*/"],
+ indent: null,
+ },
+ {
+ id: "python",
+ name: "Python",
+ extensions: ["py"],
+ uiMode: "Python",
+ lineComment: "#",
+ blockComment: null,
+ indent: null,
+ },
+ {
+ id: "json",
+ name: "JSON",
+ extensions: ["json"],
+ uiMode: "JSON",
+ lineComment: null,
+ blockComment: null,
+ indent: { tabSize: 2, insertSpaces: true },
+ },
+ {
+ id: "markdown",
+ name: "Markdown",
+ extensions: ["md"],
+ uiMode: "Markdown",
+ lineComment: null,
+ blockComment: ["<!--", "-->"],
+ indent: null,
+ },
+ {
+ id: "yaml",
+ name: "YAML",
+ extensions: ["yml", "yaml"],
+ uiMode: "YAML",
+ lineComment: "#",
+ blockComment: null,
+ indent: { tabSize: 2, insertSpaces: true },
+ },
+ {
+ id: "plaintext",
+ name: "Plain Text",
+ extensions: ["txt"],
+ uiMode: null,
+ lineComment: null,
+ blockComment: null,
+ indent: null,
+ },
];
const SAMPLE_KOTLIN = `package com.acme.orders
@@ -314,7 +422,10 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
async outline(doc) {
// Brace-based outline good enough for the dev shell.
const d = get(doc);
- const posAt = ((index) => (_text: string, offset: number) => index(offset))(lineIndex(d.text));
+ const posAt = (
+ (index) => (_text: string, offset: number) =>
+ index(offset)
+ )(lineIndex(d.text));
const items: OutlineItem[] = [];
const re = /\b(class|fun|function|fn|interface|object)\s+([A-Za-z_]\w*)/g;
for (let m = re.exec(d.text); m; m = re.exec(d.text)) {
@@ -342,7 +453,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
};
const parent = items.findLast(
(p) =>
- (p.range.start.line < start.line || (p.range.start.line === start.line && p.range.start.col <= start.col)) &&
+ (p.range.start.line < start.line ||
+ (p.range.start.line === start.line && p.range.start.col <= start.col)) &&
(p.range.end.line > start.line || (p.range.end.line === start.line && p.range.end.col >= start.col)),
);
if (parent) parent.children.push(item);
diff --git a/src/editor/core/clipboardHistory.test.ts b/src/editor/core/clipboardHistory.test.ts
index 97d915b4d..c8de4e3c9 100644
--- a/src/editor/core/clipboardHistory.test.ts
+++ b/src/editor/core/clipboardHistory.test.ts
@@ -28,9 +28,21 @@ describe("clipboard history (Paste from History)", () => {
it("copies the selections, or whole caret lines without a selection", () => {
const doc = "one\ntwo\nthree";
const ext = EditorState.allowMultipleSelections.of(true);
- const sel = EditorState.create({ doc, extensions: ext, selection: EditorSelection.create([EditorSelection.range(0, 3), EditorSelection.range(8, 13)]) });
+ const sel = EditorState.create({
+ doc,
+ extensions: ext,
+ selection: EditorSelection.create([EditorSelection.range(0, 3), EditorSelection.range(8, 13)]),
+ });
expect(copiedText(sel)).toBe("one\nthree");
- const carets = EditorState.create({ doc, extensions: ext, selection: EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(2), EditorSelection.cursor(5)]) });
+ const carets = EditorState.create({
+ doc,
+ extensions: ext,
+ selection: EditorSelection.create([
+ EditorSelection.cursor(1),
+ EditorSelection.cursor(2),
+ EditorSelection.cursor(5),
+ ]),
+ });
expect(copiedText(carets)).toBe("one\ntwo\n");
});
diff --git a/src/editor/core/clipboardHistory.ts b/src/editor/core/clipboardHistory.ts
index 640c0b53f..43b9fb084 100644
--- a/src/editor/core/clipboardHistory.ts
+++ b/src/editor/core/clipboardHistory.ts
@@ -28,7 +28,11 @@ export function clearClipboardHistory() {
/** What CodeMirror copies: the selections, or the caret lines when nothing is selected. */
export function copiedText(state: EditorState): string {
const ranges = state.selection.ranges;
- if (ranges.some((r) => !r.empty)) return ranges.filter((r) => !r.empty).map((r) => state.sliceDoc(r.from, r.to)).join(state.lineBreak);
+ if (ranges.some((r) => !r.empty))
+ return ranges
+ .filter((r) => !r.empty)
+ .map((r) => state.sliceDoc(r.from, r.to))
+ .join(state.lineBreak);
const lines: string[] = [];
let last = -1;
for (const r of ranges) {
diff --git a/src/editor/core/cm/caretCommands.test.ts b/src/editor/core/cm/caretCommands.test.ts
index fb2e2bf3b..52d460bf1 100644
--- a/src/editor/core/cm/caretCommands.test.ts
+++ b/src/editor/core/cm/caretCommands.test.ts
@@ -14,7 +14,12 @@ afterEach(() => views.splice(0).forEach((v) => v.destroy()));
const braceIndent = indentService.of((cx, pos) => {
const line = cx.lineAt(pos, -1);
const base = /^ */.exec(line.text)![0].length;
- return line.text.slice(0, pos - line.from).trimEnd().endsWith("{") ? base + 2 : base;
+ return line.text
+ .slice(0, pos - line.from)
+ .trimEnd()
+ .endsWith("{")
+ ? base + 2
+ : base;
});
/** `|` marks carets. */
@@ -96,7 +101,8 @@ describe("code block navigation", () => {
describe("editor base keymap", () => {
it("drops CodeMirror defaults that IDEA uses for other actions", () => {
const runs = editorBaseKeymap.map((b) => b.run);
- for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove]) expect(runs).not.toContain(cmd);
+ for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove])
+ expect(runs).not.toContain(cmd);
expect(editorBaseKeymap.some((b) => b.key === "Mod-Enter" || b.key === "Ctrl-m")).toBe(false);
expect(editorBaseKeymap.some((b) => b.win === "Ctrl-Shift-z")).toBe(true);
});
diff --git a/src/editor/core/cm/caretCommands.ts b/src/editor/core/cm/caretCommands.ts
index 7fd9b7422..6e71d7680 100644
--- a/src/editor/core/cm/caretCommands.ts
+++ b/src/editor/core/cm/caretCommands.ts
@@ -125,6 +125,10 @@ export const cursorMatchBrace: Command = (view) => {
return EditorSelection.cursor(target);
});
if (!moved) return false;
- view.dispatch({ selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "select.navigate" });
+ view.dispatch({
+ selection: EditorSelection.create(ranges, state.selection.mainIndex),
+ scrollIntoView: true,
+ userEvent: "select.navigate",
+ });
return true;
};
diff --git a/src/editor/core/cm/codeLens.test.ts b/src/editor/core/cm/codeLens.test.ts
index 7851364bf..7e4b93d37 100644
--- a/src/editor/core/cm/codeLens.test.ts
+++ b/src/editor/core/cm/codeLens.test.ts
@@ -6,7 +6,9 @@ const doc = (text: string) => EditorState.create({ doc: text });
describe("code lens layout", () => {
it("places lenses above attributes, annotations and doc comments", () => {
- const s = doc("mod a {\n /// Docs\n #[test]\n #[ignore]\n fn t() {}\n}\n@Test\nvoid x() {}\n/**\n * doc\n */\nfunction f() {}");
+ const s = doc(
+ "mod a {\n /// Docs\n #[test]\n #[ignore]\n fn t() {}\n}\n@Test\nvoid x() {}\n/**\n * doc\n */\nfunction f() {}",
+ );
expect(s.doc.lineAt(declarationStart(s, 5)).number).toBe(2);
expect(s.doc.lineAt(declarationStart(s, 8)).number).toBe(7);
expect(s.doc.lineAt(declarationStart(s, 12)).number).toBe(9);
diff --git a/src/editor/core/cm/codeLens.ts b/src/editor/core/cm/codeLens.ts
index d417c5ec7..c2e58852a 100644
--- a/src/editor/core/cm/codeLens.ts
+++ b/src/editor/core/cm/codeLens.ts
@@ -7,7 +7,10 @@ import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemir
import { codeLenses, type CodeLens } from "@/editor/api";
/** Groups lenses by line start, ordered by line then `order`. Exported for tests. */
-export function groupLenses(state: EditorState, lenses: readonly CodeLens[]): Array<{ lineFrom: number; lenses: CodeLens[] }> {
+export function groupLenses(
+ state: EditorState,
+ lenses: readonly CodeLens[],
+): Array<{ lineFrom: number; lenses: CodeLens[] }> {
const byLine = new Map<number, CodeLens[]>();
const len = state.doc.length;
for (const l of lenses) {
@@ -68,7 +71,11 @@ class LensWidget extends WidgetType {
}
private get key(): string {
- return this.indent + "\u0000" + this.lenses.map((l) => `${l.icon ?? ""}|${l.title}|${l.tooltip ?? ""}|${l.run ? 1 : 0}`).join("\u0001");
+ return (
+ this.indent +
+ "\u0000" +
+ this.lenses.map((l) => `${l.icon ?? ""}|${l.title}|${l.tooltip ?? ""}|${l.run ? 1 : 0}`).join("\u0001")
+ );
}
override eq(other: LensWidget): boolean {
@@ -184,7 +191,4 @@ const lensTheme = EditorView.theme({
});
/** Base extension (always installed): no cost until a provider contributes lenses. */
-export const codeLensExtension: Extension = [
- EditorView.decorations.compute([codeLenses], buildDecorations),
- lensTheme,
-];
+export const codeLensExtension: Extension = [EditorView.decorations.compute([codeLenses], buildDecorations), lensTheme];
diff --git a/src/editor/core/cm/columnMode.test.ts b/src/editor/core/cm/columnMode.test.ts
index 0da72c265..3fc4b6ccf 100644
--- a/src/editor/core/cm/columnMode.test.ts
+++ b/src/editor/core/cm/columnMode.test.ts
@@ -12,7 +12,11 @@ afterEach(() => {
function make(doc: string, at: number) {
view = new EditorView({
- state: EditorState.create({ doc, selection: { anchor: at }, extensions: [columnModeExtension, EditorState.allowMultipleSelections.of(true)] }),
+ state: EditorState.create({
+ doc,
+ selection: { anchor: at },
+ extensions: [columnModeExtension, EditorState.allowMultipleSelections.of(true)],
+ }),
parent: document.body,
});
return view;
diff --git a/src/editor/core/cm/columnMode.ts b/src/editor/core/cm/columnMode.ts
index 97945b333..13b5571c8 100644
--- a/src/editor/core/cm/columnMode.ts
+++ b/src/editor/core/cm/columnMode.ts
@@ -2,7 +2,16 @@
* Edit › Column Selection Mode (⇧⌘8): while on, a plain mouse drag and
* ⇧+arrows make rectangular (block) selections, one range per line.
*/
-import { EditorSelection, Prec, StateEffect, StateField, countColumn, findColumn, type EditorState, type Extension } from "@codemirror/state";
+import {
+ EditorSelection,
+ Prec,
+ StateEffect,
+ StateField,
+ countColumn,
+ findColumn,
+ type EditorState,
+ type Extension,
+} from "@codemirror/state";
import { EditorView, keymap, rectangularSelection } from "@codemirror/view";
/** A block between two visual columns (tabs expanded) of two lines. */
@@ -79,7 +88,12 @@ export function extendBlock(view: EditorView, dLine: number, dCol: number): bool
const a = state.doc.lineAt(main.anchor);
const h = state.doc.lineAt(main.head);
const col = (text: string, offset: number) => countColumn(text, state.tabSize, offset);
- b = { anchorLine: a.number, anchorCol: col(a.text, main.anchor - a.from), headLine: h.number, headCol: col(h.text, main.head - h.from) };
+ b = {
+ anchorLine: a.number,
+ anchorCol: col(a.text, main.anchor - a.from),
+ headLine: h.number,
+ headCol: col(h.text, main.head - h.from),
+ };
}
const headLine = Math.max(1, Math.min(state.doc.lines, b.headLine + dLine));
const next = { ...b, headLine, headCol: stepColumn(state.doc.line(b.headLine).text, b.headCol, dCol, state.tabSize) };
@@ -113,5 +127,7 @@ export const columnModeExtension: Extension = [
{ key: "Shift-ArrowRight", run: (v) => extendBlock(v, 0, 1) },
]),
),
- EditorView.editorAttributes.compute([columnModeField], (s): Record<string, string> => (isColumnMode(s) ? { class: "cm-openidea-columnMode" } : {})),
+ EditorView.editorAttributes.compute([columnModeField], (s): Record<string, string> =>
+ isColumnMode(s) ? { class: "cm-openidea-columnMode" } : {},
+ ),
];
diff --git a/src/editor/core/cm/comments.ts b/src/editor/core/cm/comments.ts
index ecd86ddd9..224f2bfc4 100644
--- a/src/editor/core/cm/comments.ts
+++ b/src/editor/core/cm/comments.ts
@@ -1,7 +1,14 @@
/**
* Comment with Line Comment and Enter inside a line comment, as in IDEA.
*/
-import { EditorSelection, Facet, countColumn, type ChangeSpec, type EditorState, type SelectionRange } from "@codemirror/state";
+import {
+ EditorSelection,
+ Facet,
+ countColumn,
+ type ChangeSpec,
+ type EditorState,
+ type SelectionRange,
+} from "@codemirror/state";
import type { Command, EditorView } from "@codemirror/view";
import { indentString, syntaxTree } from "@codemirror/language";
import { toggleComment } from "@codemirror/commands";
@@ -57,12 +64,16 @@ export const commentLine: Command = (view) => {
if (!block) blocks.push(target);
target.ranges.push(i);
target.endLine = Math.max(target.endLine, endLine);
- const wholeLines = r.empty || (r.from === doc.lineAt(r.from).from && r.to === doc.lineAt(r.to).from && r.to > r.from);
+ const wholeLines =
+ r.empty || (r.from === doc.lineAt(r.from).from && r.to === doc.lineAt(r.to).from && r.to > r.from);
const emptyLine = !doc.lineAt(r.from).text.trim();
- target.caretUpdate = r.empty && emptyLine && !repeated ? "commentStart" : r.empty ? "down" : wholeLines ? "restoreSelection" : null;
+ target.caretUpdate =
+ r.empty && emptyLine && !repeated ? "commentStart" : r.empty ? "down" : wholeLines ? "restoreSelection" : null;
}
- const tokens = blocks.map((b) => lineToken(state, doc.line(b.startLine).from + leadingWs(doc.line(b.startLine).text)));
+ const tokens = blocks.map((b) =>
+ lineToken(state, doc.line(b.startLine).from + leadingWs(doc.line(b.startLine).text)),
+ );
// Languages without line comments (CSS, HTML…): block comments.
if (tokens.some((t) => !t)) return toggleComment(view);
diff --git a/src/editor/core/cm/distractionFree.test.ts b/src/editor/core/cm/distractionFree.test.ts
index eb2720600..3c122328e 100644
--- a/src/editor/core/cm/distractionFree.test.ts
+++ b/src/editor/core/cm/distractionFree.test.ts
@@ -16,7 +16,11 @@ function mount(s: EditorSettings | undefined) {
parent,
state: EditorState.create({
doc: "fn main() {}\n",
- extensions: [lineNumbersExtension(s), distractionFreeExtension(s), prefsFor({ settings: s, path: "/p/a.rs", info: undefined, readOnly: false })],
+ extensions: [
+ lineNumbersExtension(s),
+ distractionFreeExtension(s),
+ prefsFor({ settings: s, path: "/p/a.rs", info: undefined, readOnly: false }),
+ ],
}),
});
return { view, dispose: () => (view.destroy(), parent.remove()) };
diff --git a/src/editor/core/cm/editing.test.ts b/src/editor/core/cm/editing.test.ts
index 10c136545..a63ec10f9 100644
--- a/src/editor/core/cm/editing.test.ts
+++ b/src/editor/core/cm/editing.test.ts
@@ -54,7 +54,9 @@ function show(view: EditorView): string {
const { doc, selection } = view.state;
let out = doc.toString();
for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
- out = r.empty ? out.slice(0, r.head) + "|" + out.slice(r.head) : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
+ out = r.empty
+ ? out.slice(0, r.head) + "|" + out.slice(r.head)
+ : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
return out;
}
@@ -98,8 +100,21 @@ describe("join lines", () => {
});
it("merges consecutive line comments and keeps brackets tight", () => {
- expect((() => { const v = make("// one|\n// two"); joinLines(v); return v.state.doc.toString(); })()).toBe("// one two");
- expect((() => { const v = make("f(|\n x\n)"); joinLines(v); joinLines(v); return v.state.doc.toString(); })()).toBe("f(x)");
+ expect(
+ (() => {
+ const v = make("// one|\n// two");
+ joinLines(v);
+ return v.state.doc.toString();
+ })(),
+ ).toBe("// one two");
+ expect(
+ (() => {
+ const v = make("f(|\n x\n)");
+ joinLines(v);
+ joinLines(v);
+ return v.state.doc.toString();
+ })(),
+ ).toBe("f(x)");
});
it("does nothing on the last line", () => {
@@ -163,7 +178,10 @@ describe("multiple carets", () => {
expect(toggleCaret(start, 3, 3).ranges.map((r) => r.head)).toEqual([1, 3, 5]);
expect(toggleCaret(start, 5, 5).ranges.map((r) => r.head)).toEqual([1]);
expect(toggleCaret(EditorSelection.single(2), 2, 2).ranges.map((r) => r.head)).toEqual([2]);
- expect(toggleCaret(EditorSelection.single(0), 2, 4).ranges.map((r) => [r.from, r.to])).toEqual([[0, 0], [2, 4]]);
+ expect(toggleCaret(EditorSelection.single(0), 2, 4).ranges.map((r) => [r.from, r.to])).toEqual([
+ [0, 0],
+ [2, 4],
+ ]);
});
});
diff --git a/src/editor/core/cm/editing.ts b/src/editor/core/cm/editing.ts
index 8f29b3808..ca473e962 100644
--- a/src/editor/core/cm/editing.ts
+++ b/src/editor/core/cm/editing.ts
@@ -13,7 +13,14 @@ import {
type TransactionSpec,
} from "@codemirror/state";
import { EditorView, type Command } from "@codemirror/view";
-import { foldedRanges, forceParsing, syntaxTree, getIndentUnit, indentString, getIndentation } from "@codemirror/language";
+import {
+ foldedRanges,
+ forceParsing,
+ syntaxTree,
+ getIndentUnit,
+ indentString,
+ getIndentation,
+} from "@codemirror/language";
import {
copyLineDown,
deleteLine as deleteDocLine,
@@ -69,7 +76,9 @@ function deleteHump(forward: boolean, camel = true): Command {
const to = Math.max(target, r.head);
return { changes: { from, to }, range: EditorSelection.cursor(from) };
});
- view.dispatch(view.state.update(tr, { scrollIntoView: true, userEvent: forward ? "delete.forward" : "delete.backward" }));
+ view.dispatch(
+ view.state.update(tr, { scrollIntoView: true, userEvent: forward ? "delete.forward" : "delete.backward" }),
+ );
return true;
};
}
@@ -89,7 +98,7 @@ export function visualLineSpan(state: EditorState, from: number, to: number): {
let a = state.doc.lineAt(from).from;
let b = state.doc.lineAt(to).to;
const folded = foldedRanges(state);
- for (let changed = true; changed; ) {
+ for (let changed = true; changed;) {
changed = false;
folded.between(a, b, (f, t) => {
const na = Math.min(a, state.doc.lineAt(f).from);
@@ -127,12 +136,19 @@ export const duplicateLineOrSelection: Command = (view) => {
const spans = foldedLineSpans(state);
if (!spans) return copyLineDown(view);
// On a folded region's line the whole folded block is duplicated.
- const changes = state.changes(spans.map((s) => ({ from: s.to, insert: state.lineBreak + state.sliceDoc(s.from, s.to) })));
+ const changes = state.changes(
+ spans.map((s) => ({ from: s.to, insert: state.lineBreak + state.sliceDoc(s.from, s.to) })),
+ );
const ranges = state.selection.ranges.map((r) => {
const s = spans.find((sp) => sp.from <= r.head && r.head <= sp.to)!;
return EditorSelection.cursor(changes.mapPos(r.head, -1) + s.to - s.from + state.lineBreak.length);
});
- view.dispatch({ changes, selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "input.duplicate" });
+ view.dispatch({
+ changes,
+ selection: EditorSelection.create(ranges, state.selection.mainIndex),
+ scrollIntoView: true,
+ userEvent: "input.duplicate",
+ });
return true;
}
const tr = state.changeByRange((r) => {
@@ -169,7 +185,12 @@ export const deleteLine: Command = (view) => {
const line = doc.lineAt(changes.mapPos(r.head, -1));
return EditorSelection.cursor(line.from + Math.min(col, line.length));
});
- view.dispatch({ changes, selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "delete.line" });
+ view.dispatch({
+ changes,
+ selection: EditorSelection.create(ranges, state.selection.mainIndex),
+ scrollIntoView: true,
+ userEvent: "delete.line",
+ });
return true;
};
@@ -194,7 +215,8 @@ export const occurrenceSearch = StateField.define<OccurrenceSearch | null>({
});
const IDENT = /[\p{L}\p{N}_$]/u;
-const identAt = (state: EditorState, pos: number) => pos >= 0 && pos < state.doc.length && IDENT.test(state.sliceDoc(pos, pos + 1));
+const identAt = (state: EditorState, pos: number) =>
+ pos >= 0 && pos < state.doc.length && IDENT.test(state.sliceDoc(pos, pos + 1));
/** The identifier at or right before `pos`. */
export function identifierAt(state: EditorState, pos: number): { from: number; to: number } | null {
@@ -221,7 +243,9 @@ function* matches(state: EditorState, text: string, from: number, wholeWords: bo
/** A selection of `m` with the head on the same side as in `like`. */
const rangeLike = (like: SelectionRange, m: { from: number; to: number }) =>
- like.head === like.from && like.from !== like.to ? EditorSelection.range(m.to, m.from) : EditorSelection.range(m.from, m.to);
+ like.head === like.from && like.from !== like.to
+ ? EditorSelection.range(m.to, m.from)
+ : EditorSelection.range(m.from, m.to);
/**
* ⌃G: Add Selection for Next Occurrence. From a bare caret it selects the
@@ -323,13 +347,15 @@ function statementStartingAt(state: EditorState, lineNo: number): Node | null {
}
/** Lines a moved statement stops at: blank lines, statement starts and closing braces of blocks. */
-const isStopLine = (state: EditorState, lineNo: number) => firstToken(state, lineNo) === null || !!statementStartingAt(state, lineNo);
+const isStopLine = (state: EditorState, lineNo: number) =>
+ firstToken(state, lineNo) === null || !!statementStartingAt(state, lineNo);
/** The statement containing the first token of the caret line. */
function statementAround(state: EditorState, pos: number): Node | null {
const start = firstToken(state, state.doc.lineAt(pos).number);
if (start === null) return null;
- for (let n: Node | null = syntaxTree(state).resolveInner(start, 1); n && n.parent; n = n.parent) if (isContainer(n.parent)) return n;
+ for (let n: Node | null = syntaxTree(state).resolveInner(start, 1); n && n.parent; n = n.parent)
+ if (isContainer(n.parent)) return n;
return null;
}
@@ -460,7 +486,7 @@ function shiftToIndentation(state: EditorState, from: number, to: number) {
const delta = proper - countColumn(/^\s*/.exec(first.text)![0], state.tabSize);
if (!delta) return null;
const changes: ChangeSpec[] = [];
- for (let pos = from; pos <= to; ) {
+ for (let pos = from; pos <= to;) {
const line = state.doc.lineAt(pos);
pos = line.to + 1;
const ws = /^\s*/.exec(line.text)![0];
@@ -494,18 +520,53 @@ export const moveStatementDown = moveStatement(false);
// --- complete statement -------------------------------------------------------
export const SEMICOLON_LANGS = new Set([
- "java", "c", "cpp", "csharp", "javascript", "javascriptreact", "typescript", "typescriptreact", "rust", "php",
- "dart", "objective-c", "objective-cpp", "groovy", "zig",
+ "java",
+ "c",
+ "cpp",
+ "csharp",
+ "javascript",
+ "javascriptreact",
+ "typescript",
+ "typescriptreact",
+ "rust",
+ "php",
+ "dart",
+ "objective-c",
+ "objective-cpp",
+ "groovy",
+ "zig",
]);
/** Blocks close with a keyword (`end`) or by indentation: never complete them with braces. */
export const KEYWORD_BLOCK_LANGS = new Set([
- "python", "ruby", "lua", "elixir", "haskell", "shellscript", "julia", "erlang", "fsharp", "ocaml", "ocaml.interface",
- "yaml", "markdown", "plaintext", "makefile", "cmake", "toml", "ini", "properties", "sql", "r", "perl", "powershell",
+ "python",
+ "ruby",
+ "lua",
+ "elixir",
+ "haskell",
+ "shellscript",
+ "julia",
+ "erlang",
+ "fsharp",
+ "ocaml",
+ "ocaml.interface",
+ "yaml",
+ "markdown",
+ "plaintext",
+ "makefile",
+ "cmake",
+ "toml",
+ "ini",
+ "properties",
+ "sql",
+ "r",
+ "perl",
+ "powershell",
]);
/** A line opening an indented body in `end` / layout languages (Ruby, Lua, Elixir, Haskell…). */
const KEYWORD_HEAD =
/\b(do(\s*\|[^|]*\|)?|then|where|of)$|^\s*(def|defp|defmodule|class|module|function|local function|if|unless|elsif|elseif|else|while|until|for|case|begin)\b/;
-const BLOCK_HEAD = /^\s*(if|else|for|while|do|switch|try|catch|finally|fn|fun|func|function|class|struct|enum|impl|trait|interface|object|match|when|loop|unsafe|mod|namespace)\b/;
+const BLOCK_HEAD =
+ /^\s*(if|else|for|while|do|switch|try|catch|finally|fn|fun|func|function|class|struct|enum|impl|trait|interface|object|match|when|loop|unsafe|mod|namespace)\b/;
/** Offset in `text` where a trailing line comment starts (outside string literals), else `text.length`. */
export function codeEnd(text: string, lineComment: string | undefined): number {
@@ -548,7 +609,11 @@ export function completeStatementSpec(state: EditorState, language: string): Tra
const from = line.from + text.length;
return {
// A trailing comment moves to the end of the header line.
- changes: { from, to: line.from + full.length, insert: insert.slice(0, 2) + full.slice(text.length) + insert.slice(2) },
+ changes: {
+ from,
+ to: line.from + full.length,
+ insert: insert.slice(0, 2) + full.slice(text.length) + insert.slice(2),
+ },
selection: { anchor: from + 2 + full.length - text.length + br.length + baseIndent.length + unit.length },
scrollIntoView: true,
userEvent: "input.complete",
@@ -556,9 +621,13 @@ export function completeStatementSpec(state: EditorState, language: string): Tra
}
let insert = "";
if (SEMICOLON_LANGS.has(language) && !comment && text.trim() && !/[;{},:]$/.test(text)) insert = ";";
- if (language === "python" && BLOCK_HEAD.test(text.replace(/^\s*(def|elif)\b/, "if")) && !text.endsWith(":")) insert = ":";
+ if (language === "python" && BLOCK_HEAD.test(text.replace(/^\s*(def|elif)\b/, "if")) && !text.endsWith(":"))
+ insert = ":";
const opensBlock =
- text.endsWith("{") || insert === ":" || text.endsWith(":") || (KEYWORD_BLOCK_LANGS.has(language) && KEYWORD_HEAD.test(text) && !/^\s*module\b.*\bwhere$/.test(text));
+ text.endsWith("{") ||
+ insert === ":" ||
+ text.endsWith(":") ||
+ (KEYWORD_BLOCK_LANGS.has(language) && KEYWORD_HEAD.test(text) && !/^\s*module\b.*\bwhere$/.test(text));
const nextIndent = baseIndent + (opensBlock ? unit : "");
const indentHere = getIndentation(state, line.to);
const newline = br + (indentHere !== null && !opensBlock ? indentString(state, indentHere) : nextIndent);
@@ -615,7 +684,10 @@ function newLineCommand(before: boolean): Command {
const computed = syntaxTree(state).length ? getIndentation(state, line.from) : null;
let indent = computed !== null ? indentString(state, computed) : own;
if (/^\s*[)\]}]/.test(line.text) && indent.length <= own.length) indent = own + unit;
- return { changes: { from: line.from, insert: indent + state.lineBreak }, range: EditorSelection.cursor(line.from + indent.length) };
+ return {
+ changes: { from: line.from, insert: indent + state.lineBreak },
+ range: EditorSelection.cursor(line.from + indent.length),
+ };
});
view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input" }));
return true;
@@ -665,13 +737,22 @@ export const joinLines: Command = (view) => {
// Drop the comment marker of a joined line comment (`// a` + `// b` → `// a b`).
const comment = /^(\/\/+|#+|--)\s?/.exec(nextText);
const curTrim = cur.text.slice(0, cur.length - trail);
- const skip = comment && new RegExp(`(^|\\s)${comment[1]!.replace(/[-/#]/g, "\\$&")}`).test(curTrim) ? comment[0].length : 0;
- const sep = !curTrim.length || !nextText.length || /[([{]$/.test(curTrim) || /^[)\]}.,;]/.test(nextText.slice(skip)) ? "" : " ";
+ const skip =
+ comment && new RegExp(`(^|\\s)${comment[1]!.replace(/[-/#]/g, "\\$&")}`).test(curTrim) ? comment[0].length : 0;
+ const sep =
+ !curTrim.length || !nextText.length || /[([{]$/.test(curTrim) || /^[)\]}.,;]/.test(nextText.slice(skip))
+ ? ""
+ : " ";
changes.push({ from: cur.to - trail, to: next.from + lead + skip, insert: sep });
if (n === first.number) caret = cur.to - trail;
}
const set = state.changes(changes);
- return { changes: set, range: r.empty ? EditorSelection.cursor(set.mapPos(caret, -1)) : EditorSelection.range(set.mapPos(r.from, 1), set.mapPos(r.to, -1)) };
+ return {
+ changes: set,
+ range: r.empty
+ ? EditorSelection.cursor(set.mapPos(caret, -1))
+ : EditorSelection.range(set.mapPos(r.from, 1), set.mapPos(r.to, -1)),
+ };
});
view.dispatch(state.update(tr, { scrollIntoView: true, userEvent: "input.join" }));
return true;
@@ -713,7 +794,9 @@ export const toggleCase: Command = (view) => {
const t = targets[state.selection.ranges.indexOf(r)];
if (!t) return { range: r };
const insert = caseOf(state, t.from, t.to, lower);
- const range = r.empty ? EditorSelection.range(t.from, t.from + insert.length) : EditorSelection.range(r.anchor, r.head);
+ const range = r.empty
+ ? EditorSelection.range(t.from, t.from + insert.length)
+ : EditorSelection.range(r.anchor, r.head);
return { changes: { from: t.from, to: t.to, insert }, range };
});
view.dispatch(state.update(tr, { userEvent: "input.case" }));
@@ -735,7 +818,11 @@ export const addCaretsToLineEnds: Command = (view) => {
for (let n = first; n <= last; n++) ranges.push(EditorSelection.cursor(state.doc.line(n).to));
}
if (ranges.length === state.selection.ranges.length && state.selection.ranges.every((r) => r.empty)) return false;
- view.dispatch({ selection: EditorSelection.create(ranges, ranges.length - 1), scrollIntoView: true, userEvent: "select" });
+ view.dispatch({
+ selection: EditorSelection.create(ranges, ranges.length - 1),
+ scrollIntoView: true,
+ userEvent: "select",
+ });
return true;
};
@@ -759,6 +846,11 @@ export const unselectOccurrence: Command = (view) => {
main = i;
break;
}
- view.dispatch({ selection: EditorSelection.create(ranges, main), effects, scrollIntoView: true, userEvent: "select" });
+ view.dispatch({
+ selection: EditorSelection.create(ranges, main),
+ effects,
+ scrollIntoView: true,
+ userEvent: "select",
+ });
return true;
};
diff --git a/src/editor/core/cm/find.test.ts b/src/editor/core/cm/find.test.ts
index 6fa3c52f7..091e5adf9 100644
--- a/src/editor/core/cm/find.test.ts
+++ b/src/editor/core/cm/find.test.ts
@@ -26,7 +26,10 @@ const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
function make(doc: string, o: Partial<FindOptions>, scope?: { from: number; to: number }) {
- const view = new EditorView({ state: EditorState.create({ doc, extensions: [findExtension()] }), parent: document.body });
+ const view = new EditorView({
+ state: EditorState.create({ doc, extensions: [findExtension()] }),
+ parent: document.body,
+ });
views.push(view);
const q = makeQuery({ search: "", caseSensitive: false, wholeWord: false, regexp: false, replace: "", ...o });
view.dispatch({ effects: [setSearchQuery.of(q), ...(scope ? [setFindScope.of(scope)] : [])] });
diff --git a/src/editor/core/cm/find.ts b/src/editor/core/cm/find.ts
index 6c8aedded..27644fe65 100644
--- a/src/editor/core/cm/find.ts
+++ b/src/editor/core/cm/find.ts
@@ -7,7 +7,15 @@
* string literals) and excluded matches filter matches through the query's
* `test`, so CodeMirror's own commands honour them too.
*/
-import { EditorSelection, Prec, StateEffect, StateField, type ChangeDesc, type EditorState, type Extension } from "@codemirror/state";
+import {
+ EditorSelection,
+ Prec,
+ StateEffect,
+ StateField,
+ type ChangeDesc,
+ type EditorState,
+ type Extension,
+} from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import {
SearchQuery,
@@ -52,7 +60,10 @@ export const findScope = StateField.define<FindScope | null>({
return v && tr.docChanged ? mapScope(v, tr.changes) : v;
},
// Lowest precedence: the scope's mark wraps the match marks, which stay visible inside it.
- provide: (f) => Prec.lowest(EditorView.decorations.from(f, (s) => (s ? Decoration.set([scopeDeco.range(s.from, s.to)]) : Decoration.none))),
+ provide: (f) =>
+ Prec.lowest(
+ EditorView.decorations.from(f, (s) => (s ? Decoration.set([scopeDeco.range(s.from, s.to)]) : Decoration.none)),
+ ),
});
/** IDEA's Exclude: matches skipped by Next / Previous and Replace All until the query changes. */
@@ -234,7 +245,10 @@ export function regexValid(source: string): boolean {
export const MAX_COUNT = 9_999;
/** Counts matches (capped) and the 1-based index of the selected one. */
-export function countMatches(state: EditorState, budgetMs = 30): { total: number; current: number; capped: boolean; starts: number[] } {
+export function countMatches(
+ state: EditorState,
+ budgetMs = 30,
+): { total: number; current: number; capped: boolean; starts: number[] } {
const query = getSearchQuery(state);
if (!query.valid) return { total: 0, current: 0, capped: false, starts: [] };
const main = state.selection.main;
@@ -270,7 +284,8 @@ function matchesIn(state: EditorState, limit = Infinity): Match[] {
const scope = scopeOf(state);
const out: Match[] = [];
const cursor = query.getCursor(state, scope.from, scope.to);
- for (let r = cursor.next(); !r.done && out.length < limit; r = cursor.next()) if (r.value.to > r.value.from) out.push(r.value as Match);
+ for (let r = cursor.next(); !r.done && out.length < limit; r = cursor.next())
+ if (r.value.to > r.value.from) out.push(r.value as Match);
return out;
}
@@ -293,7 +308,9 @@ function step(view: EditorView, forward: boolean): boolean {
const ms = matchesIn(view.state);
if (!ms.length) return false;
const { from, to } = view.state.selection.main;
- const m = forward ? (ms.find((x) => x.from >= to && !(x.from === from && x.to === to)) ?? ms[0]!) : ([...ms].reverse().find((x) => x.to <= from) ?? ms[ms.length - 1]!);
+ const m = forward
+ ? (ms.find((x) => x.from >= to && !(x.from === from && x.to === to)) ?? ms[0]!)
+ : ([...ms].reverse().find((x) => x.to <= from) ?? ms[ms.length - 1]!);
selectMatch(view, m);
return true;
}
diff --git a/src/editor/core/cm/folding.ts b/src/editor/core/cm/folding.ts
index fa6d71f5f..613766f02 100644
--- a/src/editor/core/cm/folding.ts
+++ b/src/editor/core/cm/folding.ts
@@ -5,7 +5,15 @@
*/
import { Prec, StateEffect, StateField, type EditorState, type Extension, type Line } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
-import { codeFolding, foldEffect, foldGutter, foldService, foldable, foldedRanges, unfoldEffect } from "@codemirror/language";
+import {
+ codeFolding,
+ foldEffect,
+ foldGutter,
+ foldService,
+ foldable,
+ foldedRanges,
+ unfoldEffect,
+} from "@codemirror/language";
import type { FoldRange } from "@/platform/ipc";
export interface BackendFold {
@@ -182,7 +190,8 @@ export function foldSelection(view: EditorView): boolean {
const sel = view.state.selection;
const folded = effects.filter((e) => e.is(foldEffect)).map((e) => e.value as { from: number; to: number });
// The caret lands after the new fold, like IDEA.
- const after = sel.ranges.some((r) => !r.empty) && folded.length ? { anchor: folded[folded.length - 1]!.to } : undefined;
+ const after =
+ sel.ranges.some((r) => !r.empty) && folded.length ? { anchor: folded[folded.length - 1]!.to } : undefined;
view.dispatch({ effects, selection: after });
return true;
}
@@ -196,9 +205,13 @@ function isFolded(state: EditorState, r: { from: number; to: number }): boolean
}
/** Every foldable region (nested ones included) of the lines in `[from, to]`, kept within `[from, to]`. */
-export function foldableRegions(state: EditorState, from = 0, to = state.doc.length): Array<{ from: number; to: number }> {
+export function foldableRegions(
+ state: EditorState,
+ from = 0,
+ to = state.doc.length,
+): Array<{ from: number; to: number }> {
const out: Array<{ from: number; to: number }> = [];
- for (let pos = state.doc.lineAt(from).from; pos <= to; ) {
+ for (let pos = state.doc.lineAt(from).from; pos <= to;) {
const line = state.doc.lineAt(pos);
const r = foldable(state, line.from, line.to);
if (r && r.from >= from && r.to <= to) out.push(r);
@@ -268,9 +281,15 @@ function dispatchEffects(view: EditorView, effects: StateEffect<unknown>[]): boo
export const collapseAll = (view: EditorView) => dispatchEffects(view, collapseAllEffects(view.state));
export const expandAll = (view: EditorView) => dispatchEffects(view, expandAllEffects(view.state));
export const collapseRecursively = (view: EditorView) =>
- dispatchEffects(view, view.state.selection.ranges.flatMap((r) => collapseRecursivelyEffects(view.state, r.head)));
+ dispatchEffects(
+ view,
+ view.state.selection.ranges.flatMap((r) => collapseRecursivelyEffects(view.state, r.head)),
+ );
export const expandRecursively = (view: EditorView) =>
- dispatchEffects(view, view.state.selection.ranges.flatMap((r) => expandRecursivelyEffects(view.state, r.head)));
+ dispatchEffects(
+ view,
+ view.state.selection.ranges.flatMap((r) => expandRecursivelyEffects(view.state, r.head)),
+ );
function chevron(open: boolean): HTMLElement {
const span = document.createElement("span");
diff --git a/src/editor/core/cm/highlight.ts b/src/editor/core/cm/highlight.ts
index 7300a79f8..07c36b9ed 100644
--- a/src/editor/core/cm/highlight.ts
+++ b/src/editor/core/cm/highlight.ts
@@ -6,7 +6,11 @@
import { HighlightStyle, type TagStyle } from "@codemirror/language";
import { tags as t, type Tag } from "@lezer/highlight";
-function token(tag: Tag | Tag[], name: string, defaults: { italic?: string; bold?: string; effect?: string } = {}): TagStyle {
+function token(
+ tag: Tag | Tag[],
+ name: string,
+ defaults: { italic?: string; bold?: string; effect?: string } = {},
+): TagStyle {
return {
tag,
color: `var(--syn-${name})`,
@@ -21,7 +25,20 @@ export const openideaHighlightStyle = HighlightStyle.define([
// Markdown tags whole links / quotes; listed first so marks, URL and title inside keep their own colours.
token(t.link, "link", { effect: "underline" }),
token(t.quote, "string"),
- token([t.keyword, t.controlKeyword, t.moduleKeyword, t.operatorKeyword, t.definitionKeyword, t.modifier, t.null, t.bool, t.unit], "keyword"),
+ token(
+ [
+ t.keyword,
+ t.controlKeyword,
+ t.moduleKeyword,
+ t.operatorKeyword,
+ t.definitionKeyword,
+ t.modifier,
+ t.null,
+ t.bool,
+ t.unit,
+ ],
+ "keyword",
+ ),
token(t.self, "self"),
token([t.string, t.special(t.string), t.character, t.attributeValue], "string"),
token(t.docString, "docstring", { italic: "italic" }),
@@ -31,7 +48,14 @@ export const openideaHighlightStyle = HighlightStyle.define([
token([t.typeName, t.className, t.namespace, t.definition(t.typeName)], "type"),
token([t.standard(t.typeName), t.standard(t.variableName), t.standard(t.function(t.variableName))], "builtin"),
token([t.function(t.variableName), t.function(t.propertyName)], "function-call"),
- token([t.function(t.definition(t.variableName)), t.definition(t.function(t.variableName)), t.function(t.definition(t.propertyName))], "function"),
+ token(
+ [
+ t.function(t.definition(t.variableName)),
+ t.definition(t.function(t.variableName)),
+ t.function(t.definition(t.propertyName)),
+ ],
+ "function",
+ ),
token([t.comment, t.lineComment, t.blockComment], "comment", { italic: "var(--syn-comment-style)" }),
token(t.docComment, "doc-comment", { italic: "italic" }),
token([t.meta, t.annotation, t.macroName], "decorator"),
diff --git a/src/editor/core/cm/indentGuides.ts b/src/editor/core/cm/indentGuides.ts
index ec67846b3..7ff452d96 100644
--- a/src/editor/core/cm/indentGuides.ts
+++ b/src/editor/core/cm/indentGuides.ts
@@ -13,7 +13,10 @@ function guideDeco(levels: number, step: number) {
let d = cache.get(key);
if (!d) {
d = Decoration.line({
- attributes: { class: "cm-openidea-guides", style: `--openidea-guide-levels: ${levels}; --openidea-guide-step: ${step}` },
+ attributes: {
+ class: "cm-openidea-guides",
+ style: `--openidea-guide-levels: ${levels}; --openidea-guide-step: ${step}`,
+ },
});
cache.set(key, d);
}
diff --git a/src/editor/core/cm/lanes.ts b/src/editor/core/cm/lanes.ts
index d02530c9f..a26e4cc66 100644
--- a/src/editor/core/cm/lanes.ts
+++ b/src/editor/core/cm/lanes.ts
@@ -97,7 +97,11 @@ class OverviewLane {
rows.set(key, { top: prev?.top ?? top, height: Math.max(height, prev?.height ?? 0), mark: m });
}
const caret = pos(view.lineBlockAt(view.state.selection.main.head).top);
- return { rows: [...rows.values()].sort((x, y) => (x.mark.priority ?? 0) - (y.mark.priority ?? 0)), caret, unit };
+ return {
+ rows: [...rows.values()].sort((x, y) => (x.mark.priority ?? 0) - (y.mark.priority ?? 0)),
+ caret,
+ unit,
+ };
},
write: ({ rows, caret, unit }) => {
const key =
@@ -107,7 +111,10 @@ class OverviewLane {
const frag = document.createDocumentFragment();
for (const r of rows) {
const el = document.createElement("div");
- el.className = r.mark.kind === "thin" ? "cm-openidea-overviewMark cm-openidea-overviewMark-thin" : "cm-openidea-overviewMark";
+ el.className =
+ r.mark.kind === "thin"
+ ? "cm-openidea-overviewMark cm-openidea-overviewMark-thin"
+ : "cm-openidea-overviewMark";
el.style.top = `${r.top}${unit}`;
el.style.height = `${r.height}${unit}`;
el.style.background = r.mark.color;
diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts
index 68f7750c5..ae770b858 100644
--- a/src/editor/core/cm/languages.ts
+++ b/src/editor/core/cm/languages.ts
@@ -61,18 +61,23 @@ export function findLanguageDescription(uiMode: string | null, path: string): La
const loose = LanguageDescription.matchLanguageName(languageData, uiMode, false);
if (loose) return loose;
}
- return uiMode === null && infos ? null : LanguageDescription.matchFilename(languageData, path.slice(path.lastIndexOf("/") + 1));
+ return uiMode === null && infos
+ ? null
+ : LanguageDescription.matchFilename(languageData, path.slice(path.lastIndexOf("/") + 1));
}
/** Loads (once) the CodeMirror language for `desc`. */
export function loadSupport(desc: LanguageDescription): Promise<LanguageSupport | null> {
let p = supports.get(desc.name);
if (!p) {
- p = desc.load().then((support) => patchSupport(desc, support)).catch((e) => {
- console.warn(`failed to load language ${desc.name}`, e);
- supports.delete(desc.name);
- return null;
- });
+ p = desc
+ .load()
+ .then((support) => patchSupport(desc, support))
+ .catch((e) => {
+ console.warn(`failed to load language ${desc.name}`, e);
+ supports.delete(desc.name);
+ return null;
+ });
supports.set(desc.name, p);
}
return p;
diff --git a/src/editor/core/cm/lines.ts b/src/editor/core/cm/lines.ts
index 99b03d7d8..4b27e33e0 100644
--- a/src/editor/core/cm/lines.ts
+++ b/src/editor/core/cm/lines.ts
@@ -1,5 +1,11 @@
/** Edit › Sort Lines / Reverse Lines: the selected lines, or the whole file without a selection. */
-import { EditorSelection, type ChangeSpec, type EditorState, type Transaction, type TransactionSpec } from "@codemirror/state";
+import {
+ EditorSelection,
+ type ChangeSpec,
+ type EditorState,
+ type Transaction,
+ type TransactionSpec,
+} from "@codemirror/state";
const collator = new Intl.Collator(undefined, { numeric: false, sensitivity: "variant" });
@@ -24,7 +30,11 @@ function blocks(state: EditorState): Array<{ from: number; to: number }> {
return out;
}
-function rewrite(state: EditorState, transform: (lines: string[]) => string[], userEvent: string): TransactionSpec | null {
+function rewrite(
+ state: EditorState,
+ transform: (lines: string[]) => string[],
+ userEvent: string,
+): TransactionSpec | null {
const changes: ChangeSpec[] = [];
for (const b of blocks(state)) {
const text = state.sliceDoc(b.from, b.to);
@@ -39,7 +49,10 @@ function rewrite(state: EditorState, transform: (lines: string[]) => string[], u
return {
changes: set,
selection: hadSelection
- ? EditorSelection.create(state.selection.ranges.map((r) => EditorSelection.range(set.mapPos(r.anchor, -1), set.mapPos(r.head, 1))), state.selection.mainIndex)
+ ? EditorSelection.create(
+ state.selection.ranges.map((r) => EditorSelection.range(set.mapPos(r.anchor, -1), set.mapPos(r.head, 1))),
+ state.selection.mainIndex,
+ )
: undefined,
scrollIntoView: true,
userEvent,
diff --git a/src/editor/core/cm/prefs.test.ts b/src/editor/core/cm/prefs.test.ts
index 6f817641f..5279a6d21 100644
--- a/src/editor/core/cm/prefs.test.ts
+++ b/src/editor/core/cm/prefs.test.ts
@@ -25,10 +25,18 @@ describe("editor settings behaviour", () => {
expect(detectIndent("a\n\tb\n\t\tc\n")).toEqual({ insertSpaces: false });
expect(detectIndent("plain\ntext\n")).toBeNull();
const info = { id: "python", indent: { tabSize: 4, insertSpaces: true } } as Parameters<typeof effectiveIndent>[1];
- const settings = { codeStyle: { languages: { python: { useTab: true, tabSize: 8 } }, detectIndents: true, editorconfig: false } } as unknown as EditorSettings;
+ const settings = {
+ codeStyle: { languages: { python: { useTab: true, tabSize: 8 } }, detectIndents: true, editorconfig: false },
+ } as unknown as EditorSettings;
expect(effectiveIndent(settings, info)).toEqual({ tabSize: 8, insertSpaces: false });
- expect(effectiveIndent(settings, info, { indentSize: 2, indentStyle: "space" } as never)).toEqual({ tabSize: 8, insertSpaces: false });
- expect(effectiveIndent(settings, info, null, { insertSpaces: true, size: 2 })).toEqual({ tabSize: 2, insertSpaces: true });
+ expect(effectiveIndent(settings, info, { indentSize: 2, indentStyle: "space" } as never)).toEqual({
+ tabSize: 8,
+ insertSpaces: false,
+ });
+ expect(effectiveIndent(settings, info, null, { insertSpaces: true, size: 2 })).toEqual({
+ tabSize: 2,
+ insertSpaces: true,
+ });
});
it("removes trailing blank lines and strips all lines on request", () => {
diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.ts
index 0e794b371..7d9b54a5f 100644
--- a/src/editor/core/cm/prefs.ts
+++ b/src/editor/core/cm/prefs.ts
@@ -3,7 +3,17 @@
* Keys, Code Editing, Code Style). Everything here is rebuilt into the
* `prefs` compartment when settings change.
*/
-import { EditorSelection, EditorState, Prec, RangeSetBuilder, StateEffect, StateField, type Extension, type Transaction, type TransactionSpec } from "@codemirror/state";
+import {
+ EditorSelection,
+ EditorState,
+ Prec,
+ RangeSetBuilder,
+ StateEffect,
+ StateField,
+ type Extension,
+ type Transaction,
+ type TransactionSpec,
+} from "@codemirror/state";
import {
Decoration,
EditorView,
@@ -47,7 +57,13 @@ export function matchesFilePatterns(patterns: string, path: string): boolean {
.map((p) => p.trim())
.filter(Boolean)
.some((p) => {
- const re = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
+ const re = new RegExp(
+ `^${p
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
+ .replace(/\*/g, ".*")
+ .replace(/\?/g, ".")}$`,
+ "i",
+ );
return re.test(name);
});
}
@@ -80,7 +96,7 @@ const wrapIndent = ViewPlugin.fromClass(
const b = new RangeSetBuilder<Decoration>();
const tab = view.state.tabSize;
for (const { from, to } of view.visibleRanges) {
- for (let pos = from; pos <= to; ) {
+ for (let pos = from; pos <= to;) {
const line = view.state.doc.lineAt(pos);
let cols = 0;
for (let i = 0; i < line.length; i++) {
@@ -193,7 +209,13 @@ function leadingColumns(text: string, tabSize: number): number {
}
/** Reformat on paste › Indent Block: re-indents a pasted block to the caret's indentation. */
-export function indentPastedText(text: string, targetCol: number, unit: string, tabSize: number, unitCols = tabSize): string {
+export function indentPastedText(
+ text: string,
+ targetCol: number,
+ unit: string,
+ tabSize: number,
+ unitCols = tabSize,
+): string {
const lines = text.split("\n");
if (lines.length < 2) return text;
const rest = lines.slice(1).filter((l) => l.trim());
@@ -205,7 +227,8 @@ export function indentPastedText(text: string, targetCol: number, unit: string,
// A block opener copied from mid-line ("if x:", "fn f() {") sat one level above its body.
if (!firstIndented && base > 0 && /[:{([]\s*$/.test(lines[0]!)) base = Math.max(0, base - unitCols);
const delta = targetCol - base;
- const pad = (n: number) => (unit === "\t" ? "\t".repeat(Math.floor(n / tabSize)) + " ".repeat(n % tabSize) : " ".repeat(n));
+ const pad = (n: number) =>
+ unit === "\t" ? "\t".repeat(Math.floor(n / tabSize)) + " ".repeat(n % tabSize) : " ".repeat(n);
return lines
.map((l, i) => {
if (i === 0) return l.trimStart();
@@ -394,7 +417,11 @@ const OPENERS: Record<string, true> = { "(": true, "[": true, "{": true, '"': tr
/** Typing a bracket / quote over a selection replaces it instead of wrapping it. */
const noSurround = EditorView.inputHandler.of((view, from, to, text) => {
if (!OPENERS[text] || from === to || view.state.selection.ranges.length !== 1) return false;
- view.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + 1), userEvent: "input.type" });
+ view.dispatch({
+ changes: { from, to, insert: text },
+ selection: EditorSelection.cursor(from + 1),
+ userEvent: "input.type",
+ });
return true;
});
@@ -441,17 +468,27 @@ export function prefsExtension(o: PrefsOptions): Extension {
if ((o.wrapOverride ?? softWrapActive(o.softWrap, prefs, o.path)) && g.softWrapIndent) out.push(wrapIndent);
if (o.showWhitespace) {
const a = prefs.appearance;
- out.push(whitespaceMarks({ leading: a.whitespaceLeading, inner: a.whitespaceInner, trailing: a.whitespaceTrailing }));
+ out.push(
+ whitespaceMarks({ leading: a.whitespaceLeading, inner: a.whitespaceInner, trailing: a.whitespaceTrailing }),
+ );
}
- if (prefs.appearance.hardWrapGuides && !o.distractionFree) out.push(marginGuides([o.hardWrapAt, ...prefs.codeStyle.visualGuides]));
- if (prefs.appearance.methodSeparators) out.push(EditorView.editorAttributes.of({ class: "cm-openidea-methodSeparators" }));
- const hidden = GUTTER_ICON_GROUPS.filter((grp) => !prefs.showGutterIcons || prefs.gutterIconsDisabled.includes(grp.id));
- if (hidden.length) out.push(EditorView.editorAttributes.of({ class: hidden.map((grp) => `cm-openidea-hideGutter-${grp.id}`).join(" ") }));
+ if (prefs.appearance.hardWrapGuides && !o.distractionFree)
+ out.push(marginGuides([o.hardWrapAt, ...prefs.codeStyle.visualGuides]));
+ if (prefs.appearance.methodSeparators)
+ out.push(EditorView.editorAttributes.of({ class: "cm-openidea-methodSeparators" }));
+ const hidden = GUTTER_ICON_GROUPS.filter(
+ (grp) => !prefs.showGutterIcons || prefs.gutterIconsDisabled.includes(grp.id),
+ );
+ if (hidden.length)
+ out.push(
+ EditorView.editorAttributes.of({ class: hidden.map((grp) => `cm-openidea-hideGutter-${grp.id}`).join(" ") }),
+ );
if (g.wheelZoom) out.push(wheelZoom);
if (!g.dragAndDrop) out.push(noTextDrag);
if (g.caretScroll === "center") out.push(centerCaret);
if (g.richTextCopy) out.push(richCopy);
- if (!o.readOnly && (k.reformatOnPaste === "indentBlock" || k.reformatOnPaste === "indentEachLine")) out.push(pasteReindentFilter(k.reformatOnPaste));
+ if (!o.readOnly && (k.reformatOnPaste === "indentBlock" || k.reformatOnPaste === "indentEachLine"))
+ out.push(pasteReindentFilter(k.reformatOnPaste));
// Pairing: closeBrackets() reads the brackets list from language data; ours comes first.
const brackets = [...(k.pairBrackets ? ["(", "[", "{"] : []), ...(k.pairQuotes ? ["'", '"'] : [])];
@@ -469,7 +506,11 @@ export function prefsExtension(o: PrefsOptions): Extension {
{ key: "Alt-Delete", run: deleteHumpForward },
);
// Delete to Word Start: the whitespace before the caret and the word before it.
- keys.push({ key: "Mod-Backspace", mac: "Alt-Backspace", run: k.camelHumps ? deleteHumpBackward : deleteWordBackward });
+ keys.push({
+ key: "Mod-Backspace",
+ mac: "Alt-Backspace",
+ run: k.camelHumps ? deleteHumpBackward : deleteWordBackward,
+ });
if (!k.smartHome)
keys.push(
{ key: "Home", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
diff --git a/src/editor/core/cm/setup.ts b/src/editor/core/cm/setup.ts
index 0fadf9218..29d14b7aa 100644
--- a/src/editor/core/cm/setup.ts
+++ b/src/editor/core/cm/setup.ts
@@ -107,7 +107,8 @@ export function detectIndent(text: string): { insertSpaces: boolean; size?: numb
if (n < 2 || (tabs === 0 && spaces === 0)) return null;
if (tabs > spaces) return { insertSpaces: false };
let best: number | undefined;
- for (const [d, c] of deltas) if (best === undefined || c > deltas.get(best)! || (c === deltas.get(best)! && d < best)) best = d;
+ for (const [d, c] of deltas)
+ if (best === undefined || c > deltas.get(best)! || (c === deltas.get(best)! && d < best)) best = d;
return { insertSpaces: true, size: best };
}
@@ -166,8 +167,16 @@ export function fontExtension(settings: EditorSettings | undefined): Extension {
if ((family && family !== BUNDLED_MONO_FAMILY) || fallback) {
vars.push(`--openidea-editor-font: ${monoFontFamily(family, fallback, "var(--font-mono)")}`);
}
- if (settings?.fontSize) vars.push(`--openidea-editor-font-size: ${settings.fontSize}px`, `--openidea-editor-base-size: ${settings.fontSize}px`);
- if (settings?.lineHeight) vars.push(`--openidea-editor-line-height: ${settings.lineHeight}px`, `--openidea-editor-base-line: ${settings.lineHeight}px`);
+ if (settings?.fontSize)
+ vars.push(
+ `--openidea-editor-font-size: ${settings.fontSize}px`,
+ `--openidea-editor-base-size: ${settings.fontSize}px`,
+ );
+ if (settings?.lineHeight)
+ vars.push(
+ `--openidea-editor-line-height: ${settings.lineHeight}px`,
+ `--openidea-editor-base-line: ${settings.lineHeight}px`,
+ );
const attrs: Record<string, string> = {};
if (vars.length) attrs.style = vars.join("; ");
if (prefs.ligatures) attrs.class = "cm-openidea-ligatures";
@@ -179,12 +188,18 @@ export function readOnlyExtension(readOnly: boolean): Extension {
}
/** Soft wraps per settings (file patterns), unless toggled for the file (`override`). */
-export function wrapExtension(settings: EditorSettings | undefined, path: string, override?: boolean | null): Extension {
+export function wrapExtension(
+ settings: EditorSettings | undefined,
+ path: string,
+ override?: boolean | null,
+): Extension {
return (override ?? softWrapActive(settings?.softWrap, prefsOf(settings), path)) ? EditorView.lineWrapping : [];
}
export function stickyExtension(settings: EditorSettings | undefined): Extension {
- return settings?.stickyScroll === false || isDistractionFree() ? [] : [stickyScroll, stickyMaxLines.of(prefsOf(settings).codeEditing.stickyLinesMax)];
+ return settings?.stickyScroll === false || isDistractionFree()
+ ? []
+ : [stickyScroll, stickyMaxLines.of(prefsOf(settings).codeEditing.stickyLinesMax)];
}
const matchingBracket = Decoration.mark({ class: "cm-matchingBracket" });
@@ -219,10 +234,16 @@ export function lineNumbersExtension(settings: EditorSettings | undefined): Exte
* Distraction Free Mode: no gutter, text column centred at the configured
* width (see `cm-openidea-distractionFree` in theme.ts).
*/
-export function distractionFreeExtension(settings: EditorSettings | undefined, active = isDistractionFree()): Extension {
+export function distractionFreeExtension(
+ settings: EditorSettings | undefined,
+ active = isDistractionFree(),
+): Extension {
if (!active) return [];
const columns = distractionFreeWidth(prefsOf(settings).appearance.distractionFreeWidth);
- return EditorView.editorAttributes.of({ class: "cm-openidea-distractionFree", style: `--openidea-df-columns: ${columns}` });
+ return EditorView.editorAttributes.of({
+ class: "cm-openidea-distractionFree",
+ style: `--openidea-df-columns: ${columns}`,
+ });
}
export function foldingFor(settings: EditorSettings | undefined): Extension {
@@ -310,7 +331,12 @@ export function baseExtensions(o: SetupOptions): Extension {
findExtension(),
overviewLane,
codeLensExtension,
- EditorView.contentAttributes.of({ spellcheck: "false", autocorrect: "off", autocapitalize: "off", "aria-label": tx`Editor for ${o.ctx.path}` }),
+ EditorView.contentAttributes.of({
+ spellcheck: "false",
+ autocorrect: "off",
+ autocapitalize: "off",
+ "aria-label": tx`Editor for ${o.ctx.path}`,
+ }),
tabKeymap,
keymap.of([...closeBracketsKeymap, ...editorBaseKeymap, indentWithTab]),
compartments.language.of(o.language ?? []),
@@ -320,7 +346,15 @@ export function baseExtensions(o: SetupOptions): Extension {
compartments.wrap.of(wrapExtension(o.settings, o.ctx.path, o.wrapOverride)),
compartments.sticky.of(stickyExtension(o.settings)),
compartments.heavy.of(heavyExtension(o.docLength, o.settings)),
- compartments.prefs.of(prefsFor({ settings: o.settings, path: o.ctx.path, info: o.info, readOnly: o.ctx.readOnly, wrapOverride: o.wrapOverride })),
+ compartments.prefs.of(
+ prefsFor({
+ settings: o.settings,
+ path: o.ctx.path,
+ info: o.info,
+ readOnly: o.ctx.readOnly,
+ wrapOverride: o.wrapOverride,
+ }),
+ ),
compartments.contributions.of(contributionExtensions(o.ctx)),
compartments.distractionFree.of(distractionFreeExtension(o.settings)),
o.extra ?? [],
diff --git a/src/editor/core/cm/smartKeys.test.ts b/src/editor/core/cm/smartKeys.test.ts
index 79ce8dd4d..eaf21b298 100644
--- a/src/editor/core/cm/smartKeys.test.ts
+++ b/src/editor/core/cm/smartKeys.test.ts
@@ -3,7 +3,14 @@ import { EditorSelection, EditorState, type Extension } from "@codemirror/state"
import { EditorView } from "@codemirror/view";
import { indentService, indentUnit } from "@codemirror/language";
import { closeBrackets, insertBracket } from "@codemirror/autocomplete";
-import { autoIndentBackspace, insertTab, smartBackspace, smartBackspaceApplies, tabOutOfScope, tabOutScopes } from "./smartKeys";
+import {
+ autoIndentBackspace,
+ insertTab,
+ smartBackspace,
+ smartBackspaceApplies,
+ tabOutOfScope,
+ tabOutScopes,
+} from "./smartKeys";
/** One unit (2) deeper after a (non-blank) line ending in `{`, one less on a line starting with `}`. */
const braces = indentService.of((cx, pos) => {
@@ -35,7 +42,12 @@ function make(text: string, extensions: Extension = [], unit = " ") {
state: EditorState.create({
doc,
selection: EditorSelection.create(ranges.length ? ranges : [EditorSelection.cursor(0)]),
- extensions: [EditorState.allowMultipleSelections.of(true), EditorState.tabSize.of(4), indentUnit.of(unit), extensions],
+ extensions: [
+ EditorState.allowMultipleSelections.of(true),
+ EditorState.tabSize.of(4),
+ indentUnit.of(unit),
+ extensions,
+ ],
}),
parent: document.body,
});
@@ -47,7 +59,9 @@ function show(view: EditorView): string {
const { doc, selection } = view.state;
let out = doc.toString();
for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
- out = r.empty ? out.slice(0, r.head) + "|" + out.slice(r.head) : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
+ out = r.empty
+ ? out.slice(0, r.head) + "|" + out.slice(r.head)
+ : out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
return out;
}
diff --git a/src/editor/core/cm/smartKeys.ts b/src/editor/core/cm/smartKeys.ts
index fd0caaacc..f8d5cd870 100644
--- a/src/editor/core/cm/smartKeys.ts
+++ b/src/editor/core/cm/smartKeys.ts
@@ -2,7 +2,15 @@
* IDEA-style Tab, smart Backspace and Tab out of auto-inserted brackets and
* quotes.
*/
-import { EditorSelection, StateEffect, countColumn, StateField, type EditorState, type Extension, type Transaction } from "@codemirror/state";
+import {
+ EditorSelection,
+ StateEffect,
+ countColumn,
+ StateField,
+ type EditorState,
+ type Extension,
+ type Transaction,
+} from "@codemirror/state";
import { EditorView, keymap, type Command } from "@codemirror/view";
import { getIndentUnit, getIndentation, indentString, indentUnit, syntaxTree } from "@codemirror/language";
import { indentMore } from "@codemirror/commands";
@@ -45,7 +53,10 @@ export function smartBackspaceApplies(mode: string, language: string | undefined
}
/** The change one Backspace makes at `pos` in "To proper indent position" mode, or null to delete normally. */
-export function autoIndentBackspace(state: EditorState, pos: number): { from: number; to: number; insert: string } | null {
+export function autoIndentBackspace(
+ state: EditorState,
+ pos: number,
+): { from: number; to: number; insert: string } | null {
const doc = state.doc;
const line = doc.lineAt(pos);
if (/[^ \t]/.test(doc.sliceString(line.from, pos))) return null;
@@ -128,7 +139,8 @@ function insertedPairs(tr: Transaction): Scope[] {
export const tabOutOfScope: Command = (view) => {
const { state } = view;
const scopes = state.field(tabOutScopes, false);
- if (!scopes?.length || state.selection.ranges.some((r) => !r.empty || !scopes.some((s) => s.to === r.head))) return false;
+ if (!scopes?.length || state.selection.ranges.some((r) => !r.empty || !scopes.some((s) => s.to === r.head)))
+ return false;
view.dispatch({
selection: EditorSelection.create(
state.selection.ranges.map((r) => EditorSelection.cursor(Math.min(r.head + 1, state.doc.length))),
@@ -148,7 +160,11 @@ export const tabOut: Extension = tabOutScopes;
/** `quote` at `pos` closes the string literal the caret is in (typed or not, the pair's end). */
export function closesStringAt(state: EditorState, pos: number, quote: string): boolean {
if (state.sliceDoc(pos, pos + 1) !== quote) return false;
- for (let n: ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]> | null = syntaxTree(state).resolveInner(pos, 1); n; n = n.parent) {
+ for (
+ let n: ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]> | null = syntaxTree(state).resolveInner(pos, 1);
+ n;
+ n = n.parent
+ ) {
if (n.to > pos + 1) break;
if (n.to === pos + 1 && n.from < pos && /String|Char|Template|Rune/.test(n.type.name)) return true;
}
diff --git a/src/editor/core/cm/stickyScroll.ts b/src/editor/core/cm/stickyScroll.ts
index 332f736b8..6e7fffa7e 100644
--- a/src/editor/core/cm/stickyScroll.ts
+++ b/src/editor/core/cm/stickyScroll.ts
@@ -225,7 +225,9 @@ class StickyScroll {
if (!row?.dataset.line) return;
e.preventDefault();
// The line number of a sticky line is not a link (IDEA).
- const inner = (e.target as HTMLElement).closest(".cm-openidea-stickyText")?.querySelector<HTMLElement>(".cm-openidea-stickyInner");
+ const inner = (e.target as HTMLElement)
+ .closest(".cm-openidea-stickyText")
+ ?.querySelector<HTMLElement>(".cm-openidea-stickyInner");
if (!inner) return;
const state = this.view.state;
const line = state.doc.line(Math.min(Number(row.dataset.line), state.doc.lines));
@@ -234,7 +236,10 @@ class StickyScroll {
// The line takes the place of its sticky row, so the text stays under the pointer.
this.view.dispatch({
selection: EditorSelection.cursor(line.from + Math.min(offset, line.length)),
- effects: EditorView.scrollIntoView(line.from, { y: "start", yMargin: Math.max(0, rowIndex) * this.view.defaultLineHeight }),
+ effects: EditorView.scrollIntoView(line.from, {
+ y: "start",
+ yMargin: Math.max(0, rowIndex) * this.view.defaultLineHeight,
+ }),
userEvent: "select.sticky",
});
this.view.focus();
diff --git a/src/editor/core/cm/syntaxHighlight.test.ts b/src/editor/core/cm/syntaxHighlight.test.ts
index a3a1ecbbb..e1ea84de2 100644
--- a/src/editor/core/cm/syntaxHighlight.test.ts
+++ b/src/editor/core/cm/syntaxHighlight.test.ts
@@ -15,12 +15,18 @@ function marks(state: EditorState) {
describe("syntaxHighlightField", () => {
const create = () =>
- EditorState.create({ doc: "def hi, do: :ok", extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField] });
+ EditorState.create({
+ doc: "def hi, do: :ok",
+ extensions: [syntaxHighlighting(openideaHighlightStyle), syntaxHighlightField],
+ });
it("styles backend ranges with the active highlight style and maps them through edits", () => {
let state = create();
state = state.update({
- effects: setSyntaxHighlights.of({ kinds: ["keyword", "atom", "functionCall"], data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0] }),
+ effects: setSyntaxHighlights.of({
+ kinds: ["keyword", "atom", "functionCall"],
+ data: [0, 3, 0, 4, 6, 2, 12, 15, 1, 99, 120, 0],
+ }),
}).state;
const keyword = highlightingFor(state, [t.keyword]);
const atom = highlightingFor(state, [t.atom]);
diff --git a/src/editor/core/cm/theme.ts b/src/editor/core/cm/theme.ts
index ff746dda0..707ec57a9 100644
--- a/src/editor/core/cm/theme.ts
+++ b/src/editor/core/cm/theme.ts
@@ -18,7 +18,8 @@ export const openideaTheme = EditorView.theme({
"--editor-gutter-border": "var(--border-gutter, var(--border))",
"--editor-caret-row": "var(--bg-current-line)",
"--editor-selection": "var(--bg-editor-selection, color-mix(in srgb, var(--accent) 24%, transparent))",
- "--editor-selection-inactive": "var(--bg-editor-selection-inactive, color-mix(in srgb, var(--accent) 14%, transparent))",
+ "--editor-selection-inactive":
+ "var(--bg-editor-selection-inactive, color-mix(in srgb, var(--accent) 14%, transparent))",
"--editor-indent-guide": "var(--border-indent-guide, var(--border))",
"--editor-search": "var(--bg-search-match, color-mix(in srgb, var(--warning) 30%, transparent))",
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
@@ -52,18 +53,24 @@ export const openideaTheme = EditorView.theme({
marginLeft: "0",
background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 55%, transparent)",
},
- "&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": { fontVariantLigatures: "normal" },
+ "&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {
+ fontVariantLigatures: "normal",
+ },
"&.cm-openidea-methodSeparators .cm-openidea-methodSeparator": {
boxShadow: "inset 0 1px 0 var(--border-method-separator, var(--border))",
},
- "&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks": { display: "none" },
+ "&.cm-openidea-hideGutter-run .cm-openidea-gutter-run, &.cm-openidea-hideGutter-bookmarks .cm-openidea-bookmarks": {
+ display: "none",
+ },
// Inheritance markers share one gutter: each group hides its own icons.
"&.cm-openidea-hideGutter-inheritors :is(.cm-openidea-lineMarker-implemented, .cm-openidea-lineMarker-overridden), &.cm-openidea-hideGutter-supers :is(.cm-openidea-lineMarker-implementing, .cm-openidea-lineMarker-overriding)":
{ display: "none" },
// Distraction Free Mode: no gutter; the text column (n chars + line padding) is centred.
"&.cm-openidea-distractionFree": { "--openidea-df-width": "calc(var(--openidea-df-columns, 80) * 1ch + 22px)" },
"&.cm-openidea-distractionFree .cm-gutters": { display: "none" },
- "&.cm-openidea-distractionFree .cm-content": { marginInlineStart: "max(0px, calc((100% - var(--openidea-df-width)) / 2))" },
+ "&.cm-openidea-distractionFree .cm-content": {
+ marginInlineStart: "max(0px, calc((100% - var(--openidea-df-width)) / 2))",
+ },
"&.cm-openidea-distractionFree .cm-content.cm-lineWrapping": { maxWidth: "var(--openidea-df-width)" },
".cm-fat-cursor": { background: "color-mix(in srgb, var(--caret, var(--fg-strong)) 45%, transparent)" },
".cm-selectionBackground": { background: "var(--editor-selection-inactive)" },
@@ -71,7 +78,9 @@ export const openideaTheme = EditorView.theme({
background: "var(--editor-selection)",
},
".cm-activeLine": { backgroundColor: "var(--editor-caret-row)" },
- ".cm-selectionMatch": { backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))" },
+ ".cm-selectionMatch": {
+ backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
+ },
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
backgroundColor: "var(--editor-brace)",
@@ -214,7 +223,10 @@ export const openideaTheme = EditorView.theme({
borderRadius: "var(--radius-popup)",
boxShadow: "var(--shadow-popup)",
},
- ".cm-tooltip .cm-tooltip-arrow:before": { borderTopColor: "var(--border-popup)", borderBottomColor: "var(--border-popup)" },
+ ".cm-tooltip .cm-tooltip-arrow:before": {
+ borderTopColor: "var(--border-popup)",
+ borderBottomColor: "var(--border-popup)",
+ },
".cm-tooltip .cm-tooltip-arrow:after": { borderTopColor: "var(--bg-popup)", borderBottomColor: "var(--bg-popup)" },
".cm-panels": { backgroundColor: "var(--bg-elev)", color: "var(--fg)" },
".cm-panels.cm-panels-top": { borderBottom: "1px solid var(--border)" },
diff --git a/src/editor/core/cm/unwrap.test.ts b/src/editor/core/cm/unwrap.test.ts
index 155aa8ee9..306386f03 100644
--- a/src/editor/core/cm/unwrap.test.ts
+++ b/src/editor/core/cm/unwrap.test.ts
@@ -31,7 +31,11 @@ describe("unwrapOptions (Unwrap/Remove)", () => {
it("keeps the else branch the caret is in", () => {
const src = "if (a) {\n x();\n} else {\n y();\n}";
- const chain = [node(src, "expression_statement", "y();"), node(src, "block", "{\n y();\n}", "alternative"), node(src, "if_statement", src)];
+ const chain = [
+ node(src, "expression_statement", "y();"),
+ node(src, "block", "{\n y();\n}", "alternative"),
+ node(src, "if_statement", src),
+ ];
const [o] = unwrapOptions(Text.of(src.split("\n")), chain);
expect(o!.label).toBe("Unwrap 'else'");
expect(apply(src, o!)).toBe("y();");
@@ -81,7 +85,11 @@ describe("unwrapOptions (Unwrap/Remove)", () => {
expect(apply(src, opts[0]!)).toBe("if (a) {\n p();\n} else {\n q();\n}");
expect(apply(src, opts[1]!)).toBe("if (b) {\n q();\n}");
- const cond = [node(src, "identifier", "b"), node(src, "parenthesized_expression", "(b)", "condition"), node(src, "if_statement", inner, "alternative")];
+ const cond = [
+ node(src, "identifier", "b"),
+ node(src, "parenthesized_expression", "(b)", "condition"),
+ node(src, "if_statement", inner, "alternative"),
+ ];
expect(unwrapOptions(Text.of(src.split("\n")), cond)).toEqual([]);
});
});
diff --git a/src/editor/core/cm/unwrap.ts b/src/editor/core/cm/unwrap.ts
index 9a221b18b..448fa29cb 100644
--- a/src/editor/core/cm/unwrap.ts
+++ b/src/editor/core/cm/unwrap.ts
@@ -60,11 +60,28 @@ const CLAUSES: Record<string, string> = {
};
/** The child on the caret's path must be a body, not the condition / header. */
-const HEADER_FIELDS = new Set(["condition", "left", "right", "value", "pattern", "initializer", "update", "resources", "parameters", "type", "name"]);
+const HEADER_FIELDS = new Set([
+ "condition",
+ "left",
+ "right",
+ "value",
+ "pattern",
+ "initializer",
+ "update",
+ "resources",
+ "parameters",
+ "type",
+ "name",
+]);
function isBody(n: ChainNode): boolean {
if (n.field && HEADER_FIELDS.has(n.field)) return false;
- return /block|body|statement|compound|suite/.test(n.kind) || n.field === "consequence" || n.field === "alternative" || n.field === "body";
+ return (
+ /block|body|statement|compound|suite/.test(n.kind) ||
+ n.field === "consequence" ||
+ n.field === "alternative" ||
+ n.field === "body"
+ );
}
const leading = (s: string) => /^[ \t]*/.exec(s)![0];
@@ -80,7 +97,10 @@ function bodyLines(doc: Text, body: ChainNode, base: string): string[] {
}
const first = doc.lineAt(from);
if (!doc.sliceString(first.from, from).trim()) from = first.from;
- const lines = doc.sliceString(from, to).split("\n").map((l) => l.trimEnd());
+ const lines = doc
+ .sliceString(from, to)
+ .split("\n")
+ .map((l) => l.trimEnd());
while (lines.length && !lines[0]!.trim()) lines.shift();
while (lines.length && !lines[lines.length - 1]!.trim()) lines.pop();
const indents = lines.filter((l) => l.trim()).map((l) => leading(l).length);
@@ -89,13 +109,17 @@ function bodyLines(doc: Text, body: ChainNode, base: string): string[] {
}
function keyword(doc: Text, n: ChainNode): string {
- return /^[A-Za-z_]+/.exec(doc.sliceString(n.from, Math.min(n.to, n.from + 20)))?.[0] ?? n.kind.replace(/_(statement|expression|block)$/, "");
+ return (
+ /^[A-Za-z_]+/.exec(doc.sliceString(n.from, Math.min(n.to, n.from + 20)))?.[0] ??
+ n.kind.replace(/_(statement|expression|block)$/, "")
+ );
}
function replacement(doc: Text, target: ChainNode, body: ChainNode): { from: number; to: number; insert: string } {
const startLine = doc.lineAt(target.from);
const endLine = doc.lineAt(target.to);
- const wholeLines = !doc.sliceString(startLine.from, target.from).trim() && !doc.sliceString(target.to, endLine.to).trim();
+ const wholeLines =
+ !doc.sliceString(startLine.from, target.from).trim() && !doc.sliceString(target.to, endLine.to).trim();
if (wholeLines) {
const lines = bodyLines(doc, body, leading(startLine.text));
// An empty body removes the statement's lines altogether.
@@ -134,7 +158,11 @@ export function unwrapOptions(doc: Text, chain: readonly ChainNode[]): UnwrapOpt
const key = `${target.from}:${target.to}:${label}`;
if (seen.has(key)) continue;
seen.add(key);
- out.push({ label: tx`Unwrap '${label}'`, target: { from: target.from, to: target.to }, ...replacement(doc, target, child) });
+ out.push({
+ label: tx`Unwrap '${label}'`,
+ target: { from: target.from, to: target.to },
+ ...replacement(doc, target, child),
+ });
}
return out;
}
diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts
index 33e7caae7..530483090 100644
--- a/src/editor/core/controller.test.ts
+++ b/src/editor/core/controller.test.ts
@@ -78,8 +78,19 @@ describe("EditorController", () => {
});
it("builds IDEA's editor tab menu", async () => {
- useProject.setState({ project: { name: "p", root: "/p", isGit: true, settings: {} } as never, settings: {} as never });
- const ids = ["navigate.selectIn", "project.revealInFinder", "vcs.localHistory", "vcs.commit", "project.copyAbsolutePath", "project.rename", "file.settings"];
+ useProject.setState({
+ project: { name: "p", root: "/p", isGit: true, settings: {} } as never,
+ settings: {} as never,
+ });
+ const ids = [
+ "navigate.selectIn",
+ "project.revealInFinder",
+ "vcs.localHistory",
+ "vcs.commit",
+ "project.copyAbsolutePath",
+ "project.rename",
+ "file.settings",
+ ];
const dispose = registerActions(ids.map((id) => ({ id, title: id, run: () => undefined })));
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "" }));
ctrl.start();
diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts
index 363cb7335..3d66df099 100644
--- a/src/editor/core/controller.ts
+++ b/src/editor/core/controller.ts
@@ -335,7 +335,10 @@ export class EditorController implements SlotHost {
files[path] = slot.viewState();
}
const kinds = useContributions.getState().editorKinds;
- storeSession(root, serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable));
+ storeSession(
+ root,
+ serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable),
+ );
}
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
@@ -912,7 +915,11 @@ export class EditorController implements SlotHost {
const encoding = await this.manager.backend.setEncoding(meta.doc, meta.encoding, true);
model.setMeta({ encoding });
} catch (e) {
- notifications().notify({ level: "error", title: "Cannot reload from disk", body: e instanceof Error ? e.message : String(e) });
+ notifications().notify({
+ level: "error",
+ title: "Cannot reload from disk",
+ body: e instanceof Error ? e.message : String(e),
+ });
}
}
}
@@ -1074,7 +1081,8 @@ export class EditorController implements SlotHost {
closePath(path: string) {
this.apply((s) => {
const keys = new Set<string>();
- for (const pane of Object.values(s.panes)) for (const t of pane.tabs) if (t.input.path === path) keys.add(t.input.key);
+ for (const pane of Object.values(s.panes))
+ for (const t of pane.tabs) if (t.input.path === path) keys.add(t.input.key);
let next = s;
for (const key of keys) next = closeKey(next, key);
return next;
@@ -1164,7 +1172,14 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "project.copyAbsolutePath", arg: path, label: "Absolute Path" },
{ kind: "action", action: "project.copyFileName", arg: path, label: "File Name" },
...(inProject
- ? ([{ kind: "action", action: "project.copyRelativePath", arg: path, label: "Path From Content Root" }] as MenuItem[])
+ ? ([
+ {
+ kind: "action",
+ action: "project.copyRelativePath",
+ arg: path,
+ label: "Path From Content Root",
+ },
+ ] as MenuItem[])
: []),
],
},
diff --git a/src/editor/core/extras.ts b/src/editor/core/extras.ts
index ae200c9dc..5e1f7d035 100644
--- a/src/editor/core/extras.ts
+++ b/src/editor/core/extras.ts
@@ -34,7 +34,12 @@ export function pasteFromHistory(view: EditorView) {
id: `${i}`,
label,
detail,
- preview: text.split(/\r\n?|\n/).slice(1, 4).join(" ⏎ ").trim() || undefined,
+ preview:
+ text
+ .split(/\r\n?|\n/)
+ .slice(1, 4)
+ .join(" ⏎ ")
+ .trim() || undefined,
run: () => {
recordClipboard(text);
void navigator.clipboard?.writeText(text).catch(() => {});
diff --git a/src/editor/core/model/document.test.ts b/src/editor/core/model/document.test.ts
index 538fd2fa7..f21b62e60 100644
--- a/src/editor/core/model/document.test.ts
+++ b/src/editor/core/model/document.test.ts
@@ -22,10 +22,8 @@ function setup(files: Record<string, string>, settings = {}) {
_resetLanguages();
const backend: MemoryBackend = createMemoryBackend(files);
const scheduled: Array<() => void> = [];
- const manager = new DocumentManager(
- backend,
- { settings: () => settings, notify: vi.fn() },
- (fn) => scheduled.push(fn),
+ const manager = new DocumentManager(backend, { settings: () => settings, notify: vi.fn() }, (fn) =>
+ scheduled.push(fn),
);
manager.start();
const frame = async () => {
@@ -108,7 +106,10 @@ describe("save cleanup", () => {
it("keeps the caret line and untouched lines", () => {
const state = EditorState.create({ doc: "a \nb \nc " });
const m = new ModifiedRanges();
- m.ranges = [[0, 3], [8, 11]];
+ m.ranges = [
+ [0, 3],
+ [8, 11],
+ ];
const changes = saveCleanupChanges(state, m, { trim: true, finalNewline: true, protectLines: new Set([3]) });
expect(changes).toEqual([
{ from: 1, to: 3 },
diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts
index 2550294e5..f741223f9 100644
--- a/src/editor/core/model/document.ts
+++ b/src/editor/core/model/document.ts
@@ -7,7 +7,16 @@ import { EditorView } from "@codemirror/view";
import type { LanguageDescription, LanguageSupport } from "@codemirror/language";
import { create } from "zustand";
import type { EditorConfigProps } from "@/bindings";
-import type { DocId, DocumentInfo, EditorSettings, FileSettings, LineEnding, OutlineItem, Settings, SyntaxHighlights } from "@/platform/ipc";
+import type {
+ DocId,
+ DocumentInfo,
+ EditorSettings,
+ FileSettings,
+ LineEnding,
+ OutlineItem,
+ Settings,
+ SyntaxHighlights,
+} from "@/platform/ipc";
import {
_emitEditorEvent,
_saveParticipants,
@@ -20,7 +29,14 @@ import {
import { isVirtualUri } from "@/platform/virtualDocs";
import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync";
import type { DocBackend, LanguageInfo } from "../backend";
-import { findLanguageDescription, languageInfo, loadLanguageInfos, loadSupport, loadedSupport, commentTokens } from "../cm/languages";
+import {
+ findLanguageDescription,
+ languageInfo,
+ loadLanguageInfos,
+ loadSupport,
+ loadedSupport,
+ commentTokens,
+} from "../cm/languages";
import { foldEffect } from "@codemirror/language";
import { backendFolds, setBackendFolds } from "../cm/folding";
import { setSyntaxHighlights } from "../cm/syntaxHighlight";
@@ -137,7 +153,13 @@ export function methodLines(items: readonly OutlineItem[]): number[] {
export function saveCleanupChanges(
state: EditorState,
modified: ModifiedRanges,
- opts: { trim: boolean; finalNewline: boolean; protectLines: Set<number>; allLines?: boolean; trailingBlankLines?: boolean },
+ opts: {
+ trim: boolean;
+ finalNewline: boolean;
+ protectLines: Set<number>;
+ allLines?: boolean;
+ trailingBlankLines?: boolean;
+ },
): Array<{ from: number; to: number; insert?: string }> {
const changes: Array<{ from: number; to: number; insert?: string }> = [];
const doc = state.doc;
@@ -274,7 +296,8 @@ export class DocModel {
addSlot(slot: EditorSlot) {
this.slots.add(slot);
- if (this.highlights?.counter === this.changeCounter) slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
+ if (this.highlights?.counter === this.changeCounter)
+ slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
}
removeSlot(slot: EditorSlot) {
@@ -320,7 +343,8 @@ export class DocModel {
this.modified.map(cs);
this.changeCounter++;
const primary = this.primarySlot();
- for (const s of this.slots) s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(s === primary)]);
+ for (const s of this.slots)
+ s.applyExternal(cs, [remoteChange.of(true), Transaction.addToHistory.of(s === primary)]);
// Without a tab, the first attached view keeps backend edits (Replace in Files…) undoable.
let first = !primary;
for (const a of this.attachments) {
@@ -405,7 +429,13 @@ export class DocModel {
compartments.heavy.reconfigure(heavyExtension(this.sync.localText.length, editor)),
compartments.distractionFree.reconfigure(distractionFreeExtension(editor)),
compartments.prefs.reconfigure(
- prefsFor({ settings: editor, path: this.path, info: this.info, readOnly: this.meta.readOnly, wrapOverride: this.softWrapOverride }),
+ prefsFor({
+ settings: editor,
+ path: this.path,
+ info: this.info,
+ readOnly: this.meta.readOnly,
+ wrapOverride: this.softWrapOverride,
+ }),
),
];
// LSP contributions read completion / hover timings when they are built.
@@ -422,12 +452,25 @@ export class DocModel {
setReadOnly(readOnly: boolean) {
if (readOnly === this.meta.readOnly) return;
const banner = this.meta.banner;
- this.setMeta({ readOnly, banner: readOnly ? (banner ?? (this.virtual ? null : "readOnly")) : banner === "readOnly" || banner === "library" ? null : banner });
+ this.setMeta({
+ readOnly,
+ banner: readOnly
+ ? (banner ?? (this.virtual ? null : "readOnly"))
+ : banner === "readOnly" || banner === "library"
+ ? null
+ : banner,
+ });
for (const s of this.slots) {
s.reconfigure([
compartments.readOnly.reconfigure(readOnlyExtension(readOnly)),
compartments.prefs.reconfigure(
- prefsFor({ settings: this.settings(), path: this.path, info: this.info, readOnly, wrapOverride: this.softWrapOverride }),
+ prefsFor({
+ settings: this.settings(),
+ path: this.path,
+ info: this.info,
+ readOnly,
+ wrapOverride: this.softWrapOverride,
+ }),
),
]);
s.syncContributions(true);
diff --git a/src/editor/core/model/editHistory.ts b/src/editor/core/model/editHistory.ts
index 4cb22e7e6..f682bff20 100644
--- a/src/editor/core/model/editHistory.ts
+++ b/src/editor/core/model/editHistory.ts
@@ -18,7 +18,8 @@ export class EditHistory {
record(loc: Place) {
const last = this.entries[this.entries.length - 1];
- if (last && last.path === loc.path && Math.abs(last.line - loc.line) <= MERGE_LINES) this.entries[this.entries.length - 1] = { ...loc };
+ if (last && last.path === loc.path && Math.abs(last.line - loc.line) <= MERGE_LINES)
+ this.entries[this.entries.length - 1] = { ...loc };
else {
this.entries = this.entries.filter((e) => e.path !== loc.path || Math.abs(e.line - loc.line) > MERGE_LINES);
this.entries.push({ ...loc });
diff --git a/src/editor/core/model/navHistory.ts b/src/editor/core/model/navHistory.ts
index 384612a3a..2e4e2fb0f 100644
--- a/src/editor/core/model/navHistory.ts
+++ b/src/editor/core/model/navHistory.ts
@@ -17,8 +17,8 @@ export const NAVIGATE_EVENT = "select.navigate";
/** Caret moves that count as navigation: mouse clicks, find, reveals, stripe / sticky-line clicks, navigate commands. */
export function isNavigation(tr: Transaction): boolean {
- return ["select.pointer", "select.reveal", "select.search", "select.overview", "select.sticky", NAVIGATE_EVENT].some((e) =>
- tr.isUserEvent(e),
+ return ["select.pointer", "select.reveal", "select.search", "select.overview", "select.sticky", NAVIGATE_EVENT].some(
+ (e) => tr.isUserEvent(e),
);
}
const MAX_ENTRIES = 100;
diff --git a/src/editor/core/model/session.test.ts b/src/editor/core/model/session.test.ts
index 11697d129..3b512109f 100644
--- a/src/editor/core/model/session.test.ts
+++ b/src/editor/core/model/session.test.ts
@@ -1,5 +1,14 @@
import { describe, expect, it } from "vitest";
-import { initialTabsState, moveTabToNewSplit, openTab, paneIds, splitAtEdge, splitPane, togglePin, type TabsState } from "./tabs";
+import {
+ initialTabsState,
+ moveTabToNewSplit,
+ openTab,
+ paneIds,
+ splitAtEdge,
+ splitPane,
+ togglePin,
+ type TabsState,
+} from "./tabs";
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
@@ -19,7 +28,10 @@ describe("editor session", () => {
const first = s.activePane;
s = splitPane(s, first, "column").state;
s = open(s, "/p/d.ts");
- const session = serializeSession(s, { "/p/a.ts": { anchor: 3, head: 5, topLine: 10 }, "/p/zzz.ts": { anchor: 0, head: 0 } })!;
+ const session = serializeSession(s, {
+ "/p/a.ts": { anchor: 3, head: 5, topLine: 10 },
+ "/p/zzz.ts": { anchor: 0, head: 0 },
+ })!;
expect(session.layout.kind).toBe("split");
expect(session.activePane).toBe(1);
expect(Object.keys(session.files)).toEqual(["/p/a.ts"]);
@@ -50,7 +62,10 @@ describe("editor session", () => {
expect(session.layout).toMatchObject({ kind: "pane", active: 1 });
const r = restoreTabsState(parseSession(JSON.parse(JSON.stringify(session)))!, fileKey);
const pane = r.panes[paneIds(r)[0]!]!;
- expect(pane.tabs.map((t) => t.input)).toEqual([file("/p/a.ts"), { kind: "agent-session", key: "agent:1", data: { task: "1" } }]);
+ expect(pane.tabs.map((t) => t.input)).toEqual([
+ file("/p/a.ts"),
+ { kind: "agent-session", key: "agent:1", data: { task: "1" } },
+ ]);
expect(pane.active).toBe(pane.tabs[1]!.id);
// Only restorable tabs: still a session. Junk inputs (file kind, no key) are dropped.
const empty = initialTabsState();
@@ -59,7 +74,11 @@ describe("editor session", () => {
expect(serializeSession(only, {})).toBeNull();
const junk = parseSession({
version: 1,
- layout: { kind: "pane", tabs: [{ input: { kind: "file", key: "k" } }, { input: { kind: "x" } }, { input: { kind: "x", key: "y" } }], active: 0 },
+ layout: {
+ kind: "pane",
+ tabs: [{ input: { kind: "file", key: "k" } }, { input: { kind: "x" } }, { input: { kind: "x", key: "y" } }],
+ active: 0,
+ },
})!;
expect(junk.layout).toEqual({ kind: "pane", tabs: [{ input: { kind: "x", key: "y" } }], active: 0 });
});
@@ -71,7 +90,11 @@ describe("editor session", () => {
const ok = parseSession({
version: 1,
activePane: 7,
- layout: { kind: "split", dir: "row", children: [{ kind: "pane", tabs: [{ path: "/x" }], active: 9 }, { kind: "bogus" }] },
+ layout: {
+ kind: "split",
+ dir: "row",
+ children: [{ kind: "pane", tabs: [{ path: "/x" }], active: 9 }, { kind: "bogus" }],
+ },
files: { "/x": { anchor: 1, head: -1 } },
})!;
expect(ok.layout).toEqual({ kind: "pane", tabs: [{ path: "/x" }], active: 0 });
@@ -109,7 +132,13 @@ describe("moveTabToNewSplit", () => {
const split = splitPane(s, first, "row");
s = open(split.state, "/b");
const bTab = s.panes[split.paneId]!.tabs.find((t) => t.input.path === "/b")!;
- s = { ...s, panes: { ...s.panes, [split.paneId]: { ...s.panes[split.paneId]!, tabs: [bTab], active: bTab.id, mru: [bTab.id] } } };
+ s = {
+ ...s,
+ panes: {
+ ...s.panes,
+ [split.paneId]: { ...s.panes[split.paneId]!, tabs: [bTab], active: bTab.id, mru: [bTab.id] },
+ },
+ };
const r = moveTabToNewSplit(s, split.paneId, bTab.id, first, "bottom")!;
expect(r.state.panes[split.paneId]).toBeUndefined();
expect(r.state.layout).toMatchObject({ kind: "split", dir: "column" });
diff --git a/src/editor/core/model/session.ts b/src/editor/core/model/session.ts
index 19987a25f..be5930b46 100644
--- a/src/editor/core/model/session.ts
+++ b/src/editor/core/model/session.ts
@@ -54,7 +54,10 @@ export function serializeSession(
if (!pane) return null;
const kept = pane.tabs.filter(saved);
if (!kept.length) return null;
- const active = Math.max(0, kept.findIndex((t) => t.id === pane.active));
+ const active = Math.max(
+ 0,
+ kept.findIndex((t) => t.id === pane.active),
+ );
return {
kind: "pane",
tabs: kept.map((t) => ({
@@ -131,10 +134,19 @@ export function parseSession(raw: unknown): EditorSession | null {
for (const [path, v] of Object.entries(r.files)) {
const f = v as Partial<FileViewState> | null;
if (f && Number.isInteger(f.anchor) && Number.isInteger(f.head) && f.anchor! >= 0 && f.head! >= 0)
- files[slashPath(path)] = { anchor: f.anchor!, head: f.head!, ...(Number.isInteger(f.topLine) && f.topLine! >= 0 ? { topLine: f.topLine } : {}) };
+ files[slashPath(path)] = {
+ anchor: f.anchor!,
+ head: f.head!,
+ ...(Number.isInteger(f.topLine) && f.topLine! >= 0 ? { topLine: f.topLine } : {}),
+ };
}
}
- return { version: 1, layout, activePane: typeof r.activePane === "number" ? Math.max(0, Math.floor(r.activePane)) : 0, files };
+ return {
+ version: 1,
+ layout,
+ activePane: typeof r.activePane === "number" ? Math.max(0, Math.floor(r.activePane)) : 0,
+ files,
+ };
}
let seq = 0;
@@ -167,7 +179,12 @@ export function restoreTabsState(session: EditorSession, fileKey: (path: string)
tabs.sort((a, b) => Number(b.pinned) - Number(a.pinned));
const activeTab = l.tabs[l.active];
const active = (activeTab && byKey.get(tabKey(activeTab))) ?? tabs[0]!;
- panes[paneId] = { id: paneId, tabs, active: active.id, mru: [active.id, ...tabs.filter((t) => t !== active).map((t) => t.id)] };
+ panes[paneId] = {
+ id: paneId,
+ tabs,
+ active: active.id,
+ mru: [active.id, ...tabs.filter((t) => t !== active).map((t) => t.id)],
+ };
order.push(paneId);
return { kind: "pane", paneId };
}
diff --git a/src/editor/core/model/slot.ts b/src/editor/core/model/slot.ts
index 3352d91b5..fdd5684f7 100644
--- a/src/editor/core/model/slot.ts
+++ b/src/editor/core/model/slot.ts
@@ -18,7 +18,14 @@ import {
type TransactionSpec,
} from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
-import { _addEditor, _removeEditor, documentSynced, isExternalChange, type EditorDocContext, type TextEditorHandle } from "@/editor/api";
+import {
+ _addEditor,
+ _removeEditor,
+ documentSynced,
+ isExternalChange,
+ type EditorDocContext,
+ type TextEditorHandle,
+} from "@/editor/api";
import { showContextMenu } from "@/ui";
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
@@ -186,7 +193,13 @@ export class EditorSlot {
}
if (tr.docChanged && !isExternalChange(tr)) {
this.model.onLocal(tr.changes, this);
- if (tr.isUserEvent("input") || tr.isUserEvent("delete") || tr.isUserEvent("move") || tr.isUserEvent("undo") || tr.isUserEvent("redo"))
+ if (
+ tr.isUserEvent("input") ||
+ tr.isUserEvent("delete") ||
+ tr.isUserEvent("move") ||
+ tr.isUserEvent("undo") ||
+ tr.isUserEvent("redo")
+ )
this.host.onUserEdit(this, tr);
}
if (tr.selection || tr.docChanged) selection = true;
@@ -241,7 +254,9 @@ export class EditorSlot {
}
this.view.dispatch({
selection: EditorSelection.single(anchor, head),
- effects: EditorView.scrollIntoView(EditorSelection.range(anchor, head), { y: r.center === false ? "nearest" : "center" }),
+ effects: EditorView.scrollIntoView(EditorSelection.range(anchor, head), {
+ y: r.center === false ? "nearest" : "center",
+ }),
userEvent: "select.reveal",
});
}
@@ -256,9 +271,14 @@ export class EditorSlot {
/** Restores a saved caret / scroll position (session restore). */
restoreView(v: { anchor: number; head: number; topLine?: number }) {
const doc = this.currentState().doc;
- const selection = EditorSelection.single(Math.min(Math.max(0, v.anchor), doc.length), Math.min(Math.max(0, v.head), doc.length));
+ const selection = EditorSelection.single(
+ Math.min(Math.max(0, v.anchor), doc.length),
+ Math.min(Math.max(0, v.head), doc.length),
+ );
const scroll =
- v.topLine !== undefined ? EditorView.scrollIntoView(doc.line(Math.min(v.topLine + 1, doc.lines)).from, { y: "start" }) : null;
+ v.topLine !== undefined
+ ? EditorView.scrollIntoView(doc.line(Math.min(v.topLine + 1, doc.lines)).from, { y: "start" })
+ : null;
if (this.view) {
this.view.dispatch({ selection, effects: scroll ? [scroll] : [] });
return;
diff --git a/src/editor/core/model/tabs.ts b/src/editor/core/model/tabs.ts
index 7a8a52c2a..0ed7a5389 100644
--- a/src/editor/core/model/tabs.ts
+++ b/src/editor/core/model/tabs.ts
@@ -55,7 +55,12 @@ const nextId = (p: string) => `${p}${++seq}`;
export function initialTabsState(): TabsState {
const id = nextId("pane");
- return { layout: { kind: "pane", paneId: id }, panes: { [id]: { id, tabs: [], active: null, mru: [] } }, activePane: id, closed: [] };
+ return {
+ layout: { kind: "pane", paneId: id },
+ panes: { [id]: { id, tabs: [], active: null, mru: [] } },
+ activePane: id,
+ closed: [],
+ };
}
export function paneOf(s: TabsState, paneId: string): Pane {
@@ -206,10 +211,17 @@ function removeTabs(s: TabsState, paneId: string, ids: Set<string>): TabsState {
let active = pane.active;
if (active && ids.has(active)) {
const at = pane.tabs.findIndex((t) => t.id === active);
- const left = pane.tabs.slice(0, at).reverse().find((t) => !ids.has(t.id));
+ const left = pane.tabs
+ .slice(0, at)
+ .reverse()
+ .find((t) => !ids.has(t.id));
const right = pane.tabs.slice(at + 1).find((t) => !ids.has(t.id));
const pick =
- tabOptions.activateOnClose === "left" ? (left ?? right) : tabOptions.activateOnClose === "right" ? (right ?? left) : undefined;
+ tabOptions.activateOnClose === "left"
+ ? (left ?? right)
+ : tabOptions.activateOnClose === "right"
+ ? (right ?? left)
+ : undefined;
active = pick?.id ?? mru[0] ?? tabs[0]?.id ?? null;
}
pane = { ...pane, tabs, mru, active };
@@ -241,14 +253,32 @@ export function closeToRight(s: TabsState, paneId: string, tabId: string): TabsS
const pane = paneOf(s, paneId);
const idx = pane.tabs.findIndex((t) => t.id === tabId);
if (idx < 0) return s;
- return removeTabs(s, paneId, new Set(pane.tabs.slice(idx + 1).filter((t) => !t.pinned).map((t) => t.id)));
+ return removeTabs(
+ s,
+ paneId,
+ new Set(
+ pane.tabs
+ .slice(idx + 1)
+ .filter((t) => !t.pinned)
+ .map((t) => t.id),
+ ),
+ );
}
export function closeToLeft(s: TabsState, paneId: string, tabId: string): TabsState {
const pane = paneOf(s, paneId);
const idx = pane.tabs.findIndex((t) => t.id === tabId);
if (idx < 0) return s;
- return removeTabs(s, paneId, new Set(pane.tabs.slice(0, idx).filter((t) => !t.pinned).map((t) => t.id)));
+ return removeTabs(
+ s,
+ paneId,
+ new Set(
+ pane.tabs
+ .slice(0, idx)
+ .filter((t) => !t.pinned)
+ .map((t) => t.id),
+ ),
+ );
}
/** IDEA "Close Unmodified Tabs": closes the unpinned tabs `modified` says no to. */
@@ -283,7 +313,10 @@ export function reopenClosed(s: TabsState): { state: TabsState; tabId: string; p
const entry = closed.pop()!;
if (openNow.has(entry.input.key) && findTab(s, entry.input.key, entry.paneId)?.paneId === entry.paneId) continue;
const paneId = s.panes[entry.paneId] ? entry.paneId : s.activePane;
- const { state, tabId } = openTab({ ...s, closed }, paneId, entry.input, { index: entry.index, pinned: entry.pinned });
+ const { state, tabId } = openTab({ ...s, closed }, paneId, entry.input, {
+ index: entry.index,
+ pinned: entry.pinned,
+ });
return { state, tabId, paneId };
}
return null;
@@ -325,7 +358,10 @@ export function sortTabs(s: TabsState, paneId: string, title: (t: Tab) => string
const pane = paneOf(s, paneId);
const byTitle = (a: Tab, b: Tab) =>
title(a).localeCompare(title(b), undefined, { sensitivity: "base" }) || title(a).localeCompare(title(b));
- const tabs = [...pane.tabs.filter((t) => t.pinned).sort(byTitle), ...pane.tabs.filter((t) => !t.pinned).sort(byTitle)];
+ const tabs = [
+ ...pane.tabs.filter((t) => t.pinned).sort(byTitle),
+ ...pane.tabs.filter((t) => !t.pinned).sort(byTitle),
+ ];
return tabs.every((t, i) => t === pane.tabs[i]) ? s : withPane(s, { ...pane, tabs });
}
diff --git a/src/editor/core/view/Banner.tsx b/src/editor/core/view/Banner.tsx
index c88911316..0023ee02a 100644
--- a/src/editor/core/view/Banner.tsx
+++ b/src/editor/core/view/Banner.tsx
@@ -18,7 +18,9 @@ export const documentBanner: EditorBannerContribution = {
order: -10,
useBanner: (path) => {
const banner = useDocMeta((s) => s[path]?.banner ?? null);
- return banner ? { text: TEXT[banner], icon: banner === "readOnly" || banner === "library" ? "lock" : "info" } : null;
+ return banner
+ ? { text: TEXT[banner], icon: banner === "readOnly" || banner === "library" ? "lock" : "info" }
+ : null;
},
};
diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx
index 2dd7b4990..71899f5e0 100644
--- a/src/editor/core/view/EditorArea.tsx
+++ b/src/editor/core/view/EditorArea.tsx
@@ -81,7 +81,11 @@ export const EDITOR_TAB_MIME = "application/x-openidea-editor-tab";
type DropZone = SplitEdge | "center";
/** Where a tab dropped at (x, y) over an editor goes: an edge (new split) or the pane itself. */
-export function dropZoneAt(x: number, y: number, rect: { left: number; top: number; width: number; height: number }): DropZone {
+export function dropZoneAt(
+ x: number,
+ y: number,
+ rect: { left: number; top: number; width: number; height: number },
+): DropZone {
const fx = (x - rect.left) / Math.max(1, rect.width);
const fy = (y - rect.top) / Math.max(1, rect.height);
const edges: Array<[SplitEdge, number]> = [
@@ -108,7 +112,8 @@ function useTitleHints(): Map<string, string> {
const paths = useTabs(
useShallow((s) => {
const out: string[] = [];
- for (const p of Object.values(s.panes)) for (const t of p.tabs) if (t.input.kind === "file" && t.input.path) out.push(t.input.path);
+ for (const p of Object.values(s.panes))
+ for (const t of p.tabs) if (t.input.kind === "file" && t.input.path) out.push(t.input.path);
return out.sort();
}),
);
@@ -133,7 +138,8 @@ function PaneView({ paneId }: { paneId: string }) {
const [dropZone, setDropZone] = useState<DropZone | null>(null);
const tabPrefs = useEditorPrefs().tabs;
const distractionFree = useDistractionFree((s) => s.active);
- const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } = tabPrefs;
+ const { showExtension, markModified, showCloseButton, showFileIcon, showDirectoryForNonUnique, showFullPathOnHover } =
+ tabPrefs;
const items: TabItem[] = useMemo(() => {
const names = tabs.map((t) => tabTitle(t.input, kinds));
@@ -266,7 +272,9 @@ function PaneView({ paneId }: { paneId: string }) {
const at = { x: e.clientX, y: e.clientY };
const path = tab.input.kind === "file" ? tab.input.path : undefined;
if (!path) return showContextMenu(at, ctrl.tabMenu(paneId, tab));
- void prepareMenuGroups("editorTab", { paths: [path] }).then(() => showContextMenu(at, ctrl.tabMenu(paneId, tab)));
+ void prepareMenuGroups("editorTab", { paths: [path] }).then(() =>
+ showContextMenu(at, ctrl.tabMenu(paneId, tab)),
+ );
}}
trailing={trailing}
/>
diff --git a/src/editor/core/view/StatusItems.tsx b/src/editor/core/view/StatusItems.tsx
index 73443efa1..082851bab 100644
--- a/src/editor/core/view/StatusItems.tsx
+++ b/src/editor/core/view/StatusItems.tsx
@@ -361,7 +361,12 @@ export function ReadOnlyStatus() {
if (!meta || isVirtualUri(meta.path) || meta.banner === "binary" || meta.banner === "tooLarge") return null;
const label = meta.readOnly ? "Make file writable" : "Make file read-only";
return (
- <BarButton tooltip={label} aria-label={label} aria-pressed={meta.readOnly} onClick={() => void executeAction("file.toggleReadOnly")}>
+ <BarButton
+ tooltip={label}
+ aria-label={label}
+ aria-pressed={meta.readOnly}
+ onClick={() => void executeAction("file.toggleReadOnly")}
+ >
<span className={styles.lock}>
<Icon name={meta.readOnly ? "lock" : "unlock"} size={14} />
</span>
diff --git a/src/editor/core/view/TextEditorHost.tsx b/src/editor/core/view/TextEditorHost.tsx
index 79cd5d38c..edbcb43cc 100644
--- a/src/editor/core/view/TextEditorHost.tsx
+++ b/src/editor/core/view/TextEditorHost.tsx
@@ -37,7 +37,5 @@ export function TextEditorHost({ tabId }: { tabId: string }) {
</EmptyState>
</div>
);
- return (
- <div ref={ref} className={styles.host} data-editor-host="" aria-busy={!slot || undefined} />
- );
+ return <div ref={ref} className={styles.host} data-editor-host="" aria-busy={!slot || undefined} />;
}
diff --git a/src/editor/core/view/navBar.test.ts b/src/editor/core/view/navBar.test.ts
index ab5d7ebf4..72f6e8ec4 100644
--- a/src/editor/core/view/navBar.test.ts
+++ b/src/editor/core/view/navBar.test.ts
@@ -3,22 +3,50 @@ import type { FileEntry, OutlineItem } from "@/platform/ipc";
import { dirChildren, navSegments, stepSegment, symbolChildren } from "./navBar";
const r = { start: { line: 0, col: 0 }, end: { line: 9, col: 0 } };
-const sym = (name: string, children: OutlineItem[] = []): OutlineItem => ({ name, kind: "class", detail: null, range: r, selection_range: r, children });
+const sym = (name: string, children: OutlineItem[] = []): OutlineItem => ({
+ name,
+ kind: "class",
+ detail: null,
+ range: r,
+ selection_range: r,
+ children,
+});
describe("navigation bar popup model", () => {
it("lists project › dirs › file › symbols, skipping the class named like its file", () => {
const segs = navSegments({ root: "/p", name: "proj" }, "/p/src/a/Foo.java", [sym("Foo"), sym("run")]);
- expect(segs.map((s) => `${s.kind}:${s.label}`)).toEqual(["dir:proj", "dir:src", "dir:a", "file:Foo.java", "symbol:run"]);
+ expect(segs.map((s) => `${s.kind}:${s.label}`)).toEqual([
+ "dir:proj",
+ "dir:src",
+ "dir:a",
+ "file:Foo.java",
+ "symbol:run",
+ ]);
expect(segs[2]).toMatchObject({ path: "/p/src/a" });
});
it("shows only the parent folder outside the project (scratches)", () => {
- expect(navSegments({ root: "/p", name: "proj" }, "/data/scratches/scratch.py", []).map((s) => s.label)).toEqual(["scratches", "scratch.py"]);
+ expect(navSegments({ root: "/p", name: "proj" }, "/data/scratches/scratch.py", []).map((s) => s.label)).toEqual([
+ "scratches",
+ "scratch.py",
+ ]);
});
it("lists folder children without IDE-hidden names, and symbol children", () => {
- const e = (name: string, kind: FileEntry["kind"]) => ({ name, path: `/p/${name}`, kind, size: 0, mtimeMs: 0, ignored: false, excluded: false, hidden: false }) as FileEntry;
- expect(dirChildren([e(".git", "dir"), e("src", "dir"), e("a.ts", "file")]).map((c) => `${c.kind}:${c.label}`)).toEqual(["dir:src", "file:a.ts"]);
+ const e = (name: string, kind: FileEntry["kind"]) =>
+ ({
+ name,
+ path: `/p/${name}`,
+ kind,
+ size: 0,
+ mtimeMs: 0,
+ ignored: false,
+ excluded: false,
+ hidden: false,
+ }) as FileEntry;
+ expect(
+ dirChildren([e(".git", "dir"), e("src", "dir"), e("a.ts", "file")]).map((c) => `${c.kind}:${c.label}`),
+ ).toEqual(["dir:src", "file:a.ts"]);
expect(symbolChildren("/p/a.ts", [sym("A", [sym("b")])]).map((c) => c.label)).toEqual(["A"]);
});
diff --git a/src/editor/core/view/navChildren.test.tsx b/src/editor/core/view/navChildren.test.tsx
index 14ff595d4..51082f2e0 100644
--- a/src/editor/core/view/navChildren.test.tsx
+++ b/src/editor/core/view/navChildren.test.tsx
@@ -21,7 +21,9 @@ describe("status bar navigation bar popup", () => {
const anchor = document.createElement("button");
document.body.appendChild(anchor);
const onClose = vi.fn();
- render(<NavChildrenPopup segment={{ kind: "file", path: "/p/a.ts", label: "a.ts" }} anchor={anchor} onClose={onClose} />);
+ render(
+ <NavChildrenPopup segment={{ kind: "file", path: "/p/a.ts", label: "a.ts" }} anchor={anchor} onClose={onClose} />,
+ );
await act(async () => {});
const list = screen.getByRole("listbox", { name: "a.ts" });
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["first", "second"]);
diff --git a/src/editor/core/virtual.test.ts b/src/editor/core/virtual.test.ts
index f14ea14b8..ceb24d9e3 100644
--- a/src/editor/core/virtual.test.ts
+++ b/src/editor/core/virtual.test.ts
@@ -2,25 +2,24 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { VirtualDocument } from "@/platform/ipc";
const JDT = "jdt://contents/lib-1.0.jar/org.example/Lib.class?=demo/%5C/m2%5C/lib-1.0.jar%3Corg.example%28Lib.class";
-const TEXT = "// Source code is unavailable, and was generated by the Fernflower decompiler.\npackage org.example;\n\npublic class Lib {\n void run() {}\n}\n";
+const TEXT =
+ "// Source code is unavailable, and was generated by the Fernflower decompiler.\npackage org.example;\n\npublic class Lib {\n void run() {}\n}\n";
vi.mock("@/platform/virtualDocs", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/virtualDocs")>();
return {
...actual,
- virtualDocument: vi.fn(
- async (uri: string): Promise<VirtualDocument> => {
- if (uri !== JDT) throw new Error(`no contents for ${uri}`);
- return {
- uri,
- text: TEXT,
- languageId: "java",
- title: "Lib.class",
- description: "/m2/lib-1.0.jar",
- decompiled: true,
- };
- },
- ),
+ virtualDocument: vi.fn(async (uri: string): Promise<VirtualDocument> => {
+ if (uri !== JDT) throw new Error(`no contents for ${uri}`);
+ return {
+ uri,
+ text: TEXT,
+ languageId: "java",
+ title: "Lib.class",
+ description: "/m2/lib-1.0.jar",
+ decompiled: true,
+ };
+ }),
};
});
@@ -81,7 +80,11 @@ describe("virtual editor input", () => {
const session = serializeSession(useTabs.getState(), {});
expect(JSON.stringify(session)).not.toContain("jdt:");
- expect(ctrl.tabMenu(useTabs.getState().activePane, activeTab()).some((i) => "label" in i && i.label === "Reveal in Project")).toBe(false);
+ expect(
+ ctrl
+ .tabMenu(useTabs.getState().activePane, activeTab())
+ .some((i) => "label" in i && i.label === "Reveal in Project"),
+ ).toBe(false);
});
it("does not open a tab when the server has no contents", async () => {
diff --git a/src/editor/lsp/Popups.test.tsx b/src/editor/lsp/Popups.test.tsx
index a5217ead5..7237641d9 100644
--- a/src/editor/lsp/Popups.test.tsx
+++ b/src/editor/lsp/Popups.test.tsx
@@ -117,7 +117,10 @@ describe("list popup", () => {
it("shows the selected row's preview, fetched lazily", async () => {
vi.useFakeTimers();
try {
- const preview = vi.fn(async () => ({ kind: "diff" as const, lines: [{ kind: "added" as const, text: "let x = 1;" }] }));
+ const preview = vi.fn(async () => ({
+ kind: "diff" as const,
+ lines: [{ kind: "added" as const, text: "let x = 1;" }],
+ }));
openPopup({
kind: "list",
anchor: { x: 0, y: 0 },
@@ -171,7 +174,9 @@ describe("documentation", () => {
fireEvent.keyDown(frame(), { key: "ArrowRight" });
expect(frame().textContent).toContain("second");
fireEvent.keyDown(frame(), { key: "F4" });
- await vi.waitFor(() => expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }));
+ await vi.waitFor(() =>
+ expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }),
+ );
expect(container).toBeTruthy();
});
diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts
index 158247ecc..69962eaf1 100644
--- a/src/editor/lsp/actions.ts
+++ b/src/editor/lsp/actions.ts
@@ -101,10 +101,17 @@ async function cleanup(view: EditorView, o: CleanupOptions) {
}
/** Code action titles of Implement Methods (⌃I) and Override Methods (⌃O). */
-export const IMPLEMENT_TITLE = /\bimplement\b|\b(add|generate) (missing|unimplemented|all missing)\b|missing (members|methods|trait items)/i;
+export const IMPLEMENT_TITLE =
+ /\bimplement\b|\b(add|generate) (missing|unimplemented|all missing)\b|missing (members|methods|trait items)/i;
export const OVERRIDE_TITLE = /\boverride\b/i;
-function editorAction(id: string, title: string, category: string, run: (view: EditorView) => unknown, extra: Partial<Action> = {}): Action {
+function editorAction(
+ id: string,
+ title: string,
+ category: string,
+ run: (view: EditorView) => unknown,
+ extra: Partial<Action> = {},
+): Action {
return { id, title, category, when: EDITOR_WHEN, run: withEditor(run), ...extra };
}
@@ -149,9 +156,15 @@ export function registerLspActions(): () => void {
keywords: ["javadoc", "docs", "hover"],
}),
editorAction("code.quickDefinition", "Quick Definition", "Code", quickDefinition),
- editorAction("code.quickTypeDefinition", "Quick Type Definition", "View", (v) => quickDefinition(v, "typeDefinition"), {
- keywords: ["type declaration", "preview"],
- }),
+ editorAction(
+ "code.quickTypeDefinition",
+ "Quick Type Definition",
+ "View",
+ (v) => quickDefinition(v, "typeDefinition"),
+ {
+ keywords: ["type declaration", "preview"],
+ },
+ ),
editorAction("code.showIntentions", "Show Context Actions", "Code", showIntentions, {
keywords: ["intention", "quick fix", "lightbulb"],
}),
@@ -164,13 +177,23 @@ export function registerLspActions(): () => void {
editorAction("code.reformatDialog", "Reformat File…", "Code", (v) =>
reformatDialog(v, (view) => applyKindSilently(view, "source.organizeImports")),
),
- editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, { keywords: ["organize imports"] }),
+ editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, {
+ keywords: ["organize imports"],
+ }),
// Project view / editor tab variants: `{ path }` of a file, opened first.
- { id: "code.reformatFile", title: "Reformat File", category: "Code", hidden: true, when: "projectOpen", run: inFile(reformat) },
+ {
+ id: "code.reformatFile",
+ title: "Reformat File",
+ category: "Code",
+ hidden: true,
+ when: "projectOpen",
+ run: inFile(reformat),
+ },
{
id: "code.cleanupFile",
title: "Code Cleanup in File",
- description: "Code Cleanup on `{ path, fixAll?, optimizeImports?, reformat? }` (all steps by default), opened first.",
+ description:
+ "Code Cleanup on `{ path, fixAll?, optimizeImports?, reformat? }` (all steps by default), opened first.",
category: "Code",
hidden: true,
when: "projectOpen",
@@ -187,11 +210,21 @@ export function registerLspActions(): () => void {
when: "projectOpen",
run: inFile(optimizeImports),
},
- editorAction("navigate.declaration", "Go to Declaration or Usages", "Navigate", (v) => gotoTargets(v, "definition"), {
- keywords: ["definition"],
- }),
- editorAction("navigate.implementation", "Go to Implementation(s)", "Navigate", (v) => gotoTargets(v, "implementation")),
- editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) => gotoTargets(v, "typeDefinition")),
+ editorAction(
+ "navigate.declaration",
+ "Go to Declaration or Usages",
+ "Navigate",
+ (v) => gotoTargets(v, "definition"),
+ {
+ keywords: ["definition"],
+ },
+ ),
+ editorAction("navigate.implementation", "Go to Implementation(s)", "Navigate", (v) =>
+ gotoTargets(v, "implementation"),
+ ),
+ editorAction("navigate.typeDeclaration", "Go to Type Declaration", "Navigate", (v) =>
+ gotoTargets(v, "typeDefinition"),
+ ),
editorAction("navigate.nextError", "Next Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, 1)),
editorAction("navigate.prevError", "Previous Highlighted Error", "Navigate", (v) => gotoDiagnostic(v, -1)),
editorAction("find.highlightUsages", "Highlight Usages in File", "Find", highlightUsages),
@@ -208,13 +241,21 @@ export function registerLspActions(): () => void {
},
},
editorAction("refactor.rename", "Rename…", "Refactor", startRename),
- editorAction("refactor.extractVariable", "Introduce Variable…", "Refactor", (v) => runRefactoring(v, "extractVariable")),
+ editorAction("refactor.extractVariable", "Introduce Variable…", "Refactor", (v) =>
+ runRefactoring(v, "extractVariable"),
+ ),
editorAction("refactor.extractMethod", "Extract Method…", "Refactor", (v) => runRefactoring(v, "extractMethod")),
- editorAction("refactor.extractConstant", "Introduce Constant…", "Refactor", (v) => runRefactoring(v, "extractConstant")),
+ editorAction("refactor.extractConstant", "Introduce Constant…", "Refactor", (v) =>
+ runRefactoring(v, "extractConstant"),
+ ),
editorAction("refactor.extractField", "Introduce Field…", "Refactor", (v) => runRefactoring(v, "extractField")),
- editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) => runRefactoring(v, "extractParameter")),
+ editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) =>
+ runRefactoring(v, "extractParameter"),
+ ),
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
- editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) => runRefactoring(v, "changeSignature")),
+ editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
+ runRefactoring(v, "changeSignature"),
+ ),
editorAction("refactor.safeDelete", "Safe Delete…", "Refactor", safeDelete),
editorAction(
"code.generate",
@@ -222,7 +263,8 @@ export function registerLspActions(): () => void {
"Code",
(v) =>
runKindAction(v, "", {
- title: /^(generate|implement|override|add (missing|derive|impl|getter|setter|constructor)|create (constructor|getter|setter))/i,
+ title:
+ /^(generate|implement|override|add (missing|derive|impl|getter|setter|constructor)|create (constructor|getter|setter))/i,
none: "Nothing to generate here",
label: "Generate",
}),
diff --git a/src/editor/lsp/authorLens.ts b/src/editor/lsp/authorLens.ts
index f35405258..be4392ec2 100644
--- a/src/editor/lsp/authorLens.ts
+++ b/src/editor/lsp/authorLens.ts
@@ -36,7 +36,9 @@ export function authorLabel(s: AuthorSummary): string {
}
export function authorTooltip(s: AuthorSummary): string {
- return s.others ? `Last changed by ${s.author}; also ${s.authors.slice(1).join(", ")}` : `Last changed by ${s.author}`;
+ return s.others
+ ? `Last changed by ${s.author}; also ${s.authors.slice(1).join(", ")}`
+ : `Last changed by ${s.author}`;
}
interface Entry {
diff --git a/src/editor/lsp/autoImport.ts b/src/editor/lsp/autoImport.ts
index 7cc15aeac..734c45494 100644
--- a/src/editor/lsp/autoImport.ts
+++ b/src/editor/lsp/autoImport.ts
@@ -20,7 +20,9 @@ const IMPORT_TITLE = /\bimport\b/i;
/** The single import fix among `actions`, if exactly one exists. */
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
- const imports = actions.filter((a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")));
+ const imports = actions.filter(
+ (a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")),
+ );
return imports.length === 1 ? imports[0]! : null;
}
diff --git a/src/editor/lsp/codeLens.ts b/src/editor/lsp/codeLens.ts
index 1b7772dda..e17657938 100644
--- a/src/editor/lsp/codeLens.ts
+++ b/src/editor/lsp/codeLens.ts
@@ -54,7 +54,8 @@ export function lensTargets(items: readonly OutlineItem[]): LensTarget[] {
const out: LensTarget[] = [];
const walk = (list: readonly OutlineItem[]) => {
for (const it of list) {
- if (LENS_KINDS.has(it.kind) && !anonymous(it.name)) out.push({
+ if (LENS_KINDS.has(it.kind) && !anonymous(it.name))
+ out.push({
name: it.name,
line: it.selection_range.start.line,
col: it.selection_range.start.col,
@@ -159,7 +160,9 @@ class UsagesLensPlugin {
const { from, to } = view.viewport;
const firstLine = Math.max(0, text.lineAt(from).number - 1 - MARGIN_LINES);
const lastLine = text.lineAt(to).number - 1 + MARGIN_LINES;
- const visible = this.outline.targets.filter((t) => t.line >= firstLine && t.line <= lastLine).slice(0, MAX_PER_PASS);
+ const visible = this.outline.targets
+ .filter((t) => t.line >= firstLine && t.line <= lastLine)
+ .slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages ? visible.filter((t) => !this.cache.has(key(t))) : [];
let unavailable = false;
@@ -185,7 +188,8 @@ class UsagesLensPlugin {
for (const t of visible) {
const offset = posToOffset(text, { line: t.line, col: t.col });
const who = lines && authorSummary(lines, t.startLine, t.endLine);
- if (who) lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
+ if (who)
+ lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
const n = usages ? this.cache.get(key(t)) : undefined;
if (n === undefined) continue;
lenses.push({
diff --git a/src/editor/lsp/completion.test.ts b/src/editor/lsp/completion.test.ts
index 369280b0f..3c53bb295 100644
--- a/src/editor/lsp/completion.test.ts
+++ b/src/editor/lsp/completion.test.ts
@@ -330,9 +330,9 @@ describe("typeColumnText", () => {
const edit = (new_text: string) => [{ range: { start: { line: 0, col: 0 }, end: { line: 0, col: 0 } }, new_text }];
it("names the module an auto-import comes from", () => {
- expect(typeColumnText({ detail: "Auto-import", additionalEdits: edit("\nfrom collections import OrderedDict") })).toBe(
- "collections",
- );
+ expect(
+ typeColumnText({ detail: "Auto-import", additionalEdits: edit("\nfrom collections import OrderedDict") }),
+ ).toBe("collections");
expect(typeColumnText({ detail: "Map<K, V>", additionalEdits: edit("import java.util.HashMap;\n") })).toBe(
"Map<K, V> (java.util)",
);
@@ -343,9 +343,9 @@ describe("typeColumnText", () => {
});
it("keeps a detail that already says where", () => {
- expect(typeColumnText({ detail: "java.util.ArrayList", additionalEdits: edit("import java.util.ArrayList;\n") })).toBe(
- "java.util.ArrayList",
- );
+ expect(
+ typeColumnText({ detail: "java.util.ArrayList", additionalEdits: edit("import java.util.ArrayList;\n") }),
+ ).toBe("java.util.ArrayList");
expect(typeColumnText({ detail: "fn() ", additionalEdits: [] })).toBe("fn() ");
});
});
diff --git a/src/editor/lsp/completionItems.ts b/src/editor/lsp/completionItems.ts
index 6aadb3ab6..402a3ba54 100644
--- a/src/editor/lsp/completionItems.ts
+++ b/src/editor/lsp/completionItems.ts
@@ -74,7 +74,15 @@ function extendsLabel(item: CompletionItem): boolean {
export function withoutDuplicates(items: readonly CompletionItem[]): CompletionItem[] {
const seen = new Set<string>();
return items.filter((it) => {
- const key = JSON.stringify([it.server, it.label, it.labelDetail, it.detail, it.kind, it.insertText, it.additionalEdits]);
+ const key = JSON.stringify([
+ it.server,
+ it.label,
+ it.labelDetail,
+ it.detail,
+ it.kind,
+ it.insertText,
+ it.additionalEdits,
+ ]);
if (seen.has(key)) return false;
seen.add(key);
return true;
diff --git a/src/editor/lsp/diagnostics.test.ts b/src/editor/lsp/diagnostics.test.ts
index abb5b52b9..91d7ccd31 100644
--- a/src/editor/lsp/diagnostics.test.ts
+++ b/src/editor/lsp/diagnostics.test.ts
@@ -3,7 +3,13 @@ import { Text } from "@codemirror/state";
import type { Diagnostic } from "@/bindings";
import { diagnosticsFor, setFileDiagnostics, subscribeDiagnostics, toLintDiagnostics } from "./diagnostics";
-const d = (line: number, col: number, endCol: number, severity: Diagnostic["severity"] = "error", over: Partial<Diagnostic> = {}): Diagnostic => ({
+const d = (
+ line: number,
+ col: number,
+ endCol: number,
+ severity: Diagnostic["severity"] = "error",
+ over: Partial<Diagnostic> = {},
+): Diagnostic => ({
range: { start: { line, col }, end: { line, col: endCol } },
severity,
message: `m${line}:${col}`,
@@ -40,7 +46,14 @@ describe("toLintDiagnostics", () => {
]);
expect(out).toEqual([
{ from: 3, to: 7, severity: "error", message: "m0:3", source: undefined, markClass: "cm-lsp-deprecated" },
- { from: 18, to: 19, severity: "warning", message: "m1:6", source: "rustc unused", markClass: "cm-lsp-unnecessary" },
+ {
+ from: 18,
+ to: 19,
+ severity: "warning",
+ message: "m1:6",
+ source: "rustc unused",
+ markClass: "cm-lsp-unnecessary",
+ },
]);
});
diff --git a/src/editor/lsp/diagnostics.ts b/src/editor/lsp/diagnostics.ts
index 320f3e17f..472fa46b5 100644
--- a/src/editor/lsp/diagnostics.ts
+++ b/src/editor/lsp/diagnostics.ts
@@ -37,7 +37,12 @@ export function setFileDiagnostics(path: string, source: string, items: Diagnost
const had = byPath.get(path)?.has(source) ?? false;
storeDiagnostics(path, source, items);
// `server` names the producer for views that see the diagnostic alone (inspection controls).
- if (items.length || had) publishLocalDiagnostics(path, source, items.map((d) => (d.server ? d : { ...d, server: source })));
+ if (items.length || had)
+ publishLocalDiagnostics(
+ path,
+ source,
+ items.map((d) => (d.server ? d : { ...d, server: source })),
+ );
}
function storeDiagnostics(path: string, source: string, items: Diagnostic[]) {
@@ -47,7 +52,10 @@ function storeDiagnostics(path: string, source: string, items: Diagnostic[]) {
if (!sources.size) byPath.delete(path);
} else {
if (!sources) byPath.set(path, (sources = new Map()));
- sources.set(source, items.map((d) => ({ ...d, source: d.source ?? source })));
+ sources.set(
+ source,
+ items.map((d) => ({ ...d, source: d.source ?? source })),
+ );
noteDiagnosticCodes(source, items);
}
listeners.get(path)?.forEach((l) => l());
@@ -92,7 +100,10 @@ export function installDiagnosticsEvents(): () => void {
const off = onIdeEvent("diagnostics", (e) => storeDiagnostics(e.path, e.source, e.items));
// Diagnostics published before this window (re)loaded were missed: ask for them again.
const resend = () => {
- if (isTauri()) void ideEventsReady().then(() => commands.lspResendDiagnostics()).catch(() => {});
+ if (isTauri())
+ void ideEventsReady()
+ .then(() => commands.lspResendDiagnostics())
+ .catch(() => {});
};
if (useProject.getState().project) resend();
const offProject = useProject.subscribe((s, prev) => {
@@ -244,12 +255,7 @@ const lintTheme = EditorView.theme({
});
export function diagnosticsExtension() {
- return [
- linter(null, { tooltipFilter: () => [], autoPanel: false }),
- marksField,
- diagnosticsSync,
- lintTheme,
- ];
+ return [linter(null, { tooltipFilter: () => [], autoPanel: false }), marksField, diagnosticsSync, lintTheme];
}
export interface PlacedDiagnostic {
@@ -292,7 +298,8 @@ export function gotoDiagnostic(view: EditorView, dir: 1 | -1): boolean {
view.dispatch({ selection: EditorSelection.cursor(target.from), scrollIntoView: true, userEvent: "select.navigate" });
showHint(view, target.diagnostic.message, {
pos: target.from,
- tone: target.diagnostic.severity === "error" ? "error" : target.diagnostic.severity === "warning" ? "warning" : "info",
+ tone:
+ target.diagnostic.severity === "error" ? "error" : target.diagnostic.severity === "warning" ? "warning" : "info",
timeout: 6000,
});
return true;
diff --git a/src/editor/lsp/docs.ts b/src/editor/lsp/docs.ts
index eb0b04aaa..42d450e7f 100644
--- a/src/editor/lsp/docs.ts
+++ b/src/editor/lsp/docs.ts
@@ -93,7 +93,10 @@ export async function editDocSource(host: DocHost): Promise<boolean> {
const loc = (await entry?.source?.().catch(() => null)) ?? null;
if (!loc) return false;
if (host === "popup") closePopup();
- await editorService().openFile(loc.path, { selection: { line: loc.range.start.line, col: loc.range.start.col }, focus: true });
+ await editorService().openFile(loc.path, {
+ selection: { line: loc.range.start.line, col: loc.range.start.col },
+ focus: true,
+ });
return true;
}
diff --git a/src/editor/lsp/features.test.ts b/src/editor/lsp/features.test.ts
index cd0dac840..4f7542394 100644
--- a/src/editor/lsp/features.test.ts
+++ b/src/editor/lsp/features.test.ts
@@ -29,7 +29,9 @@ describe("semanticRanges", () => {
it("applies the Python-specific static style without changing other languages", () => {
const input = { tokenTypes: ["property"], tokenModifiers: ["static"], data: [0, 0, 5, 0, 1] };
- expect(semanticRanges(doc, input, false, "python")[0]?.className).toBe("cm-sem-property cm-sem-static cm-sem-python-static");
+ expect(semanticRanges(doc, input, false, "python")[0]?.className).toBe(
+ "cm-sem-property cm-sem-static cm-sem-python-static",
+ );
expect(semanticRanges(doc, input, false, "java")[0]?.className).toBe("cm-sem-property cm-sem-static");
});
});
@@ -56,7 +58,9 @@ describe("semantic highlighting (rainbow identifiers)", () => {
it("hashes names to a stable palette index", () => {
expect(rainbowIndex("count")).toBe(rainbowIndex("count"));
- const all = ["a", "b", "count", "total", "index", "value", "name", "item", "result", "i", "j", "k"].map(rainbowIndex);
+ const all = ["a", "b", "count", "total", "index", "value", "name", "item", "result", "i", "j", "k"].map(
+ rainbowIndex,
+ );
for (const n of all) expect(n >= 1 && n <= RAINBOW_COLORS).toBe(true);
expect(new Set(all).size).toBeGreaterThan(2);
});
@@ -73,7 +77,9 @@ describe("semantic highlighting (rainbow identifiers)", () => {
expect(byText.get("count")).toEqual(new Set([String(rainbowIndex("count"))]));
expect(byText.get("obj")).toEqual(new Set([String(rainbowIndex("obj"))]));
// Parameters keep their own class too; self, statics and fields get no rainbow colour.
- expect(ranges.find((r) => r.from === 5)!.className).toBe(`cm-sem-parameter cm-sem-declaration cm-sem-rainbow-${rainbowIndex("total")}`);
+ expect(ranges.find((r) => r.from === 5)!.className).toBe(
+ `cm-sem-parameter cm-sem-declaration cm-sem-rainbow-${rainbowIndex("total")}`,
+ );
expect(byText.get("self")).toEqual(new Set([null]));
expect(byText.get("S")).toEqual(new Set([null]));
expect(byText.get("field")).toEqual(new Set([null]));
@@ -90,12 +96,21 @@ describe("semantic highlighting (rainbow identifiers)", () => {
},
true,
);
- expect(r.filter((x) => x.className.includes("rainbow")).map((x) => ts.sliceString(x.from, x.to))).toEqual(["p", "x", "p"]);
+ expect(r.filter((x) => x.className.includes("rainbow")).map((x) => ts.sliceString(x.from, x.to))).toEqual([
+ "p",
+ "x",
+ "p",
+ ]);
});
});
describe("sortCodeActions", () => {
- const a = (title: string, kind: string | null, isPreferred = false, disabledReason: string | null = null): CodeAction => ({
+ const a = (
+ title: string,
+ kind: string | null,
+ isPreferred = false,
+ disabledReason: string | null = null,
+ ): CodeAction => ({
title,
kind,
isPreferred,
@@ -114,14 +129,29 @@ describe("sortCodeActions", () => {
a("preferred fix", "quickfix.import", true),
a("preferred refactor", "refactor", true),
]);
- expect(sorted.map((x) => x.title)).toEqual(["preferred fix", "fix", "preferred refactor", "extract", "disabled fix"]);
+ expect(sorted.map((x) => x.title)).toEqual([
+ "preferred fix",
+ "fix",
+ "preferred refactor",
+ "extract",
+ "disabled fix",
+ ]);
});
});
describe("splitSignature", () => {
it("splits around the active parameter", () => {
const label = "fn create(req: Request, user: Long) -> Order";
- expect(splitSignature(label, [[10, 22], [24, 34]], 1)).toEqual({
+ expect(
+ splitSignature(
+ label,
+ [
+ [10, 22],
+ [24, 34],
+ ],
+ 1,
+ ),
+ ).toEqual({
before: "fn create(req: Request, ",
param: "user: Long",
after: ") -> Order",
@@ -141,7 +171,10 @@ describe("lineErrorsAwayFromCaret", () => {
const p = (from: number, to: number, severity = "error") => ({ from, to, severity });
it("offers errors elsewhere on the caret line when none is at the caret", () => {
- expect(lineErrorsAwayFromCaret([p(30, 34), p(12, 15), p(50, 52), p(5, 6, "warning")], 0, 40, 2)).toEqual([p(12, 15), p(30, 34)]);
+ expect(lineErrorsAwayFromCaret([p(30, 34), p(12, 15), p(50, 52), p(5, 6, "warning")], 0, 40, 2)).toEqual([
+ p(12, 15),
+ p(30, 34),
+ ]);
});
it("offers nothing extra when an error touches the caret", () => {
diff --git a/src/editor/lsp/fileReferences.ts b/src/editor/lsp/fileReferences.ts
index 2ade17424..b4c473209 100644
--- a/src/editor/lsp/fileReferences.ts
+++ b/src/editor/lsp/fileReferences.ts
@@ -6,7 +6,12 @@
* Paths resolve in the backend like IDEA's file references: relative to the
* file, `/…` against the project root and its resource roots.
*/
-import { startCompletion, type Completion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete";
+import {
+ startCompletion,
+ type Completion,
+ type CompletionContext,
+ type CompletionResult,
+} from "@codemirror/autocomplete";
import type { Extension } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
import { whenSynced } from "@/editor/api";
@@ -71,7 +76,10 @@ function option(entry: PathCompletion): Completion & { icon: string } {
type: "folder",
icon: folderIconName(),
apply: (view, _c, from, to) => {
- view.dispatch({ changes: { from, to, insert: `${entry.name}/` }, selection: { anchor: from + entry.name.length + 1 } });
+ view.dispatch({
+ changes: { from, to, insert: `${entry.name}/` },
+ selection: { anchor: from + entry.name.length + 1 },
+ });
startCompletion(view);
},
};
diff --git a/src/editor/lsp/files.ts b/src/editor/lsp/files.ts
index 692ccfc0c..2e4d0ba24 100644
--- a/src/editor/lsp/files.ts
+++ b/src/editor/lsp/files.ts
@@ -25,7 +25,10 @@ export async function readFileLines(path: string): Promise<string[] | null> {
}
/** Reads several files with bounded concurrency; missing files map to `null`. */
-export async function readManyFileLines(paths: readonly string[], concurrency = 4): Promise<Map<string, string[] | null>> {
+export async function readManyFileLines(
+ paths: readonly string[],
+ concurrency = 4,
+): Promise<Map<string, string[] | null>> {
const out = new Map<string, string[] | null>();
const queue = [...new Set(paths)];
const worker = async () => {
diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts
index 64d299699..1e37e1554 100644
--- a/src/editor/lsp/format.ts
+++ b/src/editor/lsp/format.ts
@@ -12,7 +12,12 @@ import type { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { executeAction } from "@/platform/actions";
-import { formatExcluded, formatGuardOptions, guardFormatChanges, type FormatGuardOptions } from "@/platform/formatGuard";
+import {
+ formatExcluded,
+ formatGuardOptions,
+ guardFormatChanges,
+ type FormatGuardOptions,
+} from "@/platform/formatGuard";
import { useProject } from "@/platform/project";
import { CONTRIBUTED_FORMAT, contributedAt, whenSynced, type ContributedFormatter } from "@/editor/api";
import { docOf, lspRequest, reportLspError } from "./lsp";
@@ -66,7 +71,9 @@ function formattedHint(view: EditorView, lines: number) {
/** LSP `FormattingOptions`: with spaces the indent width is the indent unit, not the tab size. */
export function formatOptionsOf(state: EditorState): { tabSize: number; insertSpaces: boolean } {
const unit = state.facet(indentUnit);
- return unit.includes("\t") ? { tabSize: state.tabSize, insertSpaces: false } : { tabSize: unit.length || state.tabSize, insertSpaces: true };
+ return unit.includes("\t")
+ ? { tabSize: state.tabSize, insertSpaces: false }
+ : { tabSize: unit.length || state.tabSize, insertSpaces: true };
}
export async function formatDocument(
@@ -83,7 +90,8 @@ async function format(view: EditorView, opts: { explicit: boolean; selectionOnly
const guard = formatGuardOptions(settings);
const path = docOf(view)?.path;
if (path && formatExcluded(path, project?.root ?? null, guard.doNotFormat)) {
- if (opts.explicit) showHint(view, "Formatting is turned off for this file (Code Style › Formatter › Do not format)");
+ if (opts.explicit)
+ showHint(view, "Formatting is turned off for this file (Code Style › Formatter › Do not format)");
return NOTHING;
}
const own = contributedAt<ContributedFormatter>(view.state, CONTRIBUTED_FORMAT, 0);
@@ -125,7 +133,12 @@ async function format(view: EditorView, opts: { explicit: boolean; selectionOnly
/** Whether `after` has a non-blank line at column 0 where all of `before` was indented. */
export function dedentsToColumnZero(before: string, after: string): boolean {
const minIndent = (t: string) =>
- Math.min(...t.split("\n").filter((l) => l.trim()).map((l) => l.length - l.trimStart().length));
+ Math.min(
+ ...t
+ .split("\n")
+ .filter((l) => l.trim())
+ .map((l) => l.length - l.trimStart().length),
+ );
return minIndent(before) > 0 && minIndent(after) === 0;
}
@@ -150,7 +163,9 @@ export async function formatLines(view: EditorView, from: number, to: number): P
}
if (view.state.doc !== state.doc) return false;
// Only inside the range: some servers answer a range request with whole-file edits.
- const changes = textEditsToChanges(state.doc, edits).filter((c) => c.from >= from && c.to <= to && state.sliceDoc(c.from, c.to) !== c.insert);
+ const changes = textEditsToChanges(state.doc, edits).filter(
+ (c) => c.from >= from && c.to <= to && state.sliceDoc(c.from, c.to) !== c.insert,
+ );
if (!changes.length) return true;
// A server formatting the range out of context (kotlin-language-server) moves
// indented code to column 0: its answer is ignored then.
@@ -212,7 +227,11 @@ export async function reformatDialog(
initial: lastOptions,
onRun: (options) =>
void (async () => {
- lastOptions = { ...lastOptions, ...options, selectionOnly: sel.empty ? lastOptions.selectionOnly : options.selectionOnly };
+ lastOptions = {
+ ...lastOptions,
+ ...options,
+ selectionOnly: sel.empty ? lastOptions.selectionOnly : options.selectionOnly,
+ };
view.focus();
if (options.optimizeImports) await optimizeImports(view);
await formatDocument(view, { explicit: true, selectionOnly: options.selectionOnly });
diff --git a/src/editor/lsp/hint.ts b/src/editor/lsp/hint.ts
index 0d2d16941..8054d8f38 100644
--- a/src/editor/lsp/hint.ts
+++ b/src/editor/lsp/hint.ts
@@ -70,8 +70,5 @@ export function hideHint(view: EditorView): boolean {
}
export function hintExtension(): Extension {
- return [
- hintField,
- Prec.high(keymap.of([{ key: "Escape", run: (view) => hideHint(view) }])),
- ];
+ return [hintField, Prec.high(keymap.of([{ key: "Escape", run: (view) => hideHint(view) }]))];
}
diff --git a/src/editor/lsp/inlay.test.ts b/src/editor/lsp/inlay.test.ts
index f4ab2de55..6ecf7b6e2 100644
--- a/src/editor/lsp/inlay.test.ts
+++ b/src/editor/lsp/inlay.test.ts
@@ -66,7 +66,9 @@ describe("inlay hints", () => {
it("offers to disable hints of the clicked kind", () => {
const view = editorWith([hint]);
- view.dom.querySelector(".cm-lsp-inlay")!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
+ view.dom
+ .querySelector(".cm-lsp-inlay")!
+ .dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
const items = useContextMenuStore.getState().menu?.items ?? [];
expect(items.map((i) => ("label" in i ? i.label : i.kind))).toEqual([
"Disable Type hints",
diff --git a/src/editor/lsp/inlay.ts b/src/editor/lsp/inlay.ts
index 605aa3012..6fd5be075 100644
--- a/src/editor/lsp/inlay.ts
+++ b/src/editor/lsp/inlay.ts
@@ -136,14 +136,17 @@ export function inlayDecorations(view: EditorView, hints: readonly InlayHint[]):
const doc = view.state.doc;
return Decoration.set(
hints.map((h) =>
- Decoration.widget({ widget: new InlayWidget(h), side: h.kind === "parameter" ? 1 : -1 }).range(posToOffset(doc, h.position)),
+ Decoration.widget({ widget: new InlayWidget(h), side: h.kind === "parameter" ? 1 : -1 }).range(
+ posToOffset(doc, h.position),
+ ),
),
true,
);
}
const enabled = (language: string) =>
- useProject.getState().settings?.editor?.inlayHints !== false && !editorPrefs().inlay.disabledLanguages.includes(language);
+ useProject.getState().settings?.editor?.inlayHints !== false &&
+ !editorPrefs().inlay.disabledLanguages.includes(language);
/** Inlay Hints settings: per kind (types / parameters / other). */
function shownKind(kind: InlayHint["kind"]): boolean {
@@ -160,9 +163,14 @@ const inlayPlugin = ViewPlugin.fromClass(
constructor(private view: EditorView) {
this.refresh();
view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", navigationModifierHeld());
- this.offModifier = onNavigationModifier((held) => view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", held));
+ this.offModifier = onNavigationModifier((held) =>
+ view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", held),
+ );
this.unsubscribe = useProject.subscribe((s, prev) => {
- if (s.settings?.editor?.inlayHints !== prev.settings?.editor?.inlayHints || s.settings?.editor?.inlay !== prev.settings?.editor?.inlay)
+ if (
+ s.settings?.editor?.inlayHints !== prev.settings?.editor?.inlayHints ||
+ s.settings?.editor?.inlay !== prev.settings?.editor?.inlay
+ )
this.refresh();
});
this.offReady = onLspRefresh("inlayHints", () => this.refresh());
@@ -186,7 +194,14 @@ const inlayPlugin = ViewPlugin.fromClass(
try {
const hints = await lspRequest(() => commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, first, last)));
if (view.state.doc !== state.doc) return this.refresh();
- view.dispatch({ effects: setInlays.of(inlayDecorations(view, hints.filter((h) => shownKind(h.kind)))) });
+ view.dispatch({
+ effects: setInlays.of(
+ inlayDecorations(
+ view,
+ hints.filter((h) => shownKind(h.kind)),
+ ),
+ ),
+ });
} catch (e) {
if (isUnavailable(e)) serverBackoff.mark(doc.doc);
}
diff --git a/src/editor/lsp/inplaceRename.test.ts b/src/editor/lsp/inplaceRename.test.ts
index f444cd99d..8dee99ccd 100644
--- a/src/editor/lsp/inplaceRename.test.ts
+++ b/src/editor/lsp/inplaceRename.test.ts
@@ -16,7 +16,10 @@ afterEach(() => views.splice(0).forEach((v) => v.destroy()));
// "let foo = 1; foo + foo;" — foo at 4, 13 and 19.
function session(commit = vi.fn(), dialog = vi.fn(), extensions: Extension[] = []) {
const view = new EditorView({
- state: EditorState.create({ doc: "let foo = 1; foo + foo;", extensions: [inplaceRenameExtension(), ...extensions] }),
+ state: EditorState.create({
+ doc: "let foo = 1; foo + foo;",
+ extensions: [inplaceRenameExtension(), ...extensions],
+ }),
});
views.push(view);
startInplaceRename(view, {
@@ -33,7 +36,11 @@ function session(commit = vi.fn(), dialog = vi.fn(), extensions: Extension[] = [
}
const type = (view: EditorView, from: number, to: number, insert: string) =>
- view.dispatch({ changes: { from, to, insert }, selection: EditorSelection.cursor(from + insert.length), userEvent: "input.type" });
+ view.dispatch({
+ changes: { from, to, insert },
+ selection: EditorSelection.cursor(from + insert.length),
+ userEvent: "input.type",
+ });
describe("in-place rename", () => {
it("preselects the name and mirrors edits to the other occurrences", () => {
diff --git a/src/editor/lsp/inplaceRename.ts b/src/editor/lsp/inplaceRename.ts
index 87f2a16c0..5d7e9b948 100644
--- a/src/editor/lsp/inplaceRename.ts
+++ b/src/editor/lsp/inplaceRename.ts
@@ -9,8 +9,26 @@
* back before the server renames, so the project-wide rename stays a single
* undoable edit computed against the original document.
*/
-import { Annotation, EditorSelection, EditorState, Prec, StateEffect, StateField, Transaction, type ChangeSet, type Extension } from "@codemirror/state";
-import { Decoration, EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
+import {
+ Annotation,
+ EditorSelection,
+ EditorState,
+ Prec,
+ StateEffect,
+ StateField,
+ Transaction,
+ type ChangeSet,
+ type Extension,
+} from "@codemirror/state";
+import {
+ Decoration,
+ EditorView,
+ ViewPlugin,
+ keymap,
+ showTooltip,
+ type Tooltip,
+ type ViewUpdate,
+} from "@codemirror/view";
import { completionStatus } from "@codemirror/autocomplete";
import { isExternalChange } from "@/editor/api";
@@ -40,7 +58,10 @@ const endSession = StateEffect.define<null>();
/** Marks the session's own edits (mirroring, restoring). */
const inplaceEdit = Annotation.define<boolean>();
-const mapSpan = (s: Span, changes: ChangeSet): Span => ({ from: changes.mapPos(s.from, -1), to: changes.mapPos(s.to, 1) });
+const mapSpan = (s: Span, changes: ChangeSet): Span => ({
+ from: changes.mapPos(s.from, -1),
+ to: changes.mapPos(s.to, 1),
+});
const sessionField = StateField.define<InplaceSession | null>({
create: () => null,
@@ -50,7 +71,11 @@ const sessionField = StateField.define<InplaceSession | null>({
if (e.is(endSession)) return null;
}
if (!value || !tr.docChanged) return value;
- return { ...value, primary: mapSpan(value.primary, tr.changes), others: value.others.map((o) => mapSpan(o, tr.changes)) };
+ return {
+ ...value,
+ primary: mapSpan(value.primary, tr.changes),
+ others: value.others.map((o) => mapSpan(o, tr.changes)),
+ };
},
provide: (f) => [
EditorView.decorations.from(f, (s) => {
@@ -200,7 +225,13 @@ const watcher = ViewPlugin.fromClass(
const outside = head < s.primary.from || head > s.primary.to || u.state.selection.ranges.length > 1;
const foreignEdit = u.transactions.some((tr) => {
const before = inplaceSession(tr.startState);
- return !!before && tr.docChanged && !tr.annotation(inplaceEdit) && !isExternalChange(tr) && !changesWithin(tr.changes, before.primary);
+ return (
+ !!before &&
+ tr.docChanged &&
+ !tr.annotation(inplaceEdit) &&
+ !isExternalChange(tr) &&
+ !changesWithin(tr.changes, before.primary)
+ );
});
if (outside || foreignEdit) queueMicrotask(() => endInplaceRename(this.view, "commit"));
}
diff --git a/src/editor/lsp/inspectionWidget.ts b/src/editor/lsp/inspectionWidget.ts
index a3a86afa4..52e06d16e 100644
--- a/src/editor/lsp/inspectionWidget.ts
+++ b/src/editor/lsp/inspectionWidget.ts
@@ -93,15 +93,21 @@ class InspectionWidget {
add(c.typo, "info", "cm-openidea-inspection-typo");
const children: HTMLElement[] = [summary];
if (total) {
- const prev = button(`Previous Highlighted Error${shortcutLabel("navigate.prevError") ? ` (${shortcutLabel("navigate.prevError")})` : ""}`, () => {
- gotoDiagnostic(this.view, -1);
- this.view.focus();
- });
+ const prev = button(
+ `Previous Highlighted Error${shortcutLabel("navigate.prevError") ? ` (${shortcutLabel("navigate.prevError")})` : ""}`,
+ () => {
+ gotoDiagnostic(this.view, -1);
+ this.view.focus();
+ },
+ );
prev.appendChild(iconNode("chevron-up", 14));
- const next = button(`Next Highlighted Error${shortcutLabel("navigate.nextError") ? ` (${shortcutLabel("navigate.nextError")})` : ""}`, () => {
- gotoDiagnostic(this.view, 1);
- this.view.focus();
- });
+ const next = button(
+ `Next Highlighted Error${shortcutLabel("navigate.nextError") ? ` (${shortcutLabel("navigate.nextError")})` : ""}`,
+ () => {
+ gotoDiagnostic(this.view, 1);
+ this.view.focus();
+ },
+ );
next.appendChild(iconNode("chevron-down", 14));
children.push(prev, next);
}
diff --git a/src/editor/lsp/intentions.test.ts b/src/editor/lsp/intentions.test.ts
index 53b89ba16..bb913d157 100644
--- a/src/editor/lsp/intentions.test.ts
+++ b/src/editor/lsp/intentions.test.ts
@@ -28,8 +28,15 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspResolveCodeAction } };
});
-const { bulbLine, changedLines, indentUnderBrace, intentionPreview, lightsBulb, listedCodeActions, withInspectionControls } =
- await import("./intentions");
+const {
+ bulbLine,
+ changedLines,
+ indentUnderBrace,
+ intentionPreview,
+ lightsBulb,
+ listedCodeActions,
+ withInspectionControls,
+} = await import("./intentions");
const { setFileDiagnostics } = await import("./diagnostics");
const { lspDoc } = await import("./lsp");
@@ -133,7 +140,9 @@ describe("changedLines", () => {
});
it("keeps separate edits apart", () => {
const before = text("package p;\n\nclass A {\n int a;\n int b;\n void f() {\n }\n}\n");
- const after = text("package p;\n\nimport java.util.List;\n\nclass A {\n int a;\n int b;\n void f() {\n List<String> x = null;\n x.size();\n }\n}\n");
+ const after = text(
+ "package p;\n\nimport java.util.List;\n\nclass A {\n int a;\n int b;\n void f() {\n List<String> x = null;\n x.size();\n }\n}\n",
+ );
expect(changedLines(before, after)).toEqual([
{ from: 3, to: 4 },
{ from: 9, to: 10 },
diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts
index 07b11dd6a..a1ab97070 100644
--- a/src/editor/lsp/intentions.ts
+++ b/src/editor/lsp/intentions.ts
@@ -43,7 +43,9 @@ async function fetchActions(view: EditorView, only: string[], whole = false): Pr
if (!doc) return [];
await whenSynced(view);
const sel = view.state.selection.main;
- const range = whole ? offsetsToRange(view.state.doc, 0, view.state.doc.length) : offsetsToRange(view.state.doc, sel.from, sel.to);
+ const range = whole
+ ? offsetsToRange(view.state.doc, 0, view.state.doc.length)
+ : offsetsToRange(view.state.doc, sel.from, sel.to);
return lspRequest(() => commands.lspCodeActions(doc.doc, range, only));
}
@@ -58,7 +60,12 @@ interface PlacedProblem {
* error elsewhere on the caret line are offered too. The errors to ask about,
* in line order; none when an error is at the caret.
*/
-export function lineErrorsAwayFromCaret(problems: readonly PlacedProblem[], lineFrom: number, lineTo: number, caret: number): PlacedProblem[] {
+export function lineErrorsAwayFromCaret(
+ problems: readonly PlacedProblem[],
+ lineFrom: number,
+ lineTo: number,
+ caret: number,
+): PlacedProblem[] {
const errors = problems.filter((p) => p.severity === "error");
if (errors.some((p) => p.from <= caret && caret <= p.to)) return [];
return errors.filter((p) => p.from >= lineFrom && p.from <= lineTo).sort((a, b) => a.from - b.from);
@@ -78,7 +85,9 @@ async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
for (const p of lineErrorsAwayFromCaret(problems, line.from, line.to, sel.head)) {
let more: CodeAction[];
try {
- more = await lspRequest(() => commands.lspCodeActions(doc.doc, offsetsToRange(state.doc, p.from, p.to), ["quickfix"]));
+ more = await lspRequest(() =>
+ commands.lspCodeActions(doc.doc, offsetsToRange(state.doc, p.from, p.to), ["quickfix"]),
+ );
} catch {
break;
}
@@ -97,7 +106,9 @@ export async function quickFixesAt(view: EditorView, from: number, to: number):
const doc = docOf(view);
if (!doc) return [];
await whenSynced(view);
- const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]));
+ const actions = await lspRequest(() =>
+ commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]),
+ );
return sortCodeActions(actions.filter((a) => isQuickFix(a) && !a.disabledReason));
}
@@ -112,7 +123,8 @@ export async function applyQuickFix(view: EditorView) {
const problems: Array<PlacedProblem & { rank: number }> = [];
forEachDiagnostic(state, (d, from, to) => {
if (d.severity === "hint" || to < line.from || from > line.to) return;
- const rank = (d.severity === "error" ? 0 : d.severity === "warning" ? 1 : 2) + (from <= caret && caret <= to ? 0 : 3);
+ const rank =
+ (d.severity === "error" ? 0 : d.severity === "warning" ? 1 : 2) + (from <= caret && caret <= to ? 0 : 3);
problems.push({ from, to, severity: d.severity, rank });
});
problems.sort((a, b) => a.rank - b.rank);
@@ -162,7 +174,8 @@ async function reformatGenerated(view: EditorView, before: Text) {
// A server that generated code without its context formats ranges the same
// way (back to column 0): its range formatting is skipped then.
if (shift.length) view.dispatch({ changes: shift, userEvent: "format", scrollIntoView: false });
- else if (!(await formatLines(view, doc.line(lines.from).from, doc.line(lines.to).to)) && view.state.doc !== doc) return;
+ else if (!(await formatLines(view, doc.line(lines.from).from, doc.line(lines.to).to)) && view.state.doc !== doc)
+ return;
}
}
@@ -172,14 +185,20 @@ async function reformatGenerated(view: EditorView, before: Text) {
* one level in, keeping its own nesting. Never applies to indentation-based
* languages, whose blocks don't open with `{`.
*/
-export function indentUnderBrace(doc: Text, fromLine: number, toLine: number, unit: string): Array<{ from: number; insert: string }> {
+export function indentUnderBrace(
+ doc: Text,
+ fromLine: number,
+ toLine: number,
+ unit: string,
+): Array<{ from: number; insert: string }> {
if (fromLine < 2) return [];
const prev = doc.line(fromLine - 1).text;
if (!prev.trimEnd().endsWith("{")) return [];
const lead = (t: string) => t.slice(0, t.length - t.trimStart().length);
const target = lead(prev) + unit;
let first: string | null = null;
- for (let n = fromLine; n <= toLine && first === null; n++) if (doc.line(n).text.trim()) first = lead(doc.line(n).text);
+ for (let n = fromLine; n <= toLine && first === null; n++)
+ if (doc.line(n).text.trim()) first = lead(doc.line(n).text);
if (first === null || first.length > lead(prev).length || !target.startsWith(first)) return [];
const extra = target.slice(first.length);
const out: Array<{ from: number; insert: string }> = [];
@@ -248,7 +267,11 @@ export function listedCodeActions(actions: readonly CodeAction[]): CodeAction[]
return sortCodeActions(actions).filter((a) => !seen.has(a.title) && !!seen.add(a.title));
}
-function actionItems(view: EditorView, actions: CodeAction[], resolved?: Map<CodeAction, Promise<CodeAction>>): ListPopupItem[] {
+function actionItems(
+ view: EditorView,
+ actions: CodeAction[],
+ resolved?: Map<CodeAction, Promise<CodeAction>>,
+): ListPopupItem[] {
return listedCodeActions(actions).map((a, i) => ({
id: `${i}`,
label: a.title,
@@ -261,10 +284,17 @@ function actionItems(view: EditorView, actions: CodeAction[], resolved?: Map<Cod
}
/** The action with its edit (resolved once per popup; servers may compute edits lazily). */
-function resolveOnce(doc: number, action: CodeAction, cache: Map<CodeAction, Promise<CodeAction>>): Promise<CodeAction> {
+function resolveOnce(
+ doc: number,
+ action: CodeAction,
+ cache: Map<CodeAction, Promise<CodeAction>>,
+): Promise<CodeAction> {
let p = cache.get(action);
if (!p) {
- p = action.edit || action.command ? Promise.resolve(action) : lspRequest(() => commands.lspResolveCodeAction(doc, action));
+ p =
+ action.edit || action.command
+ ? Promise.resolve(action)
+ : lspRequest(() => commands.lspResolveCodeAction(doc, action));
cache.set(action, p);
p.catch(() => cache.delete(action));
}
@@ -292,7 +322,10 @@ export async function intentionPreview(
if (lines.length) return { kind: "diff", lines, note };
}
if (note) return { kind: "text", text: note };
- return { kind: "text", text: full.command && !full.edit ? "Preview isn't available for this action" : "No changes in this file" };
+ return {
+ kind: "text",
+ text: full.command && !full.edit ? "Preview isn't available for this action" : "No changes in this file",
+ };
}
/**
@@ -467,7 +500,8 @@ const bulbPlugin = ViewPlugin.fromClass(
this.lookup.cancel();
// A blur dispatched from inside the update is not allowed.
queueMicrotask(() => {
- if (!this.view.hasFocus && this.view.state.field(bulbField, false)) this.view.dispatch({ effects: setBulb.of(null) });
+ if (!this.view.hasFocus && this.view.state.field(bulbField, false))
+ this.view.dispatch({ effects: setBulb.of(null) });
});
}
}
@@ -489,7 +523,8 @@ const bulbPlugin = ViewPlugin.fromClass(
if (!local) return;
}
}
- if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus) return;
+ if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus)
+ return;
const line = state.doc.lineAt(state.selection.main.head).number;
const any = actions.some(lightsBulb) || local;
this.view.dispatch({
diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts
index c920b17a2..67731ef0d 100644
--- a/src/editor/lsp/navigation.ts
+++ b/src/editor/lsp/navigation.ts
@@ -39,7 +39,13 @@ import { editorService } from "@/workbench/contributions";
import { fileIconName } from "@/ui";
import { NO_SERVER, debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, rangeToOffsets } from "./positions";
-import { SYNTAX_NOTE, declarationFallback, isSelfTarget, localHighlights, type DeclarationTarget } from "./syntaxFallback";
+import {
+ SYNTAX_NOTE,
+ declarationFallback,
+ isSelfTarget,
+ localHighlights,
+ type DeclarationTarget,
+} from "./syntaxFallback";
import { showHint } from "./hint";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { identifierAt, readManyFileLines } from "./files";
@@ -305,7 +311,8 @@ const linkField = StateField.define<LinkState | null>({
create: (view) => {
const dom = document.createElement("div");
dom.className = "cm-lsp-hover cm-lsp-nav-info";
- if ("code" in info) dom.appendChild(renderCode(info.code, info.language ?? docOf(view)?.uiMode ?? null, "cm-lsp-code"));
+ if ("code" in info)
+ dom.appendChild(renderCode(info.code, info.language ?? docOf(view)?.uiMode ?? null, "cm-lsp-code"));
else dom.textContent = info.text;
return { dom };
},
@@ -458,7 +465,7 @@ const linkPlugin = ViewPlugin.fromClass(
clearTimeout(this.probeTimer);
this.probing = null;
// Cancellation and server errors are transient, not negative results.
- });
+ });
}
},
{
@@ -525,7 +532,10 @@ const highlightField = StateField.define<HighlightState>({
});
/** IDEA's status bar text while ⌘⇧F7 highlights are shown. */
-export const useUsagesStatus = create<{ text: string | null; owner: EditorView | null }>(() => ({ text: null, owner: null }));
+export const useUsagesStatus = create<{ text: string | null; owner: EditorView | null }>(() => ({
+ text: null,
+ owner: null,
+}));
function setUsagesStatus(owner: EditorView | null, text: string | null) {
useUsagesStatus.setState({ owner, text });
@@ -557,7 +567,10 @@ async function fetchHighlights(view: EditorView, sticky: boolean) {
}
const at = items.find((i) => i.from <= head && head <= i.to) ?? state.wordAt(head);
const name = at ? state.sliceDoc(at.from, at.to) : "";
- setUsagesStatus(view, usagesStatusText(items.length, name ? `'${name}'` : "the element", shortcutLabel("find.highlightUsages") ?? null));
+ setUsagesStatus(
+ view,
+ usagesStatusText(items.length, name ? `'${name}'` : "the element", shortcutLabel("find.highlightUsages") ?? null),
+ );
};
let lspError: unknown = null;
if (!serverBackoff.active(doc.doc)) {
@@ -628,7 +641,8 @@ const highlightPlugin = ViewPlugin.fromClass(
}
const clear = () => {
this.request.cancel();
- if (st.deco.size) queueMicrotask(() => this.view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) }));
+ if (st.deco.size)
+ queueMicrotask(() => this.view.dispatch({ effects: setHighlights.of({ items: [], sticky: false }) }));
};
// Code Editing › "Usages of element at caret".
if (!editorPrefs().codeEditing.highlightUsages || !u.state.selection.main.empty) {
diff --git a/src/editor/lsp/positions.test.ts b/src/editor/lsp/positions.test.ts
index bc367b640..2442c30ad 100644
--- a/src/editor/lsp/positions.test.ts
+++ b/src/editor/lsp/positions.test.ts
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
-import { offsetToPos, offsetsToRange, posToOffset, rangeContains, rangeToOffsets, textEditsToChanges } from "./positions";
+import {
+ offsetToPos,
+ offsetsToRange,
+ posToOffset,
+ rangeContains,
+ rangeToOffsets,
+ textEditsToChanges,
+} from "./positions";
const doc = Text.of(["let a = 1;", "// 😀 émoji", "", "end"]);
diff --git a/src/editor/lsp/positions.ts b/src/editor/lsp/positions.ts
index 6c560d725..b27c9dcb1 100644
--- a/src/editor/lsp/positions.ts
+++ b/src/editor/lsp/positions.ts
@@ -43,7 +43,10 @@ export function rangeContains(range: Range, pos: Pos): boolean {
* sorted, non-overlapping CodeMirror changes. Overlapping edits are dropped
* rather than producing a corrupt change set.
*/
-export function textEditsToChanges(doc: Text, edits: readonly TextEdit[]): Array<{ from: number; to: number; insert: string }> {
+export function textEditsToChanges(
+ doc: Text,
+ edits: readonly TextEdit[],
+): Array<{ from: number; to: number; insert: string }> {
const changes = edits
.map((e, i) => ({ ...rangeToOffsets(doc, e.range), insert: e.new_text, i }))
.sort((a, b) => a.from - b.from || a.to - b.to || a.i - b.i);
diff --git a/src/editor/lsp/rename.ts b/src/editor/lsp/rename.ts
index 3f4afaefd..1726b6d20 100644
--- a/src/editor/lsp/rename.ts
+++ b/src/editor/lsp/rename.ts
@@ -137,7 +137,12 @@ export async function renameNamePart(view: EditorView, part: Span, replacement:
.map((o) => rangeToOffsets(view.state.doc, o.range))
.find((o) => o.from <= part.from && part.to <= o.to);
if (!at) return false;
- await commitSyntaxRename(view, doc, plan, spliceName(plan.symbol.name, part.from - at.from, word.length, replacement));
+ await commitSyntaxRename(
+ view,
+ doc,
+ plan,
+ spliceName(plan.symbol.name, part.from - at.from, word.length, replacement),
+ );
return true;
};
let range;
@@ -162,7 +167,13 @@ export async function renameNamePart(view: EditorView, part: Span, replacement:
}
/** This file's other occurrences of the symbol (document highlights with the same text). */
-async function linkedOccurrences(view: EditorView, doc: number, pos: Pos, primary: Span, name: string): Promise<Span[]> {
+async function linkedOccurrences(
+ view: EditorView,
+ doc: number,
+ pos: Pos,
+ primary: Span,
+ name: string,
+): Promise<Span[]> {
let highlights;
try {
highlights = await lspRequest(() => commands.lspDocumentHighlights(doc, pos));
@@ -275,7 +286,12 @@ async function startSyntaxRename(view: EditorView, doc: EditorDocContext, pos: P
}
/** Applies a local rename in place, asking first when the syntax answer is not certain. */
-export async function commitSyntaxRename(view: EditorView, doc: EditorDocContext, plan: LocalRenamePlan, newName: string) {
+export async function commitSyntaxRename(
+ view: EditorView,
+ doc: EditorDocContext,
+ plan: LocalRenamePlan,
+ newName: string,
+) {
const oldName = plan.symbol.name;
if (!newName || newName === oldName) return;
if (VALID_NAME.test(oldName) && !VALID_NAME.test(newName)) {
diff --git a/src/editor/lsp/semantic.ts b/src/editor/lsp/semantic.ts
index 18aa60af2..9d09656ed 100644
--- a/src/editor/lsp/semantic.ts
+++ b/src/editor/lsp/semantic.ts
@@ -166,7 +166,12 @@ const semanticPlugin = ViewPlugin.fromClass(
this.last = { doc, tokens };
const ranges = tokens ? semanticRanges(doc, tokens, this.rainbow, docOf(this.view)?.language) : [];
this.view.dispatch({
- effects: setSemantic.of(Decoration.set(ranges.map((r) => markFor(r.className).range(r.from, r.to)), true)),
+ effects: setSemantic.of(
+ Decoration.set(
+ ranges.map((r) => markFor(r.className).range(r.from, r.to)),
+ true,
+ ),
+ ),
});
}
async run() {
diff --git a/src/editor/lsp/signature.test.ts b/src/editor/lsp/signature.test.ts
index 99cfc7ef0..00d5b5bf5 100644
--- a/src/editor/lsp/signature.test.ts
+++ b/src/editor/lsp/signature.test.ts
@@ -3,7 +3,11 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { closeBrackets } from "@codemirror/autocomplete";
-const help = { signatures: [{ label: "f(a: number)", documentation: null, parameters: [[2, 11]] }], activeSignature: 0, activeParameter: 0 };
+const help = {
+ signatures: [{ label: "f(a: number)", documentation: null, parameters: [[2, 11]] }],
+ activeSignature: 0,
+ activeParameter: 0,
+};
const lspSignatureHelp = vi.fn(async () => ({ status: "ok" as const, data: help }));
vi.mock("@/platform/ipc", async (orig) => {
@@ -11,9 +15,8 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSignatureHelp } };
});
-const { signatureExtension, acceptsParameter, argumentSpans, argumentStop, parameterTabKeys, triggerSignatureHelp } = await import(
- "./signature"
-);
+const { signatureExtension, acceptsParameter, argumentSpans, argumentStop, parameterTabKeys, triggerSignatureHelp } =
+ await import("./signature");
const { lspDoc } = await import("./lsp");
const views: EditorView[] = [];
@@ -24,7 +27,8 @@ afterEach(() => {
function typeChar(view: EditorView, ch: string) {
const { from, to } = view.state.selection.main;
- const insert = () => view.state.update({ changes: { from, to, insert: ch }, selection: { anchor: from + 1 }, userEvent: "input.type" });
+ const insert = () =>
+ view.state.update({ changes: { from, to, insert: ch }, selection: { anchor: from + 1 }, userEvent: "input.type" });
if (!view.state.facet(EditorView.inputHandler).some((h) => h(view, from, to, ch, insert))) view.dispatch(insert());
}
@@ -36,7 +40,11 @@ describe("parameter info auto-popup", () => {
state: EditorState.create({
doc: "f",
selection: { anchor: 1 },
- extensions: [closeBrackets(), lspDoc.of({ doc: 1, path: "/a.ts", language: "typescript", uiMode: null, readOnly: false }), signatureExtension()],
+ extensions: [
+ closeBrackets(),
+ lspDoc.of({ doc: 1, path: "/a.ts", language: "typescript", uiMode: null, readOnly: false }),
+ signatureExtension(),
+ ],
}),
parent: document.body,
});
@@ -57,7 +65,18 @@ describe("acceptsParameter", () => {
expect(acceptsParameter({ label: "println() : void", parameters: [] }, 0)).toBe(false);
expect(acceptsParameter({ label: "println(Object x) : void", parameters: [[8, 16]] }, 0)).toBe(true);
expect(acceptsParameter({ label: "println(Object x) : void", parameters: [[8, 16]] }, 1)).toBe(false);
- expect(acceptsParameter({ label: "format(String f, Object... a)", parameters: [[7, 15], [17, 28]] }, 4)).toBe(true);
+ expect(
+ acceptsParameter(
+ {
+ label: "format(String f, Object... a)",
+ parameters: [
+ [7, 15],
+ [17, 28],
+ ],
+ },
+ 4,
+ ),
+ ).toBe(true);
});
});
@@ -101,7 +120,9 @@ describe("argument navigation", () => {
});
views.push(view);
const tab = () =>
- view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", keyCode: 9, bubbles: true, cancelable: true }));
+ view.contentDOM.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Tab", keyCode: 9, bubbles: true, cancelable: true }),
+ );
expect(tab()).toBe(true); // not handled: no parameter info
expect(view.state.selection.main.head).toBe(3);
triggerSignatureHelp(view, true);
diff --git a/src/editor/lsp/signature.ts b/src/editor/lsp/signature.ts
index 061da0bbe..41e036e13 100644
--- a/src/editor/lsp/signature.ts
+++ b/src/editor/lsp/signature.ts
@@ -122,7 +122,8 @@ export async function parameterInfoOrLeave(view: EditorView, inside: number) {
// No signature help: treated as nothing to fill in.
}
if (view.state.doc !== state.doc || view.state.selection.main.head !== inside) return;
- if (help?.signatures.some((sig) => sig.parameters.length)) view.dispatch({ effects: setSignature.of({ pos: inside, help }) });
+ if (help?.signatures.some((sig) => sig.parameters.length))
+ view.dispatch({ effects: setSignature.of({ pos: inside, help }) });
else view.dispatch({ selection: EditorSelection.cursor(inside + 1) });
}
@@ -146,7 +147,10 @@ const signaturePlugin = ViewPlugin.fromClass(
update(u: ViewUpdate) {
const active = u.state.field(signatureField, false);
let typedTrigger = false;
- if (u.docChanged && u.transactions.some((tr) => tr.isUserEvent("input.type") || tr.isUserEvent("input.complete"))) {
+ if (
+ u.docChanged &&
+ u.transactions.some((tr) => tr.isUserEvent("input.type") || tr.isUserEvent("input.complete"))
+ ) {
// The character before the caret: `(` is followed by an auto-inserted `)`.
const head = u.state.selection.main.head;
const before = u.state.sliceDoc(Math.max(0, head - 1), head);
diff --git a/src/editor/lsp/spelling.test.ts b/src/editor/lsp/spelling.test.ts
index a2fa3e83c..6f93be8c2 100644
--- a/src/editor/lsp/spelling.test.ts
+++ b/src/editor/lsp/spelling.test.ts
@@ -4,7 +4,11 @@ import { EditorView } from "@codemirror/view";
import type { Settings, Typo } from "@/bindings";
let typos: Typo[] = [];
-const commentTypo: Typo = { range: { start: { line: 0, col: 3 }, end: { line: 0, col: 9 } }, word: "mesage", context: "comment" };
+const commentTypo: Typo = {
+ range: { start: { line: 0, col: 3 }, end: { line: 0, col: 9 } },
+ word: "mesage",
+ context: "comment",
+};
const spellCheck = vi.fn(async () => ({ status: "ok" as const, data: typos }));
const settingsSet = vi.fn(async (_scope: string, _key: string, value: string) => ({
status: "ok" as const,
@@ -123,10 +127,17 @@ describe("Typo inspection", () => {
vi.useFakeTimers();
const options = (o: Record<string, boolean>) =>
({ inspections: { default: { "builtin:spelling": { options: o } } } }) as never;
- useProject.setState({ project: { root: "/p" } as never, settings: options({ processCode: false, processLiterals: false }) });
+ useProject.setState({
+ project: { root: "/p" } as never,
+ settings: options({ processCode: false, processLiterals: false }),
+ });
editor("// mesage");
await settle();
- expect(spellCheck).toHaveBeenLastCalledWith(7, { code: false, literals: false, comments: true }, expect.any(Number));
+ expect(spellCheck).toHaveBeenLastCalledWith(
+ 7,
+ { code: false, literals: false, comments: true },
+ expect.any(Number),
+ );
useProject.setState({ settings: options({ processComments: false }) });
await settle();
expect(spellCheck).toHaveBeenCalledTimes(2);
@@ -136,7 +147,13 @@ describe("Typo inspection", () => {
it("keeps lint conversion of plain info diagnostics unchanged", () => {
const doc = Text.of(["abc"]);
const out = toLintDiagnostics(doc, [
- { range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } }, severity: "info", message: "m", source: null, code: null },
+ {
+ range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
+ severity: "info",
+ message: "m",
+ source: null,
+ code: null,
+ },
]);
expect(out[0]!.markClass).toBeUndefined();
});
diff --git a/src/editor/lsp/spelling.ts b/src/editor/lsp/spelling.ts
index 11f2d74de..89284b330 100644
--- a/src/editor/lsp/spelling.ts
+++ b/src/editor/lsp/spelling.ts
@@ -58,7 +58,11 @@ const spellingEnabled = () => inspectionProfile()[SPELLING_INSPECTION]?.enabled
export function spellScope(): SpellScope {
const profile = inspectionProfile();
const on = (key: string) => inspectionOption(profile, SPELLING_INSPECTION, key);
- return { code: on(SPELLING_OPTIONS.code), literals: on(SPELLING_OPTIONS.literals), comments: on(SPELLING_OPTIONS.comments) };
+ return {
+ code: on(SPELLING_OPTIONS.code),
+ literals: on(SPELLING_OPTIONS.literals),
+ comments: on(SPELLING_OPTIONS.comments),
+ };
}
const spellingOf = (s: Settings | null) => s?.spelling;
diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.ts
index d43144fa0..e709a8e31 100644
--- a/src/editor/lsp/syntaxFallback.test.ts
+++ b/src/editor/lsp/syntaxFallback.test.ts
@@ -5,7 +5,8 @@ import type { IdeError, Locals, NodeAt, Range, SymbolMatch, SyntaxNode } from "@
type R<T> = Promise<{ status: "ok"; data: T } | { status: "error"; error: IdeError }>;
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
-const unavailable = () => Promise.resolve({ status: "error" as const, error: { kind: "unavailable", message: "no server" } as IdeError });
+const unavailable = () =>
+ Promise.resolve({ status: "error" as const, error: { kind: "unavailable", message: "no server" } as IdeError });
const cmd = {
lspHover: vi.fn((): R<unknown> => ok(null)),
@@ -79,7 +80,10 @@ function editor(doc: string, language = "typescript", anchor = 0) {
state: EditorState.create({
doc,
selection: { anchor },
- extensions: [lspDoc.of({ doc: 7, path: "/p/a.ts", language, uiMode: null, readOnly: false }), navigationExtension()],
+ extensions: [
+ lspDoc.of({ doc: 7, path: "/p/a.ts", language, uiMode: null, readOnly: false }),
+ navigationExtension(),
+ ],
}),
parent: document.body,
});
@@ -98,15 +102,27 @@ describe("usageRole / filterSymbols", () => {
it("reads the role from the tree", () => {
const id = r(0, 0, 3);
expect(fb.usageRole({ node: node("type_identifier", id), ancestors: [] })).toBe("type");
- expect(fb.usageRole({ node: node("identifier", id, "function"), ancestors: [node("call_expression", id)] })).toBe("call");
- expect(fb.usageRole({ node: node("identifier", id, "name"), ancestors: [node("method_invocation", id)] })).toBe("call");
- expect(fb.usageRole({ node: node("identifier", id, "constructor"), ancestors: [node("new_expression", id)] })).toBe("new");
+ expect(fb.usageRole({ node: node("identifier", id, "function"), ancestors: [node("call_expression", id)] })).toBe(
+ "call",
+ );
+ expect(fb.usageRole({ node: node("identifier", id, "name"), ancestors: [node("method_invocation", id)] })).toBe(
+ "call",
+ );
+ expect(fb.usageRole({ node: node("identifier", id, "constructor"), ancestors: [node("new_expression", id)] })).toBe(
+ "new",
+ );
expect(fb.usageRole({ node: node("identifier", id), ancestors: [node("binary_expression", id)] })).toBe("other");
expect(fb.usageRole(null)).toBe("other");
});
it("keeps exact names whose kind fits the role", () => {
- const all = [sym("Foo", "class", "/a"), sym("Foo", "function", "/b"), sym("Foo", "field", "/c"), sym("Foobar", "class", "/d"), sym("Foo", "file", "/e")];
+ const all = [
+ sym("Foo", "class", "/a"),
+ sym("Foo", "function", "/b"),
+ sym("Foo", "field", "/c"),
+ sym("Foobar", "class", "/d"),
+ sym("Foo", "file", "/e"),
+ ];
expect(fb.filterSymbols(all, "Foo", "type").map((s) => s.path)).toEqual(["/a"]);
expect(fb.filterSymbols(all, "Foo", "call").map((s) => s.path)).toEqual(["/a", "/b"]);
expect(fb.filterSymbols(all, "Foo", "other").map((s) => s.path)).toEqual(["/a", "/b", "/c"]);
@@ -153,9 +169,19 @@ describe("declarationFallback", () => {
});
it("looks non-locals up in the index by exact name and role", async () => {
- cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "unresolved" }));
- cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9), "function"), ancestors: [node("call_expression", r(1, 6, 11))] }));
- cmd.findSymbols.mockReturnValueOnce(ok([sym("foo", "function", "/p/b.ts", "util"), sym("foo", "field", "/p/c.ts"), sym("foobar", "function", "/p/d.ts")]));
+ cmd.syntaxLocals.mockReturnValueOnce(
+ ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "unresolved" }),
+ );
+ cmd.syntaxNodeAt.mockReturnValueOnce(
+ ok({ node: node("identifier", r(1, 6, 9), "function"), ancestors: [node("call_expression", r(1, 6, 11))] }),
+ );
+ cmd.findSymbols.mockReturnValueOnce(
+ ok([
+ sym("foo", "function", "/p/b.ts", "util"),
+ sym("foo", "field", "/p/c.ts"),
+ sym("foobar", "function", "/p/d.ts"),
+ ]),
+ );
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
expect(cmd.findSymbols).toHaveBeenCalledWith("foo", "all", 500);
expect(res).toEqual({
@@ -168,7 +194,9 @@ describe("declarationFallback", () => {
it("does not filter members by role", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("property_identifier", r(1, 6, 9)), ancestors: [] }));
- cmd.findSymbols.mockReturnValueOnce(ok([sym("foo", "method", "/p/b.ts", "A"), sym("foo", "field", "/p/c.ts", "B")]));
+ cmd.findSymbols.mockReturnValueOnce(
+ ok([sym("foo", "method", "/p/b.ts", "A"), sym("foo", "field", "/p/c.ts", "B")]),
+ );
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
expect(res).toMatchObject({ kind: "targets", ambiguous: true });
});
@@ -179,7 +207,9 @@ describe("declarationFallback", () => {
await fb.declarationFallback({ ...doc, language: "nolocals" }, text, { line: 1, col: 7 });
expect(cmd.findSymbols).toHaveBeenCalledWith("foo", "all", 500);
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: false, locals: false }));
- expect(await fb.declarationFallback({ ...doc, language: "nogrammar" }, text, { line: 0, col: 0 })).toEqual({ kind: "unsupported" });
+ expect(await fb.declarationFallback({ ...doc, language: "nogrammar" }, text, { line: 0, col: 0 })).toEqual({
+ kind: "unsupported",
+ });
});
});
@@ -205,13 +235,17 @@ describe("rename helpers", () => {
const id = r(0, 0, 1);
expect(fb.isShorthand({ node: node("shorthand_property_identifier", id), ancestors: [] })).toBe(true);
expect(fb.isShorthand({ node: node("shorthand_property_identifier_pattern", id), ancestors: [] })).toBe(true);
- expect(fb.isShorthand({ node: node("identifier", id), ancestors: [node("shorthand_field_initializer", id)] })).toBe(true);
+ expect(fb.isShorthand({ node: node("identifier", id), ancestors: [node("shorthand_field_initializer", id)] })).toBe(
+ true,
+ );
expect(fb.isShorthand({ node: node("identifier", id), ancestors: [node("arguments", id)] })).toBe(false);
});
it("refuses non-locals and plans locals with shorthand detection", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(0, 0, 3), reason: "member" }));
- expect(await fb.planLocalRename({ doc: 7, language: "typescript" }, { line: 0, col: 1 })).toMatchObject({ kind: "refused" });
+ expect(await fb.planLocalRename({ doc: 7, language: "typescript" }, { line: 0, col: 1 })).toMatchObject({
+ kind: "refused",
+ });
cmd.syntaxLocals.mockReturnValueOnce(ok(local()));
cmd.syntaxNodeAt
.mockReturnValueOnce(ok({ node: node("identifier", r(0, 6, 7)), ancestors: [] }))
@@ -226,7 +260,10 @@ describe("rename helpers", () => {
});
it("flags ambiguity and name clashes inside the scope", async () => {
- const plan = { symbol: (local({ certain: false, conflicts: [r(3, 0, 1)] }) as Extract<Locals, { status: "local" }>).symbol, occurrences: [] };
+ const plan = {
+ symbol: (local({ certain: false, conflicts: [r(3, 0, 1)] }) as Extract<Locals, { status: "local" }>).symbol,
+ occurrences: [],
+ };
cmd.syntaxIdentifiers.mockReturnValueOnce(
ok([
{ range: r(2, 0, 1), kind: "identifier", qualified: false },
@@ -269,7 +306,9 @@ describe("navigation wiring", () => {
it("opens a chooser for several index candidates", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "run", range: r(0, 4, 7), reason: "member" }));
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("property_identifier", r(0, 4, 7)), ancestors: [] }));
- cmd.findSymbols.mockReturnValueOnce(ok([sym("run", "method", "/p/a.ts", "A"), sym("run", "method", "/p/b.ts", "B")]));
+ cmd.findSymbols.mockReturnValueOnce(
+ ok([sym("run", "method", "/p/a.ts", "A"), sym("run", "method", "/p/b.ts", "B")]),
+ );
const view = editor("obj.run();", "typescript", 5);
await gotoTargets(view, "definition");
const popup = useLspPopup.getState().popup;
@@ -303,7 +342,9 @@ describe("navigation wiring", () => {
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "x", range: r(0, 0, 1), reason: "topLevel" }));
const view = editor("x;", "typescript", 0);
highlightUsages(view);
- await vi.waitFor(() => expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No language server available"));
+ await vi.waitFor(() =>
+ expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No language server available"),
+ );
expect(view.dom.querySelectorAll(".cm-lsp-occurrence")).toHaveLength(0);
});
});
@@ -326,7 +367,9 @@ describe("rename wiring", () => {
});
it("asks before renaming an ambiguous local", async () => {
- cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [r(1, 0, 1)], certain: false, conflicts: [r(2, 4, 5)] })));
+ cmd.syntaxLocals.mockReturnValueOnce(
+ ok(local({ references: [r(1, 0, 1)], certain: false, conflicts: [r(2, 4, 5)] })),
+ );
const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6);
await startRename(view);
const popup = useLspPopup.getState().popup;
@@ -364,14 +407,18 @@ describe("rename wiring", () => {
});
it("falls back to the syntax rename of a local, references included", async () => {
- cmd.syntaxLocals.mockReturnValueOnce(ok(local({ name: "mesage", definition: r(0, 0, 6), references: [r(1, 6, 12)] })));
+ cmd.syntaxLocals.mockReturnValueOnce(
+ ok(local({ name: "mesage", definition: r(0, 0, 6), references: [r(1, 6, 12)] })),
+ );
const view = editor("mesage = 'hello'\nprint(mesage)", "python", 0);
await renameNamePart(view, { from: 0, to: 6 }, "message");
expect(view.state.doc.toString()).toBe("message = 'hello'\nprint(message)");
});
it("changes nothing when the symbol can't be renamed safely", async () => {
- cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "mesage", range: r(0, 0, 6), reason: "topLevel" }));
+ cmd.syntaxLocals.mockReturnValueOnce(
+ ok({ status: "notLocal", name: "mesage", range: r(0, 0, 6), reason: "topLevel" }),
+ );
const view = editor("mesage = 'hello'\nprint(mesage)", "python", 0);
await renameNamePart(view, { from: 0, to: 6 }, "message");
expect(view.state.doc.toString()).toBe("mesage = 'hello'\nprint(mesage)");
@@ -387,7 +434,12 @@ describe("rename wiring", () => {
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("This element can't be renamed");
cmd.lspPrepareRename.mockReturnValueOnce(ok(null));
- cmd.syntaxErrors.mockReturnValueOnce(ok({ errors: [{ kind: "missing", range: r(0, 12, 12), expected: ";", message: "missing `;`" }], truncated: false }));
+ cmd.syntaxErrors.mockReturnValueOnce(
+ ok({
+ errors: [{ kind: "missing", range: r(0, 12, 12), expected: ";", message: "missing `;`" }],
+ truncated: false,
+ }),
+ );
cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] })));
await startRename(view);
expect(useLspPopup.getState().popup?.kind).toBe("rename");
diff --git a/src/editor/lsp/syntaxFallback.ts b/src/editor/lsp/syntaxFallback.ts
index 5a6ff2c56..496c0e1e2 100644
--- a/src/editor/lsp/syntaxFallback.ts
+++ b/src/editor/lsp/syntaxFallback.ts
@@ -42,7 +42,8 @@ const NON_DECLARATIONS: ReadonlySet<SymbolKind> = new Set(["file", "package", "m
export type UsageRole = "type" | "call" | "new" | "other";
const TYPE_NODE = /(^|_)type_identifier$|^user_type$|^scoped_type_identifier$/;
-const TYPE_PARENT = /^(generic_type|user_type|nullable_type|type_annotation|type_arguments|scoped_type_identifier|qualified_type|array_type)$/;
+const TYPE_PARENT =
+ /^(generic_type|user_type|nullable_type|type_annotation|type_arguments|scoped_type_identifier|qualified_type|array_type)$/;
const CALL_PARENT = /(^|_)(call|invocation)(_expression)?$|^call$/;
const NEW_PARENT = /^(new_expression|object_creation_expression|instance_creation_expression|constructor_invocation)$/;
@@ -53,7 +54,11 @@ export function usageRole(at: NodeAt | null): UsageRole {
const parent = at.ancestors[0];
if (parent && NEW_PARENT.test(parent.kind)) return "new";
if (TYPE_NODE.test(node.kind) || node.field === "type" || (parent && TYPE_PARENT.test(parent.kind))) return "type";
- if (parent && CALL_PARENT.test(parent.kind) && (node.field === "function" || node.field === "name" || node.field == null))
+ if (
+ parent &&
+ CALL_PARENT.test(parent.kind) &&
+ (node.field === "function" || node.field === "name" || node.field == null)
+ )
return "call";
return "other";
}
@@ -245,7 +250,10 @@ export async function planLocalRename(
const shorthand = SHORTHAND_LANGUAGES.has(doc.language)
? await Promise.all(ranges.map((r) => structure.nodeAt(doc.doc, r, { signal }).then(isShorthand)))
: ranges.map(() => false);
- return { kind: "plan", plan: { symbol, occurrences: ranges.map((range, i) => ({ range, shorthand: shorthand[i]! })) } };
+ return {
+ kind: "plan",
+ plan: { symbol, occurrences: ranges.map((range, i) => ({ range, shorthand: shorthand[i]! })) },
+ };
}
/** CodeMirror changes renaming every occurrence; shorthands keep their key. Null when the text no longer matches. */
@@ -260,7 +268,12 @@ export function renameChanges(doc: Text, plan: LocalRenamePlan, newName: string)
}
/** Why a syntax-based rename needs confirmation (empty: safe to apply). */
-export async function renameRisks(doc: number, plan: LocalRenamePlan, newName: string, signal?: AbortSignal): Promise<string[]> {
+export async function renameRisks(
+ doc: number,
+ plan: LocalRenamePlan,
+ newName: string,
+ signal?: AbortSignal,
+): Promise<string[]> {
const risks: string[] = [];
const { symbol } = plan;
if (!symbol.certain)
@@ -271,7 +284,9 @@ export async function renameRisks(doc: number, plan: LocalRenamePlan, newName: s
(o) => !o.qualified && rangeContains(symbol.scope, o.range.start),
);
if (clashes.length)
- risks.push(`'${newName}' is already used in this scope (${clashes.length} ${clashes.length === 1 ? "occurrence" : "occurrences"}).`);
+ risks.push(
+ `'${newName}' is already used in this scope (${clashes.length} ${clashes.length === 1 ? "occurrence" : "occurrences"}).`,
+ );
return risks;
}
diff --git a/src/editor/lsp/tempHighlight.ts b/src/editor/lsp/tempHighlight.ts
index 9cba8aa91..498d503ec 100644
--- a/src/editor/lsp/tempHighlight.ts
+++ b/src/editor/lsp/tempHighlight.ts
@@ -38,7 +38,8 @@ export function highlightRanges(view: EditorView, ranges: readonly HighlightRang
.map((r) => ({ from: Math.max(0, Math.min(r.from, len)), to: Math.max(0, Math.min(r.to, len)) }))
.sort((a, b) => a.from - b.from);
const effects: StateEffect<unknown>[] = [setTemporary.of(clamped)];
- if (!view.state.field(temporaryField, false)) effects.push(StateEffect.appendConfig.of(temporaryHighlightExtension()));
+ if (!view.state.field(temporaryField, false))
+ effects.push(StateEffect.appendConfig.of(temporaryHighlightExtension()));
const first = clamped[0];
if (first) effects.push(EditorView.scrollIntoView(first.from, { y: "nearest" }));
view.dispatch({ effects });
diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts
index 38072f31d..98b64de17 100644
--- a/src/editor/lsp/theme.ts
+++ b/src/editor/lsp/theme.ts
@@ -202,7 +202,14 @@ export const lspTheme = EditorView.theme({
".cm-lsp-diag-warning .cm-lsp-diag-icon": { color: "var(--warning)" },
".cm-lsp-diag-info .cm-lsp-diag-icon, .cm-lsp-diag-hint .cm-lsp-diag-icon": { color: "var(--info)" },
".cm-lsp-diag-message": { color: "var(--fg-strong)", whiteSpace: "pre-wrap", lineHeight: "18px" },
- ".cm-lsp-diag-meta": { display: "flex", flexWrap: "wrap", columnGap: "12px", rowGap: "2px", marginTop: "6px", alignItems: "baseline" },
+ ".cm-lsp-diag-meta": {
+ display: "flex",
+ flexWrap: "wrap",
+ columnGap: "12px",
+ rowGap: "2px",
+ marginTop: "6px",
+ alignItems: "baseline",
+ },
".cm-lsp-diag-meta > *": { whiteSpace: "nowrap" },
".cm-lsp-diag-source": { color: "var(--fg-subtle)", fontSize: "var(--fs-small)" },
".cm-lsp-link-button": {
@@ -358,7 +365,11 @@ export const lspTheme = EditorView.theme({
".cm-sem-builtin:not(.cm-sem-function)": { color: "var(--syn-builtin, inherit)" },
".cm-sem-static": { fontStyle: "var(--syn-static-italic, italic)" },
".cm-sem-python-static": { fontStyle: "var(--syn-python-static-italic, normal)" },
- ".cm-sem-mutable": { textDecoration: "underline", textDecorationColor: "var(--fg-faint)", textUnderlineOffset: "3px" },
+ ".cm-sem-mutable": {
+ textDecoration: "underline",
+ textDecorationColor: "var(--fg-faint)",
+ textUnderlineOffset: "3px",
+ },
".cm-sem-deprecated": { textDecoration: "line-through" },
// Semantic highlighting: after the base classes so a parameter's colour gives way, and over the
// syntax highlighter's span inside.
diff --git a/src/editor/lsp/typeInfo.ts b/src/editor/lsp/typeInfo.ts
index 8b7d582ee..1f75d4c5f 100644
--- a/src/editor/lsp/typeInfo.ts
+++ b/src/editor/lsp/typeInfo.ts
@@ -68,7 +68,10 @@ export async function expressionTypeInfo(view: EditorView) {
kind: "doc",
anchor: caretAnchor(view, hover.range ? rangeToOffsets(view.state.doc, hover.range).from : pos),
entries: [
- { markup: { kind: "markdown", value: `\`\`\`${language}\n${info.text}\n\`\`\`` }, language: docOf(view)?.uiMode ?? null },
+ {
+ markup: { kind: "markdown", value: `\`\`\`${language}\n${info.text}\n\`\`\`` },
+ language: docOf(view)?.uiMode ?? null,
+ },
],
index: 0,
themeClasses: view.themeClasses,
diff --git a/src/editor/lsp/workspaceEdit.test.ts b/src/editor/lsp/workspaceEdit.test.ts
index 448bc014e..324f30292 100644
--- a/src/editor/lsp/workspaceEdit.test.ts
+++ b/src/editor/lsp/workspaceEdit.test.ts
@@ -50,7 +50,15 @@ describe("summarizeWorkspaceEdit", () => {
});
describe("editPreviewLines", () => {
- const doc = Text.of(["function f() {", " return price * 2;", "}", "", "const a = 1;", "const b = 2;", "const c = 3;"]);
+ const doc = Text.of([
+ "function f() {",
+ " return price * 2;",
+ "}",
+ "",
+ "const a = 1;",
+ "const b = 2;",
+ "const c = 3;",
+ ]);
const at = (line: number, col: number) => ({ line, col });
it("shows changed lines with one line of context, hunks separated", () => {
diff --git a/src/editor/lsp/workspaceEdit.ts b/src/editor/lsp/workspaceEdit.ts
index 1ad882d62..4419af5ee 100644
--- a/src/editor/lsp/workspaceEdit.ts
+++ b/src/editor/lsp/workspaceEdit.ts
@@ -78,10 +78,15 @@ export function needsPreview(s: WorkspaceEditSummary): boolean {
function lineDiff(a: readonly string[], b: readonly string[]): DiffLine[] {
const n = a.length;
const m = b.length;
- if (n * m > 250_000) return [...a.map((text) => ({ kind: "removed" as const, text })), ...b.map((text) => ({ kind: "added" as const, text }))];
+ if (n * m > 250_000)
+ return [
+ ...a.map((text) => ({ kind: "removed" as const, text })),
+ ...b.map((text) => ({ kind: "added" as const, text })),
+ ];
const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
for (let i = n - 1; i >= 0; i--)
- for (let j = m - 1; j >= 0; j--) lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
+ for (let j = m - 1; j >= 0; j--)
+ lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
const out: DiffLine[] = [];
let i = 0;
let j = 0;
diff --git a/src/editor/navigation/gotoTest.test.ts b/src/editor/navigation/gotoTest.test.ts
index 6b0d80e90..92fc13c44 100644
--- a/src/editor/navigation/gotoTest.test.ts
+++ b/src/editor/navigation/gotoTest.test.ts
@@ -23,7 +23,10 @@ function deps(files: string[], roots = ROOTS) {
}
beforeEach(() => {
- useProject.setState({ project: { name: "p", root: "/p", isGit: false, settings: {} } as never, settings: {} as never });
+ useProject.setState({
+ project: { name: "p", root: "/p", isGit: false, settings: {} } as never,
+ settings: {} as never,
+ });
});
describe("Go to Test / Test Subject", () => {
@@ -40,7 +43,11 @@ describe("Go to Test / Test Subject", () => {
});
it("shows a chooser with Create New Test… for several tests, mirrored package first", async () => {
- const d = deps(["/p/src/test/java/b/FooTest.java", "/p/src/test/java/a/FooTests.java", "/p/src/main/java/a/Foo.java"]);
+ const d = deps([
+ "/p/src/test/java/b/FooTest.java",
+ "/p/src/test/java/a/FooTests.java",
+ "/p/src/main/java/a/Foo.java",
+ ]);
await gotoTestOrSubject("/p/src/main/java/a/Foo.java", "", d);
expect(d.chosen[0]!.title).toBe("Choose Test for Foo (2 found)");
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["Create New Test…", "FooTests.java", "FooTest.java"]);
@@ -51,11 +58,19 @@ describe("Go to Test / Test Subject", () => {
await gotoTestOrSubject("/p/src/main/java/a/Foo.java", "", d);
expect(d.chosen[0]!.items.map((i) => i.label)).toEqual(["Create New Test…"]);
await d.chosen[0]!.items[0]!.run();
- expect(d.createTest).toHaveBeenCalledWith({ directory: "/p/src/test/java/a", name: "FooTest", extension: "java", subject: "Foo.java" });
+ expect(d.createTest).toHaveBeenCalledWith({
+ directory: "/p/src/test/java/a",
+ name: "FooTest",
+ extension: "java",
+ subject: "Foo.java",
+ });
});
it("does not take a non-test file of a test-like name as a test", async () => {
- const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/main/java/a/FooTests.java"], [root("src/main/java", "source")]);
+ const d = deps(
+ ["/p/src/main/java/a/Foo.java", "/p/src/main/java/a/FooTests.java"],
+ [root("src/main/java", "source")],
+ );
// FooTests.java is a test by name, wherever it is.
await gotoTestOrSubject("/p/src/main/java/a/Foo.java", "", d);
expect(d.open).toHaveBeenCalledWith("/p/src/main/java/a/FooTests.java");
diff --git a/src/editor/navigation/gotoTest.ts b/src/editor/navigation/gotoTest.ts
index 583179117..d4ed31429 100644
--- a/src/editor/navigation/gotoTest.ts
+++ b/src/editor/navigation/gotoTest.ts
@@ -7,7 +7,15 @@
import { basename, dirname } from "@/platform/project";
import { isTestFile, rootOfPath } from "@/platform/projectRoots";
import type { RootFolder } from "@/platform/languageSettings";
-import { isTestName, newTestName, rankCandidates, rustTestModuleOffset, splitName, subjectNamesFor, testNamesFor } from "./testNaming";
+import {
+ isTestName,
+ newTestName,
+ rankCandidates,
+ rustTestModuleOffset,
+ splitName,
+ subjectNamesFor,
+ testNamesFor,
+} from "./testNaming";
export interface ChooserItem {
label: string;
@@ -87,14 +95,22 @@ export async function gotoTestOrSubject(path: string, text: string, deps: TestNa
const subjects = rank((await findAll(subjectNamesFor(name), path, deps)).filter((p) => !isTestSide(p, roots)));
if (subjects.length === 1) return deps.open(subjects[0]!);
if (!subjects.length) return deps.hint("No test subject found");
- return deps.choose(`Choose Test Subject for ${splitName(name).stem} (${subjects.length} found)`, subjects.map((p) => ({ label: basename(p), detail: relLabel(root, dirname(p)), run: () => deps.open(p) })));
+ return deps.choose(
+ `Choose Test Subject for ${splitName(name).stem} (${subjects.length} found)`,
+ subjects.map((p) => ({ label: basename(p), detail: relLabel(root, dirname(p)), run: () => deps.open(p) })),
+ );
}
const tests = rank((await findAll(testNamesFor(name), path, deps)).filter((p) => isTestSide(p, roots)));
- const items: ChooserItem[] = tests.map((p) => ({ label: basename(p), detail: relLabel(root, dirname(p)), run: () => deps.open(p) }));
+ const items: ChooserItem[] = tests.map((p) => ({
+ label: basename(p),
+ detail: relLabel(root, dirname(p)),
+ run: () => deps.open(p),
+ }));
// Rust unit tests live in the file's own `#[cfg(test)]` module.
const inFile = path.endsWith(".rs") ? rustTestModuleOffset(text) : null;
- if (inFile !== null) items.unshift({ label: "mod tests", detail: `${name} (#[cfg(test)])`, run: () => deps.open(path, inFile) });
+ if (inFile !== null)
+ items.unshift({ label: "mod tests", detail: `${name} (#[cfg(test)])`, run: () => deps.open(path, inFile) });
if (items.length === 1) return void (await items[0]!.run());
const { ext } = splitName(name);
const create: ChooserItem = {
diff --git a/src/editor/navigation/index.ts b/src/editor/navigation/index.ts
index 832b6fe10..142283559 100644
--- a/src/editor/navigation/index.ts
+++ b/src/editor/navigation/index.ts
@@ -38,7 +38,10 @@ async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promis
const outlineOf = (doc: number) => lspRequest(() => commands.docOutline(doc));
-async function caretOutline(view: EditorView, ctx: EditorDocContext): Promise<{ outline: OutlineItem[]; caret: Pos } | null> {
+async function caretOutline(
+ view: EditorView,
+ ctx: EditorDocContext,
+): Promise<{ outline: OutlineItem[]; caret: Pos } | null> {
await whenSynced(view);
const caret = offsetToPos(view.state.doc, view.state.selection.main.head);
try {
@@ -75,7 +78,8 @@ async function superMethod(view: EditorView) {
if (!at) return;
const { method, type } = memberAt(at.outline, at.caret);
const deps = {
- supertypes: (path: string, pos: Pos) => withDoc(path, (doc) => lspRequest(() => commands.lspTypeHierarchy(doc, pos, "incoming"))),
+ supertypes: (path: string, pos: Pos) =>
+ withDoc(path, (doc) => lspRequest(() => commands.lspTypeHierarchy(doc, pos, "incoming"))),
outline: (path: string) => withDoc(path, outlineOf),
};
let locs: Location[] = [];
@@ -98,18 +102,22 @@ async function superMethod(view: EditorView) {
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
- title: method ? tx`Choose Super Method of ${baseName(method.name)} (${locs.length} found)` : tx`Choose Super Class or Interface (${locs.length} found)`,
+ title: method
+ ? tx`Choose Super Method of ${baseName(method.name)} (${locs.length} found)`
+ : tx`Choose Super Class or Interface (${locs.length} found)`,
items: await locationItems(locs),
});
}
-const RUST_TEST_MODULE = "\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n \n }\n}\n";
+const RUST_TEST_MODULE =
+ "\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn it_works() {\n \n }\n}\n";
function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
return {
projectRoot: () => useProject.getState().project?.root ?? null,
roots: () => currentRoots(),
- findByName: async (name) => (await call(commands.findFiles(name, 50))).filter((m) => basename(m.path) === name).map((m) => m.path),
+ findByName: async (name) =>
+ (await call(commands.findFiles(name, 50))).filter((m) => basename(m.path) === name).map((m) => m.path),
open: async (path, offset) => {
const selection = offset !== undefined && path === ctx.path ? offsetToPos(view.state.doc, offset) : undefined;
await editorService().openFile(path, { selection, focus: true });
@@ -129,13 +137,19 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
})),
}),
hint: (text) => showHint(view, text),
- createTest: ({ directory, name, extension }) => void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
+ createTest: ({ directory, name, extension }) =>
+ void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
createRustTestModule: () => {
if (view.state.readOnly) return;
const end = view.state.doc.length;
const insert = (view.state.doc.sliceString(end - 1) === "\n" ? "" : "\n") + RUST_TEST_MODULE;
const caret = end + insert.indexOf("fn it_works() {\n") + "fn it_works() {\n ".length;
- view.dispatch({ changes: { from: end, insert }, selection: EditorSelection.cursor(caret), scrollIntoView: true, userEvent: "input" });
+ view.dispatch({
+ changes: { from: end, insert },
+ selection: EditorSelection.cursor(caret),
+ scrollIntoView: true,
+ userEvent: "input",
+ });
view.focus();
},
};
@@ -151,7 +165,12 @@ async function gotoTest(view: EditorView) {
}
}
-function editorAction(id: string, title: string, run: (view: EditorView) => unknown, extra: Partial<Action> = {}): Action {
+function editorAction(
+ id: string,
+ title: string,
+ run: (view: EditorView) => unknown,
+ extra: Partial<Action> = {},
+): Action {
return {
id,
title,
@@ -168,7 +187,9 @@ function editorAction(id: string, title: string, run: (view: EditorView) => unkn
export function registerNavigationActions(): () => void {
return registerActions([
editorAction("navigate.gotoTest", "Test", gotoTest, { keywords: ["go to test", "test subject", "create test"] }),
- editorAction("navigate.superMethod", "Super Method", superMethod, { keywords: ["go to super", "overridden", "parent"] }),
+ editorAction("navigate.superMethod", "Super Method", superMethod, {
+ keywords: ["go to super", "overridden", "parent"],
+ }),
editorAction("navigate.nextMethod", "Next Method", (v) => gotoMethod(v, 1)),
editorAction("navigate.previousMethod", "Previous Method", (v) => gotoMethod(v, -1)),
]);
diff --git a/src/editor/navigation/structureNav.test.ts b/src/editor/navigation/structureNav.test.ts
index d0781c0c5..dcfaf4eae 100644
--- a/src/editor/navigation/structureNav.test.ts
+++ b/src/editor/navigation/structureNav.test.ts
@@ -4,11 +4,23 @@ import { memberAt, methodStop, methodStops, superMethods } from "./structureNav"
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
- return { name, kind, detail: null, range: r(from, to), selection_range: { start: { line: from, col: 4 }, end: { line: from, col: 4 + name.length } }, children };
+ return {
+ name,
+ kind,
+ detail: null,
+ range: r(from, to),
+ selection_range: { start: { line: from, col: 4 }, end: { line: from, col: 4 + name.length } },
+ children,
+ };
}
const OUTLINE = [
- item("Foo", "class", 0, 20, [item("x", "field", 1, 1), item("a", "method", 2, 5), item("b", "method", 7, 9), item("Inner", "class", 11, 18, [item("c", "method", 12, 14)])]),
+ item("Foo", "class", 0, 20, [
+ item("x", "field", 1, 1),
+ item("a", "method", 2, 5),
+ item("b", "method", 7, 9),
+ item("Inner", "class", 11, 18, [item("c", "method", 12, 14)]),
+ ]),
item("main", "function", 22, 25),
];
@@ -76,9 +88,12 @@ describe("Super Method", () => {
};
const deps = {
supertypes: async (path: string) => (path === "/Foo.java" ? [base] : []),
- outline: async () => [item("Base", "class", 0, 10, [item("eat(String)", "method", 2, 2), item("eat(int)", "method", 4, 4)])],
+ outline: async () => [
+ item("Base", "class", 0, 10, [item("eat(String)", "method", 2, 2), item("eat(int)", "method", 4, 4)]),
+ ],
};
- const lines = async (name: string) => (await superMethods("/Foo.java", { line: 0, col: 4 }, name, deps)).map((l) => l.range.start.line);
+ const lines = async (name: string) =>
+ (await superMethods("/Foo.java", { line: 0, col: 4 }, name, deps)).map((l) => l.range.start.line);
expect(await lines("eat(int)")).toEqual([4]);
// Without a matching signature (or without signatures at all), every overload.
expect(await lines("eat(T)")).toEqual([2, 4]);
diff --git a/src/editor/navigation/structureNav.ts b/src/editor/navigation/structureNav.ts
index ce18f0923..0d1212719 100644
--- a/src/editor/navigation/structureNav.ts
+++ b/src/editor/navigation/structureNav.ts
@@ -103,7 +103,13 @@ export interface SuperMethod {
}
/** Super methods of `method` (a member of the type at `typePos`), with their declaring types, nearest level first. */
-export async function superMethodTargets(path: string, typePos: Pos, method: string, deps: SuperDeps, depth = 3): Promise<SuperMethod[]> {
+export async function superMethodTargets(
+ path: string,
+ typePos: Pos,
+ method: string,
+ deps: SuperDeps,
+ depth = 3,
+): Promise<SuperMethod[]> {
let level: Array<{ path: string; pos: Pos }> = [{ path, pos: typePos }];
const seen = new Set<string>();
for (let d = 0; d < depth && level.length; d++) {
@@ -117,7 +123,8 @@ export async function superMethodTargets(path: string, typePos: Pos, method: str
seen.add(key);
const methods = methodsInType(await deps.outline(s.path).catch(() => [] as OutlineItem[]), s, method);
if (methods.length)
- for (const m of methods) found.push({ location: { path: s.path, range: m.selection_range }, owner: s, method: m });
+ for (const m of methods)
+ found.push({ location: { path: s.path, range: m.selection_range }, owner: s, method: m });
else next.push({ path: s.path, pos: s.selectionRange.start });
}
}
@@ -128,6 +135,12 @@ export async function superMethodTargets(path: string, typePos: Pos, method: str
}
/** Super methods of `method` (a member of the type at `typePos`), searching up to `depth` levels of supertypes. */
-export async function superMethods(path: string, typePos: Pos, method: string, deps: SuperDeps, depth = 3): Promise<Location[]> {
+export async function superMethods(
+ path: string,
+ typePos: Pos,
+ method: string,
+ deps: SuperDeps,
+ depth = 3,
+): Promise<Location[]> {
return (await superMethodTargets(path, typePos, method, deps, depth)).map((s) => s.location);
}
diff --git a/src/editor/navigation/testNaming.test.ts b/src/editor/navigation/testNaming.test.ts
index 32eb7b314..b1de0517d 100644
--- a/src/editor/navigation/testNaming.test.ts
+++ b/src/editor/navigation/testNaming.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from "vitest";
-import { isTestName, newTestName, rankCandidates, rustTestModuleOffset, subjectNamesFor, testNamesFor } from "./testNaming";
+import {
+ isTestName,
+ newTestName,
+ rankCandidates,
+ rustTestModuleOffset,
+ subjectNamesFor,
+ testNamesFor,
+} from "./testNaming";
describe("test naming conventions (Go to Test)", () => {
it.each([
@@ -31,9 +38,20 @@ describe("test naming conventions (Go to Test)", () => {
});
it("recognises test file names", () => {
- for (const n of ["FooTest.java", "TestFoo.java", "FooTests.cs", "foo_test.go", "test_foo.py", "foo.test.tsx", "foo.spec.js", "foo_spec.rb", "bar_test.cc"])
+ for (const n of [
+ "FooTest.java",
+ "TestFoo.java",
+ "FooTests.cs",
+ "foo_test.go",
+ "test_foo.py",
+ "foo.test.tsx",
+ "foo.spec.js",
+ "foo_spec.rb",
+ "bar_test.cc",
+ ])
expect(isTestName(n), n).toBe(true);
- for (const n of ["Foo.java", "Test.java", "Testing.java", "foo.go", "foo.py", "foo.ts", "contest.py", "latest.ts"]) expect(isTestName(n), n).toBe(false);
+ for (const n of ["Foo.java", "Test.java", "Testing.java", "foo.go", "foo.py", "foo.ts", "contest.py", "latest.ts"])
+ expect(isTestName(n), n).toBe(false);
expect(newTestName("Foo.java")).toBe("FooTest.java");
});
@@ -41,7 +59,11 @@ describe("test naming conventions (Go to Test)", () => {
const below = (p: string) => p.replace(/^\/p\/(?:a|b)\/src\/(?:main|test)\/java\//, "");
const ranked = rankCandidates(
"/p/a/src/main/java/com/x/Foo.java",
- ["/p/b/src/test/java/com/y/FooTest.java", "/p/a/src/test/java/com/z/FooTest.java", "/p/a/src/test/java/com/x/FooTest.java"],
+ [
+ "/p/b/src/test/java/com/y/FooTest.java",
+ "/p/a/src/test/java/com/z/FooTest.java",
+ "/p/a/src/test/java/com/x/FooTest.java",
+ ],
below,
);
expect(ranked).toEqual([
diff --git a/src/editor/navigation/testNaming.ts b/src/editor/navigation/testNaming.ts
index f33849ad9..3a80434de 100644
--- a/src/editor/navigation/testNaming.ts
+++ b/src/editor/navigation/testNaming.ts
@@ -29,7 +29,8 @@ export function isTestName(name: string): boolean {
if (ext === ".go") return stem.endsWith("_test");
if (ext === ".py") return stem.startsWith("test_") || stem.endsWith("_test") || stem === "conftest";
if (ext === ".rb") return stem.endsWith("_spec") || stem.endsWith("_test");
- if (JVM_EXT.test(name)) return /^Test[A-Z0-9_]/.test(stem) || (/Tests?$/.test(stem) && stem !== "Test" && stem !== "Tests");
+ if (JVM_EXT.test(name))
+ return /^Test[A-Z0-9_]/.test(stem) || (/Tests?$/.test(stem) && stem !== "Test" && stem !== "Tests");
if (C_EXT.test(name)) return stem.startsWith("test_") || stem.endsWith("_test") || stem.endsWith("_unittest");
return false;
}
@@ -42,7 +43,8 @@ export function testNamesFor(name: string): string[] {
if (ext === ".py") return [`test_${stem}.py`, `${stem}_test.py`];
if (ext === ".rb") return [`${stem}_spec.rb`, `${stem}_test.rb`];
if (ext === ".rs") return [`${stem}.rs`, `${stem}_test.rs`, `${stem}_tests.rs`];
- if (JVM_EXT.test(name)) return [`${stem}Test${ext}`, `${stem}Tests${ext}`, `Test${stem}${ext}`, `${stem}IT${ext}`, `${stem}Spec${ext}`];
+ if (JVM_EXT.test(name))
+ return [`${stem}Test${ext}`, `${stem}Tests${ext}`, `Test${stem}${ext}`, `${stem}IT${ext}`, `${stem}Spec${ext}`];
if (C_EXT.test(name)) return [`${stem}_test${ext}`, `test_${stem}${ext}`, `${stem}_unittest${ext}`];
return [`${stem}_test${ext}`, `test_${stem}${ext}`];
}
@@ -59,13 +61,15 @@ export function subjectNamesFor(name: string): string[] {
const out: string[] = [];
const strip = (s: string) => out.push(`${s}${ext}`);
if (ext === ".go" || ext === ".py" || ext === ".rb" || ext === ".rs" || C_EXT.test(name)) {
- for (const suffix of ["_test", "_tests", "_spec", "_unittest"]) if (stem.endsWith(suffix) && stem.length > suffix.length) strip(stem.slice(0, -suffix.length));
+ for (const suffix of ["_test", "_tests", "_spec", "_unittest"])
+ if (stem.endsWith(suffix) && stem.length > suffix.length) strip(stem.slice(0, -suffix.length));
if (stem.startsWith("test_") && stem.length > 5) strip(stem.slice(5));
// Rust integration tests (`tests/foo.rs`) are named like their subject.
if (ext === ".rs") strip(stem);
return [...new Set(out)];
}
- for (const suffix of ["Tests", "Test", "IT", "Spec"]) if (stem.endsWith(suffix) && stem.length > suffix.length) strip(stem.slice(0, -suffix.length));
+ for (const suffix of ["Tests", "Test", "IT", "Spec"])
+ if (stem.endsWith(suffix) && stem.length > suffix.length) strip(stem.slice(0, -suffix.length));
if (/^Test[A-Z0-9_]/.test(stem)) strip(stem.slice(4));
return [...new Set(out)];
}
@@ -83,7 +87,11 @@ function sharedPrefix(a: string, b: string): number {
* Orders candidate paths for `from`: the mirrored package (same path below
* its root) first, then the closest in the tree.
*/
-export function rankCandidates(from: string, candidates: readonly string[], relBelowRoot: (path: string) => string | null): string[] {
+export function rankCandidates(
+ from: string,
+ candidates: readonly string[],
+ relBelowRoot: (path: string) => string | null,
+): string[] {
const own = relBelowRoot(from);
const ownDir = own === null ? null : own.slice(0, Math.max(own.lastIndexOf("/"), 0));
const score = (p: string) => {
diff --git a/src/editor/refactor/catalog.ts b/src/editor/refactor/catalog.ts
index c23d785a8..2074331a0 100644
--- a/src/editor/refactor/catalog.ts
+++ b/src/editor/refactor/catalog.ts
@@ -33,7 +33,13 @@ const AT_NAME = "Caret should be positioned at the name of the element to be ref
/** IDEA's Refactor This order. */
export const REFACTORINGS: readonly Refactoring[] = [
- { id: "rename", action: "refactor.rename", label: "Rename…", kind: null, reason: () => "Caret should be on a symbol" },
+ {
+ id: "rename",
+ action: "refactor.rename",
+ label: "Rename…",
+ kind: null,
+ reason: () => "Caret should be on a symbol",
+ },
{
id: "changeSignature",
action: "refactor.changeSignature",
@@ -42,7 +48,13 @@ export const REFACTORINGS: readonly Refactoring[] = [
reason: () => "Caret should be positioned at the name of the function or method to be refactored",
},
{ id: "move", action: "refactor.move", label: "Move…", kind: "refactor.move", reason: () => AT_NAME },
- { id: "safeDelete", action: "refactor.safeDelete", label: "Safe Delete…", kind: null, reason: () => "Caret should be on a symbol" },
+ {
+ id: "safeDelete",
+ action: "refactor.safeDelete",
+ label: "Safe Delete…",
+ kind: null,
+ reason: () => "Caret should be on a symbol",
+ },
{
id: "extractMethod",
action: "refactor.extractMethod",
@@ -108,7 +120,12 @@ export function classifyAction(action: Pick<CodeAction, "kind" | "title">): Refa
if (kindIs(kind, "refactor.extract") || (generic && /^(extract|introduce)\b/i.test(title))) {
const sub = kind.slice("refactor.extract".length);
const is = (re: RegExp) => re.test(sub) || re.test(title);
- if (/^(extract|introduce)( (in)?to)?( an?)? (type\b|typedef|interface|struct|enum|trait|superclass|module)/i.test(title)) return null;
+ if (
+ /^(extract|introduce)( (in)?to)?( an?)? (type\b|typedef|interface|struct|enum|trait|superclass|module)/i.test(
+ title,
+ )
+ )
+ return null;
if (is(/function|method/i)) return "extractMethod";
if (is(/field|member|property/i)) return "extractField";
if (is(/parameter|argument/i)) return "extractParameter";
@@ -120,7 +137,8 @@ export function classifyAction(action: Pick<CodeAction, "kind" | "title">): Refa
}
if (kindIs(kind, "refactor.inline") || (generic && /^inline\b/i.test(title))) return "inline";
if (kindIs(kind, "refactor.move") || (generic && /^move\b/i.test(title))) return "move";
- if (/signature/i.test(kind) || /\bchange signature\b|\breorder (parameters|arguments)\b/i.test(title)) return "changeSignature";
+ if (/signature/i.test(kind) || /\bchange signature\b|\breorder (parameters|arguments)\b/i.test(title))
+ return "changeSignature";
return null;
}
diff --git a/src/editor/refactor/index.ts b/src/editor/refactor/index.ts
index 822c7952d..1d8fd77e6 100644
--- a/src/editor/refactor/index.ts
+++ b/src/editor/refactor/index.ts
@@ -5,4 +5,11 @@
*/
export { introduceFallback, type FallbackReason, type IntroduceKind } from "./introduce";
export { refactorThis, runRefactoring, showNothingHere } from "./refactorThis";
-export { askUsagesDetected, fileUsages, safeDelete, viewUsages, type FileUsages, type UsagesAnswer } from "./safeDelete";
+export {
+ askUsagesDetected,
+ fileUsages,
+ safeDelete,
+ viewUsages,
+ type FileUsages,
+ type UsagesAnswer,
+} from "./safeDelete";
diff --git a/src/editor/refactor/query.ts b/src/editor/refactor/query.ts
index acb3c4825..2eb980f45 100644
--- a/src/editor/refactor/query.ts
+++ b/src/editor/refactor/query.ts
@@ -26,7 +26,11 @@ export async function cancellable<T>(run: (request: number) => Promise<Result<T>
}
/** `refactor*` code actions for the selection, with the kinds the servers advertise. */
-export async function queryRefactorActions(view: EditorView, signal?: AbortSignal, only: string[] = ["refactor"]): Promise<CodeActionQuery> {
+export async function queryRefactorActions(
+ view: EditorView,
+ signal?: AbortSignal,
+ only: string[] = ["refactor"],
+): Promise<CodeActionQuery> {
const ctx = docOf(view);
if (!ctx) throw new IpcError({ kind: "unavailable", message: "No document" });
await whenSynced(view);
diff --git a/src/editor/refactor/refactorThis.test.ts b/src/editor/refactor/refactorThis.test.ts
index 7f02077c4..e3b624d19 100644
--- a/src/editor/refactor/refactorThis.test.ts
+++ b/src/editor/refactor/refactorThis.test.ts
@@ -9,7 +9,9 @@ const unavailable: Result = { status: "error", error: { kind: "unavailable", mes
let query: (request: number) => Promise<Result> = async () => ok({ actions: [], advertisedKinds: null });
let prepare: Result = ok(null);
-const lspCodeActionQuery = vi.fn(async (request: number, _doc: number, _range: unknown, _only: string[]) => query(request));
+const lspCodeActionQuery = vi.fn(async (request: number, _doc: number, _range: unknown, _only: string[]) =>
+ query(request),
+);
const lspPrepareRename = vi.fn(async () => prepare);
let onApply: (() => void) | null = null;
const lspApplyCodeAction = vi.fn(async () => {
@@ -25,7 +27,15 @@ vi.mock("@/platform/ipc", async (orig) => {
return {
...actual,
isTauri: () => true,
- commands: { ...actual.commands, lspCodeActionQuery, lspPrepareRename, lspApplyCodeAction, lspCodeActions, cancelRequest, languages },
+ commands: {
+ ...actual.commands,
+ lspCodeActionQuery,
+ lspPrepareRename,
+ lspApplyCodeAction,
+ lspCodeActions,
+ cancelRequest,
+ languages,
+ },
};
});
let expression = false;
@@ -33,7 +43,11 @@ let candidates: unknown[] = [];
vi.mock("@/editor/structure", () => ({
structure: {
support: vi.fn(async () => ({ tree: true, locals: false })),
- expressionAt: vi.fn(async () => ({ expression: expression ? { kind: "call_expression" } : null, exact: expression, candidates })),
+ expressionAt: vi.fn(async () => ({
+ expression: expression ? { kind: "call_expression" } : null,
+ exact: expression,
+ candidates,
+ })),
identifiers: vi.fn(async () => []),
},
}));
@@ -65,8 +79,10 @@ const action = (title: string, kind: string, disabledReason: string | null = nul
data: null,
server: 1,
});
-const answer = (actions: CodeAction[], advertisedKinds: string[] | null = null) => async () =>
- ok({ actions, advertisedKinds } satisfies CodeActionQuery);
+const answer =
+ (actions: CodeAction[], advertisedKinds: string[] | null = null) =>
+ async () =>
+ ok({ actions, advertisedKinds } satisfies CodeActionQuery);
let view: EditorView | null = null;
function editor(text = "fn main() { let total = price * 2; }") {
@@ -137,7 +153,9 @@ describe("catalog", () => {
});
it("formats IDEA's hint", () => {
- expect(cannotPerform("Caret should be on a symbol.")).toBe("Cannot perform refactoring. Caret should be on a symbol");
+ expect(cannotPerform("Caret should be on a symbol.")).toBe(
+ "Cannot perform refactoring. Caret should be on a symbol",
+ );
});
});
@@ -235,7 +253,10 @@ describe("Refactor menu actions", () => {
query = answer([], ["quickfix", "refactor.extract", "refactor.inline"]);
const v = editor();
await runRefactoring(v, "move");
- expect(showHint).toHaveBeenCalledWith(v, "Cannot perform refactoring. The language server for Rust doesn't support Move");
+ expect(showHint).toHaveBeenCalledWith(
+ v,
+ "Cannot perform refactoring. The language server for Rust doesn't support Move",
+ );
});
it("give IDEA's caret reason, the server's disabled reason, or the missing server", async () => {
@@ -270,7 +291,12 @@ describe("Refactor menu actions", () => {
const text = "fn main() { let total = price * 2; }";
const node = (t: string) => {
const from = text.indexOf(t);
- return { kind: "e", range: { start: { line: 0, col: from }, end: { line: 0, col: from + t.length } }, error: false, missing: false };
+ return {
+ kind: "e",
+ range: { start: { line: 0, col: from }, end: { line: 0, col: from + t.length } },
+ error: false,
+ missing: false,
+ };
};
candidates = [node("price"), node("price * 2")];
const v = editor(text);
diff --git a/src/editor/refactor/refactorThis.ts b/src/editor/refactor/refactorThis.ts
index 0e005fad5..b19ec601a 100644
--- a/src/editor/refactor/refactorThis.ts
+++ b/src/editor/refactor/refactorThis.ts
@@ -40,7 +40,10 @@ import {
import { safeDelete } from "./safeDelete";
/** Outcome of the server query: its answer, or why there is none. */
-export type ServerAnswer = { status: "ok"; query: CodeActionQuery } | { status: "notReady" } | { status: "error"; message: string };
+export type ServerAnswer =
+ | { status: "ok"; query: CodeActionQuery }
+ | { status: "notReady" }
+ | { status: "error"; message: string };
async function askServer(view: EditorView, signal?: AbortSignal, only?: string[]): Promise<ServerAnswer> {
try {
@@ -79,7 +82,8 @@ export function groupActions(actions: readonly CodeAction[]): {
*/
function runActions(view: EditorView, title: string, actions: readonly CodeAction[], id: RefactoringId | null = null) {
if (id && EXPRESSION_REFACTORINGS.has(id) && chooseOccurrences(view, actions, id)) return;
- const apply = (a: CodeAction) => (id && introducesName(id) ? applyIntroduceAction(view, a, id) : applyCodeAction(view, a));
+ const apply = (a: CodeAction) =>
+ id && introducesName(id) ? applyIntroduceAction(view, a, id) : applyCodeAction(view, a);
if (actions.length === 1) return apply(actions[0]!);
openPopup({
kind: "list",
@@ -113,7 +117,12 @@ function errorAround(view: EditorView): string | null {
}
/** IDEA's reason for `r` being unavailable, given the server's answer. */
-export async function unavailableReason(view: EditorView, r: Refactoring, answer: ServerAnswer, actions: readonly CodeAction[]): Promise<string> {
+export async function unavailableReason(
+ view: EditorView,
+ r: Refactoring,
+ answer: ServerAnswer,
+ actions: readonly CodeAction[],
+): Promise<string> {
const ctx = docOf(view);
const lang = await languageName(ctx?.language ?? "");
if (answer.status === "notReady") return `No language server for ${lang} is running`;
@@ -229,7 +238,13 @@ export function refactorThisItems(
items.push({ id: r.id, label: r.label, shortcut: shortcutLabel(r.action), run: () => void exec() });
}
other.forEach((a, i) =>
- items.push({ id: `server${i}`, label: a.title, icon: "bulb", emphasis: a.isPreferred, run: () => applyCodeAction(view, a) }),
+ items.push({
+ id: `server${i}`,
+ label: a.title,
+ icon: "bulb",
+ emphasis: a.isPreferred,
+ run: () => applyCodeAction(view, a),
+ }),
);
return items;
}
@@ -264,11 +279,19 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
showNothingHere(caretAnchor(view, state.selection.main.head));
return;
}
- openPopup({ kind: "list", anchor: caretAnchor(view, state.selection.main.head), title: "Refactor This", items, numbered: true });
+ openPopup({
+ kind: "list",
+ anchor: caretAnchor(view, state.selection.main.head),
+ title: "Refactor This",
+ items,
+ numbered: true,
+ });
}
/** IDEA's "Nothing here" popup: Refactor This where no refactoring applies (or outside an editor). */
-export function showNothingHere(anchor: { x: number; y: number } = { x: window.innerWidth / 2, y: window.innerHeight / 3 }) {
+export function showNothingHere(
+ anchor: { x: number; y: number } = { x: window.innerWidth / 2, y: window.innerHeight / 3 },
+) {
openPopup({
kind: "list",
anchor,
diff --git a/src/editor/refactor/safeDelete.test.ts b/src/editor/refactor/safeDelete.test.ts
index ae9951a27..c66ee85de 100644
--- a/src/editor/refactor/safeDelete.test.ts
+++ b/src/editor/refactor/safeDelete.test.ts
@@ -8,7 +8,9 @@ import type { LocalSymbol, Location, Locals, OutlineItem, Range, StructuralRange
// --- backend fakes ---------------------------------------------------------
type Answer<T> = () => { status: "ok"; data: T } | { status: "error"; error: { kind: string; message: string } };
-const ok = <T,>(data: T) => () => ({ status: "ok" as const, data });
+const ok =
+ <T>(data: T) =>
+ () => ({ status: "ok" as const, data });
const unavailable = () => ({ status: "error" as const, error: { kind: "unavailable", message: "no server" } });
let goto: Answer<Location[]> = ok([]);
@@ -65,7 +67,9 @@ vi.mock("@/platform/actions", () => ({ executeAction }));
let answer = "cancel";
const ask = vi.fn(async (_request: MessageRequest) => ({ button: answer, checked: false }));
let confirmAnswer: { checked: boolean } | null = { checked: false };
-const confirmChecked = vi.fn(async (_opts: { title: string; message: string; checkbox?: string; checked?: boolean }) => confirmAnswer);
+const confirmChecked = vi.fn(
+ async (_opts: { title: string; message: string; checkbox?: string; checked?: boolean }) => confirmAnswer,
+);
vi.mock("@/workbench/messages", () => ({ ask, confirmChecked }));
const { deletionRange, localDeclaration, outlineItemAt, safeDelete, fileUsages, usagesMessage, textOccurrences } =
@@ -178,26 +182,51 @@ describe("outlineItemAt", () => {
});
describe("localDeclaration", () => {
- const text = "fn f(p: i32) {\n let x = 1;\n let (a, b) = t;\n let m: HashMap<K, V> = m();\n for i in v {}\n}\n";
+ const text =
+ "fn f(p: i32) {\n let x = 1;\n let (a, b) = t;\n let m: HashMap<K, V> = m();\n for i in v {}\n}\n";
const sym = (name: string, kind: LocalSymbol["kind"] = "var", after = "{"): LocalSymbol => {
const at = text.indexOf(` ${name}`, text.indexOf(after)) + 1;
- return { name, kind, definition: rangeOf(text, at, at + name.length), scope: rangeOf(text, 0, text.length), references: [], certain: true, conflicts: [] };
+ return {
+ name,
+ kind,
+ definition: rangeOf(text, at, at + name.length),
+ scope: rangeOf(text, 0, text.length),
+ references: [],
+ certain: true,
+ conflicts: [],
+ };
};
const stmt = (kind: string, needle: string): SyntaxNode => {
const at = text.indexOf(needle);
- return { kind, range: rangeOf(text, at, at + needle.length), field: null, named: true, error: false, missing: false, hasError: false };
+ return {
+ kind,
+ range: rangeOf(text, at, at + needle.length),
+ field: null,
+ named: true,
+ error: false,
+ missing: false,
+ hasError: false,
+ };
};
it("returns the declaring statement of a single local", () => {
- expect(localDeclaration(doc(text), sym("x"), stmt("let_declaration", "let x = 1;"))).toEqual(stmt("let_declaration", "let x = 1;").range);
- expect(localDeclaration(doc(text), sym("m"), stmt("let_declaration", "let m: HashMap<K, V> = m();"))).not.toBeTypeOf("string");
+ expect(localDeclaration(doc(text), sym("x"), stmt("let_declaration", "let x = 1;"))).toEqual(
+ stmt("let_declaration", "let x = 1;").range,
+ );
+ expect(
+ localDeclaration(doc(text), sym("m"), stmt("let_declaration", "let m: HashMap<K, V> = m();")),
+ ).not.toBeTypeOf("string");
});
it("refuses parameters, destructuring, loop variables and ambiguous locals", () => {
expect(localDeclaration(doc(text), sym("p", "parameter", "f"), null)).toMatch(/Change Signature/);
expect(localDeclaration(doc(text), sym("b"), stmt("let_declaration", "let (a, b) = t;"))).toMatch(/other names/);
- expect(localDeclaration(doc(text), sym("i"), stmt("for_expression", "for i in v {}"))).toMatch(/separate statement/);
- expect(localDeclaration(doc(text), { ...sym("x"), certain: false }, stmt("let_declaration", "let x = 1;"))).toMatch(/more than once/);
+ expect(localDeclaration(doc(text), sym("i"), stmt("for_expression", "for i in v {}"))).toMatch(
+ /separate statement/,
+ );
+ expect(localDeclaration(doc(text), { ...sym("x"), certain: false }, stmt("let_declaration", "let x = 1;"))).toMatch(
+ /more than once/,
+ );
});
});
@@ -299,7 +328,10 @@ describe("safeDelete in the editor", () => {
const v = editor(text, "main");
goto = ok([{ path: "/p/other.rs", range: rangeOf(text, 0, 1) }]);
await safeDelete(v);
- expect(showHint).toHaveBeenCalledWith(v, "Cannot perform refactoring. 'main' is declared in other.rs; Safe Delete it there");
+ expect(showHint).toHaveBeenCalledWith(
+ v,
+ "Cannot perform refactoring. 'main' is declared in other.rs; Safe Delete it there",
+ );
expect(v.state.doc.toString()).toBe(text);
});
@@ -310,10 +342,26 @@ describe("safeDelete in the editor", () => {
const x = body.indexOf("x");
locals = {
status: "local",
- symbol: { name: "x", kind: "var", definition: rangeOf(body, x, x + 1), scope: rangeOf(body, 0, body.length), references: [], certain: true, conflicts: [] },
+ symbol: {
+ name: "x",
+ kind: "var",
+ definition: rangeOf(body, x, x + 1),
+ scope: rangeOf(body, 0, body.length),
+ references: [],
+ certain: true,
+ conflicts: [],
+ },
};
const at = body.indexOf("let x");
- statement = { kind: "let_declaration", range: rangeOf(body, at, at + 10), field: null, named: true, error: false, missing: false, hasError: false };
+ statement = {
+ kind: "let_declaration",
+ range: rangeOf(body, at, at + 10),
+ field: null,
+ named: true,
+ error: false,
+ missing: false,
+ hasError: false,
+ };
const v = editor(body, " x =");
v.dispatch({ selection: { anchor: x } });
await safeDelete(v);
@@ -347,7 +395,10 @@ describe("fileUsages", () => {
it("collects references to top-level symbols from other files", async () => {
outline = ok([item(text, "a", "pub fn a() {}"), item(text, "B", "pub struct B;", "struct")]);
- const r = (path: string, line: number): Location => ({ path, range: { start: { line, col: 0 }, end: { line, col: 1 } } });
+ const r = (path: string, line: number): Location => ({
+ path,
+ range: { start: { line, col: 0 }, end: { line, col: 1 } },
+ });
references = ok([r("/p/a.rs", 0), r("/p/main.rs", 4), r("/p/main.rs", 4), r("/p/gone.rs", 1)]);
const res = await fileUsages(["/p/a.rs", "/p/gone.rs"]);
expect(res).toEqual({ status: "ok", usages: [r("/p/main.rs", 4)] });
diff --git a/src/editor/refactor/safeDelete.ts b/src/editor/refactor/safeDelete.ts
index 95858b212..ce651d65a 100644
--- a/src/editor/refactor/safeDelete.ts
+++ b/src/editor/refactor/safeDelete.ts
@@ -253,7 +253,9 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
comparePos(range.start, target.range.end) > 0;
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
- const { locations: refs } = await lspRequest(() => commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true));
+ const { locations: refs } = await lspRequest(() =>
+ commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true),
+ );
return refs.filter((l) => outside(l.path, l.range));
}
@@ -396,7 +398,12 @@ function previewTextOccurrences(
) {
const occurrences: PreviewOccurrence[] = hits.map((h) => {
const line = doc.lineAt(h.from);
- return { line: line.number - 1, text: line.text, from: h.from - line.from, to: Math.min(h.to, line.to) - line.from };
+ return {
+ line: line.number - 1,
+ text: line.text,
+ from: h.from - line.from,
+ to: Math.min(h.to, line.to) - line.from,
+ };
});
openPopup({
kind: "preview",
@@ -527,7 +534,11 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
let refs: Location[];
try {
// Every symbol of every file: the server's own scope (a project search each would be too slow).
- refs = (await lspRequest(() => commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false))).locations;
+ refs = (
+ await lspRequest(() =>
+ commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false),
+ )
+ ).locations;
} catch (e) {
if (isUnavailable(e)) {
reason = errorText(e);
diff --git a/src/editor/refactor/serverIntroduce.ts b/src/editor/refactor/serverIntroduce.ts
index 17b1fd11c..a596995e5 100644
--- a/src/editor/refactor/serverIntroduce.ts
+++ b/src/editor/refactor/serverIntroduce.ts
@@ -171,7 +171,9 @@ function insertedTokens(before: Token[], after: Token[]): Token[] {
for (let i = n - 1; i >= 0; i--)
for (let j = m - 1; j >= 0; j--)
lcs[at(i, j)] =
- before[i]!.text === after[j]!.text ? lcs[at(i + 1, j + 1)]! + 1 : Math.max(lcs[at(i + 1, j)]!, lcs[at(i, j + 1)]!);
+ before[i]!.text === after[j]!.text
+ ? lcs[at(i + 1, j + 1)]! + 1
+ : Math.max(lcs[at(i + 1, j)]!, lcs[at(i, j + 1)]!);
const out: Token[] = [];
let i = 0;
let j = 0;
@@ -208,7 +210,10 @@ export function introducedName(before: string, after: string): { name: string; s
afterTo++;
beforeTo++;
}
- const inserted = insertedTokens(tokens(before.slice(start, beforeTo), start), tokens(after.slice(start, afterTo), start));
+ const inserted = insertedTokens(
+ tokens(before.slice(start, beforeTo), start),
+ tokens(after.slice(start, afterTo), start),
+ );
const byName = new Map<string, Span[]>();
for (const t of inserted) {
if (!WORD.test(t.text[0]!) || !isIdentifier(t.text) || isKeyword(t.text)) continue;
@@ -261,7 +266,8 @@ async function expressionInfo(view: EditorView): Promise<{ kind: string; text: s
}
async function docChange(view: EditorView, before: EditorView["state"]["doc"], ms = 1500): Promise<boolean> {
- for (let waited = 0; waited < ms && view.state.doc === before; waited += 20) await new Promise((r) => setTimeout(r, 20));
+ for (let waited = 0; waited < ms && view.state.doc === before; waited += 20)
+ await new Promise((r) => setTimeout(r, 20));
return view.state.doc !== before;
}
diff --git a/src/editor/structure/structure.test.ts b/src/editor/structure/structure.test.ts
index eed5168be..c41720876 100644
--- a/src/editor/structure/structure.test.ts
+++ b/src/editor/structure/structure.test.ts
@@ -6,7 +6,10 @@ const unavailable = () => new IpcError({ kind: "unavailable", message: "no serve
const protocol = () => new IpcError({ kind: "protocol", message: "boom" });
const cancelled = () => new IpcError({ kind: "cancelled", message: "cancelled" });
const fail = (e: Error) => () => Promise.reject(e);
-const ok = <T>(v: T) => () => Promise.resolve(v);
+const ok =
+ <T>(v: T) =>
+ () =>
+ Promise.resolve(v);
describe("withFallback", () => {
it("prefers the language server", async () => {
@@ -26,10 +29,12 @@ describe("withFallback", () => {
value: [],
source: "lsp",
});
- expect(await withFallback(ok({ items: [] }), ok({ items: [1] }), { isEmpty: (v) => v.items.length === 0 })).toEqual({
- value: { items: [1] },
- source: "syntax",
- });
+ expect(await withFallback(ok({ items: [] }), ok({ items: [1] }), { isEmpty: (v) => v.items.length === 0 })).toEqual(
+ {
+ value: { items: [1] },
+ source: "syntax",
+ },
+ );
});
it("never falls back on cancellation and keeps the server outcome when the fallback fails", async () => {
@@ -47,7 +52,10 @@ describe("withFallback", () => {
it("answers from the fallback when the server is slow", async () => {
const slowLsp = () => new Promise<number[]>((resolve) => setTimeout(() => resolve([1]), 200));
- expect(await withFallback(slowLsp, ok([2]), { when: ["slow"], slowMs: 10 })).toEqual({ value: [2], source: "syntax" });
+ expect(await withFallback(slowLsp, ok([2]), { when: ["slow"], slowMs: 10 })).toEqual({
+ value: [2],
+ source: "syntax",
+ });
// An empty fallback waits for the server.
expect(await withFallback(slowLsp, ok<number[]>([]), { when: ["slow"], slowMs: 10 })).toEqual({
value: [1],
diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx
index 04e2a5a5c..d93d078a1 100644
--- a/src/features/agents/AgentsView.tsx
+++ b/src/features/agents/AgentsView.tsx
@@ -58,7 +58,9 @@ export function AgentsView() {
roots={roots}
getKey={nodeKey}
getLabel={(n) => (n.kind === "group" ? n.group.label : n.task.title)}
- getChildren={(n) => (n.kind === "group" ? n.group.tasks.map((task) => ({ kind: "task", task }) as Node) : undefined)}
+ getChildren={(n) =>
+ n.kind === "group" ? n.group.tasks.map((task) => ({ kind: "task", task }) as Node) : undefined
+ }
isExpandable={(n) => n.kind === "group"}
expanded={expanded}
onExpandedChange={(_next, node, open) =>
diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsx
index ec6e14520..287759354 100644
--- a/src/features/agents/Composer.tsx
+++ b/src/features/agents/Composer.tsx
@@ -33,9 +33,7 @@ import { isImeKey } from "@/platform/ime";
const MAX_PROMPT_HEIGHT = 280;
const MAX_ITEMS = 12;
-type Item =
- | { kind: "file"; path: string; rel: string }
- | { kind: "command"; command: AgentCommand };
+type Item = { kind: "file"; path: string; rel: string } | { kind: "command"; command: AgentCommand };
export interface ComposerProps {
/** Store key of the draft. */
diff --git a/src/features/agents/HomeEditor.tsx b/src/features/agents/HomeEditor.tsx
index ab65f9cee..91df874d7 100644
--- a/src/features/agents/HomeEditor.tsx
+++ b/src/features/agents/HomeEditor.tsx
@@ -134,7 +134,10 @@ export function HomeEditor() {
)}
</div>
{(error || (provider && !provider.installed) || (provider && !provider.config.length)) && (
- <p className={error || !provider?.installed ? styles.warning : styles.note} role={error ? "alert" : undefined}>
+ <p
+ className={error || !provider?.installed ? styles.warning : styles.note}
+ role={error ? "alert" : undefined}
+ >
{error ??
(provider && !provider.installed ? (
txTemplate(`${provider.command} was not found on PATH`)
diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsx
index 2ebd07561..d67bc114b 100644
--- a/src/features/agents/SessionEditor.tsx
+++ b/src/features/agents/SessionEditor.tsx
@@ -502,7 +502,9 @@ function FindBar({
className={styles.findField}
trailing={
query.trim() ? (
- <span className={styles.findCount}>{ranges.length ? `${index + 1}/${ranges.length}` : tx("0 results")}</span>
+ <span className={styles.findCount}>
+ {ranges.length ? `${index + 1}/${ranges.length}` : tx("0 results")}
+ </span>
) : null
}
onKeyDown={(e) => {
@@ -516,8 +518,20 @@ function FindBar({
}
}}
/>
- <IconButton icon="arrow-up" title={tx("Previous Occurrence")} size="small" disabled={!ranges.length} onClick={() => step(-1)} />
- <IconButton icon="arrow-down" title={tx("Next Occurrence")} size="small" disabled={!ranges.length} onClick={() => step(1)} />
+ <IconButton
+ icon="arrow-up"
+ title={tx("Previous Occurrence")}
+ size="small"
+ disabled={!ranges.length}
+ onClick={() => step(-1)}
+ />
+ <IconButton
+ icon="arrow-down"
+ title={tx("Next Occurrence")}
+ size="small"
+ disabled={!ranges.length}
+ onClick={() => step(1)}
+ />
<IconButton icon="close" title={tx("Close")} size="small" onClick={close} />
</div>
);
@@ -567,7 +581,10 @@ function Entry({
</div>
{entry.items.map((item, i) => (
<div key={i} className={clsx(styles.planItem, item.status === "completed" && styles.planDone)}>
- <Icon name={item.status === "completed" ? "check" : item.status === "in_progress" ? "run" : "minus"} size={12} />
+ <Icon
+ name={item.status === "completed" ? "check" : item.status === "in_progress" ? "run" : "minus"}
+ size={12}
+ />
{item.content}
</div>
))}
@@ -605,7 +622,8 @@ function Entry({
function UserMessage({ task, entry }: { task: AgentTask; entry: UserEntry }) {
const tx = useTx();
- const fail = (e: unknown) => notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) });
+ const fail = (e: unknown) =>
+ notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) });
const archived = task.status === "archived";
return (
<div className={styles.message}>
@@ -714,7 +732,12 @@ function SubagentCard({ task, entry, onOpen }: { task: AgentTask; entry: Subagen
return (
<div className={styles.subagent}>
<div className={styles.subagentHead}>
- <button type="button" className={styles.subagentOpen} onClick={onOpen} title={tx("Open the subagent's conversation")}>
+ <button
+ type="button"
+ className={styles.subagentOpen}
+ onClick={onOpen}
+ title={tx("Open the subagent's conversation")}
+ >
<SubagentStatusIcon status={entry.status} />
<Icon name="toolwindow-agents" size={14} className={styles.muted} />
<span className={styles.subagentTitle}>{title}</span>
@@ -732,7 +755,12 @@ function SubagentCard({ task, entry, onOpen }: { task: AgentTask; entry: Subagen
<Icon name="chevron-right" size={12} className={styles.muted} />
</button>
{working && entry.cancellable && (
- <IconButton icon="stop" title="Stop Subagent" size="small" onClick={() => void cancelTask(task.id, entry.id)} />
+ <IconButton
+ icon="stop"
+ title="Stop Subagent"
+ size="small"
+ onClick={() => void cancelTask(task.id, entry.id)}
+ />
)}
</div>
{working && entry.activity && (
@@ -776,7 +804,13 @@ function WorkingSubagents({ entries, onOpen }: { entries: AgentEntry[] | null; o
return (
<div className={styles.subagentStrip} aria-label={tx("Subagents at work")}>
{working.map((e) => (
- <button key={e.id} type="button" className={styles.subagentChip} onClick={() => onOpen(e.id)} title={e.activity ?? undefined}>
+ <button
+ key={e.id}
+ type="button"
+ className={styles.subagentChip}
+ onClick={() => onOpen(e.id)}
+ title={e.activity ?? undefined}
+ >
<SubagentStatusIcon status={e.status} />
<span className={styles.subagentChipTitle}>{subagentTitle(e)}</span>
</button>
@@ -801,7 +835,9 @@ function PermissionLine({ task, entry }: { task: AgentTask; entry: Extract<Agent
/** The open permission request, as an editor notification banner above the conversation. */
function PermissionBanner({ task, entries }: { task: AgentTask; entries: AgentEntry[] | null }) {
const [busy, setBusy] = useState(false);
- const entry = entries?.find((e): e is Extract<AgentEntry, { type: "permission" }> => e.type === "permission" && !e.chosen);
+ const entry = entries?.find(
+ (e): e is Extract<AgentEntry, { type: "permission" }> => e.type === "permission" && !e.chosen,
+ );
if (!entry) return null;
const answer = (option: string | null) => {
setBusy(true);
@@ -846,7 +882,9 @@ function SessionComposer({
if (!canSend(composer) || sending || task.status === "archived") return;
setSending(true);
sendMessage(task.id, now)
- .catch((e: unknown) => notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) }))
+ .catch((e: unknown) =>
+ notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) }),
+ )
.finally(() => setSending(false));
};
const setOption = (id: string, value: string) =>
@@ -893,7 +931,8 @@ function SessionComposer({
/** Messages waiting for the turn to end: send now, edit, or drop. */
function Queue({ task }: { task: AgentTask }) {
- const fail = (e: unknown) => notifications().notify({ level: "error", title: "Couldn't update the queue", body: String(e) });
+ const fail = (e: unknown) =>
+ notifications().notify({ level: "error", title: "Couldn't update the queue", body: String(e) });
return (
<div className={styles.queue} aria-label={tx("Queued messages")}>
{task.queue.map((q) => (
@@ -902,11 +941,25 @@ function Queue({ task }: { task: AgentTask }) {
<span className={styles.queuedText} title={q.prompt.text}>
{q.prompt.text || <T>Image</T>}
</span>
- <button type="button" className={styles.bannerLink} onClick={() => void sendQueuedNow(task.id, q.id).catch(fail)}>
+ <button
+ type="button"
+ className={styles.bannerLink}
+ onClick={() => void sendQueuedNow(task.id, q.id).catch(fail)}
+ >
<T>Send now</T>
</button>
- <IconButton icon="edit" title="Edit" size="small" onClick={() => void editQueued(task.id, q.id).catch(fail)} />
- <IconButton icon="close" title="Remove" size="small" onClick={() => void removeQueued(task.id, q.id).catch(fail)} />
+ <IconButton
+ icon="edit"
+ title="Edit"
+ size="small"
+ onClick={() => void editQueued(task.id, q.id).catch(fail)}
+ />
+ <IconButton
+ icon="close"
+ title="Remove"
+ size="small"
+ onClick={() => void removeQueued(task.id, q.id).catch(fail)}
+ />
</div>
))}
</div>
diff --git a/src/features/agents/agents.test.ts b/src/features/agents/agents.test.ts
index 43bbeb121..cf06e212c 100644
--- a/src/features/agents/agents.test.ts
+++ b/src/features/agents/agents.test.ts
@@ -124,21 +124,18 @@ describe("agent composer", () => {
const config = [option("fast", ["on"], null), option("mode", ["ask", "code"], "code"), option("model", ["m"], "m")];
expect(mainOptions(config).map((o) => o.id)).toEqual(["model", "mode"]);
expect(nextValue(config[1]!)).toBe("ask");
- expect(["default", "acceptEdits", "plan", "auto", "bypassPermissions", "auto_edit", "read-only", "x"].map(modeIcon)).toEqual([
- "lock",
- "edit",
- "todo",
- "run",
- "unlock",
- "edit",
- "eye",
- "lock",
- ]);
+ expect(
+ ["default", "acceptEdits", "plan", "auto", "bypassPermissions", "auto_edit", "read-only", "x"].map(modeIcon),
+ ).toEqual(["lock", "edit", "todo", "run", "unlock", "edit", "eye", "lock"]);
expect(usageLabel({ used: 24_000, size: 200_000 })).toEqual({
short: "12%",
detail: "24k / 200k tokens",
});
- expect(imageFromDataUrl("data:image/png;base64,AAA", "a.png")).toEqual({ mimeType: "image/png", data: "AAA", name: "a.png" });
+ expect(imageFromDataUrl("data:image/png;base64,AAA", "a.png")).toEqual({
+ mimeType: "image/png",
+ data: "AAA",
+ name: "a.png",
+ });
expect(imageFromDataUrl("data:text/plain;base64,AAA")).toBeNull();
});
});
diff --git a/src/features/agents/composerModel.ts b/src/features/agents/composerModel.ts
index 17468b8d4..86d14cc92 100644
--- a/src/features/agents/composerModel.ts
+++ b/src/features/agents/composerModel.ts
@@ -28,7 +28,8 @@ export function completionAt(text: string, caret: number): Completion | null {
if (!word) return null;
const from = caret - word[3]!.length - 1;
// Commands only as the message's first word.
- if (word[2] === "/") return before.slice(0, from).trim() === "" ? { kind: "command", query: word[3]!, from, to: caret } : null;
+ if (word[2] === "/")
+ return before.slice(0, from).trim() === "" ? { kind: "command", query: word[3]!, from, to: caret } : null;
return { kind: "file", query: word[3]!, from, to: caret };
}
@@ -75,7 +76,8 @@ export function mentionOf(rel: string, lines?: { from: number; to: number }): st
export function toPrompt(draft: ComposerDraft): AgentPrompt {
const seen = new Set<string>();
const files = draft.files.filter((f) => {
- if (seen.has(f.path) || !new RegExp(`@${escapeRe(f.rel)}(?![\\w./-])|@${escapeRe(f.rel)}:`).test(draft.text)) return false;
+ if (seen.has(f.path) || !new RegExp(`@${escapeRe(f.rel)}(?![\\w./-])|@${escapeRe(f.rel)}:`).test(draft.text))
+ return false;
seen.add(f.path);
return true;
});
diff --git a/src/features/agents/conversation.test.ts b/src/features/agents/conversation.test.ts
index 78d1d1e6b..36d0c8547 100644
--- a/src/features/agents/conversation.test.ts
+++ b/src/features/agents/conversation.test.ts
@@ -21,7 +21,17 @@ describe("pathLink", () => {
expect(pathLink("/abs/x.py#L7", cwd)).toEqual({ path: "/abs/x.py", line: 6 });
});
it("ignores code that isn't a path", () => {
- for (const t of ["foo()", "cargo test", "https://x.dev/a.md", "inventory", "1.5", "v2.0", "a.b()", "failing-tests", "tests/"]) {
+ for (const t of [
+ "foo()",
+ "cargo test",
+ "https://x.dev/a.md",
+ "inventory",
+ "1.5",
+ "v2.0",
+ "a.b()",
+ "failing-tests",
+ "tests/",
+ ]) {
expect(pathLink(t, cwd)).toBeNull();
}
});
diff --git a/src/features/agents/model.ts b/src/features/agents/model.ts
index d9504352f..a4d66f0db 100644
--- a/src/features/agents/model.ts
+++ b/src/features/agents/model.ts
@@ -37,7 +37,20 @@ export function subagentStatusLabel(s: AgentSubagentStatus): string {
}
}
-const PROVIDER_ICONS = new Set(["claude", "codex", "gemini", "copilot", "cursor", "opencode", "qwen", "kimi", "goose", "auggie", "kiro", "vibe"]);
+const PROVIDER_ICONS = new Set([
+ "claude",
+ "codex",
+ "gemini",
+ "copilot",
+ "cursor",
+ "opencode",
+ "qwen",
+ "kimi",
+ "goose",
+ "auggie",
+ "kiro",
+ "vibe",
+]);
/** The agent's logo; custom agents get the generic agents icon. */
export const providerIcon = (provider: string) =>
@@ -109,7 +122,10 @@ export function age(ms: number, now = Date.now()): string {
}
/** The status change worth a notification, if any. */
-export function attentionChange(prev: AgentStatus | undefined, next: AgentStatus): "finished" | "failed" | "input" | null {
+export function attentionChange(
+ prev: AgentStatus | undefined,
+ next: AgentStatus,
+): "finished" | "failed" | "input" | null {
if (prev === next || prev === undefined) return null;
if (next === "needsInput") return "input";
if (!isBusy(prev)) return null;
diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts
index a3bc43a31..a5e8431ff 100644
--- a/src/features/agents/store.ts
+++ b/src/features/agents/store.ts
@@ -15,7 +15,16 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { editorService, notifications } from "@/workbench/contributions";
import { canSend, emptyDraft, toPrompt, type ComposerDraft, type FileRef } from "./composerModel";
import { withQuote } from "./conversation";
-import { HOME_KEY, HOME_KIND, SESSION_KIND, attentionChange, entriesKey, isBusy, sessionKey, upsertEntry } from "./model";
+import {
+ HOME_KEY,
+ HOME_KIND,
+ SESSION_KIND,
+ attentionChange,
+ entriesKey,
+ isBusy,
+ sessionKey,
+ upsertEntry,
+} from "./model";
/** New Task page settings (its text lives in the `HOME` composer). */
export interface Draft {
@@ -138,7 +147,8 @@ export async function connect(): Promise<void> {
const editors = editorService();
for (const t of editors.openTabs?.() ?? []) {
const task = (t.input.data as { task?: string } | undefined)?.task;
- if (t.input.kind === SESSION_KIND && task && !useAgents.getState().tasks.has(task)) editors.closeInput?.(t.input.key);
+ if (t.input.kind === SESSION_KIND && task && !useAgents.getState().tasks.has(task))
+ editors.closeInput?.(t.input.key);
}
}
@@ -189,7 +199,11 @@ function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
if (!change) return;
if (visible.has(task.id) && document.hasFocus()) return;
const body =
- change === "input" ? "Waiting for your answer" : change === "failed" ? (task.error ?? "The agent stopped") : "Finished";
+ change === "input"
+ ? "Waiting for your answer"
+ : change === "failed"
+ ? (task.error ?? "The agent stopped")
+ : "Finished";
notifications().notify({
level: change === "failed" ? "error" : "info",
title: task.title,
@@ -369,7 +383,8 @@ export function addReferences(refs: Array<{ path: string; rel: string; mention:
const root = task?.isolation === "worktree" ? task.cwd : null;
const files: FileRef[] = refs.map((r) => ({ path: root ? `${root}/${r.rel}` : r.path, rel: r.rel }));
const mentions = refs.map((r) => r.mention).join(" ");
- const text = current.text && !/\s$/.test(current.text) ? `${current.text} ${mentions} ` : `${current.text}${mentions} `;
+ const text =
+ current.text && !/\s$/.test(current.text) ? `${current.text} ${mentions} ` : `${current.text}${mentions} `;
updateComposer(key, { text, files: [...current.files, ...files] });
if (task) openTask(task.id);
else openHome();
diff --git a/src/features/analysis/analysis.test.ts b/src/features/analysis/analysis.test.ts
index 76320027f..23b145392 100644
--- a/src/features/analysis/analysis.test.ts
+++ b/src/features/analysis/analysis.test.ts
@@ -71,7 +71,10 @@ describe("Inspect Code grouping", () => {
});
it("groups by inspection by default, worst severity first, merging severities", () => {
- const withWarning = [...files, { path: "/p/d.ts", relPath: "d.ts", diagnostics: [diag(5, "warning", "ts", "2304")] }];
+ const withWarning = [
+ ...files,
+ { path: "/p/d.ts", relPath: "d.ts", diagnostics: [diag(5, "warning", "ts", "2304")] },
+ ];
const nodes = buildInspectionNodes(groupInspection(withWarning), false);
expect(nodes.map((n) => (n.kind === "inspection" ? [n.name, n.severity, n.count] : n.kind))).toEqual([
["ts(2304)", "error", 4],
diff --git a/src/features/analysis/cleanup.ts b/src/features/analysis/cleanup.ts
index 2910023cf..f1b971cf7 100644
--- a/src/features/analysis/cleanup.ts
+++ b/src/features/analysis/cleanup.ts
@@ -93,7 +93,13 @@ export async function runCodeCleanup(choice: ScopeChoice, options: CleanupOption
if (!isTauri() || running) return;
const files = await cleanupFiles(choice);
if (typeof files === "string") {
- notifications().notify({ group: "analysis", level: "warning", title: "Code Cleanup", body: files, key: "code.cleanup" });
+ notifications().notify({
+ group: "analysis",
+ level: "warning",
+ title: "Code Cleanup",
+ body: files,
+ key: "code.cleanup",
+ });
return;
}
if (
@@ -131,7 +137,9 @@ export async function runCodeCleanup(choice: ScopeChoice, options: CleanupOption
notifications().notify({
group: "analysis",
level: "info",
- title: run.cancelled ? `Code Cleanup cancelled after ${done} of ${files.length} files` : `Code Cleanup processed ${done} files`,
+ title: run.cancelled
+ ? `Code Cleanup cancelled after ${done} of ${files.length} files`
+ : `Code Cleanup processed ${done} files`,
key: "code.cleanup",
});
}
diff --git a/src/features/app/NewProject.tsx b/src/features/app/NewProject.tsx
index 09035805f..154905f15 100644
--- a/src/features/app/NewProject.tsx
+++ b/src/features/app/NewProject.tsx
@@ -24,7 +24,8 @@ export function NewProjectOverlay() {
export function projectNameError(name: string): string | null {
const n = name.trim();
if (!n) return "Enter a project name";
- if (/[/\\:*?"<>|]/.test(n) || n === "." || n === "..") return "The name contains characters a folder name cannot have";
+ if (/[/\\:*?"<>|]/.test(n) || n === "." || n === "..")
+ return "The name contains characters a folder name cannot have";
return null;
}
@@ -82,7 +83,12 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const browse = async () => {
if (!isTauri()) return;
const { open } = await import("@tauri-apps/plugin-dialog");
- const picked = await open({ directory: true, multiple: false, title: "Project Location", defaultPath: location || undefined });
+ const picked = await open({
+ directory: true,
+ multiple: false,
+ title: "Project Location",
+ defaultPath: location || undefined,
+ });
const dir = Array.isArray(picked) ? picked[0] : picked;
if (dir) setLocation(dir);
};
@@ -124,7 +130,13 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
<span className={styles.newProjectLabel}>
<T>Name:</T>
</span>
- <Input data-autofocus value={name} invalid={!!nameError} onChange={(e) => setName(e.target.value)} aria-label="Name" />
+ <Input
+ data-autofocus
+ value={name}
+ invalid={!!nameError}
+ onChange={(e) => setName(e.target.value)}
+ aria-label="Name"
+ />
</label>
<div className={styles.newProjectRow}>
<span className={styles.newProjectLabel}>
diff --git a/src/features/app/__tests__/invalidateCaches.test.tsx b/src/features/app/__tests__/invalidateCaches.test.tsx
index 0bf2b8826..c9b999ce1 100644
--- a/src/features/app/__tests__/invalidateCaches.test.tsx
+++ b/src/features/app/__tests__/invalidateCaches.test.tsx
@@ -31,7 +31,9 @@ describe("Invalidate Caches", () => {
render(<InvalidateCachesOverlay />);
await executeAction("file.invalidateCaches");
const dialog = await screen.findByRole("dialog", { name: "Invalidate Caches" });
- const buttons = within(dialog).getAllByRole("button").map((b) => b.textContent);
+ const buttons = within(dialog)
+ .getAllByRole("button")
+ .map((b) => b.textContent);
expect(buttons).toEqual(expect.arrayContaining(["Invalidate and Restart", "Just Restart", "Cancel"]));
fireEvent.click(within(dialog).getByRole("checkbox", { name: "Clear file system cache and Local History" }));
expect(dialog).toHaveTextContent("Local History of all projects will be deleted.");
diff --git a/src/features/app/__tests__/newProject.test.ts b/src/features/app/__tests__/newProject.test.ts
index abbeb6adc..efedeabc9 100644
--- a/src/features/app/__tests__/newProject.test.ts
+++ b/src/features/app/__tests__/newProject.test.ts
@@ -26,7 +26,11 @@ describe("Manage IDE Settings › Export Settings…", () => {
"openidea.runAnything.history.v1:/p": "[]",
};
const keys = Object.keys(data);
- const storage = { length: keys.length, key: (i: number) => keys[i] ?? null, getItem: (k: string) => data[k] ?? null };
+ const storage = {
+ length: keys.length,
+ key: (i: number) => keys[i] ?? null,
+ getItem: (k: string) => data[k] ?? null,
+ };
expect(Object.keys(exportedStorage(storage)).sort()).toEqual([
"openidea.liveTemplates.v1",
"openidea.macros.v1",
diff --git a/src/features/app/__tests__/shell.test.tsx b/src/features/app/__tests__/shell.test.tsx
index 990d2966b..f1c217439 100644
--- a/src/features/app/__tests__/shell.test.tsx
+++ b/src/features/app/__tests__/shell.test.tsx
@@ -134,7 +134,11 @@ describe("prompt", () => {
});
const dialog = await screen.findByRole("dialog");
const footer = dialog.querySelector("[data-dialog-footer]") as HTMLElement;
- expect([...footer.querySelectorAll("button")].map((b) => b.textContent)).toEqual(["Cancel", "This Window", "New Window"]);
+ expect([...footer.querySelectorAll("button")].map((b) => b.textContent)).toEqual([
+ "Cancel",
+ "This Window",
+ "New Window",
+ ]);
await userEvent.setup().keyboard("{Enter}");
await expect(result).resolves.toMatchObject({ button: "new" });
usePlatform.setState({ os });
diff --git a/src/features/app/projectActions.ts b/src/features/app/projectActions.ts
index 288faa7b2..0ede70e04 100644
--- a/src/features/app/projectActions.ts
+++ b/src/features/app/projectActions.ts
@@ -21,7 +21,9 @@ export const EXPORTED_STORAGE = [
"openidea.toolWindowLayouts.",
];
-export function exportedStorage(storage: Pick<Storage, "length" | "key" | "getItem"> = localStorage): Record<string, string> {
+export function exportedStorage(
+ storage: Pick<Storage, "length" | "key" | "getItem"> = localStorage,
+): Record<string, string> {
const out: Record<string, string> = {};
for (let i = 0; i < storage.length; i++) {
const key = storage.key(i);
@@ -48,7 +50,12 @@ async function exportSettings() {
await call(commands.settingsExport(path, exportedStorage()));
notifications().notify({ level: "info", title: "Settings exported", body: path, key: "app.settingsExport" });
} catch (e) {
- notifications().notify({ level: "error", title: "Cannot export settings", body: errorText(e), key: "app.settingsExport" });
+ notifications().notify({
+ level: "error",
+ title: "Cannot export settings",
+ body: errorText(e),
+ key: "app.settingsExport",
+ });
}
}
@@ -80,7 +87,12 @@ async function importSettings() {
actions: [{ label: "Restart", run: () => void executeAction("app.restart") }],
});
} catch (e) {
- notifications().notify({ level: "error", title: "Cannot import settings", body: errorText(e), key: "app.settingsImport" });
+ notifications().notify({
+ level: "error",
+ title: "Cannot import settings",
+ body: errorText(e),
+ key: "app.settingsImport",
+ });
}
}
diff --git a/src/features/app/title.ts b/src/features/app/title.ts
index 288342954..1a178ff94 100644
--- a/src/features/app/title.ts
+++ b/src/features/app/title.ts
@@ -7,7 +7,11 @@ import { t, useI18n } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { basename, useProject } from "@/platform/project";
-export function windowTitle(project: string | null | undefined, file: string | null | undefined, fullPath = false): string {
+export function windowTitle(
+ project: string | null | undefined,
+ file: string | null | undefined,
+ fullPath = false,
+): string {
const name = file ? (fullPath ? file : basename(file)) : null;
if (!project) return name ?? t("app.title.default");
return name ? `${project} – ${name}` : project;
diff --git a/src/features/build-tools/actions.test.tsx b/src/features/build-tools/actions.test.tsx
index bb8ac6019..b6e896db1 100644
--- a/src/features/build-tools/actions.test.tsx
+++ b/src/features/build-tools/actions.test.tsx
@@ -69,7 +69,11 @@ describe("build tools feature", () => {
it("offers its actions in Search Everywhere only for Maven projects and toggles run options", async () => {
const visible = () => allActions().filter((a) => !a.hidden && a.id.startsWith("maven."));
- expect(visible().map((a) => a.id).sort()).toEqual([
+ expect(
+ visible()
+ .map((a) => a.id)
+ .sort(),
+ ).toEqual([
"maven.analyzeDependencies",
"maven.executeGoal",
"maven.reload",
@@ -85,7 +89,11 @@ describe("build tools feature", () => {
await executeAction("maven.toggleOffline");
expect(useBuild.getState().settings.maven).toMatchObject({ offline: true, skipTests: true });
expect(JSON.parse(localStorage.getItem("openidea.buildTools:/p")!).maven.skipTests).toBe(true);
- expect(allActions().find((a) => a.id === "maven.toggleOffline")!.toggled?.()).toBe(true);
+ expect(
+ allActions()
+ .find((a) => a.id === "maven.toggleOffline")!
+ .toggled?.(),
+ ).toBe(true);
await executeAction("maven.executeGoal");
expect(useBuild.getState().executeOpen).toBe("maven");
@@ -93,8 +101,19 @@ describe("build tools feature", () => {
it("runs a lifecycle phase through the run feature with the toolbar options", async () => {
const started: unknown[] = [];
- const off = registerAction({ id: "run.runConfig", title: "Run", hidden: true, run: ({ arg }) => void started.push(arg) });
- act(() => useBuild.setState({ root: "/p", model: mavenModel, expanded: { maven: new Set(["mvn:pom.xml", "mvn:pom.xml:lifecycle"]), gradle: new Set() } }));
+ const off = registerAction({
+ id: "run.runConfig",
+ title: "Run",
+ hidden: true,
+ run: ({ arg }) => void started.push(arg),
+ });
+ act(() =>
+ useBuild.setState({
+ root: "/p",
+ model: mavenModel,
+ expanded: { maven: new Set(["mvn:pom.xml", "mvn:pom.xml:lifecycle"]), gradle: new Set() },
+ }),
+ );
await executeAction("maven.toggleSkipTests");
render(<MavenView />);
expect(screen.getByText("Build files changed since the last reload")).toBeTruthy();
@@ -106,6 +125,11 @@ describe("build tools feature", () => {
expect(started).toHaveLength(1);
const { config, temporary } = started[0] as { config: RunConfig; temporary: boolean };
expect(temporary).toBe(true);
- expect(config).toMatchObject({ name: "spring-demo [package]", command: "/p/mvnw", args: ["package", "-DskipTests"], kind: "maven" });
+ expect(config).toMatchObject({
+ name: "spring-demo [package]",
+ command: "/p/mvnw",
+ args: ["package", "-DskipTests"],
+ kind: "maven",
+ });
});
});
diff --git a/src/features/build-tools/index.ts b/src/features/build-tools/index.ts
index f70182fdd..cb6ad7631 100644
--- a/src/features/build-tools/index.ts
+++ b/src/features/build-tools/index.ts
@@ -43,10 +43,16 @@ function expandAll(tool: BuildTool) {
const { model, configs } = useBuild.getState();
if (tool === "maven" && model?.maven) {
const m = model.maven;
- setExpanded(tool, expandableKeys(mavenRoots(m), (n) => mavenChildren(n, m, configs)));
+ setExpanded(
+ tool,
+ expandableKeys(mavenRoots(m), (n) => mavenChildren(n, m, configs)),
+ );
} else if (tool === "gradle" && model?.gradle) {
const g = model.gradle;
- setExpanded(tool, expandableKeys(gradleRoots(g), (n) => gradleChildren(n, g, configs)));
+ setExpanded(
+ tool,
+ expandableKeys(gradleRoots(g), (n) => gradleChildren(n, g, configs)),
+ );
}
}
@@ -78,8 +84,22 @@ function apply(model: BuildModel | null, registered: Partial<Record<BuildTool, (
if (has[tool] && !registered[tool]) {
registered[tool] =
tool === "maven"
- ? registerToolWindow({ id: "maven", title: "Maven", icon: "toolwindow-maven", anchor: "right", order: 10, component: MavenView })
- : registerToolWindow({ id: "gradle", title: "Gradle", icon: "toolwindow-gradle", anchor: "right", order: 11, component: GradleView });
+ ? registerToolWindow({
+ id: "maven",
+ title: "Maven",
+ icon: "toolwindow-maven",
+ anchor: "right",
+ order: 10,
+ component: MavenView,
+ })
+ : registerToolWindow({
+ id: "gradle",
+ title: "Gradle",
+ icon: "toolwindow-gradle",
+ anchor: "right",
+ order: 11,
+ component: GradleView,
+ });
} else if (!has[tool] && registered[tool]) {
registered[tool]!();
delete registered[tool];
diff --git a/src/features/build-tools/model.test.ts b/src/features/build-tools/model.test.ts
index 0d3f00e78..07fedfb82 100644
--- a/src/features/build-tools/model.test.ts
+++ b/src/features/build-tools/model.test.ts
@@ -86,7 +86,14 @@ const maven: MavenModel = {
},
],
}),
- project({ pom: "app/pom.xml", dir: "app", artifactId: "app", displayName: "Demo App", packaging: "jar", aggregated: true }),
+ project({
+ pom: "app/pom.xml",
+ dir: "app",
+ artifactId: "app",
+ displayName: "Demo App",
+ packaging: "jar",
+ aggregated: true,
+ }),
],
profiles: [
{ id: "dev", activeByDefault: true },
@@ -121,7 +128,17 @@ describe("Maven tree", () => {
expect(labels(children(roots[0]!))).toEqual(["dev", "ci"]);
const top = children(roots[1]!);
expect(labels(top)).toEqual(["Lifecycle", "Plugins", "core", "Demo App"]);
- expect(labels(children(top[0]!))).toEqual(["clean", "validate", "compile", "test", "package", "verify", "install", "site", "deploy"]);
+ expect(labels(children(top[0]!))).toEqual([
+ "clean",
+ "validate",
+ "compile",
+ "test",
+ "package",
+ "verify",
+ "install",
+ "site",
+ "deploy",
+ ]);
expect(nodeIcon(top[2]!)).toBe("maven-module");
expect(nodeIcon(roots[1]!)).toBe("maven-project");
});
@@ -168,7 +185,11 @@ describe("Maven runs", () => {
it("passes goals, offline, skip tests and changed profiles", () => {
expect(profilesArg(maven.profiles, {})).toBeNull();
expect(profilesArg(maven.profiles, { ci: true, dev: false })).toBe("!dev,ci");
- const config = mavenGoalConfig(core, ["clean", "test"], maven, { offline: true, skipTests: false, profiles: { ci: true } });
+ const config = mavenGoalConfig(core, ["clean", "test"], maven, {
+ offline: true,
+ skipTests: false,
+ profiles: { ci: true },
+ });
expect(config).toMatchObject({
name: "core [clean,test]",
kind: "maven",
@@ -182,20 +203,24 @@ describe("Maven runs", () => {
const skipped = mavenGoalConfig(core, ["test"], maven, { offline: false, skipTests: true, profiles: {} });
expect(skipped.args).toEqual(["test", "-DskipTests"]);
expect(skipped.isTest).toBe(false);
- const root = mavenGoalConfig(maven.projects[0]!, ["clean"], maven, { offline: false, skipTests: false, profiles: {} });
+ const root = mavenGoalConfig(maven.projects[0]!, ["clean"], maven, {
+ offline: false,
+ skipTests: false,
+ profiles: {},
+ });
expect(root.cwd).toBeNull();
expect(root.isTest).toBe(false);
// Settings › Maven options go before the goals.
const configured = { ...core, options: ["-s", "/m2/settings.xml"] };
- expect(mavenGoalConfig(configured, ["test"], maven, { offline: false, skipTests: true, profiles: {} }).args).toEqual(
- ["-s", "/m2/settings.xml", "test", "-DskipTests"],
- );
+ expect(
+ mavenGoalConfig(configured, ["test"], maven, { offline: false, skipTests: true, profiles: {} }).args,
+ ).toEqual(["-s", "/m2/settings.xml", "test", "-DskipTests"]);
});
it("parses typed command lines", () => {
expect(parseGoalLine("mvn clean install -Dmsg='a b'")).toEqual(["clean", "install", "-Dmsg=a b"]);
expect(parseGoalLine("./mvnw -q verify")).toEqual(["-q", "verify"]);
- expect(parseTaskLine("./gradlew :app:run --args \"x y\"")).toEqual([":app:run", "--args", "x y"]);
+ expect(parseTaskLine('./gradlew :app:run --args "x y"')).toEqual([":app:run", "--args", "x y"]);
expect(splitArgs(`a "" 'b c'`)).toEqual(["a", "", "b c"]);
});
@@ -244,7 +269,8 @@ describe("Gradle tree and runs", () => {
stale: false,
syncError: null,
};
- const kids = (n: BuildNode) => gradleChildren(n, gradle, [runConfig({ id: "g", name: "app [run]", kind: "gradle" })]) ?? [];
+ const kids = (n: BuildNode) =>
+ gradleChildren(n, gradle, [runConfig({ id: "g", name: "app [run]", kind: "gradle" })]) ?? [];
it("nests subprojects and groups tasks, other last", () => {
const roots = gradleRoots(gradle);
@@ -260,9 +286,19 @@ describe("Gradle tree and runs", () => {
it("runs tasks by path from the build directory", () => {
const app = gradle.projects[1]!;
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true });
- expect(config).toMatchObject({ name: "app [test]", kind: "gradle", command: "/p/gradlew", args: [":app:test", "--offline"], cwd: null, isTest: true });
+ expect(config).toMatchObject({
+ name: "app [test]",
+ kind: "gradle",
+ command: "/p/gradlew",
+ args: [":app:test", "--offline"],
+ cwd: null,
+ isTest: true,
+ });
expect(gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false }).args).toEqual(["wrapper"]);
- expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false }).args).toEqual([":lib:jar", "--info"]);
+ expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false }).args).toEqual([
+ ":lib:jar",
+ "--info",
+ ]);
});
it("completes task names and paths", () => {
diff --git a/src/features/build-tools/model.ts b/src/features/build-tools/model.ts
index 036dd86f4..51957d283 100644
--- a/src/features/build-tools/model.ts
+++ b/src/features/build-tools/model.ts
@@ -139,10 +139,17 @@ export function gradleRunConfigs(configs: readonly RunConfig[]): RunConfig[] {
}
function normalizeDir(cwd: string | null | undefined): string {
- return (cwd ?? "").replace(/\\/g, "/").replace(/^\.\/?/, "").replace(/\/+$/, "");
+ return (cwd ?? "")
+ .replace(/\\/g, "/")
+ .replace(/^\.\/?/, "")
+ .replace(/\/+$/, "");
}
-export function mavenChildren(node: BuildNode, model: MavenModel, configs: readonly RunConfig[]): BuildNode[] | undefined {
+export function mavenChildren(
+ node: BuildNode,
+ model: MavenModel,
+ configs: readonly RunConfig[],
+): BuildNode[] | undefined {
switch (node.kind) {
case "profiles":
return model.profiles.map((profile) => ({ kind: "profile", key: `mvn:profile:${profile.id}`, profile }));
@@ -153,7 +160,8 @@ export function mavenChildren(node: BuildNode, model: MavenModel, configs: reado
{ kind: "lifecycle", key: `${k}:lifecycle`, project: p },
{ kind: "plugins", key: `${k}:plugins`, project: p },
];
- if (p.dependencies.length) out.push({ kind: "dependencies", key: `${k}:deps`, project: p, dependencies: p.dependencies });
+ if (p.dependencies.length)
+ out.push({ kind: "dependencies", key: `${k}:deps`, project: p, dependencies: p.dependencies });
const runs = mavenRunConfigs(p, configs);
if (runs.length) out.push({ kind: "runConfigs", key: `${k}:runs`, configs: runs });
for (const pom of p.modules) {
@@ -196,7 +204,13 @@ export function mavenChildren(node: BuildNode, model: MavenModel, configs: reado
function dependencyNodes(parent: string, deps: readonly MavenDependency[]): BuildNode[] {
return deps.flatMap((dependency, i) =>
dependency.omitted == null
- ? [{ kind: "dependency" as const, key: `${parent}/${dependency.groupId}:${dependency.artifactId}:${i}`, dependency }]
+ ? [
+ {
+ kind: "dependency" as const,
+ key: `${parent}/${dependency.groupId}:${dependency.artifactId}:${i}`,
+ dependency,
+ },
+ ]
: [],
);
}
@@ -232,7 +246,11 @@ export function gradleSubprojects(model: GradleModel, path: string): GradleProje
});
}
-export function gradleChildren(node: BuildNode, model: GradleModel, configs: readonly RunConfig[]): BuildNode[] | undefined {
+export function gradleChildren(
+ node: BuildNode,
+ model: GradleModel,
+ configs: readonly RunConfig[],
+): BuildNode[] | undefined {
switch (node.kind) {
case "gradleProject": {
const p = node.project;
@@ -383,7 +401,11 @@ export function parseTaskLine(line: string): string[] {
return args;
}
-export function mavenArgs(goals: readonly string[], model: Pick<MavenModel, "profiles">, options: MavenRunOptions): string[] {
+export function mavenArgs(
+ goals: readonly string[],
+ model: Pick<MavenModel, "profiles">,
+ options: MavenRunOptions,
+): string[] {
const args = [...goals];
const has = (flag: string) => args.some((a) => a === flag || a.startsWith(`${flag}=`));
if (options.offline && !has("-o") && !has("--offline")) args.push("-o");
@@ -465,7 +487,11 @@ export interface Completion {
}
/** Completes the last word of `line` with phases and `prefix:goal`s of `plugins`. */
-export function goalCompletions(line: string, plugins: readonly MavenPlugin[], history: readonly string[] = []): Completion[] {
+export function goalCompletions(
+ line: string,
+ plugins: readonly MavenPlugin[],
+ history: readonly string[] = [],
+): Completion[] {
const at = /\S*$/.exec(line)!.index;
const head = line.slice(0, at);
const word = line.slice(at).toLowerCase();
@@ -476,7 +502,10 @@ export function goalCompletions(line: string, plugins: readonly MavenPlugin[], h
seen.add(label);
out.push({ line: head + label, label, detail });
};
- if (!head.trim()) for (const h of history) if (h.toLowerCase().startsWith(line.toLowerCase()) && h !== line) out.push({ line: h, label: h, detail: "recent" });
+ if (!head.trim())
+ for (const h of history)
+ if (h.toLowerCase().startsWith(line.toLowerCase()) && h !== line)
+ out.push({ line: h, label: h, detail: "recent" });
if (word.startsWith("-")) return out;
for (const phase of [...LIFECYCLE, ...ALL_PHASES]) push(phase, "phase");
const goals = plugins.flatMap((p) => p.goals.map((g) => ({ label: `${p.prefix}:${g}`, detail: p.artifactId })));
@@ -492,7 +521,10 @@ export function taskCompletions(line: string, model: GradleModel, history: reado
const word = line.slice(at).toLowerCase();
const out: Completion[] = [];
const seen = new Set<string>();
- if (!head.trim()) for (const h of history) if (h.toLowerCase().startsWith(line.toLowerCase()) && h !== line) out.push({ line: h, label: h, detail: "recent" });
+ if (!head.trim())
+ for (const h of history)
+ if (h.toLowerCase().startsWith(line.toLowerCase()) && h !== line)
+ out.push({ line: h, label: h, detail: "recent" });
for (const p of model.projects) {
for (const t of p.tasks) {
const label = p.path === ":" ? t.name : `${p.path}:${t.name}`;
@@ -501,14 +533,23 @@ export function taskCompletions(line: string, model: GradleModel, history: reado
out.push({ line: head + label, label, detail: t.group });
}
}
- return out.sort((a, b) => (a.detail === "recent" ? -1 : b.detail === "recent" ? 1 : a.label.length - b.label.length || a.label.localeCompare(b.label)));
+ return out.sort((a, b) =>
+ a.detail === "recent"
+ ? -1
+ : b.detail === "recent"
+ ? 1
+ : a.label.length - b.label.length || a.label.localeCompare(b.label),
+ );
}
/**
* Keys of every expandable node below `roots` (Expand All). Dependency nodes are
* not opened (transitive trees can be huge); their "Dependencies" folder is.
*/
-export function expandableKeys(roots: readonly BuildNode[], children: (n: BuildNode) => BuildNode[] | undefined): Set<string> {
+export function expandableKeys(
+ roots: readonly BuildNode[],
+ children: (n: BuildNode) => BuildNode[] | undefined,
+): Set<string> {
const out = new Set<string>();
const walk = (nodes: readonly BuildNode[]) => {
for (const n of nodes) {
diff --git a/src/features/build-tools/runAnything.ts b/src/features/build-tools/runAnything.ts
index f1fa275a2..146b6c1c3 100644
--- a/src/features/build-tools/runAnything.ts
+++ b/src/features/build-tools/runAnything.ts
@@ -79,16 +79,14 @@ export const buildToolsRunAnything: RunAnythingProvider = {
const head = /^\S+\s*/.exec(query)![0];
return completions(tool, query.slice(head.length))
.slice(0, 50)
- .map(
- (c): RunAnythingItem => ({
- key: `${c.detail === "recent" ? "h" : "c"}:${c.line}`,
- label: `${WORD[tool]} ${c.line}`,
- detail: c.detail,
- icon: tool === "maven" ? "file-maven" : "file-gradle",
- completion: `${WORD[tool]} ${c.detail === "recent" ? c.line : `${c.line} `}`,
- run: () => void executeBuildLine(tool, c.line),
- }),
- );
+ .map((c): RunAnythingItem => ({
+ key: `${c.detail === "recent" ? "h" : "c"}:${c.line}`,
+ label: `${WORD[tool]} ${c.line}`,
+ detail: c.detail,
+ icon: tool === "maven" ? "file-maven" : "file-gradle",
+ completion: `${WORD[tool]} ${c.detail === "recent" ? c.line : `${c.line} `}`,
+ run: () => void executeBuildLine(tool, c.line),
+ }));
},
execute(line) {
const tool = lineTool(line);
diff --git a/src/features/build-tools/store.ts b/src/features/build-tools/store.ts
index d26f964b6..f5a71cabf 100644
--- a/src/features/build-tools/store.ts
+++ b/src/features/build-tools/store.ts
@@ -105,9 +105,12 @@ export function updateSettings(patch: (s: BuildSettings) => BuildSettings) {
if (root) writeSettings(root, settings);
}
-export const toggleMavenOffline = () => updateSettings((s) => ({ ...s, maven: { ...s.maven, offline: !s.maven.offline } }));
-export const toggleSkipTests = () => updateSettings((s) => ({ ...s, maven: { ...s.maven, skipTests: !s.maven.skipTests } }));
-export const toggleGradleOffline = () => updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
+export const toggleMavenOffline = () =>
+ updateSettings((s) => ({ ...s, maven: { ...s.maven, offline: !s.maven.offline } }));
+export const toggleSkipTests = () =>
+ updateSettings((s) => ({ ...s, maven: { ...s.maven, skipTests: !s.maven.skipTests } }));
+export const toggleGradleOffline = () =>
+ updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
export function setProfile(id: string, checked: boolean) {
updateSettings((s) => ({ ...s, maven: { ...s.maven, profiles: { ...s.maven.profiles, [id]: checked } } }));
@@ -169,7 +172,8 @@ export async function loadModel(): Promise<void> {
/** Tree keys expanded on first show: the top-level projects. */
export function initialExpanded(tool: BuildTool, model: BuildModel): Set<string> {
- if (tool === "maven") return new Set(model.maven?.projects.filter((p) => !p.aggregated).map((p) => `mvn:${p.pom}`) ?? []);
+ if (tool === "maven")
+ return new Set(model.maven?.projects.filter((p) => !p.aggregated).map((p) => `mvn:${p.pom}`) ?? []);
return new Set(model.gradle ? ["gradle::"] : []);
}
diff --git a/src/features/build/index.ts b/src/features/build/index.ts
index 32e2993f9..7af0d7877 100644
--- a/src/features/build/index.ts
+++ b/src/features/build/index.ts
@@ -5,7 +5,12 @@
*/
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
-import { maybeEditorService, registerMenuGroup, registerTitleItem, registerToolWindow } from "@/workbench/contributions";
+import {
+ maybeEditorService,
+ registerMenuGroup,
+ registerTitleItem,
+ registerToolWindow,
+} from "@/workbench/contributions";
import { BuildTitleItem } from "./BuildTitleItem";
import { BuildHeaderActions, BuildView } from "./BuildView";
import { BUILD_RUNNING, resetBuildRun, startBuild, stopBuild, useBuildRun } from "./store";
@@ -19,7 +24,9 @@ function moduleTarget(arg: unknown): string | null {
}
function useErrorBadge(): number | null {
- return useBuildRun((s) => (s.status === "failed" ? s.messages.filter((m) => m.severity === "error").length || null : null));
+ return useBuildRun((s) =>
+ s.status === "failed" ? s.messages.filter((m) => m.severity === "error").length || null : null,
+ );
}
export function activate(): () => void {
@@ -35,7 +42,13 @@ export function activate(): () => void {
headerActions: BuildHeaderActions,
useBadge: useErrorBadge,
}),
- registerTitleItem({ id: "build.project", title: "Build Project", align: "right", priority: -1, component: BuildTitleItem }),
+ registerTitleItem({
+ id: "build.project",
+ title: "Build Project",
+ align: "right",
+ priority: -1,
+ component: BuildTitleItem,
+ }),
registerActions([
{
id: "build.buildProject",
diff --git a/src/features/build/store.ts b/src/features/build/store.ts
index 4b75dca15..ff8f7c3f0 100644
--- a/src/features/build/store.ts
+++ b/src/features/build/store.ts
@@ -207,7 +207,10 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
}
} finally {
if (useBuildRun.getState().request === request) useBuildRun.setState({ request: null });
- setContext(BUILD_LAST_STATUS, result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed");
+ setContext(
+ BUILD_LAST_STATUS,
+ result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed",
+ );
setContext(BUILD_RUNNING, false);
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: 1, done: true });
}
diff --git a/src/features/code-insight/ServerStatus.tsx b/src/features/code-insight/ServerStatus.tsx
index ab9ea7117..bda8b5b0f 100644
--- a/src/features/code-insight/ServerStatus.tsx
+++ b/src/features/code-insight/ServerStatus.tsx
@@ -50,7 +50,10 @@ export function ServerStatus() {
<div key={s.id} className={styles.server}>
<div className={styles.line}>
<span
- className={clsx(styles.dot, styles[s.status === "missing" && servedByOther(s, servers) ? "idle" : toneOf(s.status)])}
+ className={clsx(
+ styles.dot,
+ styles[s.status === "missing" && servedByOther(s, servers) ? "idle" : toneOf(s.status)],
+ )}
aria-hidden
/>
<span className={styles.name}>{s.name}</span>
diff --git a/src/features/code-insight/hierarchy.test.ts b/src/features/code-insight/hierarchy.test.ts
index 4f15ee91e..9321c3b46 100644
--- a/src/features/code-insight/hierarchy.test.ts
+++ b/src/features/code-insight/hierarchy.test.ts
@@ -11,7 +11,13 @@ const range = (l1: number, c1: number, l2: number, c2: number) => ({
start: { line: l1, col: c1 },
end: { line: l2, col: c2 },
});
-const outlineItem = (name: string, kind: SymbolKind, r: ReturnType<typeof range>, nameAt: [number, number], children: OutlineItem[] = []): OutlineItem => ({
+const outlineItem = (
+ name: string,
+ kind: SymbolKind,
+ r: ReturnType<typeof range>,
+ nameAt: [number, number],
+ children: OutlineItem[] = [],
+): OutlineItem => ({
name,
detail: null,
kind,
@@ -21,10 +27,16 @@ const outlineItem = (name: string, kind: SymbolKind, r: ReturnType<typeof range>
});
// class Orders { void list() { int x = 1; } } — class on lines 0-10, `list` on lines 2-6.
const OUTLINE = [
- outlineItem("Orders", "class", range(0, 0, 10, 1), [0, 6], [
- outlineItem("list", "method", range(2, 2, 6, 3), [2, 7]),
- outlineItem("count", "field", range(8, 2, 8, 12), [8, 6]),
- ]),
+ outlineItem(
+ "Orders",
+ "class",
+ range(0, 0, 10, 1),
+ [0, 6],
+ [
+ outlineItem("list", "method", range(2, 2, 6, 3), [2, 7]),
+ outlineItem("count", "field", range(8, 2, 8, 12), [8, 6]),
+ ],
+ ),
];
const item = (name: string, fromRanges: HierarchyItem["fromRanges"] = []): HierarchyItem => ({
@@ -41,7 +53,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
- call: async <T,>(p: Promise<T>) => p,
+ call: async <T>(p: Promise<T>) => p,
commands: {
...real.commands,
docOutline: async () => OUTLINE,
@@ -56,8 +68,8 @@ vi.mock("@/platform/ipc", async (orig) => {
vi.mock("./ipc", async (orig) => ({
...(await orig<typeof import("./ipc")>()),
caretContext: () => ({ doc: 1, path: "/p/Orders.java", line: 4, col: 10, word: "x", view: null }),
- withDocument: async <T,>(_path: string, fn: (doc: number) => Promise<T>) => fn(1),
- lspRequest: async <T,>(run: () => Promise<T>) => run(),
+ withDocument: async <T>(_path: string, fn: (doc: number) => Promise<T>) => fn(1),
+ lspRequest: async <T>(run: () => Promise<T>) => run(),
hint: (...a: unknown[]) => hint(...a),
}));
diff --git a/src/features/code-insight/hierarchy.ts b/src/features/code-insight/hierarchy.ts
index 8ef5ef451..cd5d3377f 100644
--- a/src/features/code-insight/hierarchy.ts
+++ b/src/features/code-insight/hierarchy.ts
@@ -196,7 +196,11 @@ export async function showHierarchy(mode: HierarchyMode) {
await loadRoot();
} else {
useHierarchy.setState((st) => ({ failed: new Set(st.failed).add(ROOT_ID) }));
- hint(mode === "call" ? "No method at the caret to show the call hierarchy of" : "No type at the caret to show the hierarchy of");
+ hint(
+ mode === "call"
+ ? "No method at the caret to show the call hierarchy of"
+ : "No type at the caret to show the hierarchy of",
+ );
}
}
@@ -206,7 +210,10 @@ export function hierarchyTarget(
direction: HierarchyDirection,
item: HierarchyItem,
): { path: string; line: number; col: number } {
- const at = mode === "call" && direction === "incoming" && item.fromRanges[0] ? item.fromRanges[0].start : item.selectionRange.start;
+ const at =
+ mode === "call" && direction === "incoming" && item.fromRanges[0]
+ ? item.fromRanges[0].start
+ : item.selectionRange.start;
return { path: item.path, line: at.line, col: at.col };
}
diff --git a/src/features/code-insight/ipc.ts b/src/features/code-insight/ipc.ts
index 9fcdb4afe..77ea565c1 100644
--- a/src/features/code-insight/ipc.ts
+++ b/src/features/code-insight/ipc.ts
@@ -24,12 +24,21 @@ export const isUnavailable = (e: unknown) => e instanceof IpcError && e.kind ===
/** Small hint at the caret (via editor/lsp), or a notification without an editor. */
export function hint(text: string, tone: "info" | "warning" | "error" = "info") {
if (activeEditor()) void executeAction("editor.showHint", { text, tone });
- else notifications().notify({ group: "lsp", level: tone === "error" ? "error" : "info", title: text, key: "code-insight.hint" });
+ else
+ notifications().notify({
+ group: "lsp",
+ level: tone === "error" ? "error" : "info",
+ title: text,
+ key: "code-insight.hint",
+ });
}
export function reportError(e: unknown) {
if (isCancelled(e)) return;
- hint(isUnavailable(e) ? "No language server available" : e instanceof Error ? e.message : String(e), isUnavailable(e) ? "info" : "error");
+ hint(
+ isUnavailable(e) ? "No language server available" : e instanceof Error ? e.message : String(e),
+ isUnavailable(e) ? "info" : "error",
+ );
}
export interface CaretContext {
@@ -52,7 +61,14 @@ export function caretContext(): CaretContext | null {
if (!ed) return null;
const head = ed.view.state.selection.main.head;
const line = ed.view.state.doc.lineAt(head);
- return { doc: ed.ctx.doc, path: ed.ctx.path, line: line.number - 1, col: head - line.from, word: wordAt(ed.view, head), view: ed.view };
+ return {
+ doc: ed.ctx.doc,
+ path: ed.ctx.path,
+ line: line.number - 1,
+ col: head - line.from,
+ word: wordAt(ed.view, head),
+ view: ed.view,
+ };
}
function wordAt(view: EditorView, offset: number): string | null {
@@ -93,7 +109,10 @@ export async function previewText(path: string): Promise<string> {
return lines.join("\n");
}
-export async function readManyFileLines(paths: readonly string[], concurrency = 4): Promise<Map<string, string[] | null>> {
+export async function readManyFileLines(
+ paths: readonly string[],
+ concurrency = 4,
+): Promise<Map<string, string[] | null>> {
const out = new Map<string, string[] | null>();
const queue = [...new Set(paths)];
const worker = async () => {
diff --git a/src/features/code-insight/problemsStore.test.ts b/src/features/code-insight/problemsStore.test.ts
index 2eaf06603..ce036d992 100644
--- a/src/features/code-insight/problemsStore.test.ts
+++ b/src/features/code-insight/problemsStore.test.ts
@@ -90,7 +90,9 @@ describe("local inspections (issue #42)", () => {
clearProblems();
const off = installProblemsEvents();
try {
- setFileDiagnostics("/p/a.py", "spelling", [{ ...d(0, "info"), message: "Typo: In word 'mesage'", source: "Spelling" }]);
+ setFileDiagnostics("/p/a.py", "spelling", [
+ { ...d(0, "info"), message: "Typo: In word 'mesage'", source: "Spelling" },
+ ]);
const [typo] = fileDiagnostics(useProblems.getState().map, "/p/a.py");
expect(typo).toMatchObject({ message: "Typo: In word 'mesage'", typo: true });
const producer = producerFor(useProblems.getState().map, "/p/a.py", typo!);
diff --git a/src/features/code-insight/problemsStore.ts b/src/features/code-insight/problemsStore.ts
index 87df26532..348a2f0d9 100644
--- a/src/features/code-insight/problemsStore.ts
+++ b/src/features/code-insight/problemsStore.ts
@@ -26,12 +26,21 @@ export interface SeverityCounts {
}
/** Replaces `source`'s diagnostics for `path`; returns the same map when nothing changed. */
-export function mergeDiagnostics(map: ProblemsMap, path: string, source: string, items: readonly Diagnostic[]): ProblemsMap {
+export function mergeDiagnostics(
+ map: ProblemsMap,
+ path: string,
+ source: string,
+ items: readonly Diagnostic[],
+): ProblemsMap {
const prev = map.get(path);
if (!items.length && !prev?.has(source)) return map;
const next = new Map(map);
const sources = new Map(prev ?? []);
- if (items.length) sources.set(source, items.map((d) => (d.source ? d : { ...d, source })));
+ if (items.length)
+ sources.set(
+ source,
+ items.map((d) => (d.source ? d : { ...d, source })),
+ );
else sources.delete(source);
if (sources.size) next.set(path, sources);
else next.delete(path);
diff --git a/src/features/code-insight/servers.test.ts b/src/features/code-insight/servers.test.ts
index e23f5c20a..b9e85dd1e 100644
--- a/src/features/code-insight/servers.test.ts
+++ b/src/features/code-insight/servers.test.ts
@@ -33,7 +33,13 @@ describe("server status", () => {
const info: ServerInfo = { id, name: "jdtls", languages: [], root: "/p", status: "starting", pid: null };
// The first event requests a snapshot; the server reports missing before it answers.
emitLocalIdeEvent({ type: "languageServer", server: id, name: "jdtls", status: "starting", message: null });
- emitLocalIdeEvent({ type: "languageServer", server: id, name: "jdtls", status: "missing", message: "install jdtls" });
+ emitLocalIdeEvent({
+ type: "languageServer",
+ server: id,
+ name: "jdtls",
+ status: "missing",
+ message: "install jdtls",
+ });
pending.splice(0).forEach((resolve) => resolve([info]));
await vi.waitFor(() => expect(useServers.getState().servers.get(id)?.languages).toEqual([]));
await new Promise((r) => setTimeout(r, 0));
@@ -81,7 +87,9 @@ describe("serversSummary", () => {
root: "/p",
});
it("doesn't flag a missing server whose languages another one serves", () => {
- expect(serversSummary([entry(1, "vtsls", "missing"), entry(2, "typescript-language-server", "ready")])?.tone).toBe("ok");
+ expect(serversSummary([entry(1, "vtsls", "missing"), entry(2, "typescript-language-server", "ready")])?.tone).toBe(
+ "ok",
+ );
expect(serversSummary([entry(1, "vtsls", "missing")])?.tone).toBe("error");
});
it("doesn't count stopped servers next to running ones", () => {
diff --git a/src/features/code-insight/servers.ts b/src/features/code-insight/servers.ts
index 1da19ec0e..3c8243bbc 100644
--- a/src/features/code-insight/servers.ts
+++ b/src/features/code-insight/servers.ts
@@ -150,15 +150,20 @@ export const STATUS_LABEL: Record<ServerStatus, string> = {
export function servedByOther(server: ServerEntry, servers: readonly ServerEntry[]): boolean {
return (
server.languages.length > 0 &&
- server.languages.every((l) => servers.some((o) => o !== server && o.status !== "missing" && o.languages.includes(l)))
+ server.languages.every((l) =>
+ servers.some((o) => o !== server && o.status !== "missing" && o.languages.includes(l)),
+ )
);
}
/** One-line summary for the status bar. */
-export function serversSummary(servers: readonly ServerEntry[]): { text: string; tone: "ok" | "busy" | "error" | "idle" } | null {
+export function serversSummary(
+ servers: readonly ServerEntry[],
+): { text: string; tone: "ok" | "busy" | "error" | "idle" } | null {
if (!servers.length) return null;
const bad = servers.filter(
- (s) => s.status === "crashed" || s.status === "misconfigured" || (s.status === "missing" && !servedByOther(s, servers)),
+ (s) =>
+ s.status === "crashed" || s.status === "misconfigured" || (s.status === "missing" && !servedByOther(s, servers)),
);
const busy = servers.filter((s) => s.status === "starting" || s.status === "busy");
const tone = bad.length ? "error" : busy.length ? "busy" : servers.some((s) => s.status === "ready") ? "ok" : "idle";
diff --git a/src/features/code-insight/syntaxUsages.test.ts b/src/features/code-insight/syntaxUsages.test.ts
index d675a015f..6e19a3861 100644
--- a/src/features/code-insight/syntaxUsages.test.ts
+++ b/src/features/code-insight/syntaxUsages.test.ts
@@ -5,7 +5,8 @@ import type { IdeError, Locals, Range } from "@/bindings";
type R<T> = Promise<{ status: "ok"; data: T } | { status: "error"; error: IdeError }>;
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
-const err = (kind: IdeError["kind"]) => Promise.resolve({ status: "error" as const, error: { kind, message: kind } as IdeError });
+const err = (kind: IdeError["kind"]) =>
+ Promise.resolve({ status: "error" as const, error: { kind, message: kind } as IdeError });
const cmd = {
lspReferences: vi.fn((): R<unknown> => err("unavailable")),
@@ -51,25 +52,39 @@ describe("Find Usages fallback", () => {
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true);
expect(res.groups[0]!.usages.length).toBe(1);
expect(res.note).toBe(incompleteNote("indexing", "x"));
- expect(incompleteNote("tooManyFiles", "x")).toBe("May be incomplete: too many files mention 'x' to search them all");
+ expect(incompleteNote("tooManyFiles", "x")).toBe(
+ "May be incomplete: too many files mention 'x' to search them all",
+ );
});
it("lists a certain local's references when the server is not ready", async () => {
cmd.syntaxLocals.mockReturnValueOnce(
ok({
status: "local",
- symbol: { name: "x", kind: "var", definition: r(0, 4, 5), scope: r(0, 0, 20), references: [r(1, 0, 1)], certain: true, conflicts: [] },
+ symbol: {
+ name: "x",
+ kind: "var",
+ definition: r(0, 4, 5),
+ scope: r(0, 0, 20),
+ references: [r(1, 0, 1)],
+ certain: true,
+ conflicts: [],
+ },
}),
);
const res = await fetchUsages(caret);
expect(res.note).toBe(LOCAL_NOTE);
- expect(res.groups.map((g) => [g.path, g.usages.map((u) => [u.line, u.col, u.text])])).toEqual([["/p/a.ts", [[1, 0, "x + y;"]]]]);
+ expect(res.groups.map((g) => [g.path, g.usages.map((u) => [u.line, u.col, u.text])])).toEqual([
+ ["/p/a.ts", [[1, 0, "x + y;"]]],
+ ]);
expect(filesMentioning).not.toHaveBeenCalled();
});
it("searches the project for identifier occurrences of non-locals", async () => {
cmd.lspReferences.mockReturnValueOnce(err("internal"));
- cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "y", range: r(1, 4, 5), reason: "unresolved" }));
+ cmd.syntaxLocals.mockReturnValueOnce(
+ ok({ status: "notLocal", name: "y", range: r(1, 4, 5), reason: "unresolved" }),
+ );
cmd.syntaxIdentifiersInFiles.mockReturnValueOnce(
ok([
{ path: "/p/b.ts", occurrences: [{ range: r(2, 0, 1), kind: "identifier", qualified: false }] },
@@ -85,8 +100,13 @@ describe("Find Usages fallback", () => {
it("keeps the server error when the language has no grammar", async () => {
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: false, locals: false }));
const other = new EditorView({ state: EditorState.create({ doc: "x" }) });
- _addEditor({ view: other, ctx: { doc: 4, path: "/p/a.txt", language: "plaintext", uiMode: null, readOnly: false } });
- await expect(fetchUsages({ doc: 4, path: "/p/a.txt", line: 0, col: 0, word: "x", view: other })).rejects.toMatchObject({
+ _addEditor({
+ view: other,
+ ctx: { doc: 4, path: "/p/a.txt", language: "plaintext", uiMode: null, readOnly: false },
+ });
+ await expect(
+ fetchUsages({ doc: 4, path: "/p/a.txt", line: 0, col: 0, word: "x", view: other }),
+ ).rejects.toMatchObject({
kind: "unavailable",
});
});
diff --git a/src/features/code-insight/syntaxUsages.ts b/src/features/code-insight/syntaxUsages.ts
index ec8e5b218..161c93942 100644
--- a/src/features/code-insight/syntaxUsages.ts
+++ b/src/features/code-insight/syntaxUsages.ts
@@ -28,7 +28,9 @@ function inside(range: Range, pos: Range["start"]) {
/** Null when the structure service cannot answer for this file (no grammar, no editor). */
export async function syntaxUsages(c: CaretContext): Promise<SyntaxUsages | null> {
- const language = c.view ? editorsFor(c.path).find((e) => e.view === c.view)?.ctx.language : editorsFor(c.path)[0]?.ctx.language;
+ const language = c.view
+ ? editorsFor(c.path).find((e) => e.view === c.view)?.ctx.language
+ : editorsFor(c.path)[0]?.ctx.language;
if (!language) return null;
const support = await structure.support(language);
if (!support.tree) return null;
@@ -45,7 +47,9 @@ export async function syntaxUsages(c: CaretContext): Promise<SyntaxUsages | null
// Re-declared in the same scope: every plain occurrence in that scope, as text.
const occ = await structure.identifiers(c.doc, symbol.name);
return {
- locs: occ.filter((o) => !o.qualified && inside(symbol.scope, o.range.start)).map((o) => ({ path: c.path, range: o.range })),
+ locs: occ
+ .filter((o) => !o.qualified && inside(symbol.scope, o.range.start))
+ .map((o) => ({ path: c.path, range: o.range })),
note: TEXT_NOTE,
};
}
diff --git a/src/features/code-insight/usageResults.test.ts b/src/features/code-insight/usageResults.test.ts
index b7782b12c..02907c386 100644
--- a/src/features/code-insight/usageResults.test.ts
+++ b/src/features/code-insight/usageResults.test.ts
@@ -10,7 +10,8 @@ vi.mock("./ipc", async (orig) => ({
readManyFileLines: async () => new Map([["/p/b.rs", ["", " used();"]]]),
}));
-const { activeUsageSearch, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } = await import("./usages");
+const { activeUsageSearch, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
+ await import("./usages");
describe("showUsageResults", () => {
it("shows given usages in the Find Usages tool window", async () => {
@@ -19,7 +20,9 @@ describe("showUsageResults", () => {
expect(show).toHaveBeenCalledWith("usages");
const search = activeUsageSearch(useUsages.getState())!;
expect(search).toMatchObject({ symbol: "used", loading: false, error: null, rerun: null });
- expect(search.groups).toEqual([{ path: "/p/b.rs", usages: [{ path: "/p/b.rs", line: 1, col: 4, endCol: 8, text: " used();" }] }]);
+ expect(search.groups).toEqual([
+ { path: "/p/b.rs", usages: [{ path: "/p/b.rs", line: 1, col: 4, endCol: 8, text: " used();" }] },
+ ]);
});
it("ignores malformed arguments", async () => {
@@ -30,7 +33,15 @@ describe("showUsageResults", () => {
});
describe("usage tabs", () => {
- const search = (id: number) => ({ id, symbol: `s${id}`, loading: false, groups: [], error: null, note: null, rerun: null });
+ const search = (id: number) => ({
+ id,
+ symbol: `s${id}`,
+ loading: false,
+ groups: [],
+ error: null,
+ note: null,
+ rerun: null,
+ });
it("replace the selected tab unless it is pinned", () => {
resetUsages();
diff --git a/src/features/code-insight/usages.ts b/src/features/code-insight/usages.ts
index 1791bceeb..39998570e 100644
--- a/src/features/code-insight/usages.ts
+++ b/src/features/code-insight/usages.ts
@@ -31,7 +31,10 @@ export interface UsageGroup {
}
/** Groups reference locations by file (sorted by path, then position), attaching line previews. */
-export function groupUsages(locs: readonly Location[], files: ReadonlyMap<string, readonly string[] | null>): UsageGroup[] {
+export function groupUsages(
+ locs: readonly Location[],
+ files: ReadonlyMap<string, readonly string[] | null>,
+): UsageGroup[] {
const byPath = new Map<string, Usage[]>();
const seen = new Set<string>();
for (const l of locs) {
@@ -170,7 +173,9 @@ export async function fetchUsages(c: CaretContext, request: RequestId = nextRequ
let locs: Location[];
let note: string | null = null;
try {
- const refs = await lspRequest(() => commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true));
+ const refs = await lspRequest(() =>
+ commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true),
+ );
locs = refs.locations;
if (refs.incomplete) note = incompleteNote(refs.incomplete, c.word);
} catch (e) {
diff --git a/src/features/code-insight/views.test.ts b/src/features/code-insight/views.test.ts
index 9a2c9d15d..15887ab13 100644
--- a/src/features/code-insight/views.test.ts
+++ b/src/features/code-insight/views.test.ts
@@ -94,7 +94,8 @@ describe("sortProblems", () => {
code: null,
});
const items = [d("warning", 1, "b"), d("error", 5, "c"), d("warning", 0, "z"), d("error", 2, "a")];
- const lines = (order: { bySeverity: boolean; byName: boolean }) => sortProblems(items, order).map((x) => x.range.start.line);
+ const lines = (order: { bySeverity: boolean; byName: boolean }) =>
+ sortProblems(items, order).map((x) => x.range.start.line);
it("orders by severity, then position (IDEA's default)", () => {
expect(lines({ bySeverity: true, byName: false })).toEqual([2, 5, 0, 1]);
diff --git a/src/features/coverage/coverage.test.ts b/src/features/coverage/coverage.test.ts
index 311aacc26..22257cc20 100644
--- a/src/features/coverage/coverage.test.ts
+++ b/src/features/coverage/coverage.test.ts
@@ -3,10 +3,31 @@ import { EditorState } from "@codemirror/state";
import type { CoverageSuite, FileCoverage, RunConfig } from "@/platform/ipc";
import { coverageMarkers } from "./gutter";
import { coverageBadges, coverageSupports, coverageTree, formatPercent, lineState, sortTree } from "./model";
-import { MAX_SUITES, addSuite, closeSuite, reportEntries, resetCoverage, setCoverageVisible, shownFileCoverage, useCoverage } from "./store";
+import {
+ MAX_SUITES,
+ addSuite,
+ closeSuite,
+ reportEntries,
+ resetCoverage,
+ setCoverageVisible,
+ shownFileCoverage,
+ useCoverage,
+} from "./store";
function cfg(command: string, args: string[], extra: Partial<RunConfig> = {}): RunConfig {
- return { id: "c", name: "c", kind: "shell", command, args, cwd: null, env: {}, detected: true, isTest: false, debugAdapter: null, ...extra };
+ return {
+ id: "c",
+ name: "c",
+ kind: "shell",
+ command,
+ args,
+ cwd: null,
+ env: {},
+ detected: true,
+ isTest: false,
+ debugAdapter: null,
+ ...extra,
+ };
}
function file(path: string, covered: number, total: number, branches: [number, number] = [0, 0]): FileCoverage {
@@ -98,7 +119,11 @@ describe("gutter and suites", () => {
expect(f.lines.map(lineState)).toEqual(["covered", "partial", "uncovered", "covered"]);
const doc = EditorState.create({ doc: "a\nb\nc\n" }).doc;
const colors: string[] = [];
- coverageMarkers(f, doc).between(0, doc.length, (_from, _to, m) => void colors.push((m as unknown as { color: string }).color));
+ coverageMarkers(f, doc).between(
+ 0,
+ doc.length,
+ (_from, _to, m) => void colors.push((m as unknown as { color: string }).color),
+ );
expect(colors).toEqual(["var(--coverage-covered)", "var(--coverage-partial)", "var(--coverage-uncovered)"]);
});
diff --git a/src/features/coverage/executor.ts b/src/features/coverage/executor.ts
index b007042b7..ad3918b4a 100644
--- a/src/features/coverage/executor.ts
+++ b/src/features/coverage/executor.ts
@@ -4,7 +4,12 @@
*/
import { executeAction } from "@/platform/actions";
import { call, commands, isTauri, type InstallCommand, type RunConfig } from "@/platform/ipc";
-import { notifications, toolWindowService, type ExecutorLaunch, type RunExecutorContribution } from "@/workbench/contributions";
+import {
+ notifications,
+ toolWindowService,
+ type ExecutorLaunch,
+ type RunExecutorContribution,
+} from "@/workbench/contributions";
import { coverageSupports, formatPercent } from "./model";
import { addSuite } from "./store";
import { tx } from "@/platform/i18n";
@@ -35,7 +40,8 @@ export function notifyMissingTool(
const { tool, install } = missing;
const line = install ? [install.command, ...install.args].join(" ") : null;
const actions = [];
- if (install) actions.push({ label: "Install", run: () => void executeAction("run.runConfig", installConfig(tool, install)) });
+ if (install)
+ actions.push({ label: "Install", run: () => void executeAction("run.runConfig", installConfig(tool, install)) });
if (missing.homepage) {
const url = missing.homepage;
actions.push({
@@ -48,7 +54,11 @@ export function notifyMissingTool(
level: "warning",
key: `${group}-missing-${tool}`,
title: `${tool} is not installed`,
- body: line ? tx`${missing.message} Install it with: ${line}` : missing.homepage ? `${missing.message} ${missing.homepage}` : missing.message,
+ body: line
+ ? tx`${missing.message} Install it with: ${line}`
+ : missing.homepage
+ ? `${missing.message} ${missing.homepage}`
+ : missing.message,
sticky: true,
actions,
});
@@ -61,7 +71,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
}
const plan = await call(commands.coveragePrepare(config));
if (plan.status === "unsupported") {
- notifications().notify({ group: "run", level: "info", key: "coverage-unsupported", title: `Cannot run '${config.name}' with coverage`, body: plan.reason });
+ notifications().notify({
+ group: "run",
+ level: "info",
+ key: "coverage-unsupported",
+ title: `Cannot run '${config.name}' with coverage`,
+ body: plan.reason,
+ });
return null;
}
if (plan.status === "missingTool") {
@@ -90,7 +106,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
title: `Coverage of '${suite.name}': ${formatPercent(totals[0]!, totals[1]!)} lines`,
});
} catch (e) {
- notifications().notify({ group: "run", level: "error", key: "coverage-done", title: `No coverage data for '${config.name}'`, body: errorText(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ key: "coverage-done",
+ title: `No coverage data for '${config.name}'`,
+ body: errorText(e),
+ });
}
})();
},
diff --git a/src/features/coverage/index.ts b/src/features/coverage/index.ts
index f1035d60d..60acde68e 100644
--- a/src/features/coverage/index.ts
+++ b/src/features/coverage/index.ts
@@ -49,12 +49,14 @@ export function activate(): () => void {
icon: "run-coverage",
when: "projectOpen",
keywords: ["coverage"],
- run: ({ arg }) => executeAction("run.withExecutor", { executor: "coverage", context: arg ?? true }).then(() => undefined),
+ run: ({ arg }) =>
+ executeAction("run.withExecutor", { executor: "coverage", context: arg ?? true }).then(() => undefined),
},
{
id: "coverage.importReport",
title: "Import a Coverage Report…",
- description: "Show a report collected elsewhere (CI): lcov, JaCoCo XML or a Go cover profile; argument: the file path",
+ description:
+ "Show a report collected elsewhere (CI): lcov, JaCoCo XML or a Go cover profile; argument: the file path",
category: "Run",
icon: "folder-open",
when: "projectOpen",
diff --git a/src/features/coverage/model.ts b/src/features/coverage/model.ts
index d421b4e15..e36d8ceac 100644
--- a/src/features/coverage/model.ts
+++ b/src/features/coverage/model.ts
@@ -85,7 +85,16 @@ const join = (a: string, b: string) => (a ? `${a.replace(/\/$/, "")}/${b}` : b);
* (`src/main/java/com/x`) and every directory sums its files.
*/
export function coverageTree(suite: CoverageSuite, root: string, compactDirs = true): CoverageNode[] {
- const top: CoverageNode = { path: root, name: "", dir: true, children: [], linesTotal: 0, linesCovered: 0, branchesTotal: 0, branchesCovered: 0 };
+ const top: CoverageNode = {
+ path: root,
+ name: "",
+ dir: true,
+ children: [],
+ linesTotal: 0,
+ linesCovered: 0,
+ branchesTotal: 0,
+ branchesCovered: 0,
+ };
const prefix = root.replace(/\/$/, "") + "/";
for (const f of suite.files) {
const inside = f.path.startsWith(prefix);
@@ -97,7 +106,16 @@ export function coverageTree(suite: CoverageSuite, root: string, compactDirs = t
base = inside || base ? join(base, part) : `/${part}`;
let child = node.children.find((c) => c.dir && c.name === part);
if (!child) {
- child = { path: base, name: part, dir: true, children: [], linesTotal: 0, linesCovered: 0, branchesTotal: 0, branchesCovered: 0 };
+ child = {
+ path: base,
+ name: part,
+ dir: true,
+ children: [],
+ linesTotal: 0,
+ linesCovered: 0,
+ branchesTotal: 0,
+ branchesCovered: 0,
+ };
node.children.push(child);
}
node = child;
diff --git a/src/features/coverage/store.ts b/src/features/coverage/store.ts
index d820730f1..69f4f9f79 100644
--- a/src/features/coverage/store.ts
+++ b/src/features/coverage/store.ts
@@ -92,7 +92,8 @@ export function syncCoverageViews(): () => void {
const root = useProject.getState().project?.root;
const decorations = new Map<string, FileDecoration>();
if (suite && root) {
- for (const [path, badge] of coverageBadges(coverageTree(suite.data, root, false))) decorations.set(path, { badge });
+ for (const [path, badge] of coverageBadges(coverageTree(suite.data, root, false)))
+ decorations.set(path, { badge });
}
setFileDecorations("coverage", decorations);
};
@@ -148,7 +149,11 @@ export function rememberImport(report: ImportedReport) {
export function forgetImport(path: string) {
const root = useProject.getState().project?.root;
- if (root) saveImported(root, importedReports(root).filter((r) => r.path !== path));
+ if (root)
+ saveImported(
+ root,
+ importedReports(root).filter((r) => r.path !== path),
+ );
}
/** A row of "Manage Coverage Reports": a loaded suite, or an imported report not loaded now. */
diff --git a/src/features/database/database.test.ts b/src/features/database/database.test.ts
index a906df93d..8310f593a 100644
--- a/src/features/database/database.test.ts
+++ b/src/features/database/database.test.ts
@@ -21,12 +21,28 @@ import { VENDORS, sourceUrl, vendorById, vendorOf, vendorPreset } from "./vendor
describe("clipboard formats", () => {
it("copies TSV with NULL as empty and whitespace flattened", () => {
- expect(toTsv(["a", "b"], [["1", null], ["x\ty", "line\nbreak"]])).toBe("a\tb\n1\t\nx y\tline break");
+ expect(
+ toTsv(
+ ["a", "b"],
+ [
+ ["1", null],
+ ["x\ty", "line\nbreak"],
+ ],
+ ),
+ ).toBe("a\tb\n1\t\nx y\tline break");
expect(toTsv(null, [["1"]])).toBe("1");
});
it("copies RFC 4180 CSV", () => {
- expect(toCsv(["id", "note"], [["1", 'say "hi", ok'], ["2", null]])).toBe('id,note\r\n1,"say ""hi"", ok"\r\n2,');
+ expect(
+ toCsv(
+ ["id", "note"],
+ [
+ ["1", 'say "hi", ok'],
+ ["2", null],
+ ],
+ ),
+ ).toBe('id,note\r\n1,"say ""hi"", ok"\r\n2,');
});
});
@@ -87,7 +103,9 @@ describe("export formats", () => {
});
it("writes a Markdown table, numbers right-aligned", () => {
- expect(exportData("markdown", { ...data, rows: [["1", "a|b"]] })).toBe("| id | name |\n| --: | --- |\n| 1 | a\\|b |");
+ expect(exportData("markdown", { ...data, rows: [["1", "a|b"]] })).toBe(
+ "| id | name |\n| --: | --- |\n| 1 | a\\|b |",
+ );
});
});
@@ -95,8 +113,12 @@ describe("connection errors", () => {
const ssh = (auth: "password" | "keyPair" | "openSsh") => ({ ssh: { enabled: true, host: "bastion", auth } });
it("asks for what the failed connection needs", () => {
- expect(connectRemedy("protocol", "Unknown SSH host key for bastion:22 (ssh-ed25519 SHA256:abc)")).toBe("trustHostKey");
- expect(connectRemedy("permissionDenied", "SSH password required for me@bastion:22", ssh("password"))).toBe("sshSecret");
+ expect(connectRemedy("protocol", "Unknown SSH host key for bastion:22 (ssh-ed25519 SHA256:abc)")).toBe(
+ "trustHostKey",
+ );
+ expect(connectRemedy("permissionDenied", "SSH password required for me@bastion:22", ssh("password"))).toBe(
+ "sshSecret",
+ );
expect(connectRemedy("permissionDenied", "SSH key passphrase required for /k", ssh("keyPair"))).toBe("sshSecret");
expect(connectRemedy("permissionDenied", "SSH authentication failed for me@bastion:22", ssh("password"))).toBe(
"sshSecret",
@@ -144,14 +166,22 @@ describe("parseSourceUrl", () => {
});
it("reads SQLite files and rejects other drivers", () => {
- expect(parseSourceUrl("jdbc:sqlite:C:/data/shop.db")?.source).toEqual({ driver: "sqlite", file: "C:/data/shop.db", name: "shop" });
+ expect(parseSourceUrl("jdbc:sqlite:C:/data/shop.db")?.source).toEqual({
+ driver: "sqlite",
+ file: "C:/data/shop.db",
+ name: "shop",
+ });
expect(parseSourceUrl("oracle://x")).toBeNull();
});
});
describe("data source types", () => {
it("presets wire-compatible products on the existing drivers", () => {
- expect(vendorPreset(vendorById("cockroachdb")!)).toEqual({ driver: "postgres", vendor: "cockroachdb", port: 26257 });
+ expect(vendorPreset(vendorById("cockroachdb")!)).toEqual({
+ driver: "postgres",
+ vendor: "cockroachdb",
+ port: 26257,
+ });
expect(vendorPreset(vendorById("postgres")!)).toEqual({ driver: "postgres", vendor: "", port: 5432 });
expect(vendorPreset(vendorById("supabase")!).ssl).toBe("require");
expect(VENDORS.every((v) => ["postgres", "mysql", "sqlite"].includes(v.driver))).toBe(true);
@@ -170,7 +200,9 @@ describe("data source types", () => {
expect(sourceUrl({ driver: "postgres", host: "localhost", port: 5432, database: "postgres" })).toBe(
"jdbc:postgresql://localhost:5432/postgres",
);
- expect(sourceUrl({ driver: "postgres", vendor: "redshift", host: "r", port: null, database: "" })).toBe("jdbc:redshift://r:5439");
+ expect(sourceUrl({ driver: "postgres", vendor: "redshift", host: "r", port: null, database: "" })).toBe(
+ "jdbc:redshift://r:5439",
+ );
expect(sourceUrl({ driver: "mysql", vendor: "mariadb", host: "::1", port: 3307, database: "a b" })).toBe(
"jdbc:mariadb://[::1]:3307/a%20b",
);
@@ -178,7 +210,9 @@ describe("data source types", () => {
});
it("reads URLs of compatible products, SSL settings and driver properties", () => {
- const tidb = parseSourceUrl("jdbc:tidb://[email protected]:4000/test?sslmode=verify-full&sslrootcert=/ca.pem&sql_mode=ANSI");
+ const tidb = parseSourceUrl(
+ "jdbc:tidb://[email protected]:4000/test?sslmode=verify-full&sslrootcert=/ca.pem&sql_mode=ANSI",
+ );
expect(tidb?.source).toEqual({
driver: "mysql",
vendor: "tidb",
@@ -223,7 +257,8 @@ describe("Options tab", () => {
["a:other", 50_000],
["b", 0],
]);
- const idle = (busy: string[]) => idleTargets(["a", "a:other", "b", "c"], sources, used, (t) => busy.includes(t), 60_000);
+ const idle = (busy: string[]) =>
+ idleTargets(["a", "a:other", "b", "c"], sources, used, (t) => busy.includes(t), 60_000);
expect(idle([])).toEqual(["a"]);
expect(idle(["a"])).toEqual([]);
});
diff --git a/src/features/database/objects.test.ts b/src/features/database/objects.test.ts
index 9549aeb57..1d3265e73 100644
--- a/src/features/database/objects.test.ts
+++ b/src/features/database/objects.test.ts
@@ -22,7 +22,11 @@ const col = (name: string, dataType: string, extra: Partial<DbColumnInfo> = {}):
...extra,
});
-const users = [col("id", "INTEGER", { primaryKey: true, nullable: false }), col("email", "TEXT", { nullable: false }), col("name", "TEXT")];
+const users = [
+ col("id", "INTEGER", { primaryKey: true, nullable: false }),
+ col("email", "TEXT", { nullable: false }),
+ col("name", "TEXT"),
+];
describe("database object SQL", () => {
it("quotes only when needed", () => {
@@ -34,12 +38,18 @@ describe("database object SQL", () => {
it("copies references", () => {
expect(reference("sqlite", { kind: "table", schema: "main", name: "users" })).toBe("users");
- expect(reference("postgres", { kind: "column", schema: "public", name: "users", column: "email" })).toBe("public.users.email");
+ expect(reference("postgres", { kind: "column", schema: "public", name: "users", column: "email" })).toBe(
+ "public.users.email",
+ );
});
it("renames per dialect", () => {
- expect(renameSql("sqlite", { kind: "table", schema: "main", name: "users" }, "people")).toBe("alter table users rename to people;");
- expect(renameSql("mysql", { kind: "table", schema: "app", name: "users" }, "people")).toBe("rename table app.users to app.people;");
+ expect(renameSql("sqlite", { kind: "table", schema: "main", name: "users" }, "people")).toBe(
+ "alter table users rename to people;",
+ );
+ expect(renameSql("mysql", { kind: "table", schema: "app", name: "users" }, "people")).toBe(
+ "rename table app.users to app.people;",
+ );
expect(renameSql("postgres", { kind: "column", schema: "public", name: "users", column: "email" }, "mail")).toBe(
"alter table public.users rename column email to mail;",
);
@@ -47,14 +57,24 @@ describe("database object SQL", () => {
it("drops with IF EXISTS / CASCADE", () => {
const t = { kind: "table" as const, schema: "public", name: "users" };
- expect(dropSql("postgres", t, { ifExists: true, cascade: true })).toBe("drop table if exists public.users cascade;");
- expect(dropSql("sqlite", { ...t, schema: "main" }, { ifExists: false, cascade: true })).toBe("drop table users;");
- expect(dropSql("mysql", { kind: "index", schema: "app", name: "ix", table: "users" }, { ifExists: false, cascade: false })).toBe(
- "drop index ix on app.users;",
- );
- expect(dropSql("sqlite", { kind: "column", schema: "main", name: "users", column: "name" }, { ifExists: true, cascade: false })).toBe(
- "alter table users drop column name;",
+ expect(dropSql("postgres", t, { ifExists: true, cascade: true })).toBe(
+ "drop table if exists public.users cascade;",
);
+ expect(dropSql("sqlite", { ...t, schema: "main" }, { ifExists: false, cascade: true })).toBe("drop table users;");
+ expect(
+ dropSql(
+ "mysql",
+ { kind: "index", schema: "app", name: "ix", table: "users" },
+ { ifExists: false, cascade: false },
+ ),
+ ).toBe("drop index ix on app.users;");
+ expect(
+ dropSql(
+ "sqlite",
+ { kind: "column", schema: "main", name: "users", column: "name" },
+ { ifExists: true, cascade: false },
+ ),
+ ).toBe("alter table users drop column name;");
});
it("truncates (SQLite deletes)", () => {
@@ -66,8 +86,12 @@ describe("database object SQL", () => {
it("writes script templates keyed by the primary key", () => {
expect(scriptSql("sqlite", "selectFirst", "main", "users", users)).toBe("select *\nfrom users\nlimit 10;\n");
- expect(scriptSql("sqlite", "insert", "main", "users", users)).toBe("insert into users (id, email, name)\nvalues (?, ?, ?);\n");
- expect(scriptSql("sqlite", "update", "main", "users", users)).toBe("update users\nset email = ?,\n name = ?\nwhere id = ?;\n");
+ expect(scriptSql("sqlite", "insert", "main", "users", users)).toBe(
+ "insert into users (id, email, name)\nvalues (?, ?, ?);\n",
+ );
+ expect(scriptSql("sqlite", "update", "main", "users", users)).toBe(
+ "update users\nset email = ?,\n name = ?\nwhere id = ?;\n",
+ );
expect(scriptSql("sqlite", "delete", "main", "users", users)).toBe("delete\nfrom users\nwhere id = ?;\n");
});
@@ -82,7 +106,16 @@ describe("database object SQL", () => {
const d = users.map(draftOf);
d[1] = { ...d[1]!, name: "mail" };
d[2] = { ...d[2]!, dropped: true };
- d.push({ key: 9, original: null, name: "age", dataType: "INTEGER", notNull: false, default: "0", primaryKey: false, dropped: false });
+ d.push({
+ key: 9,
+ original: null,
+ name: "age",
+ dataType: "INTEGER",
+ notNull: false,
+ default: "0",
+ primaryKey: false,
+ dropped: false,
+ });
expect(alterTableSql("sqlite", "main", "users", "people", d)).toEqual([
"alter table users rename column email to mail;",
"alter table users drop column name;",
diff --git a/src/features/database/sql/analyze.ts b/src/features/database/sql/analyze.ts
index fd59951f5..fb0332e34 100644
--- a/src/features/database/sql/analyze.ts
+++ b/src/features/database/sql/analyze.ts
@@ -536,7 +536,8 @@ export function valuesSlot(text: string, pos: number, driver: DbDriver): ValuesS
continue;
}
if (depth === 0 && isW(t, "VALUES")) afterValues = true;
- else if (depth === 1 && !afterValues && columns && (t.kind === "word" || t.kind === "quoted")) columns.push(identName(t));
+ else if (depth === 1 && !afterValues && columns && (t.kind === "word" || t.kind === "quoted"))
+ columns.push(identName(t));
else if (depth === 1 && inTuple && isP(t, ",")) index++;
}
return inTuple ? { target, columns: columns?.length ? columns : null, index } : null;
diff --git a/src/features/database/sql/format.test.ts b/src/features/database/sql/format.test.ts
index 89a91b75f..274a3539b 100644
--- a/src/features/database/sql/format.test.ts
+++ b/src/features/database/sql/format.test.ts
@@ -10,7 +10,9 @@ const fmt = (sql: string) => {
describe("formatSql", () => {
it("lays out a query like IDEA", () => {
expect(
- fmt("SELECT u.id,u.name , count( * ) AS n FROM users u LEFT JOIN orders o ON o.user_id=u.id WHERE u.id>1 AND o.total BETWEEN 1 AND 5 OR o.status='x' GROUP BY u.id ORDER BY n DESC LIMIT 10;"),
+ fmt(
+ "SELECT u.id,u.name , count( * ) AS n FROM users u LEFT JOIN orders o ON o.user_id=u.id WHERE u.id>1 AND o.total BETWEEN 1 AND 5 OR o.status='x' GROUP BY u.id ORDER BY n DESC LIMIT 10;",
+ ),
).toBe(
[
"SELECT u.id,",
@@ -29,7 +31,11 @@ describe("formatSql", () => {
});
it("aligns subqueries and CTEs after their parenthesis", () => {
- expect(fmt("with big as (select user_id, total from orders where total > 10) select * from big where exists (select 1 from users u where u.id = big.user_id);")).toBe(
+ expect(
+ fmt(
+ "with big as (select user_id, total from orders where total > 10) select * from big where exists (select 1 from users u where u.id = big.user_id);",
+ ),
+ ).toBe(
[
"with big as (select user_id,",
" total",
diff --git a/src/features/database/sql/format.ts b/src/features/database/sql/format.ts
index e842930a1..9d31530c6 100644
--- a/src/features/database/sql/format.ts
+++ b/src/features/database/sql/format.ts
@@ -25,11 +25,21 @@ interface Item {
}
/** Edits formatting every statement (or those overlapping `range`). */
-export function formatSql(text: string, driver: DbDriver, range: { from: number; to: number } | null = null): SqlEdit[] {
+export function formatSql(
+ text: string,
+ driver: DbDriver,
+ range: { from: number; to: number } | null = null,
+): SqlEdit[] {
const lexed = lex(text, driver);
const items: Item[] = [
...lexed.tokens,
- ...lexed.comments.map((c) => ({ kind: "comment" as const, text: text.slice(c.from, c.to), upper: "", from: c.from, to: c.to })),
+ ...lexed.comments.map((c) => ({
+ kind: "comment" as const,
+ text: text.slice(c.from, c.to),
+ upper: "",
+ from: c.from,
+ to: c.to,
+ })),
].sort((a, b) => a.from - b.from);
const edits: SqlEdit[] = [];
@@ -60,7 +70,23 @@ export function formatSql(text: string, driver: DbDriver, range: { from: number;
return edits;
}
-const NEWLINE_CLAUSES = new Set(["SELECT", "FROM", "WHERE", "GROUP", "HAVING", "ORDER", "LIMIT", "OFFSET", "WINDOW", "RETURNING", "VALUES", "SET", "UNION", "INTERSECT", "EXCEPT"]);
+const NEWLINE_CLAUSES = new Set([
+ "SELECT",
+ "FROM",
+ "WHERE",
+ "GROUP",
+ "HAVING",
+ "ORDER",
+ "LIMIT",
+ "OFFSET",
+ "WINDOW",
+ "RETURNING",
+ "VALUES",
+ "SET",
+ "UNION",
+ "INTERSECT",
+ "EXCEPT",
+]);
const JOIN_START = new Set(["JOIN", "LEFT", "RIGHT", "FULL", "INNER", "CROSS", "NATURAL", "STRAIGHT_JOIN"]);
const JOIN_MODIFIERS = new Set(["LEFT", "RIGHT", "FULL", "INNER", "CROSS", "NATURAL", "OUTER"]);
/** Where a list item continues: the width of `select `, `from `, `set `, `values `. */
@@ -190,11 +216,17 @@ function spaceBefore(prev: Item | null, it: Item, beforePrev: Item | undefined,
/** `into users (` — a column list, written with a space. */
function isInsertTarget(beforePrev: Item | undefined): boolean {
- return beforePrev?.kind === "word" && (beforePrev.upper === "INTO" || beforePrev.upper === "TABLE" || beforePrev.upper === "EXISTS");
+ return (
+ beforePrev?.kind === "word" &&
+ (beforePrev.upper === "INTO" || beforePrev.upper === "TABLE" || beforePrev.upper === "EXISTS")
+ );
}
function isCreateTable(items: Item[]): boolean {
- const words = items.filter((t) => t.kind === "word").slice(0, 3).map((t) => t.upper);
+ const words = items
+ .filter((t) => t.kind === "word")
+ .slice(0, 3)
+ .map((t) => t.upper);
return words[0] === "CREATE" && words.includes("TABLE");
}
diff --git a/src/features/database/sql/params.ts b/src/features/database/sql/params.ts
index e1dd77d75..c773c8b8d 100644
--- a/src/features/database/sql/params.ts
+++ b/src/features/database/sql/params.ts
@@ -38,7 +38,11 @@ export function findParams(text: string, driver: DbDriver, numbered = 0): SqlPar
}
/** `text` with each parameter replaced by its value (empty: `NULL`). */
-export function bindParams(text: string, params: readonly SqlParam[], values: Readonly<Record<string, string>>): string {
+export function bindParams(
+ text: string,
+ params: readonly SqlParam[],
+ values: Readonly<Record<string, string>>,
+): string {
let out = "";
let at = 0;
for (const p of params) {
diff --git a/src/features/database/sql/resolve.ts b/src/features/database/sql/resolve.ts
index f6b0afbef..4287f0c2e 100644
--- a/src/features/database/sql/resolve.ts
+++ b/src/features/database/sql/resolve.ts
@@ -52,10 +52,16 @@ const NOT_COLUMNS = new Set(
const eq = (a: string | null | undefined, b: string | null | undefined) =>
!!a && !!b && a.toLowerCase() === b.toLowerCase();
-export function findTable(model: DbCompletion | null, schema: string | null, name: string): DbCompletionTable | undefined {
+export function findTable(
+ model: DbCompletion | null,
+ schema: string | null,
+ name: string,
+): DbCompletionTable | undefined {
const tables = model?.tables ?? [];
if (schema) return tables.find((t) => eq(t.schema, schema) && eq(t.name, name));
- return tables.find((t) => eq(t.schema, model?.defaultSchema) && eq(t.name, name)) ?? tables.find((t) => eq(t.name, name));
+ return (
+ tables.find((t) => eq(t.schema, model?.defaultSchema) && eq(t.name, name)) ?? tables.find((t) => eq(t.name, name))
+ );
}
const isName = (t: Token | undefined): t is Token => !!t && (t.kind === "word" || t.kind === "quoted");
@@ -223,7 +229,9 @@ export class SqlResolver {
clause !== "values" &&
clause !== "limit" &&
!this.outputAliases(i).has(name.toLowerCase());
- return judged ? { ...span, symbol: null, problem: `Unable to resolve column '${name}'` } : { ...span, symbol: null };
+ return judged
+ ? { ...span, symbol: null, problem: `Unable to resolve column '${name}'` }
+ : { ...span, symbol: null };
}
/** Every unresolved name of the text. */
@@ -273,7 +281,12 @@ export class SqlResolver {
const t = toks[k]!;
if (!isName(t)) continue;
const prev = toks[k - 1]!;
- if ((prev.kind === "word" && prev.upper === "AS") || isP(prev, ")") || prev.kind === "number" || prev.kind === "string")
+ if (
+ (prev.kind === "word" && prev.upper === "AS") ||
+ isP(prev, ")") ||
+ prev.kind === "number" ||
+ prev.kind === "string"
+ )
out.add(identName(t).toLowerCase());
}
return out;
diff --git a/src/features/database/sql/sql.test.ts b/src/features/database/sql/sql.test.ts
index f893f6aa8..907ea5f0d 100644
--- a/src/features/database/sql/sql.test.ts
+++ b/src/features/database/sql/sql.test.ts
@@ -245,7 +245,9 @@ describe("completion candidates", () => {
insert: "id, email, name, created_at",
});
const two = complete("select | from users u join orders o on o.user_id = u.id");
- expect(two.find((x) => x.kind === "columns" && x.tail === "(u)")?.insert).toBe("u.id, u.email, u.name, u.created_at");
+ expect(two.find((x) => x.kind === "columns" && x.tail === "(u)")?.insert).toBe(
+ "u.id, u.email, u.name, u.created_at",
+ );
});
it("names unaliased tables by schema in column rows", () => {
@@ -320,7 +322,10 @@ describe("VALUES parameter info", () => {
return valuesSlot(sql.slice(0, pos) + sql.slice(pos + 1), pos, "sqlite");
};
it("finds the column of the value at the caret", () => {
- expect(slot("insert into users (email, name) values ('a', |)")).toMatchObject({ columns: ["email", "name"], index: 1 });
+ expect(slot("insert into users (email, name) values ('a', |)")).toMatchObject({
+ columns: ["email", "name"],
+ index: 1,
+ });
expect(slot("insert into users values (|)")).toMatchObject({ columns: null, index: 0 });
expect(slot("insert into users (email) values ('a'), (|")).toMatchObject({ index: 0 });
expect(slot("insert into users (email|)")).toBeNull();
@@ -359,7 +364,9 @@ describe("resolve", () => {
});
it("leaves names alone when it cannot judge them", () => {
- expect(problems("select foo from unknown_table;")).toEqual(["unknown_table: Unable to resolve table 'unknown_table'"]);
+ expect(problems("select foo from unknown_table;")).toEqual([
+ "unknown_table: Unable to resolve table 'unknown_table'",
+ ]);
expect(problems("select * from (select * from users) x where x.whatever = 1;")).toEqual([]);
expect(problems("select rowid, * from users;")).toEqual([]);
});
@@ -384,7 +391,12 @@ describe("params", () => {
it("finds parameters per dialect and binds values", () => {
const names = (sql: string, driver: "sqlite" | "postgres" | "mysql" = "sqlite", n = 0) =>
findParams(sql, driver, n).map((p) => p.name);
- expect(names("select * from t where a = :id and b = ? and c = ?3 and d = @x and e = '?' -- ?")).toEqual([":id", "?1", "?3", "@x"]);
+ expect(names("select * from t where a = :id and b = ? and c = ?3 and d = @x and e = '?' -- ?")).toEqual([
+ ":id",
+ "?1",
+ "?3",
+ "@x",
+ ]);
expect(names("select * from t where a = ? and b = ?", "sqlite", 2)).toEqual(["?3", "?4"]);
expect(names("select @x := 1, @@version, ? from t", "mysql")).toEqual(["?1"]);
expect(names("select j ? 'k', $1, a::int from t where b = :name", "postgres")).toEqual(["$1", ":name"]);
diff --git a/src/features/database/vendors.ts b/src/features/database/vendors.ts
index 67246378d..a1e769d78 100644
--- a/src/features/database/vendors.ts
+++ b/src/features/database/vendors.ts
@@ -19,19 +19,63 @@ export interface DbVendor {
export const VENDORS: readonly DbVendor[] = [
{ id: "aurora-mysql", label: "Amazon Aurora MySQL", driver: "mysql", port: 3306, icon: "db-aurora", scheme: "mysql" },
- { id: "redshift", label: "Amazon Redshift", driver: "postgres", port: 5439, icon: "db-redshift", scheme: "redshift", ssl: "require" },
- { id: "cockroachdb", label: "CockroachDB", driver: "postgres", port: 26257, icon: "db-cockroach", scheme: "postgresql" },
+ {
+ id: "redshift",
+ label: "Amazon Redshift",
+ driver: "postgres",
+ port: 5439,
+ icon: "db-redshift",
+ scheme: "redshift",
+ ssl: "require",
+ },
+ {
+ id: "cockroachdb",
+ label: "CockroachDB",
+ driver: "postgres",
+ port: 26257,
+ icon: "db-cockroach",
+ scheme: "postgresql",
+ },
{ id: "greenplum", label: "Greenplum", driver: "postgres", port: 5432, icon: "db-greenplum", scheme: "postgresql" },
{ id: "mariadb", label: "MariaDB", driver: "mysql", port: 3306, icon: "db-mariadb", scheme: "mariadb" },
{ id: "mysql", label: "MySQL", driver: "mysql", port: 3306, icon: "db-mysql", scheme: "mysql" },
{ id: "neon", label: "Neon", driver: "postgres", port: 5432, icon: "db-neon", scheme: "postgresql", ssl: "require" },
- { id: "oceanbase", label: "OceanBase (MySQL mode)", driver: "mysql", port: 2881, icon: "db-oceanbase", scheme: "oceanbase" },
+ {
+ id: "oceanbase",
+ label: "OceanBase (MySQL mode)",
+ driver: "mysql",
+ port: 2881,
+ icon: "db-oceanbase",
+ scheme: "oceanbase",
+ },
{ id: "postgres", label: "PostgreSQL", driver: "postgres", port: 5432, icon: "db-postgres", scheme: "postgresql" },
- { id: "singlestore", label: "SingleStore", driver: "mysql", port: 3306, icon: "db-singlestore", scheme: "singlestore" },
+ {
+ id: "singlestore",
+ label: "SingleStore",
+ driver: "mysql",
+ port: 3306,
+ icon: "db-singlestore",
+ scheme: "singlestore",
+ },
{ id: "sqlite", label: "SQLite", driver: "sqlite", port: null, icon: "db-sqlite", scheme: "sqlite" },
- { id: "supabase", label: "Supabase", driver: "postgres", port: 5432, icon: "db-supabase", scheme: "postgresql", ssl: "require" },
+ {
+ id: "supabase",
+ label: "Supabase",
+ driver: "postgres",
+ port: 5432,
+ icon: "db-supabase",
+ scheme: "postgresql",
+ ssl: "require",
+ },
{ id: "tidb", label: "TiDB", driver: "mysql", port: 4000, icon: "db-tidb", scheme: "mysql" },
- { id: "timescaledb", label: "TimescaleDB", driver: "postgres", port: 5432, icon: "db-timescale", scheme: "postgresql" },
+ {
+ id: "timescaledb",
+ label: "TimescaleDB",
+ driver: "postgres",
+ port: 5432,
+ icon: "db-timescale",
+ scheme: "postgresql",
+ },
{ id: "yugabytedb", label: "YugabyteDB", driver: "postgres", port: 5433, icon: "db-yugabyte", scheme: "postgresql" },
];
diff --git a/src/features/debugger/__tests__/hotswap.test.ts b/src/features/debugger/__tests__/hotswap.test.ts
index 428af3071..a8ffc840b 100644
--- a/src/features/debugger/__tests__/hotswap.test.ts
+++ b/src/features/debugger/__tests__/hotswap.test.ts
@@ -5,7 +5,9 @@ const ipc = vi.hoisted(() => {
return {
ok,
javaBuildWorkspace: vi.fn(() => ok("succeed" as string)),
- debugRedefineClasses: vi.fn(() => ok({ changedClasses: ["com.x.A", "com.x.B"], errorMessage: null as string | null })),
+ debugRedefineClasses: vi.fn(() =>
+ ok({ changedClasses: ["com.x.A", "com.x.B"], errorMessage: null as string | null }),
+ ),
};
});
@@ -36,7 +38,16 @@ function session(id: number, hotCodeReplace: boolean): DebugSession {
name: "App",
adapter: hotCodeReplace ? "java-debug" : "debugpy",
parent: null,
- launch: { name: "App", adapter: "java-debug", request: "launch", program: null, args: [], cwd: "/p/app", env: {}, extraJson: null },
+ launch: {
+ name: "App",
+ adapter: "java-debug",
+ request: "launch",
+ program: null,
+ args: [],
+ cwd: "/p/app",
+ env: {},
+ extraJson: null,
+ },
process: null,
status: "running",
stoppedThread: null,
diff --git a/src/features/debugger/__tests__/launch.test.ts b/src/features/debugger/__tests__/launch.test.ts
index c49746c24..f9e098dd4 100644
--- a/src/features/debugger/__tests__/launch.test.ts
+++ b/src/features/debugger/__tests__/launch.test.ts
@@ -94,25 +94,44 @@ describe("run config → launch config", () => {
expect(extra(node).runtimeExecutable).toBeUndefined();
// A located Node.js (e.g. 22.6+ for TypeScript) is used instead of PATH's.
- const ts = launchConfigFor(rc({ command: "/opt/node22/bin/node", args: ["a.ts"], debugAdapter: "js-debug" }), "/p")!;
+ const ts = launchConfigFor(
+ rc({ command: "/opt/node22/bin/node", args: ["a.ts"], debugAdapter: "js-debug" }),
+ "/p",
+ )!;
expect(ts.program).toBe("/p/a.ts");
expect(extra(ts).runtimeExecutable).toBe("/opt/node22/bin/node");
});
it("js-debug: TypeScript through a runner or type-stripping flag runs as the runtime", () => {
const flag = launchConfigFor(
- rc({ kind: "node", command: "/bin/node", args: ["--experimental-strip-types", "a.ts"], debugAdapter: "js-debug" }),
+ rc({
+ kind: "node",
+ command: "/bin/node",
+ args: ["--experimental-strip-types", "a.ts"],
+ debugAdapter: "js-debug",
+ }),
"/p",
)!;
expect(flag.program).toBeNull();
- expect(extra(flag)).toMatchObject({ runtimeExecutable: "/bin/node", runtimeArgs: ["--experimental-strip-types", "a.ts"] });
- const tsx = launchConfigFor(rc({ kind: "node", command: "npx", args: ["tsx", "a.ts"], debugAdapter: "js-debug" }), "/p")!;
+ expect(extra(flag)).toMatchObject({
+ runtimeExecutable: "/bin/node",
+ runtimeArgs: ["--experimental-strip-types", "a.ts"],
+ });
+ const tsx = launchConfigFor(
+ rc({ kind: "node", command: "npx", args: ["tsx", "a.ts"], debugAdapter: "js-debug" }),
+ "/p",
+ )!;
expect(extra(tsx)).toMatchObject({ runtimeExecutable: "npx", runtimeArgs: ["tsx", "a.ts"] });
});
it("deno: waits on its inspector at a free port that js-debug attaches to", () => {
const l = launchConfigFor(
- rc({ kind: "deno", command: "/bin/deno", args: ["run", "-A", "--inspect", "main.ts", "x"], debugAdapter: "js-debug" }),
+ rc({
+ kind: "deno",
+ command: "/bin/deno",
+ args: ["run", "-A", "--inspect", "main.ts", "x"],
+ debugAdapter: "js-debug",
+ }),
"/p",
)!;
expect(l.adapter).toBe("js-debug");
@@ -123,7 +142,10 @@ describe("run config → launch config", () => {
runtimeArgs: ["run", "--inspect-wait=127.0.0.1:${freePort}", "-A", "main.ts", "x"],
attachSimplePort: "${freePort}",
});
- const test = launchConfigFor(rc({ kind: "deno", command: "deno", args: ["test"], debugAdapter: "js-debug" }), "/p")!;
+ const test = launchConfigFor(
+ rc({ kind: "deno", command: "deno", args: ["test"], debugAdapter: "js-debug" }),
+ "/p",
+ )!;
expect(extra(test).runtimeArgs).toEqual(["test", "--inspect-wait=127.0.0.1:${freePort}"]);
});
@@ -157,12 +179,20 @@ describe("run config → launch config", () => {
expect(test.program).toBe("/p");
// A gutter test / subtest: the package, and `-run` for the test binary.
const one = launchConfigFor(
- rc({ kind: "go", command: "go", args: ["test", "./calc", "-run", "^TestSub$/^zero_case$"], debugAdapter: "delve" }),
+ rc({
+ kind: "go",
+ command: "go",
+ args: ["test", "./calc", "-run", "^TestSub$/^zero_case$"],
+ debugAdapter: "delve",
+ }),
"/p",
)!;
expect(one.program).toBe("/p/calc");
expect(one.args).toEqual(["-test.run", "^TestSub$/^zero_case$"]);
- const eq = launchConfigFor(rc({ kind: "go", command: "go", args: ["test", "-run=^TestA$", "."], debugAdapter: "delve" }), "/p")!;
+ const eq = launchConfigFor(
+ rc({ kind: "go", command: "go", args: ["test", "-run=^TestA$", "."], debugAdapter: "delve" }),
+ "/p",
+ )!;
expect(eq.program).toBe("/p");
expect(eq.args).toEqual(["-test.run", "^TestA$"]);
});
@@ -199,7 +229,13 @@ describe("run config → launch config", () => {
});
it("Godot: the editor's adapter plays the main scene or the chosen one of the project", () => {
- const project = rc({ kind: "godot", command: "/Apps/Godot", args: ["--path", "."], cwd: "game", debugAdapter: "godot" });
+ const project = rc({
+ kind: "godot",
+ command: "/Apps/Godot",
+ args: ["--path", "."],
+ cwd: "game",
+ debugAdapter: "godot",
+ });
const main = launchConfigFor(project, "/p")!;
expect(main).toMatchObject({ adapter: "godot", request: "launch", cwd: "/p/game", program: null });
expect(extra(main)).toEqual({ project: "/p/game", scene: "main" });
diff --git a/src/features/debugger/__tests__/smartStep.test.ts b/src/features/debugger/__tests__/smartStep.test.ts
index b2ef44085..2cab3f4b0 100644
--- a/src/features/debugger/__tests__/smartStep.test.ts
+++ b/src/features/debugger/__tests__/smartStep.test.ts
@@ -19,7 +19,10 @@ vi.mock("@/platform/ipc", async (orig) => {
return {
...real,
call: (p: Promise<unknown>) => p,
- commands: { ...real.commands, debugStepInTarget: (...a: unknown[]) => (ipc.debugStepInTarget(...a), Promise.resolve(null)) },
+ commands: {
+ ...real.commands,
+ debugStepInTarget: (...a: unknown[]) => (ipc.debugStepInTarget(...a), Promise.resolve(null)),
+ },
};
});
@@ -57,7 +60,12 @@ describe("locating Smart Step Into targets", () => {
const line = " total = add(total, square(i))";
const all = [target(0, "square(i)"), target(1, "add(total, square(i))"), target(2, 'print("total", total)')];
expect(targetsOnLine(line, 11, all).map((t) => t.id)).toEqual([0, 1]);
- expect(targetsOnLine(line, 11, [{ ...target(5, "print()"), line: 11 }, { ...target(6, "add()"), line: 12 }]).map((t) => t.id)).toEqual([5]);
+ expect(
+ targetsOnLine(line, 11, [
+ { ...target(5, "print()"), line: 11 },
+ { ...target(6, "add()"), line: 12 },
+ ]).map((t) => t.id),
+ ).toEqual([5]);
expect(targetsOnLine("pass", 0, all)).toBe(all);
});
});
diff --git a/src/features/debugger/editor/execution.ts b/src/features/debugger/editor/execution.ts
index 64da80588..f466e459c 100644
--- a/src/features/debugger/editor/execution.ts
+++ b/src/features/debugger/editor/execution.ts
@@ -3,14 +3,7 @@
* IDEA) and inline values of the frame's locals after line ends.
*/
import { StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
-import {
- Decoration,
- EditorView,
- ViewPlugin,
- WidgetType,
- type DecorationSet,
- type ViewUpdate,
-} from "@codemirror/view";
+import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { useExecutionPoint } from "../state";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
diff --git a/src/features/debugger/editor/smartStep.ts b/src/features/debugger/editor/smartStep.ts
index bd149f125..ec44dfcb7 100644
--- a/src/features/debugger/editor/smartStep.ts
+++ b/src/features/debugger/editor/smartStep.ts
@@ -47,7 +47,10 @@ export function locateStepTargets(lineText: string, line: number, targets: StepI
let to = -1;
if (t.column != null && (t.line == null || t.line === line) && t.column < lineText.length) {
from = t.column;
- to = t.endColumn != null && t.endColumn > from ? Math.min(t.endColumn, lineText.length) : identifierEnd(lineText, from);
+ to =
+ t.endColumn != null && t.endColumn > from
+ ? Math.min(t.endColumn, lineText.length)
+ : identifierEnd(lineText, from);
} else {
const name = calleeName(t.label);
if (!name) return null;
@@ -107,7 +110,9 @@ export function startInlineSmartStep(session: DebugSessionId, thread: number, ta
const ranges = locateStepTargets(doc.line(line + 1).text, line, targets);
if (!ranges || ranges.length < 2) return false;
const first = ranges.findIndex((r) => r.id === targets[0]!.id);
- useOverlays.setState({ smartStep: { session, thread, targets, inline: { path, line, ranges, index: Math.max(0, first) } } });
+ useOverlays.setState({
+ smartStep: { session, thread, targets, inline: { path, line, ranges, index: Math.max(0, first) } },
+ });
editor.view.focus();
return true;
}
diff --git a/src/features/debugger/frames.ts b/src/features/debugger/frames.ts
index c6075ae06..115d602ae 100644
--- a/src/features/debugger/frames.ts
+++ b/src/features/debugger/frames.ts
@@ -12,7 +12,8 @@ export function isLibraryFrame(frame: StackFrame, root: string | null): boolean
}
export type FrameItem =
- { kind: "frame"; frame: StackFrame; library: boolean } | { kind: "hidden"; count: number; key: string };
+ | { kind: "frame"; frame: StackFrame; library: boolean }
+ | { kind: "hidden"; count: number; key: string };
/**
* Groups runs of library frames. The selected frame and the first frame are
diff --git a/src/features/debugger/hotswap.ts b/src/features/debugger/hotswap.ts
index baedf0fae..d13abdb0c 100644
--- a/src/features/debugger/hotswap.ts
+++ b/src/features/debugger/hotswap.ts
@@ -23,7 +23,10 @@ function plural(n: number, word: string) {
}
/** Message for the reload result (IDEA wording). */
-export function hotSwapMessage(changed: number, errors: string[]): { level: "info" | "error"; title: string; body?: string } {
+export function hotSwapMessage(
+ changed: number,
+ errors: string[],
+): { level: "info" | "error"; title: string; body?: string } {
if (errors.length) return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
if (changed === 0) return { level: "info", title: "Loaded classes are up to date. Nothing to reload." };
return { level: "info", title: tx`${plural(changed, "class")} reloaded` };
diff --git a/src/features/debugger/ui/DebugToolWindow.module.css b/src/features/debugger/ui/DebugToolWindow.module.css
index 3367f7440..e9cf9c704 100644
--- a/src/features/debugger/ui/DebugToolWindow.module.css
+++ b/src/features/debugger/ui/DebugToolWindow.module.css
@@ -237,7 +237,7 @@
white-space: pre-wrap;
word-break: break-word;
-webkit-user-select: text;
-cursor: text;
+ cursor: text;
-webkit-user-select: text;
user-select: text;
outline: none;
diff --git a/src/features/github/PullRequestsView.tsx b/src/features/github/PullRequestsView.tsx
index 766209d48..7469fd553 100644
--- a/src/features/github/PullRequestsView.tsx
+++ b/src/features/github/PullRequestsView.tsx
@@ -136,7 +136,9 @@ function Filters() {
<Select
value={query.state}
options={STATES.map((value) => ({ value, label: t(`github.prState.${value}`) }))}
- onChange={(state) => setQuery({ state })} aria-label="State" />
+ onChange={(state) => setQuery({ state })}
+ aria-label="State"
+ />
<Checkbox checked={query.authorMe} onChange={(authorMe) => setQuery({ authorMe })} label="Mine" />
<Checkbox
checked={query.reviewRequested}
diff --git a/src/features/github/github.test.ts b/src/features/github/github.test.ts
index 269dffbaa..0e9fbe715 100644
--- a/src/features/github/github.test.ts
+++ b/src/features/github/github.test.ts
@@ -2,7 +2,13 @@ import { describe, expect, it } from "vitest";
import type { PrCheck, PrReviewComment, PullRequestDetails } from "@/platform/ipc";
import { checksSummary, checksText, diffNotes, fileDiffData, relativeTime, reviewThreads, stateLabel } from "./model";
-const comment = (id: number, path: string, line: number | null, inReplyTo: number | null = null, side = "RIGHT"): PrReviewComment => ({
+const comment = (
+ id: number,
+ path: string,
+ line: number | null,
+ inReplyTo: number | null = null,
+ side = "RIGHT",
+): PrReviewComment => ({
id,
inReplyTo,
path,
@@ -57,7 +63,12 @@ describe("pull request model", () => {
});
it("threads replies under their root, ordered by file and line", () => {
- const threads = reviewThreads([comment(1, "b.ts", 9), comment(2, "a.ts", 5), comment(3, "b.ts", 9, 1), comment(4, "b.ts", 9, 3)]);
+ const threads = reviewThreads([
+ comment(1, "b.ts", 9),
+ comment(2, "a.ts", 5),
+ comment(3, "b.ts", 9, 1),
+ comment(4, "b.ts", 9, 3),
+ ]);
expect(threads.map((t) => [t.root.id, t.replies.map((r) => r.id)])).toEqual([
[2, []],
[1, [3, 4]],
@@ -65,7 +76,12 @@ describe("pull request model", () => {
});
it("turns current comments into diff notes", () => {
- const notes = diffNotes("a.ts", [comment(1, "a.ts", 5), comment(2, "a.ts", null), comment(3, "a.ts", 2, null, "LEFT"), comment(4, "b.ts", 1)]);
+ const notes = diffNotes("a.ts", [
+ comment(1, "a.ts", 5),
+ comment(2, "a.ts", null),
+ comment(3, "a.ts", 2, null, "LEFT"),
+ comment(4, "b.ts", 1),
+ ]);
expect(notes.map((n) => [n.side, n.line])).toEqual([
["right", 4],
["left", 1],
@@ -80,7 +96,12 @@ describe("pull request model", () => {
root: "/repo",
files: [{ path: "src/new.ts", kind: "renamed" as const, oldPath: "src/old.ts" }],
};
- const renamed = fileDiffData(pr, { path: "src/new.ts", additions: 1, deletions: 0, changeType: "RENAMED" }, revs, []);
+ const renamed = fileDiffData(
+ pr,
+ { path: "src/new.ts", additions: 1, deletions: 0, changeType: "RENAMED" },
+ revs,
+ [],
+ );
expect(renamed.path).toBe("/repo/src/new.ts");
expect(renamed.left).toMatchObject({ type: "rev", rev: revs.base, path: "/repo/src/old.ts" });
expect(renamed.right).toMatchObject({ type: "rev", rev: revs.head });
diff --git a/src/features/github/index.ts b/src/features/github/index.ts
index db1caf23e..f5ee2feb0 100644
--- a/src/features/github/index.ts
+++ b/src/features/github/index.ts
@@ -63,7 +63,14 @@ export function activate(): () => void {
when: WHEN,
run: () => openInBrowser(),
},
- { id: "github.refresh", title: "Refresh Pull Requests", category: "GitHub", icon: "refresh", when: WHEN, run: () => refreshAll() },
+ {
+ id: "github.refresh",
+ title: "Refresh Pull Requests",
+ category: "GitHub",
+ icon: "refresh",
+ when: WHEN,
+ run: () => refreshAll(),
+ },
]),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) resetGithub();
diff --git a/src/features/github/model.ts b/src/features/github/model.ts
index eeab618fb..d5dd4fec3 100644
--- a/src/features/github/model.ts
+++ b/src/features/github/model.ts
@@ -1,5 +1,13 @@
/** Pure helpers of the Pull Requests view (labels, check summaries, review threads, diff inputs). */
-import type { ChangedFile, PrCheck, PrDiffRevisions, PrFile, PrReviewComment, PullRequestDetails, PullRequestSummary } from "@/platform/ipc";
+import type {
+ ChangedFile,
+ PrCheck,
+ PrDiffRevisions,
+ PrFile,
+ PrReviewComment,
+ PullRequestDetails,
+ PullRequestSummary,
+} from "@/platform/ipc";
import { t, tx } from "@/platform/i18n";
/** Keyed, not source text: "Open" as a state reads differently from the "Open" action in some locales. */
@@ -107,7 +115,9 @@ export function reviewThreads(comments: readonly PrReviewComment[]): ReviewThrea
}
}
return threads.sort(
- (a, b) => a.root.path.localeCompare(b.root.path) || (a.root.line ?? a.root.originalLine ?? 0) - (b.root.line ?? b.root.originalLine ?? 0),
+ (a, b) =>
+ a.root.path.localeCompare(b.root.path) ||
+ (a.root.line ?? a.root.originalLine ?? 0) - (b.root.line ?? b.root.originalLine ?? 0),
);
}
@@ -124,15 +134,24 @@ export interface DiffNote {
export function diffNotes(path: string, comments: readonly PrReviewComment[]): DiffNote[] {
return comments
.filter((c) => c.path === path && c.line != null)
- .map((c) => ({ side: c.side === "LEFT" ? "left" : "right", line: c.line! - 1, author: c.author, body: c.body, date: c.createdAt }));
+ .map((c) => ({
+ side: c.side === "LEFT" ? "left" : "right",
+ line: c.line! - 1,
+ author: c.author,
+ body: c.body,
+ date: c.createdAt,
+ }));
}
-type Side =
- | { type: "rev"; rev: string; path?: string; label?: string }
- | { type: "text"; text: string; label: string };
+type Side = { type: "rev"; rev: string; path?: string; label?: string } | { type: "text"; text: string; label: string };
/** `DiffData` for one changed file of a pull request (merge base ↔ head), with its review comments. */
-export function fileDiffData(pr: PullRequestDetails, file: PrFile, revs: PrDiffRevisions, comments: readonly PrReviewComment[]) {
+export function fileDiffData(
+ pr: PullRequestDetails,
+ file: PrFile,
+ revs: PrDiffRevisions,
+ comments: readonly PrReviewComment[],
+) {
const root = revs.root;
const changed: ChangedFile | undefined = revs.files.find((f) => f.path === file.path);
const added = file.changeType === "ADDED" || changed?.kind === "added";
@@ -146,7 +165,15 @@ export function fileDiffData(pr: PullRequestDetails, file: PrFile, revs: PrDiffR
path: changed?.oldPath ? `${root}/${changed.oldPath}` : undefined,
label: `${pr.summary.baseRef} (${revs.base.slice(0, 8)})`,
};
- const right: Side = deleted ? { type: "text", text: "", label: "(deleted)" } : { type: "rev", rev: revs.head, label: `#${n} ${pr.summary.headRef}` };
+ const right: Side = deleted
+ ? { type: "text", text: "", label: "(deleted)" }
+ : { type: "rev", rev: revs.head, label: `#${n} ${pr.summary.headRef}` };
const name = file.path.slice(file.path.lastIndexOf("/") + 1);
- return { path: `${root}/${file.path}`, left, right, title: `#${n}: ${name}`, annotations: diffNotes(file.path, comments) };
+ return {
+ path: `${root}/${file.path}`,
+ left,
+ right,
+ title: `#${n}: ${name}`,
+ annotations: diffNotes(file.path, comments),
+ };
}
diff --git a/src/features/github/ops.ts b/src/features/github/ops.ts
index 27805772d..0bf22f868 100644
--- a/src/features/github/ops.ts
+++ b/src/features/github/ops.ts
@@ -5,7 +5,16 @@ import { call, commands } from "@/platform/ipc";
import { notifications, toolWindowService } from "@/workbench/contributions";
import { createPullRequestDialog, numberDialog, reviewDialog } from "./dialogs";
import { fileDiffData } from "./model";
-import { diffRevisions, errorMessage, loadDetails, loadList, readyRepo, refreshAll, useGithub, withBusy } from "./store";
+import {
+ diffRevisions,
+ errorMessage,
+ loadDetails,
+ loadList,
+ readyRepo,
+ refreshAll,
+ useGithub,
+ withBusy,
+} from "./store";
export const WINDOW = "pullRequests";
@@ -34,14 +43,20 @@ function notReady(): boolean {
export async function checkoutPullRequest(number: number) {
const done = await withBusy(`Checking out #${number}…`, (r, out) => call(commands.ghPrCheckout(r, number, out)));
if (done !== null)
- notifications().notify({ group: "vcs", level: "info", title: `Checked out pull request #${number}`, key: "github-checkout" });
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ title: `Checked out pull request #${number}`,
+ key: "github-checkout",
+ });
}
/** Git › GitHub › Checkout Pull Request…: the selected one, else asks for a number. */
export async function checkoutAction(arg: unknown) {
if (useGithub.getState().availability?.kind !== "ready") await refreshAll();
if (notReady()) return;
- const n = typeof arg === "number" ? arg : (useGithub.getState().selected ?? (await numberDialog("Checkout Pull Request")));
+ const n =
+ typeof arg === "number" ? arg : (useGithub.getState().selected ?? (await numberDialog("Checkout Pull Request")));
if (n) await checkoutPullRequest(n);
}
@@ -62,10 +77,21 @@ export async function submitReview(number: number, initial: ReviewEvent) {
if (!r) return;
try {
await call(commands.ghPrReview(number, r.event, r.body));
- notifications().notify({ group: "vcs", level: "info", title: `Review submitted on #${number}`, key: "github-review" });
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ title: `Review submitted on #${number}`,
+ key: "github-review",
+ });
await loadDetails(number);
} catch (e) {
- notifications().notify({ group: "vcs", level: "error", title: "Could not submit the review", body: errorMessage(e), key: "github-review" });
+ notifications().notify({
+ group: "vcs",
+ level: "error",
+ title: "Could not submit the review",
+ body: errorMessage(e),
+ key: "github-review",
+ });
}
}
@@ -75,7 +101,13 @@ export async function addComment(number: number, body: string): Promise<boolean>
await loadDetails(number);
return true;
} catch (e) {
- notifications().notify({ group: "vcs", level: "error", title: "Could not add the comment", body: errorMessage(e), key: "github-comment" });
+ notifications().notify({
+ group: "vcs",
+ level: "error",
+ title: "Could not add the comment",
+ body: errorMessage(e),
+ key: "github-comment",
+ });
return false;
}
}
@@ -92,12 +124,21 @@ export async function createPullRequest() {
const info = await call(commands.vcsBranchInfo(null));
head = info.head;
needsPush = !info.upstream || info.ahead > 0;
- if (head) title = head.replace(/^[^/]+\//, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
+ if (head)
+ title = head
+ .replace(/^[^/]+\//, "")
+ .replace(/[-_]+/g, " ")
+ .replace(/^\w/, (c) => c.toUpperCase());
} catch {
// Not a git repository: gh will explain.
}
if (!head) {
- notifications().notify({ group: "vcs", level: "warning", title: "Check out a branch to create a pull request from", key: "github-create" });
+ notifications().notify({
+ group: "vcs",
+ level: "warning",
+ title: "Check out a branch to create a pull request from",
+ key: "github-create",
+ });
return;
}
if (head === repo?.defaultBranch) {
diff --git a/src/features/github/store.ts b/src/features/github/store.ts
index 8b25b3de2..02da43d3d 100644
--- a/src/features/github/store.ts
+++ b/src/features/github/store.ts
@@ -113,7 +113,12 @@ let detailSeq = 0;
export async function loadDetails(number: number): Promise<void> {
const seq = ++detailSeq;
const same = useGithub.getState().details?.summary.number === number;
- useGithub.setState({ selected: number, detailsLoading: true, detailsError: null, ...(same ? {} : { details: null, reviewComments: [] }) });
+ useGithub.setState({
+ selected: number,
+ detailsLoading: true,
+ detailsError: null,
+ ...(same ? {} : { details: null, reviewComments: [] }),
+ });
try {
const [details, comments] = await Promise.all([
call(commands.ghPrView(number)),
@@ -136,9 +141,17 @@ export function select(number: number | null) {
}
/** Runs a cancellable, streaming gh operation shown in the view's banner. */
-export async function withBusy<T>(title: string, run: (request: RequestId, out: Channel<string>) => Promise<T>): Promise<T | null> {
+export async function withBusy<T>(
+ title: string,
+ run: (request: RequestId, out: Channel<string>) => Promise<T>,
+): Promise<T | null> {
if (useGithub.getState().busy) {
- notifications().notify({ group: "vcs", level: "info", title: "Another GitHub operation is still running", key: "github-busy" });
+ notifications().notify({
+ group: "vcs",
+ level: "info",
+ title: "Another GitHub operation is still running",
+ key: "github-busy",
+ });
return null;
}
const request = nextRequestId();
@@ -149,7 +162,13 @@ export async function withBusy<T>(title: string, run: (request: RequestId, out:
return await run(request, out);
} catch (e) {
if (!isCancelled(e))
- notifications().notify({ group: "vcs", level: "error", title: `${title.replace(/…$/, "")} failed`, body: errorMessage(e), key: "github-op" });
+ notifications().notify({
+ group: "vcs",
+ level: "error",
+ title: `${title.replace(/…$/, "")} failed`,
+ body: errorMessage(e),
+ key: "github-op",
+ });
return null;
} finally {
useGithub.setState({ busy: null });
@@ -166,7 +185,14 @@ const diffCache = new Map<string, PrDiffRevisions>();
/** Another project: start over. */
export function resetGithub() {
diffCache.clear();
- useGithub.setState({ availability: null, list: [], selected: null, details: null, reviewComments: [], query: DEFAULT_QUERY });
+ useGithub.setState({
+ availability: null,
+ list: [],
+ selected: null,
+ details: null,
+ reviewComments: [],
+ query: DEFAULT_QUERY,
+ });
}
/** Fetches what the local repository lacks to diff `pr`, once per head commit. */
@@ -176,7 +202,17 @@ export async function diffRevisions(pr: PullRequestDetails): Promise<PrDiffRevis
if (hit) return hit;
const repo = readyRepo();
const revs = await withBusy(`Fetching #${pr.summary.number}…`, (r, out) =>
- call(commands.ghPrPrepareDiff(r, pr.summary.number, pr.headOid, pr.baseOid, pr.summary.baseRef, repo?.nameWithOwner ?? "", out)),
+ call(
+ commands.ghPrPrepareDiff(
+ r,
+ pr.summary.number,
+ pr.headOid,
+ pr.baseOid,
+ pr.summary.baseRef,
+ repo?.nameWithOwner ?? "",
+ out,
+ ),
+ ),
);
if (revs) diffCache.set(key, revs);
return revs;
diff --git a/src/features/http-client/format.ts b/src/features/http-client/format.ts
index 13a3c43f5..2dc94ab7f 100644
--- a/src/features/http-client/format.ts
+++ b/src/features/http-client/format.ts
@@ -30,7 +30,20 @@ export function prettyJson(body: string): string {
}
const VOID_HTML = new Set([
- "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr",
+ "area",
+ "base",
+ "br",
+ "col",
+ "embed",
+ "hr",
+ "img",
+ "input",
+ "link",
+ "meta",
+ "param",
+ "source",
+ "track",
+ "wbr",
]);
/**
diff --git a/src/features/http-client/httpClient.test.ts b/src/features/http-client/httpClient.test.ts
index ee3877cdf..5bb4ba7c2 100644
--- a/src/features/http-client/httpClient.test.ts
+++ b/src/features/http-client/httpClient.test.ts
@@ -24,12 +24,23 @@ describe("response bodies", () => {
it("re-indents XML, keeping text-only elements on one line", () => {
expect(prettyMarkup('<?xml version="1.0"?><a><b>1</b><c/><d><e>x</e></d><f></f></a>')).toBe(
- ['<?xml version="1.0"?>', "<a>", " <b>1</b>", " <c/>", " <d>", " <e>x</e>", " </d>", " <f></f>", "</a>"].join("\n"),
+ [
+ '<?xml version="1.0"?>',
+ "<a>",
+ " <b>1</b>",
+ " <c/>",
+ " <d>",
+ " <e>x</e>",
+ " </d>",
+ " <f></f>",
+ "</a>",
+ ].join("\n"),
);
});
it("re-indents HTML with void elements and raw script contents", () => {
- const html = "<html><head><meta charset=utf-8><script>if (a < b) { x(); }</script></head><body><p>Hi</p><br></body></html>";
+ const html =
+ "<html><head><meta charset=utf-8><script>if (a < b) { x(); }</script></head><body><p>Hi</p><br></body></html>";
expect(prettyMarkup(html, true)).toBe(
[
"<html>",
@@ -69,14 +80,14 @@ describe("http highlighting", () => {
}
it("tags separators, methods, URLs, headers, variables and comments", () => {
- const t = tokens("### Users\n# @name list\nGET https://{{host}}/users\nAccept: json\n\n{\"a\": 1}\n");
+ const t = tokens('### Users\n# @name list\nGET https://{{host}}/users\nAccept: json\n\n{"a": 1}\n');
const has = (name: string, text: string) => t.some(([n, s]) => n.includes(name) && s === text);
expect(has("heading", "### Users")).toBe(true);
expect(has("keyword", "GET")).toBe(true);
expect(has("link", "https://")).toBe(true);
expect(has("variableName", "{{host}}")).toBe(true);
expect(has("propertyName", "Accept")).toBe(true);
- expect(has("string", ' json')).toBe(true);
+ expect(has("string", " json")).toBe(true);
expect(has("string", '"a"')).toBe(true);
expect(has("number", "1")).toBe(true);
expect(has("meta", "# @name")).toBe(true);
diff --git a/src/features/http-client/store.ts b/src/features/http-client/store.ts
index 16afd399b..0ff936b95 100644
--- a/src/features/http-client/store.ts
+++ b/src/features/http-client/store.ts
@@ -108,7 +108,11 @@ export async function selectEntry(id: string) {
const ex = await call(commands.httpHistoryGet(id));
useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } }));
} catch (e) {
- notifications().notify({ level: "error", title: "Cannot open the response", body: e instanceof Error ? e.message : String(e) });
+ notifications().notify({
+ level: "error",
+ title: "Cannot open the response",
+ body: e instanceof Error ? e.message : String(e),
+ });
}
}
diff --git a/src/features/libraries/index.ts b/src/features/libraries/index.ts
index 5923f7afd..cee6b3623 100644
--- a/src/features/libraries/index.ts
+++ b/src/features/libraries/index.ts
@@ -56,7 +56,8 @@ const MANIFESTS = new Set([
export function touchesManifest(paths: readonly string[]): boolean {
return paths.some(
(p) =>
- !/[\\/]node_modules[\\/]/.test(p) && MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1)),
+ !/[\\/]node_modules[\\/]/.test(p) &&
+ MANIFESTS.has(p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1)),
);
}
diff --git a/src/features/libraries/libraries.test.ts b/src/features/libraries/libraries.test.ts
index d7596c44f..7d64dc1b2 100644
--- a/src/features/libraries/libraries.test.ts
+++ b/src/features/libraries/libraries.test.ts
@@ -28,11 +28,13 @@ describe("External Libraries", () => {
it("gives each ecosystem's groups their icon", () => {
const root = librariesRoot(
- ["jdk", "nodeCore", "nodeModules", "rust", "cargo", "go", "goModules", "maven", "gradle", "other"].map((kind) => ({
- name: kind,
- kind,
- roots: [{ name: "r", path: `/libs/${kind}` }],
- })),
+ ["jdk", "nodeCore", "nodeModules", "rust", "cargo", "go", "goModules", "maven", "gradle", "other"].map(
+ (kind) => ({
+ name: kind,
+ kind,
+ roots: [{ name: "r", path: `/libs/${kind}` }],
+ }),
+ ),
)!;
expect(root.children?.map((g) => g.icon)).toEqual([
"file-java",
diff --git a/src/features/macros/MacrosDialog.tsx b/src/features/macros/MacrosDialog.tsx
index 19512bc1e..17e2f9a42 100644
--- a/src/features/macros/MacrosDialog.tsx
+++ b/src/features/macros/MacrosDialog.tsx
@@ -60,7 +60,14 @@ function EditMacrosDialog({ onClose }: { onClose: () => void }) {
};
const remove = async () => {
if (!macro) return;
- if (await confirm({ title: "Delete Macro", message: tx`Delete the macro '${macro.name}'?`, ok: "Delete", icon: "warning" }))
+ if (
+ await confirm({
+ title: "Delete Macro",
+ message: tx`Delete the macro '${macro.name}'?`,
+ ok: "Delete",
+ icon: "warning",
+ })
+ )
deleteMacro(macro.name);
};
diff --git a/src/features/macros/editorKeys.ts b/src/features/macros/editorKeys.ts
index 7e1fb2f66..3f140fef7 100644
--- a/src/features/macros/editorKeys.ts
+++ b/src/features/macros/editorKeys.ts
@@ -81,7 +81,9 @@ export const EDITOR_KEY_COMMANDS: Record<string, Command> = {
};
/** The recorded name of a key event, or null when it is not an editor key a macro records. */
-export function editorKeyName(e: Pick<KeyboardEvent, "key" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey">): string | null {
+export function editorKeyName(
+ e: Pick<KeyboardEvent, "key" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey">,
+): string | null {
const name = [e.metaKey && "Meta", e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.key]
.filter(Boolean)
.join("+");
diff --git a/src/features/macros/index.ts b/src/features/macros/index.ts
index 3c483796f..e1ff97ba9 100644
--- a/src/features/macros/index.ts
+++ b/src/features/macros/index.ts
@@ -98,19 +98,17 @@ function registerSavedMacroActions(): () => void {
names = key;
dispose();
dispose = registerActions(
- saved.map(
- (m): Action => ({
- id: playActionId(m.name),
- title: m.name,
- category: "Macros",
- keywords: ["macro", "play"],
- when: "!macroRecording",
- run: () => {
- const macro = useMacros.getState().saved.find((x) => x.name === m.name);
- if (macro) return playMacro(macro.steps, macro.name);
- },
- }),
- ),
+ saved.map((m): Action => ({
+ id: playActionId(m.name),
+ title: m.name,
+ category: "Macros",
+ keywords: ["macro", "play"],
+ when: "!macroRecording",
+ run: () => {
+ const macro = useMacros.getState().saved.find((x) => x.name === m.name);
+ if (macro) return playMacro(macro.steps, macro.name);
+ },
+ })),
);
};
sync();
@@ -179,7 +177,10 @@ export function activate(): () => void {
keywords: ["macro", "replay"],
when: "!macroRecording && macrosSaved",
run: async () => {
- const name = await chooseItem({ title: "Play Saved Macro", items: useMacros.getState().saved.map((m) => m.name) });
+ const name = await chooseItem({
+ title: "Play Saved Macro",
+ items: useMacros.getState().saved.map((m) => m.name),
+ });
const macro = useMacros.getState().saved.find((m) => m.name === name);
if (macro) await playMacro(macro.steps, macro.name);
},
diff --git a/src/features/macros/model.test.ts b/src/features/macros/model.test.ts
index 556e839d4..37fdf6466 100644
--- a/src/features/macros/model.test.ts
+++ b/src/features/macros/model.test.ts
@@ -56,7 +56,10 @@ describe("macros", () => {
it("drops malformed stored steps", () => {
localStorage.setItem(
STORAGE_KEY,
- JSON.stringify({ last: [{ kind: "text", text: "a" }, { kind: "action" }, { kind: "action", id: "x", arg: {} }], saved: [{ name: "" }] }),
+ JSON.stringify({
+ last: [{ kind: "text", text: "a" }, { kind: "action" }, { kind: "action", id: "x", arg: {} }],
+ saved: [{ name: "" }],
+ }),
);
_reloadMacros();
expect(useMacros.getState().last).toEqual([{ kind: "text", text: "a" }]);
diff --git a/src/features/macros/model.ts b/src/features/macros/model.ts
index 398ffbe83..061ab2dce 100644
--- a/src/features/macros/model.ts
+++ b/src/features/macros/model.ts
@@ -32,7 +32,8 @@ export const STORAGE_KEY = "openidea.macros.v1";
function isStep(v: unknown): v is MacroStep {
if (!v || typeof v !== "object") return false;
const s = v as Record<string, unknown>;
- if (s.kind === "action") return typeof s.id === "string" && ["undefined", "string", "number", "boolean"].includes(typeof s.arg);
+ if (s.kind === "action")
+ return typeof s.id === "string" && ["undefined", "string", "number", "boolean"].includes(typeof s.arg);
if (s.kind === "text") return typeof s.text === "string";
return s.kind === "key" && typeof s.key === "string";
}
@@ -84,7 +85,8 @@ export function recordStep(step: MacroStep) {
/** An action's argument when it can be stored (plain values only). */
export function storableArg(arg: unknown): string | number | boolean | undefined | null {
if (arg === undefined) return undefined;
- if (typeof arg === "string" || typeof arg === "boolean" || (typeof arg === "number" && Number.isFinite(arg))) return arg;
+ if (typeof arg === "string" || typeof arg === "boolean" || (typeof arg === "number" && Number.isFinite(arg)))
+ return arg;
return null;
}
@@ -147,7 +149,11 @@ export async function playSteps(
try {
for (const step of macroSteps) {
const ok =
- step.kind === "action" ? await run.action(step.id, step.arg) : step.kind === "text" ? run.text(step.text) : run.key(step.key);
+ step.kind === "action"
+ ? await run.action(step.id, step.arg)
+ : step.kind === "text"
+ ? run.text(step.text)
+ : run.key(step.key);
if (!ok) return false;
// Let the UI settle (popups open, editors mount) before the next step.
await new Promise((r) => setTimeout(r, 0));
diff --git a/src/features/plugins/__tests__/plugins.test.tsx b/src/features/plugins/__tests__/plugins.test.tsx
index c6412dfbb..7e637357a 100644
--- a/src/features/plugins/__tests__/plugins.test.tsx
+++ b/src/features/plugins/__tests__/plugins.test.tsx
@@ -184,7 +184,10 @@ describe("bridge events", () => {
useThemeOverride.setState({ theme: "dark-hc" });
applyThemeAttributes("dark-hc", root);
expect([root.dataset.theme, root.dataset.contrast]).toEqual(["dark", "high"]);
- applyPluginTheme({ pluginId: "p", theme: { id: "l", name: "L", kind: "light", tokens: { "--accent": "#123456" } } });
+ applyPluginTheme({
+ pluginId: "p",
+ theme: { id: "l", name: "L", kind: "light", tokens: { "--accent": "#123456" } },
+ });
expect([root.dataset.theme, root.dataset.contrast]).toEqual(["light", undefined]);
expect(root.dataset.pluginThemeKind).toBe("light");
// The appearance runtime re-applying the built-in theme keeps the plugin's base.
diff --git a/src/features/profiler/executor.ts b/src/features/profiler/executor.ts
index 6d2e630d6..ce5a3a593 100644
--- a/src/features/profiler/executor.ts
+++ b/src/features/profiler/executor.ts
@@ -1,7 +1,12 @@
/** The "Profile" executor: runs a configuration under a sampling profiler, then opens the snapshot. */
import { executeAction } from "@/platform/actions";
import { call, commands, isTauri, type ProfilerInstall, type RunConfig } from "@/platform/ipc";
-import { notifications, toolWindowService, type ExecutorLaunch, type RunExecutorContribution } from "@/workbench/contributions";
+import {
+ notifications,
+ toolWindowService,
+ type ExecutorLaunch,
+ type RunExecutorContribution,
+} from "@/workbench/contributions";
import { profilerSupports } from "./model";
import { addSnapshot } from "./store";
import { tx } from "@/platform/i18n";
@@ -49,7 +54,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
}
const plan = await call(commands.profilerPrepare(config));
if (plan.status === "unsupported") {
- notifications().notify({ group: "run", level: "info", key: "profiler-unsupported", title: `Cannot profile '${config.name}'`, body: plan.reason });
+ notifications().notify({
+ group: "run",
+ level: "info",
+ key: "profiler-unsupported",
+ title: `Cannot profile '${config.name}'`,
+ body: plan.reason,
+ });
return null;
}
if (plan.status === "missingTool") {
@@ -71,7 +82,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
/* no workbench (tests) */
}
} catch (e) {
- notifications().notify({ group: "run", level: "error", key: "profiler-done", title: `No profile for '${config.name}'`, body: errorText(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ key: "profiler-done",
+ title: `No profile for '${config.name}'`,
+ body: errorText(e),
+ });
}
})();
},
diff --git a/src/features/profiler/index.ts b/src/features/profiler/index.ts
index 3e8dafdd4..5f8f7069b 100644
--- a/src/features/profiler/index.ts
+++ b/src/features/profiler/index.ts
@@ -41,7 +41,8 @@ export function activate(): () => void {
icon: "profile",
when: "projectOpen",
keywords: ["profiler", "flame graph"],
- run: ({ arg }) => executeAction("run.withExecutor", { executor: "profiler", context: arg ?? true }).then(() => undefined),
+ run: ({ arg }) =>
+ executeAction("run.withExecutor", { executor: "profiler", context: arg ?? true }).then(() => undefined),
},
]),
useProject.subscribe((s, prev) => {
diff --git a/src/features/profiler/model.ts b/src/features/profiler/model.ts
index f3417dc8e..6fe270c9d 100644
--- a/src/features/profiler/model.ts
+++ b/src/features/profiler/model.ts
@@ -25,7 +25,11 @@ export function profilerSupports(config: Pick<RunConfig, "command" | "args" | "k
}
function isLinux(): boolean {
- return typeof navigator !== "undefined" && /linux/i.test(navigator.platform || navigator.userAgent) && !/android/i.test(navigator.userAgent);
+ return (
+ typeof navigator !== "undefined" &&
+ /linux/i.test(navigator.platform || navigator.userAgent) &&
+ !/android/i.test(navigator.userAgent)
+ );
}
/** `12.3 ms`, `1.2 s`, `340 samples`. */
diff --git a/src/features/profiler/profiler.test.ts b/src/features/profiler/profiler.test.ts
index 26ba35f52..e5f721554 100644
--- a/src/features/profiler/profiler.test.ts
+++ b/src/features/profiler/profiler.test.ts
@@ -23,7 +23,18 @@ const profile: Profile = {
};
function cfg(command: string, args: string[], kind = "shell"): RunConfig {
- return { id: "c", name: "c", kind, command, args, cwd: null, env: {}, detected: true, isTest: false, debugAdapter: null };
+ return {
+ id: "c",
+ name: "c",
+ kind,
+ command,
+ args,
+ cwd: null,
+ env: {},
+ detected: true,
+ isTest: false,
+ debugAdapter: null,
+ };
}
describe("profiler model", () => {
diff --git a/src/features/profiler/store.ts b/src/features/profiler/store.ts
index d6a293d62..f7139b2dd 100644
--- a/src/features/profiler/store.ts
+++ b/src/features/profiler/store.ts
@@ -28,7 +28,10 @@ let seq = 0;
export function addSnapshot(name: string, profile: Profile): Snapshot {
const snapshot: Snapshot = { id: `profile${++seq}`, name, createdAt: Date.now(), profile };
- useProfiler.setState((s) => ({ snapshots: [snapshot, ...s.snapshots].slice(0, MAX_SNAPSHOTS), activeId: snapshot.id }));
+ useProfiler.setState((s) => ({
+ snapshots: [snapshot, ...s.snapshots].slice(0, MAX_SNAPSHOTS),
+ activeId: snapshot.id,
+ }));
return snapshot;
}
diff --git a/src/features/project-tree/ProjectView.test.tsx b/src/features/project-tree/ProjectView.test.tsx
index 476a83a28..897995bc5 100644
--- a/src/features/project-tree/ProjectView.test.tsx
+++ b/src/features/project-tree/ProjectView.test.tsx
@@ -57,7 +57,10 @@ function setup() {
within(tree)
.queryAllByRole("treeitem")
.map((r) => r.textContent);
- const row = (label: string) => within(tree).getAllByRole("treeitem").find((r) => r.textContent?.startsWith(label))!;
+ const row = (label: string) =>
+ within(tree)
+ .getAllByRole("treeitem")
+ .find((r) => r.textContent?.startsWith(label))!;
return { tree, rows, row };
}
@@ -225,7 +228,9 @@ describe("ProjectView", () => {
act(() => useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src"]) }));
await waitFor(() => expect(rows()).toContain("App.kt"));
await act(() => fs.createFile("/w/acme/src/New.kt"));
- await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "New.kt", "Util.kt", "README.md"]));
+ await waitFor(() =>
+ expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "New.kt", "Util.kt", "README.md"]),
+ );
});
it("renders large folders virtualized", async () => {
diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx
index 69dd5c014..a0bf123ab 100644
--- a/src/features/project-tree/ProjectView.tsx
+++ b/src/features/project-tree/ProjectView.tsx
@@ -96,7 +96,9 @@ export const treeHandle: { current: TreeHandle | null } = { current: null };
export function showNewPopup(): boolean {
const lead = treeHandle.current?.leadKey();
const row = lead ? document.querySelector<HTMLElement>(`[data-project-key="${CSS.escape(lead)}"]`) : null;
- const rect = (row ?? document.querySelector<HTMLElement>('[role="tree"][aria-label="Project"]'))?.getBoundingClientRect();
+ const rect = (
+ row ?? document.querySelector<HTMLElement>('[role="tree"][aria-label="Project"]')
+ )?.getBoundingClientRect();
if (!rect) return false;
openNewPopup({ x: rect.left + 24, y: rect.bottom }, newMenuItems(targetFolder()));
return true;
@@ -261,7 +263,11 @@ const Row = memo(function Row({
onDoubleClick={(e) => onDoubleClick(node, e)}
onPointerDown={(e) => onPointerDown(node, e)}
>
- <Icon name={icon} size={16} className={clsx(styles.icon, node.dir && styles.folderIcon, dimIcon && styles.faded)} />
+ <Icon
+ name={icon}
+ size={16}
+ className={clsx(styles.icon, node.dir && styles.folderIcon, dimIcon && styles.faded)}
+ />
{isEditing && editing ? (
<InlineEditor
editing={editing}
@@ -310,7 +316,8 @@ function folderAt(container: HTMLElement | null, x: number, y: number): { key: s
const el = document.elementFromPoint(x, y);
if (!el || !container.contains(el)) return null;
const row = el.closest("[data-row]");
- const content = (row ?? el).querySelector<HTMLElement>("[data-project-path]") ?? el.closest<HTMLElement>("[data-project-path]");
+ const content =
+ (row ?? el).querySelector<HTMLElement>("[data-project-path]") ?? el.closest<HTMLElement>("[data-project-path]");
if (!content) return null;
const path = content.dataset.projectPath!;
if (content.dataset.dir) return { key: content.dataset.projectKey!, path };
@@ -410,7 +417,9 @@ export function ProjectView() {
if (target.every((n) => n.group)) return;
// Contributed groups may read the file first (bounded wait).
const at = { x: e.clientX, y: e.clientY };
- void prepareMenuGroups("projectView", menuGroupContext(target)).then(() => showContextMenu(at, contextMenuItems(target)));
+ void prepareMenuGroups("projectView", menuGroupContext(target)).then(() =>
+ showContextMenu(at, contextMenuItems(target)),
+ );
}, []);
const focusTree = useCallback(() => requestAnimationFrame(() => handle.current?.focus()), []);
@@ -630,7 +639,9 @@ export function ProjectView() {
onBlur={() => setContext("projectViewFocus", false)}
>
{!model.roots.length && (
- <div className={styles.empty}>{txTemplate(`Nothing to show in ${VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "this view"}`)}</div>
+ <div className={styles.empty}>
+ {txTemplate(`Nothing to show in ${VIEW_MODES.find(([id]) => id === mode)?.[1] ?? "this view"}`)}
+ </div>
)}
<Tree<ProjectNode>
aria-label="Project"
diff --git a/src/features/project-tree/RefactoringPreview.tsx b/src/features/project-tree/RefactoringPreview.tsx
index 65ef5afe7..00886ca96 100644
--- a/src/features/project-tree/RefactoringPreview.tsx
+++ b/src/features/project-tree/RefactoringPreview.tsx
@@ -55,7 +55,17 @@ async function readLines(path: string): Promise<string[] | null> {
}
}
-function FileGroup({ file, root, included, onToggle }: { file: EditFile; root: string; included: boolean; onToggle: (on: boolean) => void }) {
+function FileGroup({
+ file,
+ root,
+ included,
+ onToggle,
+}: {
+ file: EditFile;
+ root: string;
+ included: boolean;
+ onToggle: (on: boolean) => void;
+}) {
const [lines, setLines] = useState<string[] | null>(null);
useEffect(() => {
let live = true;
@@ -64,7 +74,9 @@ function FileGroup({ file, root, included, onToggle }: { file: EditFile; root: s
live = false;
};
}, [file.path]);
- const sorted = [...file.edits].sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col);
+ const sorted = [...file.edits].sort(
+ (a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col,
+ );
return (
<li className={styles.previewFile}>
<div className={styles.previewFileRow}>
diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts
index 621d6805c..b3bf0d213 100644
--- a/src/features/project-tree/actions.ts
+++ b/src/features/project-tree/actions.ts
@@ -417,7 +417,11 @@ export function registerProjectActions(): () => void {
when: FOCUS,
run: ({ arg }) => {
const files = nodesFrom(arg).filter((n) => !n.dir);
- if (files.length === 2) delegate("diff.compareFiles", files.map((f) => f.path));
+ if (files.length === 2)
+ delegate(
+ "diff.compareFiles",
+ files.map((f) => f.path),
+ );
else if (files[0]) delegate("diff.compareWith", files[0].path);
},
},
diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts
index c1613ac0e..082af17f2 100644
--- a/src/features/project-tree/contextMenu.test.ts
+++ b/src/features/project-tree/contextMenu.test.ts
@@ -52,7 +52,10 @@ let disposers: Array<() => void> = [];
beforeEach(() => {
useProjectTree.setState({ root: ROOT });
- useProject.setState({ project: { name: "p", root: ROOT, isGit: true, settings: {} } as never, settings: {} as never });
+ useProject.setState({
+ project: { name: "p", root: ROOT, isGit: true, settings: {} } as never,
+ settings: {} as never,
+ });
disposers = [
registerActions(OTHER_ACTIONS.map((id) => ({ id, title: id, run: () => undefined }))),
registerMenuGroup({
@@ -121,7 +124,8 @@ describe("project view context menu", () => {
expect(l).not.toContain("Refactor");
expect(l).not.toContain("Mark Directory as");
const resolved = resolveMenuItems(items);
- for (const label of ["Cut", "Copy", "Delete…"]) expect(resolved.find((r) => r.label === label)?.disabled).toBe(true);
+ for (const label of ["Cut", "Copy", "Delete…"])
+ expect(resolved.find((r) => r.label === label)?.disabled).toBe(true);
});
it("drops project-only groups for scratch files", () => {
@@ -141,7 +145,10 @@ describe("project view context menu", () => {
it("never shows an empty submenu", () => {
disposers.forEach((d) => d());
disposers = [];
- useProject.setState({ project: { name: "p", root: ROOT, isGit: true, settings: {} } as never, settings: {} as never });
+ useProject.setState({
+ project: { name: "p", root: ROOT, isGit: true, settings: {} } as never,
+ settings: {} as never,
+ });
const l = labels(contextMenuItems([node(`${ROOT}/a.py`)]));
expect(l).not.toContain("Git");
expect(l).not.toContain("Local History");
diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts
index 80ae286a8..1e7df7846 100644
--- a/src/features/project-tree/contextMenu.ts
+++ b/src/features/project-tree/contextMenu.ts
@@ -111,7 +111,12 @@ function act(action: string, arg?: unknown, label?: string): MenuItem | null {
}
/** Runs another feature's action directly (the project view decides availability), with its shortcut. */
-function delegated(id: string, arg: unknown, label: string, extra: { icon?: string; shortcut?: string } = {}): MenuItem | null {
+function delegated(
+ id: string,
+ arg: unknown,
+ label: string,
+ extra: { icon?: string; shortcut?: string } = {},
+): MenuItem | null {
if (!getAction(id)) return null;
return { id, label, ...extra, shortcut: extra.shortcut ?? shortcutLabel(id), run: () => void delegate(id, arg) };
}
@@ -328,9 +333,21 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
// IDEA: Compare With… (one file) / Compare Files (two files).
if (files.length === 2 && nodes.length === 2)
- push(delegated("diff.compareFiles", files.map((f) => f.path), "Compare Files", { icon: "diff" }));
+ push(
+ delegated(
+ "diff.compareFiles",
+ files.map((f) => f.path),
+ "Compare Files",
+ { icon: "diff" },
+ ),
+ );
else if (singleFile)
- push(delegated("diff.compareWith", singleFile.path, "Compare With…", { icon: "diff", shortcut: keyLabel("project.compareWith") }));
+ push(
+ delegated("diff.compareWith", singleFile.path, "Compare With…", {
+ icon: "diff",
+ shortcut: keyLabel("project.compareWith"),
+ }),
+ );
if (inProject && single?.dir && !single.root && !single.placeholder) {
const current = directoryRole(single.path);
@@ -375,15 +392,27 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
id: "copyPath",
label: "Copy Path/Reference…",
submenu: [
- { id: "abs", label: "Absolute Path", shortcut: keyLabel("project.copyAbsolutePath"), run: () => void copyPaths("absolute", nodes) },
+ {
+ id: "abs",
+ label: "Absolute Path",
+ shortcut: keyLabel("project.copyAbsolutePath"),
+ run: () => void copyPaths("absolute", nodes),
+ },
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
],
},
{ kind: "separator" },
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
!!folder && { kind: "separator" },
- submenu("openIn", "Open In", [{ id: "finder", label: revealLabel(), icon: "external-link", run: () => void revealInFinder(nodes) }]),
- single && !single.dir && delegated("diff.compareWith", single.path, "Compare With…", { icon: "diff", shortcut: keyLabel("project.compareWith") }),
+ submenu("openIn", "Open In", [
+ { id: "finder", label: revealLabel(), icon: "external-link", run: () => void revealInFinder(nodes) },
+ ]),
+ single &&
+ !single.dir &&
+ delegated("diff.compareWith", single.path, "Compare With…", {
+ icon: "diff",
+ shortcut: keyLabel("project.compareWith"),
+ }),
];
return items.filter((i): i is MenuItem => !!i);
}
diff --git a/src/features/project-tree/extraRoots.test.ts b/src/features/project-tree/extraRoots.test.ts
index 402461ed5..67e3bc6de 100644
--- a/src/features/project-tree/extraRoots.test.ts
+++ b/src/features/project-tree/extraRoots.test.ts
@@ -36,7 +36,12 @@ describe("withExtraRoots", () => {
["/data/scratches", [entry("/data/scratches/scratch.java")]],
]);
const base = buildModel({ path: "/p", name: "proj" }, listings, DEFAULT_TREE_OPTIONS);
- const m = withExtraRoots(base, [{ path: "/data/scratches", label: "Scratches", icon: "scratches" }], listings, DEFAULT_TREE_OPTIONS);
+ const m = withExtraRoots(
+ base,
+ [{ path: "/data/scratches", label: "Scratches", icon: "scratches" }],
+ listings,
+ DEFAULT_TREE_OPTIONS,
+ );
expect(m.roots.map((r) => [r.label, r.root, r.icon])).toEqual([
["proj", true, undefined],
["Scratches", true, "scratches"],
@@ -60,7 +65,12 @@ describe("project view with a scratches root", () => {
const fs = new MemoryFs({ "/p/README.md": "x", "/data/scratches/scratch.py": "x" }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "proj");
- unregister = registerProjectViewRoot({ id: "scratches", label: "Scratches", icon: "scratches", path: "/data/scratches" });
+ unregister = registerProjectViewRoot({
+ id: "scratches",
+ label: "Scratches",
+ icon: "scratches",
+ path: "/data/scratches",
+ });
});
afterEach(() => {
unregister();
diff --git a/src/features/project-tree/fileRefactor.test.tsx b/src/features/project-tree/fileRefactor.test.tsx
index fe8e57f31..34eb34f94 100644
--- a/src/features/project-tree/fileRefactor.test.tsx
+++ b/src/features/project-tree/fileRefactor.test.tsx
@@ -27,7 +27,10 @@ describe("file refactoring edits", () => {
files: [edit("/p/main.ts", [0, 20, 26, "./b/util"]), { kind: "rename", from: "/p/a", to: "/p/b" }],
};
const text: WorkspaceEdit = {
- files: [edit("/p/main.ts", [0, 22, 26, "b/util"], [3, 3, 10, "b/util.ts"]), edit("/p/README.md", [1, 0, 9, "b/util.ts"])],
+ files: [
+ edit("/p/main.ts", [0, 22, 26, "b/util"], [3, 3, 10, "b/util.ts"]),
+ edit("/p/README.md", [1, 0, 9, "b/util.ts"]),
+ ],
};
const merged = mergeEdits(lsp, text);
expect(merged.files.map((f) => f.kind === "edit" && [f.path, f.edits.length])).toEqual([
@@ -54,7 +57,10 @@ describe("runFileRefactoring", () => {
provideNotificationService({ notify });
backend = {
calls: [],
- edits: vi.fn(async () => ({ edit: { files: [edit("/p/main.ts", [0, 20, 26, "./b/util"])] }, errors: ["tsserver: busy"] })),
+ edits: vi.fn(async () => ({
+ edit: { files: [edit("/p/main.ts", [0, 20, 26, "./b/util"])] },
+ errors: ["tsserver: busy"],
+ })),
move: vi.fn(async (moves: FileMove[], e: WorkspaceEdit) => {
backend.calls.push(`move ${moves.length} ${e.files.length}`);
return 7;
@@ -117,8 +123,8 @@ describe("runFileRefactoring", () => {
expect(backend.edits).not.toHaveBeenCalled();
const ctrl = new AbortController();
ctrl.abort();
- expect(await runFileRefactoring(moves, { references: true, textOccurrences: false }, "Move", { signal: ctrl.signal })).toBe(
- "cancelled",
- );
+ expect(
+ await runFileRefactoring(moves, { references: true, textOccurrences: false }, "Move", { signal: ctrl.signal }),
+ ).toBe("cancelled");
});
});
diff --git a/src/features/project-tree/fileRefactor.ts b/src/features/project-tree/fileRefactor.ts
index 79fb54835..63e3a65e1 100644
--- a/src/features/project-tree/fileRefactor.ts
+++ b/src/features/project-tree/fileRefactor.ts
@@ -81,7 +81,10 @@ export function memoryRefactorBackend(): FileRefactorBackend {
done.push(m);
}
} catch (e) {
- for (const m of done.reverse()) await fs().rename(m.to, m.from).catch(() => {});
+ for (const m of done.reverse())
+ await fs()
+ .rename(m.to, m.from)
+ .catch(() => {});
throw e;
}
records.set(++next, moves);
@@ -142,7 +145,9 @@ export function mergeEdits(lsp: WorkspaceEdit, text: WorkspaceEdit): WorkspaceEd
/** Whether `edit` changes files other than the moved ones (IDEA previews those refactorings). */
export function touchesOtherFiles(edit: WorkspaceEdit, moves: readonly FileMove[]): boolean {
- return edit.files.some((f) => f.kind === "edit" && f.edits.length && !moves.some((m) => isSameOrInside(f.path, m.from)));
+ return edit.files.some(
+ (f) => f.kind === "edit" && f.edits.length && !moves.some((m) => isSameOrInside(f.path, m.from)),
+ );
}
// ---------------------------------------------------------------------------
@@ -263,7 +268,11 @@ export async function runFileRefactoring(
notifications().notify({
level: "info",
title,
- body: !edited ? undefined : edited === 1 ? tx`Updated references in ${edited} file` : tx`Updated references in ${edited} files`,
+ body: !edited
+ ? undefined
+ : edited === 1
+ ? tx`Updated references in ${edited} file`
+ : tx`Updated references in ${edited} files`,
actions: [{ label: "Undo", run: () => void undoFileRefactoring(id) }],
key: "project.refactor.done",
});
diff --git a/src/features/project-tree/fs.ts b/src/features/project-tree/fs.ts
index 7e9bf13ed..6aee22bc2 100644
--- a/src/features/project-tree/fs.ts
+++ b/src/features/project-tree/fs.ts
@@ -37,8 +37,7 @@ export const tauriFs: ProjectFs = {
type MemNode = { kind: "file"; size: number } | { kind: "dir" };
-const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) =>
- new IpcError({ kind, message });
+const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) => new IpcError({ kind, message });
/** Minimal in-memory file system with the backend's semantics (no overwrite, folders first). */
export class MemoryFs implements ProjectFs {
@@ -112,7 +111,8 @@ export class MemoryFs implements ProjectFs {
async rename(from: string, to: string) {
if (!this.nodes.has(from)) throw err("notFound", `${from} not found`);
- if (this.nodes.has(to) && from.toLowerCase() !== to.toLowerCase()) throw err("alreadyExists", `${to} already exists`);
+ if (this.nodes.has(to) && from.toLowerCase() !== to.toLowerCase())
+ throw err("alreadyExists", `${to} already exists`);
if (isInside(to, from)) throw err("invalidInput", "cannot move a folder into itself");
for (const p of [...this.nodes.keys()]) {
if (p !== from && !isInside(p, from)) continue;
diff --git a/src/features/project-tree/model.test.ts b/src/features/project-tree/model.test.ts
index 1ae5aa79d..e7909b514 100644
--- a/src/features/project-tree/model.test.ts
+++ b/src/features/project-tree/model.test.ts
@@ -13,7 +13,17 @@ import {
const entry = (path: string, kind: "file" | "dir" = "file", extra: Partial<FileEntry> = {}): FileEntry => {
const name = path.slice(path.lastIndexOf("/") + 1);
- return { name, path, kind, size: 0, mtimeMs: 1, ignored: false, excluded: false, hidden: name.startsWith("."), ...extra };
+ return {
+ name,
+ path,
+ kind,
+ size: 0,
+ mtimeMs: 1,
+ ignored: false,
+ excluded: false,
+ hidden: name.startsWith("."),
+ ...extra,
+ };
};
const ROOT = { path: "/r", name: "acme" };
diff --git a/src/features/project-tree/model.ts b/src/features/project-tree/model.ts
index f35d38003..ed2c63736 100644
--- a/src/features/project-tree/model.ts
+++ b/src/features/project-tree/model.ts
@@ -286,13 +286,26 @@ export function withExtraRoots(
if (ns === null && model.roots.some((r) => !r.group && isSameOrInside(path, r.path))) return null;
const sub = buildModel({ path, name: extra.label }, listings, opts, ro ? null : placeholder);
const subRoot = sub.roots[0]!;
- const rootNode: ProjectNode = { ...subRoot, key: rekey(subRoot.key), root: !parentKey, icon: extra.icon, detail: extra.detail };
+ const rootNode: ProjectNode = {
+ ...subRoot,
+ key: rekey(subRoot.key),
+ root: !parentKey,
+ icon: extra.icon,
+ detail: extra.detail,
+ };
if (ro) rootNode.readOnly = true;
const nodes = new Map<string, ProjectNode>();
for (const [k, v] of sub.byKey)
- nodes.set(k, k === subRoot.key ? rootNode : ns !== null || ro ? { ...v, key: rekey(k), readOnly: ro || v.readOnly } : v);
+ nodes.set(
+ k,
+ k === subRoot.key ? rootNode : ns !== null || ro ? { ...v, key: rekey(k), readOnly: ro || v.readOnly } : v,
+ );
for (const n of nodes.values()) out.byKey.set(n.key, n);
- for (const [k, v] of sub.children) out.children.set(rekey(k), v.map((n) => nodes.get(n.key) ?? n));
+ for (const [k, v] of sub.children)
+ out.children.set(
+ rekey(k),
+ v.map((n) => nodes.get(n.key) ?? n),
+ );
for (const [p, k] of sub.keyOfPath) if (!out.keyOfPath.has(p)) out.keyOfPath.set(p, rekey(k));
return rootNode;
}
@@ -341,7 +354,11 @@ export function withReadOnlyFolders(model: TreeModel, folders: readonly string[]
}
if (!changed) return model;
const children = new Map<string, ProjectNode[]>();
- for (const [k, kids] of model.children) children.set(k, kids.map((n) => byKey.get(n.key) ?? n));
+ for (const [k, kids] of model.children)
+ children.set(
+ k,
+ kids.map((n) => byKey.get(n.key) ?? n),
+ );
return { roots: model.roots.map((n) => byKey.get(n.key) ?? n), children, byKey, keyOfPath: model.keyOfPath };
}
@@ -387,7 +404,12 @@ export function buildPathsModel(roots: readonly ExtraRoot[], paths: readonly str
const ensureRoot = (r: ExtraRoot & { path: string }, rank: number) => {
const existing = byKey.get(r.path);
if (existing) return existing;
- const n = node(r.path, r.label, true, { root: true, icon: r.icon || undefined, detail: r.detail, readOnly: r.readOnly });
+ const n = node(r.path, r.label, true, {
+ root: true,
+ icon: r.icon || undefined,
+ detail: r.detail,
+ readOnly: r.readOnly,
+ });
rootNodes.push([rank, n]);
return n;
};
@@ -396,7 +418,8 @@ export function buildPathsModel(roots: readonly ExtraRoot[], paths: readonly str
if (byKey.has(path)) continue;
let rank = -1;
for (let i = 0; i < folders.length; i++)
- if (isInside(path, folders[i]!.path) && (rank < 0 || folders[i]!.path.length > folders[rank]!.path.length)) rank = i;
+ if (isInside(path, folders[i]!.path) && (rank < 0 || folders[i]!.path.length > folders[rank]!.path.length))
+ rank = i;
const root =
rank >= 0
? ensureRoot(folders[rank]!, rank)
diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts
index 1c8b54213..73d841800 100644
--- a/src/features/project-tree/operations.ts
+++ b/src/features/project-tree/operations.ts
@@ -358,7 +358,11 @@ export async function safeToDelete(files: string[]): Promise<boolean> {
result = await fileUsages(files, abort.signal);
} catch {
if (user.choice) return user.choice === "skip";
- notifications().notify({ level: "warning", title: "Usage search did not finish; nothing was deleted", key: "project.safeDelete" });
+ notifications().notify({
+ level: "warning",
+ title: "Usage search did not finish; nothing was deleted",
+ key: "project.safeDelete",
+ });
return false;
} finally {
clearTimeout(timer);
@@ -385,7 +389,12 @@ export async function findFileUsages(path: string) {
return;
}
if (result.status !== "ok")
- notifications().notify({ level: "info", title: `Cannot find usages of '${name}'`, body: result.reason, group: "search" });
+ notifications().notify({
+ level: "info",
+ title: `Cannot find usages of '${name}'`,
+ body: result.reason,
+ group: "search",
+ });
else if (!result.usages.length)
notifications().notify({ level: "info", title: `No usages of '${name}' found`, group: "search" });
else viewUsages(name, result.usages);
@@ -487,7 +496,8 @@ export async function paste(target = targetFolder()) {
// win over ours — unless they are the copy we handed to the OS ourselves.
if (external.length && !sameFiles(external, clipboard?.paths)) return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) return;
- const isDir = (p: string) => get().listings.has(p) || currentModel().byKey.get(currentModel().keyOfPath.get(p) ?? p)?.dir === true;
+ const isDir = (p: string) =>
+ get().listings.has(p) || currentModel().byKey.get(currentModel().keyOfPath.get(p) ?? p)?.dir === true;
const single = clipboard.paths.length === 1 && isDir(clipboard.paths[0]!);
if (!clipboard.cut) return openCopyDialogFor(clipboard.paths, target, single);
const paths = clipboard.paths.filter((p) => parentOf(p) !== target);
@@ -506,7 +516,11 @@ async function pasteFromOsClipboard(paths: string[], target: string) {
/** The same files, as the clipboard keeps them (`/`-separated, any order). */
function sameFiles(files: string[], paths: string[] | undefined): boolean {
if (!paths || files.length !== paths.length) return false;
- const key = (list: string[]) => list.map((p) => (caseInsensitive ? p.toLowerCase() : p)).sort().join("\n");
+ const key = (list: string[]) =>
+ list
+ .map((p) => (caseInsensitive ? p.toLowerCase() : p))
+ .sort()
+ .join("\n");
return key(files) === key(paths);
}
@@ -554,7 +568,8 @@ export async function transfer(
errors.push(`${name}: cannot copy a folder into itself`);
continue;
}
- const srcIsDir = get().listings.has(src) || currentModel().byKey.get(currentModel().keyOfPath.get(src) ?? src)?.dir === true;
+ const srcIsDir =
+ get().listings.has(src) || currentModel().byKey.get(currentModel().keyOfPath.get(src) ?? src)?.dir === true;
const finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
const to = joinPath(target, finalName);
try {
@@ -613,10 +628,12 @@ export async function dropPaths(paths: string[], target: string, copy: boolean)
if (!movable.length) return;
// IDEA opens the Move refactoring dialog for drops inside the project.
if (!copy) {
- const node = movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
+ const node =
+ movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
return openMoveDialogFor(movable, target, node?.dir);
}
- const node = movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
+ const node =
+ movable.length === 1 ? currentModel().byKey.get(currentModel().keyOfPath.get(movable[0]!) ?? "") : undefined;
openCopyDialogFor(movable, target, node?.dir);
}
diff --git a/src/features/project-tree/packages.ts b/src/features/project-tree/packages.ts
index 5131b2749..510b106f3 100644
--- a/src/features/project-tree/packages.ts
+++ b/src/features/project-tree/packages.ts
@@ -6,7 +6,8 @@ const JVM_BUILD = /(^|\/)(pom\.xml|build\.gradle(\.kts)?)$/;
const PY_BUILD = /(^|\/)(pyproject\.toml|setup\.py|setup\.cfg|Pipfile|requirements\.txt)$/;
const JVM_DIR = /(^|\/)(java|kotlin|scala|groovy)$/;
-const moduleDir = (buildFile: string) => (buildFile.includes("/") ? buildFile.slice(0, buildFile.lastIndexOf("/")) : "");
+const moduleDir = (buildFile: string) =>
+ buildFile.includes("/") ? buildFile.slice(0, buildFile.lastIndexOf("/")) : "";
const within = (rel: string, dir: string) => !dir || rel === dir || rel.startsWith(`${dir}/`);
/**
diff --git a/src/features/project-tree/roots.test.ts b/src/features/project-tree/roots.test.ts
index e9b37e92b..6f16cf41b 100644
--- a/src/features/project-tree/roots.test.ts
+++ b/src/features/project-tree/roots.test.ts
@@ -68,7 +68,10 @@ describe("creating packages", () => {
fs = new MemoryFs({ "/p/src/main/java/App.java": "x", "/p/pkg/__init__.py": "" }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "p");
- useProject.setState({ project: { name: "p", root: "/p", isGit: false, settings: {} } as never, settings: {} as never });
+ useProject.setState({
+ project: { name: "p", root: "/p", isGit: false, settings: {} } as never,
+ settings: {} as never,
+ });
useProjectRoots.setState({ root: "/p", detected: MAVEN });
});
afterEach(() => {
diff --git a/src/features/project-tree/selectIn.test.ts b/src/features/project-tree/selectIn.test.ts
index 0c8bcdc53..046b34807 100644
--- a/src/features/project-tree/selectIn.test.ts
+++ b/src/features/project-tree/selectIn.test.ts
@@ -17,7 +17,11 @@ afterEach(() => {
describe("Select In (⌥F1)", () => {
it("lists the project view, contributed targets, Finder and the terminal", () => {
disposers.push(
- registerMenuGroup({ id: "test.selectIn", menus: ["selectIn"], items: () => [{ label: "Structure", run: () => {} }] }),
+ registerMenuGroup({
+ id: "test.selectIn",
+ menus: ["selectIn"],
+ items: () => [{ label: "Structure", run: () => {} }],
+ }),
registerActions([{ id: "terminal.openAt", title: "Open Terminal At", run: () => {} }]),
);
expect(labels(selectInTargets("/p/src/a.ts"))).toEqual([
diff --git a/src/features/project-tree/store.ts b/src/features/project-tree/store.ts
index 95a9dc265..df7d4c975 100644
--- a/src/features/project-tree/store.ts
+++ b/src/features/project-tree/store.ts
@@ -189,16 +189,36 @@ export function selectModel(s: ProjectTreeState): TreeModel {
if (s.root) {
if (s.mode === "projectFiles") model = project();
else if (s.mode === "scratches")
- model = withExtraRoots(EMPTY_MODEL, contributed.filter((r) => r.scope === "scratches"), s.listings, s.options, placeholder);
+ model = withExtraRoots(
+ EMPTY_MODEL,
+ contributed.filter((r) => r.scope === "scratches"),
+ s.listings,
+ s.options,
+ placeholder,
+ );
else if (files)
- model = buildPathsModel([{ path: s.root, label: s.name, icon: "" }, ...extraFolders(contributed)], files, s.options.foldersFirst);
+ model = buildPathsModel(
+ [{ path: s.root, label: s.name, icon: "" }, ...extraFolders(contributed)],
+ files,
+ s.options.foldersFirst,
+ );
else model = withExtraRoots(project(), contributed, s.listings, s.options, placeholder);
const libraries = extraFolders(contributed).flatMap((r) =>
r.readOnly && r.path !== undefined && isSameOrInside(r.path, s.root!) ? [r.path] : [],
);
model = withReadOnlyFolders(model, libraries);
}
- memo = { root: s.root, name: s.name, listings: s.listings, options: s.options, editing: s.editing, mode: s.mode, files, extras, model };
+ memo = {
+ root: s.root,
+ name: s.name,
+ listings: s.listings,
+ options: s.options,
+ editing: s.editing,
+ mode: s.mode,
+ files,
+ extras,
+ model,
+ };
return model;
}
@@ -240,7 +260,12 @@ const autoExpanded = new Set<string>();
/** "Project" restores the persisted expansion; other panes start with their roots open. */
function initialExpanded(root: string | null, mode: ViewMode): Set<string> {
if (!root || isFilteredMode(mode)) return new Set();
- if (mode === "scratches") return new Set(projectViewRoots(useProjectViewRoots.getState().roots).flatMap((r) => (r.scope === "scratches" && r.path ? [r.path] : [])));
+ if (mode === "scratches")
+ return new Set(
+ projectViewRoots(useProjectViewRoots.getState().roots).flatMap((r) =>
+ r.scope === "scratches" && r.path ? [r.path] : [],
+ ),
+ );
const persisted = mode === "project" ? (readJson<string[]>(expandedKey(root)) ?? []) : [];
const expanded = new Set(persisted.filter((p) => isSameOrInside(p, root)));
expanded.add(root);
@@ -479,7 +504,7 @@ export function isReadOnlyPath(path: string): boolean {
/** Group node keys above the node `key`, outermost first. */
function groupAncestors(model: TreeModel, key: string): string[] {
const out: string[] = [];
- for (let child = key; ; ) {
+ for (let child = key; ;) {
let parent: string | null = null;
for (const [k, kids] of model.children)
if (k.startsWith(GROUP_PREFIX) && kids.some((n) => n.key === child)) {
diff --git a/src/features/project-tree/viewModes.test.ts b/src/features/project-tree/viewModes.test.ts
index a0f040a77..9e0e7ea71 100644
--- a/src/features/project-tree/viewModes.test.ts
+++ b/src/features/project-tree/viewModes.test.ts
@@ -83,7 +83,11 @@ describe("withExtraRoots groups", () => {
["site-packages", undefined, true, false, pyKey("/p/.venv/lib/site-packages"), "/p/.venv/lib/site-packages"],
]);
const os = m.byKey.get(pyKey("/py/lib/python3.12/os.py"))!;
- expect([os.readOnly, os.path, pathOfKey(os.key)]).toEqual([true, "/py/lib/python3.12/os.py", "/py/lib/python3.12/os.py"]);
+ expect([os.readOnly, os.path, pathOfKey(os.key)]).toEqual([
+ true,
+ "/py/lib/python3.12/os.py",
+ "/py/lib/python3.12/os.py",
+ ]);
expect(m.children.get(pyKey("/py/lib/python3.12"))![0]).toBe(os);
expect(m.keyOfPath.get("/py/lib/python3.12/os.py")).toBe(os.key);
});
@@ -117,7 +121,12 @@ describe("buildPathsModel", () => {
describe("localChangedPaths", () => {
it("lists change-list files, all lists or one, optionally without deleted ones", () => {
const lists = [
- { id: "default", name: "Changes", active: true, files: [{ path: "/p/b.ts" }, { path: "/p/gone.ts", deleted: true }] },
+ {
+ id: "default",
+ name: "Changes",
+ active: true,
+ files: [{ path: "/p/b.ts" }, { path: "/p/gone.ts", deleted: true }],
+ },
{ id: "ui", name: "UI", active: false, files: [{ path: "/p/a.ts" }] },
];
expect(localChangedPaths(lists, null, true)).toEqual(["/p/a.ts", "/p/b.ts"]);
@@ -260,7 +269,9 @@ describe("project view modes", () => {
const ids = contextMenuItems([projectFile]).map((i) => ("id" in i ? i.id : i.kind));
expect(ids).not.toContain("delete");
expect(ids).not.toContain("rename");
- expect(contextMenuItems([m.byKey.get("/p/.venv/pyvenv.cfg")!]).map((i) => ("id" in i ? i.id : i.kind))).toContain("delete");
+ expect(contextMenuItems([m.byKey.get("/p/.venv/pyvenv.cfg")!]).map((i) => ("id" in i ? i.id : i.kind))).toContain(
+ "delete",
+ );
});
it("expands library folders in their own namespace", async () => {
diff --git a/src/features/remote-dev/ConnectDialog.tsx b/src/features/remote-dev/ConnectDialog.tsx
index 50a813178..ef8426fd0 100644
--- a/src/features/remote-dev/ConnectDialog.tsx
+++ b/src/features/remote-dev/ConnectDialog.tsx
@@ -73,7 +73,12 @@ function ConnectDialog() {
onClose={closeConnectDialog}
width={560}
buttons={[
- { label: connecting ? "Connecting…" : "Open", role: "default", disabled: !ready, onClick: () => void connect() },
+ {
+ label: connecting ? "Connecting…" : "Open",
+ role: "default",
+ disabled: !ready,
+ onClick: () => void connect(),
+ },
{ label: "Cancel", role: "cancel" },
]}
>
@@ -85,9 +90,7 @@ function ConnectDialog() {
}}
>
<p className={styles.hint}>
- {tx(
- "The project runs on the remote host; the IDE backend is installed there on first use.",
- )}
+ {tx("The project runs on the remote host; the IDE backend is installed there on first use.")}
</p>
<label className={styles.label}>{tx("SSH configuration:")}</label>
<div className={styles.row}>
diff --git a/src/features/run-anything/model.test.ts b/src/features/run-anything/model.test.ts
index d6ed5ab45..2bafac8e7 100644
--- a/src/features/run-anything/model.test.ts
+++ b/src/features/run-anything/model.test.ts
@@ -1,6 +1,15 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { RunAnythingProvider } from "@/workbench/contributions";
-import { buildRows, clearHistory, MAX_HISTORY, matches, pushHistory, readHistory, shellCommand, shellRunConfig } from "./model";
+import {
+ buildRows,
+ clearHistory,
+ MAX_HISTORY,
+ matches,
+ pushHistory,
+ readHistory,
+ shellCommand,
+ shellRunConfig,
+} from "./model";
beforeEach(() => localStorage.clear());
@@ -30,7 +39,8 @@ describe("run anything", () => {
{
id: "npm",
group: "npm scripts",
- items: (q) => [{ key: "dev", label: "npm run dev", icon: "run", run: () => {} }].filter((i) => matches(i.label, q)),
+ items: (q) =>
+ [{ key: "dev", label: "npm run dev", icon: "run", run: () => {} }].filter((i) => matches(i.label, q)),
},
{
id: "broken",
diff --git a/src/features/run-anything/model.ts b/src/features/run-anything/model.ts
index 6a5f5389e..b454cfac5 100644
--- a/src/features/run-anything/model.ts
+++ b/src/features/run-anything/model.ts
@@ -14,7 +14,9 @@ const GROUP_LIMIT = 8;
export function readHistory(scope: string): string[] {
try {
const v: unknown = JSON.parse(localStorage.getItem(HISTORY_PREFIX + scope) ?? "[]");
- return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && !!x.trim()).slice(0, MAX_HISTORY) : [];
+ return Array.isArray(v)
+ ? v.filter((x): x is string => typeof x === "string" && !!x.trim()).slice(0, MAX_HISTORY)
+ : [];
} catch {
return [];
}
@@ -41,7 +43,9 @@ export function clearHistory(scope: string) {
}
}
-export type Row = { kind: "section"; key: string; label: string } | { kind: "item"; key: string; item: RunAnythingItem; group: string };
+export type Row =
+ | { kind: "section"; key: string; label: string }
+ | { kind: "item"; key: string; item: RunAnythingItem; group: string };
/** Case-insensitive: every word of `query` occurs in `text`. */
export function matches(text: string, query: string): boolean {
diff --git a/src/features/run/ConfigChooser.tsx b/src/features/run/ConfigChooser.tsx
index becadcc4e..2e9b90bff 100644
--- a/src/features/run/ConfigChooser.tsx
+++ b/src/features/run/ConfigChooser.tsx
@@ -94,7 +94,8 @@ function ConfigChooser() {
const initial = Math.max(
0,
rows.findIndex(
- (r) => (r.type === "config" && r.config.id === selectedId) || (r.type === "current" && selectedId === CURRENT_FILE),
+ (r) =>
+ (r.type === "config" && r.config.id === selectedId) || (r.type === "current" && selectedId === CURRENT_FILE),
),
);
const [active, setActive] = useState(initial);
@@ -138,7 +139,9 @@ function ConfigChooser() {
if (row.type === "current") {
selectConfig(CURRENT_FILE);
if (how === "run" || how === "debug")
- void executeAction(how === "run" ? "run.runContext" : "run.debugContext").then(() => selectConfig(CURRENT_FILE));
+ void executeAction(how === "run" ? "run.runContext" : "run.debugContext").then(() =>
+ selectConfig(CURRENT_FILE),
+ );
return;
}
if (row.type !== "config") return;
@@ -247,7 +250,11 @@ function ConfigChooser() {
<span className={styles.chooserRow}>
<Icon name="file" size={13} className={styles.chooserIcon} />
<span className={clsx(styles.chooserName, selectedId === CURRENT_FILE && styles.chooserSelected)}>
- {r.indices ? <HighlightedText text={CURRENT_FILE_LABEL} indices={r.indices} /> : <T>{CURRENT_FILE_LABEL}</T>}
+ {r.indices ? (
+ <HighlightedText text={CURRENT_FILE_LABEL} indices={r.indices} />
+ ) : (
+ <T>{CURRENT_FILE_LABEL}</T>
+ )}
</span>
</span>
);
@@ -277,15 +284,21 @@ function ConfigChooser() {
{r.indices ? <HighlightedText text={c.name} indices={r.indices} /> : c.name}
</span>
{c.target && <span className={styles.chooserMuted}>@ {targetName(c, runTargets)}</span>}
- {c.isTest && <span className={styles.badge}>
+ {c.isTest && (
+ <span className={styles.badge}>
<T>test</T>
- </span>}
- {!c.detected && <span className={styles.chooserMuted}>
+ </span>
+ )}
+ {!c.detected && (
+ <span className={styles.chooserMuted}>
<T>user</T>
- </span>}
- {temporary.includes(c.id) && <span className={styles.chooserMuted}>
+ </span>
+ )}
+ {temporary.includes(c.id) && (
+ <span className={styles.chooserMuted}>
<T>temporary</T>
- </span>}
+ </span>
+ )}
{isActive && (
<span className={styles.chooserActions}>
<IconButton
diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx
index 17913c65c..99aaf1f66 100644
--- a/src/features/run/ConfigForm.tsx
+++ b/src/features/run/ConfigForm.tsx
@@ -260,7 +260,10 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
...ADAPTERS.map((a) => ({ value: a.id, label: a.label })),
];
if (config.debugAdapter && !ADAPTERS.some((a) => a.id === config.debugAdapter))
- adapterOptions.push({ value: config.debugAdapter, label: txTemplate(`${config.debugAdapter} (no launch template)`) });
+ adapterOptions.push({
+ value: config.debugAdapter,
+ label: txTemplate(`${config.debugAdapter} (no launch template)`),
+ });
const targetOptions: SelectOption[] = [
{ value: "", label: "Local machine" },
diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx
index 0bac60623..5322b1146 100644
--- a/src/features/run/ConsoleView.tsx
+++ b/src/features/run/ConsoleView.tsx
@@ -93,10 +93,14 @@ export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind:
* Folds runs of consecutive output lines (one or more) that contain one of
* `patterns`; runs whose first line id is in `expanded` stay open.
*/
-export function foldRows(lines: readonly ConsoleLine[], patterns: readonly string[], expanded: ReadonlySet<number>): DisplayRow[] {
+export function foldRows(
+ lines: readonly ConsoleLine[],
+ patterns: readonly string[],
+ expanded: ReadonlySet<number>,
+): DisplayRow[] {
const rows: DisplayRow[] = [];
const matches = (l: ConsoleLine) => l.kind !== "system" && patterns.some((p) => l.text.includes(p));
- for (let i = 0; i < lines.length; ) {
+ for (let i = 0; i < lines.length;) {
if (patterns.length && matches(lines[i]!)) {
let j = i + 1;
while (j < lines.length && matches(lines[j]!)) j++;
@@ -139,7 +143,17 @@ export interface ConsoleViewProps {
"aria-label"?: string;
}
-export function ConsoleView({ model, version, softWrap, follow, onFollowChange, cwd, onClear, input, ...aria }: ConsoleViewProps) {
+export function ConsoleView({
+ model,
+ version,
+ softWrap,
+ follow,
+ onFollowChange,
+ cwd,
+ onClear,
+ input,
+ ...aria
+}: ConsoleViewProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const lines = model.lines;
const patterns = useWorkflowSettings((s) => s.console.foldPatterns);
@@ -208,7 +222,9 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
{ label: "Copy All", run: () => void navigator.clipboard?.writeText(model.text()).catch(() => undefined) },
{ kind: "separator" },
{ label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() },
- ...(input ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }] : []),
+ ...(input
+ ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }]
+ : []),
]);
};
@@ -249,11 +265,22 @@ export function ConsoleView({ model, version, softWrap, follow, onFollowChange,
);
const foldButton = (fold: Fold, attached: boolean) =>
fold.expanded ? (
- <button type="button" className={styles.foldToggle} title={tx("Collapse folded lines")} aria-label={tx("Collapse folded lines")} onClick={() => toggleFold(fold.id)}>
+ <button
+ type="button"
+ className={styles.foldToggle}
+ title={tx("Collapse folded lines")}
+ aria-label={tx("Collapse folded lines")}
+ onClick={() => toggleFold(fold.id)}
+ >
<Icon name="chevron-up" size={10} />
</button>
) : (
- <button type="button" className={styles.fold} title={tx("Expand folded lines")} onClick={() => toggleFold(fold.id)}>
+ <button
+ type="button"
+ className={styles.fold}
+ title={tx("Expand folded lines")}
+ onClick={() => toggleFold(fold.id)}
+ >
{`${attached ? " " : ""}${fold.count === 1 ? tx`<${fold.count} internal line>` : tx`<${fold.count} internal lines>`}`}
</button>
);
diff --git a/src/features/run/EditConfigsDialog.tsx b/src/features/run/EditConfigsDialog.tsx
index 124d5aef6..06018bebe 100644
--- a/src/features/run/EditConfigsDialog.tsx
+++ b/src/features/run/EditConfigsDialog.tsx
@@ -40,7 +40,9 @@ export function EditConfigsOverlay() {
}
type Selection =
- { type: "config"; id: string } | { type: "folder"; kind: string; name: string } | { type: "template"; kind: string };
+ | { type: "config"; id: string }
+ | { type: "folder"; kind: string; name: string }
+ | { type: "template"; kind: string };
export type TreeRow =
| { type: "group"; key: string; kind: string; label: string; icon: string }
diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx
index c17616476..44378442b 100644
--- a/src/features/run/TestTreeView.tsx
+++ b/src/features/run/TestTreeView.tsx
@@ -144,15 +144,20 @@ export function TestTreeView({ results, version, cwd, selected, onSelect, runnin
}
if (ids.length === 1 && nodeStatus(node) === "failed" && parseComparison(node.output))
items.push({ label: "Show Diff", icon: "diff", run: () => void showTestDiff(node) });
- items.push({ label: "Jump to Source", icon: "external-link", shortcut: "F4", disabled: !located, run: () => jumpToSource(node) });
+ items.push({
+ label: "Jump to Source",
+ icon: "external-link",
+ shortcut: "F4",
+ disabled: !located,
+ run: () => jumpToSource(node),
+ });
e.preventDefault();
showContextMenu(e, items);
};
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
const roots = useMemo(() => {
- const keep = (n: TestNode) =>
- (showPassed || n.own !== "passed") && (showIgnored || n.own !== "skipped");
+ const keep = (n: TestNode) => (showPassed || n.own !== "passed") && (showIgnored || n.own !== "skipped");
return showPassed && showIgnored ? [...results.roots] : filterTree(results.roots, keep);
}, [results, version, showPassed, showIgnored]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -235,7 +240,11 @@ export function TestTreeView({ results, version, cwd, selected, onSelect, runnin
}}
empty={
<div className={styles.testEmpty}>
- {running ? tx("Waiting for test results…") : results.isEmpty ? tx("No test results") : tx("Passed tests are hidden")}
+ {running
+ ? tx("Waiting for test results…")
+ : results.isEmpty
+ ? tx("No test results")
+ : tx("Passed tests are hidden")}
</div>
}
/>
diff --git a/src/features/run/configs.test.ts b/src/features/run/configs.test.ts
index 5f8c1694e..6258c3f86 100644
--- a/src/features/run/configs.test.ts
+++ b/src/features/run/configs.test.ts
@@ -64,7 +64,11 @@ describe("config merge / override", () => {
});
it("groups by kind in order", () => {
- const groups = groupConfigs([cfg({ id: "a", kind: "npm" }), cfg({ id: "b", kind: "cargo" }), cfg({ id: "c", kind: "npm" })]);
+ const groups = groupConfigs([
+ cfg({ id: "a", kind: "npm" }),
+ cfg({ id: "b", kind: "cargo" }),
+ cfg({ id: "c", kind: "npm" }),
+ ]);
expect(groups.map((g) => [g.label, g.configs.map((c) => c.id)])).toEqual([
["npm", ["a", "c"]],
["Cargo", ["b"]],
@@ -97,15 +101,32 @@ describe("validateConfig", () => {
});
it("validates env table rows", () => {
- expect(envFromRows([{ key: "A", value: "1" }, { key: "", value: "" }])).toEqual({ env: { A: "1" } });
+ expect(
+ envFromRows([
+ { key: "A", value: "1" },
+ { key: "", value: "" },
+ ]),
+ ).toEqual({ env: { A: "1" } });
expect(envFromRows([{ key: "", value: "x" }]).error).toMatch(/empty/);
- expect(envFromRows([{ key: "A", value: "1" }, { key: "A", value: "2" }]).error).toMatch(/Duplicate/);
+ expect(
+ envFromRows([
+ { key: "A", value: "1" },
+ { key: "A", value: "2" },
+ ]).error,
+ ).toMatch(/Duplicate/);
});
});
describe("argument parsing", () => {
it("splits with quotes and escapes", () => {
- expect(parseArgs(`run --name "hello world" 'it''s' a\\ b ""`)).toEqual(["run", "--name", "hello world", "its", "a b", ""]);
+ expect(parseArgs(`run --name "hello world" 'it''s' a\\ b ""`)).toEqual([
+ "run",
+ "--name",
+ "hello world",
+ "its",
+ "a b",
+ "",
+ ]);
expect(parseArgs(" ")).toEqual([]);
});
@@ -142,7 +163,12 @@ describe("context configuration", () => {
it("runs a JS test file through the closest test script", () => {
const c = contextConfig("web/src/cart.test.ts", configs)!;
- expect(c).toMatchObject({ args: ["run", "test", "--", "src/cart.test.ts"], cwd: "web", isTest: true, name: "cart.test.ts" });
+ expect(c).toMatchObject({
+ args: ["run", "test", "--", "src/cart.test.ts"],
+ cwd: "web",
+ isTest: true,
+ name: "cart.test.ts",
+ });
expect(c.id).toBe("context:npm:web:test:web/src/cart.test.ts");
expect(contextConfig("src/a.spec.js", configs)!.args).toEqual(["run", "test", "--", "src/a.spec.js"]);
});
@@ -160,7 +186,10 @@ describe("context configuration", () => {
it("finds run targets and script invocations", () => {
expect(contextConfig("src/bin/server.rs", configs)!.id).toBe("cargo:run:server");
- expect(contextConfig("tools/gen.py", configs)).toMatchObject({ command: ".venv/bin/python", args: ["tools/gen.py"] });
+ expect(contextConfig("tools/gen.py", configs)).toMatchObject({
+ command: ".venv/bin/python",
+ args: ["tools/gen.py"],
+ });
expect(contextConfig("scripts/build.sh", configs)).toMatchObject({ command: "sh", args: ["scripts/build.sh"] });
expect(contextConfig("docs/readme.md", configs)).toBeNull();
});
@@ -186,7 +215,10 @@ describe("context configuration", () => {
];
const main = "package main\nfunc main() {}";
expect(contextConfig("api/main.go", nested, main)!.id).toBe("go:run:api");
- expect(contextConfig("api/cmd/tool/main.go", nested, main)).toMatchObject({ args: ["run", "./cmd/tool"], cwd: "api" });
+ expect(contextConfig("api/cmd/tool/main.go", nested, main)).toMatchObject({
+ args: ["run", "./cmd/tool"],
+ cwd: "api",
+ });
expect(contextConfig("api/main_test.go", nested)).toMatchObject({ args: ["test", "."], cwd: "api" });
});
diff --git a/src/features/run/configs.ts b/src/features/run/configs.ts
index bc46d4ce3..53f2ffa1d 100644
--- a/src/features/run/configs.ts
+++ b/src/features/run/configs.ts
@@ -268,7 +268,8 @@ export function parseArgs(input: string): string[] {
const ch = input[i]!;
if (quote) {
if (ch === quote) quote = null;
- else if (ch === "\\" && quote === '"' && i + 1 < input.length && '"\\$`'.includes(input[i + 1]!)) cur += input[++i];
+ else if (ch === "\\" && quote === '"' && i + 1 < input.length && '"\\$`'.includes(input[i + 1]!))
+ cur += input[++i];
else cur += ch;
} else if (ch === "'" || ch === '"') {
quote = ch;
@@ -290,9 +291,7 @@ export function parseArgs(input: string): string[] {
/** Inverse of `parseArgs` (quotes only when needed). */
export function formatArgs(args: readonly string[]): string {
- return args
- .map((a) => (a === "" ? "''" : /[\s'"\\$`]/.test(a) ? `'${a.replace(/'/g, `'\\''`)}'` : a))
- .join(" ");
+ return args.map((a) => (a === "" ? "''" : /[\s'"\\$`]/.test(a) ? `'${a.replace(/'/g, `'\\''`)}'` : a)).join(" ");
}
/** Display command line, e.g. `pnpm run dev`. */
diff --git a/src/features/run/contextRun.test.ts b/src/features/run/contextRun.test.ts
index 9120f414f..3d19e40a7 100644
--- a/src/features/run/contextRun.test.ts
+++ b/src/features/run/contextRun.test.ts
@@ -84,7 +84,9 @@ describe("run context menu group", () => {
it("shows nothing when no producer matches or for several paths", () => {
expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]);
- expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual([]);
+ expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual(
+ [],
+ );
useProject.setState({ project: null });
expect(contextMenuItems("editor", { paths: [`${SCRATCHES}/hi.ts`], text: "", line: 0 })).toEqual([]);
});
@@ -143,7 +145,9 @@ describe("run gutter popup", () => {
const text = "describe('math', () => {\n it('adds', () => {\n });\n});\n";
const adds: RunTarget = { line: 1, kind: "test", name: "math > adds", path: ["math", "adds"] };
const itemLabels = (items: MenuItem[]): string[] =>
- items.map((i) => (i.kind === "separator" ? "---" : "label" in i ? `${i.label}${"submenu" in i && i.submenu ? " ▸" : ""}` : ""));
+ items.map((i) =>
+ i.kind === "separator" ? "---" : "label" in i ? `${i.label}${"submenu" in i && i.submenu ? " ▸" : ""}` : "",
+ );
beforeEach(() => {
useProject.setState({ project: { name: "app", root: ROOT, isGit: false, settings: {} } as never });
@@ -167,7 +171,15 @@ describe("run gutter popup", () => {
const run = items[0] as Extract<MenuItem, { submenu?: MenuItem[] }>;
expect(run.submenu!.map((i) => ("shortcut" in i ? i.shortcut : null))).toEqual(["test", "npm run test:unit"]);
// ⌃⇧R's chooser lists the same, under a header.
- expect(choiceItems(produceContextChoices({ path: `${ROOT}/src/m.test.ts`, root: ROOT, configs: [npmTest, unit], content: text, line: 1 }, OPTIMISTIC), false)[0]).toEqual({
+ expect(
+ choiceItems(
+ produceContextChoices(
+ { path: `${ROOT}/src/m.test.ts`, root: ROOT, configs: [npmTest, unit], content: text, line: 1 },
+ OPTIMISTIC,
+ ),
+ false,
+ )[0],
+ ).toEqual({
kind: "header",
label: "Choose configuration to run",
});
diff --git a/src/features/run/contextRun.ts b/src/features/run/contextRun.ts
index f25b37a53..11b04b3ce 100644
--- a/src/features/run/contextRun.ts
+++ b/src/features/run/contextRun.ts
@@ -75,7 +75,13 @@ export async function produceResolved(input: ContextInput, dir = false): Promise
function reportMissing(p: Produced) {
if (!p.missing) return;
- notifications().notify({ group: "run", level: "warning", title: p.missing.title, body: p.missing.body, key: "run-context-missing" });
+ notifications().notify({
+ group: "run",
+ level: "warning",
+ title: p.missing.title,
+ body: p.missing.body,
+ key: "run-context-missing",
+ });
}
/** Builds with `build` in the Run window; resolves whether it succeeded. */
@@ -86,8 +92,8 @@ async function buildFirst(build: RunConfig): Promise<boolean> {
const check = () => {
const s = useRun.getState().sessions.find((x) => x.id === session.id);
if (!s) return true;
- if (s.status === "failed") return resolve(false), true;
- if (s.status === "finished") return resolve(s.exitCode === 0), true;
+ if (s.status === "failed") return (resolve(false), true);
+ if (s.status === "finished") return (resolve(s.exitCode === 0), true);
return false;
};
if (check()) return;
@@ -111,7 +117,12 @@ export async function launchProduced(p: Produced, debug: boolean): Promise<void>
if (remoteDebugBlocked(config)) return;
if (p.debug) {
if (!getAction("debug.startConfig")) {
- notifications().notify({ group: "run", level: "warning", title: "Debugger is not available", key: "run-no-debugger" });
+ notifications().notify({
+ group: "run",
+ level: "warning",
+ title: "Debugger is not available",
+ key: "run-no-debugger",
+ });
return;
}
if (!(await buildFirst(p.debug.build))) return;
@@ -142,7 +153,9 @@ export async function compiledDebugPlan(config: RunConfig): Promise<Produced | n
if (m[2]) {
// A test: find the target by name again.
const lines = (content ?? "").split("\n");
- const line = lines.findIndex((l) => new RegExp(`\\bfn\\s+${m[2]!.split("::").pop()}\\b|\\bmod\\s+${m[2]}\\b`).test(l));
+ const line = lines.findIndex((l) =>
+ new RegExp(`\\bfn\\s+${m[2]!.split("::").pop()}\\b|\\bmod\\s+${m[2]}\\b`).test(l),
+ );
return line >= 0 ? produceContext({ ...input, line }, env) : null;
}
return produceFile(input, env);
@@ -165,7 +178,9 @@ export async function runContextAction(debug: boolean, arg?: unknown): Promise<b
const input = target ?? editorInput();
if (!input) return false;
const dir = target?.dir ?? false;
- const choices = dir ? [] : produceContextChoices({ ...input, configs: useRun.getState().configs, goModule: goModulePath }, OPTIMISTIC);
+ const choices = dir
+ ? []
+ : produceContextChoices({ ...input, configs: useRun.getState().configs, goModule: goModulePath }, OPTIMISTIC);
if (choices.length > 1) {
// Several test configurations match equally well: like IDEA, let the user choose.
showContextMenu(chooserPoint(target === null), choiceItems(choices, debug));
@@ -181,15 +196,13 @@ export async function runContextAction(debug: boolean, arg?: unknown): Promise<b
export function choiceItems(choices: readonly Produced[], debug: boolean): MenuItem[] {
return [
{ kind: "header", label: debug ? "Choose configuration to debug" : "Choose configuration to run" },
- ...choices.map(
- (p): MenuItem => ({
- label: debug ? tx`Debug '${p.name}'` : tx`Run '${p.name}'`,
- verbatim: true,
- icon: debug ? "debug" : "run",
- shortcut: p.detail,
- run: () => void launchProduced(p, debug),
- }),
- ),
+ ...choices.map((p): MenuItem => ({
+ label: debug ? tx`Debug '${p.name}'` : tx`Run '${p.name}'`,
+ verbatim: true,
+ icon: debug ? "debug" : "run",
+ shortcut: p.detail,
+ run: () => void launchProduced(p, debug),
+ })),
];
}
@@ -222,7 +235,13 @@ export function executorItems(config: RunConfig | null | undefined, name: string
if (!config) return [];
return runExecutors()
.filter((e) => e.supports(config))
- .map((e) => ({ kind: "action", action: "run.withExecutor", arg: { executor: e.id, context }, label: e.label(name), icon: e.icon }));
+ .map((e) => ({
+ kind: "action",
+ action: "run.withExecutor",
+ arg: { executor: e.id, context },
+ label: e.label(name),
+ icon: e.icon,
+ }));
}
export interface ContextArg {
@@ -322,7 +341,9 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
{ kind: "action", action: "run.runContext", arg, label: tx`Run '${p.name}'`, icon: "run" },
// Like IDEA, Debug only where a debugger can run it.
...(p.debug || p.config?.debugAdapter || p.missing
- ? ([{ kind: "action", action: "run.debugContext", arg, label: tx`Debug '${p.name}'`, icon: "debug" }] as MenuItem[])
+ ? ([
+ { kind: "action", action: "run.debugContext", arg, label: tx`Debug '${p.name}'`, icon: "debug" },
+ ] as MenuItem[])
: []),
{
label: "More Run/Debug",
diff --git a/src/features/run/externalTools.ts b/src/features/run/externalTools.ts
index 9bd997388..0cefe7d14 100644
--- a/src/features/run/externalTools.ts
+++ b/src/features/run/externalTools.ts
@@ -34,7 +34,8 @@ export function macroValue(name: string, ctx: MacroContext): string | undefined
const file = ctx.filePath;
const dir = file ? file.slice(0, Math.max(file.lastIndexOf("/"), 0)) || "/" : "";
const base = file ? file.slice(file.lastIndexOf("/") + 1) : "";
- const rel = (p: string) => (p === ctx.projectRoot ? "" : p.startsWith(ctx.projectRoot + "/") ? p.slice(ctx.projectRoot.length + 1) : p);
+ const rel = (p: string) =>
+ p === ctx.projectRoot ? "" : p.startsWith(ctx.projectRoot + "/") ? p.slice(ctx.projectRoot.length + 1) : p;
switch (name) {
case "FilePath":
return file ?? "";
@@ -87,7 +88,14 @@ function currentContext(): MacroContext | null {
column = sel.head - l.from + 1;
selectedText = state.sliceDoc(sel.from, sel.to);
}
- return { projectRoot: project.root, projectName: project.name, filePath: ed?.ctx.path ?? null, line, column, selectedText };
+ return {
+ projectRoot: project.root,
+ projectName: project.name,
+ filePath: ed?.ctx.path ?? null,
+ line,
+ column,
+ selectedText,
+ };
}
/** The run configuration a tool expands to (no `$Prompt$` handling). */
diff --git a/src/features/run/index.ts b/src/features/run/index.ts
index c57ae1c7d..5e6e6336b 100644
--- a/src/features/run/index.ts
+++ b/src/features/run/index.ts
@@ -201,7 +201,12 @@ function stopAction() {
}
}
const items = [
- ...running.map((s): MenuItem => ({ label: s.config.name, verbatim: true, icon: "run", run: () => void stopSession(s.id) })),
+ ...running.map((s): MenuItem => ({
+ label: s.config.name,
+ verbatim: true,
+ icon: "run",
+ run: () => void stopSession(s.id),
+ })),
...menuGroupItems("stopProcess", { paths: [] }),
].filter((i): i is MenuItem & { run: () => void } => "run" in i && !!i.run);
if (items.length === 0) return;
@@ -332,7 +337,8 @@ export function activate(): () => void {
{
id: "run.chooseConfig",
title: "Select Run/Debug Configuration…",
- description: "Run a configuration (hold Shift to debug); the title bar widget passes \"select\" to only select one",
+ description:
+ 'Run a configuration (hold Shift to debug); the title bar widget passes "select" to only select one',
category: "Run",
when: "projectOpen",
run: async ({ arg }) => {
@@ -385,7 +391,12 @@ export function activate(): () => void {
(s.activeSession && failedTests(s.activeSession).length ? s.activeSession : null) ??
[...s.sessions].reverse().find((x) => failedTests(x.id).length > 0)?.id;
if (!id || !rerunFailed(id))
- notifications().notify({ group: "run", level: "info", title: "No failed tests to rerun", key: "run-rerun-failed" });
+ notifications().notify({
+ group: "run",
+ level: "info",
+ title: "No failed tests to rerun",
+ key: "run-rerun-failed",
+ });
},
},
{
diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts
index abf2308d0..974a5bcf2 100644
--- a/src/features/run/java.test.ts
+++ b/src/features/run/java.test.ts
@@ -56,7 +56,9 @@ describe("scanJvmTargets (Java)", () => {
});
it("ignores non-main methods named main and Java 25 instance mains count", () => {
- expect(pick("class A {\n int main(String[] a) { return 0; }\n static void main(int x) {}\n}", "A.java")).toEqual([]);
+ expect(pick("class A {\n int main(String[] a) { return 0; }\n static void main(int x) {}\n}", "A.java")).toEqual(
+ [],
+ );
expect(pick("class B {\n void main() {}\n}", "B.java")).toEqual([[1, "main", "B", null, false]]);
});
@@ -140,7 +142,8 @@ describe("application configurations", () => {
it("creates an Application / Spring Boot config named after the class", () => {
const rel = "src/main/java/com/example/demo/SpringDemoApplication.java";
- const src = "package com.example.demo;\n@SpringBootApplication\nclass SpringDemoApplication {\n public static void main(String[] a) {}\n}";
+ const src =
+ "package com.example.demo;\n@SpringBootApplication\nclass SpringDemoApplication {\n public static void main(String[] a) {}\n}";
const main = detectRunTargets(src, rel).find((t) => t.kind === "main")!;
const c = targetConfig(main, rel, maven, src)!;
expect(c).toMatchObject({
@@ -245,7 +248,9 @@ describe("java command lines", () => {
describe("debugging build tool configurations", () => {
it("adds a waiting JDWP agent to spring-boot:run, Surefire and Gradle", () => {
const boot = jdwpLaunch(cfg({ id: "b", kind: "maven", args: ["spring-boot:run"] }))!;
- expect(boot.args[1]).toMatch(/^-Dspring-boot\.run\.jvmArguments=-agentlib:jdwp=.*suspend=y.*address=127\.0\.0\.1:0$/);
+ expect(boot.args[1]).toMatch(
+ /^-Dspring-boot\.run\.jvmArguments=-agentlib:jdwp=.*suspend=y.*address=127\.0\.0\.1:0$/,
+ );
const merged = jdwpLaunch(
cfg({ id: "b", kind: "maven", args: ["spring-boot:run", "-Dspring-boot.run.jvmArguments=-Xmx1g"] }),
)!;
diff --git a/src/features/run/javaDebug.ts b/src/features/run/javaDebug.ts
index 27ccd39a9..def29583c 100644
--- a/src/features/run/javaDebug.ts
+++ b/src/features/run/javaDebug.ts
@@ -10,7 +10,8 @@ import type { RunConfig } from "@/platform/ipc";
import { JDWP_AGENT, jdwpListeningPort } from "@/platform/javaLaunch";
import { startRun, useRun } from "./store";
-const isMavenTestGoal = (a: string) => /^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(a);
+const isMavenTestGoal = (a: string) =>
+ /^(test|verify|integration-test|surefire:test|failsafe:integration-test)$/.test(a);
const isGradleJvmTask = (a: string) => /(^|:)(test|bootRun|run|integrationTest|check)$/.test(a);
function withProperty(args: readonly string[], key: string, value: string): string[] {
diff --git a/src/features/run/navigate.ts b/src/features/run/navigate.ts
index 77c18078d..a81dcfae1 100644
--- a/src/features/run/navigate.ts
+++ b/src/features/run/navigate.ts
@@ -17,7 +17,8 @@ async function exists(path: string): Promise<boolean> {
}
}
-const packageOf = (className: string) => (className.includes(".") ? className.slice(0, className.lastIndexOf(".")) : "");
+const packageOf = (className: string) =>
+ className.includes(".") ? className.slice(0, className.lastIndexOf(".")) : "";
/** Whether a JVM source file declares `pkg` (Kotlin files needn't sit in their package's directory). */
async function declaresPackage(path: string, pkg: string): Promise<boolean> {
@@ -62,9 +63,7 @@ async function findLibraryClass(className: string): Promise<string | null> {
const pkg = packageOf(outer);
try {
const symbols = await call(commands.lspWorkspaceSymbols(nextRequestId(), simple));
- const hit = symbols.find(
- (s) => s.name === simple && TYPE_KINDS.has(s.kind) && (s.container ?? "") === pkg,
- );
+ const hit = symbols.find((s) => s.name === simple && TYPE_KINDS.has(s.kind) && (s.container ?? "") === pkg);
return hit ? (hit.location.uri ?? hit.location.path) : null;
} catch {
return null;
@@ -106,7 +105,13 @@ export async function openTarget(target: FileTarget, cwd: string, focus = true):
return;
}
if (!path) {
- notifications().notify({ group: "run", level: "warning", title: "File not found", body: target.path, key: "run-link" });
+ notifications().notify({
+ group: "run",
+ level: "warning",
+ title: "File not found",
+ body: target.path,
+ key: "run-link",
+ });
return;
}
const selection = target.line ? { line: target.line - 1, col: Math.max(0, (target.col ?? 1) - 1) } : undefined;
diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts
index c159baa4b..3c75d02dc 100644
--- a/src/features/run/producers.test.ts
+++ b/src/features/run/producers.test.ts
@@ -89,9 +89,16 @@ describe("single-file producers (scratches)", () => {
it("TypeScript: node type stripping by version, then tsx / ts-node, else what is missing", () => {
expect(run(scratch("hi.ts"), env({ node: "23.6.0" }))).toMatchObject({ command: "/bin/node", args: ["hi.ts"] });
expect(run(scratch("hi.ts"), env({ node: "22.18.0" }))).toMatchObject({ args: ["hi.ts"] });
- expect(run(scratch("hi.ts"), env({ node: "22.6.0" }))).toMatchObject({ args: ["--experimental-strip-types", "hi.ts"] });
- expect(run(scratch("hi.ts"), env({ node: "23.5.0" }))).toMatchObject({ args: ["--experimental-strip-types", "hi.ts"] });
- expect(run(scratch("hi.ts"), env({ node: "20.11.0", tsx: null }))).toMatchObject({ command: "/bin/tsx", args: ["hi.ts"] });
+ expect(run(scratch("hi.ts"), env({ node: "22.6.0" }))).toMatchObject({
+ args: ["--experimental-strip-types", "hi.ts"],
+ });
+ expect(run(scratch("hi.ts"), env({ node: "23.5.0" }))).toMatchObject({
+ args: ["--experimental-strip-types", "hi.ts"],
+ });
+ expect(run(scratch("hi.ts"), env({ node: "20.11.0", tsx: null }))).toMatchObject({
+ command: "/bin/tsx",
+ args: ["hi.ts"],
+ });
expect(run(scratch("hi.ts"), env({ node: "20.11.0", "ts-node": null }))).toMatchObject({ command: "/bin/ts-node" });
const missing = produceContext(scratch("hi.ts"), env({ node: "20.11.0" }))!;
expect(missing.name).toBe("hi.ts");
@@ -112,7 +119,11 @@ describe("single-file producers (scratches)", () => {
it("Deno / Bun projects run JS and TS with their runtime", () => {
const input: ContextInput = { path: `${ROOT}/scripts/x.ts`, root: ROOT, configs: [] };
- expect(run(input, { ...ALL, deno: true })).toMatchObject({ command: "/bin/deno", args: ["run", "scripts/x.ts"], cwd: null });
+ expect(run(input, { ...ALL, deno: true })).toMatchObject({
+ command: "/bin/deno",
+ args: ["run", "scripts/x.ts"],
+ cwd: null,
+ });
expect(produceContext(input, { ...ALL, deno: true })!.config!.debugAdapter).toBe("js-debug");
expect(run(input, { ...ALL, bun: true })).toMatchObject({ command: "/bin/bun", args: ["run", "scripts/x.ts"] });
// Bun's inspector is WebKit-only: js-debug can't attach.
@@ -134,18 +145,33 @@ describe("single-file producers (scratches)", () => {
args: ["tools/gen.py"],
cwd: null,
});
- expect(produceContext(scratch("hi.py"), ALL)!.config).toMatchObject({ command: "/bin/python3", debugAdapter: "debugpy" });
+ expect(produceContext(scratch("hi.py"), ALL)!.config).toMatchObject({
+ command: "/bin/python3",
+ debugAdapter: "debugpy",
+ });
expect(produceContext(scratch("hi.py"), env({}))!.missing!.title).toBe("Cannot run 'hi.py'");
});
it("shell scripts: the shell of the #! line, else by extension; extensionless files by #!", () => {
- expect(run(scratch("a.sh", "#!/usr/bin/env bash\necho hi"))).toMatchObject({ command: "/bin/bash", args: ["a.sh"] });
+ expect(run(scratch("a.sh", "#!/usr/bin/env bash\necho hi"))).toMatchObject({
+ command: "/bin/bash",
+ args: ["a.sh"],
+ });
expect(run(scratch("a.sh", "#!/bin/zsh -f\necho"))).toMatchObject({ command: "/bin/zsh", args: ["-f", "a.sh"] });
expect(run(scratch("a.sh", "echo"))).toMatchObject({ command: "/bin/sh" });
expect(run(scratch("a.zsh", "echo"))).toMatchObject({ command: "/bin/zsh" });
- expect(run(scratch("tool", "#!/usr/bin/env ruby\nputs 1"))).toMatchObject({ name: "tool", command: "/bin/ruby", args: ["tool"] });
- expect(run(scratch("tool", "#!/usr/bin/env -S deno run -A\n"))).toMatchObject({ command: "/bin/deno", args: ["run", "-A", "tool"] });
- expect(produceContext(scratch("tool", "#!/usr/bin/env -S deno run -A\n"), ALL)!.config!.debugAdapter).toBe("js-debug");
+ expect(run(scratch("tool", "#!/usr/bin/env ruby\nputs 1"))).toMatchObject({
+ name: "tool",
+ command: "/bin/ruby",
+ args: ["tool"],
+ });
+ expect(run(scratch("tool", "#!/usr/bin/env -S deno run -A\n"))).toMatchObject({
+ command: "/bin/deno",
+ args: ["run", "-A", "tool"],
+ });
+ expect(produceContext(scratch("tool", "#!/usr/bin/env -S deno run -A\n"), ALL)!.config!.debugAdapter).toBe(
+ "js-debug",
+ );
expect(run(scratch("tool", "#!/usr/bin/env python3\n"))).toMatchObject({ command: "/bin/python3", args: ["tool"] });
expect(produceContext(scratch("notes", "just text"), ALL)).toBeNull();
expect(shebang("#!/usr/bin/env node")).toEqual(["node"]);
@@ -162,25 +188,35 @@ describe("single-file producers (scratches)", () => {
expect(run(scratch("a.exs"))).toMatchObject({ command: "/bin/elixir", args: ["a.exs"] });
expect(run(scratch("a.sc"))).toMatchObject({ command: "/bin/scala-cli", args: ["run", "a.sc"] });
expect(run(scratch("a.kts"))).toMatchObject({ command: "/bin/kotlin", args: ["a.kts"] });
- expect(run(scratch("a.kts"), env({ kotlinc: null }))).toMatchObject({ command: "/bin/kotlinc", args: ["-script", "a.kts"] });
+ expect(run(scratch("a.kts"), env({ kotlinc: null }))).toMatchObject({
+ command: "/bin/kotlinc",
+ args: ["-script", "a.kts"],
+ });
expect(produceContext(scratch("a.rb"), env({}))!.missing!.body).toMatch(/brew install ruby/);
expect(produceContext(scratch("build.gradle.kts"), ALL)).toBeNull();
});
it("Go: go run <file> for package main outside a module", () => {
- expect(run(scratch("hi.go", "package main\nfunc main() {}"))).toMatchObject({ command: "/bin/go", args: ["run", "hi.go"], cwd: SCRATCH });
+ expect(run(scratch("hi.go", "package main\nfunc main() {}"))).toMatchObject({
+ command: "/bin/go",
+ args: ["run", "hi.go"],
+ cwd: SCRATCH,
+ });
expect(produceContext(scratch("lib.go", "package lib"), ALL)).toBeNull();
expect(produceContext(scratch("hi.go", "package main"), ALL)!.config!.debugAdapter).toBe("delve");
});
it("Go: the module's go run for packages in the project", () => {
const go = [cfg({ id: "go:run", kind: "go", command: "go", args: ["run", "."] })];
- const p = produceContext({ path: `${ROOT}/cmd/tool/main.go`, root: ROOT, configs: go, content: "package main\nfunc main() {}" }, ALL)!;
+ const p = produceContext(
+ { path: `${ROOT}/cmd/tool/main.go`, root: ROOT, configs: go, content: "package main\nfunc main() {}" },
+ ALL,
+ )!;
expect(p.config).toMatchObject({ args: ["run", "./cmd/tool"] });
});
it("Rust: rustc into the compile directory, then the binary; codelldb debugs the binary", () => {
- const p = produceContext(scratch("hihi.rs", "fn main() {\n println!(\"hi\");\n}"), ALL)!;
+ const p = produceContext(scratch("hihi.rs", 'fn main() {\n println!("hi");\n}'), ALL)!;
expect(p.name).toBe("hihi.rs");
expect(p.config!.cwd).toBe(SCRATCH);
expect(p.config!.args).toEqual([]);
@@ -195,10 +231,21 @@ describe("single-file producers (scratches)", () => {
});
it("Rust: a test at the caret of a standalone file builds with --test and filters", () => {
- const src = ["fn main() {}", "#[cfg(test)]", "mod tests {", " #[test]", " fn adds() {", " assert!(true);", " }", "}"].join("\n");
+ const src = [
+ "fn main() {}",
+ "#[cfg(test)]",
+ "mod tests {",
+ " #[test]",
+ " fn adds() {",
+ " assert!(true);",
+ " }",
+ "}",
+ ].join("\n");
const p = produceContext(scratch("calc.rs", src, 5), ALL)!;
expect(p).toMatchObject({ name: "tests::adds", scope: "element" });
- expect(p.config!.command).toMatch(/rustc -g --edition 2021 --test -o \S+-test calc\.rs && \S+-test tests::adds --exact$/);
+ expect(p.config!.command).toMatch(
+ /rustc -g --edition 2021 --test -o \S+-test calc\.rs && \S+-test tests::adds --exact$/,
+ );
expect(p.config!.isTest).toBe(true);
// On the module line: the whole module.
expect(produceContext(scratch("calc.rs", src, 2), ALL)!.config!.command).toMatch(/-test tests::$/);
@@ -211,11 +258,19 @@ describe("single-file producers (scratches)", () => {
cfg({ id: "cargo:run:server", kind: "cargo", command: "cargo", args: ["run", "--bin", "server"] }),
cfg({ id: "cargo:test", kind: "cargo", command: "cargo", args: ["test"], isTest: true }),
];
- const bin = produceContext({ path: `${ROOT}/src/bin/server.rs`, root: ROOT, configs: cargo, content: "fn main() {}" }, ALL)!;
+ const bin = produceContext(
+ { path: `${ROOT}/src/bin/server.rs`, root: ROOT, configs: cargo, content: "fn main() {}" },
+ ALL,
+ )!;
expect(bin.config!.id).toBe("cargo:run:server");
- const ex = produceContext({ path: `${ROOT}/examples/demo.rs`, root: ROOT, configs: cargo, content: "fn main() {}" }, ALL)!;
+ const ex = produceContext(
+ { path: `${ROOT}/examples/demo.rs`, root: ROOT, configs: cargo, content: "fn main() {}" },
+ ALL,
+ )!;
expect(ex.config).toMatchObject({ args: ["run", "--example", "demo"], name: "Run demo" });
- expect(produceContext({ path: `${ROOT}/src/lib.rs`, root: ROOT, configs: cargo, content: "pub fn x() {}" }, ALL)).toBeNull();
+ expect(
+ produceContext({ path: `${ROOT}/src/lib.rs`, root: ROOT, configs: cargo, content: "pub fn x() {}" }, ALL),
+ ).toBeNull();
const test = produceContext(
{ path: `${ROOT}/src/lib.rs`, root: ROOT, configs: cargo, content: "#[test]\nfn works() {\n}\n", line: 2 },
ALL,
@@ -229,14 +284,25 @@ describe("single-file producers (scratches)", () => {
expect(produceContext(scratch("Hi.java", src), ALL)!.config!.kind).toBe("java-file");
expect(produceContext(scratch("Lib.java", "class Lib {}"), ALL)).toBeNull();
const gradle = [cfg({ id: "gradle:test", kind: "gradle", command: "./gradlew", args: ["test"], isTest: true })];
- const p = produceContext({ path: `${ROOT}/src/main/java/demo/Hi.java`, root: ROOT, configs: gradle, content: `package demo;\n${src}`, line: 3 }, ALL)!;
+ const p = produceContext(
+ {
+ path: `${ROOT}/src/main/java/demo/Hi.java`,
+ root: ROOT,
+ configs: gradle,
+ content: `package demo;\n${src}`,
+ line: 3,
+ },
+ ALL,
+ )!;
expect(p.config).toMatchObject({ kind: "application", name: "Hi" });
expect(p.config!.args.at(-1)).toBe("demo.Hi");
});
it("C / C++: compile with debug info into the compile directory", () => {
const c = produceContext(scratch("a.c", "int main(void) { return 0; }"), ALL)!;
- expect(c.config!.command).toMatch(/^mkdir -p \/tmp\/openidea-run && \/bin\/clang -g -o \/tmp\/openidea-run\/a-\w+ a\.c && \/tmp\/openidea-run\/a-\w+$/);
+ expect(c.config!.command).toMatch(
+ /^mkdir -p \/tmp\/openidea-run && \/bin\/clang -g -o \/tmp\/openidea-run\/a-\w+ a\.c && \/tmp\/openidea-run\/a-\w+$/,
+ );
const cpp = produceContext(scratch("a.cpp", "int main() {}"), env({ "g++": null }))!;
expect(cpp.config!.command).toMatch(/\/bin\/g\+\+ -g -std=c\+\+17 -o/);
expect(cpp.debug!.config.debugAdapter).toBe("codelldb");
@@ -283,16 +349,27 @@ describe("project producers", () => {
});
it("keeps package.json test files on the project's runner", () => {
- const p = produceContext({ path: `${ROOT}/src/a.test.ts`, root: ROOT, configs, content: "test('x', () => {})" }, ALL)!;
+ const p = produceContext(
+ { path: `${ROOT}/src/a.test.ts`, root: ROOT, configs, content: "test('x', () => {})" },
+ ALL,
+ )!;
expect(p).toMatchObject({ name: "a.test.ts", scope: "file" });
expect(p.config!.args).toEqual(["run", "test", "--", "src/a.test.ts"]);
});
it("⌃⇧R picks the innermost context: test > describe > file", () => {
- const src = ["describe('math', () => {", " it('adds', () => {", " expect(1).toBe(1);", " });", "", "});", "", "const x = 1;"].join(
- "\n",
- );
- const at = (line: number) => produceContext({ path: `${ROOT}/src/m.test.ts`, root: ROOT, configs, content: src, line }, ALL)!;
+ const src = [
+ "describe('math', () => {",
+ " it('adds', () => {",
+ " expect(1).toBe(1);",
+ " });",
+ "",
+ "});",
+ "",
+ "const x = 1;",
+ ].join("\n");
+ const at = (line: number) =>
+ produceContext({ path: `${ROOT}/src/m.test.ts`, root: ROOT, configs, content: src, line }, ALL)!;
expect(at(2)).toMatchObject({ name: "math > adds", scope: "element" });
expect(at(4)).toMatchObject({ name: "math", scope: "element" });
expect(at(7)).toMatchObject({ name: "m.test.ts", scope: "file" });
@@ -301,7 +378,14 @@ describe("project producers", () => {
it("several equally close test configurations: one choice each, the default first", () => {
const withUnit = [
...configs,
- cfg({ id: "npm:test:unit", name: "npm run test:unit", kind: "npm", command: "npm", args: ["run", "test:unit"], isTest: true }),
+ cfg({
+ id: "npm:test:unit",
+ name: "npm run test:unit",
+ kind: "npm",
+ command: "npm",
+ args: ["run", "test:unit"],
+ isTest: true,
+ }),
];
const src = "describe('math', () => {\n it('adds', () => {\n });\n});\n";
const input = { path: `${ROOT}/src/m.test.ts`, root: ROOT, configs: withUnit, content: src, line: 1 };
@@ -312,12 +396,24 @@ describe("project producers", () => {
]);
expect(choices[1]!.config!.args.slice(0, 2)).toEqual(["run", "test:unit"]);
// The file context offers the same choice; a single matching configuration needs none.
- expect(produceContextChoices({ ...input, line: undefined }, ALL).map((c) => c.detail)).toEqual(["npm:test", "npm run test:unit"]);
+ expect(produceContextChoices({ ...input, line: undefined }, ALL).map((c) => c.detail)).toEqual([
+ "npm:test",
+ "npm run test:unit",
+ ]);
expect(produceContextChoices({ ...input, configs }, ALL)).toHaveLength(1);
});
it("python: test function > test class > file; __main__ runs the file", () => {
- const src = ["class TestMath:", " def test_add(self):", " assert 1", "", " x = 1", "", "def helper():", " pass"].join("\n");
+ const src = [
+ "class TestMath:",
+ " def test_add(self):",
+ " assert 1",
+ "",
+ " x = 1",
+ "",
+ "def helper():",
+ " pass",
+ ].join("\n");
const at = (line: number) =>
produceContext({ path: `${ROOT}/tests/test_m.py`, root: ROOT, configs, content: src, line }, ALL)!.name;
expect(at(2)).toBe("TestMath.test_add");
@@ -339,12 +435,12 @@ describe("project producers", () => {
"src/__tests__",
]);
const gradle = [cfg({ id: "gradle:test", kind: "gradle", command: "./gradlew", args: ["test"], isTest: true })];
- expect(produceDirectory({ path: `${ROOT}/src/test/java`, root: ROOT, configs: gradle })).toMatchObject({ name: "All Tests" });
- expect(produceDirectory({ path: `${ROOT}/src/test/java/com/acme`, root: ROOT, configs: gradle })!.config!.args).toEqual([
- "test",
- "--tests",
- "com.acme.*",
- ]);
+ expect(produceDirectory({ path: `${ROOT}/src/test/java`, root: ROOT, configs: gradle })).toMatchObject({
+ name: "All Tests",
+ });
+ expect(
+ produceDirectory({ path: `${ROOT}/src/test/java/com/acme`, root: ROOT, configs: gradle })!.config!.args,
+ ).toEqual(["test", "--tests", "com.acme.*"]);
expect(produceDirectory({ path: `${ROOT}/src/main`, root: ROOT, configs })).toBeNull();
expect(produceDirectory({ path: ROOT, root: ROOT, configs })).toBeNull();
});
@@ -352,7 +448,8 @@ describe("project producers", () => {
describe("file-level gutter targets", () => {
it("scratches: Python __main__, Go main, Rust fn main, C main; no JS", () => {
- const at = (name: string, text: string) => fileTargets({ path: `${SCRATCH}/${name}`, root: ROOT, configs: [] }, text).map((t) => [t.line, t.kind]);
+ const at = (name: string, text: string) =>
+ fileTargets({ path: `${SCRATCH}/${name}`, root: ROOT, configs: [] }, text).map((t) => [t.line, t.kind]);
expect(at("hi.py", 'x = 1\nif __name__ == "__main__":\n print(x)')).toEqual([[1, "main"]]);
expect(at("hi.go", "package main\n\nfunc main() {\n}")).toEqual([[2, "main"]]);
expect(at("hihi.rs", "use std::io;\nfn main() {\n}")).toEqual([[1, "main"]]);
@@ -401,13 +498,20 @@ describe("Kotlin single file (.kt)", () => {
const noKotlinc = produceContext(scratch("hello.kt", hello), env({ java: null }))!;
expect(noKotlinc.config).toBeUndefined();
expect(noKotlinc.missing!.title).toBe("Cannot run 'hello.kt'");
- expect(noKotlinc.missing!.body).toMatch(/The Kotlin compiler was not found \(looked for `kotlinc`\)\..*brew install kotlin/);
- expect(produceContext(scratch("hello.kt", hello), env({ kotlinc: null }))!.missing!.body).toMatch(/Java was not found.*JDK/);
+ expect(noKotlinc.missing!.body).toMatch(
+ /The Kotlin compiler was not found \(looked for `kotlinc`\)\..*brew install kotlin/,
+ );
+ expect(produceContext(scratch("hello.kt", hello), env({ kotlinc: null }))!.missing!.body).toMatch(
+ /Java was not found.*JDK/,
+ );
});
it("a Gradle / Maven project runs .kt mains through the build tool", () => {
const gradle = [cfg({ id: "gradle:run", kind: "gradle", command: "./gradlew", args: ["run"] })];
- const p = produceContext({ path: `${ROOT}/src/main/kotlin/App.kt`, root: ROOT, configs: gradle, content: hello }, KT)!;
+ const p = produceContext(
+ { path: `${ROOT}/src/main/kotlin/App.kt`, root: ROOT, configs: gradle, content: hello },
+ KT,
+ )!;
expect(p.config!.kind).not.toBe("kotlinc");
});
});
@@ -422,7 +526,8 @@ describe("compile-and-run lines on Windows", () => {
}) satisfies ToolEnv;
const DIR = String.raw`C:\Users\me\AppData\Local\Temp\openidea-run`;
/** The command with the per-file hash replaced by `H`. */
- const line = (p: { config?: { command: string } } | null) => p!.config!.command.replace(/-[0-9a-z]+(-test)?\.(exe|jar)/g, "-H$1.$2");
+ const line = (p: { config?: { command: string } } | null) =>
+ p!.config!.command.replace(/-[0-9a-z]+(-test)?\.(exe|jar)/g, "-H$1.$2");
it("cmd quoting: double quotes only where needed, never POSIX single quotes", () => {
expect(shellWord(String.raw`C:\Program Files\x.exe`, true)).toBe(String.raw`"C:\Program Files\x.exe"`);
@@ -445,7 +550,9 @@ describe("compile-and-run lines on Windows", () => {
it("clang / gcc and kotlinc", () => {
const c = produceContext(scratch("a.c", "int main(void) {}"), WIN({ gcc: null }))!;
- expect(c.config!.command).toMatch(/&& "C:\\Program Files\\Tools\\gcc\.exe" -g -o \S+\\a-\w+\.exe a\.c && \S+\\a-\w+\.exe$/);
+ expect(c.config!.command).toMatch(
+ /&& "C:\\Program Files\\Tools\\gcc\.exe" -g -o \S+\\a-\w+\.exe a\.c && \S+\\a-\w+\.exe$/,
+ );
const kt = produceContext(scratch("hello.kt", "fun main() {}"), WIN({ kotlinc: null, java: null }))!;
expect(kt.config!.command).toMatch(
/&& "C:\\Program Files\\Tools\\kotlinc\.exe" -include-runtime -d \S+\\hello-\w+\.jar hello\.kt && "C:\\Program Files\\Tools\\java\.exe" -jar \S+\\hello-\w+\.jar$/,
@@ -455,7 +562,11 @@ describe("compile-and-run lines on Windows", () => {
it("batch-file compilers (kotlinc.bat) are run with call", () => {
const e: ToolEnv = {
...WIN({}),
- tool: (n) => ({ kotlinc: { path: String.raw`C:\kotlin\bin\kotlinc.bat`, version: null }, java: { path: String.raw`C:\jdk\bin\java.exe`, version: null } })[n] ?? null,
+ tool: (n) =>
+ ({
+ kotlinc: { path: String.raw`C:\kotlin\bin\kotlinc.bat`, version: null },
+ java: { path: String.raw`C:\jdk\bin\java.exe`, version: null },
+ })[n] ?? null,
};
expect(line(produceContext(scratch("hello.kt", "fun main() {}"), e))).toBe(
`(if not exist ${DIR} mkdir ${DIR}) && call C:\\kotlin\\bin\\kotlinc.bat -include-runtime -d ${DIR}\\hello-H.jar hello.kt && C:\\jdk\\bin\\java.exe -jar ${DIR}\\hello-H.jar`,
@@ -465,8 +576,12 @@ describe("compile-and-run lines on Windows", () => {
it("a compile directory with spaces is quoted for cmd", () => {
const e = { ...WIN({ clang: null }), compileDir: "C:/Users/John Smith/Temp/openidea-run/" };
const p = produceContext(scratch("a.c", "int main() {}"), e)!;
- expect(p.config!.command).toMatch(/^\(if not exist "C:\\Users\\John Smith\\Temp\\openidea-run" mkdir "C:\\Users\\John Smith\\Temp\\openidea-run"\) && /);
- expect(p.config!.command).toMatch(/ -o "C:\\Users\\John Smith\\Temp\\openidea-run\\a-\w+\.exe" a\.c && "C:\\Users\\John Smith\\Temp\\openidea-run\\a-\w+\.exe"$/);
+ expect(p.config!.command).toMatch(
+ /^\(if not exist "C:\\Users\\John Smith\\Temp\\openidea-run" mkdir "C:\\Users\\John Smith\\Temp\\openidea-run"\) && /,
+ );
+ expect(p.config!.command).toMatch(
+ / -o "C:\\Users\\John Smith\\Temp\\openidea-run\\a-\w+\.exe" a\.c && "C:\\Users\\John Smith\\Temp\\openidea-run\\a-\w+\.exe"$/,
+ );
});
});
@@ -504,7 +619,11 @@ describe("Go test names (GoLand)", () => {
it("a test function: 'TestFoo in <import path>' with -run '^TestFoo$'", () => {
const p = at(5, modules);
expect(p.name).toBe("TestAdd in example.com/fixture/calc");
- expect(p.config).toMatchObject({ args: ["test", "./calc", "-run", "^TestAdd$"], debugAdapter: "delve", isTest: true });
+ expect(p.config).toMatchObject({
+ args: ["test", "./calc", "-run", "^TestAdd$"],
+ debugAdapter: "delve",
+ isTest: true,
+ });
});
it("subtests and table-driven entries", () => {
@@ -530,7 +649,9 @@ describe("Go test names (GoLand)", () => {
});
it("nested modules use their own go.mod", () => {
- const nested = [cfg({ id: "go:test:api", kind: "go", command: "go", args: ["test", "./..."], cwd: "api", isTest: true })];
+ const nested = [
+ cfg({ id: "go:test:api", kind: "go", command: "go", args: ["test", "./..."], cwd: "api", isTest: true }),
+ ];
const p = produceContext(
{
path: `${ROOT}/api/calc_test.go`,
diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts
index 87d74641c..fe528a8f3 100644
--- a/src/features/run/producers.ts
+++ b/src/features/run/producers.ts
@@ -129,9 +129,14 @@ export function goModuleDir(root: string, cwd: string | null): string {
* `TestFoo in <package>`, the package being its import path (module path from
* `go.mod`), else the `package` clause or directory.
*/
-export function goTestNamed(config: RunConfig, input: Pick<ContextInput, "root" | "content" | "goModule">, test?: string): RunConfig {
+export function goTestNamed(
+ config: RunConfig,
+ input: Pick<ContextInput, "root" | "content" | "goModule">,
+ test?: string,
+): RunConfig {
if (config.kind !== "go" || config.args[0] !== "test") return config;
- const pkgArg = config.args.find((a, i) => i > 0 && !a.startsWith("-") && !/^-(run|skip|bench)$/.test(config.args[i - 1]!)) ?? ".";
+ const pkgArg =
+ config.args.find((a, i) => i > 0 && !a.startsWith("-") && !/^-(run|skip|bench)$/.test(config.args[i - 1]!)) ?? ".";
const recursive = /(^|\/)\.\.\.$/.test(pkgArg);
const dir = pkgArg.replace(/\/?\.\.\.$/, "").replace(/^\.(?:\/|$)/, "");
const module = input.root ? input.goModule?.(goModuleDir(input.root, config.cwd)) : undefined;
@@ -271,7 +276,8 @@ const INSTALL: Record<string, string> = {
go: "Install Go from https://go.dev/dl (or `brew install go`).",
rust: "Install Rust with rustup: https://rustup.rs",
java: "Install a JDK 11+ (`brew install openjdk`), or download one in Settings › Languages & Frameworks › Java (Project JDK › Download JDK…).",
- kotlin: "Install the Kotlin compiler (`brew install kotlin`, or https://kotlinlang.org/docs/command-line.html) so that `kotlinc` is on the PATH.",
+ kotlin:
+ "Install the Kotlin compiler (`brew install kotlin`, or https://kotlinlang.org/docs/command-line.html) so that `kotlinc` is on the PATH.",
"kotlin-script": "Install Kotlin (`brew install kotlin`).",
swift: "Install the Xcode command line tools (`xcode-select --install`).",
c: "Install a C compiler: `xcode-select --install` (clang) or `brew install gcc`.",
@@ -360,7 +366,13 @@ function site(input: ContextInput): FileSite {
};
}
-function fileConfig(s: FileSite, kind: string, command: string, args: string[], debugAdapter: string | null = null): RunConfig {
+function fileConfig(
+ s: FileSite,
+ kind: string,
+ command: string,
+ args: string[],
+ debugAdapter: string | null = null,
+): RunConfig {
return {
id: `context:file:${s.idPath}`,
name: s.file,
@@ -381,9 +393,10 @@ function pythonCommand(input: ContextInput, env: ToolEnv, s: FileSite): { comman
const py = projectPython([...input.configs]);
if (py) {
// A venv-relative interpreter is relative to the project root.
- const command = !s.inProject && input.root && py.command.includes("/") && !py.command.startsWith("/")
- ? `${input.root}/${py.command.replace(/^\.\//, "")}`
- : py.command;
+ const command =
+ !s.inProject && input.root && py.command.includes("/") && !py.command.startsWith("/")
+ ? `${input.root}/${py.command.replace(/^\.\//, "")}`
+ : py.command;
return { command, prefix: py.prefix };
}
const t = pick(env, ["python3", "python"]);
@@ -496,7 +509,8 @@ function simple(
}
const hasGoMain = (content?: string) => content === undefined || /^\s*package\s+main\b/m.test(content);
-const hasRustMain = (content?: string) => content === undefined || /^(?:pub\s+)?(?:async\s+)?fn\s+main\s*\(/m.test(content);
+const hasRustMain = (content?: string) =>
+ content === undefined || /^(?:pub\s+)?(?:async\s+)?fn\s+main\s*\(/m.test(content);
const hasCMain = (content?: string) => content === undefined || /^\s*(?:int|void)\s+main\s*\(/m.test(content);
/** A top-level `fun main` (with or without `args`, `suspend` allowed). */
const hasKotlinMain = (content?: string) => content === undefined || /^(?:suspend\s+)?fun\s+main\s*\(/m.test(content);
@@ -597,7 +611,11 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
case "python": {
const py = pythonCommand(input, env, s);
if (!py) return { name: s.file, scope: "file", missing: missing("python", s.file, ["python3", "python"]) };
- return { name: s.file, scope: "file", config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy") };
+ return {
+ name: s.file,
+ scope: "file",
+ config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy"),
+ };
}
case "shell":
case "shebang": {
@@ -607,7 +625,12 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
const interp = interpreterName(sb[0]!);
if (/^python[\d.]*$/.test(interp)) {
const py = pythonCommand(input, env, s);
- if (py) return { name: s.file, scope: "file", config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy") };
+ if (py)
+ return {
+ name: s.file,
+ scope: "file",
+ config: fileConfig(s, "python", py.command, [...py.prefix, s.arg], "debugpy"),
+ };
}
const t = sb[0]!.startsWith("/") ? { command: sb[0]!, name: interp } : pick(env, [interp]);
if (!t) return { name: s.file, scope: "file", missing: missing(lang, s.file, [interp]) };
@@ -615,14 +638,30 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
return {
name: s.file,
scope: "file",
- config: fileConfig(s, kind, t.command, [...sb.slice(1), s.arg], interp === "node" || interp === "deno" ? "js-debug" : null),
+ config: fileConfig(
+ s,
+ kind,
+ t.command,
+ [...sb.slice(1), s.arg],
+ interp === "node" || interp === "deno" ? "js-debug" : null,
+ ),
};
}
// A shell script: the shell of its #! line, else by extension.
- const preferred = sb ? interpreterName(sb[0]!) : /\.bash$/.test(s.file) ? "bash" : /\.zsh$/.test(s.file) ? "zsh" : "sh";
+ const preferred = sb
+ ? interpreterName(sb[0]!)
+ : /\.bash$/.test(s.file)
+ ? "bash"
+ : /\.zsh$/.test(s.file)
+ ? "zsh"
+ : "sh";
const t = pick(env, [preferred]);
if (!t) return { name: s.file, scope: "file", missing: missing("shell", s.file, tools) };
- return { name: s.file, scope: "file", config: fileConfig(s, "shell", t.command, [...(sb?.slice(1) ?? []), s.arg]) };
+ return {
+ name: s.file,
+ scope: "file",
+ config: fileConfig(s, "shell", t.command, [...(sb?.slice(1) ?? []), s.arg]),
+ };
}
case "ruby":
case "php":
@@ -684,8 +723,7 @@ export function targetEnd(lines: readonly string[], target: RunTarget, python: b
let depth = 0;
let opened = false;
for (let i = start; i < lines.length; i++) {
- const code = lines[i]!
- .replace(/\/\/.*$/, "")
+ const code = lines[i]!.replace(/\/\/.*$/, "")
.replace(/"(?:[^"\\]|\\.)*"/g, '""')
.replace(/'(?:[^'\\]|\\.)*'/g, "''")
.replace(/`(?:[^`\\]|\\.)*`/g, "``");
@@ -702,7 +740,12 @@ export function targetEnd(lines: readonly string[], target: RunTarget, python: b
}
/** The innermost run target whose declaration contains `line`. */
-export function innermostTarget(content: string, targets: readonly RunTarget[], line: number, python = false): RunTarget | null {
+export function innermostTarget(
+ content: string,
+ targets: readonly RunTarget[],
+ line: number,
+ python = false,
+): RunTarget | null {
const lines = content.split("\n");
let best: RunTarget | null = null;
for (const t of targets) {
@@ -734,7 +777,8 @@ export function fileTargets(input: Pick<ContextInput, "path" | "root" | "configs
const s = { inProject: inProject(input.path, input.root), rel: relTo(input.path, input.root) };
const rust = /\.rs$/.test(input.path);
if (/\.(c|cpp|cc|cxx)$/.test(input.path)) return standaloneTargets(content, input.path);
- const cargo = s.inProject && (cargoOwner(s.rel, input.configs).length > 0 || /(^|\/)(src|tests|examples|benches)\//.test(s.rel));
+ const cargo =
+ s.inProject && (cargoOwner(s.rel, input.configs).length > 0 || /(^|\/)(src|tests|examples|benches)\//.test(s.rel));
if (rust && !cargo) return standaloneTargets(content, input.path);
if (!targetLanguage(input.path)) return [];
if (!s.inProject) {
@@ -795,7 +839,8 @@ export function produceContext(input: ContextInput, env: ToolEnv): Produced | nu
*/
export function produceContextChoices(input: ContextInput, env: ToolEnv): Produced[] {
const produced = produceContext(input, env);
- if (!produced?.config || produced.scope === "directory" || !inProject(input.path, input.root)) return produced ? [produced] : [];
+ if (!produced?.config || produced.scope === "directory" || !inProject(input.path, input.root))
+ return produced ? [produced] : [];
const rel = relTo(input.path, input.root);
const bases = testBasesFor(rel, [...input.configs]);
if (bases.length < 2) return [produced];
@@ -841,7 +886,10 @@ export function produceDirectory(input: ContextInput): Produced | null {
if (!cwd) return 0;
return rel === cwd || rel.startsWith(cwd + "/") ? cwd.length : -1;
};
- return cands.map((c) => [c, score(c)] as const).filter(([, n]) => n >= 0).sort((a, b) => b[1] - a[1])[0]?.[0];
+ return cands
+ .map((c) => [c, score(c)] as const)
+ .filter(([, n]) => n >= 0)
+ .sort((a, b) => b[1] - a[1])[0]?.[0];
};
const relToCwd = (c: RunConfig) => {
const cwd = (c.cwd ?? "").replace(/^\.\/?/, "").replace(/\/+$/, "");
@@ -863,7 +911,11 @@ export function produceDirectory(input: ContextInput): Produced | null {
const pkg = jvmPackage[2]!.replace(/\//g, ".");
return base.kind === "gradle"
? make(moduleBase, `Tests in '${pkg}'`, [...base.args, "--tests", `${pkg}.*`])
- : make(moduleBase, `Tests in '${pkg}'`, [...base.args, `-Dtest=${pkg}.**.*`, "-Dsurefire.failIfNoSpecifiedTests=false"]);
+ : make(moduleBase, `Tests in '${pkg}'`, [
+ ...base.args,
+ `-Dtest=${pkg}.**.*`,
+ "-Dsurefire.failIfNoSpecifiedTests=false",
+ ]);
}
}
const js = closest(["npm", "bun", "deno"]);
@@ -879,7 +931,11 @@ export function produceDirectory(input: ContextInput): Produced | null {
}
if (go) {
const dir = relToCwd(go);
- const p = make(go, testsIn, go.args.map((a) => (a === "./..." ? `./${dir}/...` : a)));
+ const p = make(
+ go,
+ testsIn,
+ go.args.map((a) => (a === "./..." ? `./${dir}/...` : a)),
+ );
const config = goTestNamed(p.config!, input);
return { ...p, name: config.name, config };
}
diff --git a/src/features/run/runConfigTypes.test.tsx b/src/features/run/runConfigTypes.test.tsx
index 4ec666e44..c928520f6 100644
--- a/src/features/run/runConfigTypes.test.tsx
+++ b/src/features/run/runConfigTypes.test.tsx
@@ -90,7 +90,11 @@ describe("configuration types", () => {
args: ["--path", ".", "res://one.tscn", "--debug-collisions"],
cwd: null,
});
- const detected = cfg("godot:project", { kind: "godot", command: "/Apps/Godot.app/Contents/MacOS/Godot", args: ["--path", "."] });
+ const detected = cfg("godot:project", {
+ kind: "godot",
+ command: "/Apps/Godot.app/Contents/MacOS/Godot",
+ args: ["--path", "."],
+ });
expect(godot.paramsFrom!(detected)).toEqual({ projectDir: "", scene: "", arguments: "" });
const scene = { ...detected, cwd: "demo", args: ["--path", ".", "res://a.tscn", "--verbose"] };
expect(godot.paramsFrom!(scene)).toEqual({ projectDir: "demo", scene: "res://a.tscn", arguments: "--verbose" });
diff --git a/src/features/run/runGutter.ts b/src/features/run/runGutter.ts
index ea69fa1b9..7065c62e6 100644
--- a/src/features/run/runGutter.ts
+++ b/src/features/run/runGutter.ts
@@ -107,7 +107,14 @@ export function targetMenuItems(target: RunTarget, path: string, content: string
return [
{ label: tx`Run '${name}'`, icon: "run", shortcut: shortcutLabel("run.runContext"), ...pick(false) } as MenuItem,
...(debuggable
- ? [{ label: tx`Debug '${name}'`, icon: "debug", shortcut: shortcutLabel("run.debugContext"), ...pick(true) } as MenuItem]
+ ? [
+ {
+ label: tx`Debug '${name}'`,
+ icon: "debug",
+ shortcut: shortcutLabel("run.debugContext"),
+ ...pick(true),
+ } as MenuItem,
+ ]
: []),
...runExecutors()
.filter((e) => !!p?.config && e.supports(p.config))
@@ -187,7 +194,8 @@ const DEBOUNCE = 350;
export function runGutter(ctx: EditorDocContext): Extension {
const path = ctx.path;
if (!useProject.getState().project?.root || isVirtualUri(path) || !hasGutterTargets(path)) return [];
- if (/\.go$/.test(path)) void loadGoModules(useProject.getState().project?.root ?? null, useRun.getState().configs).catch(() => {});
+ if (/\.go$/.test(path))
+ void loadGoModules(useProject.getState().project?.root ?? null, useRun.getState().configs).catch(() => {});
const detect = (text: string) =>
fileTargets({ path, root: useProject.getState().project?.root ?? null, configs: useRun.getState().configs }, text);
diff --git a/src/features/run/runtimes.ts b/src/features/run/runtimes.ts
index 4c93c478f..b8bb4b3a5 100644
--- a/src/features/run/runtimes.ts
+++ b/src/features/run/runtimes.ts
@@ -42,7 +42,10 @@ async function viaSdkDetect(names: string[]): Promise<Map<string, LocatedTool |
}
/** Looks up `names` near `file` (cached). */
-export async function locateTools(names: string[], file: string | null): Promise<Map<string, LocatedTool | null | undefined>> {
+export async function locateTools(
+ names: string[],
+ file: string | null,
+): Promise<Map<string, LocatedTool | null | undefined>> {
const near = file ? dirOf(file) : "";
const now = Date.now();
const out = new Map<string, LocatedTool | null | undefined>();
@@ -98,7 +101,12 @@ async function rootMarkers(root: string | null): Promise<{ deno: boolean; bun: b
}
/** The tool environment for running `file` with any of `names`. */
-export async function toolEnv(names: string[], file: string | null, root: string | null, python: boolean): Promise<ToolEnv> {
+export async function toolEnv(
+ names: string[],
+ file: string | null,
+ root: string | null,
+ python: boolean,
+): Promise<ToolEnv> {
const [tools, py, markers] = await Promise.all([
locateTools(names, file),
python ? projectPython() : Promise.resolve(null),
diff --git a/src/features/run/session.test.tsx b/src/features/run/session.test.tsx
index 5d1d4a787..c3a57b27d 100644
--- a/src/features/run/session.test.tsx
+++ b/src/features/run/session.test.tsx
@@ -17,7 +17,12 @@ import { closeSessionTab, resetRuns, startRun, useRun, type RunSession } from ".
const confirm = vi.hoisted(() => vi.fn(async () => true));
const confirmTerminate = vi.hoisted(() => vi.fn(async () => true));
-vi.mock("./dialogs", () => ({ confirmRerun: confirm, confirmTerminate, promptValue: vi.fn(), RunDialogsOverlay: () => null }));
+vi.mock("./dialogs", () => ({
+ confirmRerun: confirm,
+ confirmTerminate,
+ promptValue: vi.fn(),
+ RunDialogsOverlay: () => null,
+}));
const config = (id: string, extra: Partial<RunConfig> = {}): RunConfig => ({
id,
diff --git a/src/features/run/store.ts b/src/features/run/store.ts
index e177b3a64..70990a87d 100644
--- a/src/features/run/store.ts
+++ b/src/features/run/store.ts
@@ -5,7 +5,15 @@
*/
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
-import { call, commands, isTauri, type OutputChunk, type RunConfig, type RunId, type TestCaseReport } from "@/platform/ipc";
+import {
+ call,
+ commands,
+ isTauri,
+ type OutputChunk,
+ type RunConfig,
+ type RunId,
+ type TestCaseReport,
+} from "@/platform/ipc";
import { formatCompileErrors, isJvmApplication, parseJavaArgs, resolveJavaCommand } from "@/platform/javaLaunch";
import { downloadJdkActions } from "@/platform/jdk";
import { useProject } from "@/platform/project";
@@ -15,7 +23,14 @@ import { maybeEditorService, notifications, toolWindowService } from "@/workbenc
import { ConsoleModel } from "./console";
import { jvmFrameTarget } from "./links";
import { confirmRerun, confirmTerminate } from "./dialogs";
-import { createTestParser, frameworkFor, TestResults, withTestReporting, type TestEvent, type TestOutputParser } from "./testing";
+import {
+ createTestParser,
+ frameworkFor,
+ TestResults,
+ withTestReporting,
+ type TestEvent,
+ type TestOutputParser,
+} from "./testing";
import { recordTestStates } from "./testing/states";
import { failedTestPaths, leafTestPaths, rerunFailedConfig, testsConfig } from "./testing/rerun";
import { compoundChildren } from "./configs";
@@ -220,7 +235,10 @@ function persistTemporary() {
const root = useProject.getState().project?.root;
if (!root) return;
const { configs, temporary } = useRun.getState();
- writeTemporary(root, temporary.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c));
+ writeTemporary(
+ root,
+ temporary.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c),
+ );
}
export function isTemporary(id: string | null | undefined): boolean {
@@ -240,12 +258,17 @@ export function adoptTemporary(config: RunConfig): RunConfig {
return existing;
}
let temporary = [...state.temporary.filter((id) => id !== config.id), config.id];
- const busy = new Set(state.sessions.filter((x) => x.status === "running" || x.status === "starting").map((x) => x.config.id));
+ const busy = new Set(
+ state.sessions.filter((x) => x.status === "running" || x.status === "starting").map((x) => x.config.id),
+ );
while (temporary.length > MAX_TEMPORARY) {
const evict = temporary.find((id) => id !== config.id && !busy.has(id)) ?? temporary[0]!;
temporary = temporary.filter((id) => id !== evict);
}
- const configs = [...state.configs.filter((c) => c.id !== config.id && (!state.temporary.includes(c.id) || temporary.includes(c.id))), config];
+ const configs = [
+ ...state.configs.filter((c) => c.id !== config.id && (!state.temporary.includes(c.id) || temporary.includes(c.id))),
+ config,
+ ];
useRun.setState({ configs, temporary });
persistTemporary();
selectConfig(config.id);
@@ -386,7 +409,9 @@ export async function prepareLaunch(config: RunConfig, chain: readonly string[]
export async function startCompound(config: RunConfig, chain: readonly string[] = []): Promise<RunSession[]> {
if (!(await prepareLaunch(config, chain))) return [];
const children = compoundChildren(config, useRun.getState().configs);
- const sessions = await Promise.all(children.map((c) => startRun(c, undefined, undefined, { chain: [...chain, config.id] })));
+ const sessions = await Promise.all(
+ children.map((c) => startRun(c, undefined, undefined, { chain: [...chain, config.id] })),
+ );
return sessions.filter((s): s is RunSession => !!s);
}
@@ -438,9 +463,14 @@ export async function startRun(
let session = reuse ? state.sessions.find((s) => s.id === reuse) : undefined;
// As in IDEA, a configuration that doesn't allow parallel
// runs asks before stopping its running instances; rerunning a tab restarts it without asking.
- const others = config.allowParallel ? [] : state.sessions.filter((s) => s.config.id === config.id && busy(s) && s.id !== session?.id);
+ const others = config.allowParallel
+ ? []
+ : state.sessions.filter((s) => s.config.id === config.id && busy(s) && s.id !== session?.id);
if (others.length) {
- if (workflowSettings().run.confirmRerun && !(await confirmRerun(config.name, others.length + (session && busy(session) ? 1 : 0))))
+ if (
+ workflowSettings().run.confirmRerun &&
+ !(await confirmRerun(config.name, others.length + (session && busy(session) ? 1 : 0)))
+ )
return null;
await Promise.all(others.map((s) => stopSession(s.id)));
session ??= others[0];
@@ -474,7 +504,10 @@ export async function startRun(
stopped: false,
};
const updated = session;
- useRun.setState((s) => ({ sessions: s.sessions.map((x) => (x.id === updated.id ? updated : x)), activeSession: updated.id }));
+ useRun.setState((s) => ({
+ sessions: s.sessions.map((x) => (x.id === updated.id ? updated : x)),
+ activeSession: updated.id,
+ }));
} else {
session = {
id: `run${++sessionSeq}`,
@@ -499,7 +532,8 @@ export async function startRun(
rt.onExit = options.onExit;
try {
if (config.focusToolWindow) toolWindowService().show("run", true);
- else if (options.show ?? config.openToolWindow ?? workflowSettings().run.showOnStart) toolWindowService().show("run");
+ else if (options.show ?? config.openToolWindow ?? workflowSettings().run.showOnStart)
+ toolWindowService().show("run");
} catch {
/* no workbench (tests) */
}
@@ -595,7 +629,8 @@ async function resolveJvmApplication(sessionId: string, config: RunConfig): Prom
say(`Building and resolving the classpath of ${parsed.mainClass}…\n`);
try {
const info = await call(commands.javaResolveLaunch(config.cwd ?? "", parsed.classpath === "test", true));
- if (info.build === "withErrors") say("Build completed with errors; launching with the last compiled classes.\n", "stderr");
+ if (info.build === "withErrors")
+ say("Build completed with errors; launching with the last compiled classes.\n", "stderr");
if (info.build === "failed") say("Build failed; launching with the last compiled classes.\n", "stderr");
const compileReport = formatCompileErrors(info);
if (compileReport) say(compileReport, "stderr");
@@ -620,7 +655,13 @@ async function resolveJvmApplication(sessionId: string, config: RunConfig): Prom
say(`Cannot resolve the classpath: ${message}\n`, "stderr");
// jdtls can't start without a newer JDK: "Download JDK 25".
const actions = downloadJdkActions(message);
- notifications().notify({ group: "run", level: "error", title: `Cannot run '${config.name}'`, body: message, actions });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: `Cannot run '${config.name}'`,
+ body: message,
+ actions,
+ });
return null;
}
}
@@ -680,9 +721,9 @@ export function testReportEvents(reports: readonly TestCaseReport[]): TestEvent[
const text = [r.message, r.output].filter(Boolean).join("\n");
for (const line of text.split("\n").slice(0, 200)) events.push({ type: "output", path, line });
const outer = r.className.split("$")[0]!;
- const frame = new RegExp(`at (${outer.replace(/[.$]/g, "\\$&")}(?:\\$[\\w$]+)?)\\.[\\w$<>]+\\(([\\w$-]+\\.(?:java|kt|groovy|scala)):(\\d+)\\)`).exec(
- r.output ?? "",
- );
+ const frame = new RegExp(
+ `at (${outer.replace(/[.$]/g, "\\$&")}(?:\\$[\\w$]+)?)\\.[\\w$<>]+\\(([\\w$-]+\\.(?:java|kt|groovy|scala)):(\\d+)\\)`,
+ ).exec(r.output ?? "");
if (frame) events.push({ type: "location", path, location: jvmFrameTarget(frame[1], frame[2]!, Number(frame[3])) });
}
return events;
@@ -736,7 +777,12 @@ export async function stopSession(sessionId: string): Promise<void> {
try {
await call(commands.runStop(session.runId));
} catch (e) {
- notifications().notify({ group: "run", level: "error", title: "Cannot stop process", body: e instanceof Error ? e.message : String(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: "Cannot stop process",
+ body: e instanceof Error ? e.message : String(e),
+ });
}
}
@@ -766,7 +812,11 @@ export function rerunFailed(sessionId: string): boolean {
* Run / Debug the tests selected in a session's test tree (IDEA: a temporary
* configuration for them). False when the framework can't filter tests.
*/
-export async function runSelectedTests(sessionId: string, nodeIds: readonly string[], debug: boolean): Promise<boolean> {
+export async function runSelectedTests(
+ sessionId: string,
+ nodeIds: readonly string[],
+ debug: boolean,
+): Promise<boolean> {
const session = getSession(sessionId);
const tests = runtimes.get(sessionId)?.tests;
if (!session || !tests) return false;
@@ -776,7 +826,10 @@ export async function runSelectedTests(sessionId: string, nodeIds: readonly stri
const name = nodes.length === 1 ? nodes[0]!.name : `${paths.length} tests`;
const derived = testsConfig(base, paths, name);
if (!derived) return false;
- const config = adoptTemporary({ ...derived, id: `context:tests:${base.id}:${paths.map((p) => p.join("/")).join("|")}` });
+ const config = adoptTemporary({
+ ...derived,
+ id: `context:tests:${base.id}:${paths.map((p) => p.join("/")).join("|")}`,
+ });
if (debug) await executeAction("run.debugConfig", config);
else await startRun(config);
return true;
@@ -803,7 +856,10 @@ export async function sendStdin(sessionId: string, text: string): Promise<void>
try {
await call(commands.runStdin(session.runId, text + "\n"));
} catch (e) {
- enqueue(sessionId, { kind: "system", text: tx`Cannot write to stdin: ${e instanceof Error ? e.message : String(e)}\n` });
+ enqueue(sessionId, {
+ kind: "system",
+ text: tx`Cannot write to stdin: ${e instanceof Error ? e.message : String(e)}\n`,
+ });
}
}
@@ -846,7 +902,8 @@ export async function closeSessionTab(sessionId: string): Promise<boolean> {
const session = getSession(sessionId);
if (!session) return false;
const running = session.status === "running" || session.status === "starting";
- if (running && workflowSettings().run.confirmTerminate && !(await confirmTerminate(session.config.name))) return false;
+ if (running && workflowSettings().run.confirmTerminate && !(await confirmTerminate(session.config.name)))
+ return false;
closeSession(sessionId);
return true;
}
@@ -913,5 +970,10 @@ export function modifyTemporary(config: RunConfig) {
useRun.setState({ configs: st.configs.map((c) => (c.id === adopted.id ? { ...c, detected: true } : c)) });
persistTemporary();
});
- useRun.setState({ editorOpen: true, chooserOpen: false, editTarget: adopted.id, editDirty: adopted.detected === false });
+ useRun.setState({
+ editorOpen: true,
+ chooserOpen: false,
+ editTarget: adopted.id,
+ editDirty: adopted.detected === false,
+ });
}
diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts
index f39de78da..a951c6d41 100644
--- a/src/features/run/targets.ts
+++ b/src/features/run/targets.ts
@@ -198,7 +198,8 @@ function goSubtests(lines: string[], start: number, test: string): RunTarget[] {
const out: RunTarget[] = [];
const add = (offset: number, name: string) => {
const sub = goSubtestName(name.replace(/\\(.)/g, "$1"));
- if (!out.some((t) => t.path[1] === sub)) out.push({ line: start + 1 + offset, kind: "test", name: `${test}/${sub}`, path: [test, sub] });
+ if (!out.some((t) => t.path[1] === sub))
+ out.push({ line: start + 1 + offset, kind: "test", name: `${test}/${sub}`, path: [test, sub] });
};
const fields = new Set<string>();
const keys = new Set<string>();
@@ -208,7 +209,8 @@ function goSubtests(lines: string[], start: number, test: string): RunTarget[] {
const field = /\b\w+\.Run\(\s*\w+\.(\w+)\s*,/.exec(l);
if (field) fields.add(field[1]!);
const key = /\b\w+\.Run\(\s*(\w+)\s*,/.exec(l);
- if (key && body.slice(0, i).some((b) => new RegExp(`\\bfor\\s+${key[1]}\\s*,\\s*\\w+\\s*:=\\s*range\\b`).test(b))) keys.add(key[1]!);
+ if (key && body.slice(0, i).some((b) => new RegExp(`\\bfor\\s+${key[1]}\\s*,\\s*\\w+\\s*:=\\s*range\\b`).test(b)))
+ keys.add(key[1]!);
});
if (fields.size || keys.size) {
body.forEach((l, i) => {
@@ -231,7 +233,14 @@ function javaKotlinTargets(text: string, relPath: string): RunTarget[] {
const simple = simpleClassName(t.className);
switch (t.kind) {
case "main":
- return { line: t.line, kind: "main", name: simple, path: [t.className], className: t.className, spring: t.spring };
+ return {
+ line: t.line,
+ kind: "main",
+ name: simple,
+ path: [t.className],
+ className: t.className,
+ spring: t.spring,
+ };
case "suite":
return { line: t.line, kind: "suite", name: simple, path: [t.className], className: t.className };
default:
@@ -323,13 +332,18 @@ export function targetConfig(
base?: RunConfig,
): RunConfig | null {
if (target.kind === "main") {
- if (target.className) return applicationConfig({ className: target.className, spring: target.spring }, relPath, configs);
+ if (target.className)
+ return applicationConfig({ className: target.className, spring: target.spring }, relPath, configs);
return contextConfig(relPath, configs, content);
}
const file = testConfigFor(relPath, configs, base);
if (!file) return null;
if (target.className && (file.kind === "maven" || file.kind === "gradle"))
- return jvmTestConfig(file, target.className, target.kind === "test" ? target.path[target.path.length - 1] : undefined);
+ return jvmTestConfig(
+ file,
+ target.className,
+ target.kind === "test" ? target.path[target.path.length - 1] : undefined,
+ );
const shortName = target.kind === "suite" ? target.path[target.path.length - 1]! : target.name;
const named = (args: string[]): RunConfig => ({
...file,
diff --git a/src/features/run/testing/cargo.ts b/src/features/run/testing/cargo.ts
index 0983ce641..2a56c8948 100644
--- a/src/features/run/testing/cargo.ts
+++ b/src/features/run/testing/cargo.ts
@@ -10,7 +10,8 @@ const PANIC_RE = /panicked at (?:'.*', |".*", )?([^\s:'"][^:'"]*):(\d+):(\d+)/;
const SUMMARY_RE =
/^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed; (\d+) ignored;.*?(?:finished in ([\d.]+s))?$/;
const NEXTEST_RE = /^\s*(PASS|FAIL|SKIP|SIGSEGV|SIGABRT|TIMEOUT|LEAK)\s+\[\s*([\d.]+s)\]\s+(\S+)\s+(.+)$/;
-const NEXTEST_SUMMARY_RE = /^\s*Summary \[\s*([\d.]+s)\]\s+(\d+) tests? run: (\d+) passed(?:.*?(\d+) failed)?(?:.*?(\d+) skipped)?/;
+const NEXTEST_SUMMARY_RE =
+ /^\s*Summary \[\s*([\d.]+s)\]\s+(\d+) tests? run: (\d+) passed(?:.*?(\d+) failed)?(?:.*?(\d+) skipped)?/;
export function cargoParser(): TestOutputParser {
let suite: string | null = null;
diff --git a/src/features/run/testing/go.ts b/src/features/run/testing/go.ts
index 9fd81ddc0..88cf6f674 100644
--- a/src/features/run/testing/go.ts
+++ b/src/features/run/testing/go.ts
@@ -46,7 +46,12 @@ export function goParser(): TestOutputParser {
const events = flush(pkg);
// Without -v a passing package prints nothing per test: show the package itself.
if (!events.some((e) => e.type === "result")) {
- events.push({ type: "result", path: [pkg], status: m[1] === "ok" ? "passed" : "failed", durationMs: parseDuration(m[3]) });
+ events.push({
+ type: "result",
+ path: [pkg],
+ status: m[1] === "ok" ? "passed" : "failed",
+ durationMs: parseDuration(m[3]),
+ });
}
events.push({ type: "summary", ...totals });
return events;
@@ -57,7 +62,11 @@ export function goParser(): TestOutputParser {
const key = current.join("/");
if (loc && !located.has(key)) {
located.add(key);
- buffer.push({ type: "location", path: current, location: { path: loc[1]!, line: Number(loc[2]), resolve: "name" } });
+ buffer.push({
+ type: "location",
+ path: current,
+ location: { path: loc[1]!, line: Number(loc[2]), resolve: "name" },
+ });
}
}
return [];
diff --git a/src/features/run/testing/jvm.ts b/src/features/run/testing/jvm.ts
index cec56175a..b0344419d 100644
--- a/src/features/run/testing/jvm.ts
+++ b/src/features/run/testing/jvm.ts
@@ -8,7 +8,8 @@ const FRAME_RE =
/(?:([\w$]+(?:\.[\w$]+)*)\.[\w$<>-]+)?\(([\w$.-]+\.(?:java|kt|kts|scala|groovy)):(\d+)\)|\bat ([\w$.-]+\.(?:java|kt|kts|scala|groovy)):(\d+)/;
// [ERROR] com.acme.OrderTest.shouldX -- Time elapsed: 0.01 s <<< FAILURE! (Surefire 3)
// shouldX(com.acme.OrderTest) Time elapsed: 0.01 sec <<< FAILURE! (Surefire 2)
-const SUREFIRE3_RE = /^(?:\[\w+\]\s+)?([\w$.]+)\.([\w$]+)(?:\(\))?\s+--\s+Time elapsed: ([\d.]+ s(?:ec)?)\s+<<<\s+(FAILURE|ERROR)!/;
+const SUREFIRE3_RE =
+ /^(?:\[\w+\]\s+)?([\w$.]+)\.([\w$]+)(?:\(\))?\s+--\s+Time elapsed: ([\d.]+ s(?:ec)?)\s+<<<\s+(FAILURE|ERROR)!/;
const SUREFIRE2_RE = /^(?:\[\w+\]\s+)?([\w$]+)\(([\w$.]+)\)\s+Time elapsed: ([\d.]+ s(?:ec)?)\s+<<<\s+(FAILURE|ERROR)!/;
const SUREFIRE_CLASS_RE =
/^(?:\[\w+\]\s+)?Tests run: (\d+), Failures: (\d+), Errors: (\d+), Skipped: (\d+), Time elapsed: ([\d.]+ s(?:ec)?).*?(?:-- in |- in )([\w$.]+)\s*$/;
@@ -79,7 +80,10 @@ export function jvmParser(): TestOutputParser {
}
events.push({ type: "output", path: failure, line });
const f = FRAME_RE.exec(line);
- const libraryFrame = /^\s*at\s+(?:org\.junit|junit\.|org\.opentest4j|kotlin\.|jdk\.internal|java\.|javax\.|sun\.|org\.gradle)/.test(line);
+ const libraryFrame =
+ /^\s*at\s+(?:org\.junit|junit\.|org\.opentest4j|kotlin\.|jdk\.internal|java\.|javax\.|sun\.|org\.gradle)/.test(
+ line,
+ );
if (f && !located && !libraryFrame) {
located = true;
events.push({
diff --git a/src/features/run/testing/parsers.test.ts b/src/features/run/testing/parsers.test.ts
index d5cd001f0..67522b9a8 100644
--- a/src/features/run/testing/parsers.test.ts
+++ b/src/features/run/testing/parsers.test.ts
@@ -415,7 +415,10 @@ describe("parser selection", () => {
});
it("the combined parser understands any supported format", () => {
- const r = results(createTestParser(cfg("make", "make", ["test"])), "test a ... ok\n--- PASS: TestB (0.00s)\nok \tpkg\t0.1s");
+ const r = results(
+ createTestParser(cfg("make", "make", ["test"])),
+ "test a ... ok\n--- PASS: TestB (0.00s)\nok \tpkg\t0.1s",
+ );
expect(leaf(r, "a")?.own).toBe("passed");
expect(leaf(r, "pkg", "TestB")?.own).toBe("passed");
});
diff --git a/src/features/run/testing/pytest.ts b/src/features/run/testing/pytest.ts
index dce03153f..d5e935f9a 100644
--- a/src/features/run/testing/pytest.ts
+++ b/src/features/run/testing/pytest.ts
@@ -7,7 +7,9 @@ const OUTCOME = String.raw`(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)`;
// `tests/test_x.py::TestC::test_y[1] PASSED [ 50%]`
const VERBOSE_RE = new RegExp(String.raw`^(\S+\.py::\S+)\s+${OUTCOME}(?:\s|$)`);
// `[gw0] PASSED tests/test_x.py::test_add` (xdist) and short summary `FAILED tests/test_x.py::test_sub - msg`
-const PREFIX_RE = new RegExp(String.raw`^(?:\[gw\d+\]\s+(?:\[\s*\d+%\]\s+)?)?${OUTCOME}\s+(\S+\.py::\S+?)(?:\s+-\s+.*)?$`);
+const PREFIX_RE = new RegExp(
+ String.raw`^(?:\[gw\d+\]\s+(?:\[\s*\d+%\]\s+)?)?${OUTCOME}\s+(\S+\.py::\S+?)(?:\s+-\s+.*)?$`,
+);
// `tests/test_x.py .F.s [100%]`
const PROGRESS_RE = /^(\S+\.py) ([.FEsxX]+)\s*(?:\[\s*\d+%\])?$/;
const SECTION_RE = /^_{3,} (.+?) _{3,}$/;
diff --git a/src/features/run/types.ts b/src/features/run/types.ts
index cd2adc6df..8b4f68935 100644
--- a/src/features/run/types.ts
+++ b/src/features/run/types.ts
@@ -134,9 +134,16 @@ const godot: RunConfigTypeContribution = {
mono: true,
placeholder: "Main scene",
hint: "e.g. res://levels/level_1.tscn; empty runs the project's main scene",
- suggestions: (configs) => [...new Set(configs.filter((c) => c.kind === "godot").flatMap((c) => c.args.filter(isScene)))],
+ suggestions: (configs) => [
+ ...new Set(configs.filter((c) => c.kind === "godot").flatMap((c) => c.args.filter(isScene))),
+ ],
+ },
+ {
+ key: "arguments",
+ label: "Arguments",
+ mono: true,
+ placeholder: "Godot command line options, e.g. --debug-collisions",
},
- { key: "arguments", label: "Arguments", mono: true, placeholder: "Godot command line options, e.g. --debug-collisions" },
],
commandLine: (p) => ({
command: "godot",
@@ -245,21 +252,33 @@ function buildToolType(
};
}
-const gradle = buildToolType("gradle", "Gradle", "file-gradle", { label: "Tasks", description: "Run Gradle tasks" }, {
- unix: "gradlew",
- windows: "gradlew.bat",
- plain: "gradle",
- label: "Use the Gradle wrapper",
- byDefault: true,
-});
+const gradle = buildToolType(
+ "gradle",
+ "Gradle",
+ "file-gradle",
+ { label: "Tasks", description: "Run Gradle tasks" },
+ {
+ unix: "gradlew",
+ windows: "gradlew.bat",
+ plain: "gradle",
+ label: "Use the Gradle wrapper",
+ byDefault: true,
+ },
+);
-const maven = buildToolType("maven", "Maven", "file-maven", { label: "Goals", description: "Run Maven goals" }, {
- unix: "mvnw",
- windows: "mvnw.cmd",
- plain: "mvn",
- label: "Use the Maven wrapper",
- byDefault: false,
-});
+const maven = buildToolType(
+ "maven",
+ "Maven",
+ "file-maven",
+ { label: "Goals", description: "Run Maven goals" },
+ {
+ unix: "mvnw",
+ windows: "mvnw.cmd",
+ plain: "mvn",
+ label: "Use the Maven wrapper",
+ byDefault: false,
+ },
+);
const compound: RunConfigTypeContribution = {
id: COMPOUND,
@@ -270,7 +289,15 @@ const compound: RunConfigTypeContribution = {
commandLine: () => null,
};
-export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [shell, program, npm, gradle, maven, godot, compound];
+export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
+ shell,
+ program,
+ npm,
+ gradle,
+ maven,
+ godot,
+ compound,
+];
export function registerBuiltinTypes(): () => void {
const disposers = BUILTIN_TYPES.map(registerRunConfigType);
diff --git a/src/features/run/workflow.test.ts b/src/features/run/workflow.test.ts
index 825b8f286..d18380406 100644
--- a/src/features/run/workflow.test.ts
+++ b/src/features/run/workflow.test.ts
@@ -29,7 +29,9 @@ describe("console settings", () => {
m.append({ kind: "stderr", text: "Error\n at org.junit.A\n at org.junit.B\n at app.Main\n at org.junit.C\n" });
const rows = foldRows(m.lines, ["at org.junit."], new Set());
const show = (rs: typeof rows) =>
- rs.map((r) => (r.kind === "fold" ? `fold${r.fold.count}` : m.lines[r.index]!.text.trim() + (r.fold ? ` +${r.fold.count}` : "")));
+ rs.map((r) =>
+ r.kind === "fold" ? `fold${r.fold.count}` : m.lines[r.index]!.text.trim() + (r.fold ? ` +${r.fold.count}` : ""),
+ );
expect(show(rows)).toEqual(["Error +2", "at app.Main +1"]);
const first = rows[0]!.kind === "line" ? rows[0]!.fold! : null;
const open = foldRows(m.lines, ["at org.junit."], new Set([first!.id]));
@@ -58,11 +60,19 @@ describe("external tools", () => {
expect(expandMacros("$FileName$ $FileNameWithoutExtension$ $FileExt$ $FileRelativePath$", ctx)).toBe(
"main.rs main rs src/main.rs",
);
- expect(expandMacros("$ProjectFileDir$:$LineNumber$:$ColumnNumber$ $Unknown$ $Prompt$", ctx, "x")).toBe("/p:3:5 $Unknown$ x");
+ expect(expandMacros("$ProjectFileDir$:$LineNumber$:$ColumnNumber$ $Unknown$ $Prompt$", ctx, "x")).toBe(
+ "/p:3:5 $Unknown$ x",
+ );
});
it("builds a run configuration with per-argument expansion", () => {
- const tool = { ...DEFAULT_EXTERNAL_TOOL, id: "t", name: "Fmt", program: "rustfmt", arguments: `--edition 2021 "$FilePath$"` };
+ const tool = {
+ ...DEFAULT_EXTERNAL_TOOL,
+ id: "t",
+ name: "Fmt",
+ program: "rustfmt",
+ arguments: `--edition 2021 "$FilePath$"`,
+ };
expect(toolRunConfig(tool, { ...ctx, filePath: "/p/my dir/a.rs" })).toMatchObject({
id: "external:t",
command: "rustfmt",
diff --git a/src/features/scratch/__tests__/scratch.test.tsx b/src/features/scratch/__tests__/scratch.test.tsx
index 76d1cc8e9..5ba67b655 100644
--- a/src/features/scratch/__tests__/scratch.test.tsx
+++ b/src/features/scratch/__tests__/scratch.test.tsx
@@ -28,11 +28,21 @@ describe("scratch naming", () => {
describe("language chooser rows", () => {
it("keeps languages with an extension, sorted by name, first extension wins", () => {
- expect(LANGS.map((l) => `${l.name}:${l.ext}`)).toEqual(["Java:java", "JavaScript:js", "Plain Text:txt", "Python:py"]);
+ expect(LANGS.map((l) => `${l.name}:${l.ext}`)).toEqual([
+ "Java:java",
+ "JavaScript:js",
+ "Plain Text:txt",
+ "Python:py",
+ ]);
});
it("puts recently used languages first when not filtering", () => {
- expect(chooserRows(LANGS, ["python", "gone"], "").map((r) => r.lang.id)).toEqual(["python", "java", "javascript", "plaintext"]);
+ expect(chooserRows(LANGS, ["python", "gone"], "").map((r) => r.lang.id)).toEqual([
+ "python",
+ "java",
+ "javascript",
+ "plaintext",
+ ]);
});
it("filters by name prefix, then fuzzy, then extension", () => {
@@ -83,7 +93,9 @@ describe("creating scratch files", () => {
it("registers the action and the Scratches root; the chooser creates the picked language", async () => {
const dispose = activate();
try {
- await vi.waitFor(() => expect(useProjectViewRoots.getState().roots.get("scratches")?.path).toBe("/data/scratches"));
+ await vi.waitFor(() =>
+ expect(useProjectViewRoots.getState().roots.get("scratches")?.path).toBe("/data/scratches"),
+ );
expect(useProjectViewRoots.getState().roots.get("scratches")?.label).toBe("Scratches");
const action = getAction("file.newScratchFile")!;
expect(action.title).toBe("New Scratch File…");
diff --git a/src/features/scratch/index.ts b/src/features/scratch/index.ts
index 04475dfe2..e489a8b20 100644
--- a/src/features/scratch/index.ts
+++ b/src/features/scratch/index.ts
@@ -25,7 +25,14 @@ export function activate(): () => void {
.then((path) => {
if (disposed) return;
dir = path;
- unregisterRoot = registerProjectViewRoot({ id: "scratches", label: SCRATCHES_ROOT_LABEL, icon: "scratches", path, order: 10, scope: "scratches" });
+ unregisterRoot = registerProjectViewRoot({
+ id: "scratches",
+ label: SCRATCHES_ROOT_LABEL,
+ icon: "scratches",
+ path,
+ order: 10,
+ scope: "scratches",
+ });
})
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
const disposers = [
diff --git a/src/features/scratch/model.ts b/src/features/scratch/model.ts
index 7a7412b87..f559271e4 100644
--- a/src/features/scratch/model.ts
+++ b/src/features/scratch/model.ts
@@ -20,7 +20,9 @@ export function scratchFileName(existing: Iterable<string>, ext: string): string
}
/** Languages a scratch file can be created for (those with an extension), by name. */
-export function scratchLanguages(langs: ReadonlyArray<{ id: string; name: string; extensions: readonly string[] }>): ScratchLanguage[] {
+export function scratchLanguages(
+ langs: ReadonlyArray<{ id: string; name: string; extensions: readonly string[] }>,
+): ScratchLanguage[] {
const out: ScratchLanguage[] = [];
for (const l of langs) {
const ext = l.extensions.find((e) => e.trim())?.replace(/^\./, "");
@@ -39,7 +41,11 @@ export interface LanguageRow {
* filtering; with a filter, prefix matches of the name, then fuzzy matches,
* then extension matches.
*/
-export function chooserRows(langs: readonly ScratchLanguage[], recent: readonly string[], filter: string): LanguageRow[] {
+export function chooserRows(
+ langs: readonly ScratchLanguage[],
+ recent: readonly string[],
+ filter: string,
+): LanguageRow[] {
const q = filter.trim().toLowerCase();
if (!q) {
const byId = new Map(langs.map((l) => [l.id, l]));
@@ -55,7 +61,8 @@ export function chooserRows(langs: readonly ScratchLanguage[], recent: readonly
else {
const m = fuzzyMatch(lang.name, q);
if (m) fuzzy.push({ lang, matches: m });
- else if (lang.ext.toLowerCase().startsWith(q) || lang.id.toLowerCase().startsWith(q)) ext.push({ lang, matches: null });
+ else if (lang.ext.toLowerCase().startsWith(q) || lang.id.toLowerCase().startsWith(q))
+ ext.push({ lang, matches: null });
}
}
return [...prefix, ...fuzzy, ...ext];
diff --git a/src/features/search/__tests__/bookmarkPopups.test.tsx b/src/features/search/__tests__/bookmarkPopups.test.tsx
index c3c1d1e2c..f3a88fd50 100644
--- a/src/features/search/__tests__/bookmarkPopups.test.tsx
+++ b/src/features/search/__tests__/bookmarkPopups.test.tsx
@@ -47,7 +47,13 @@ describe("Bookmarks popup", () => {
{ path: "/p/a", line: 5, text: "five", created: 2, mnemonic: "3" },
{ path: "/p/b", line: 0, text: "zero", created: 3 },
]);
- expect(bookmarkRows(useBookmarks.getState().items).map((r) => r.kind)).toEqual(["file", "mark", "mark", "file", "mark"]);
+ expect(bookmarkRows(useBookmarks.getState().items).map((r) => r.kind)).toEqual([
+ "file",
+ "mark",
+ "mark",
+ "file",
+ "mark",
+ ]);
const { items, lists } = useBookmarks.getState();
expect(bookmarkRows(items, [], lists).map((r) => r.kind)).toEqual(["list", "file", "mark", "mark", "file", "mark"]);
render(<BookmarkPopupsOverlay />);
diff --git a/src/features/search/__tests__/bookmarks.test.ts b/src/features/search/__tests__/bookmarks.test.ts
index 55ee91d43..1988b1483 100644
--- a/src/features/search/__tests__/bookmarks.test.ts
+++ b/src/features/search/__tests__/bookmarks.test.ts
@@ -65,7 +65,10 @@ describe("bookmark store", () => {
});
it("ignores corrupt storage", () => {
- localStorage.setItem("openidea.bookmarks.v1:/bad", JSON.stringify([{ path: 1 }, { path: "/bad/x", line: 2 }, "nope"]));
+ localStorage.setItem(
+ "openidea.bookmarks.v1:/bad",
+ JSON.stringify([{ path: 1 }, { path: "/bad/x", line: 2 }, "nope"]),
+ );
loadBookmarks("/bad");
expect(useBookmarks.getState().items.map((b) => b.line)).toEqual([2]);
});
@@ -96,8 +99,15 @@ describe("mnemonic bookmarks", () => {
it("keeps mnemonics and descriptions when lines move or storage reloads", () => {
const list: Bookmark[] = [{ path: "/p/a", line: 1, text: "a", created: 1, mnemonic: "7", description: "note" }];
- expect(setFileLines(list, "/p/a", [{ line: 4, text: "a" }])[0]).toMatchObject({ line: 4, mnemonic: "7", description: "note" });
- localStorage.setItem("openidea.bookmarks.v1:/m", JSON.stringify([...list, { path: "/p/b", line: 0, mnemonic: "ab" }]));
+ expect(setFileLines(list, "/p/a", [{ line: 4, text: "a" }])[0]).toMatchObject({
+ line: 4,
+ mnemonic: "7",
+ description: "note",
+ });
+ localStorage.setItem(
+ "openidea.bookmarks.v1:/m",
+ JSON.stringify([...list, { path: "/p/b", line: 0, mnemonic: "ab" }]),
+ );
loadBookmarks("/m");
expect(useBookmarks.getState().items.map((b) => b.mnemonic)).toEqual(["7", undefined]);
});
diff --git a/src/features/search/__tests__/codePreview.test.tsx b/src/features/search/__tests__/codePreview.test.tsx
index 63988197e..111cd0407 100644
--- a/src/features/search/__tests__/codePreview.test.tsx
+++ b/src/features/search/__tests__/codePreview.test.tsx
@@ -13,7 +13,13 @@ describe("CodePreview", () => {
it("marks matches (the current line's as current) and the current line", () => {
const doc = Text.of(["ab", "order order", "x"]);
const set = previewDecorations(doc, 1, [
- { line: 1, ranges: [[0, 5], [6, 11]] },
+ {
+ line: 1,
+ ranges: [
+ [0, 5],
+ [6, 11],
+ ],
+ },
{ line: 2, ranges: [[0, 9]] },
{ line: 7, ranges: [[0, 1]] },
]);
@@ -30,9 +36,7 @@ describe("CodePreview", () => {
});
it("shows the file read-only in an editor view with the matches highlighted", async () => {
- const { container } = render(
- <CodePreview path="/p/a.kt" line={1} highlights={[{ line: 1, ranges: [[4, 9]] }]} />,
- );
+ const { container } = render(<CodePreview path="/p/a.kt" line={1} highlights={[{ line: 1, ranges: [[4, 9]] }]} />);
await act(() => new Promise((r) => setTimeout(r, 150)));
expect(container.querySelector(".cm-content")?.textContent).toContain("val order = 1");
expect(container.querySelector(".cm-content")?.getAttribute("contenteditable")).not.toBe("true");
diff --git a/src/features/search/__tests__/controller.test.ts b/src/features/search/__tests__/controller.test.ts
index c8ed1bfe6..65ba0ae31 100644
--- a/src/features/search/__tests__/controller.test.ts
+++ b/src/features/search/__tests__/controller.test.ts
@@ -52,19 +52,30 @@ describe("SeController", () => {
expect(last().loading).toBe(true);
files.resolve([fm("Order.kt")]);
await flush();
- expect(last().sections.get("files")!.items.map((i) => i.key)).toEqual(["f:/p/Order.kt"]);
+ expect(
+ last()
+ .sections.get("files")!
+ .items.map((i) => i.key),
+ ).toEqual(["f:/p/Order.kt"]);
});
it("drops late results of a superseded query and cancels its requests", async () => {
const first = deferred<ReturnType<typeof fm>[]>();
- const findFiles = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValueOnce([fm("New.kt")]);
+ const findFiles = vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValueOnce([fm("New.kt")]);
const lsp = deferred<never[]>();
const { c, deps, last } = setup({ findFiles, workspaceSymbols: () => lsp.promise });
c.run({ query: "old", tab: "files", includeNonProject: false, extra: {} });
c.run({ query: "new", tab: "files", includeNonProject: false, extra: {} });
first.resolve([fm("Old.kt")]);
await flush();
- expect(last().sections.get("files")!.items.map((i) => i.key)).toEqual(["f:/p/New.kt"]);
+ expect(
+ last()
+ .sections.get("files")!
+ .items.map((i) => i.key),
+ ).toEqual(["f:/p/New.kt"]);
c.run({ query: "sym", tab: "symbols", includeNonProject: false, extra: {} });
c.run({ query: "sym2", tab: "symbols", includeNonProject: false, extra: {} });
@@ -85,7 +96,11 @@ describe("SeController", () => {
const { c, last } = setup({ recentFiles: async () => ["/p/a/B.kt", "/p/C.kt"] });
c.run({ query: "", tab: "all", includeNonProject: false, extra: {} });
await flush();
- expect(last().sections.get("recent")!.items.map((i) => (i.kind === "file" ? i.rel : ""))).toEqual(["a/B.kt", "C.kt"]);
+ expect(
+ last()
+ .sections.get("recent")!
+ .items.map((i) => (i.kind === "file" ? i.rel : "")),
+ ).toEqual(["a/B.kt", "C.kt"]);
});
it("re-fetches only the section whose limit changed (Show more)", async () => {
@@ -105,7 +120,16 @@ describe("SeController", () => {
const lsp = deferred<never[]>();
const { c, last } = setup({
findSymbols: async () => [
- { name: "order", kind: "variable", container: null, path: "/p/A.kt", relPath: "A.kt", range: { start: { line: 1, col: 0 }, end: { line: 1, col: 5 } }, score: 1, indices: [0] },
+ {
+ name: "order",
+ kind: "variable",
+ container: null,
+ path: "/p/A.kt",
+ relPath: "A.kt",
+ range: { start: { line: 1, col: 0 }, end: { line: 1, col: 5 } },
+ score: 1,
+ indices: [0],
+ },
],
workspaceSymbols: () => lsp.promise,
});
@@ -123,7 +147,11 @@ describe("SeController", () => {
const searchText = vi.fn(async (_id: number, q: SearchQuery, onFile: (f: FileMatches) => void) => {
expect(q.maxMatches).toBe(7);
for (let i = 0; i < 3; i++)
- onFile({ path: `/p/${i}.kt`, relPath: `${i}.kt`, matches: [1, 2, 3].map((line) => ({ line, text: "order", ranges: [[0, 5]], textOffset: 0 })) });
+ onFile({
+ path: `/p/${i}.kt`,
+ relPath: `${i}.kt`,
+ matches: [1, 2, 3].map((line) => ({ line, text: "order", ranges: [[0, 5]], textOffset: 0 })),
+ });
});
const { c, last } = setup({ searchText });
c.run({ query: "order", tab: "all", includeNonProject: false, extra: {} });
@@ -145,11 +173,19 @@ describe("SeController", () => {
});
c.run({ query: "a", tab: "files", includeNonProject: false, fileSet: "test", extra: {} });
await flush();
- expect(last().sections.get("files")!.items.map((i) => i.key)).toEqual(["f:/p/src/test/ATest.kt"]);
+ expect(
+ last()
+ .sections.get("files")!
+ .items.map((i) => i.key),
+ ).toEqual(["f:/p/src/test/ATest.kt"]);
expect(findFiles).toHaveBeenLastCalledWith("a", 4 * 50 + 1);
c.run({ query: "a", tab: "files", includeNonProject: false, fileSet: "production", extra: {} });
await flush();
- expect(last().sections.get("files")!.items.map((i) => i.key)).toEqual(["f:/p/src/main/A.kt"]);
+ expect(
+ last()
+ .sections.get("files")!
+ .items.map((i) => i.key),
+ ).toEqual(["f:/p/src/main/A.kt"]);
// "All Places" ignores the narrowed scope.
c.run({ query: "a", tab: "files", includeNonProject: true, fileSet: "production", extra: {} });
await flush();
diff --git a/src/features/search/__tests__/dialogs.test.tsx b/src/features/search/__tests__/dialogs.test.tsx
index 27a2f8160..3e10bacd2 100644
--- a/src/features/search/__tests__/dialogs.test.tsx
+++ b/src/features/search/__tests__/dialogs.test.tsx
@@ -30,7 +30,11 @@ vi.mock("../find/windowStore", async (orig) => ({
ipcFindDeps: () => ({
validate: async () => {},
start: async (_id: number, _q: unknown, onFile: (f: unknown) => void) => {
- onFile({ path: "/p/a.kt", relPath: "a.kt", matches: [{ line: 2, text: "val order = 1", ranges: [[4, 9]], textOffset: 0 }] });
+ onFile({
+ path: "/p/a.kt",
+ relPath: "a.kt",
+ matches: [{ line: 2, text: "val order = 1", ranges: [[4, 9]], textOffset: 0 }],
+ });
return null;
},
cancel: () => {},
diff --git a/src/features/search/__tests__/everywhereModel.test.ts b/src/features/search/__tests__/everywhereModel.test.ts
index d52d1577c..1d2eae940 100644
--- a/src/features/search/__tests__/everywhereModel.test.ts
+++ b/src/features/search/__tests__/everywhereModel.test.ts
@@ -17,7 +17,13 @@ import {
} from "../everywhere/model";
const range = (line: number, col = 0) => ({ start: { line, col }, end: { line, col: col + 1 } });
-const sym = (name: string, kind: SymbolMatch["kind"], path: string, line: number, container: string | null = null): SymbolMatch => ({
+const sym = (
+ name: string,
+ kind: SymbolMatch["kind"],
+ path: string,
+ line: number,
+ container: string | null = null,
+): SymbolMatch => ({
name,
kind,
container,
@@ -59,8 +65,15 @@ describe("mergeSymbols", () => {
});
it("applies type filters and reports overflow", () => {
- const index = [sym("Order", "class", "/p/A.kt", 0), sym("order", "variable", "/p/A.kt", 2), sym("OrderKind", "enum", "/p/A.kt", 5)];
- expect(mergeSymbols(index, [], "ord", { ...opts, typesOnly: true }).items.map((i) => i.name)).toEqual(["Order", "OrderKind"]);
+ const index = [
+ sym("Order", "class", "/p/A.kt", 0),
+ sym("order", "variable", "/p/A.kt", 2),
+ sym("OrderKind", "enum", "/p/A.kt", 5),
+ ];
+ expect(mergeSymbols(index, [], "ord", { ...opts, typesOnly: true }).items.map((i) => i.name)).toEqual([
+ "Order",
+ "OrderKind",
+ ]);
expect(mergeSymbols(index, [], "ord", { ...opts, excludeTypes: true }).items.map((i) => i.name)).toEqual(["order"]);
const limited = mergeSymbols(index, [], "ord", { ...opts, limit: 2 });
expect(limited.items).toHaveLength(2);
@@ -73,7 +86,12 @@ describe("mergeSymbols", () => {
});
describe("matchActions", () => {
- const act = (id: string, title: string, extra: Partial<Action> = {}): Action => ({ id, title, run: () => {}, ...extra });
+ const act = (id: string, title: string, extra: Partial<Action> = {}): Action => ({
+ id,
+ title,
+ run: () => {},
+ ...extra,
+ });
const actions = [
act("code.optimizeImports", "Optimize Imports", { category: "Code" }),
act("run.editConfigs", "Edit Configurations…", { keywords: ["run config"] }),
@@ -127,7 +145,11 @@ describe("matchActions", () => {
describe("items and rows", () => {
it("fileItem splits name and directory highlights", () => {
- const f = fileItem({ path: "/p/src/orders/OrderController.kt", relPath: "src/orders/OrderController.kt", indices: [4, 11, 12, 16] }, 41, null);
+ const f = fileItem(
+ { path: "/p/src/orders/OrderController.kt", relPath: "src/orders/OrderController.kt", indices: [4, 11, 12, 16] },
+ 41,
+ null,
+ );
expect(f.name).toBe("OrderController.kt");
expect(f.dir).toBe("src/orders");
expect(f.nameIndices).toEqual([0, 1, 5]);
@@ -135,7 +157,9 @@ describe("items and rows", () => {
});
it("textItems collapses indentation and shifts ranges", () => {
- const [t] = textItems("/p/a.kt", "a.kt", [{ line: 4, text: "\t\t val order = 1", ranges: [[8, 13]], textOffset: 0 }]);
+ const [t] = textItems("/p/a.kt", "a.kt", [
+ { line: 4, text: "\t\t val order = 1", ranges: [[8, 13]], textOffset: 0 },
+ ]);
expect(t!.text).toBe(" val order = 1");
expect(t!.indices).toEqual([6, 7, 8, 9, 10]);
expect([t!.col, t!.endCol]).toEqual([8, 13]);
@@ -143,8 +167,21 @@ describe("items and rows", () => {
it("buildRows orders sections, adds headers and more rows", () => {
const sections = new Map<SectionId, SectionState>([
- ["actions", { items: matchActions([{ id: "a", title: "Order", run: () => {} }], "ord", { isEnabled: () => true, recent: [] }), hasMore: false, loading: false }],
- ["files", { items: [fileItem({ path: "/p/O.kt", relPath: "O.kt", indices: [] })], hasMore: true, loading: false }],
+ [
+ "actions",
+ {
+ items: matchActions([{ id: "a", title: "Order", run: () => {} }], "ord", {
+ isEnabled: () => true,
+ recent: [],
+ }),
+ hasMore: false,
+ loading: false,
+ },
+ ],
+ [
+ "files",
+ { items: [fileItem({ path: "/p/O.kt", relPath: "O.kt", indices: [] })], hasMore: true, loading: false },
+ ],
["classes", { items: [], hasMore: false, loading: true }],
]);
const rows = buildRows(sections, { headers: true });
@@ -157,7 +194,14 @@ describe("items and rows", () => {
const sections = new Map<SectionId, SectionState>([
["files", { items: [file("src/upload_gray.py"), file("src/upgrade.py")], hasMore: true, loading: false }],
["symbols", { items: [symbolItem(sym("upgrade", "function", "/p/m.py", 3))], hasMore: false, loading: false }],
- ["text", { items: textItems("/p/a.md", "a.md", [{ line: 0, text: "upgrade", ranges: [[0, 3]], textOffset: 0 }]), hasMore: false, loading: false }],
+ [
+ "text",
+ {
+ items: textItems("/p/a.md", "a.md", [{ line: 0, text: "upgrade", ranges: [[0, 3]], textOffset: 0 }]),
+ hasMore: false,
+ loading: false,
+ },
+ ],
]);
const rows = buildRows(sections, { headers: false, mix: "upg" });
expect(rows.map((r) => (r.kind === "more" ? `more:${r.section}` : (r as { section: SectionId }).section))).toEqual([
@@ -176,11 +220,25 @@ describe("items and rows", () => {
it("stableIndex keeps the selected key while rows stream in", () => {
const sections = new Map<SectionId, SectionState>([
- ["files", { items: [fileItem({ path: "/p/A.kt", relPath: "A.kt", indices: [] }), fileItem({ path: "/p/B.kt", relPath: "B.kt", indices: [] })], hasMore: false, loading: false }],
+ [
+ "files",
+ {
+ items: [
+ fileItem({ path: "/p/A.kt", relPath: "A.kt", indices: [] }),
+ fileItem({ path: "/p/B.kt", relPath: "B.kt", indices: [] }),
+ ],
+ hasMore: false,
+ loading: false,
+ },
+ ],
]);
const before = buildRows(sections, { headers: true });
const key = before[2]!.key;
- sections.set("classes", { items: [fileItem({ path: "/p/C.kt", relPath: "C.kt", indices: [] })], hasMore: false, loading: false });
+ sections.set("classes", {
+ items: [fileItem({ path: "/p/C.kt", relPath: "C.kt", indices: [] })],
+ hasMore: false,
+ loading: false,
+ });
const after = buildRows(sections, { headers: true });
expect(after[stableIndex(after, key, 2, true)]!.key).toBe(key);
// Without a user selection the first selectable row wins.
@@ -198,22 +256,69 @@ describe("items and rows", () => {
});
describe("topResultSettled", () => {
- const sec = (loading: boolean, n = 0): SectionState => ({ items: Array.from({ length: n }, () => ({}) as never), hasMore: false, loading });
+ const sec = (loading: boolean, n = 0): SectionState => ({
+ items: Array.from({ length: n }, () => ({}) as never),
+ hasMore: false,
+ loading,
+ });
it("waits while a section above the first result is loading", () => {
- expect(topResultSettled(new Map([["classes", sec(true)], ["files", sec(false, 2)]]))).toBe(false);
+ expect(
+ topResultSettled(
+ new Map([
+ ["classes", sec(true)],
+ ["files", sec(false, 2)],
+ ]),
+ ),
+ ).toBe(false);
});
it("is settled once the first section with items is done, even if later ones load", () => {
- expect(topResultSettled(new Map([["classes", sec(false)], ["files", sec(false, 1)], ["text", sec(true)]]))).toBe(true);
+ expect(
+ topResultSettled(
+ new Map([
+ ["classes", sec(false)],
+ ["files", sec(false, 1)],
+ ["text", sec(true)],
+ ]),
+ ),
+ ).toBe(true);
});
it("with mixing waits for every source but a text search the top row already beats", () => {
- const strong = { items: [fileItem({ path: "/p/upgrade.py", relPath: "upgrade.py", indices: [] })], hasMore: false, loading: false };
- expect(topResultSettled(new Map([["files", strong], ["symbols", sec(true)]]), "upg")).toBe(false);
- expect(topResultSettled(new Map([["files", strong], ["text", sec(true)]]), "upg")).toBe(true);
+ const strong = {
+ items: [fileItem({ path: "/p/upgrade.py", relPath: "upgrade.py", indices: [] })],
+ hasMore: false,
+ loading: false,
+ };
+ expect(
+ topResultSettled(
+ new Map([
+ ["files", strong],
+ ["symbols", sec(true)],
+ ]),
+ "upg",
+ ),
+ ).toBe(false);
+ expect(
+ topResultSettled(
+ new Map([
+ ["files", strong],
+ ["text", sec(true)],
+ ]),
+ "upg",
+ ),
+ ).toBe(true);
const weak = { ...strong, items: [fileItem({ path: "/p/xuxpxg.py", relPath: "xuxpxg.py", indices: [] })] };
- expect(topResultSettled(new Map([["files", weak], ["text", sec(true)]]), "upg")).toBe(false);
+ expect(
+ topResultSettled(
+ new Map([
+ ["files", weak],
+ ["text", sec(true)],
+ ]),
+ "upg",
+ ),
+ ).toBe(false);
});
it("is settled when everything finished empty", () => {
@@ -249,9 +354,8 @@ describe("parseCommand", () => {
describe("Search Everywhere initial text", () => {
it("each tab starts with its own last query; closing remembers the text", async () => {
- const { hideSearchEverywhere, selectSearchEverywhereTab, showSearchEverywhere, useSearchEverywhere } = await import(
- "../everywhere/store"
- );
+ const { hideSearchEverywhere, selectSearchEverywhereTab, showSearchEverywhere, useSearchEverywhere } =
+ await import("../everywhere/store");
localStorage.clear();
showSearchEverywhere("files");
useSearchEverywhere.setState({ query: "Order" });
diff --git a/src/features/search/__tests__/fileStructure.test.tsx b/src/features/search/__tests__/fileStructure.test.tsx
index a7659953c..46583a103 100644
--- a/src/features/search/__tests__/fileStructure.test.tsx
+++ b/src/features/search/__tests__/fileStructure.test.tsx
@@ -25,7 +25,10 @@ function open() {
doc: 1,
loading: false,
error: null,
- items: [item("OrderController", "class", 0, [item("list", "method", 2), item("create", "method", 8)]), item("helper", "function", 22)],
+ items: [
+ item("OrderController", "class", 0, [item("list", "method", 2), item("create", "method", 8)]),
+ item("helper", "function", 22),
+ ],
});
useStructureOptions.setState({ narrowDown: true });
render(<FileStructureOverlay />);
diff --git a/src/features/search/__tests__/findPopup.test.tsx b/src/features/search/__tests__/findPopup.test.tsx
index bdcf67113..0c6593ea3 100644
--- a/src/features/search/__tests__/findPopup.test.tsx
+++ b/src/features/search/__tests__/findPopup.test.tsx
@@ -18,7 +18,11 @@ vi.mock("../find/windowStore", async (orig) => ({
{ line: 4, text: "order()", ranges: [[0, 5]], textOffset: 0 },
],
});
- onFile({ path: "/p/b.kt", relPath: "b.kt", matches: [{ line: 0, text: "// order", ranges: [[3, 8]], textOffset: 0 }] });
+ onFile({
+ path: "/p/b.kt",
+ relPath: "b.kt",
+ matches: [{ line: 0, text: "// order", ranges: [[3, 8]], textOffset: 0 }],
+ });
return null;
},
cancel: () => {},
@@ -78,7 +82,15 @@ describe("Find in Files popup", () => {
fireEvent.keyDown(field(), { key: "Enter" });
await settle();
expect(replaced).toHaveLength(1);
- expect(replaced[0]!.targets).toEqual([{ path: "/p/a.kt", only: [{ line: 1, col: 4 }, { line: 4, col: 0 }] }]);
+ expect(replaced[0]!.targets).toEqual([
+ {
+ path: "/p/a.kt",
+ only: [
+ { line: 1, col: 4 },
+ { line: 4, col: 0 },
+ ],
+ },
+ ]);
// The next row still to replace is selected.
expect(selectedRows().map((o) => o.textContent)).toEqual([expect.stringContaining("b.kt")]);
});
diff --git a/src/features/search/__tests__/findSession.test.ts b/src/features/search/__tests__/findSession.test.ts
index 1159df865..bc8c8f6a2 100644
--- a/src/features/search/__tests__/findSession.test.ts
+++ b/src/features/search/__tests__/findSession.test.ts
@@ -1,6 +1,13 @@
import { describe, expect, it, vi } from "vitest";
import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc";
-import { FindSession, matchRows, previewReplacement, rangesToIndices, type FindDeps, type FindState } from "../find/session";
+import {
+ FindSession,
+ matchRows,
+ previewReplacement,
+ rangesToIndices,
+ type FindDeps,
+ type FindState,
+} from "../find/session";
const q = (pattern: string, extra: Partial<SearchQuery> = {}): SearchQuery => ({
pattern,
@@ -149,7 +156,13 @@ describe("FindSession", () => {
describe("result helpers", () => {
it("matchRows trims indentation and keeps real columns", () => {
- const rows = matchRows([{ path: "/p/a", relPath: "a", matches: [{ line: 3, text: " let foo = 1", ranges: [[8, 11]], textOffset: 10 }] }]);
+ const rows = matchRows([
+ {
+ path: "/p/a",
+ relPath: "a",
+ matches: [{ line: 3, text: " let foo = 1", ranges: [[8, 11]], textOffset: 10 }],
+ },
+ ]);
expect(rows[0]).toMatchObject({ text: "let foo = 1", ranges: [[4, 7]], col: 18, endCol: 21, matched: ["foo"] });
});
@@ -161,6 +174,11 @@ describe("result helpers", () => {
});
it("rangesToIndices flattens and dedupes", () => {
- expect(rangesToIndices([[0, 2], [1, 3]])).toEqual([0, 1, 2]);
+ expect(
+ rangesToIndices([
+ [0, 2],
+ [1, 3],
+ ]),
+ ).toEqual([0, 1, 2]);
});
});
diff --git a/src/features/search/__tests__/inherited.test.ts b/src/features/search/__tests__/inherited.test.ts
index 3add4e7ac..e4910bb5f 100644
--- a/src/features/search/__tests__/inherited.test.ts
+++ b/src/features/search/__tests__/inherited.test.ts
@@ -47,7 +47,11 @@ const deps = {
describe("Show Inherited", () => {
it("collects supertype members level by level, without overridden ones or constructors", async () => {
const members = await inheritedMembers("/p/Dog.java", dog, deps);
- expect(members.map((m) => `${m.owner}.${m.item.name}`)).toEqual(["Animal.sleep()", "Animal.sleep(int)", "Living.age"]);
+ expect(members.map((m) => `${m.owner}.${m.item.name}`)).toEqual([
+ "Animal.sleep()",
+ "Animal.sleep(int)",
+ "Living.age",
+ ]);
expect(members[0]!.path).toBe("/p/Animal.java");
});
diff --git a/src/features/search/__tests__/outline.test.ts b/src/features/search/__tests__/outline.test.ts
index 083100c41..d538d10d2 100644
--- a/src/features/search/__tests__/outline.test.ts
+++ b/src/features/search/__tests__/outline.test.ts
@@ -14,7 +14,13 @@ import {
visibleCount,
} from "../structure/outline";
-const item = (name: string, kind: OutlineItem["kind"], from: number, to: number, children: OutlineItem[] = []): OutlineItem => ({
+const item = (
+ name: string,
+ kind: OutlineItem["kind"],
+ from: number,
+ to: number,
+ children: OutlineItem[] = [],
+): OutlineItem => ({
name,
detail: null,
kind,
@@ -24,7 +30,11 @@ const item = (name: string, kind: OutlineItem["kind"], from: number, to: number,
});
const outline = [
- item("OrderController", "class", 0, 20, [item("list", "method", 2, 6), item("create", "method", 8, 12), item("list", "method", 14, 16)]),
+ item("OrderController", "class", 0, 20, [
+ item("list", "method", 2, 6),
+ item("create", "method", 8, 12),
+ item("list", "method", 14, 16),
+ ]),
item("helper", "function", 22, 25),
];
@@ -91,7 +101,9 @@ describe("outline helpers", () => {
it("narrows to matches and their ancestors", () => {
const f = filterOutline(nodes, "creat", true);
- expect(f.nodes.map((n) => [n.item.name, n.children.map((c) => c.item.name)])).toEqual([["OrderController", ["create"]]]);
+ expect(f.nodes.map((n) => [n.item.name, n.children.map((c) => c.item.name)])).toEqual([
+ ["OrderController", ["create"]],
+ ]);
expect(f.best).toBe(nodes[0]!.children[1]!.key);
expect(f.matches.has(nodes[0]!.key)).toBe(false);
expect(filterOutline(nodes, "", true).nodes).toBe(nodes);
diff --git a/src/features/search/__tests__/query.test.ts b/src/features/search/__tests__/query.test.ts
index ff23921a6..b6343ab0d 100644
--- a/src/features/search/__tests__/query.test.ts
+++ b/src/features/search/__tests__/query.test.ts
@@ -23,7 +23,11 @@ describe("parseLocationQuery", () => {
});
it("strips the project root from pasted absolute paths", () => {
- expect(parseLocationQuery("/dev/acme/src/Order.kt:3", "/dev/acme")).toEqual({ text: "src/Order.kt", line: 2, col: null });
+ expect(parseLocationQuery("/dev/acme/src/Order.kt:3", "/dev/acme")).toEqual({
+ text: "src/Order.kt",
+ line: 2,
+ col: null,
+ });
expect(parseLocationQuery("/elsewhere/x.kt", "/dev/acme").text).toBe("/elsewhere/x.kt");
});
diff --git a/src/features/search/__tests__/recent.test.ts b/src/features/search/__tests__/recent.test.ts
index b238ca147..cb98e5c5d 100644
--- a/src/features/search/__tests__/recent.test.ts
+++ b/src/features/search/__tests__/recent.test.ts
@@ -91,7 +91,12 @@ describe("recent locations", () => {
});
it("normalises editor navigation history entries", () => {
- const out = fromNavigationHistory([{ path: "/a", selection: { line: 3, col: 2 } }, { path: "/b", line: 1, column: 4, text: "x" }, null, { nope: 1 }]);
+ const out = fromNavigationHistory([
+ { path: "/a", selection: { line: 3, col: 2 } },
+ { path: "/b", line: 1, column: 4, text: "x" },
+ null,
+ { nope: 1 },
+ ]);
expect(out!.map((l) => [l.path, l.line, l.col, l.snippet])).toEqual([
["/a", 3, 2, []],
["/b", 1, 4, ["x"]],
@@ -111,13 +116,19 @@ describe("recent files switcher", () => {
const paths = ["/p/src/Main.kt", "/p/src/Order.kt", "/p/README.md", "/p/src/Main.kt"];
it("dedupes, filters and supports edited-only", () => {
- expect(filterRecentFiles(paths, "", { root: "/p" }).map((f) => f.rel)).toEqual(["src/Main.kt", "src/Order.kt", "README.md"]);
+ expect(filterRecentFiles(paths, "", { root: "/p" }).map((f) => f.rel)).toEqual([
+ "src/Main.kt",
+ "src/Order.kt",
+ "README.md",
+ ]);
const hit = filterRecentFiles(paths, "ord", { root: "/p" });
expect(hit.map((f) => [f.name, f.indices])).toEqual([["Order.kt", [0, 1, 2]]]);
expect(filterRecentFiles(paths, "src", { root: "/p" }).map((f) => f.name)).toEqual(["Main.kt", "Order.kt"]);
- expect(filterRecentFiles(paths, "", { root: "/p", editedOnly: true, edited: new Set(["/p/README.md"]) }).map((f) => f.name)).toEqual([
- "README.md",
- ]);
+ expect(
+ filterRecentFiles(paths, "", { root: "/p", editedOnly: true, edited: new Set(["/p/README.md"]) }).map(
+ (f) => f.name,
+ ),
+ ).toEqual(["README.md"]);
});
it("preselects the previous file when the current one is first", () => {
@@ -162,10 +173,24 @@ describe("recent files switcher", () => {
});
it("orders tool windows by stripe", () => {
- const tw = (id: string, anchor: ToolWindowContribution["anchor"], order: number, extra: Partial<ToolWindowContribution> = {}) =>
- ({ id, title: id, icon: "folder", anchor, order, component: () => null, ...extra }) as ToolWindowContribution;
- const list = [tw("terminal", "bottom", 10), tw("project", "left", 0), tw("bookmarks", "left", 30, { secondary: true }), tw("structure", "left", 20)];
- expect(switcherToolWindows(list, true, "").map((x) => x.tw.id)).toEqual(["project", "structure", "bookmarks", "terminal"]);
+ const tw = (
+ id: string,
+ anchor: ToolWindowContribution["anchor"],
+ order: number,
+ extra: Partial<ToolWindowContribution> = {},
+ ) => ({ id, title: id, icon: "folder", anchor, order, component: () => null, ...extra }) as ToolWindowContribution;
+ const list = [
+ tw("terminal", "bottom", 10),
+ tw("project", "left", 0),
+ tw("bookmarks", "left", 30, { secondary: true }),
+ tw("structure", "left", 20),
+ ];
+ expect(switcherToolWindows(list, true, "").map((x) => x.tw.id)).toEqual([
+ "project",
+ "structure",
+ "bookmarks",
+ "terminal",
+ ]);
expect(switcherToolWindows(list, true, "ter").map((x) => x.tw.id)).toEqual(["terminal"]);
expect(switcherToolWindows(list, false, "")).toEqual([]);
});
@@ -174,7 +199,13 @@ describe("recent files switcher", () => {
describe("navigation history snapshot", () => {
it("accepts the editor's { entries, index } snapshot and merges with recorded locations", async () => {
const { mergeLocations } = await import("../common/locations");
- const history = fromNavigationHistory({ entries: [{ path: "/a", line: 1, col: 0, time: 1 }, { path: "/b", line: 50, col: 0, time: 3 }], index: 1 })!;
+ const history = fromNavigationHistory({
+ entries: [
+ { path: "/a", line: 1, col: 0, time: 1 },
+ { path: "/b", line: 50, col: 0, time: 3 },
+ ],
+ index: 1,
+ })!;
const recorded = [loc("/a", 2, { time: 2, snippet: ["code"], changed: true })];
const merged = mergeLocations(history, recorded);
expect(merged.map((l) => `${l.path}:${l.line}`)).toEqual(["/b:50", "/a:2"]);
diff --git a/src/features/search/__tests__/replaceFlow.test.ts b/src/features/search/__tests__/replaceFlow.test.ts
index b494a4869..9e6d9a7ef 100644
--- a/src/features/search/__tests__/replaceFlow.test.ts
+++ b/src/features/search/__tests__/replaceFlow.test.ts
@@ -35,7 +35,15 @@ const files: FileMatches[] = [
path: "/p/a.ts",
relPath: "a.ts",
matches: [
- { line: 0, text: "foo foo", ranges: [[0, 3], [4, 7]], textOffset: 0 },
+ {
+ line: 0,
+ text: "foo foo",
+ ranges: [
+ [0, 3],
+ [4, 7],
+ ],
+ textOffset: 0,
+ },
{ line: 3, text: " x foo", ranges: [[4, 7]], textOffset: 0 },
],
},
@@ -93,7 +101,9 @@ describe("replace flow model", () => {
});
it("confirmation and summary texts carry the counts", () => {
- expect(confirmText({ usages: 3, files: 1 }, "foo", "bar")).toBe("Replace 3 occurrences of 'foo' with 'bar' in 1 file?");
+ expect(confirmText({ usages: 3, files: 1 }, "foo", "bar")).toBe(
+ "Replace 3 occurrences of 'foo' with 'bar' in 1 file?",
+ );
expect(summaryText({ files: 2, replacements: 1, failed: 0, cancelled: false, elapsedMs: 3 })).toBe(
"Replaced 1 occurrence in 2 files",
);
@@ -126,7 +136,11 @@ describe("startReplace", () => {
const run = startReplace({ query: q, replacement: "bar", preserveCase: true, targets }, progress, d);
await expect(run.result).resolves.toEqual(summary);
expect(d.synced).toHaveBeenCalledWith(["/p/a.ts"]);
- expect(d.start).toHaveBeenCalledWith(7, expect.objectContaining({ preserveCase: true, targets }), expect.any(Function));
+ expect(d.start).toHaveBeenCalledWith(
+ 7,
+ expect.objectContaining({ preserveCase: true, targets }),
+ expect.any(Function),
+ );
expect(progress).toHaveBeenLastCalledWith({
done: 2,
total: 2,
@@ -149,9 +163,9 @@ describe("replace previews", () => {
expect(preserveCase("FOO", "bar")).toBe("BAR");
expect(preserveCase("Foo", "bar")).toBe("Bar");
expect(preserveCase("foo", "Bar")).toBe("bar");
- expect(previewReplacement("Foo1", { pattern: "foo(\\d)", isRegex: true, caseSensitive: false }, "bar$1", true)).toBe(
- "Bar1",
- );
+ expect(
+ previewReplacement("Foo1", { pattern: "foo(\\d)", isRegex: true, caseSensitive: false }, "bar$1", true),
+ ).toBe("Bar1");
});
it("unified line preview of the edits", () => {
diff --git a/src/features/search/bookmarks/BookmarkPopups.tsx b/src/features/search/bookmarks/BookmarkPopups.tsx
index c02e97b02..10bf6c41c 100644
--- a/src/features/search/bookmarks/BookmarkPopups.tsx
+++ b/src/features/search/bookmarks/BookmarkPopups.tsx
@@ -54,7 +54,10 @@ function MnemonicChooser() {
const target = useBookmarkPopups((s) => s.chooser)!;
const items = useBookmarks((s) => s.items);
const current = bookmarkAt(items, target.path, target.line);
- const assigned = useMemo(() => new Set(items.filter((b) => b.mnemonic && b !== current).map((b) => b.mnemonic!)), [items, current]);
+ const assigned = useMemo(
+ () => new Set(items.filter((b) => b.mnemonic && b !== current).map((b) => b.mnemonic!)),
+ [items, current],
+ );
const [description, setDescription] = useState(current?.description ?? "");
const close = () => useBookmarkPopups.setState({ chooser: null });
const choose = (mnemonic: string) => {
@@ -86,11 +89,7 @@ function MnemonicChooser() {
<button
key={m}
type="button"
- className={clsx(
- styles.key,
- m === current?.mnemonic && styles.keyCurrent,
- assigned.has(m) && styles.keyAssigned,
- )}
+ className={clsx(styles.key, m === current?.mnemonic && styles.keyCurrent, assigned.has(m) && styles.keyAssigned)}
aria-pressed={m === current?.mnemonic}
onClick={() => choose(m)}
>
@@ -165,7 +164,11 @@ export function bookmarkRows(
for (const p of marked.filter((p) => p.dir).sort((a, b) => a.path.localeCompare(b.path)))
rows.push({ kind: "path", key: `d:${k}:${p.path}`, path: p.path, dir: true });
for (const [path, f] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
- rows.push(f.bookmarked ? { kind: "path", key: `p:${k}:${path}`, path, dir: false } : { kind: "file", key: `f:${k}:${path}`, path });
+ rows.push(
+ f.bookmarked
+ ? { kind: "path", key: `p:${k}:${path}`, path, dir: false }
+ : { kind: "file", key: `f:${k}:${path}`, path },
+ );
for (const b of f.marks) rows.push({ kind: "mark", key: `b:${b.path}:${b.line}`, bookmark: b });
}
};
diff --git a/src/features/search/bookmarks/store.ts b/src/features/search/bookmarks/store.ts
index f62371549..a3cf61866 100644
--- a/src/features/search/bookmarks/store.ts
+++ b/src/features/search/bookmarks/store.ts
@@ -109,8 +109,15 @@ function withoutMnemonic(b: Bookmark): Bookmark {
}
/** ⌃⇧digit: the line already has `mnemonic` → remove the bookmark; otherwise assign it. */
-export function toggleMnemonic(list: readonly Bookmark[], path: string, line: number, text: string, mnemonic: string): Bookmark[] {
- if (bookmarkAt(list, path, line)?.mnemonic === mnemonic) return list.filter((b) => !(b.path === path && b.line === line));
+export function toggleMnemonic(
+ list: readonly Bookmark[],
+ path: string,
+ line: number,
+ text: string,
+ mnemonic: string,
+): Bookmark[] {
+ if (bookmarkAt(list, path, line)?.mnemonic === mnemonic)
+ return list.filter((b) => !(b.path === path && b.line === line));
return assignMnemonic(list, path, line, text, mnemonic);
}
@@ -119,7 +126,12 @@ export function bookmarkByMnemonic(list: readonly Bookmark[], mnemonic: string):
}
/** Rename (F2 in the Bookmarks view): an empty description shows the line again. */
-export function describeBookmark(list: readonly Bookmark[], path: string, line: number, description: string): Bookmark[] {
+export function describeBookmark(
+ list: readonly Bookmark[],
+ path: string,
+ line: number,
+ description: string,
+): Bookmark[] {
return list.map((b) => {
if (b.path !== path || b.line !== line) return b;
const { description: _, ...rest } = b;
@@ -172,7 +184,10 @@ export function renameBookmarks(list: readonly Bookmark[], from: string, to: str
}
export function linesOf(list: readonly Bookmark[], path: string): number[] {
- return list.filter((b) => b.path === path).map((b) => b.line).sort((a, b) => a - b);
+ return list
+ .filter((b) => b.path === path)
+ .map((b) => b.line)
+ .sort((a, b) => a - b);
}
/** Lines of `path`'s bookmarks with their mnemonics (gutter), sorted by line. */
@@ -186,16 +201,26 @@ export function marksOf(list: readonly Bookmark[], path: string): Array<{ line:
function sanitize(raw: unknown): Bookmark[] {
if (!Array.isArray(raw)) return [];
return sortBookmarks(
- raw.filter(
- (b): b is Bookmark =>
- !!b && typeof b === "object" && typeof (b as Bookmark).path === "string" && Number.isInteger((b as Bookmark).line),
- ).map((b) => {
- const out: Bookmark = { path: b.path, line: Math.max(0, b.line), text: String(b.text ?? ""), created: Number(b.created) || 0 };
- if (isMnemonic(b.mnemonic)) out.mnemonic = b.mnemonic;
- if (typeof b.description === "string" && b.description.trim()) out.description = b.description;
- if (typeof b.list === "string" && b.list) out.list = b.list;
- return out;
- }),
+ raw
+ .filter(
+ (b): b is Bookmark =>
+ !!b &&
+ typeof b === "object" &&
+ typeof (b as Bookmark).path === "string" &&
+ Number.isInteger((b as Bookmark).line),
+ )
+ .map((b) => {
+ const out: Bookmark = {
+ path: b.path,
+ line: Math.max(0, b.line),
+ text: String(b.text ?? ""),
+ created: Number(b.created) || 0,
+ };
+ if (isMnemonic(b.mnemonic)) out.mnemonic = b.mnemonic;
+ if (typeof b.description === "string" && b.description.trim()) out.description = b.description;
+ if (typeof b.list === "string" && b.list) out.list = b.list;
+ return out;
+ }),
);
}
diff --git a/src/features/search/common/locations.ts b/src/features/search/common/locations.ts
index cebf8f463..b0d7f97b8 100644
--- a/src/features/search/common/locations.ts
+++ b/src/features/search/common/locations.ts
@@ -29,7 +29,10 @@ export function mergeLocations(...lists: ReadonlyArray<readonly RecentLocation[]
let out: RecentLocation[] = [];
for (const l of all) {
const prev = out.find((x) => x.path === l.path && Math.abs(x.line - l.line) <= MERGE_DISTANCE);
- out = recordLocation(out, prev && !l.snippet.length ? { ...l, snippet: prev.snippet, snippetStart: prev.snippetStart } : l);
+ out = recordLocation(
+ out,
+ prev && !l.snippet.length ? { ...l, snippet: prev.snippet, snippetStart: prev.snippetStart } : l,
+ );
}
return out;
}
diff --git a/src/features/search/common/open.ts b/src/features/search/common/open.ts
index b0f6e9813..c5f52601f 100644
--- a/src/features/search/common/open.ts
+++ b/src/features/search/common/open.ts
@@ -16,16 +16,25 @@ export async function openLocation(
): Promise<void> {
const service = maybeEditorService();
if (!service) {
- notifications().notify({ group: "search", level: "warning", title: "No editor available", body: path, key: "search.noEditor" });
+ notifications().notify({
+ group: "search",
+ level: "warning",
+ title: "No editor available",
+ body: path,
+ key: "search.noEditor",
+ });
return;
}
- const selection = pos
- ? { line: pos.line, col: pos.col ?? 0, endLine: pos.endLine, endCol: pos.endCol }
- : undefined;
+ const selection = pos ? { line: pos.line, col: pos.col ?? 0, endLine: pos.endLine, endCol: pos.endCol } : undefined;
try {
await service.openFile(path, { focus: true, ...options, selection });
} catch (e) {
- notifications().notify({ group: "search", level: "error", title: `Cannot open ${basename(path)}`, body: String(e) });
+ notifications().notify({
+ group: "search",
+ level: "error",
+ title: `Cannot open ${basename(path)}`,
+ body: String(e),
+ });
}
}
diff --git a/src/features/search/common/textSearch.ts b/src/features/search/common/textSearch.ts
index 98c16c681..2e9f9e06f 100644
--- a/src/features/search/common/textSearch.ts
+++ b/src/features/search/common/textSearch.ts
@@ -1,5 +1,13 @@
import { Channel } from "@tauri-apps/api/core";
-import { call, commands, type FileMatches, type RequestId, type SearchEvent, type SearchQuery, type SearchSummary } from "@/platform/ipc";
+import {
+ call,
+ commands,
+ type FileMatches,
+ type RequestId,
+ type SearchEvent,
+ type SearchQuery,
+ type SearchSummary,
+} from "@/platform/ipc";
/**
* Starts a streaming Find in Files request. `onFile` receives each file's
diff --git a/src/features/search/common/tracking.ts b/src/features/search/common/tracking.ts
index 71fa18668..59b34cc57 100644
--- a/src/features/search/common/tracking.ts
+++ b/src/features/search/common/tracking.ts
@@ -5,7 +5,13 @@
*/
import { EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
-import { activeEditor, isExternalChange, onEditorEvent, registerEditorContribution, useEditorRegistry } from "@/editor/api";
+import {
+ activeEditor,
+ isExternalChange,
+ onEditorEvent,
+ registerEditorContribution,
+ useEditorRegistry,
+} from "@/editor/api";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import {
MERGE_DISTANCE,
@@ -155,7 +161,8 @@ export function installTracking(): () => void {
});
const unsubPatched = onIdeEvent("docPatched", (e) => {
- const path = docPaths.get(e.doc) ?? [...useEditorRegistry.getState().editors].find((h) => h.ctx.doc === e.doc)?.ctx.path;
+ const path =
+ docPaths.get(e.doc) ?? [...useEditorRegistry.getState().editors].find((h) => h.ctx.doc === e.doc)?.ctx.path;
if (path) bumpVersion(path, false);
});
const unsubFs = onIdeEvent("fsChanged", (e) => {
diff --git a/src/features/search/everywhere/controller.ts b/src/features/search/everywhere/controller.ts
index a0d9076f9..9c32a6edd 100644
--- a/src/features/search/everywhere/controller.ts
+++ b/src/features/search/everywhere/controller.ts
@@ -214,7 +214,11 @@ export class SeController {
const paths = await this.deps.recentFiles();
const root = this.deps.root();
const items = paths.slice(0, limit).map((p) =>
- fileItem({ path: p, relPath: root && p.startsWith(root + "/") ? p.slice(root.length + 1) : p, indices: [] }),
+ fileItem({
+ path: p,
+ relPath: root && p.startsWith(root + "/") ? p.slice(root.length + 1) : p,
+ indices: [],
+ }),
);
this.set(id, gen, items, paths.length > limit, false);
break;
diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx
index 5fd36f918..96eb6421b 100644
--- a/src/features/search/find/FindInFiles.tsx
+++ b/src/features/search/find/FindInFiles.tsx
@@ -361,7 +361,8 @@ function FindInFilesDialog() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [previewMode, s.replace, selected?.key, s.replacement, s.preserveCase, queryKey, marks, previewVersion]);
- const moveTo = (next: number, extend: boolean) => setSel((cur) => selectRow(rows, cur, next, extend ? "range" : "single"));
+ const moveTo = (next: number, extend: boolean) =>
+ setSel((cur) => selectRow(rows, cur, next, extend ? "range" : "single"));
const onRowClick = (index: number, e: MouseEvent) => {
const mode = e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single";
setSel((cur) => selectRow(rows, cur, index, mode));
@@ -510,12 +511,7 @@ function FindInFilesDialog() {
pressed={s.context !== "any"}
onClick={() => setContextMenu(true)}
/>
- <IconButton
- icon="pin"
- title="Pin Window"
- pressed={s.pinned}
- onClick={() => setFindPopupPinned(!s.pinned)}
- />
+ <IconButton icon="pin" title="Pin Window" pressed={s.pinned} onClick={() => setFindPopupPinned(!s.pinned)} />
</header>
<div className={styles.fields}>
<div data-find-field ref={patternBoxRef}>
diff --git a/src/features/search/find/parts.tsx b/src/features/search/find/parts.tsx
index 6c8d02af3..1d83e2e74 100644
--- a/src/features/search/find/parts.tsx
+++ b/src/features/search/find/parts.tsx
@@ -159,7 +159,8 @@ export function CodePreview({
const { line, highlights } = latest.current;
const doc = view.state.doc;
const effects: StateEffect<unknown>[] = [setPreviewMarks.of(previewDecorations(doc, line, highlights))];
- if (line >= 0 && line < doc.lines) effects.push(EditorView.scrollIntoView(doc.line(line + 1).from, { y: "center" }));
+ if (line >= 0 && line < doc.lines)
+ effects.push(EditorView.scrollIntoView(doc.line(line + 1).from, { y: "center" }));
view.dispatch({ effects });
}, [current, loaded, line]);
useEffect(() => {
diff --git a/src/features/search/find/replaceFlow.ts b/src/features/search/find/replaceFlow.ts
index a203707e7..8c938717c 100644
--- a/src/features/search/find/replaceFlow.ts
+++ b/src/features/search/find/replaceFlow.ts
@@ -237,7 +237,9 @@ export interface PreviewLine {
/** Unified line preview of `edits` (non-overlapping, UTF-16 line/col) applied to `before`. */
export function replacePreviewLines(before: string, edits: readonly TextEdit[]): PreviewLine[] {
const lines = before.split("\n");
- const sorted = [...edits].sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col);
+ const sorted = [...edits].sort(
+ (a, b) => a.range.start.line - b.range.start.line || a.range.start.col - b.range.start.col,
+ );
const out: PreviewLine[] = [];
const between = (from: Pos, to: Pos) => {
if (from.line === to.line) return (lines[from.line] ?? "").slice(from.col, to.col);
@@ -248,7 +250,7 @@ export function replacePreviewLines(before: string, edits: readonly TextEdit[]):
};
let next = 0;
let delta = 0;
- for (let i = 0; i < sorted.length; ) {
+ for (let i = 0; i < sorted.length;) {
const first = sorted[i]!;
const startLine = first.range.start.line;
let endLine = first.range.end.line;
diff --git a/src/features/search/index.ts b/src/features/search/index.ts
index f086032d4..759e5c80b 100644
--- a/src/features/search/index.ts
+++ b/src/features/search/index.ts
@@ -75,7 +75,10 @@ function selectionDescription(): string | null {
const view = activeEditor()?.view;
if (!view) return null;
const { from, to } = view.state.selection.main;
- const text = view.state.sliceDoc(from, Math.min(to, from + 1000)).replace(/\s+/g, " ").trim();
+ const text = view.state
+ .sliceDoc(from, Math.min(to, from + 1000))
+ .replace(/\s+/g, " ")
+ .trim();
return text || null;
}
diff --git a/src/features/search/recent/RecentPopups.tsx b/src/features/search/recent/RecentPopups.tsx
index 4a7d88f28..d2674f7df 100644
--- a/src/features/search/recent/RecentPopups.tsx
+++ b/src/features/search/recent/RecentPopups.tsx
@@ -63,7 +63,9 @@ function RecentFilesDialog() {
const toolWindows = useContributions((s) => s.toolWindows);
const [paths, setPaths] = useState<string[] | null>(null);
// Switcher: the open editor tabs (files and others), when the editor service lists them.
- const [tabs] = useState<OpenEditorTab[] | null>(() => (switcher ? (maybeEditorService()?.openTabs?.() ?? null) : null));
+ const [tabs] = useState<OpenEditorTab[] | null>(() =>
+ switcher ? (maybeEditorService()?.openTabs?.() ?? null) : null,
+ );
const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set());
const [query, setQuery] = useState("");
const [column, setColumn] = useState<"files" | "tools">("files");
@@ -249,7 +251,11 @@ function RecentFilesDialog() {
showRecentPopup("files");
inputRef.current?.focus();
}}
- label={<><T>Show edited only</T> {recentShortcut && <span className={styles.hint}>{recentShortcut}</span>}</>}
+ label={
+ <>
+ <T>Show edited only</T> {recentShortcut && <span className={styles.hint}>{recentShortcut}</span>}
+ </>
+ }
/>
</>
)}
@@ -416,7 +422,17 @@ function useOpenOutlines(paths: readonly string[]): ReadonlyMap<string, OutlineI
const tokenCache = new Map<string, CodeToken[]>();
/** A snippet's lines coloured by the file's language (parsed together, so multi-line constructs colour right). */
-function SnippetCode({ path, lines, first, caret }: { path: string; lines: readonly string[]; first: number; caret: number }) {
+function SnippetCode({
+ path,
+ lines,
+ first,
+ caret,
+}: {
+ path: string;
+ lines: readonly string[];
+ first: number;
+ caret: number;
+}) {
const language = useMemo(() => languageForPath(path), [path]);
const text = lines.join("\n");
const key = `${language}\u0000${text}`;
@@ -565,9 +581,11 @@ function RecentLocationsDialog() {
tone="strong"
/>
<span className={styles.dir}>{breadcrumbOf(outlines.get(l.path), l) || l.rel}</span>
- {l.changed && <span className={styles.changed}>
+ {l.changed && (
+ <span className={styles.changed}>
<T>changed</T>
- </span>}
+ </span>
+ )}
<span className={styles.time}>{locationTime(l.time, now)}</span>
</div>
<SnippetCode path={l.path} lines={dedent(l.snippet)} first={l.snippetStart} caret={l.line} />
diff --git a/src/features/search/recent/model.ts b/src/features/search/recent/model.ts
index 8e159db48..f90ee5d39 100644
--- a/src/features/search/recent/model.ts
+++ b/src/features/search/recent/model.ts
@@ -167,7 +167,11 @@ export function filterLocations(
}
/** IDEA's Recent Locations time: "Just now", "14 minutes ago", then the pretty timestamp ("Yesterday 22:52"). */
-export function locationTime(ms: number, now = Date.now(), format: (ms: number, now: number) => string = formatTimestamp): string {
+export function locationTime(
+ ms: number,
+ now = Date.now(),
+ format: (ms: number, now: number) => string = formatTimestamp,
+): string {
if (!ms) return "";
const minutes = Math.floor((now - ms) / 60_000);
if (minutes >= 0 && minutes < 1) return "Just now";
diff --git a/src/features/search/recent/store.ts b/src/features/search/recent/store.ts
index 98581ff30..c5b6bacfa 100644
--- a/src/features/search/recent/store.ts
+++ b/src/features/search/recent/store.ts
@@ -31,7 +31,14 @@ export function showRecentPopup(kind: RecentPopupKind) {
else useRecentPopup.setState({ changedOnly: !s.changedOnly });
return;
}
- useRecentPopup.setState({ open: kind, editedOnly: false, changedOnly: false, session: s.session + 1, switcher: false, step: 0 });
+ useRecentPopup.setState({
+ open: kind,
+ editedOnly: false,
+ changedOnly: false,
+ session: s.session + 1,
+ switcher: false,
+ step: 0,
+ });
}
/** ⌃⇥ / ⌃⇧⇥: opens the switcher, or moves its selection while Ctrl is held. */
diff --git a/src/features/search/structure/StructureView.tsx b/src/features/search/structure/StructureView.tsx
index c92642e9d..685fbcfe0 100644
--- a/src/features/search/structure/StructureView.tsx
+++ b/src/features/search/structure/StructureView.tsx
@@ -49,7 +49,12 @@ function useOutlineNodes() {
const inherited = useOutline((s) => s.inherited);
const extra = showInherited && supported ? inherited : null;
return useMemo(
- () => sortOutline(applyViewFilter(withInherited(keyOutline(items ?? []), extra), { fields, nonPublic }), alphabetical, byVisibility),
+ () =>
+ sortOutline(
+ applyViewFilter(withInherited(keyOutline(items ?? []), extra), { fields, nonPublic }),
+ alphabetical,
+ byVisibility,
+ ),
[items, extra, alphabetical, byVisibility, fields, nonPublic],
);
}
@@ -88,7 +93,17 @@ const navigate = (path: string, node: OutlineNode, focus: boolean) => {
};
/** A symbol row; inherited members are greyed and name their supertype. */
-function SymbolRow({ node, indices, selected, dim }: { node: OutlineNode; indices?: readonly number[] | null; selected: boolean; dim?: boolean }) {
+function SymbolRow({
+ node,
+ indices,
+ selected,
+ dim,
+}: {
+ node: OutlineNode;
+ indices?: readonly number[] | null;
+ selected: boolean;
+ dim?: boolean;
+}) {
return (
<span className={clsx(styles.node, dim && styles.ancestor, node.inherited && styles.inherited)}>
<SymbolBadge kind={badgeKind(node.item.kind)} className={styles.badge} />
@@ -334,11 +349,15 @@ function FileStructureDialog() {
walk(filter.nodes);
return m;
}, [filter.nodes]);
- const expanded = useMemo(() => new Set(allKeys(filter.nodes).filter((k) => !collapsed.has(k))), [filter.nodes, collapsed]);
+ const expanded = useMemo(
+ () => new Set(allKeys(filter.nodes).filter((k) => !collapsed.has(k))),
+ [filter.nodes, collapsed],
+ );
// Preselect the symbol at the caret, then the best match while filtering.
const caretKey = useMemo(
- () => (caret && caret.path === path ? (symbolPathAt(nodes, { line: caret.line, col: caret.col }).pop() ?? null) : null),
+ () =>
+ caret && caret.path === path ? (symbolPathAt(nodes, { line: caret.line, col: caret.col }).pop() ?? null) : null,
[caret, path, nodes],
);
const preselect = query.trim() ? filter.best : caretKey;
@@ -491,7 +510,11 @@ function FileStructureDialog() {
onActivate={(n) => choose(n)}
rowHeight={POPUP_ROW}
indent={16}
- empty={<span className={styles.popupEmpty}>{!path ? tx("Open a file first") : loading && !items ? tx("Loading…") : tx("No symbols")}</span>}
+ empty={
+ <span className={styles.popupEmpty}>
+ {!path ? tx("Open a file first") : loading && !items ? tx("Loading…") : tx("No symbols")}
+ </span>
+ }
renderNode={(n, s) => {
const matched = filter.matches.get(n.key);
return <SymbolRow node={n} indices={matched} selected={s.selected} dim={!!query.trim() && !matched} />;
diff --git a/src/features/search/structure/inherited.ts b/src/features/search/structure/inherited.ts
index d58667c68..25ab4fcd5 100644
--- a/src/features/search/structure/inherited.ts
+++ b/src/features/search/structure/inherited.ts
@@ -48,7 +48,12 @@ function typeAt(outline: readonly OutlineItem[], at: Pos): OutlineItem | null {
}
/** Inherited members of `type` (declared in `path`), nearest supertypes first, up to `depth` levels. */
-export async function inheritedMembers(path: string, type: OutlineItem, deps: InheritedDeps, depth = 6): Promise<InheritedMember[]> {
+export async function inheritedMembers(
+ path: string,
+ type: OutlineItem,
+ deps: InheritedDeps,
+ depth = 6,
+): Promise<InheritedMember[]> {
const own = new Set(type.children.map((c) => baseName(c.name)));
const out: InheritedMember[] = [];
const seen = new Set<string>();
diff --git a/src/features/search/structure/outline.ts b/src/features/search/structure/outline.ts
index a6011e2ad..e50c94809 100644
--- a/src/features/search/structure/outline.ts
+++ b/src/features/search/structure/outline.ts
@@ -22,7 +22,10 @@ export function keyOutline(items: readonly OutlineItem[], parent = ""): OutlineN
}
/** Appends each type's inherited members (keyed by `typeKey`) after its own ones. */
-export function withInherited(nodes: readonly OutlineNode[], inherited: ReadonlyMap<string, readonly InheritedMember[]> | null): OutlineNode[] {
+export function withInherited(
+ nodes: readonly OutlineNode[],
+ inherited: ReadonlyMap<string, readonly InheritedMember[]> | null,
+): OutlineNode[] {
if (!inherited?.size) return nodes as OutlineNode[];
return nodes.map((n) => {
const children = withInherited(n.children, inherited);
@@ -33,7 +36,12 @@ export function withInherited(nodes: readonly OutlineNode[], inherited: Readonly
const id = `${m.owner}:${m.item.kind}:${m.item.name}`;
const k = seen.get(id) ?? 0;
seen.set(id, k + 1);
- return { key: `${n.key}/inherited:${id}${k ? `#${k}` : ""}`, item: m.item, children: [], inherited: { path: m.path, owner: m.owner } };
+ return {
+ key: `${n.key}/inherited:${id}${k ? `#${k}` : ""}`,
+ item: m.item,
+ children: [],
+ inherited: { path: m.path, owner: m.owner },
+ };
});
return { ...n, children: [...children, ...added] };
});
@@ -44,11 +52,7 @@ const VISIBILITY_RANK: Record<Visibility, number> = { public: 0, protected: 1, p
/** Rank for "Sort by Visibility": unknown counts as public. */
export const visibilityRank = (item: OutlineItem) => (item.visibility ? VISIBILITY_RANK[item.visibility] : 0);
-export function sortOutline(
- nodes: readonly OutlineNode[],
- alphabetical: boolean,
- byVisibility = false,
-): OutlineNode[] {
+export function sortOutline(nodes: readonly OutlineNode[], alphabetical: boolean, byVisibility = false): OutlineNode[] {
if (!alphabetical && !byVisibility) return nodes as OutlineNode[];
return [...nodes]
.sort(
@@ -151,8 +155,7 @@ export function filterOutline(nodes: readonly OutlineNode[], query: string, narr
}
}
const children = walk(node.children);
- if (!q || !narrow || hit || children.length)
- out.push(narrow ? { ...node, children } : node);
+ if (!q || !narrow || hit || children.length) out.push(narrow ? { ...node, children } : node);
}
return out;
};
@@ -161,7 +164,11 @@ export function filterOutline(nodes: readonly OutlineNode[], query: string, narr
}
/** Parent key of every node (`null` for top-level ones). */
-export function parentKeys(nodes: readonly OutlineNode[], parent: string | null = null, out = new Map<string, string | null>()) {
+export function parentKeys(
+ nodes: readonly OutlineNode[],
+ parent: string | null = null,
+ out = new Map<string, string | null>(),
+) {
for (const n of nodes) {
out.set(n.key, parent);
parentKeys(n.children, n.key, out);
diff --git a/src/features/search/structure/store.ts b/src/features/search/structure/store.ts
index dc3b27fb9..94dccb122 100644
--- a/src/features/search/structure/store.ts
+++ b/src/features/search/structure/store.ts
@@ -81,14 +81,19 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI
return;
}
const deps = inheritedDeps(path, doc);
- const entries = await Promise.all(types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const));
- if (my === seq) useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) });
+ const entries = await Promise.all(
+ types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const),
+ );
+ if (my === seq)
+ useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) });
}
async function load(doc: number, path: string) {
const my = ++seq;
useOutline.setState((s) =>
- s.path === path ? { loading: true } : { path, doc, items: null, loading: true, error: null, inheritedSupported: false, inherited: null },
+ s.path === path
+ ? { loading: true }
+ : { path, doc, items: null, loading: true, error: null, inheritedSupported: false, inherited: null },
);
try {
const items = await call(commands.docOutline(doc));
@@ -108,7 +113,15 @@ function start(): () => void {
const ctx = current();
if (!ctx) {
seq++;
- useOutline.setState({ path: null, doc: null, items: null, loading: false, error: null, inheritedSupported: false, inherited: null });
+ useOutline.setState({
+ path: null,
+ doc: null,
+ items: null,
+ loading: false,
+ error: null,
+ inheritedSupported: false,
+ inherited: null,
+ });
return;
}
void load(ctx.doc, ctx.path);
diff --git a/src/features/services/dialogs.tsx b/src/features/services/dialogs.tsx
index 11a223724..eae933c10 100644
--- a/src/features/services/dialogs.tsx
+++ b/src/features/services/dialogs.tsx
@@ -205,7 +205,9 @@ function ConnectionDialog({ existing, onDone }: { existing?: DockerConnection; o
placeholder="contains ca.pem, cert.pem and key.pem"
onChange={(e) => setTls(e.target.value)}
/>
- <Button onClick={() => void pickDirectory("Certificates Folder").then((d) => d && setTls(d))}>Browse…</Button>
+ <Button onClick={() => void pickDirectory("Certificates Folder").then((d) => d && setTls(d))}>
+ Browse…
+ </Button>
</div>
</>
)}
@@ -243,7 +245,12 @@ function RegistryDialog({ existing, onDone }: { existing?: DockerRegistry; onDon
const [testing, setTesting] = useState(false);
const [id] = useState(() => existing?.id ?? newId("r"));
const ok = name.trim().length > 0 && address.trim().length > 0;
- const registry = (): DockerRegistry => ({ id, name: name.trim(), address: address.trim(), username: username.trim() });
+ const registry = (): DockerRegistry => ({
+ id,
+ name: name.trim(),
+ address: address.trim(),
+ username: username.trim(),
+ });
const submit = async () => {
if (!ok) return;
if (await saveRegistry(registry(), password ? password : existing ? undefined : null)) onDone();
@@ -267,7 +274,12 @@ function RegistryDialog({ existing, onDone }: { existing?: DockerRegistry; onDon
width={480}
footerStart={status && <span className={status.ok ? styles.okText : styles.stderr}>{status.text}</span>}
buttons={[
- { label: "Test Connection", role: "extra", disabled: !ok || !username.trim() || testing, onClick: () => void test() },
+ {
+ label: "Test Connection",
+ role: "extra",
+ disabled: !ok || !username.trim() || testing,
+ onClick: () => void test(),
+ },
{ label: "OK", role: "default", disabled: !ok, onClick: () => void submit() },
{ label: "Cancel", role: "cancel" },
]}
diff --git a/src/features/services/docker.tsx b/src/features/services/docker.tsx
index 8d6dca472..0b21841fc 100644
--- a/src/features/services/docker.tsx
+++ b/src/features/services/docker.tsx
@@ -368,7 +368,9 @@ function LogStream(props: {
</div>
))}
{error && <div className={styles.stderr}>{error}</div>}
- {!lines.length && !error && <div className={styles.dim}>{tx(running ? "Waiting for output…" : "No output")}</div>}
+ {!lines.length && !error && (
+ <div className={styles.dim}>{tx(running ? "Waiting for output…" : "No output")}</div>
+ )}
</div>
</div>
);
@@ -457,7 +459,9 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
<span className={styles.bannerText}>{snapshot.errors.join("; ")}</span>
</div>
)}
- <EmptyState title={node.kind === "compose" ? txTemplate(`Compose project '${node.project}'`) : (conn?.name ?? "Docker")}>
+ <EmptyState
+ title={node.kind === "compose" ? txTemplate(`Compose project '${node.project}'`) : (conn?.name ?? "Docker")}
+ >
<div>
{txTemplate(`Engine ${a.serverVersion} · CLI ${a.clientVersion}`)}
{a.context ? txTemplate(` · context ${a.context}`) : ""}
diff --git a/src/features/services/dockerGutter.ts b/src/features/services/dockerGutter.ts
index b95161df4..56a8c9909 100644
--- a/src/features/services/dockerGutter.ts
+++ b/src/features/services/dockerGutter.ts
@@ -45,11 +45,18 @@ function menu(target: DockerTarget, path: string): MenuItem[] {
}
class Marker extends GutterMarker {
- constructor(readonly target: DockerTarget, readonly path: string) {
+ constructor(
+ readonly target: DockerTarget,
+ readonly path: string,
+ ) {
super();
}
override eq(other: GutterMarker): boolean {
- return other instanceof Marker && other.path === this.path && targetTitle(other.target, other.path) === targetTitle(this.target, this.path);
+ return (
+ other instanceof Marker &&
+ other.path === this.path &&
+ targetTitle(other.target, other.path) === targetTitle(this.target, this.path)
+ );
}
override toDOM(): Node {
const el = document.createElement("div");
@@ -76,7 +83,10 @@ export function dockerGutter(ctx: EditorDocContext): Extension {
}
schedule(delay: number) {
clearTimeout(this.timer);
- this.timer = setTimeout(() => this.view.dispatch({ effects: setTargets.of(place(this.view.state, path)) }), delay);
+ this.timer = setTimeout(
+ () => this.view.dispatch({ effects: setTargets.of(place(this.view.state, path)) }),
+ delay,
+ );
}
destroy() {
clearTimeout(this.timer);
@@ -89,7 +99,11 @@ export function dockerGutter(ctx: EditorDocContext): Extension {
gutter({
// Shares the run gutter's class so "Show run icons" hides these too.
class: `${styles.gutter} cm-openidea-gutter-run`,
- markers: (view) => RangeSet.of(view.state.field(targetsField).map((p) => new Marker(p.target, path).range(p.pos)), true),
+ markers: (view) =>
+ RangeSet.of(
+ view.state.field(targetsField).map((p) => new Marker(p.target, path).range(p.pos)),
+ true,
+ ),
initialSpacer: () => new Marker({ kind: "composeAll", line: 0 }, path),
domEventHandlers: {
mousedown: (view, block, event) => {
diff --git a/src/features/services/index.ts b/src/features/services/index.ts
index 5c4bf7f0c..f1b77b9de 100644
--- a/src/features/services/index.ts
+++ b/src/features/services/index.ts
@@ -22,7 +22,19 @@ import { dockerGutter } from "./dockerGutter";
import { registerDockerRunTypes } from "./runTypes";
import { ServicesDialogHost } from "./dialogs";
import { dockerProvider, selectedTarget } from "./docker";
-import { canRemove, canStart, canStop, execShell, pullPrompt, prunePrompt, remove, restart, showDetail, start, stop } from "./ops";
+import {
+ canRemove,
+ canStart,
+ canStop,
+ execShell,
+ pullPrompt,
+ prunePrompt,
+ remove,
+ restart,
+ showDetail,
+ start,
+ stop,
+} from "./ops";
import { SERVICES_VIEW_FOCUS, ServicesTreeView, showAddServiceMenu } from "./ServicesTree";
import { ServicesHeaderActions, ServicesHost, ServicesTabs } from "./ServicesHost";
import { connections, refresh } from "./store";
@@ -48,7 +60,13 @@ export function activate(): () => void {
headerContent: ServicesTabs,
headerActions: ServicesHeaderActions,
}),
- registerServiceView({ id: SERVICES_TREE_VIEW, title: "Services", icon: "toolwindow-services", order: 0, component: ServicesTreeView }),
+ registerServiceView({
+ id: SERVICES_TREE_VIEW,
+ title: "Services",
+ icon: "toolwindow-services",
+ order: 0,
+ component: ServicesTreeView,
+ }),
registerServiceProvider(dockerProvider),
registerOverlay({ id: "services.dialogs", component: ServicesDialogHost }),
registerEditorContribution({ id: "services.dockerGutter", order: 56, extensions: dockerGutter }),
@@ -77,7 +95,14 @@ export function activate(): () => void {
requestAnimationFrame(() => showAddServiceMenu());
},
},
- { id: "docker.refresh", title: "Refresh Docker", category: "Docker", icon: "refresh", when: PROJECT, run: () => refresh() },
+ {
+ id: "docker.refresh",
+ title: "Refresh Docker",
+ category: "Docker",
+ icon: "refresh",
+ when: PROJECT,
+ run: () => refresh(),
+ },
{
id: "docker.start",
title: "Start Container",
@@ -94,7 +119,14 @@ export function activate(): () => void {
when: PROJECT,
run: () => (canStop(selectedTarget()) ? stop(selectedTarget()) : undefined),
},
- { id: "docker.restart", title: "Restart Container", category: "Docker", icon: "rerun", when: PROJECT, run: () => restart(selectedTarget()) },
+ {
+ id: "docker.restart",
+ title: "Restart Container",
+ category: "Docker",
+ icon: "rerun",
+ when: PROJECT,
+ run: () => restart(selectedTarget()),
+ },
{
id: "docker.remove",
title: "Delete Docker Object…",
diff --git a/src/features/services/model.ts b/src/features/services/model.ts
index 9d527b384..842a34a50 100644
--- a/src/features/services/model.ts
+++ b/src/features/services/model.ts
@@ -42,7 +42,12 @@ export function childrenOf(snap: DockerSnapshot | null): (n: ServiceNode) => Ser
if (!snap || snap.availability.kind !== "ready") return undefined;
switch (n.kind) {
case "docker":
- return GROUPS.map(([group]) => ({ kind: "group", key: `group:${group}`, group, count: groupCount(snap, group) }));
+ return GROUPS.map(([group]) => ({
+ kind: "group",
+ key: `group:${group}`,
+ group,
+ count: groupCount(snap, group),
+ }));
case "group":
return groupChildren(snap, n.group);
case "compose":
@@ -58,10 +63,20 @@ export function childrenOf(snap: DockerSnapshot | null): (n: ServiceNode) => Ser
}
function groupCount(snap: DockerSnapshot, g: GroupKind): number {
- return g === "containers" ? snap.containers.length : g === "images" ? snap.images.length : g === "volumes" ? snap.volumes.length : snap.networks.length;
+ return g === "containers"
+ ? snap.containers.length
+ : g === "images"
+ ? snap.images.length
+ : g === "volumes"
+ ? snap.volumes.length
+ : snap.networks.length;
}
-const containerNode = (c: DockerContainer): ServiceNode => ({ kind: "container", key: `container:${c.id}`, container: c });
+const containerNode = (c: DockerContainer): ServiceNode => ({
+ kind: "container",
+ key: `container:${c.id}`,
+ container: c,
+});
/** Compose projects (by label) first, then standalone containers, as IDEA groups them. */
export function groupChildren(snap: DockerSnapshot, g: GroupKind): ServiceNode[] {
@@ -79,7 +94,9 @@ export function groupChildren(snap: DockerSnapshot, g: GroupKind): ServiceNode[]
kind: "compose",
key: `compose:${project}`,
project,
- containers: [...containers].sort((a, b) => (a.composeService ?? a.name).localeCompare(b.composeService ?? b.name)),
+ containers: [...containers].sort((a, b) =>
+ (a.composeService ?? a.name).localeCompare(b.composeService ?? b.name),
+ ),
}));
return [...compose, ...loose.map(containerNode)];
}
diff --git a/src/features/services/ops.ts b/src/features/services/ops.ts
index 62d0f6de0..c604c2225 100644
--- a/src/features/services/ops.ts
+++ b/src/features/services/ops.ts
@@ -6,7 +6,16 @@ import type { MenuItem } from "@/ui";
import { confirm, confirmChecked } from "@/workbench/messages";
import { promptText } from "./dialogs";
import { isRunning, nodeContainers, nodeLabel, shortId, type DockerTarget, type ServiceNode } from "./model";
-import { composeOp, connectionState, containerOp, prune, pullImage, refresh, removeObjects, useServices } from "./store";
+import {
+ composeOp,
+ connectionState,
+ containerOp,
+ prune,
+ pullImage,
+ refresh,
+ removeObjects,
+ useServices,
+} from "./store";
export function canStart(t: DockerTarget | null): boolean {
return !!t && nodeContainers(t.node).some((c) => !isRunning(c));
@@ -24,14 +33,18 @@ export function canRemove(t: DockerTarget | null): boolean {
export async function start(t: DockerTarget | null) {
if (!t) return;
if (t.node.kind === "compose") return composeAction(t.conn, t.node, "start");
- const ids = nodeContainers(t.node).filter((c) => !isRunning(c)).map((c) => c.id);
+ const ids = nodeContainers(t.node)
+ .filter((c) => !isRunning(c))
+ .map((c) => c.id);
if (ids.length) await containerOp(t.conn, ids, "start");
}
export async function stop(t: DockerTarget | null) {
if (!t) return;
if (t.node.kind === "compose") return composeAction(t.conn, t.node, "stop");
- const ids = nodeContainers(t.node).filter(isRunning).map((c) => c.id);
+ const ids = nodeContainers(t.node)
+ .filter(isRunning)
+ .map((c) => c.id);
if (ids.length) await containerOp(t.conn, ids, "stop");
}
@@ -42,9 +55,15 @@ export async function restart(t: DockerTarget | null) {
if (ids.length) await containerOp(t.conn, ids, "restart");
}
-function composeAction(conn: string, n: Extract<ServiceNode, { kind: "compose" }>, op: "start" | "stop" | "restart" | "down") {
+function composeAction(
+ conn: string,
+ n: Extract<ServiceNode, { kind: "compose" }>,
+ op: "start" | "stop" | "restart" | "down",
+) {
const first = n.containers[0];
- return composeOp(conn, n.project, first?.composeFiles ?? [], first?.composeWorkingDir ?? null, op).then(() => undefined);
+ return composeOp(conn, n.project, first?.composeFiles ?? [], first?.composeWorkingDir ?? null, op).then(
+ () => undefined,
+ );
}
function deleteQuestion(kind: "container" | "image" | "volume" | "network", label: string, running: boolean) {
@@ -87,7 +106,14 @@ export async function remove(t: DockerTarget | null) {
checkbox: n.kind === "image" ? "Force (also untag / remove when used by stopped containers)" : undefined,
});
if (!answer) return;
- const id = n.kind === "container" ? n.container.id : n.kind === "image" ? n.image.id : n.kind === "volume" ? n.volume.name : n.network.id;
+ const id =
+ n.kind === "container"
+ ? n.container.id
+ : n.kind === "image"
+ ? n.image.id
+ : n.kind === "volume"
+ ? n.volume.name
+ : n.network.id;
await removeObjects(t.conn, what, [id], running || answer.checked);
}
@@ -98,7 +124,15 @@ export function execShell(t: DockerTarget | null) {
const snap = connectionState(t.conn).snapshot;
void executeAction("terminal.runCommand", {
program: snap?.executable ?? "docker",
- args: [...(snap?.globalArgs ?? []), "exec", "-it", c.id, "sh", "-c", "command -v bash >/dev/null 2>&1 && exec bash || exec sh"],
+ args: [
+ ...(snap?.globalArgs ?? []),
+ "exec",
+ "-it",
+ c.id,
+ "sh",
+ "-c",
+ "command -v bash >/dev/null 2>&1 && exec bash || exec sh",
+ ],
name: c.name,
});
}
@@ -114,7 +148,11 @@ const PRUNE: Array<[PruneTarget, string, string]> = [
["allImages", "Unused Images", "Remove all images not used by a container?"],
["volumes", "Unused Volumes", "Remove all anonymous volumes not used by a container? Their data is lost."],
["networks", "Unused Networks", "Remove all networks not used by a container?"],
- ["system", "Everything Unused (System Prune)", "Remove stopped containers, unused networks, dangling images and the build cache?"],
+ [
+ "system",
+ "Everything Unused (System Prune)",
+ "Remove stopped containers, unused networks, dangling images and the build cache?",
+ ],
];
export async function prunePrompt(conn: string, target: PruneTarget) {
@@ -167,7 +205,12 @@ export function nodeMenu(t: DockerTarget): MenuItem[] {
items.push(
n.container.state === "paused"
? { label: "Unpause", icon: "resume", run: () => void containerOp(conn, [n.container.id], "unpause") }
- : { label: "Pause", icon: "pause", disabled: !running, run: () => void containerOp(conn, [n.container.id], "pause") },
+ : {
+ label: "Pause",
+ icon: "pause",
+ disabled: !running,
+ run: () => void containerOp(conn, [n.container.id], "pause"),
+ },
{ kind: "separator" },
{ label: "Show Log", icon: "file-log", run: () => showDetail("log") },
{ label: "Inspect", icon: "info", run: () => showDetail("inspect") },
@@ -181,13 +224,26 @@ export function nodeMenu(t: DockerTarget): MenuItem[] {
items.push({ label: "Inspect", icon: "info", run: () => showDetail("inspect") });
if (n.kind === "image")
items.push(
- { label: "Pull Again", icon: "git-pull", disabled: n.image.repository === "<none>", run: () => void pullImage(conn, nodeLabel(n)) },
+ {
+ label: "Pull Again",
+ icon: "git-pull",
+ disabled: n.image.repository === "<none>",
+ run: () => void pullImage(conn, nodeLabel(n)),
+ },
{ label: "Copy Image ID", icon: "copy", run: () => copy(shortId(n.image.id)) },
);
}
- if (n.kind === "group" && n.group === "images") items.push({ label: "Pull Image…", icon: "git-pull", run: () => void pullPrompt(conn) });
+ if (n.kind === "group" && n.group === "images")
+ items.push({ label: "Pull Image…", icon: "git-pull", run: () => void pullPrompt(conn) });
if (n.kind === "group") {
- const target: PruneTarget = n.group === "containers" ? "containers" : n.group === "images" ? "images" : n.group === "volumes" ? "volumes" : "networks";
+ const target: PruneTarget =
+ n.group === "containers"
+ ? "containers"
+ : n.group === "images"
+ ? "images"
+ : n.group === "volumes"
+ ? "volumes"
+ : "networks";
items.push({
label: pruneLabel(target),
run: () => void prunePrompt(conn, target),
@@ -200,7 +256,15 @@ export function nodeMenu(t: DockerTarget): MenuItem[] {
{ label: "Prune", submenu: pruneMenu(conn) },
);
if (canRemove(t)) {
- items.push({ kind: "separator" }, { label: n.kind === "compose" ? "Compose Down" : "Delete…", icon: "trash", danger: true, run: () => void remove(t) });
+ items.push(
+ { kind: "separator" },
+ {
+ label: n.kind === "compose" ? "Compose Down" : "Delete…",
+ icon: "trash",
+ danger: true,
+ run: () => void remove(t),
+ },
+ );
}
return items;
}
diff --git a/src/features/services/services.test.ts b/src/features/services/services.test.ts
index 094ab9f0f..8e12341cc 100644
--- a/src/features/services/services.test.ts
+++ b/src/features/services/services.test.ts
@@ -1,8 +1,25 @@
import { describe, expect, it } from "vitest";
import type { DockerContainer, DockerSnapshot } from "@/platform/ipc";
import { composeTargets, dockerfileTargets, fileTargets, imageTag, isComposeFile, isDockerfile } from "./compose";
-import { DOCKERFILE, DOCKER_COMPOSE, containerName, dockerComposeType, dockerImageType, gutterActions, shellQuote } from "./runTypes";
-import { childrenOf, findNode, nodeDetail, nodeLabel, parseTreeKey, rootNodes, treeKey, type ServiceNode } from "./model";
+import {
+ DOCKERFILE,
+ DOCKER_COMPOSE,
+ containerName,
+ dockerComposeType,
+ dockerImageType,
+ gutterActions,
+ shellQuote,
+} from "./runTypes";
+import {
+ childrenOf,
+ findNode,
+ nodeDetail,
+ nodeLabel,
+ parseTreeKey,
+ rootNodes,
+ treeKey,
+ type ServiceNode,
+} from "./model";
import { endpointFrom } from "./dialogs";
import { dockerItems } from "./docker";
import { addServiceMenu, expandableKeys, indexTree } from "./tree";
@@ -25,7 +42,11 @@ const container = (name: string, state: string, project?: string, service?: stri
const snapshot: DockerSnapshot = {
availability: { kind: "ready", clientVersion: "27", serverVersion: "27", context: null },
executable: "/usr/bin/docker",
- containers: [container("web", "exited"), container("shop-db-1", "running", "shop", "db"), container("shop-api-1", "exited", "shop", "api")],
+ containers: [
+ container("web", "exited"),
+ container("shop-db-1", "running", "shop", "db"),
+ container("shop-api-1", "exited", "shop", "api"),
+ ],
images: [{ id: "sha256:abc", repository: "postgres", tag: "16", size: "1MB", createdSince: "now" }],
volumes: [],
networks: [],
@@ -59,7 +80,10 @@ describe("services tree", () => {
});
describe("services tree host", () => {
- const conns = [{ id: "default", name: "Docker", endpoint: { kind: "default" as const } }, { id: "c2", name: "Build box", endpoint: { kind: "tcp" as const, host: "build:2376", tlsCertDir: null } }];
+ const conns = [
+ { id: "default", name: "Docker", endpoint: { kind: "default" as const } },
+ { id: "c2", name: "Build box", endpoint: { kind: "tcp" as const, host: "build:2376", tlsCertDir: null } },
+ ];
const state = { default: { snapshot, loading: false, error: null } };
it("puts every connection and registry at the root, with connection-scoped keys", () => {
@@ -73,7 +97,10 @@ describe("services tree host", () => {
expect(items[1]!.children).toEqual([]);
const containers = items[0]!.children![0]!;
expect(containers.key).toBe("docker:default:group:containers");
- expect(containers.children!.map((c) => c.key)).toEqual(["docker:default:compose:shop", "docker:default:container:web-id"]);
+ expect(containers.children!.map((c) => c.key)).toEqual([
+ "docker:default:compose:shop",
+ "docker:default:container:web-id",
+ ]);
expect(containers.children![1]!.dim).toBe(true);
const index = indexTree({ docker: items });
expect(index.get("docker:default:container:shop-db-1-id")?.item.label).toBe("db");
@@ -107,8 +134,16 @@ describe("services tree host", () => {
const f = { path: " /var/run/docker.sock ", host: "", tls: "", context: "" };
expect(endpointFrom("socket", f)).toEqual({ kind: "socket", path: "/var/run/docker.sock" });
expect(endpointFrom("tcp", f)).toBeNull();
- expect(endpointFrom("tcp", { ...f, host: "tcp://h:2376", tls: "/certs" })).toEqual({ kind: "tcp", host: "tcp://h:2376", tlsCertDir: "/certs" });
- expect(endpointFrom("tcp", { ...f, host: "h:2375", tls: " " })).toEqual({ kind: "tcp", host: "h:2375", tlsCertDir: null });
+ expect(endpointFrom("tcp", { ...f, host: "tcp://h:2376", tls: "/certs" })).toEqual({
+ kind: "tcp",
+ host: "tcp://h:2376",
+ tlsCertDir: "/certs",
+ });
+ expect(endpointFrom("tcp", { ...f, host: "h:2375", tls: " " })).toEqual({
+ kind: "tcp",
+ host: "h:2375",
+ tlsCertDir: null,
+ });
expect(endpointFrom("context", { ...f, context: "--evil" })).toBeNull();
expect(endpointFrom("context", { ...f, context: "orbstack" })).toEqual({ kind: "context", name: "orbstack" });
expect(endpointFrom("default", f)).toEqual({ kind: "default" });
@@ -151,7 +186,8 @@ describe("docker run targets", () => {
});
it("builds each FROM stage", () => {
- const text = "FROM node:22 AS build\nRUN npm ci\nFROM --platform=linux/amd64 nginx:1.27\nCOPY --from=build /app /usr/share/nginx/html\n";
+ const text =
+ "FROM node:22 AS build\nRUN npm ci\nFROM --platform=linux/amd64 nginx:1.27\nCOPY --from=build /app /usr/share/nginx/html\n";
expect(dockerfileTargets(text)).toEqual([
{ kind: "build", line: 0, stage: "build", last: false },
{ kind: "build", line: 2, stage: null, last: true },
@@ -161,13 +197,25 @@ describe("docker run targets", () => {
it("creates Dockerfile and Docker Compose run configurations", () => {
expect(imageTag("/work/My App/Dockerfile")).toBe("my-app:latest");
- const [stage] = gutterActions({ kind: "build", line: 0, stage: "build", last: false }, "/work/app/docker/Dockerfile", "/work/app");
+ const [stage] = gutterActions(
+ { kind: "build", line: 0, stage: "build", last: false },
+ "/work/app/docker/Dockerfile",
+ "/work/app",
+ );
expect(stage!.title).toBe("Build Stage 'build'");
- expect(stage!.config).toMatchObject({ kind: DOCKERFILE, cwd: null, params: { dockerfile: "docker/Dockerfile", target: "build" } });
+ expect(stage!.config).toMatchObject({
+ kind: DOCKERFILE,
+ cwd: null,
+ params: { dockerfile: "docker/Dockerfile", target: "build" },
+ });
expect(stage!.config.command).toBe("docker build -f docker/Dockerfile -t docker:latest --target build docker");
expect(stage!.config.stopCommand).toBeUndefined();
- const [run, buildOnly] = gutterActions({ kind: "build", line: 4, stage: null, last: true }, "/work/app/Dockerfile", "/work/app");
+ const [run, buildOnly] = gutterActions(
+ { kind: "build", line: 4, stage: null, last: true },
+ "/work/app/Dockerfile",
+ "/work/app",
+ );
expect(run!.title).toBe("Run 'Dockerfile'");
expect(run!.config.command).toBe(
"docker build -f Dockerfile -t app:latest . && (docker rm -f app >/dev/null 2>&1; docker run --name app app:latest)",
@@ -175,7 +223,11 @@ describe("docker run targets", () => {
expect(run!.config.stopCommand).toBe("docker stop app");
expect(buildOnly!.title).toBe("Build Image 'app:latest'");
- const [up] = gutterActions({ kind: "composeService", line: 3, service: "db" }, "/work/app/compose.yaml", "/work/app");
+ const [up] = gutterActions(
+ { kind: "composeService", line: 3, service: "db" },
+ "/work/app/compose.yaml",
+ "/work/app",
+ );
expect(up!.config).toMatchObject({
id: "docker:compose:compose.yaml:db",
kind: DOCKER_COMPOSE,
@@ -201,7 +253,12 @@ describe("docker run targets", () => {
expect(image.stop).toBe("docker stop postgres");
expect(containerName({ containerName: " web " }, "x")).toBe("web");
expect(containerName({}, "ghcr.io/org/my-app@sha256:abc")).toBe("my-app");
- const detached = dockerComposeType.commandLine({ files: "a.yml; b.yml", project: "demo", detach: "true", build: "true" })!;
+ const detached = dockerComposeType.commandLine({
+ files: "a.yml; b.yml",
+ project: "demo",
+ detach: "true",
+ build: "true",
+ })!;
expect(detached).toMatchObject({ command: "docker compose -f a.yml -f b.yml -p demo up -d --build", stop: null });
expect(shellQuote('a "b"', true)).toBe('"a ""b"""');
});
diff --git a/src/features/services/store.ts b/src/features/services/store.ts
index 812fa81cd..9534fe59d 100644
--- a/src/features/services/store.ts
+++ b/src/features/services/store.ts
@@ -90,10 +90,17 @@ export function loadSettings(): Promise<void> {
return Promise.resolve();
}
settingsLoad ??= call(commands.dockerSettings())
- .then((s: DockerSettings) => useServices.setState({ settings: { connections: s.connections ?? [], registries: s.registries ?? [] } }))
+ .then((s: DockerSettings) =>
+ useServices.setState({ settings: { connections: s.connections ?? [], registries: s.registries ?? [] } }),
+ )
.catch((e) => {
settingsLoad = null;
- notifications().notify({ group: "run", level: "error", title: "Cannot read Docker settings", body: errorMessage(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: "Cannot read Docker settings",
+ body: errorMessage(e),
+ });
});
return settingsLoad;
}
@@ -104,7 +111,12 @@ async function saveSettings(settings: Settings): Promise<boolean> {
useServices.setState({ settings });
return true;
} catch (e) {
- notifications().notify({ group: "run", level: "error", title: "Cannot save Docker settings", body: errorMessage(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: "Cannot save Docker settings",
+ body: errorMessage(e),
+ });
return false;
}
}
@@ -116,7 +128,10 @@ export async function saveConnection(c: DockerConnection): Promise<boolean> {
await loadSettings();
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const exists = s.connections.some((x) => x.id === c.id);
- const ok = await saveSettings({ ...s, connections: exists ? s.connections.map((x) => (x.id === c.id ? c : x)) : [...s.connections, c] });
+ const ok = await saveSettings({
+ ...s,
+ connections: exists ? s.connections.map((x) => (x.id === c.id ? c : x)) : [...s.connections, c],
+ });
if (ok) {
stopEvents(c.id);
if (watchers > 0) void refresh(c.id);
@@ -142,12 +157,20 @@ export async function saveRegistry(r: DockerRegistry, password: string | null |
await loadSettings();
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const exists = s.registries.some((x) => x.id === r.id);
- const ok = await saveSettings({ ...s, registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r] });
+ const ok = await saveSettings({
+ ...s,
+ registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
+ });
if (ok && password !== undefined && isTauri()) {
try {
await call(commands.dockerSetRegistryPassword(r.id, password));
} catch (e) {
- notifications().notify({ group: "run", level: "error", title: "Cannot save the registry password", body: errorMessage(e) });
+ notifications().notify({
+ group: "run",
+ level: "error",
+ title: "Cannot save the registry password",
+ body: errorMessage(e),
+ });
}
}
return ok;
@@ -200,7 +223,10 @@ export function refresh(id?: string): Promise<void> {
const debounces = new Map<string, ReturnType<typeof setTimeout>>();
function refreshSoon(id: string) {
clearTimeout(debounces.get(id));
- debounces.set(id, setTimeout(() => void refresh(id), 250));
+ debounces.set(
+ id,
+ setTimeout(() => void refresh(id), 250),
+ );
}
const events = new Map<string, RequestId>();
@@ -272,12 +298,18 @@ async function guarded(connId: string, title: string, run: () => Promise<unknown
}
export function containerOp(connId: string, ids: string[], op: ContainerOp): Promise<boolean> {
- const verb = { start: "start", stop: "stop", restart: "restart", pause: "pause", unpause: "unpause", kill: "kill" }[op];
- return guarded(connId, `Could not ${verb} container`, () => call(commands.dockerContainerOp(endpointOf(connId), ids, op)));
+ const verb = { start: "start", stop: "stop", restart: "restart", pause: "pause", unpause: "unpause", kill: "kill" }[
+ op
+ ];
+ return guarded(connId, `Could not ${verb} container`, () =>
+ call(commands.dockerContainerOp(endpointOf(connId), ids, op)),
+ );
}
export function removeObjects(connId: string, object: DockerObject, ids: string[], force: boolean): Promise<boolean> {
- return guarded(connId, `Could not remove ${object}`, () => call(commands.dockerRemove(endpointOf(connId), object, ids, force)));
+ return guarded(connId, `Could not remove ${object}`, () =>
+ call(commands.dockerRemove(endpointOf(connId), object, ids, force)),
+ );
}
/** Runs a streaming operation, showing its latest output line in the view's banner. */
@@ -287,7 +319,12 @@ async function task(
run: (request: RequestId, out: Channel<string>) => Promise<unknown>,
): Promise<boolean> {
if (useServices.getState().task) {
- notifications().notify({ group: "run", level: "info", title: "Another Docker operation is still running", key: "docker-op" });
+ notifications().notify({
+ group: "run",
+ level: "info",
+ title: "Another Docker operation is still running",
+ key: "docker-op",
+ });
return false;
}
const request = nextRequestId();
@@ -302,7 +339,14 @@ async function task(
return await guarded(connId, title.replace(/…$/, "") + " failed", () => run(request, out));
} finally {
useServices.setState({ task: null });
- if (last) notifications().notify({ group: "run", level: "info", title: title.replace(/…$/, ""), body: last, key: "docker-task" });
+ if (last)
+ notifications().notify({
+ group: "run",
+ level: "info",
+ title: title.replace(/…$/, ""),
+ body: last,
+ key: "docker-task",
+ });
}
}
diff --git a/src/features/settings/__tests__/inspections.test.ts b/src/features/settings/__tests__/inspections.test.ts
index f3e408f3f..c20644a00 100644
--- a/src/features/settings/__tests__/inspections.test.ts
+++ b/src/features/settings/__tests__/inspections.test.ts
@@ -44,7 +44,15 @@ describe("inspections tree", () => {
const tree = buildInspectionTree(languages, seen, [{ "lsp:ruff:E501": { severity: "typo" } }]);
it("groups servers by language with seen and configured codes, built-ins by category", () => {
- expect(tree.map((g) => g.name)).toEqual(["General", "JavaScript", "Other", "Proofreading", "Python", "SQL", "TypeScript"]);
+ expect(tree.map((g) => g.name)).toEqual([
+ "General",
+ "JavaScript",
+ "Other",
+ "Proofreading",
+ "Python",
+ "SQL",
+ "TypeScript",
+ ]);
const python = find(tree, "group:Python")!;
expect(python.children.map((n) => n.id)).toEqual(["lsp:basedpyright", "lsp:ruff"]);
expect(python.children[1]!.children.map((n) => n.id)).toEqual(["lsp:ruff:E501", "lsp:ruff:F401"]);
diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts
index b7a05a6d0..5a44781d5 100644
--- a/src/features/settings/__tests__/languages.test.ts
+++ b/src/features/settings/__tests__/languages.test.ts
@@ -53,7 +53,14 @@ describe("language pages", () => {
const tree = buildPageTree(LANGUAGE_PAGES.map((p) => ({ ...p, component: p.component! })));
expect(tree.map((n) => n.title)).toEqual(["Project Structure", "Languages & Frameworks"]);
const langs = tree.find((n) => n.title === "Languages & Frameworks")!;
- expect(langs.children.map((n) => n.title)).toEqual(["Go", "Java", "Node.js", "Python Interpreter", "Rust", "TypeScript"]);
+ expect(langs.children.map((n) => n.title)).toEqual([
+ "Go",
+ "Java",
+ "Node.js",
+ "Python Interpreter",
+ "Rust",
+ "TypeScript",
+ ]);
});
it("filters packages and shortens home paths", () => {
@@ -64,7 +71,9 @@ describe("language pages", () => {
expect(filterPackages(pkgs, "dj").map((p) => p.name)).toEqual(["Django"]);
expect(filterPackages(pkgs, "")).toHaveLength(2);
expect(tildify("/Users/me/p/.venv/bin/python")).toBe("~/p/.venv/bin/python");
- expect(tildify("C:/Users/me/.m2/wrapper/dists/apache-maven-3.9.16")).toBe("~/.m2/wrapper/dists/apache-maven-3.9.16");
+ expect(tildify("C:/Users/me/.m2/wrapper/dists/apache-maven-3.9.16")).toBe(
+ "~/.m2/wrapper/dists/apache-maven-3.9.16",
+ );
expect(tildify("C:/Program Files/Java/jdk-21")).toBe("C:/Program Files/Java/jdk-21");
});
});
diff --git a/src/features/settings/appearanceRuntime.ts b/src/features/settings/appearanceRuntime.ts
index f0458947b..1c2734c26 100644
--- a/src/features/settings/appearanceRuntime.ts
+++ b/src/features/settings/appearanceRuntime.ts
@@ -118,7 +118,9 @@ export function zoomActions(): Action[] {
run: async () => {
if (!isTauri()) return;
const next = !validateSettings(useProject.getState().settings).appearance.compactMode;
- useProject.setState({ settings: await call(commands.settingsSet("global", "appearance.compactMode", JSON.stringify(next))) });
+ useProject.setState({
+ settings: await call(commands.settingsSet("global", "appearance.compactMode", JSON.stringify(next))),
+ });
},
},
];
diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx
index a67039b92..548b74a9a 100644
--- a/src/features/settings/pages/editor/codeStyle.tsx
+++ b/src/features/settings/pages/editor/codeStyle.tsx
@@ -60,40 +60,40 @@ const LINE_SEPARATORS: SelectOption[] = [
];
const GENERAL_SECTIONS: EditorSection[] = [
- {
- items: [
- {
- t: "select",
- key: "editor.codeStyle.lineSeparator",
- label: "Line separator",
- options: LINE_SEPARATORS,
- hint: "Used for new files.",
- },
- { t: "number", key: "editor.codeStyle.hardWrapAt", label: "Hard wrap at", min: 1, max: 999, unit: "columns" },
- { t: "custom", label: "Visual guides", component: VisualGuidesRow },
- ],
- },
- {
- title: "Indents Detection",
- items: [
- {
- t: "check",
- key: "editor.codeStyle.detectIndents",
- label: "Detect and use existing file indents for editing",
- },
- ],
- },
- {
- title: "EditorConfig",
- items: [
- {
- t: "check",
- key: "editor.codeStyle.editorconfig",
- label: "Enable EditorConfig support",
- hint: ".editorconfig files override indentation, line separators, encodings and save options.",
- },
- ],
- },
+ {
+ items: [
+ {
+ t: "select",
+ key: "editor.codeStyle.lineSeparator",
+ label: "Line separator",
+ options: LINE_SEPARATORS,
+ hint: "Used for new files.",
+ },
+ { t: "number", key: "editor.codeStyle.hardWrapAt", label: "Hard wrap at", min: 1, max: 999, unit: "columns" },
+ { t: "custom", label: "Visual guides", component: VisualGuidesRow },
+ ],
+ },
+ {
+ title: "Indents Detection",
+ items: [
+ {
+ t: "check",
+ key: "editor.codeStyle.detectIndents",
+ label: "Detect and use existing file indents for editing",
+ },
+ ],
+ },
+ {
+ title: "EditorConfig",
+ items: [
+ {
+ t: "check",
+ key: "editor.codeStyle.editorconfig",
+ label: "Enable EditorConfig support",
+ hint: ".editorconfig files override indentation, line separators, encodings and save options.",
+ },
+ ],
+ },
];
/** Shared by Code Style and its sub-pages: the scheme is one scope. */
@@ -120,7 +120,7 @@ const OTHER = {
{ items: [{ t: "custom", label: "Scheme", component: SchemeRow }] },
{
title: "Tabs and Indents",
- items: [
+ items: [
{ t: "check", key: "editor.insertSpaces", label: "Use tab character", invert: true },
{ t: "number", key: "editor.tabSize", label: "Tab size", min: 1, max: 16 },
],
@@ -251,7 +251,16 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
group: "Editor",
order: 100,
...SCHEME_SCOPE,
- keywords: ["Scheme", "Tabs and Indents", "Tab size", "Indent", "Use tab character", "Hard wrap at", "Comment Code", "Line comment at first column"],
+ keywords: [
+ "Scheme",
+ "Tabs and Indents",
+ "Tab size",
+ "Indent",
+ "Use tab character",
+ "Hard wrap at",
+ "Comment Code",
+ "Line comment at first column",
+ ],
component: () => <LanguageStyle lang={lang} />,
}));
}
diff --git a/src/features/settings/pages/editor/font.tsx b/src/features/settings/pages/editor/font.tsx
index b94543679..45c632610 100644
--- a/src/features/settings/pages/editor/font.tsx
+++ b/src/features/settings/pages/editor/font.tsx
@@ -141,7 +141,19 @@ const WEIGHT_OPTIONS: SelectOption[] = [
{ value: "custom", label: "Custom" },
];
-function WeightRow({ label, value, onChange, defaultWeight, hint }: { label: string; value: number; onChange: (value: number) => void; defaultWeight: number; hint?: string }) {
+function WeightRow({
+ label,
+ value,
+ onChange,
+ defaultWeight,
+ hint,
+}: {
+ label: string;
+ value: number;
+ onChange: (value: number) => void;
+ defaultWeight: number;
+ hint?: string;
+}) {
const [customSelected, setCustomSelected] = useState(false);
const weight = fontWeightOf(value, defaultWeight);
const custom = customSelected || !FONT_WEIGHTS.some(([w]) => w === weight);
@@ -157,7 +169,15 @@ function WeightRow({ label, value, onChange, defaultWeight, hint }: { label: str
aria-label={label}
/>
{custom && (
- <NumberInput value={weight} onChange={(n) => onChange(fontWeightOf(n, defaultWeight))} min={100} max={900} step={50} integer aria-label={tx`${label} custom value`} />
+ <NumberInput
+ value={weight}
+ onChange={(n) => onChange(fontWeightOf(n, defaultWeight))}
+ min={100}
+ max={900}
+ step={50}
+ integer
+ aria-label={tx`${label} custom value`}
+ />
)}
</Row>
);
@@ -175,7 +195,14 @@ function WeightRows() {
return (
<>
<WeightRow key={`${scope}-main`} label="Main font weight" value={main} onChange={setMain} defaultWeight={400} />
- <WeightRow key={`${scope}-bold`} label="Bold font weight" value={bold} onChange={setBold} defaultWeight={700} hint="Used wherever the color scheme shows text in bold" />
+ <WeightRow
+ key={`${scope}-bold`}
+ label="Bold font weight"
+ value={bold}
+ onChange={setBold}
+ defaultWeight={700}
+ hint="Used wherever the color scheme shows text in bold"
+ />
</>
);
}
diff --git a/src/features/settings/pages/editor/general.tsx b/src/features/settings/pages/editor/general.tsx
index 7278f102e..0aaee6a17 100644
--- a/src/features/settings/pages/editor/general.tsx
+++ b/src/features/settings/pages/editor/general.tsx
@@ -413,7 +413,12 @@ const TABS = editorPage({
},
{ t: "check", key: `${P}.tabs.markModified`, label: "Mark modified (*)" },
{ t: "check", key: `${P}.tabs.showFullPathOnHover`, label: "Show full path on mouse hover" },
- { t: "custom", label: "Close button position:", keywords: ["Right", "Left", "None"], component: CloseButtonPosition },
+ {
+ t: "custom",
+ label: "Close button position:",
+ keywords: ["Right", "Left", "None"],
+ component: CloseButtonPosition,
+ },
],
},
{
@@ -425,9 +430,7 @@ const TABS = editorPage({
},
{
title: "Opening Policy",
- items: [
- { t: "check", key: `${P}.tabs.previewTab`, label: "Enable preview tab" },
- ],
+ items: [{ t: "check", key: `${P}.tabs.previewTab`, label: "Enable preview tab" }],
},
{
title: "Closing Policy",
@@ -473,15 +476,29 @@ function TabRows() {
</label>
);
return (
- <div className={clsx(styles.radioBlock, matched && styles.matched)} role="radiogroup" aria-label={tx("Show tabs in")}>
+ <div
+ className={clsx(styles.radioBlock, matched && styles.matched)}
+ role="radiogroup"
+ aria-label={tx("Show tabs in")}
+ >
<div className={clsx(styles.radioLabel, disabled && styles.dim)}>
<SearchLabel text="Show tabs in" />:
</div>
<div className={styles.radios}>
{radio("One row, and if tabs don't fit:", !multiple, () => setMultiple(false))}
<div className={styles.children} role="radiogroup" aria-label={tx("If tabs don't fit")}>
- {radio("Scroll the tabs panel", !multiple && overflow !== "squeeze", () => setOverflow("scroll"), disabled || multiple)}
- {radio("Squeeze tabs", !multiple && overflow === "squeeze", () => setOverflow("squeeze"), disabled || multiple)}
+ {radio(
+ "Scroll the tabs panel",
+ !multiple && overflow !== "squeeze",
+ () => setOverflow("scroll"),
+ disabled || multiple,
+ )}
+ {radio(
+ "Squeeze tabs",
+ !multiple && overflow === "squeeze",
+ () => setOverflow("squeeze"),
+ disabled || multiple,
+ )}
</div>
{radio("Multiple rows", multiple, () => setMultiple(true))}
</div>
diff --git a/src/features/settings/pages/editor/inspections.tsx b/src/features/settings/pages/editor/inspections.tsx
index 69a0103f5..ce2f8df01 100644
--- a/src/features/settings/pages/editor/inspections.tsx
+++ b/src/features/settings/pages/editor/inspections.tsx
@@ -212,7 +212,12 @@ function InspectionsPage() {
disabled: !isCopy,
run: () => setNameDialog({ mode: "rename", level: location.level, initial: label }),
},
- { label: "Restore Defaults", icon: "undo", disabled: !Object.keys(overrides).length, run: () => setOverrides({}) },
+ {
+ label: "Restore Defaults",
+ icon: "undo",
+ disabled: !Object.keys(overrides).length,
+ run: () => setOverrides({}),
+ },
// Default and Project Default cannot be deleted.
...(isCopy
? ([
@@ -239,7 +244,9 @@ function InspectionsPage() {
disabled={profileOptions.length < 2}
/>
<IconButton icon="settings" title="Profile Actions" onClick={gearMenu} />
- <span className={styles.profileLevel}><T>{location.level === "project" ? "Stored in Project" : "Stored in IDE"}</T></span>
+ <span className={styles.profileLevel}>
+ <T>{location.level === "project" ? "Stored in Project" : "Stored in IDE"}</T>
+ </span>
</div>
<div className={styles.toolbar}>
diff --git a/src/features/templates/__tests__/editor.test.ts b/src/features/templates/__tests__/editor.test.ts
index e17c9e9b6..39d38ad63 100644
--- a/src/features/templates/__tests__/editor.test.ts
+++ b/src/features/templates/__tests__/editor.test.ts
@@ -123,7 +123,10 @@ describe("surround with", () => {
]);
// Expression surrounders need a selection within the line.
expect(req.items.some((i) => i.label === "(expr)")).toBe(false);
- req.onPick(req.items.find((i) => i.mnemonic === "9")!, "");
+ req.onPick(
+ req.items.find((i) => i.mnemonic === "9")!,
+ "",
+ );
await tick();
expect(v.state.doc.toString()).toContain("synchronized (this) {");
});
diff --git a/src/features/templates/__tests__/surrounders.test.ts b/src/features/templates/__tests__/surrounders.test.ts
index 4275fa6ee..8d694c8ff 100644
--- a/src/features/templates/__tests__/surrounders.test.ts
+++ b/src/features/templates/__tests__/surrounders.test.ts
@@ -16,7 +16,20 @@ describe("surround with entries", () => {
const java = surroundersFor("java", { lines: true, inline: false });
expect(java.length).toBeGreaterThan(10);
const entries = surroundEntries(java, []);
- expect(entries.slice(0, 12).map((e) => e.mnemonic)).toEqual(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A", "B"]);
+ expect(entries.slice(0, 12).map((e) => e.mnemonic)).toEqual([
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9",
+ "0",
+ "A",
+ "B",
+ ]);
});
it("gives templates the first abbreviation character not taken yet", () => {
diff --git a/src/features/templates/editor.ts b/src/features/templates/editor.ts
index dd8800161..3fa69ad91 100644
--- a/src/features/templates/editor.ts
+++ b/src/features/templates/editor.ts
@@ -129,7 +129,8 @@ export async function expandInto(
// The document may have changed while reading the clipboard.
if (view.state.doc !== state.doc) return;
snippet(exp.snippet)(view, null, from, to);
- if (view.state.field(fieldCompletion, false) !== undefined) view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
+ if (view.state.field(fieldCompletion, false) !== undefined)
+ view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
if (exp.completeFirst) setTimeout(() => startCompletion(view), 0);
}
@@ -298,7 +299,8 @@ const templateLookup = StateField.define<boolean>({
});
const endTemplateLookup = EditorView.updateListener.of((u) => {
- if (!u.state.field(templateLookup) || completionStatus(u.startState) === null || completionStatus(u.state) !== null) return;
+ if (!u.state.field(templateLookup) || completionStatus(u.startState) === null || completionStatus(u.state) !== null)
+ return;
queueMicrotask(() => {
if (u.view.state.field(templateLookup) && completionStatus(u.view.state) === null)
u.view.dispatch({ effects: setTemplateLookup.of(false) });
@@ -306,7 +308,11 @@ const endTemplateLookup = EditorView.updateListener.of((u) => {
});
/** Live templates applicable at `pos` as lookup items replacing the word before it. */
-function liveTemplateOptions(state: EditorState, pos: number, word: { from: number; text: string } | null): CompletionResult | null {
+function liveTemplateOptions(
+ state: EditorState,
+ pos: number,
+ word: { from: number; text: string } | null,
+): CompletionResult | null {
const list = templatesAt(state, pos).filter((t) => !usesSelection(t.body));
if (!list.length) return null;
return {
@@ -344,7 +350,10 @@ export function insertLiveTemplate(view: EditorView) {
* spans several lines, from the tree-sitter structure service; `null` when the
* statement is a single line, broken, or shares its lines with other code.
*/
-export function multiLineStatement(state: EditorState, r: StructuralRanges | null): { from: number; to: number } | null {
+export function multiLineStatement(
+ state: EditorState,
+ r: StructuralRanges | null,
+): { from: number; to: number } | null {
if (!r) return null;
const span = (n: NonNullable<StructuralRanges["statement"]>) => ({
from: posToOffset(state.doc, n.range.start),
@@ -364,7 +373,10 @@ export function multiLineStatement(state: EditorState, r: StructuralRanges | nul
}
/** The statement range Surround With uses for a caret (no selection), if the structure service knows it. */
-export async function surroundTarget(view: EditorView, ctx: EditorDocContext): Promise<{ from: number; to: number } | null> {
+export async function surroundTarget(
+ view: EditorView,
+ ctx: EditorDocContext,
+): Promise<{ from: number; to: number } | null> {
const state = view.state;
if (!state.selection.main.empty || state.selection.ranges.length > 1) return null;
try {
@@ -550,7 +562,8 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
EditorState.languageData.of(() => [
{
[EXTRA_COMPLETION_KEY]: templateCompletionSource,
- [EXCLUSIVE_COMPLETION_KEY]: (state: EditorState) => (state.field(templateLookup, false) ? templateLookupSource : null),
+ [EXCLUSIVE_COMPLETION_KEY]: (state: EditorState) =>
+ state.field(templateLookup, false) ? templateLookupSource : null,
},
]),
Prec.high(
diff --git a/src/features/templates/emmet/model.ts b/src/features/templates/emmet/model.ts
index 14af86da7..19e409a1b 100644
--- a/src/features/templates/emmet/model.ts
+++ b/src/features/templates/emmet/model.ts
@@ -214,7 +214,9 @@ export function updateTagEdits(tag: TagRange, abbreviation: string): TextEdit[]
}
const quote = (v: string) => (v.includes('"') ? `'${v}'` : `"${v}"`);
const attrText = attrs.map((a) => (a.value === null ? ` ${a.name}` : ` ${a.name}=${quote(a.value)}`)).join("");
- const edits: TextEdit[] = [{ from: tag.from, to: tag.to, insert: `<${name}${attrText}${tag.selfClosing ? " /" : ""}>` }];
+ const edits: TextEdit[] = [
+ { from: tag.from, to: tag.to, insert: `<${name}${attrText}${tag.selfClosing ? " /" : ""}>` },
+ ];
if (tag.close && name !== tag.name) edits.push({ from: tag.close.from, to: tag.close.to, insert: name });
return edits;
}
diff --git a/src/features/templates/files/NewFileDialog.tsx b/src/features/templates/files/NewFileDialog.tsx
index 9ffc767c6..60077ff1d 100644
--- a/src/features/templates/files/NewFileDialog.tsx
+++ b/src/features/templates/files/NewFileDialog.tsx
@@ -118,7 +118,12 @@ function NameStep({
initialKind?: string;
}) {
const [name, setName] = useState(initialName ?? "");
- const [kind, setKind] = useState(() => Math.max(0, template.kinds.findIndex((k) => k.id === initialKind)));
+ const [kind, setKind] = useState(() =>
+ Math.max(
+ 0,
+ template.kinds.findIndex((k) => k.id === initialKind),
+ ),
+ );
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [pkg, setPkg] = useState("");
diff --git a/src/features/templates/files/create.ts b/src/features/templates/files/create.ts
index 12f9122cb..4374bc3ed 100644
--- a/src/features/templates/files/create.ts
+++ b/src/features/templates/files/create.ts
@@ -134,7 +134,10 @@ export async function createFromTemplate(
const applied = await editorService().reformat?.(plan.path);
const after = view.state.doc.toString();
if (applied && after !== before)
- view.dispatch({ selection: EditorSelection.cursor(caretAfterReformat(before, at, after)), scrollIntoView: true });
+ view.dispatch({
+ selection: EditorSelection.cursor(caretAfterReformat(before, at, after)),
+ scrollIntoView: true,
+ });
}
await executeAction("file.save");
}
diff --git a/src/features/templates/files/model.ts b/src/features/templates/files/model.ts
index 547b81d54..591031b04 100644
--- a/src/features/templates/files/model.ts
+++ b/src/features/templates/files/model.ts
@@ -325,7 +325,7 @@ export function caretAfterReformat(before: string, caret: number, after: string)
return p;
}
let q = p;
- for (let n = 0; n < newlines; ) {
+ for (let n = 0; n < newlines;) {
const nl = after.indexOf("\n", q);
if (nl < 0 || !/^[ \t\r]*$/.test(after.slice(q, nl))) break;
q = nl + 1;
diff --git a/src/features/templates/live/surrounders.ts b/src/features/templates/live/surrounders.ts
index 2cdf60a72..c69c2980b 100644
--- a/src/features/templates/live/surrounders.ts
+++ b/src/features/templates/live/surrounders.ts
@@ -205,7 +205,10 @@ export interface SurroundEntry {
* IDEA's mnemonics: surrounders get 1–9, 0, then A–Z in order; each template
* the first character of its abbreviation not taken yet (none if all are).
*/
-export function surroundEntries(surrounders: readonly Surrounder[], templates: readonly LiveTemplate[]): SurroundEntry[] {
+export function surroundEntries(
+ surrounders: readonly Surrounder[],
+ templates: readonly LiveTemplate[],
+): SurroundEntry[] {
const used = new Set<string>();
const out: SurroundEntry[] = surrounders.map((s, i) => {
const mnemonic = i < 9 ? String(i + 1) : i === 9 ? "0" : String.fromCharCode(65 + i - 10);
diff --git a/src/features/templates/popup/Chooser.tsx b/src/features/templates/popup/Chooser.tsx
index c965ca0bd..274230747 100644
--- a/src/features/templates/popup/Chooser.tsx
+++ b/src/features/templates/popup/Chooser.tsx
@@ -59,7 +59,12 @@ function MnemonicLabel({ item }: { item: ChooserItem }) {
function ChooserPopup({ request }: { request: ChooserRequest }) {
const [filter, setFilter] = useState(request.filter ?? "");
const rows = useMemo(() => filterChooserItems(request.items, filter), [request.items, filter]);
- const [active, setActive] = useState(() => Math.max(0, rows.findIndex((r) => !isSection(r))));
+ const [active, setActive] = useState(() =>
+ Math.max(
+ 0,
+ rows.findIndex((r) => !isSection(r)),
+ ),
+ );
const current = Math.min(active, rows.length - 1);
const close = () => {
diff --git a/src/features/templates/settings/FileTemplatesPage.tsx b/src/features/templates/settings/FileTemplatesPage.tsx
index e67fc0567..a91859efa 100644
--- a/src/features/templates/settings/FileTemplatesPage.tsx
+++ b/src/features/templates/settings/FileTemplatesPage.tsx
@@ -256,13 +256,17 @@ function FileTemplateEditor({ template: t }: { template: FileTemplate }) {
aria-label={tx("Template body")}
onChange={(e) => updateKind({ body: e.target.value })}
/>
- <Checkbox checked={reformatsOnCreate(t)} onChange={(v) => update({ reformat: v })} label="Reformat according to style" />
+ <Checkbox
+ checked={reformatsOnCreate(t)}
+ onChange={(v) => update({ reformat: v })}
+ label="Reformat according to style"
+ />
<div className={styles.hint}>
- <T>Variables:</T> <code>$NAME$</code> <code>$PACKAGE$</code> <code>$FILE_NAME$</code> <code>$PROJECT_NAME$</code>{" "}
- <code>$USER$</code> <code>$DATE$</code> <code>$TIME$</code> <code>$YEAR$</code> <T>(or</T> <code>{"${NAME}"}</code>…);{" "}
- <code>$END$</code> <T>places the caret. A line with</T> <code>$PACKAGE$</code>{" "}
- <T>is omitted (with one following blank line) when there is no package.</T> <code>#parse("File Header")</code>{" "}
- <T>inserts a template from the Includes or Code tab.</T>
+ <T>Variables:</T> <code>$NAME$</code> <code>$PACKAGE$</code> <code>$FILE_NAME$</code>{" "}
+ <code>$PROJECT_NAME$</code> <code>$USER$</code> <code>$DATE$</code> <code>$TIME$</code> <code>$YEAR$</code>{" "}
+ <T>(or</T> <code>{"${NAME}"}</code>…); <code>$END$</code> <T>places the caret. A line with</T>{" "}
+ <code>$PACKAGE$</code> <T>is omitted (with one following blank line) when there is no package.</T>{" "}
+ <code>#parse("File Header")</code> <T>inserts a template from the Includes or Code tab.</T>
</div>
{isBuiltinFileTemplate(t.id) && isModifiedFileTemplate(t.id) && (
<div className={styles.buttons}>
diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx
index 524357ae2..b95c3bd35 100644
--- a/src/features/terminal/TerminalView.tsx
+++ b/src/features/terminal/TerminalView.tsx
@@ -224,7 +224,11 @@ function availableShells(): Promise<string[]> {
/** "zsh", or "bash (/opt/homebrew/bin/bash)" when several shells share a name. */
export function shellItems(paths: string[]): MenuItem[] {
- const name = (p: string) => p.split(/[\\/]/).pop()!.replace(/\.exe$/i, "");
+ const name = (p: string) =>
+ p
+ .split(/[\\/]/)
+ .pop()!
+ .replace(/\.exe$/i, "");
return paths.map((p) => ({
kind: "action",
action: "terminal.newPredefinedSession",
diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts
index c3e39ac69..75eddf2da 100644
--- a/src/features/terminal/index.ts
+++ b/src/features/terminal/index.ts
@@ -23,7 +23,12 @@ function focusActiveSoon() {
}
function shellName(path: string): string {
- return path.split(/[\\/]/).pop()!.replace(/\.exe$/i, "") || path;
+ return (
+ path
+ .split(/[\\/]/)
+ .pop()!
+ .replace(/\.exe$/i, "") || path
+ );
}
async function openNewTab(dir?: string) {
diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts
index 8de81d1e2..f4926af80 100644
--- a/src/features/terminal/session.ts
+++ b/src/features/terminal/session.ts
@@ -16,7 +16,14 @@ import { splitCommandLine } from "@/platform/commandLine";
import { useProject } from "@/platform/project";
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
import { editorPrefs } from "@/platform/editorSettings";
-import { readSearchDecorations, readTerminalTheme, remeasureWhenFontsLoad, terminalFont, type EditorFont, type TerminalFontSettings } from "./theme";
+import {
+ readSearchDecorations,
+ readTerminalTheme,
+ remeasureWhenFontsLoad,
+ terminalFont,
+ type EditorFont,
+ type TerminalFontSettings,
+} from "./theme";
export interface TerminalSearchOptions {
caseSensitive: boolean;
@@ -224,7 +231,8 @@ export class TerminalSession {
return true;
}),
this.term.registerLinkProvider({
- provideLinks: (y, callback) => callback(workflowSettings().terminal.highlightHyperlinks ? this.linksAt(y) : undefined),
+ provideLinks: (y, callback) =>
+ callback(workflowSettings().terminal.highlightHyperlinks ? this.linksAt(y) : undefined),
}),
this.term.onBell(() => {
if (workflowSettings().terminal.audibleBell) beep();
@@ -257,7 +265,13 @@ export class TerminalSession {
const o = this.term.options;
if (o.fontFamily !== font.family) {
o.fontFamily = font.family;
- if (this.opened) remeasureWhenFontsLoad(this.term, font, () => !this.disposed, () => this.scheduleFit());
+ if (this.opened)
+ remeasureWhenFontsLoad(
+ this.term,
+ font,
+ () => !this.disposed,
+ () => this.scheduleFit(),
+ );
}
if (o.fontSize !== font.size) o.fontSize = font.size;
if (o.lineHeight !== font.lineHeight) o.lineHeight = font.lineHeight;
@@ -311,7 +325,12 @@ export class TerminalSession {
// xterm's DOM renderer: the WebGL one rasterizes glyphs per background, so
// selected text rendered at a visibly different weight than the rest.
this.term.open(this.host);
- remeasureWhenFontsLoad(this.term, fontFor(workflowSettings().terminal), () => !this.disposed, () => this.scheduleFit());
+ remeasureWhenFontsLoad(
+ this.term,
+ fontFor(workflowSettings().terminal),
+ () => !this.disposed,
+ () => this.scheduleFit(),
+ );
this.term.textarea?.addEventListener("focus", () => this.opts.onFocus(this.key));
}
this.resizeObserver?.disconnect();
@@ -375,7 +394,15 @@ export class TerminalSession {
const args = custom ? custom.args : shellArgs;
const info = await call(
commands.termSpawn(
- { cwd: this.opts.cwd, shell: shell ?? null, args, env: { ...t.env }, cols, rows, shellIntegration: (!custom || !!custom.shell) && t.shellIntegration },
+ {
+ cwd: this.opts.cwd,
+ shell: shell ?? null,
+ args,
+ env: { ...t.env },
+ cols,
+ rows,
+ shellIntegration: (!custom || !!custom.shell) && t.shellIntegration,
+ },
channel,
),
);
@@ -492,9 +519,15 @@ export class TerminalSession {
return false;
}
this.searchDecorations ??= readSearchDecorations();
- const options: ISearchOptions = { ...opts, incremental: direction === "next" && incremental, decorations: this.searchDecorations };
+ const options: ISearchOptions = {
+ ...opts,
+ incremental: direction === "next" && incremental,
+ decorations: this.searchDecorations,
+ };
try {
- return direction === "next" ? this.searchAddon.findNext(query, options) : this.searchAddon.findPrevious(query, options);
+ return direction === "next"
+ ? this.searchAddon.findNext(query, options)
+ : this.searchAddon.findPrevious(query, options);
} catch {
// Invalid regular expression.
this.clearSearch();
diff --git a/src/features/terminal/terminal.test.ts b/src/features/terminal/terminal.test.ts
index a643c06e9..b15fbd96d 100644
--- a/src/features/terminal/terminal.test.ts
+++ b/src/features/terminal/terminal.test.ts
@@ -4,7 +4,16 @@ import { isAllowedIdeShortcut, terminalKeyAction } from "./keys";
import { matchCounter } from "./FindBar";
import { buildSearchDecorations } from "./theme";
import { findTerminalLinks, resolvePath, trimUrl } from "./links";
-import { layoutPanes, nextTabName, removeFromLayout, splitLayout, tabFullTitle, tabTitle, trimMiddle, type TerminalTab } from "./store";
+import {
+ layoutPanes,
+ nextTabName,
+ removeFromLayout,
+ splitLayout,
+ tabFullTitle,
+ tabTitle,
+ trimMiddle,
+ type TerminalTab,
+} from "./store";
import type { SessionSnapshot } from "./session";
import { buildTheme, mix, parseColor, terminalFont, toHex } from "./theme";
@@ -115,7 +124,10 @@ describe("terminal keys", () => {
expect(terminalKeyAction(key({ key: "T", code: "KeyT", ctrlKey: true, shiftKey: true }), false)).toEqual({
kind: "pass",
});
- expect(terminalKeyAction(key({ key: "t", code: "KeyT", ctrlKey: true }), false)).toEqual({ kind: "send", data: "\x14" });
+ expect(terminalKeyAction(key({ key: "t", code: "KeyT", ctrlKey: true }), false)).toEqual({
+ kind: "send",
+ data: "\x14",
+ });
});
it("implements macOS conveniences", () => {
@@ -211,18 +223,55 @@ describe("split layout", () => {
describe("terminalFont", () => {
const BASE = '"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, Menlo, monospace';
- const t = { useEditorFont: true, fontFamily: "JetBrains Mono", fontSize: 10, lineHeight: 1, fallbackFontFamily: "", columnWidth: 1 };
+ const t = {
+ useEditorFont: true,
+ fontFamily: "JetBrains Mono",
+ fontSize: 10,
+ lineHeight: 1,
+ fallbackFontFamily: "",
+ columnWidth: 1,
+ };
const editor = { fontFamily: "JetBrains Mono", fontSize: 10, lineHeight: 12 };
const head = (family: string) => family.slice(0, family.indexOf('"Symbols Nerd Font Mono"'));
it.each([
// #26: "Use editor font" with the default family must reach the bundled face, not the system monospace.
- ["editor font, default family", t, editor, `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `],
- ["editor font, no editor settings", t, undefined, `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `],
- ["editor font, custom family", t, { ...editor, fontFamily: "Fira Code" }, `"Fira Code", ${BASE.replace(", monospace", "")}, `],
- ["editor font, editor fallback", t, { ...editor, fallbackFont: "PingFang SC" }, `"JetBrains Mono Variable", "JetBrains Mono", "PingFang SC", ${BASE.replace(", monospace", "")}, `],
- ["own font, default family", { ...t, useEditorFont: false }, editor, `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `],
- ["own font, custom + fallback", { ...t, useEditorFont: false, fontFamily: "Hack", fallbackFontFamily: "PingFang SC" }, editor, `"Hack", "PingFang SC", ${BASE.replace(", monospace", "")}, `],
+ [
+ "editor font, default family",
+ t,
+ editor,
+ `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
+ ],
+ [
+ "editor font, no editor settings",
+ t,
+ undefined,
+ `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
+ ],
+ [
+ "editor font, custom family",
+ t,
+ { ...editor, fontFamily: "Fira Code" },
+ `"Fira Code", ${BASE.replace(", monospace", "")}, `,
+ ],
+ [
+ "editor font, editor fallback",
+ t,
+ { ...editor, fallbackFont: "PingFang SC" },
+ `"JetBrains Mono Variable", "JetBrains Mono", "PingFang SC", ${BASE.replace(", monospace", "")}, `,
+ ],
+ [
+ "own font, default family",
+ { ...t, useEditorFont: false },
+ editor,
+ `"JetBrains Mono Variable", "JetBrains Mono", ${BASE.replace(", monospace", "")}, `,
+ ],
+ [
+ "own font, custom + fallback",
+ { ...t, useEditorFont: false, fontFamily: "Hack", fallbackFontFamily: "PingFang SC" },
+ editor,
+ `"Hack", "PingFang SC", ${BASE.replace(", monospace", "")}, `,
+ ],
])("%s resolves through the bundled stack", (_, settings, ed, expected) => {
const font = terminalFont(settings, ed, BASE);
expect(head(font.family)).toBe(expected);
@@ -231,7 +280,11 @@ describe("terminalFont", () => {
});
it("prefers the terminal's fallback over the editor's", () => {
- const font = terminalFont({ ...t, fallbackFontFamily: "Sarasa Mono SC" }, { ...editor, fallbackFont: "PingFang SC" }, BASE);
+ const font = terminalFont(
+ { ...t, fallbackFontFamily: "Sarasa Mono SC" },
+ { ...editor, fallbackFont: "PingFang SC" },
+ BASE,
+ );
expect(font.family).toContain('"Sarasa Mono SC"');
expect(font.family).not.toContain("PingFang SC");
});
diff --git a/src/features/terminal/theme.ts b/src/features/terminal/theme.ts
index 0f8544ef0..aaaa79ca7 100644
--- a/src/features/terminal/theme.ts
+++ b/src/features/terminal/theme.ts
@@ -202,7 +202,11 @@ function cssNumber(name: string): number {
* The column width (a multiple of the cell width) becomes xterm's letter spacing,
* from the ≈ 0.6 em advance of monospace fonts.
*/
-export function terminalFont(t: TerminalFontSettings, editor: EditorFont | undefined, base = monoStack()): TerminalFont {
+export function terminalFont(
+ t: TerminalFontSettings,
+ editor: EditorFont | undefined,
+ base = monoStack(),
+): TerminalFont {
let family: string, fallback: string, size: number, lineHeight: number;
let weight = 400,
boldWeight = 700;
@@ -222,7 +226,14 @@ export function terminalFont(t: TerminalFontSettings, editor: EditorFont | undef
boldWeight = fontWeightOf(editor?.boldFontWeight, boldWeight);
}
const letterSpacing = Math.round((t.columnWidth - 1) * size * 0.6 * 10) / 10;
- return { family: withNerdFonts(monoFontFamily(family, fallback, base)), size, lineHeight, letterSpacing, weight, boldWeight };
+ return {
+ family: withNerdFonts(monoFontFamily(family, fallback, base)),
+ size,
+ lineHeight,
+ letterSpacing,
+ weight,
+ boldWeight,
+ };
}
/**
diff --git a/src/features/todo/TodoView.tsx b/src/features/todo/TodoView.tsx
index 57396ae2f..5d7895b9b 100644
--- a/src/features/todo/TodoView.tsx
+++ b/src/features/todo/TodoView.tsx
@@ -185,7 +185,9 @@ function useScopeQuery() {
const scope = useTodoView((s) => s.scope);
const custom = useCustomScopeList();
// Open tabs change with the active editor (or its count): re-read them then.
- const openKey = useEditorRegistry((s) => (scope === "openFiles" ? `${s.editors.size}:${s.active?.ctx.path ?? ""}` : ""));
+ const openKey = useEditorRegistry((s) =>
+ scope === "openFiles" ? `${s.editors.size}:${s.active?.ctx.path ?? ""}` : "",
+ );
return useMemo(() => {
const search = todoSearchScope(scope, custom, scope === "openFiles" ? openEditorPaths() : []);
return { search, key: JSON.stringify(search) };
@@ -225,7 +227,11 @@ function ChangelistBar() {
aria-label="Changelist"
className={styles.scopeSelect}
value={value}
- options={lists.map((l) => ({ value: l.id, label: l.name, detail: l.files.length === 1 ? tx`${l.files.length} file` : tx`${l.files.length} files` }))}
+ options={lists.map((l) => ({
+ value: l.id,
+ label: l.name,
+ detail: l.files.length === 1 ? tx`${l.files.length} file` : tx`${l.files.length} files`,
+ }))}
onChange={(id) => useTodoView.setState({ changelist: id })}
/>
</div>
@@ -245,12 +251,20 @@ function ScopeBar() {
<span className={styles.muted}>
<T>Scope:</T>
</span>
- <Select<TodoScope> aria-label="Scope" className={styles.scopeSelect} value={scope} options={options} onChange={setScope} />
+ <Select<TodoScope>
+ aria-label="Scope"
+ className={styles.scopeSelect}
+ value={scope}
+ options={options}
+ onChange={setScope}
+ />
<IconButton
icon="more-horizontal"
size="small"
title="Edit Scopes…"
- onClick={() => void executeAction(EDIT_SCOPES_ACTION, scope.startsWith("custom:") ? { select: scope.slice(7) } : undefined)}
+ onClick={() =>
+ void executeAction(EDIT_SCOPES_ACTION, scope.startsWith("custom:") ? { select: scope.slice(7) } : undefined)
+ }
/>
</div>
);
diff --git a/src/features/todo/highlight.ts b/src/features/todo/highlight.ts
index d2992f90c..7fdafd962 100644
--- a/src/features/todo/highlight.ts
+++ b/src/features/todo/highlight.ts
@@ -83,7 +83,10 @@ export function todoDecorations(view: EditorView, settings: TodoSettings): Decor
const theme = EditorView.baseTheme({
".cm-openidea-todo, .cm-openidea-todo *": { color: "var(--todo-color) !important", fontStyle: "italic" },
- ".cm-openidea-todo-keyword, .cm-openidea-todo-keyword *": { fontWeight: "var(--fw-code-bold, 700)", fontStyle: "normal" },
+ ".cm-openidea-todo-keyword, .cm-openidea-todo-keyword *": {
+ fontWeight: "var(--fw-code-bold, 700)",
+ fontStyle: "normal",
+ },
});
export function todoEditorExtension(ctx: EditorDocContext): Extension {
diff --git a/src/features/todo/store.ts b/src/features/todo/store.ts
index 68d449eb2..ca7dc7e02 100644
--- a/src/features/todo/store.ts
+++ b/src/features/todo/store.ts
@@ -226,7 +226,11 @@ export async function scanScope(key: string, scope: SearchScope | null): Promise
useTodos.setState({ scoped: new Map(), scopedKey: key, scopedScanning: false });
return;
}
- useTodos.setState((s) => ({ scopedScanning: true, scoped: s.scopedKey === key ? s.scoped : new Map(), scopedKey: key }));
+ useTodos.setState((s) => ({
+ scopedScanning: true,
+ scoped: s.scopedKey === key ? s.scoped : new Map(),
+ scopedKey: key,
+ }));
const found = new Map<string, TodoItem[]>();
try {
const r = await run(
@@ -281,7 +285,14 @@ export function installTodoIndex(): () => void {
const r = s.project?.root ?? null;
if (r === root) return;
root = r;
- useTodos.setState({ scanned: new Map(), live: new Map(), scannedOnce: false, error: null, scoped: new Map(), scopedKey: null });
+ useTodos.setState({
+ scanned: new Map(),
+ live: new Map(),
+ scannedOnce: false,
+ error: null,
+ scoped: new Map(),
+ scopedKey: null,
+ });
if (r) start();
});
let settings = useTodoSettings.getState();
diff --git a/src/features/todo/todo.test.ts b/src/features/todo/todo.test.ts
index 9eba2ff60..bca36ce9d 100644
--- a/src/features/todo/todo.test.ts
+++ b/src/features/todo/todo.test.ts
@@ -145,7 +145,12 @@ describe("scope based and changes tabs", () => {
it("keeps only files of the chosen change list (the active one by default)", () => {
const lists = [
- { id: "default", name: "Changes", active: true, files: [{ path: "/p/a.ts" }, { path: "/p/new.ts" }, { path: "/p/gone.ts", deleted: true }] },
+ {
+ id: "default",
+ name: "Changes",
+ active: true,
+ files: [{ path: "/p/a.ts" }, { path: "/p/new.ts" }, { path: "/p/gone.ts", deleted: true }],
+ },
{ id: "ui", name: "UI", active: false, files: [{ path: "/p/b.ts" }] },
];
const changed = changedPaths(lists);
diff --git a/src/features/tools/missing.ts b/src/features/tools/missing.ts
index f6b823d4e..e5af938e9 100644
--- a/src/features/tools/missing.ts
+++ b/src/features/tools/missing.ts
@@ -19,7 +19,13 @@ export async function promptInstall(name: string): Promise<boolean> {
// An installed alternative (typescript-language-server for vtsls) already serves these files.
const served = useTools
.getState()
- .tools.some((t) => t.name !== name && t.kind === tool.kind && t.status !== "missing" && t.languages.some((l) => tool.languages.includes(l)));
+ .tools.some(
+ (t) =>
+ t.name !== name &&
+ t.kind === tool.kind &&
+ t.status !== "missing" &&
+ t.languages.some((l) => tool.languages.includes(l)),
+ );
if (served) return false;
const key = missingKey(name);
const langs = tool.languages.length ? tool.languages.join(", ") : "these files";
diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx
index 7535a0c23..4e21ad2a1 100644
--- a/src/features/vcs/DiffEditor.tsx
+++ b/src/features/vcs/DiffEditor.tsx
@@ -201,10 +201,15 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}, []);
// A HEAD ↔ working file diff of a tracked change: blocks can be left out of the commit.
- const includable = useVcs((s) => {
- const fs = s.status.find((f) => stripSlash(f.path) === path);
- return !!fs && groupOf(fs) === "changes" && effectiveKind(fs) === "modified";
- }) && left.type === "rev" && left.rev === "HEAD" && !left.path && isWorktree(right);
+ const includable =
+ useVcs((s) => {
+ const fs = s.status.find((f) => stripSlash(f.path) === path);
+ return !!fs && groupOf(fs) === "changes" && effectiveKind(fs) === "modified";
+ }) &&
+ left.type === "rev" &&
+ left.rev === "HEAD" &&
+ !left.path &&
+ isWorktree(right);
const editableA = !!attached?.a && !attached.a.readOnly;
const editableB = !!attached?.b && !attached.b.readOnly;
const ready = !!attached && !!statics && lang !== null;
@@ -241,7 +246,12 @@ export function DiffEditor({ input }: { input: EditorInput }) {
lang,
att?.extension ?? [],
editable ? [editableExtensions(), embeddedEditorExtensions(path)] : [],
- notes ? diffAnnotations((data.annotations ?? []).filter((n) => n.side === notes), styles) : [],
+ notes
+ ? diffAnnotations(
+ (data.annotations ?? []).filter((n) => n.side === notes),
+ styles,
+ )
+ : [],
];
let views: Views;
if (opts.mode === "split") {
@@ -314,7 +324,21 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}
viewsRef.current = views;
requestAnimationFrame(updateChunkInfo);
- }, [attached, statics, lang, opts.mode, opts.collapse, opts.ignore, opts.highlight, editableA, editableB, updateChunkInfo, data.annotations, includable, path]);
+ }, [
+ attached,
+ statics,
+ lang,
+ opts.mode,
+ opts.collapse,
+ opts.ignore,
+ opts.highlight,
+ editableA,
+ editableB,
+ updateChunkInfo,
+ data.annotations,
+ includable,
+ path,
+ ]);
useEffect(
() => () => {
@@ -498,7 +522,8 @@ export function DiffEditor({ input }: { input: EditorInput }) {
[],
);
- const identical = ready && chunkInfo.count === 0 && (attached?.a?.text() ?? statics?.a) === (attached?.b?.text() ?? statics?.b);
+ const identical =
+ ready && chunkInfo.count === 0 && (attached?.a?.text() ?? statics?.a) === (attached?.b?.text() ?? statics?.b);
// Staging applies to local changes against HEAD / the index only.
const canStage = editableB && isWorktree(right) && left.type === "rev" && !!useVcs.getState().root;
const hasSource = !!source;
@@ -518,10 +543,28 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}}
>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Diff")}>
- <IconButton icon="arrow-up" title="Previous Difference" shortcut={shortcutLabel("diff.prevDifference")} size="small" onClick={() => step(-1)} />
- <IconButton icon="arrow-down" title="Next Difference" shortcut={shortcutLabel("diff.nextDifference")} size="small" onClick={() => step(1)} />
+ <IconButton
+ icon="arrow-up"
+ title="Previous Difference"
+ shortcut={shortcutLabel("diff.prevDifference")}
+ size="small"
+ onClick={() => step(-1)}
+ />
+ <IconButton
+ icon="arrow-down"
+ title="Next Difference"
+ shortcut={shortcutLabel("diff.nextDifference")}
+ size="small"
+ onClick={() => step(1)}
+ />
{hasSource && (
- <IconButton icon="edit" title="Jump to Source" shortcut={shortcutLabel("diff.jumpToSource")} size="small" onClick={jumpToSource} />
+ <IconButton
+ icon="edit"
+ title="Jump to Source"
+ shortcut={shortcutLabel("diff.jumpToSource")}
+ size="small"
+ onClick={jumpToSource}
+ />
)}
<span className={styles.sep} />
<IconButton
@@ -572,7 +615,13 @@ export function DiffEditor({ input }: { input: EditorInput }) {
{editableB && (
<>
<span className={styles.sep} />
- <IconButton icon="revert" title="Revert Change" size="small" disabled={!chunkInfo.count} onClick={revertChunk} />
+ <IconButton
+ icon="revert"
+ title="Revert Change"
+ size="small"
+ disabled={!chunkInfo.count}
+ onClick={revertChunk}
+ />
{canStage && (
<IconButton
icon="plus"
@@ -604,9 +653,11 @@ export function DiffEditor({ input }: { input: EditorInput }) {
<div className={styles.labels}>
<span className={styles.label} title={sideLabel(left)}>
{sideLabel(left)}
- {editableA && <span className={styles.badge}>
+ {editableA && (
+ <span className={styles.badge}>
<T>editable</T>
- </span>}
+ </span>
+ )}
</span>
<span className={styles.label} title={sideLabel(right)}>
{sideLabel(right)}
diff --git a/src/features/vcs/RevisionChooser.tsx b/src/features/vcs/RevisionChooser.tsx
index d0074cf05..6228227a6 100644
--- a/src/features/vcs/RevisionChooser.tsx
+++ b/src/features/vcs/RevisionChooser.tsx
@@ -61,7 +61,11 @@ function Chooser({
const items = useMemo(() => {
const all: Item[] = [
{ rev: "HEAD", detail: "Last commit", matches: null },
- ...sortLocal(branches).map((b) => ({ rev: b.name, detail: b.current ? "current branch" : "local", matches: null })),
+ ...sortLocal(branches).map((b) => ({
+ rev: b.name,
+ detail: b.current ? "current branch" : "local",
+ matches: null,
+ })),
...sortRemote(branches).map((b) => ({ rev: b.name, detail: "remote", matches: null })),
...tags.map((t) => ({ rev: t, detail: "tag", matches: null })),
];
@@ -120,7 +124,12 @@ function Chooser({
renderItem={(i) => (
<span className={styles.fileRow} style={{ flex: 1, padding: 0 }}>
<Icon name={i.detail === "revision" ? "commit" : i.detail === "tag" ? "tag" : "branch"} size={14} />
- <HighlightedText className={`${styles.fileName} ${styles.mono}`} text={i.rev} indices={i.matches} tone="accent" />
+ <HighlightedText
+ className={`${styles.fileName} ${styles.mono}`}
+ text={i.rev}
+ indices={i.matches}
+ tone="accent"
+ />
<span className={styles.fileDir}>{i.detail}</span>
</span>
)}
diff --git a/src/features/vcs/__tests__/changelists.test.ts b/src/features/vcs/__tests__/changelists.test.ts
index 439247294..9a46f76b6 100644
--- a/src/features/vcs/__tests__/changelists.test.ts
+++ b/src/features/vcs/__tests__/changelists.test.ts
@@ -42,9 +42,17 @@ const shape = (nodes: ChangeNode[], depth = 0): string[] =>
describe("change list model", () => {
it("publishes each list with its files (unversioned left out, deletions marked)", () => {
const { state, feature } = twoLists();
- const lists = localChangelists([...status, fs("gone.ts", null, "deleted"), fs("c.ts", "conflicted", null)], "/r", state);
+ const lists = localChangelists(
+ [...status, fs("gone.ts", null, "deleted"), fs("c.ts", "conflicted", null)],
+ "/r",
+ state,
+ );
expect(lists.map((l) => [l.id, l.active, l.files])).toEqual([
- ["default", true, [{ path: "/r/src/a.ts" }, { path: "/r/README.md" }, { path: "/r/gone.ts", deleted: true }, { path: "/r/c.ts" }]],
+ [
+ "default",
+ true,
+ [{ path: "/r/src/a.ts" }, { path: "/r/README.md" }, { path: "/r/gone.ts", deleted: true }, { path: "/r/c.ts" }],
+ ],
[feature, false, [{ path: "/r/src/b.ts" }]],
]);
});
diff --git a/src/features/vcs/__tests__/conflicts.test.ts b/src/features/vcs/__tests__/conflicts.test.ts
index cf41d834c..13c693723 100644
--- a/src/features/vcs/__tests__/conflicts.test.ts
+++ b/src/features/vcs/__tests__/conflicts.test.ts
@@ -23,7 +23,13 @@ describe("parseConflicts", () => {
const blocks = parseConflicts(text);
expect(blocks).toHaveLength(2);
const [a, b] = blocks;
- expect(a).toMatchObject({ ours: "ours 1\nours 2\n", base: "base\n", theirs: "theirs\n", oursLabel: "HEAD", theirsLabel: "feature" });
+ expect(a).toMatchObject({
+ ours: "ours 1\nours 2\n",
+ base: "base\n",
+ theirs: "theirs\n",
+ oursLabel: "HEAD",
+ theirsLabel: "feature",
+ });
expect(text.slice(a!.from, a!.to)).toMatch(/^<<<<<<< HEAD\n[\s\S]*>>>>>>> feature\n$/);
expect(b).toMatchObject({ ours: "", base: null, theirs: "only theirs\n" });
expect(blockAt(blocks, text.indexOf("theirs\n"))).toBe(a);
diff --git a/src/features/vcs/__tests__/decorations.test.ts b/src/features/vcs/__tests__/decorations.test.ts
index f269d407e..f11370e1b 100644
--- a/src/features/vcs/__tests__/decorations.test.ts
+++ b/src/features/vcs/__tests__/decorations.test.ts
@@ -3,7 +3,12 @@ import type { FileStatus } from "@/bindings";
import { getFileDecoration, setFileDecorations } from "@/workbench/contributions";
import { effectiveKind, stashLabel, statusDecorations } from "../model";
-const fs = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"], renamedFrom: string | null = null): FileStatus => ({
+const fs = (
+ rel: string,
+ staged: FileStatus["staged"],
+ unstaged: FileStatus["unstaged"],
+ renamedFrom: string | null = null,
+): FileStatus => ({
path: `/repo/${rel}`,
relPath: rel,
staged,
@@ -66,7 +71,10 @@ describe("statusDecorations", () => {
describe("stashLabel", () => {
it("splits git's stash subjects into branch and message", () => {
expect(stashLabel("On main: wip make")).toEqual({ branch: "main", text: "wip make" });
- expect(stashLabel("WIP on feature/x: 1a2b3c4 Add thing")).toEqual({ branch: "feature/x", text: "1a2b3c4 Add thing" });
+ expect(stashLabel("WIP on feature/x: 1a2b3c4 Add thing")).toEqual({
+ branch: "feature/x",
+ text: "1a2b3c4 Add thing",
+ });
expect(stashLabel("custom subject")).toEqual({ branch: null, text: "custom subject" });
});
});
diff --git a/src/features/vcs/__tests__/gitOps.test.ts b/src/features/vcs/__tests__/gitOps.test.ts
index b27ee3cd0..8dd435daf 100644
--- a/src/features/vcs/__tests__/gitOps.test.ts
+++ b/src/features/vcs/__tests__/gitOps.test.ts
@@ -215,7 +215,10 @@ describe("interactive rebase plan", () => {
describe("log ordering and staleness", () => {
it("orders commits by their position in the log, not by date", () => {
const log = [commit("new"), commit("mid"), commit("old")];
- const picked = [{ ...log[2]!, timeMs: 3 }, { ...log[0]!, timeMs: 1 }];
+ const picked = [
+ { ...log[2]!, timeMs: 3 },
+ { ...log[0]!, timeMs: 1 },
+ ];
expect(newestFirst(picked, log).map((c) => c.id)).toEqual(["new", "old"]);
expect(newestFirst([commit("a"), { ...commit("b"), timeMs: 5 }], []).map((c) => c.id)).toEqual(["b", "a"]);
});
@@ -223,9 +226,9 @@ describe("log ordering and staleness", () => {
it("changes the refs signature when HEAD or any branch tip moves", () => {
const base = refsSignature(info(), [branch("main", "c3"), branch("origin/main", "c3", true)]);
expect(refsSignature(info(), [branch("origin/main", "c3", true), branch("main", "c3")])).toBe(base);
- expect(refsSignature(info({ headCommit: "c2" }), [branch("main", "c2"), branch("origin/main", "c3", true)])).not.toBe(
- base,
- );
+ expect(
+ refsSignature(info({ headCommit: "c2" }), [branch("main", "c2"), branch("origin/main", "c3", true)]),
+ ).not.toBe(base);
expect(refsSignature(info(), [branch("main", "c3"), branch("origin/main", "c4", true)])).not.toBe(base);
expect(refsSignature(info(), [branch("main", "c3")])).not.toBe(base);
});
diff --git a/src/features/vcs/__tests__/hunks.test.ts b/src/features/vcs/__tests__/hunks.test.ts
index be2185632..dca3bad23 100644
--- a/src/features/vcs/__tests__/hunks.test.ts
+++ b/src/features/vcs/__tests__/hunks.test.ts
@@ -4,7 +4,14 @@ import type { LineHunk } from "@/bindings";
import { applyRollback, hunkAtLine, hunkKeys, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
import { editorHunks, hunkAtPos, hunkField, hunksInSelection, setHunksEffect } from "../gutter";
-const h = (kind: LineHunk["kind"], start: number, lines: number, oldStart: number, oldLines: number, oldText: string): LineHunk => ({
+const h = (
+ kind: LineHunk["kind"],
+ start: number,
+ lines: number,
+ oldStart: number,
+ oldLines: number,
+ oldText: string,
+): LineHunk => ({
kind,
start,
lines,
@@ -117,7 +124,9 @@ describe("change lane clicks", () => {
view.dispatch({ effects: setHunksEffect.of([h("modified", 0, 1, 0, 1, "b\n")]) });
const lane = view.dom.querySelector(".cm-openidea-lane")!;
expect(view.contentDOM.contains(lane)).toBe(false);
- lane.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 0, clientY: 0 }));
+ lane.dispatchEvent(
+ new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 0, clientY: 0 }),
+ );
expect(opened).toEqual(["modified:/p/f.txt"]);
view.destroy();
setHunkPopupHooks(null);
diff --git a/src/features/vcs/__tests__/workflow.test.ts b/src/features/vcs/__tests__/workflow.test.ts
index 40d0cca89..7a3b6a5dd 100644
--- a/src/features/vcs/__tests__/workflow.test.ts
+++ b/src/features/vcs/__tests__/workflow.test.ts
@@ -55,7 +55,9 @@ describe("git settings helpers", () => {
});
it("propagates folder colours only when enabled", () => {
- const status = [{ path: "/p/src/a.ts", relPath: "src/a.ts", staged: null, unstaged: "modified" as const, renamedFrom: null }];
+ const status = [
+ { path: "/p/src/a.ts", relPath: "src/a.ts", staged: null, unstaged: "modified" as const, renamedFrom: null },
+ ];
expect(statusDecorations(status).get("/p/src/a.ts")?.propagate).toBe(true);
expect(statusDecorations(status, false).get("/p/src/a.ts")?.propagate).toBeUndefined();
});
diff --git a/src/features/vcs/blame.ts b/src/features/vcs/blame.ts
index a3507e3a8..6430fd649 100644
--- a/src/features/vcs/blame.ts
+++ b/src/features/vcs/blame.ts
@@ -173,7 +173,11 @@ function blameExtension(lines: BlameLine[], path: string): Extension {
showContextMenu(event as MouseEvent, [
...(l && !isUncommitted(l)
? [
- { label: "Show Commit in Git Log", icon: "commit", run: () => void executeAction("vcs.showCommit", l.commit) },
+ {
+ label: "Show Commit in Git Log",
+ icon: "commit",
+ run: () => void executeAction("vcs.showCommit", l.commit),
+ },
{
label: "Copy Revision Number",
icon: "copy",
diff --git a/src/features/vcs/changelists.ts b/src/features/vcs/changelists.ts
index b61193f2c..b0e57e4a3 100644
--- a/src/features/vcs/changelists.ts
+++ b/src/features/vcs/changelists.ts
@@ -87,7 +87,9 @@ export function setActiveList(state: ChangelistState, id: string): ChangelistSta
/** Deletes a list (never the active one); its files move to the active list. */
export function removeList(state: ChangelistState, id: string): ChangelistState {
if (id === state.active || !state.lists.some((l) => l.id === id)) return state;
- const files = Object.fromEntries(Object.entries(state.files ?? {}).map(([rel, l]) => [rel, l === id ? state.active : l]));
+ const files = Object.fromEntries(
+ Object.entries(state.files ?? {}).map(([rel, l]) => [rel, l === id ? state.active : l]),
+ );
return { ...state, lists: state.lists.filter((l) => l.id !== id), files };
}
@@ -162,8 +164,17 @@ export function changedRels(status: readonly FileStatus[], root: string): string
}
/** The lists with their files, for the `useLocalChanges` service (conflicted files stay in their list). */
-export function localChangelists(status: readonly FileStatus[], root: string, state: ChangelistState): LocalChangelist[] {
- const lists = state.lists.map((l): LocalChangelist => ({ id: l.id, name: l.name, active: l.id === state.active, files: [] }));
+export function localChangelists(
+ status: readonly FileStatus[],
+ root: string,
+ state: ChangelistState,
+): LocalChangelist[] {
+ const lists = state.lists.map((l): LocalChangelist => ({
+ id: l.id,
+ name: l.name,
+ active: l.id === state.active,
+ files: [],
+ }));
const byId = new Map(lists.map((l) => [l.id, l]));
for (const f of status) {
const group = groupOf(f);
diff --git a/src/features/vcs/changes.ts b/src/features/vcs/changes.ts
index 07d61eea9..9bf342bb7 100644
--- a/src/features/vcs/changes.ts
+++ b/src/features/vcs/changes.ts
@@ -49,7 +49,11 @@ export function groupOf(fs: FileStatus): GroupId | null {
export function isPartiallyStaged(fs: FileStatus): boolean {
return (
- !!fs.staged && !!fs.unstaged && fs.unstaged !== "untracked" && fs.unstaged !== "conflicted" && fs.staged !== "conflicted"
+ !!fs.staged &&
+ !!fs.unstaged &&
+ fs.unstaged !== "untracked" &&
+ fs.unstaged !== "conflicted" &&
+ fs.staged !== "conflicted"
);
}
@@ -73,7 +77,11 @@ export function aggregateCheck(files: readonly FileStatus[], checks: ReadonlyMap
if (c !== "none") on++;
if (c === "staged" || c === "hunks") partial = true;
}
- return { checked: on > 0 && on === files.length && !partial, indeterminate: (on > 0 && on < files.length) || partial, on };
+ return {
+ checked: on > 0 && on === files.length && !partial,
+ indeterminate: (on > 0 && on < files.length) || partial,
+ on,
+ };
}
const KIND_ORDER: GroupId[] = ["conflicts", "changes", "unversioned"];
diff --git a/src/features/vcs/commitChecks.tsx b/src/features/vcs/commitChecks.tsx
index 6bd91621a..8f3ebc0ca 100644
--- a/src/features/vcs/commitChecks.tsx
+++ b/src/features/vcs/commitChecks.tsx
@@ -314,7 +314,9 @@ export async function runCommitChecks(files: readonly CommitCandidate[], amend:
}
if (git.warnCrlf) {
- const autocrlf = (await call(commands.vcsConfigGet(currentRepo(), "core.autocrlf")).catch(() => null))?.toLowerCase();
+ const autocrlf = (
+ await call(commands.vcsConfigGet(currentRepo(), "core.autocrlf")).catch(() => null)
+ )?.toLowerCase();
if (autocrlf !== "true" && autocrlf !== "input") {
const crlf: string[] = [];
for (const p of existing) {
diff --git a/src/features/vcs/compare.tsx b/src/features/vcs/compare.tsx
index 283b6c9f4..cafaf8e9c 100644
--- a/src/features/vcs/compare.tsx
+++ b/src/features/vcs/compare.tsx
@@ -47,7 +47,9 @@ export function clipboardDiffData(path: string, clipboard: string, selection: st
path,
title: selection ? tx`Clipboard ↔ ${baseName(path)} (selection)` : tx`Clipboard ↔ ${baseName(path)}`,
left: { type: "text", text: clipboard, label: "Clipboard" },
- right: selection ? { type: "text", text: selection, label: "Selection" } : { type: "worktree", label: displayPath(path) },
+ right: selection
+ ? { type: "text", text: selection, label: "Selection" }
+ : { type: "worktree", label: displayPath(path) },
};
}
diff --git a/src/features/vcs/diffAnnotations.ts b/src/features/vcs/diffAnnotations.ts
index b516bc366..273fd12d8 100644
--- a/src/features/vcs/diffAnnotations.ts
+++ b/src/features/vcs/diffAnnotations.ts
@@ -57,7 +57,11 @@ function build(state: EditorState, notes: readonly DiffAnnotation[], cls: Classe
}
const ranges = [...byLine.entries()]
.sort((a, b) => a[0] - b[0])
- .map(([line, list]) => Decoration.widget({ widget: new NotesWidget(list, cls), block: true, side: 1 }).range(state.doc.line(line + 1).to));
+ .map(([line, list]) =>
+ Decoration.widget({ widget: new NotesWidget(list, cls), block: true, side: 1 }).range(
+ state.doc.line(line + 1).to,
+ ),
+ );
return Decoration.set(ranges);
}
diff --git a/src/features/vcs/diffControls.ts b/src/features/vcs/diffControls.ts
index c229f4ec4..df9788903 100644
--- a/src/features/vcs/diffControls.ts
+++ b/src/features/vcs/diffControls.ts
@@ -40,7 +40,10 @@ function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void
* `renderRevertControl` for MergeView: one or two arrows per chunk. `toB`:
* the right side is editable (">>"); `toA`: the left side is (">>" / "<<").
*/
-export function arrowControls(getView: () => MergeView | null, sides: { toA: boolean; toB: boolean }): () => HTMLElement {
+export function arrowControls(
+ getView: () => MergeView | null,
+ sides: { toA: boolean; toB: boolean },
+): () => HTMLElement {
return () => {
const box = document.createElement("div");
box.className = "cm-diffArrows";
diff --git a/src/features/vcs/gitMenuDialogs.tsx b/src/features/vcs/gitMenuDialogs.tsx
index ffcf91f2a..943aac3e8 100644
--- a/src/features/vcs/gitMenuDialogs.tsx
+++ b/src/features/vcs/gitMenuDialogs.tsx
@@ -146,7 +146,13 @@ function PullDialog({ onClose }: { onClose: () => void }) {
onClose();
await saveAll();
await runRemote(
- { op: "pullFrom", remote, branches: branch ? [branch] : [], rebase, options: mergeOptionsOf(rebase ? new Set() : flags) },
+ {
+ op: "pullFrom",
+ remote,
+ branches: branch ? [branch] : [],
+ rebase,
+ options: mergeOptionsOf(rebase ? new Set() : flags),
+ },
`${info?.head ?? "HEAD"} ← ${remote}${branch ? `/${branch}` : ""}`,
);
};
@@ -244,7 +250,13 @@ function MergeDialog({ onClose }: { onClose: () => void }) {
<div className={styles.fieldLabel}>
<T>Branch to merge:</T>
</div>
- <Select aria-label="Branch to merge" value={branch} placeholder="Select branch" options={options} onChange={setBranch} />
+ <Select
+ aria-label="Branch to merge"
+ value={branch}
+ placeholder="Select branch"
+ options={options}
+ onChange={setBranch}
+ />
<div className={styles.fieldLabel}>
<T>Options:</T>
</div>
@@ -319,7 +331,13 @@ function RebaseDialog({ onClose }: { onClose: () => void }) {
<div className={styles.fieldLabel}>
{useOnto ? tx`Rebase commits of ${head ?? "HEAD"} not on:` : `Rebase ${head ?? "HEAD"} onto:`}
</div>
- <Select aria-label="Upstream" value={upstream} placeholder="Select branch" options={options} onChange={setUpstream} />
+ <Select
+ aria-label="Upstream"
+ value={upstream}
+ placeholder="Select branch"
+ options={options}
+ onChange={setUpstream}
+ />
<Checkbox label="--onto" checked={useOnto} onChange={setUseOnto} />
{useOnto && (
<Select aria-label="New base" value={onto} placeholder="New base" options={options} onChange={setOnto} />
@@ -383,7 +401,9 @@ function RemotesDialog({ onClose }: { onClose: () => void }) {
close();
if (!r) return;
void apply(
- remote ? { op: "edit", name: remote.name, new_name: r.name, url: r.url } : { op: "add", name: r.name, url: r.url },
+ remote
+ ? { op: "edit", name: remote.name, new_name: r.name, url: r.url }
+ : { op: "add", name: r.name, url: r.url },
);
}}
/>
@@ -411,7 +431,13 @@ function RemotesDialog({ onClose }: { onClose: () => void }) {
<div className={styles.form}>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Remotes")}>
<IconButton icon="plus" title="Add Remote…" size="small" onClick={() => edit()} />
- <IconButton icon="minus" title="Remove Remote" size="small" disabled={!current} onClick={() => void remove()} />
+ <IconButton
+ icon="minus"
+ title="Remove Remote"
+ size="small"
+ disabled={!current}
+ onClick={() => void remove()}
+ />
<IconButton icon="edit" title="Edit Remote…" size="small" disabled={!current} onClick={() => edit(current)} />
</div>
<div className={styles.choiceList} role="listbox" aria-label={tx("Remotes")}>
@@ -550,7 +576,10 @@ function WorktreesDialog({ onClose }: { onClose: () => void }) {
okLabel: "Force Remove",
danger: true,
});
- if (force) await call(commands.vcsRemoveWorktree(currentRepo(), current.path, true)).catch((x) => setError(errorMessage(x)));
+ if (force)
+ await call(commands.vcsRemoveWorktree(currentRepo(), current.path, true)).catch((x) =>
+ setError(errorMessage(x)),
+ );
}
setSelected(null);
await reload();
@@ -566,7 +595,12 @@ function WorktreesDialog({ onClose }: { onClose: () => void }) {
>
<div className={styles.form}>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Worktrees")}>
- <IconButton icon="plus" title="New Worktree…" size="small" onClick={() => showNewWorktree(() => void reload())} />
+ <IconButton
+ icon="plus"
+ title="New Worktree…"
+ size="small"
+ onClick={() => showNewWorktree(() => void reload())}
+ />
<IconButton
icon="minus"
title="Remove Worktree"
@@ -615,7 +649,10 @@ function NewWorktreeDialog({ onClose }: { onClose: (created: boolean) => void })
const [newBranch, setNewBranch] = useState("");
const [path, setPath] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const options = useMemo(() => [...branchOptions(sortLocal(branches)), ...branchOptions(sortRemote(branches))], [branches]);
+ const options = useMemo(
+ () => [...branchOptions(sortLocal(branches)), ...branchOptions(sortRemote(branches))],
+ [branches],
+ );
const sourceRemote = branches.find((b) => b.name === source)?.remote ?? false;
// A remote branch `origin/x` suggests the local name `x`.
const shortSource = source && sourceRemote ? source.slice(source.indexOf("/") + 1) : (source ?? "");
@@ -657,7 +694,13 @@ function NewWorktreeDialog({ onClose }: { onClose: (created: boolean) => void })
<div className={styles.fieldLabel}>
<T>Check out:</T>
</div>
- <Select aria-label="Check out" value={source} placeholder="Select branch" options={options} onChange={setSource} />
+ <Select
+ aria-label="Check out"
+ value={source}
+ placeholder="Select branch"
+ options={options}
+ onChange={setSource}
+ />
<Checkbox label="Create a new branch" checked={createBranch} onChange={setCreateBranch} />
{createBranch && (
<Input
diff --git a/src/features/vcs/hunks.ts b/src/features/vcs/hunks.ts
index f0cc5e455..23c18e3f9 100644
--- a/src/features/vcs/hunks.ts
+++ b/src/features/vcs/hunks.ts
@@ -55,13 +55,19 @@ export function hunkAtLine<H extends Pick<LineHunk, "start" | "lines">>(
}
/** Next hunk starting after `line` (wraps around). */
-export function nextHunk<H extends Pick<LineHunk, "start" | "lines">>(hunks: readonly H[], line: number): H | undefined {
+export function nextHunk<H extends Pick<LineHunk, "start" | "lines">>(
+ hunks: readonly H[],
+ line: number,
+): H | undefined {
if (!hunks.length) return undefined;
return hunks.find((h) => h.start > line) ?? hunks[0];
}
/** Previous hunk ending before `line` (wraps around). */
-export function prevHunk<H extends Pick<LineHunk, "start" | "lines">>(hunks: readonly H[], line: number): H | undefined {
+export function prevHunk<H extends Pick<LineHunk, "start" | "lines">>(
+ hunks: readonly H[],
+ line: number,
+): H | undefined {
if (!hunks.length) return undefined;
for (let i = hunks.length - 1; i >= 0; i--) {
const h = hunks[i]!;
diff --git a/src/features/vcs/index.ts b/src/features/vcs/index.ts
index 0ba1e6788..4764885ae 100644
--- a/src/features/vcs/index.ts
+++ b/src/features/vcs/index.ts
@@ -44,7 +44,13 @@ function trackTitleItem(): () => void {
let dispose: (() => void) | null = null;
const sync = (available: boolean) => {
if (available && !dispose) {
- dispose = registerTitleItem({ id: "vcs.branch", title: "VCS Widget", align: "left", priority: 10, component: BranchWidget });
+ dispose = registerTitleItem({
+ id: "vcs.branch",
+ title: "VCS Widget",
+ align: "left",
+ priority: 10,
+ component: BranchWidget,
+ });
} else if (!available && dispose) {
dispose();
dispose = null;
@@ -63,7 +69,9 @@ function trackTitleItem(): () => void {
function conflictsBody(names: string[]): string {
const list = names.slice(0, 3).join(", ") + (names.length > 3 ? "…" : "");
- return names.length === 1 ? tx`${names.length} file has conflicts: ${list}` : tx`${names.length} files have conflicts: ${list}`;
+ return names.length === 1
+ ? tx`${names.length} file has conflicts: ${list}`
+ : tx`${names.length} files have conflicts: ${list}`;
}
export function activate(): () => void {
diff --git a/src/features/vcs/localHistoryActions.ts b/src/features/vcs/localHistoryActions.ts
index a97be69c3..ff119caba 100644
--- a/src/features/vcs/localHistoryActions.ts
+++ b/src/features/vcs/localHistoryActions.ts
@@ -17,7 +17,11 @@ export async function putLabel(): Promise<boolean> {
if (!r) return false;
try {
await call(commands.historyPutLabel(r.value));
- notifications().notify({ level: "info", title: `Label '${r.value}' added to Local History`, key: "localHistory.label" });
+ notifications().notify({
+ level: "info",
+ title: `Label '${r.value}' added to Local History`,
+ key: "localHistory.label",
+ });
return true;
} catch (e) {
notifications().notify({ level: "error", title: "Cannot put label", body: errorMessage(e) });
diff --git a/src/features/vcs/logOptions.ts b/src/features/vcs/logOptions.ts
index 67c394c9c..b8704265d 100644
--- a/src/features/vcs/logOptions.ts
+++ b/src/features/vcs/logOptions.ts
@@ -95,7 +95,8 @@ export function refLabels(
const tags = refs.filter((r) => r.startsWith("tag: ")).map((r) => r.slice(5));
const branches = refs.filter((r) => r !== "HEAD" && !r.startsWith("tag: "));
const out: RefLabel[] = [];
- if (refs.includes("HEAD") && (!opts.compact || !branches.length)) out.push({ kind: "head", text: "HEAD", title: "HEAD" });
+ if (refs.includes("HEAD") && (!opts.compact || !branches.length))
+ out.push({ kind: "head", text: "HEAD", title: "HEAD" });
const locals = branches.filter((b) => !isRemote(b));
const remotes = branches.filter(isRemote);
const absorbed = new Set<string>();
diff --git a/src/features/vcs/model.ts b/src/features/vcs/model.ts
index bf6828a62..43cb0e6c6 100644
--- a/src/features/vcs/model.ts
+++ b/src/features/vcs/model.ts
@@ -155,7 +155,10 @@ export function stashLabel(message: string): { branch: string | null; text: stri
* `https://user@host/o/r.git`), or null for local paths.
*/
export function remoteWebUrl(url: string): string | null {
- const u = url.trim().replace(/\/+$/, "").replace(/\.git$/, "");
+ const u = url
+ .trim()
+ .replace(/\/+$/, "")
+ .replace(/\.git$/, "");
let host: string;
let path: string;
const scp = /^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(u);
diff --git a/src/features/vcs/rebasePlan.ts b/src/features/vcs/rebasePlan.ts
index 82d1a1ce3..d2ff2beca 100644
--- a/src/features/vcs/rebasePlan.ts
+++ b/src/features/vcs/rebasePlan.ts
@@ -81,13 +81,20 @@ export function autosquash(rows: readonly RebaseRow[]): RebaseRow[] {
export function squashPlan(range: RebaseRange, ids: ReadonlySet<string>, message: string): RebaseEntry[] {
const first = range.commits.findIndex((c) => ids.has(c.id));
const selected = range.commits.filter((c) => ids.has(c.id));
- const entry = (c: Commit, action: RebaseAction, msg: string | null = null): RebaseEntry => ({ commit: c.id, action, message: msg });
+ const entry = (c: Commit, action: RebaseAction, msg: string | null = null): RebaseEntry => ({
+ commit: c.id,
+ action,
+ message: msg,
+ });
return [
...range.commits.slice(0, first).map((c) => entry(c, "pick")),
...selected.map((c, i) =>
entry(c, i === 0 ? "pick" : "squash", i === selected.length - 1 && i > 0 ? message.trim() : null),
),
- ...range.commits.slice(first + 1).filter((c) => !ids.has(c.id)).map((c) => entry(c, "pick")),
+ ...range.commits
+ .slice(first + 1)
+ .filter((c) => !ids.has(c.id))
+ .map((c) => entry(c, "pick")),
];
}
@@ -130,7 +137,12 @@ export function toEntries(rows: readonly RebaseRow[]): RebaseEntry[] {
}
/** Plan for a single-commit action from the log (Edit Commit Message, Drop Commit). */
-export function singleCommitPlan(range: RebaseRange, target: string, action: RebaseAction, message?: string): RebaseEntry[] {
+export function singleCommitPlan(
+ range: RebaseRange,
+ target: string,
+ action: RebaseAction,
+ message?: string,
+): RebaseEntry[] {
return range.commits.map((c) =>
c.id === target
? { commit: c.id, action, message: action === "reword" ? (message ?? c.message).trim() : null }
diff --git a/src/features/vcs/remoteUi.tsx b/src/features/vcs/remoteUi.tsx
index ac702f994..f691a022c 100644
--- a/src/features/vcs/remoteUi.tsx
+++ b/src/features/vcs/remoteUi.tsx
@@ -115,7 +115,9 @@ export function pushCandidates(repos: readonly RepoPush[]): RepoPush[] {
/** Checked by default: repositories with outgoing commits (a new branch only in the selected one). */
export function defaultPushChecked(repos: readonly RepoPush[], selected: string | null): Set<string> {
- return new Set(repos.filter((r) => (r.branch.upstream ? r.commits.length > 0 : r.root === selected)).map((r) => r.root));
+ return new Set(
+ repos.filter((r) => (r.branch.upstream ? r.commits.length > 0 : r.root === selected)).map((r) => r.root),
+ );
}
type PushRow = { type: "repo"; repo: RepoPush } | { type: "commit"; repo: RepoPush; commit: Commit };
@@ -162,7 +164,8 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
if (!next.delete(root)) next.add(root);
return next;
});
- const targetOf = (r: RepoPush) => (r.branch.upstream ? r.branch.upstream.slice(r.branch.upstream.indexOf("/") + 1) : r.branch.head!);
+ const targetOf = (r: RepoPush) =>
+ r.branch.upstream ? r.branch.upstream.slice(r.branch.upstream.indexOf("/") + 1) : r.branch.head!;
const picked = (repos ?? []).filter((r) => checked.has(r.root));
const push = async () => {
onClose();
diff --git a/src/features/viewers/index.ts b/src/features/viewers/index.ts
index 4b5882326..215d01252 100644
--- a/src/features/viewers/index.ts
+++ b/src/features/viewers/index.ts
@@ -93,7 +93,11 @@ export function activate(): () => void {
return wantsHexView(probe) ? binaryInput(path, probe) : null;
},
}),
- registerTextEditorWrapper({ id: "viewers.markdown", matches: isMarkdownPath, component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor)) }),
+ registerTextEditorWrapper({
+ id: "viewers.markdown",
+ matches: isMarkdownPath,
+ component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor)),
+ }),
registerMarkdownLiveSource(),
registerActions([...imageActions(), ...markdownActions()]),
];
diff --git a/src/features/viewers/markdown/mermaid.test.ts b/src/features/viewers/markdown/mermaid.test.ts
index bff0c51eb..fe63bbb3a 100644
--- a/src/features/viewers/markdown/mermaid.test.ts
+++ b/src/features/viewers/markdown/mermaid.test.ts
@@ -162,16 +162,14 @@ describe("mermaid in the markdown preview", () => {
"--fg": "color(srgb 0.6 0.62 0.66)",
};
let probe = "";
- const computed = vi
- .spyOn(globalThis, "getComputedStyle")
- .mockImplementation(
- (el) =>
- (el === document.documentElement
- ? { getPropertyValue: (n: string) => values[n] ?? "" }
- : {
- color: resolved[(probe = (el as HTMLElement).style.color.slice(4, -1))] ?? "",
- }) as unknown as CSSStyleDeclaration,
- );
+ const computed = vi.spyOn(globalThis, "getComputedStyle").mockImplementation(
+ (el) =>
+ (el === document.documentElement
+ ? { getPropertyValue: (n: string) => values[n] ?? "" }
+ : {
+ color: resolved[(probe = (el as HTMLElement).style.color.slice(4, -1))] ?? "",
+ }) as unknown as CSSStyleDeclaration,
+ );
try {
await renderMermaidIn(preview(SEQ)).done;
expect(probe).not.toBe("");
diff --git a/src/features/web/index.ts b/src/features/web/index.ts
index df7451c1e..d0c4dcb68 100644
--- a/src/features/web/index.ts
+++ b/src/features/web/index.ts
@@ -46,9 +46,12 @@ function browserMenu(path: string): MenuItem {
{ kind: "action", action: "web.openInBrowser", arg: { path }, label: "Default Browser" },
{ kind: "separator" },
...(html ? [{ label: "Built-in Preview", icon: "eye", run: () => void showPreview(path) }] : []),
- ...useBrowsers
- .getState()
- .list.map((b): MenuItem => ({ label: b.name, verbatim: true, icon: browserIcon(b.id), run: () => void openInBrowser(path, b.id) })),
+ ...useBrowsers.getState().list.map((b): MenuItem => ({
+ label: b.name,
+ verbatim: true,
+ icon: browserIcon(b.id),
+ run: () => void openInBrowser(path, b.id),
+ })),
],
};
}
diff --git a/src/features/welcome/ProjectPopup.tsx b/src/features/welcome/ProjectPopup.tsx
index 39e2ecf22..6aa42ca9c 100644
--- a/src/features/welcome/ProjectPopup.tsx
+++ b/src/features/welcome/ProjectPopup.tsx
@@ -10,7 +10,8 @@ import styles from "./ProjectPopup.module.css";
import { tx } from "@/platform/i18n";
type Entry =
- { kind: "action"; id: string; label: string; icon: IconName } | { kind: "project"; open: boolean; m: RecentMatch };
+ | { kind: "action"; id: string; label: string; icon: IconName }
+ | { kind: "project"; open: boolean; m: RecentMatch };
const ACTIONS: { id: string; label: string; icon: IconName }[] = [
{ id: "file.openProject", label: "Open…", icon: "folder" },
diff --git a/src/platform/colorScheme.test.ts b/src/platform/colorScheme.test.ts
index 41f454f9d..ade559383 100644
--- a/src/platform/colorScheme.test.ts
+++ b/src/platform/colorScheme.test.ts
@@ -83,9 +83,15 @@ describe("color schemes", () => {
const root = document.documentElement;
useProject.setState({ settings: { editor: { fontWeight: 300, boldFontWeight: 800 } } as unknown as Settings });
const dispose = installColorScheme();
- expect([root.style.getPropertyValue("--fw-code"), root.style.getPropertyValue("--fw-code-bold")]).toEqual(["300", "800"]);
+ expect([root.style.getPropertyValue("--fw-code"), root.style.getPropertyValue("--fw-code-bold")]).toEqual([
+ "300",
+ "800",
+ ]);
useProject.setState({ settings: { editor: {} } as unknown as Settings });
- expect([root.style.getPropertyValue("--fw-code"), root.style.getPropertyValue("--fw-code-bold")]).toEqual(["400", "700"]);
+ expect([root.style.getPropertyValue("--fw-code"), root.style.getPropertyValue("--fw-code-bold")]).toEqual([
+ "400",
+ "700",
+ ]);
dispose();
expect(root.style.getPropertyValue("--fw-code")).toBe("");
});
@@ -101,7 +107,10 @@ describe("color schemes", () => {
});
it("coerces editor settings to their defaults' shape", () => {
- const v = validateEditorExtras({ tabs: { tabLimit: "x", placement: "none" }, codeStyle: { languages: { go: { useTab: true } } } });
+ const v = validateEditorExtras({
+ tabs: { tabLimit: "x", placement: "none" },
+ codeStyle: { languages: { go: { useTab: true } } },
+ });
expect(v.tabs.tabLimit).toBe(30);
expect(v.tabs.placement).toBe("none");
expect(v.codeStyle.languages.go).toEqual({ useTab: true });
diff --git a/src/platform/colorScheme.ts b/src/platform/colorScheme.ts
index 6b6fe3586..8ba950c8c 100644
--- a/src/platform/colorScheme.ts
+++ b/src/platform/colorScheme.ts
@@ -13,7 +13,10 @@ import { BUILTIN_THEMES, isBuiltinTheme, themeKind, type BuiltinThemeId } from "
export type SchemeId = BuiltinThemeId;
-export const SCHEMES: ReadonlyArray<{ id: SchemeId; name: string }> = BUILTIN_THEMES.map((t) => ({ id: t.id, name: t.label }));
+export const SCHEMES: ReadonlyArray<{ id: SchemeId; name: string }> = BUILTIN_THEMES.map((t) => ({
+ id: t.id,
+ name: t.label,
+}));
export interface AttributeDef {
id: string;
@@ -47,16 +50,36 @@ export const ATTRIBUTES: readonly AttributeDef[] = [
{ id: "caret", name: "Caret", path: ["General", "Editor"], fg: "--caret" },
{ id: "caretRow", name: "Caret row", path: ["General", "Editor"], bg: "--bg-current-line" },
{ id: "selection", name: "Selection background", path: ["General", "Editor"], bg: "--bg-editor-selection" },
- { id: "selectionInactive", name: "Selection background (inactive)", path: ["General", "Editor"], bg: "--bg-editor-selection-inactive" },
+ {
+ id: "selectionInactive",
+ name: "Selection background (inactive)",
+ path: ["General", "Editor"],
+ bg: "--bg-editor-selection-inactive",
+ },
{ id: "whitespaces", name: "Whitespaces", path: ["General", "Editor"], fg: "--fg-whitespace" },
{ id: "indentGuide", name: "Indent guide", path: ["General", "Editor"], fg: "--border-indent-guide" },
{ id: "rightMargin", name: "Hard wrap guide", path: ["General", "Editor"], fg: "--border-right-margin" },
- { id: "methodSeparator", name: "Method separator color", path: ["General", "Editor"], fg: "--border-method-separator" },
+ {
+ id: "methodSeparator",
+ name: "Method separator color",
+ path: ["General", "Editor"],
+ fg: "--border-method-separator",
+ },
{ id: "lineNumber", name: "Line number", path: ["General", "Code"], fg: "--fg-line-number" },
- { id: "lineNumberCaret", name: "Line number on caret row", path: ["General", "Code"], fg: "--fg-line-number-current" },
+ {
+ id: "lineNumberCaret",
+ name: "Line number on caret row",
+ path: ["General", "Code"],
+ fg: "--fg-line-number-current",
+ },
{ id: "gutter", name: "Gutter background", path: ["General", "Code"], bg: "--bg-editor-gutter" },
{ id: "matchedBrace", name: "Matched brace", path: ["General", "Code"], bg: "--bg-matched-brace" },
- { id: "identifierUnderCaret", name: "Identifier under caret", path: ["General", "Code"], bg: "--bg-identifier-under-caret" },
+ {
+ id: "identifierUnderCaret",
+ name: "Identifier under caret",
+ path: ["General", "Code"],
+ bg: "--bg-identifier-under-caret",
+ },
{
id: "identifierUnderCaretWrite",
name: "Identifier under caret (write)",
@@ -64,9 +87,20 @@ export const ATTRIBUTES: readonly AttributeDef[] = [
bg: "--bg-identifier-under-caret-write",
},
{ id: "inlay", name: "Inlay hints", path: ["General", "Code"], fg: "--fg-inlay", bg: "--bg-inlay" },
- { id: "folded", name: "Folded text", path: ["General", "Code"], fg: "--fg-fold-placeholder", bg: "--bg-fold-placeholder" },
+ {
+ id: "folded",
+ name: "Folded text",
+ path: ["General", "Code"],
+ fg: "--fg-fold-placeholder",
+ bg: "--bg-fold-placeholder",
+ },
{ id: "searchResult", name: "Search result", path: ["General", "Search Results"], bg: "--bg-search-match" },
- { id: "searchResultCurrent", name: "Current search result", path: ["General", "Search Results"], bg: "--bg-search-match-current" },
+ {
+ id: "searchResultCurrent",
+ name: "Current search result",
+ path: ["General", "Search Results"],
+ bg: "--bg-search-match-current",
+ },
{ id: "error", name: "Error", path: ["General", "Errors and Warnings"], effect: "--wave-error" },
{ id: "warning", name: "Warning", path: ["General", "Errors and Warnings"], effect: "--wave-warning" },
{ id: "weakWarning", name: "Weak warning", path: ["General", "Errors and Warnings"], fg: "--fg-weak-warning" },
@@ -99,7 +133,14 @@ export const ATTRIBUTES: readonly AttributeDef[] = [
...[1, 2, 3].map((n) => syn(`bracket${n}`, `Rainbow brackets › Level ${n}`, [LD], `bracket-${n}`)),
syn("pySelf", "Self parameter", ["Python"], "self"),
- { id: "pyStaticSymbol", name: "Static symbol", path: ["Python"], token: "python-static", italicOnly: true, defaultItalic: false },
+ {
+ id: "pyStaticSymbol",
+ name: "Static symbol",
+ path: ["Python"],
+ token: "python-static",
+ italicOnly: true,
+ defaultItalic: false,
+ },
syn("pyKeywordArg", "Keyword argument", ["Python"], "keyword-arg"),
syn("pyDocstring", "Docstring", ["Python"], "docstring"),
syn("pyBuiltin", "Built-in name", ["Python"], "predefined"),
@@ -191,10 +232,17 @@ export function schemeTokens(id: SchemeId, css: string = source): Vars {
const resolve = (value: string, depth = 0): string =>
depth > 8
? value
- : value.replace(/var\((--[\w-]+)(?:\s*,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/g, (_m, name: string, fallback?: string) => {
- const v = merged.get(name);
- return v !== undefined ? resolve(v, depth + 1) : fallback !== undefined ? resolve(fallback.trim(), depth + 1) : `var(${name})`;
- });
+ : value.replace(
+ /var\((--[\w-]+)(?:\s*,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/g,
+ (_m, name: string, fallback?: string) => {
+ const v = merged.get(name);
+ return v !== undefined
+ ? resolve(v, depth + 1)
+ : fallback !== undefined
+ ? resolve(fallback.trim(), depth + 1)
+ : `var(${name})`;
+ },
+ );
const out: Vars = new Map();
for (const [k, v] of merged) out.set(k, resolve(v));
if (css === source) resolvedCache.set(id, out);
@@ -202,13 +250,18 @@ export function schemeTokens(id: SchemeId, css: string = source): Vars {
}
/** The scheme the editor shows for `setting` under the current theme. */
-export function effectiveScheme(setting: string | undefined, root: HTMLElement | null = typeof document !== "undefined" ? document.documentElement : null): SchemeId {
+export function effectiveScheme(
+ setting: string | undefined,
+ root: HTMLElement | null = typeof document !== "undefined" ? document.documentElement : null,
+): SchemeId {
if (isBuiltinTheme(setting)) return setting;
return themeScheme(root);
}
/** Scheme belonging to the active IDE theme (`data-theme` / `data-contrast`). */
-export function themeScheme(root: HTMLElement | null = typeof document !== "undefined" ? document.documentElement : null): SchemeId {
+export function themeScheme(
+ root: HTMLElement | null = typeof document !== "undefined" ? document.documentElement : null,
+): SchemeId {
if (!root) return "light";
if (isBuiltinTheme(root.dataset.colorTheme)) return root.dataset.colorTheme;
if (root.dataset.theme === "light") return "light";
@@ -233,7 +286,9 @@ const EFFECT_CSS: Record<string, (c: string) => string> = {
};
/** Declarations for the overrides of one scheme. */
-export function overrideDeclarations(overrides: Record<string, TextAttributesOverride> | undefined): Array<[string, string]> {
+export function overrideDeclarations(
+ overrides: Record<string, TextAttributesOverride> | undefined,
+): Array<[string, string]> {
const out: Array<[string, string]> = [];
if (!overrides) return out;
for (const attr of ATTRIBUTES) {
@@ -263,7 +318,11 @@ export function overrideDeclarations(overrides: Record<string, TextAttributesOve
const SAFE = /^[^;{}<>]*$/;
/** Stylesheet text for the chosen scheme and its overrides ("" when the theme's own is used unchanged). */
-export function schemeCss(setting: string | undefined, overrides: Record<string, Record<string, TextAttributesOverride>> | undefined, root?: HTMLElement | null): string {
+export function schemeCss(
+ setting: string | undefined,
+ overrides: Record<string, Record<string, TextAttributesOverride>> | undefined,
+ root?: HTMLElement | null,
+): string {
const id = effectiveScheme(setting, root);
const decls: Array<[string, string]> = [];
// A plugin theme brings its own editor colours: an explicit scheme replaces them even on the same base.
@@ -277,6 +336,8 @@ export function schemeCss(setting: string | undefined, overrides: Record<string,
if (bg) decls.push(["--bg-editor", bg], ["--bg-editor-gutter", tokens.get("--bg-editor-gutter") ?? bg]);
}
decls.push(...overrideDeclarations(overrides?.[id]));
- const body = decls.filter(([k, v]) => /^--[\w-]+$/.test(k) && SAFE.test(v)).map(([k, v]) => ` ${k}: ${v} !important;`);
+ const body = decls
+ .filter(([k, v]) => /^--[\w-]+$/.test(k) && SAFE.test(v))
+ .map(([k, v]) => ` ${k}: ${v} !important;`);
return body.length ? `:root {\n${body.join("\n")}\n}\n` : "";
}
diff --git a/src/platform/context.ts b/src/platform/context.ts
index c1cfeee75..b89479f88 100644
--- a/src/platform/context.ts
+++ b/src/platform/context.ts
@@ -31,7 +31,12 @@ function tokenize(src: string): Token[] {
const c = src[i]!;
if (/\s/.test(c)) {
i++;
- } else if (src.startsWith("&&", i) || src.startsWith("||", i) || src.startsWith("==", i) || src.startsWith("!=", i)) {
+ } else if (
+ src.startsWith("&&", i) ||
+ src.startsWith("||", i) ||
+ src.startsWith("==", i) ||
+ src.startsWith("!=", i)
+ ) {
out.push({ t: "op", v: src.slice(i, i + 2) });
i += 2;
} else if (c === "!" || c === "(" || c === ")") {
@@ -73,7 +78,8 @@ export function compileWhen(expr: string | undefined): (ctx: ContextKeys) => boo
const parseOr = (): Node => {
let left = parseAnd();
while (eat("||")) {
- const l = left, r = parseAnd();
+ const l = left,
+ r = parseAnd();
left = (c) => l(c) || r(c);
}
return left;
@@ -81,7 +87,8 @@ export function compileWhen(expr: string | undefined): (ctx: ContextKeys) => boo
const parseAnd = (): Node => {
let left = parseUnary();
while (eat("&&")) {
- const l = left, r = parseUnary();
+ const l = left,
+ r = parseUnary();
left = (c) => l(c) && r(c);
}
return left;
@@ -104,7 +111,8 @@ export function compileWhen(expr: string | undefined): (ctx: ContextKeys) => boo
const valTok = toks[p++];
if (!valTok || valTok.t === "op") throw new Error(`expected value in when clause: ${expr}`);
const raw = valTok.v;
- const lit: ContextValue = valTok.t === "str" ? raw : raw === "true" ? true : raw === "false" ? false : isFinite(+raw) ? +raw : raw;
+ const lit: ContextValue =
+ valTok.t === "str" ? raw : raw === "true" ? true : raw === "false" ? false : isFinite(+raw) ? +raw : raw;
return (c) => (c[key] === lit) !== negate;
}
return (c) => !!c[key];
diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts
index 07e8ac122..6f4b52715 100644
--- a/src/platform/editorSettings.ts
+++ b/src/platform/editorSettings.ts
@@ -41,11 +41,15 @@ export function lineCommentDefaults(language: string | undefined): { atFirstColu
}
/** Effective Comment Code style of a language: Code Style override, else the language default. */
-export function lineCommentStyleFor(prefs: EditorExtras, language: string | undefined): { atFirstColumn: boolean; addSpace: boolean } {
+export function lineCommentStyleFor(
+ prefs: EditorExtras,
+ language: string | undefined,
+): { atFirstColumn: boolean; addSpace: boolean } {
const base = lineCommentDefaults(language);
const own = language ? prefs.codeStyle.languages[language] : undefined;
return {
- atFirstColumn: typeof own?.lineCommentAtFirstColumn === "boolean" ? own.lineCommentAtFirstColumn : base.atFirstColumn,
+ atFirstColumn:
+ typeof own?.lineCommentAtFirstColumn === "boolean" ? own.lineCommentAtFirstColumn : base.atFirstColumn,
addSpace: typeof own?.lineCommentAddSpace === "boolean" ? own.lineCommentAddSpace : base.addSpace,
};
}
@@ -142,7 +146,14 @@ export const EDITOR_EXTRA_DEFAULTS = {
nextErrorErrorsOnly: true,
stickyLinesMax: 5,
},
- inlay: { types: true, parameters: true, other: true, disabledLanguages: [] as string[], codeVisionUsages: true, codeVisionAuthor: true },
+ inlay: {
+ types: true,
+ parameters: true,
+ other: true,
+ disabledLanguages: [] as string[],
+ codeVisionUsages: true,
+ codeVisionAuthor: true,
+ },
inlineCompletion: { enabled: true, onlyOnPause: false, pauseMs: 500, disabledLanguages: [] as string[] },
gutterIconsDisabled: [] as string[],
showGutterIcons: true,
diff --git a/src/platform/inspectionControls.test.ts b/src/platform/inspectionControls.test.ts
index 17d71ebe9..c30a5f63d 100644
--- a/src/platform/inspectionControls.test.ts
+++ b/src/platform/inspectionControls.test.ts
@@ -12,8 +12,14 @@ vi.mock("./ipc", async (orig) => {
});
vi.mock("./actions", async (orig) => ({ ...(await orig<typeof import("./actions")>()), executeAction }));
-const { disableInspection, intentionControls, patchOverride, problemControls, setInspectionOption, setInspectionSeverity } =
- await import("./inspectionControls");
+const {
+ disableInspection,
+ intentionControls,
+ patchOverride,
+ problemControls,
+ setInspectionOption,
+ setInspectionSeverity,
+} = await import("./inspectionControls");
const { diagnosticInspection, inspectionOption, SPELLING_INSPECTION } = await import("./inspections");
const { useProject } = await import("./project");
@@ -36,7 +42,10 @@ describe("inspection controls", () => {
});
it("writes to the profile in effect, at its level", async () => {
- useProject.setState({ project: null, settings: { inspections: { default: { x: { severity: "error" } } } } as never });
+ useProject.setState({
+ project: null,
+ settings: { inspections: { default: { x: { severity: "error" } } } } as never,
+ });
await disableInspection(SPELLING_INSPECTION);
expect(written()).toEqual({
scope: "global",
@@ -44,13 +53,22 @@ describe("inspection controls", () => {
value: { x: { severity: "error" }, [SPELLING_INSPECTION]: { enabled: false } },
});
- useProject.setState({ project: { root: "/p" } as never, settings: { inspections: { profile: "project" } } as never });
+ useProject.setState({
+ project: { root: "/p" } as never,
+ settings: { inspections: { profile: "project" } } as never,
+ });
await setInspectionSeverity("lsp:ruff:F401", "weakWarning");
- expect(written()).toEqual({ scope: "project", key: "inspections.project", value: { "lsp:ruff:F401": { severity: "weakWarning" } } });
+ expect(written()).toEqual({
+ scope: "project",
+ key: "inspections.project",
+ value: { "lsp:ruff:F401": { severity: "weakWarning" } },
+ });
useProject.setState({
project: { root: "/p" } as never,
- settings: { inspections: { profile: "ide:strict", ideProfiles: { strict: { name: "Strict", overrides: {} } } } } as never,
+ settings: {
+ inspections: { profile: "ide:strict", ideProfiles: { strict: { name: "Strict", overrides: {} } } },
+ } as never,
});
await setInspectionOption(SPELLING_INSPECTION, "processCode", false);
expect(written()).toEqual({
@@ -66,17 +84,28 @@ describe("inspection controls", () => {
it("reads options with their defaults", () => {
expect(inspectionOption({}, SPELLING_INSPECTION, "processCode")).toBe(true);
- expect(inspectionOption({ [SPELLING_INSPECTION]: { options: { processCode: false } } }, SPELLING_INSPECTION, "processCode")).toBe(false);
+ expect(
+ inspectionOption(
+ { [SPELLING_INSPECTION]: { options: { processCode: false } } },
+ SPELLING_INSPECTION,
+ "processCode",
+ ),
+ ).toBe(false);
});
it("offers IDEA's menu rows, opening Settings on the inspection", () => {
const ref = { id: "lsp:ruff:F401", name: "ruff F401" };
const rows = intentionControls(ref);
- expect(rows.map((r) => ("label" in r ? r.label : "-"))).toEqual(["Edit inspection profile setting", "Disable inspection"]);
+ expect(rows.map((r) => ("label" in r ? r.label : "-"))).toEqual([
+ "Edit inspection profile setting",
+ "Disable inspection",
+ ]);
(rows[0] as { run: () => void }).run();
expect(executeAction).toHaveBeenCalledWith("file.settings", "editor.inspections#lsp:ruff:F401");
- useProject.setState({ settings: { inspections: { default: { "lsp:ruff:F401": { severity: "error" } } } } as never });
+ useProject.setState({
+ settings: { inspections: { default: { "lsp:ruff:F401": { severity: "error" } } } } as never,
+ });
const menu = problemControls(ref);
expect(menu.map((r) => ("label" in r ? r.label : "-"))).toEqual([
"Disable Inspection 'ruff F401'",
diff --git a/src/platform/ipc.ts b/src/platform/ipc.ts
index 47cab688b..1995206fb 100644
--- a/src/platform/ipc.ts
+++ b/src/platform/ipc.ts
@@ -64,7 +64,10 @@ export async function ideEventsReady(): Promise<void> {
}
/** Subscribes to one backend event type (or `"*"`); returns an unsubscribe function. */
-export function onIdeEvent<K extends IdeEvent["type"]>(type: K | "*", handler: (event: EventOf<K>) => void): () => void {
+export function onIdeEvent<K extends IdeEvent["type"]>(
+ type: K | "*",
+ handler: (event: EventOf<K>) => void,
+): () => void {
ensureListening();
let set = handlers.get(type);
if (!set) handlers.set(type, (set = new Set()));
diff --git a/src/platform/keymap.test.ts b/src/platform/keymap.test.ts
index 82b12c240..2b159e493 100644
--- a/src/platform/keymap.test.ts
+++ b/src/platform/keymap.test.ts
@@ -123,7 +123,9 @@ describe("keymap", () => {
const at = (ms: number) => (t = ms);
const shift = (type: "keydown" | "keyup", ms: number) => {
at(ms);
- window.dispatchEvent(new KeyboardEvent(type, { key: "Shift", code: "ShiftLeft", shiftKey: type === "keydown" }));
+ window.dispatchEvent(
+ new KeyboardEvent(type, { key: "Shift", code: "ShiftLeft", shiftKey: type === "keydown" }),
+ );
};
const tap = (ms: number, hold = 50) => {
shift("keydown", ms);
@@ -201,7 +203,14 @@ describe("keymap", () => {
const mod = (type: "keydown" | "keyup", key: "Alt" | "Control", ms: number) => {
t = ms;
const held = type === "keydown";
- window.dispatchEvent(new KeyboardEvent(type, { key, code: `${key}Left`, altKey: key === "Alt" && held, ctrlKey: key === "Control" && held }));
+ window.dispatchEvent(
+ new KeyboardEvent(type, {
+ key,
+ code: `${key}Left`,
+ altKey: key === "Alt" && held,
+ ctrlKey: key === "Control" && held,
+ }),
+ );
};
const up = (ms: number) => {
t = ms;
@@ -247,7 +256,14 @@ describe("keymap", () => {
});
const altGr = (key: string, code: string, target: EventTarget) => {
- const e = new KeyboardEvent("keydown", { key, code, ctrlKey: true, altKey: true, bubbles: true, cancelable: true });
+ const e = new KeyboardEvent("keydown", {
+ key,
+ code,
+ ctrlKey: true,
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
Object.defineProperty(e, "getModifierState", { value: (k: string) => k === "AltGraph" });
target.dispatchEvent(e);
return e;
@@ -273,7 +289,16 @@ describe("keymap", () => {
it("never applies on macOS, where ⌥ shortcuts type symbols", () => {
usePlatform.setState({ os: "macos" });
const input = document.createElement("input");
- const e = { key: "ƒ", code: "KeyF", target: input, metaKey: false, ctrlKey: false, altKey: true, shiftKey: false, getModifierState: () => true };
+ const e = {
+ key: "ƒ",
+ code: "KeyF",
+ target: input,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: true,
+ shiftKey: false,
+ getModifierState: () => true,
+ };
expect(isAltGrTyping(e)).toBe(false);
});
});
diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts
index 2a9008863..501b8f885 100644
--- a/src/platform/keymap.ts
+++ b/src/platform/keymap.ts
@@ -380,7 +380,10 @@ function runIfEnabled(id: string): boolean {
* over CodeMirror defaults). Returns an uninstall function. `now` is the clock
* for the double-modifier gestures.
*/
-export function installKeyboardDispatcher(target: Window = window, now: () => number = () => performance.now()): () => void {
+export function installKeyboardDispatcher(
+ target: Window = window,
+ now: () => number = () => performance.now(),
+): () => void {
let pending: string[] = [];
let pendingTimer: ReturnType<typeof setTimeout> | undefined;
/**
@@ -416,7 +419,9 @@ export function installKeyboardDispatcher(target: Window = window, now: () => nu
const key = strokeOf(e)?.split("+").pop();
if (!key) return false;
const binding = normalizeBinding(`${tap.modifier} ${tap.modifier}+${key}`);
- const ids = effectiveBindings().filter(([b]) => b === binding).map(([, id]) => id);
+ const ids = effectiveBindings()
+ .filter(([b]) => b === binding)
+ .map(([, id]) => id);
for (const id of ids.reverse()) {
const action = getAction(id);
if (!action || !isActionKeyEnabled(action)) continue;
@@ -494,7 +499,9 @@ export function installKeyboardDispatcher(target: Window = window, now: () => nu
const fire = tap.step === 3 && !tap.keyUsed && !tap.typed;
resetTap();
if (!fire) return;
- const ids = effectiveBindings().filter(([b]) => b === `${modifier} ${modifier}`).map(([, id]) => id);
+ const ids = effectiveBindings()
+ .filter(([b]) => b === `${modifier} ${modifier}`)
+ .map(([, id]) => id);
for (const id of ids.reverse()) if (runIfEnabled(id)) return;
};
@@ -508,7 +515,9 @@ export function installKeyboardDispatcher(target: Window = window, now: () => nu
e.preventDefault();
e.stopPropagation();
reset();
- const ids = effectiveBindings().filter(([b]) => b === stroke).map(([, id]) => id);
+ const ids = effectiveBindings()
+ .filter(([b]) => b === stroke)
+ .map(([, id]) => id);
for (const id of ids.reverse()) if (runIfEnabled(id)) return;
};
diff --git a/src/platform/keymaps/navExtras.test.ts b/src/platform/keymaps/navExtras.test.ts
index bb5ef624f..64f1c3861 100644
--- a/src/platform/keymaps/navExtras.test.ts
+++ b/src/platform/keymaps/navExtras.test.ts
@@ -4,7 +4,9 @@ import { vscodeMacos } from "./vscode-macos";
describe("IDEA macOS bindings for navigation and editor extras", () => {
it("⇧⌘T is Go to Test only; Reopen Closed Tab has no default (VS Code keeps it)", () => {
- const owners = Object.entries(intellijMacos).filter(([, keys]) => keys.includes("Meta+Shift+T")).map(([id]) => id);
+ const owners = Object.entries(intellijMacos)
+ .filter(([, keys]) => keys.includes("Meta+Shift+T"))
+ .map(([id]) => id);
expect(owners).toEqual(["navigate.gotoTest"]);
expect(intellijMacos["editor.reopenClosedTab"]).toEqual([]);
expect(vscodeMacos["editor.reopenClosedTab"]).toEqual(["Meta+Shift+T"]);
diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts
index 8140d26f3..08ceaab49 100644
--- a/src/platform/languageSettings.ts
+++ b/src/platform/languageSettings.ts
@@ -8,7 +8,13 @@ import { useProject } from "./project";
export interface LanguagesValid {
python: { interpreter: string; activateVirtualenv: boolean };
node: { interpreter: string; packageManager: "" | "npm" | "pnpm" | "yarn" | "bun" };
- rust: { toolchain: string; stdlib: string; checkOnSave: boolean; checkCommand: "check" | "clippy"; rustfmtArgs: string };
+ rust: {
+ toolchain: string;
+ stdlib: string;
+ checkOnSave: boolean;
+ checkCommand: "check" | "clippy";
+ rustfmtArgs: string;
+ };
go: { goroot: string; gopath: string };
typescript: { version: string };
java: {
@@ -34,7 +40,13 @@ export interface ProjectStructureValid {
}
/** The folder lists of `ProjectStructureValid` (marks). */
-export type FolderListKey = "sourceRoots" | "testRoots" | "resourceRoots" | "testResourceRoots" | "excluded" | "unmarked";
+export type FolderListKey =
+ | "sourceRoots"
+ | "testRoots"
+ | "resourceRoots"
+ | "testResourceRoots"
+ | "excluded"
+ | "unmarked";
export const DEFAULT_LANGUAGES: LanguagesValid = {
python: { interpreter: "", activateVirtualenv: true },
@@ -74,7 +86,14 @@ export function normalizeFolder(path: string): string {
const folders = (v: unknown): string[] =>
Array.isArray(v)
- ? [...new Set(v.filter((x): x is string => typeof x === "string").map(normalizeFolder).filter((x) => x))]
+ ? [
+ ...new Set(
+ v
+ .filter((x): x is string => typeof x === "string")
+ .map(normalizeFolder)
+ .filter((x) => x),
+ ),
+ ]
: [];
/** Settings store the content root itself as `.`; roots use `""`. */
@@ -186,8 +205,7 @@ export function effectiveRoots(detected: readonly RootFolder[], ps: ProjectStruc
for (const path of ps[ROLE_KEYS[role]].map(folderKey))
if (!out.some((r) => r.path === path)) out.push({ path, kind: role, detectedFrom: null });
const unmarked = ps.unmarked.map(folderKey);
- for (const d of detected)
- if (!unmarked.includes(d.path) && !out.some((r) => r.path === d.path)) out.push({ ...d });
+ for (const d of detected) if (!unmarked.includes(d.path) && !out.some((r) => r.path === d.path)) out.push({ ...d });
return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
}
diff --git a/src/platform/projectRoots.test.ts b/src/platform/projectRoots.test.ts
index 63e31e116..6d58a8657 100644
--- a/src/platform/projectRoots.test.ts
+++ b/src/platform/projectRoots.test.ts
@@ -66,7 +66,10 @@ describe("effective roots", () => {
});
it("finds the innermost root and recognises test files", () => {
- const roots = effectiveRoots([...DETECTED, { path: "", kind: "source", detectedFrom: "go.mod" }], validateProjectStructure({}));
+ const roots = effectiveRoots(
+ [...DETECTED, { path: "", kind: "source", detectedFrom: "go.mod" }],
+ validateProjectStructure({}),
+ );
expect(rootFor(roots, "src/test/java/a/B.java")?.path).toBe("src/test/java");
expect(rootFor(roots, "src/test/javax/B.java")?.path).toBe("");
expect(isTestPath(roots, "src/test/java/a/B.java")).toBe(true);
diff --git a/src/platform/remoteSettings.ts b/src/platform/remoteSettings.ts
index 55cc28b16..04292116f 100644
--- a/src/platform/remoteSettings.ts
+++ b/src/platform/remoteSettings.ts
@@ -109,9 +109,9 @@ type Obj = Record<string, unknown>;
const obj = (v: unknown): Obj => (v && typeof v === "object" && !Array.isArray(v) ? (v as Obj) : {});
const text = (v: unknown, d: string) => (typeof v === "string" ? v : d);
const bool = (v: unknown, d: boolean) => (typeof v === "boolean" ? v : d);
-const strings = (v: unknown, d: string[]) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : d);
-const oneOf = <T extends string>(v: unknown, values: readonly T[], d: T): T =>
- values.includes(v as T) ? (v as T) : d;
+const strings = (v: unknown, d: string[]) =>
+ Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : d;
+const oneOf = <T extends string>(v: unknown, values: readonly T[], d: T): T => (values.includes(v as T) ? (v as T) : d);
const port = (v: unknown): number | null =>
typeof v === "number" && Number.isInteger(v) && v > 0 && v <= 65535 ? v : null;
diff --git a/src/platform/virtualDocs.ts b/src/platform/virtualDocs.ts
index 941a243ad..1baa20af4 100644
--- a/src/platform/virtualDocs.ts
+++ b/src/platform/virtualDocs.ts
@@ -37,13 +37,16 @@ export function virtualParent(uri: string): string {
export function virtualContainer(uri: string): string {
const scheme = uri.slice(0, uri.indexOf(":"));
const rest = uri.replace(/^[^:]+:(\/\/)?/, "").split(/[?#]/)[0]!;
- const segs = rest.split("/").filter(Boolean).map((s) => {
- try {
- return decodeURIComponent(s);
- } catch {
- return s;
- }
- });
+ const segs = rest
+ .split("/")
+ .filter(Boolean)
+ .map((s) => {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+ });
segs.pop();
if (scheme === "jdt" && segs[0] === "contents") segs.shift();
return segs.join(" › ");
diff --git a/src/platform/workflowSettings.test.ts b/src/platform/workflowSettings.test.ts
index 5be1da643..6f5518191 100644
--- a/src/platform/workflowSettings.test.ts
+++ b/src/platform/workflowSettings.test.ts
@@ -6,7 +6,11 @@ describe("validateWorkflow", () => {
it("falls back to defaults for missing or malformed values", () => {
expect(validateWorkflow(undefined)).toEqual(DEFAULT_WORKFLOW);
const v = validateWorkflow({
- vcs: { historyLimit: -5, git: { updateMethod: "squash", incomingCheck: "never" }, issueNavigation: [{ pattern: "" }, { pattern: "#(\\d+)", link: "x/$1" }] },
+ vcs: {
+ historyLimit: -5,
+ git: { updateMethod: "squash", incomingCheck: "never" },
+ issueNavigation: [{ pattern: "" }, { pattern: "#(\\d+)", link: "x/$1" }],
+ },
console: { bufferKb: 1e12, foldPatterns: ["a", 3, ""] },
terminal: { cursorShape: "bar", env: { A: "1", B: 2 }, tabName: " " },
externalTools: [{ name: "Lint", id: "x" }, { name: "" }, { name: "Again", id: "x" }],
diff --git a/src/platform/workflowSettings.ts b/src/platform/workflowSettings.ts
index b506ce077..08cac9995 100644
--- a/src/platform/workflowSettings.ts
+++ b/src/platform/workflowSettings.ts
@@ -346,7 +346,12 @@ export function validateRun(raw: unknown): RunSettingsValid {
confirmRerun: bool(v.confirmRerun, d.confirmRerun),
confirmTerminate: bool(v.confirmTerminate, d.confirmTerminate),
showOnStart: bool(v.showOnStart, d.showOnStart),
- terminationTimeoutMs: num(v.terminationTimeoutMs, d.terminationTimeoutMs, WORKFLOW_LIMITS.terminationTimeoutMs, true),
+ terminationTimeoutMs: num(
+ v.terminationTimeoutMs,
+ d.terminationTimeoutMs,
+ WORKFLOW_LIMITS.terminationTimeoutMs,
+ true,
+ ),
};
}
@@ -457,7 +462,10 @@ export function useWorkflowSettings<T>(select: (s: WorkflowSettings) => T): T {
}
/** Calls `listener` whenever a section changes (deep-compared by JSON), not initially. */
-export function onWorkflowSettingsChange<T>(select: (s: WorkflowSettings) => T, listener: (value: T, prev: T) => void): () => void {
+export function onWorkflowSettingsChange<T>(
+ select: (s: WorkflowSettings) => T,
+ listener: (value: T, prev: T) => void,
+): () => void {
let prev = select(workflowSettings());
let prevJson = JSON.stringify(prev);
return useProject.subscribe((s, old) => {
diff --git a/src/styles/global.css b/src/styles/global.css
index f359bf836..f311b3846 100644
--- a/src/styles/global.css
+++ b/src/styles/global.css
@@ -103,28 +103,46 @@ a:hover {
outline: none;
}
:where(
- button,
- a[href],
- input:is([type="checkbox"], [type="radio"], [type="range"], [type="color"], [type="file"], [type="button"], [type="submit"], [type="reset"]),
- select,
- summary,
- [role="button"],
- [role="link"],
- [role="checkbox"],
- [role="radio"],
- [role="switch"],
- [role="tab"],
- [role="combobox"],
- [role="slider"],
- [role="spinbutton"]
-):not(
- :where(
- input:not([type="checkbox"], [type="radio"], [type="range"], [type="color"], [type="file"], [type="button"], [type="submit"], [type="reset"]),
- textarea,
- [contenteditable="true"],
- [contenteditable=""]
- )
-):focus-visible {
+ button,
+ a[href],
+ input:is(
+ [type="checkbox"],
+ [type="radio"],
+ [type="range"],
+ [type="color"],
+ [type="file"],
+ [type="button"],
+ [type="submit"],
+ [type="reset"]
+ ),
+ select,
+ summary,
+ [role="button"],
+ [role="link"],
+ [role="checkbox"],
+ [role="radio"],
+ [role="switch"],
+ [role="tab"],
+ [role="combobox"],
+ [role="slider"],
+ [role="spinbutton"]
+ ):not(
+ :where(
+ input:not(
+ [type="checkbox"],
+ [type="radio"],
+ [type="range"],
+ [type="color"],
+ [type="file"],
+ [type="button"],
+ [type="submit"],
+ [type="reset"]
+ ),
+ textarea,
+ [contenteditable="true"],
+ [contenteditable=""]
+ )
+ ):focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
diff --git a/src/ui/Dialog.test.tsx b/src/ui/Dialog.test.tsx
index 3aa6e762d..964420fb9 100644
--- a/src/ui/Dialog.test.tsx
+++ b/src/ui/Dialog.test.tsx
@@ -33,7 +33,11 @@ describe("orderDialogButtons", () => {
it("Windows / Linux: the default button first, then declaration order", () => {
expect(labels(orderDialogButtons(safeDelete(), "other"))).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
- const settings: DialogButton[] = [{ label: "Cancel", role: "cancel" }, { label: "Apply" }, { label: "OK", role: "default" }];
+ const settings: DialogButton[] = [
+ { label: "Cancel", role: "cancel" },
+ { label: "Apply" },
+ { label: "OK", role: "default" },
+ ];
expect(labels(orderDialogButtons(settings, "other"))).toEqual(["OK", "Cancel", "Apply"]);
});
@@ -74,7 +78,11 @@ describe("Dialog chrome", () => {
const onClose = vi.fn();
show("other", onClose);
const bar = document.querySelector("[data-dialog-titlebar]") as HTMLElement;
- expect(within(bar).getAllByRole("button").map((b) => b.getAttribute("aria-label"))).toEqual(["Close"]);
+ expect(
+ within(bar)
+ .getAllByRole("button")
+ .map((b) => b.getAttribute("aria-label")),
+ ).toEqual(["Close"]);
expect(footerLabels()).toEqual(["View Usages", "Delete Anyway", "Cancel"]);
fireEvent.click(within(bar).getByRole("button", { name: "Close" }));
expect(onClose).toHaveBeenCalledTimes(1);
@@ -98,7 +106,15 @@ describe("Dialog chrome", () => {
it("renders the help button and footer start on the left", () => {
const onHelp = vi.fn();
render(
- <Dialog open onClose={() => {}} title="T" onHelp={onHelp} footerStart={<span>status</span>} buttons={safeDelete()} platform="mac">
+ <Dialog
+ open
+ onClose={() => {}}
+ title="T"
+ onHelp={onHelp}
+ footerStart={<span>status</span>}
+ buttons={safeDelete()}
+ platform="mac"
+ >
<p>x</p>
</Dialog>,
);
@@ -126,7 +142,15 @@ describe("Dialog keyboard", () => {
it("Enter is left to text areas, buttons and handlers that consumed it; disabled default does nothing", () => {
const ok = vi.fn();
const { rerender } = render(
- <Dialog open onClose={() => {}} title="T" buttons={[{ label: "OK", role: "default", onClick: ok }, { label: "Cancel", role: "cancel" }]}>
+ <Dialog
+ open
+ onClose={() => {}}
+ title="T"
+ buttons={[
+ { label: "OK", role: "default", onClick: ok },
+ { label: "Cancel", role: "cancel" },
+ ]}
+ >
<textarea aria-label="Message" />
<input aria-label="Own" onKeyDown={(e) => e.key === "Enter" && e.preventDefault()} />
</Dialog>,
@@ -139,7 +163,12 @@ describe("Dialog keyboard", () => {
fireEvent.keyDown(screen.getByLabelText("Message"), { key: "Enter", metaKey: true });
expect(ok).toHaveBeenCalledTimes(1);
rerender(
- <Dialog open onClose={() => {}} title="T" buttons={[{ label: "OK", role: "default", onClick: ok, disabled: true }]}>
+ <Dialog
+ open
+ onClose={() => {}}
+ title="T"
+ buttons={[{ label: "OK", role: "default", onClick: ok, disabled: true }]}
+ >
<input aria-label="Field" />
</Dialog>,
);
@@ -150,7 +179,15 @@ describe("Dialog keyboard", () => {
it("a cancel button without a handler closes the dialog", () => {
const onClose = vi.fn();
render(
- <Dialog open onClose={onClose} title="T" buttons={[{ label: "OK", role: "default", onClick: () => {} }, { label: "Cancel", role: "cancel" }]}>
+ <Dialog
+ open
+ onClose={onClose}
+ title="T"
+ buttons={[
+ { label: "OK", role: "default", onClick: () => {} },
+ { label: "Cancel", role: "cancel" },
+ ]}
+ >
<p>x</p>
</Dialog>,
);
diff --git a/src/ui/Input.tsx b/src/ui/Input.tsx
index c5908ff03..1898156a1 100644
--- a/src/ui/Input.tsx
+++ b/src/ui/Input.tsx
@@ -24,7 +24,17 @@ export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>,
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
- { invalid, mono, variant = "framed", className, spellCheck = false, autoComplete = "off", placeholder, "aria-label": ariaLabel, ...rest },
+ {
+ invalid,
+ mono,
+ variant = "framed",
+ className,
+ spellCheck = false,
+ autoComplete = "off",
+ placeholder,
+ "aria-label": ariaLabel,
+ ...rest
+ },
ref,
) {
const tx = useTx();
diff --git a/src/ui/List.tsx b/src/ui/List.tsx
index 718c1d86d..5a361ddcd 100644
--- a/src/ui/List.tsx
+++ b/src/ui/List.tsx
@@ -4,7 +4,16 @@
* also be driven from an external input via `listNavigate`, so focus can stay
* in a search field while ↑/↓ move the selection.
*/
-import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
+import {
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent,
+ type MouseEvent,
+ type ReactNode,
+} from "react";
import clsx from "clsx";
import { useVirtualizer } from "@tanstack/react-virtual";
import styles from "./List.module.css";
diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx
index 2188b828f..5f9cbe30a 100644
--- a/src/ui/Tabs.tsx
+++ b/src/ui/Tabs.tsx
@@ -282,10 +282,15 @@ export function Tabs({
dnd
? (e) => {
if ((e.target as Element).closest("[data-tab-close]")) return;
- startPointerDrag(e, e.currentTarget, { type: dnd.type, payload: dnd.payload(item.id) }, {
- onStart: () => setDragging(item.id),
- onEnd: () => setDragging(null),
- });
+ startPointerDrag(
+ e,
+ e.currentTarget,
+ { type: dnd.type, payload: dnd.payload(item.id) },
+ {
+ onStart: () => setDragging(item.id),
+ onEnd: () => setDragging(null),
+ },
+ );
}
: undefined
}
diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx
index fdb5e88b3..1723f2ba1 100644
--- a/src/ui/icons.tsx
+++ b/src/ui/icons.tsx
@@ -862,7 +862,15 @@ export function fileIconName(fileName: string): IconName {
}
export type FolderKind =
- "plain" | "source" | "test" | "resources" | "testResources" | "excluded" | "library" | "github" | "module";
+ | "plain"
+ | "source"
+ | "test"
+ | "resources"
+ | "testResources"
+ | "excluded"
+ | "library"
+ | "github"
+ | "module";
/** Folder icon by role (expui has no separate "open" folder glyph). */
export function folderIconName(kind: FolderKind = "plain"): IconName {
diff --git a/src/ui/index.ts b/src/ui/index.ts
index 91c75f372..05accd68c 100644
--- a/src/ui/index.ts
+++ b/src/ui/index.ts
@@ -6,7 +6,17 @@ export * from "./Input";
export * from "./Checkbox";
export * from "./Select";
export * from "./Tabs";
-export { FILES_DRAG, dragRequiresAlt, dragSession, registerDropTarget, setDragRequiresAlt, startPointerDrag, type DragData, type DragSession, type DropTarget } from "./pointerDrag";
+export {
+ FILES_DRAG,
+ dragRequiresAlt,
+ dragSession,
+ registerDropTarget,
+ setDragRequiresAlt,
+ startPointerDrag,
+ type DragData,
+ type DragSession,
+ type DropTarget,
+} from "./pointerDrag";
export * from "./Tree";
export * from "./List";
export * from "./Popup";
diff --git a/src/workbench/MainToolbarDialog.tsx b/src/workbench/MainToolbarDialog.tsx
index 7bdd653fd..cf1909b2b 100644
--- a/src/workbench/MainToolbarDialog.tsx
+++ b/src/workbench/MainToolbarDialog.tsx
@@ -111,7 +111,11 @@ function CustomizeDialog({ onClose }: { onClose: () => void }) {
}
renderItem={(id) => (
<div className={styles.row}>
- <Icon name={isActionEntry(id) ? (allActionIcon(id) ?? "run") : "main-menu"} size={14} className={styles.rowIcon} />
+ <Icon
+ name={isActionEntry(id) ? (allActionIcon(id) ?? "run") : "main-menu"}
+ size={14}
+ className={styles.rowIcon}
+ />
<span className={styles.rowLabel}>{widgetTitle(id, items)}</span>
</div>
)}
diff --git a/src/workbench/Notifications.tsx b/src/workbench/Notifications.tsx
index d81306ffa..4622e2ee0 100644
--- a/src/workbench/Notifications.tsx
+++ b/src/workbench/Notifications.tsx
@@ -33,7 +33,11 @@ function subscribeWindowFocus(onChange: () => void) {
/** Whether the app window is active (focused). */
function useWindowActive(): boolean {
- return useSyncExternalStore(subscribeWindowFocus, () => document.hasFocus(), () => true);
+ return useSyncExternalStore(
+ subscribeWindowFocus,
+ () => document.hasFocus(),
+ () => true,
+ );
}
const DONT_SHOW_AGAIN = "Don't Show Again";
diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts
index c7f25dc15..6a5b7fb38 100644
--- a/src/workbench/contributions.ts
+++ b/src/workbench/contributions.ts
@@ -720,7 +720,14 @@ export function projectViewRoots(map: ReadonlyMap<string, ProjectViewRootContrib
// in `paths[0]`, the target directory (features/templates: file templates, http-client: HTTP Request).
export type ContextMenuId =
- "editor" | "projectView" | "editorTab" | "editorGutter" | "openIn" | "stopProcess" | "selectIn" | "new";
+ | "editor"
+ | "projectView"
+ | "editorTab"
+ | "editorGutter"
+ | "openIn"
+ | "stopProcess"
+ | "selectIn"
+ | "new";
export interface MenuGroupContext {
/** Files / directories the menu is for (absolute paths; a virtual URI for virtual documents). */
diff --git a/src/workbench/mainToolbar.ts b/src/workbench/mainToolbar.ts
index e05a8d778..b0281eab9 100644
--- a/src/workbench/mainToolbar.ts
+++ b/src/workbench/mainToolbar.ts
@@ -24,13 +24,20 @@ export interface ToolbarLayout {
export const isActionEntry = (id: string) => id.startsWith(ACTION_PREFIX);
export const entryAction = (id: string) => id.slice(ACTION_PREFIX.length);
-const byPriority = (a: TitleItemContribution, b: TitleItemContribution) => a.priority - b.priority || a.id.localeCompare(b.id);
+const byPriority = (a: TitleItemContribution, b: TitleItemContribution) =>
+ a.priority - b.priority || a.id.localeCompare(b.id);
/** Widgets in their default place (built-ins included), by side. */
function defaultWidgets(items: Iterable<TitleItemContribution>): { left: string[]; right: string[] } {
const all = [...items];
- const left = all.filter((i) => i.align === "left").sort(byPriority).map((i) => i.id);
- const right = all.filter((i) => i.align === "right").sort(byPriority).map((i) => i.id);
+ const left = all
+ .filter((i) => i.align === "left")
+ .sort(byPriority)
+ .map((i) => i.id);
+ const right = all
+ .filter((i) => i.align === "right")
+ .sort(byPriority)
+ .map((i) => i.id);
return { left: [PROJECT_WIDGET, ...(left.includes(VCS_WIDGET) ? [] : [VCS_WIDGET]), ...left], right };
}
@@ -62,7 +69,10 @@ export function resolveToolbar(
}
/** The full editable layout (Customize Main Toolbar dialog). */
-export function editableToolbar(saved: MainToolbarSettings | null | undefined, items: Iterable<TitleItemContribution>): ToolbarLayout {
+export function editableToolbar(
+ saved: MainToolbarSettings | null | undefined,
+ items: Iterable<TitleItemContribution>,
+): ToolbarLayout {
const list = [...items];
const { left, right } = resolveToolbar(saved, list);
return { left, right, hidden: saved ? [...(saved.hidden ?? [])] : [] };
@@ -84,7 +94,10 @@ export function toggleWidget(layout: ToolbarLayout, id: string, defaultSide: "le
right: layout.right.filter((x) => x !== id),
hidden: [...layout.hidden.filter((x) => x !== id), ...(isActionEntry(id) ? [] : [id])],
};
- const side = defaultSide === "left" ? { left: [...layout.left, id], right: layout.right } : { left: layout.left, right: [...layout.right, id] };
+ const side =
+ defaultSide === "left"
+ ? { left: [...layout.left, id], right: layout.right }
+ : { left: layout.left, right: [...layout.right, id] };
return { ...side, hidden: layout.hidden.filter((x) => x !== id) };
}
diff --git a/src/workbench/quickSwitch.ts b/src/workbench/quickSwitch.ts
index 03c4d5696..bb1485e0a 100644
--- a/src/workbench/quickSwitch.ts
+++ b/src/workbench/quickSwitch.ts
@@ -42,7 +42,12 @@ export function keymapItems(keymapId: string, customKeymaps: string[]): MenuItem
export function colorSchemeItems(current: string | undefined): MenuItem[] {
const value = current && SCHEMES.some((s) => s.id === current) ? current : "theme-default";
return [
- { id: "scheme.theme-default", label: "Theme default", checked: value === "theme-default", run: () => void setGlobal("editor.colorScheme", "theme-default", "color scheme") },
+ {
+ id: "scheme.theme-default",
+ label: "Theme default",
+ checked: value === "theme-default",
+ run: () => void setGlobal("editor.colorScheme", "theme-default", "color scheme"),
+ },
...SCHEMES.map<MenuItem>((s) => ({
id: `scheme.${s.id}`,
label: s.name,
@@ -72,7 +77,11 @@ export function keymapState(): { keymapId: string; customs: string[] } {
export function quickSwitchItems(): MenuItem[] {
const { keymapId, customs } = keymapState();
return [
- { id: "qs.scheme", label: "Editor Color Scheme", submenu: colorSchemeItems(useProject.getState().settings?.editor?.colorScheme) },
+ {
+ id: "qs.scheme",
+ label: "Editor Color Scheme",
+ submenu: colorSchemeItems(useProject.getState().settings?.editor?.colorScheme),
+ },
{ id: "qs.keymap", label: "Keymap", submenu: keymapItems(keymapId, customs) },
{ id: "qs.viewMode", label: "View Mode", submenu: VIEW_MODE_ITEMS },
{ id: "qs.theme", label: "Theme", submenu: themeItems() },
diff --git a/src/workbench/theme.ts b/src/workbench/theme.ts
index 9350b4952..487840ccd 100644
--- a/src/workbench/theme.ts
+++ b/src/workbench/theme.ts
@@ -188,7 +188,8 @@ export async function setTheme(next: ThemeSetting) {
try {
let settings = await call(commands.settingsSet("global", "appearance.theme", JSON.stringify(next)));
// An explicit choice ends "Sync with OS", as in IDEA.
- if (settings.appearance?.syncWithOs) settings = await call(commands.settingsSet("global", "appearance.syncWithOs", "false"));
+ if (settings.appearance?.syncWithOs)
+ settings = await call(commands.settingsSet("global", "appearance.syncWithOs", "false"));
useProject.setState({ settings });
useThemeOverride.setState({ theme: null });
} catch {
diff --git a/src/workbench/toolwindows/actions.ts b/src/workbench/toolwindows/actions.ts
index d1d8380ab..98195279f 100644
--- a/src/workbench/toolwindows/actions.ts
+++ b/src/workbench/toolwindows/actions.ts
@@ -53,7 +53,11 @@ function layoutActions(): Action[] {
const pick = (title: string) =>
chooseItem({ title, items: layoutNames(), empty: "No saved layouts. Use Save Current Layout as… first." });
const free = (current?: string) => (v: string) =>
- !v.trim() ? "Enter a layout name" : v.trim() !== current && layoutNames().includes(v.trim()) ? "A layout with this name exists" : null;
+ !v.trim()
+ ? "Enter a layout name"
+ : v.trim() !== current && layoutNames().includes(v.trim())
+ ? "A layout with this name exists"
+ : null;
return [
{
id: "layout.save",
@@ -105,7 +109,13 @@ function layoutActions(): Action[] {
run: async () => {
const from = await pick("Rename Layout");
if (!from) return;
- const to = await promptInput({ title: "Rename Layout", label: "New name:", initial: from, okLabel: "Rename", validate: free(from) });
+ const to = await promptInput({
+ title: "Rename Layout",
+ label: "New name:",
+ initial: from,
+ okLabel: "Rename",
+ validate: free(from),
+ });
if (to) renameLayout(from, to);
},
},
@@ -116,7 +126,15 @@ function layoutActions(): Action[] {
when: "toolWindowLayoutsSaved",
run: async () => {
const name = await pick("Delete Layout");
- if (name && (await confirm({ title: "Delete Layout", message: tx`Delete the layout '${name}'?`, ok: "Delete", icon: "warning" })))
+ if (
+ name &&
+ (await confirm({
+ title: "Delete Layout",
+ message: tx`Delete the layout '${name}'?`,
+ ok: "Delete",
+ icon: "warning",
+ }))
+ )
deleteLayout(name);
},
},
diff --git a/src/workbench/toolwindows/layouts.test.ts b/src/workbench/toolwindows/layouts.test.ts
index 25bb7e610..5f243e22f 100644
--- a/src/workbench/toolwindows/layouts.test.ts
+++ b/src/workbench/toolwindows/layouts.test.ts
@@ -83,7 +83,10 @@ describe("tool window layouts", () => {
saveLayout("Kept");
_reloadLayouts();
expect(layoutNames()).toEqual(["Kept"]);
- localStorage.setItem("openidea.toolWindowLayouts.v1", JSON.stringify({ layouts: [{ name: "" }, { nope: 1 }, { name: "X", layout: 5 }] }));
+ localStorage.setItem(
+ "openidea.toolWindowLayouts.v1",
+ JSON.stringify({ layouts: [{ name: "" }, { nope: 1 }, { name: "X", layout: 5 }] }),
+ );
_reloadLayouts();
expect(layoutNames()).toEqual(["X"]);
});
diff --git a/templates/theme-plugin/README.md b/templates/theme-plugin/README.md
index a39233550..63f9a27a2 100644
--- a/templates/theme-plugin/README.md
+++ b/templates/theme-plugin/README.md
@@ -35,16 +35,16 @@ The folder is the package. To share it, publish the folder as a Git repository
or a zip that users extract.
1. In OpenIDEA open **Settings › Plugins**, click the gear menu and choose
- **Install Plugin from Disk…** (or run the *Install Plugin from Disk…*
+ **Install Plugin from Disk…** (or run the _Install Plugin from Disk…_
action), then pick the folder that contains `plugin.toml`.
-2. Select the plugin in the *Installed* tab and press **Apply** next to the theme.
+2. Select the plugin in the _Installed_ tab and press **Apply** next to the theme.
3. **Use Default Theme** in the same place goes back to the built-in theme.
## Iterate
Put (or symlink) the folder in `<project>/.openidea/plugins/` of an open
-project. It loads as a *dev* plugin, and **Reload** in Settings › Plugins (or
-the *Reload Plugins* action) re-reads your edits without reinstalling. Invalid
+project. It loads as a _dev_ plugin, and **Reload** in Settings › Plugins (or
+the _Reload Plugins_ action) re-reads your edits without reinstalling. Invalid
JSON or values are reported in Settings › Plugins with the file and line.
## Licence
diff --git a/vite.config.ts b/vite.config.ts
index b0b8c3506..8464cbc4f 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -12,7 +12,10 @@ export default defineConfig(() => ({
alias: [
{ find: "@", replacement: fileURLToPath(new URL("./src", import.meta.url)) },
// `invoke` with remote-development routing (src/platform/tauriCore.ts).
- { find: /^@tauri-apps\/api\/core$/, replacement: fileURLToPath(new URL("./src/platform/tauriCore.ts", import.meta.url)) },
+ {
+ find: /^@tauri-apps\/api\/core$/,
+ replacement: fileURLToPath(new URL("./src/platform/tauriCore.ts", import.meta.url)),
+ },
],
},
// Tauri: keep Rust errors visible, fixed port, don't watch the backend.