Compare commits

..
Author SHA1 Message Date
l0ng-ai 7f5403ba8a fix(database): table tabs keep their filter, sort and page when switching tabs
Table editor tabs unmounted when another tab was shown, so their WHERE / ORDER BY
text, paging and unsubmitted edits were lost and the rows were queried again.
Table tabs are now kept alive like other editors, and the view state (filter,
sort, page) is remembered per table so a tab that is closed and reopened, or
dropped from the kept set, starts from the same view.

Fixes #4158
2026-11-18 17:47:09 +08:00
Bert Verhelstandbertyhell 10d39e14ca feat(php): align key-value pairs and consecutive assignments when formatting (#4045)
Settings › Editor › Code Style › PHP gets an Alignment section with Align key-value pairs (=> in multi-line arrays) and Align consecutive assignments (= in assignment statements on consecutive lines), both off by default. The backend applies them after whichever formatter ran (language server, PHP-CS-Fixer or a plugin formatter), for Reformat Code, format on save and the Reformat dialog; a selection changes only its lines. Alignment walks the PHP tree-sitter tree per array and statement list, so operators inside strings, comments, heredocs, foreach, arrow functions, match and default parameters are never touched.

Closes #3889

Co-authored-by: bertyhell <[email protected]>
2026-11-18 17:42:39 +08:00
l0ng-ai 101890ab4c fix(mcp): execute_run_configuration resolves a Java application's classpath (#4215)
MCP runs started a JVM application configuration as written, so ${classpath} reached java literally and the main class was not found. Application and Spring Boot configurations now go through the Run tool window's launch preparation (ops::java::resolve_launch): build per the configuration's policy (including the delegated Maven build), resolve ${classpath} / ${testClasspath}, the module path and the module's JDK, find a missing module from the main class, and stop on compile errors unless the policy continues on errors. Before-launch runs of such configurations are resolved the same way.

Fixes #4127
2026-11-18 17:20:47 +08:00
usong 86778d259f fix(editor): locate Lombok accessors and Java fields in library sources (#4190)
Go to Definition into a dependency's Lombok entity landed on the class header or the @Getter/@Setter annotation: library source lookup recognized Java methods but not fields, and never mapped a generated get/set/is accessor back to its field. Java field declarations (with or without an initializer) are now located, accessors map to their field when no method of that name is declared, and a jdt: library class uses the source declaration only when jdtls' range does not name the member, so overloads keep jdtls' exact range.

Closes #4186

Co-authored-by: usongon <[email protected]>
2026-11-18 17:12:47 +08:00
Bin 59c39a7e77 fix(editor): collapse multiline imports after the import keyword (#4170)
An import group whose first statement spans several lines folded from the end of its header line, leaving the first specifier visible. The fold now starts after the import keyword, so the editor shows `import …`, and the gutter finds an imports fold that starts inside its header line. Go and Rust delimiter handling is unchanged.

Co-authored-by: ffgenius <[email protected]>
2026-11-18 17:08:22 +08:00
Muuandmuutot 4d45ddc5a5 fix(editor): a fold click can miss folds that arrived asynchronously (#4165)
CodeMirror's fold gutter rebuilds its chevrons only on document, viewport or language changes, but backend folding ranges arrive through setBackendFolds, so a chevron could sit at a stale line and a click did nothing. The placeholder chip resolved its fold through the clicked line block, which can miss a fold starting at a line boundary (a Python docstring, an Allman header). The gutter now rebuilds whenever the backend fold field changes, and the chip resolves the fold at its own position, falling back to CodeMirror's handler.

Closes #4082

Co-authored-by: muutot <[email protected]>
2026-11-18 17:06:47 +08:00
Bert Verhelstandbertyhell bfd6f01471 perf(markdown): sanitize only the changed blocks when the preview re-renders (#4041)
The Markdown preview re-sanitized the whole document with DOMPurify on every settled edit. It now caches each block's sanitized HTML and sanitizes only the blocks an edit changed; a block whose markup carries into the following blocks (unclosed tags, comments, form state) falls back to sanitizing the whole document, so the output is the same.

Part of #3940

Co-authored-by: bertyhell <[email protected]>
2026-11-18 17:04:44 +08:00
Bert Verhelstandbertyhell 895d042dd7 perf(problems): rebuild only the changed file's Problems entries per diagnostics update (#4040)
A diagnostics event for one file made the Problems view merge, filter and sort every file's diagnostics again, and the tab header and tool window badge recounted every error in the workspace. Each file's merged list and Problems node are now cached by its sources map (replaced only when that file changes), and the store keeps project severity counts up to date per event, recomputing them on a profile change. Output is unchanged.

Part of #3937

Co-authored-by: bertyhell <[email protected]>
2026-11-18 17:04:39 +08:00
Bert Verhelstandbertyhell eb37d9e96a perf(search): claim the match budget while a file is searched, not after it (#4043)
Each file claimed its matches from the shared budget only after it was fully searched, so a broad Find in Files query over dense files could build up to the whole budget once per walker thread and throw most of it away. Files now claim matches in batches of 64 as they find them; a binary file gives its claim back, and a non-UTF-8 file searched again as decoded text fills its byte search's claim. When the limit is hit, exactly the budget is returned. Adds a dense-files bench with a budget.

Part of #3939

Co-authored-by: bertyhell <[email protected]>
2026-11-18 16:58:56 +08:00
Bert Verhelstandbertyhell dc8ae96206 perf(text): diff a document without copying its whole rope (#4039)
Document::diff copied the whole rope into a String and counted UTF-16 units across the unchanged prefix before trimming the common ends. The common ends are now found by walking the rope's chunks against the new text, only the changed middle is copied, and the prefix's UTF-16 offset comes from the rope's metadata. The trimmed (prefix, suffix) is unchanged, so the change sets are too. Adds a 5 MB one-edit diff bench with a budget.

Part of #3938

Co-authored-by: bertyhell <[email protected]>
2026-11-18 16:57:29 +08:00
l0ng-ai e70bca39ee fix(editor): autosave leaves a file changed on disk after an edit (#4197)
After an external change to a file whose buffer had unsaved edits, the next autosave wrote the buffer over the disk change despite the conflict warning. The document store now remembers the conflict and the new doc_autosave command declines to write such a buffer; an explicit save still overwrites and a reload clears the conflict.

Fixes #4115
2026-11-18 16:55:49 +08:00
l0ng-ai 2fe09e73f5 fix(editor): a document closed with changes no longer counts as unsaved (#4196)
Closing a modified document with Don't Save left the backend dirty flag set, so the exit guard asked about it again on Exit. The document store now reports a buffer clean when it is closed.

Fixes #4118
2026-11-18 16:54:23 +08:00
l0ng-ai b921de184b fix(editor): keep a modified file open when its last tab closes without autosave (#4191)
With autosave off, closing the only tab of a modified file disposed its document and lost the edits. As in IDEA, DocumentManager.release keeps a dirty (non-untitled) document open without a tab: reopening shows the edits, Save All and the exit check still cover them; also when autosave on close fails.

Fixes #4116
2026-11-18 16:43:51 +08:00
l0ng-ai 23739c90c7 fix(run): Run starts another instance of a configuration that allows multiple instances (#4187)
run.run reran the selected configuration's running session even with Allow multiple instances, stopping the process. As in IDEA (Rerun/Stop only for configurations that don't run in parallel), such a configuration keeps Run/Debug in the toolbar and Run starts another instance; a tab's Rerun still restarts its session.

Fixes #4148
2026-11-18 16:39:53 +08:00
LU XIANGRUIandwildcatDownstairs 923325aeae feat(color-scheme): foreground for Identifier under caret (#4135)
Identifier under caret and Identifier under caret (write) can now set a Foreground, as in IDEA; imported .icls schemes carry it too. The highlight mark wraps the syntax and semantic token spans, so the colour is applied with the inherited -webkit-text-fill-color: unset, the declaration drops and tokens keep their syntax colours; find matches, selection, links, inlay hints and fold placeholders keep their own colours. Multi-line highlights colour only the highlighted text, not the indent.

Closes #4109

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-18 16:37:49 +08:00
LU XIANGRUIandwildcatDownstairs d7351dca1d feat(run): Python run configuration type (#4126)
Adds PyCharm's Python configuration: a script or a -m module with arguments, command (interpreter or uv/poetry) and runner arguments; a plain python/python3 runs on the project interpreter as before. Existing python configurations (detected, imported, run from the context menu) open in this form when their command line maps to a script or module. projectPython prefers a detected python configuration over one made by hand.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-18 16:36:56 +08:00
l0ng-ai 8959f7aa5d fix(debugger): answer the debuggee terminal's cursor position query (#4185)
Python debugging on Windows timed out waiting for debugpy's launcher: since #3374 it runs through runInTerminal on a ConPTY, which asks the terminal for the cursor position (ESC[6n) and starts the program only after the answer; the debug console never answered. The runInTerminal output forwarder now answers cursor position queries and drops them from the output. A runInTerminal test now runs on Windows too.

Fixes #4123
Fixes #4141
2026-11-18 16:34:54 +08:00
l0ng-ai 5e4f187107 fix(settings): detect SDKs and install tools from Settings without a project (#4184)
SDK combos in Settings opened from the Welcome screen loaded forever: sdk_detect and the interpreter/tool commands were Trusted and called require_trust, which refuse a window without a project, and useDetected kept loading after a failed detection. They are now OutsideRestricted with Host::require_trust_if_project (still refused in Restricted Mode; commands that take a project path keep the strict check), and a failed detection ends loading.

Closes #4110
2026-11-18 16:34:49 +08:00
l0ng-ai aebd26bd7d feat(maven): setting to download dependency sources on import (#4182)
Settings › Build Tools › Maven › Automatically download sources maps to jdtls java.maven.downloadSources (previously always on in languages/java.toml). Off by default, as in IDEA's Maven › Importing: library classes open decompiled and the Download Sources banner fetches one library's sources on demand.

Closes #4097
2026-11-18 16:34:44 +08:00
l0ng-aiandClaude c43a6169be ci: run only the jobs and smoke languages a pull request can affect (#4172)
CI's Changes job now decides each job on its own: Plugins on the plugin
workspaces, Cargo deny on manifests, the remote server build skips
desktop-, SDK- and test-only changes, Frontend skips backend-only changes
(a new Text catalog job runs the one test that reads Rust sources), and
E2E runs on the browser app's own sources.

Language smoke picks its matrix from the changed files: a language's
fixture, definition or JDT LS bundle runs that language, crates the
smoke doesn't exercise and crate tests run none. java/ now triggers it.

Co-authored-by: Claude <[email protected]>
2026-11-18 16:23:00 +08:00
LU XIANGRUIandwildcatDownstairs c4836f6cd8 fix(viewers): Markdown preview follows File Types associations (#4139)
The Editor / Editor and Preview / Preview layouts were gated on a fixed extension list, while highlighting and LSP follow the language the backend detects from Settings › File Types. A file associated with Markdown (e.g. *.mmd) or overridden to Markdown now gets the preview, a file moved away from Markdown loses it, and open tabs update when File Types change. The check reuses hasFileType from #4144; the live-text contribution keys on the document's language.

Refs #4099

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-18 16:14:32 +08:00
l0ng-ai 02235cae04 test(heap): wait for the background cleanup in the stuck-capture shutdown test (#4169)
shutdown_within waits only briefly for the snapshot-directory cleanup and lets it finish in the background; on a busy CI runner the stuck-capture test asserted before it was done. The test now waits up to 10 s for the directory to go.
2026-11-18 16:14:09 +08:00
LU XIANGRUIandwildcatDownstairs fcef18048a fix(web): HTML preview follows File Types associations (#4144)
The browser bar, Built-in Preview and Open in Browser were gated on a fixed extension list, and the built-in server chose Content-Type by extension, so a file associated with HTML in Settings › File Types (or via Override File Type) had no preview, and one moved away from HTML kept it. The frontend now decides with hasFileType (override, user patterns, then built-in extensions not removed — the order of LanguageRegistry::detect), open tabs update when File Types change, and web_url serves a file the backend detects as HTML as text/html (also fixes .shtml being served as application/octet-stream).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-18 16:12:54 +08:00
Bin d72363b6ba fix(lsp): include workspace folder in ESLint configuration (#4145)
vscode-eslint resolves workingDirectory {mode: auto} from settings.workspaceFolder; without it the server falls back to the linted file's directory, so resolvers configured relative to the project (eslint-import-resolver-alias './src') looked under src/src and reported import/no-unresolved. The full workspace/configuration answer for eslint now carries the server root as workspaceFolder, as VS Code's client does. Other servers' answers are unchanged.

Closes #4143

Co-authored-by: ffgenius <[email protected]>
2026-11-18 16:11:18 +08:00
l0ng-ai 4ab4e0b44f fix(ci): use a Windows-absolute devshell path in the project environment test (#4149)
The project environment test's PATH entry /nix/store/x-devshell/bin has no drive letter on Windows, so the tool search path, which keeps absolute entries only, dropped it and the test failed there. The test uses C:\nix\store\x-devshell\bin on Windows.
2026-11-18 15:11:25 +08:00
109 changed files with 3331 additions and 242 deletions

No files matched your search

+65 -15
View File
@@ -32,7 +32,12 @@ jobs:
pull-requests: read
outputs:
rust: ${{ steps.classify.outputs.rust }}
server: ${{ steps.classify.outputs.server }}
plugins: ${{ steps.classify.outputs.plugins }}
deny: ${{ steps.classify.outputs.deny }}
frontend: ${{ steps.classify.outputs.frontend }}
e2e: ${{ steps.classify.outputs.e2e }}
catalog: ${{ steps.classify.outputs.catalog }}
steps:
- id: classify
env:
@@ -40,26 +45,55 @@ jobs:
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
jobs="rust server plugins deny frontend e2e catalog"
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
echo "rust=true" >> "$GITHUB_OUTPUT"
echo "frontend=true" >> "$GITHUB_OUTPUT"
for job in $jobs; do echo "$job=true" >> "$GITHUB_OUTPUT"; done
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# A change to CI itself runs everything.
ci='^\.github/(workflows/ci\.yml|actions/)'
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|evals/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
# A job runs when any changed file falls outside the paths that can't affect it.
rust=false
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
frontend=false
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
echo "rust=$rust frontend=$frontend"
echo "rust=$rust" >> "$GITHUB_OUTPUT"
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
# Plugin web pages are their own pnpm projects, checked by the Plugins job only.
plugin_web='^plugins/official/[^/]+/web-src/'
# Paths the frontend checks never read...
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
# ...except these, which frontend tests and e2e fixtures load.
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# What the browser app and its e2e tests are built from.
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
plugin_ws='^(sdk/|plugins/|wit/|crates/ide-plugin/tests/fixtures/|rust-toolchain(\.toml)?$)'
# Never compiled into the openidea-server binary.
not_server='^(src-tauri/|sdk/|fixtures/|crates/[^/]+/(tests|benches)/)'
deps='(^|/)Cargo\.(toml|lock)$|^deny\.toml$'
# The text catalog test reads the string literals of every Rust source.
rust_source='^(crates|src-tauri/src)/.*\.rs$'
any() { grep -Eq "$1" files.txt; }
outside() { [ -n "$(grep -Ev "$1" files.txt || true)" ]; }
set_job() { echo "$1=$2" | tee -a "$GITHUB_OUTPUT"; }
if any "$ci"; then
for job in $jobs; do set_job "$job" true; done
exit 0
fi
on() { if "${@:2}"; then set_job "$1" true; else set_job "$1" false; fi; }
rust_build() { outside "$1" || any "$embedded"; }
web_checks() { outside "$docs|$plugin_web|$backend" || any "$read_by_web"; }
catalog_only() { ! web_checks && any "$rust_source"; }
on rust rust_build "$docs|$web|$plugin_web"
on server rust_build "$docs|$web|$plugin_web|$not_server"
on plugins any "$plugin_ws"
on deny any "$deps"
on frontend web_checks
on e2e any "$app"
on catalog catalog_only
rust:
name: Rust (${{ matrix.os }})
@@ -111,7 +145,7 @@ jobs:
server:
name: Remote server (linux musl)
needs: changes
if: needs.changes.outputs.rust == 'true'
if: needs.changes.outputs.server == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
steps:
@@ -129,7 +163,7 @@ jobs:
plugins:
name: Plugins (SDK, official, fixtures)
needs: changes
if: needs.changes.outputs.rust == 'true'
if: needs.changes.outputs.plugins == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
@@ -181,7 +215,7 @@ jobs:
deny:
name: Cargo deny
needs: changes
if: needs.changes.outputs.rust == 'true'
if: needs.changes.outputs.deny == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
@@ -210,10 +244,26 @@ jobs:
- run: pnpm test
- run: pnpm build
# A backend-only change can still drop a string the text catalog uses: run that one test.
catalog:
name: Text catalog
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
needs: changes
if: needs.changes.outputs.frontend == 'true'
if: needs.changes.outputs.e2e == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
strategy:
+67 -1
View File
@@ -15,6 +15,7 @@ on:
- "crates/**"
- "languages/**"
- "fixtures/**"
- "java/**"
- "Cargo.toml"
- "Cargo.lock"
- "src/features/run/**"
@@ -41,12 +42,77 @@ env:
CARGO_INCREMENTAL: 0
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
# JDT LS bundle runs that language; crates the smoke doesn't exercise and other crates' tests
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
outputs:
languages: ${{ steps.classify.outputs.languages }}
steps:
- id: classify
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
all="typescript python rust go java kotlin php c cpp"
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
crates/*/tests/* | crates/*/benches/*) ;;
fixtures/ts-app/*) langs+=" typescript" ;;
fixtures/python-app/*) langs+=" python" ;;
fixtures/rust-app/*) langs+=" rust" ;;
fixtures/go-app/*) langs+=" go" ;;
fixtures/java-app/*) langs+=" java" ;;
fixtures/kotlin-gradle/*) langs+=" kotlin" ;;
fixtures/php-app/*) langs+=" php" ;;
fixtures/c-app/*) langs+=" c cpp" ;;
fixtures/*) ;;
languages/typescript.toml | languages/typescriptreact.toml | languages/javascript.toml | languages/javascriptreact.toml) langs+=" typescript" ;;
languages/python.toml) langs+=" python" ;;
languages/rust.toml) langs+=" rust" ;;
languages/go.toml | languages/gomod.toml | languages/gowork.toml) langs+=" go" ;;
languages/java.toml) langs+=" java" ;;
languages/kotlin.toml) langs+=" kotlin" ;;
languages/php.toml) langs+=" php" ;;
languages/c.toml) langs+=" c" ;;
languages/cpp.toml) langs+=" cpp" ;;
languages/*) ;;
java/kotlin-bridge/*) langs+=" kotlin" ;;
java/*) langs+=" java kotlin" ;;
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
esac
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
needs: changes
if: needs.changes.outputs.languages != '[]'
strategy:
fail-fast: false
matrix:
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
language: ${{ fromJSON(needs.changes.outputs.languages) }}
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
timeout-minutes: 40
+6
View File
@@ -446,6 +446,12 @@ pub struct LanguageCodeStyle {
/// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>,
/// PHP: align `=>` in multi-line arrays after formatting (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub align_key_value_pairs: Option<bool>,
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
+4
View File
@@ -1504,6 +1504,10 @@ pub struct MavenSettings {
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
/// Download `-sources.jar` of dependencies when the Java language server imports the
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
pub download_sources: bool,
}
impl MavenSettings {
+42 -6
View File
@@ -912,7 +912,7 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
/// A `runInTerminal` program and the pseudo-terminal it runs in.
pub(crate) struct ProgramTerminal {
writer: ide_core::input::InputWriter,
writer: Arc<ide_core::input::InputWriter>,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
#[cfg_attr(not(unix), allow(dead_code))]
pid: Option<u32>,
@@ -1025,10 +1025,12 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
let _ = child.wait();
})
.map_err(|e| format!("terminal input worker: {e}"))?;
let writer = Arc::new(writer);
let pid = child.process_id();
forward_terminal_output(
s,
reader,
writer.clone(),
#[cfg(unix)]
wait_readable,
);
@@ -1043,10 +1045,35 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
Ok(json!({ "processId": pid }))
}
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept).
/// A terminal's cursor position query (DSR). ConPTY sends one when it starts and runs the program
/// only once the terminal answers; programs that lay out a prompt ask it too.
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
/// `chunk` without its cursor position queries, and how many there were.
pub(crate) fn take_cursor_queries(chunk: &[u8]) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(chunk.len());
let mut queries = 0;
let mut rest = chunk;
while let Some(at) = rest.windows(CURSOR_QUERY.len()).position(|w| w == CURSOR_QUERY) {
out.extend_from_slice(&rest[..at]);
rest = &rest[at + CURSOR_QUERY.len()..];
queries += 1;
}
out.extend_from_slice(rest);
(out, queries)
}
/// Length of the end of `pending` that may begin a cursor position query the next read completes.
pub(crate) fn partial_cursor_query(pending: &[u8]) -> usize {
(1..CURSOR_QUERY.len()).rev().find(|&n| pending.ends_with(&CURSOR_QUERY[..n])).unwrap_or(0)
}
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept). The debug
/// console is no terminal, so cursor position queries are answered here (top-left corner).
fn forward_terminal_output(
s: &Session,
mut reader: Box<dyn std::io::Read + Send>,
answer: Arc<ide_core::input::InputWriter>,
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) {
let session = s.id;
@@ -1078,11 +1105,20 @@ fn forward_terminal_output(
break;
}
}
// Keep incomplete UTF-8 sequences, and a `\r` that may start a `\r\n`, for the next chunk.
let mut valid = match std::str::from_utf8(&pending) {
Ok(_) => pending.len(),
let (rest, queries) = take_cursor_queries(&pending);
pending = rest;
for _ in 0..queries {
if let Err(e) = answer.write(b"\x1b[1;1R") {
tracing::warn!(%session, "debug terminal cursor position: {e}");
}
}
// Keep incomplete UTF-8 sequences, a `\r` that may start a `\r\n`, and the start of
// a cursor position query for the next chunk.
let keep = partial_cursor_query(&pending);
let mut valid = match std::str::from_utf8(&pending[..pending.len() - keep]) {
Ok(_) => pending.len() - keep,
Err(e) if e.error_len().is_none() => e.valid_up_to(),
Err(_) => pending.len(),
Err(_) => pending.len() - keep,
};
if valid > 0 && pending[valid - 1] == b'\r' {
valid -= 1;
+38
View File
@@ -1010,6 +1010,44 @@ async fn run_in_terminal_spawns_debuggee() {
assert!(response["body"]["processId"].as_u64().unwrap() > 0);
}
/// The debug console answers a terminal's cursor position query: ConPTY asks one before it runs
/// the program at all (Windows debuggees never started), and programs that lay out a prompt ask too.
#[tokio::test]
async fn run_in_terminal_answers_cursor_position_queries() {
#[cfg(unix)]
let program = vec![
"sh".into(),
"-c".into(),
r"stty -echo -icanon min 6; printf '\033[6n'; reply=$(dd bs=6 count=1 2>/dev/null); stty sane; case $reply in *'[1;1R') echo answered;; esac".into(),
];
#[cfg(windows)]
let program = vec!["cmd".into(), "/c".into(), "echo answered".into()];
let h = harness(Script { run_in_terminal: Some(program), ..Script::default() });
h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output.contains("answered"))).await;
let output: String = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } => Some(output.clone()),
_ => None,
})
.collect();
assert!(!output.contains("\x1b[6n"), "{output:?}");
}
#[test]
fn cursor_position_queries_are_taken_out_of_the_output() {
use crate::session::{partial_cursor_query, take_cursor_queries};
assert_eq!(take_cursor_queries(b"a\x1b[6nb\x1b[6n"), (b"ab".to_vec(), 2));
assert_eq!(take_cursor_queries(b"\x1b[0mtext"), (b"\x1b[0mtext".to_vec(), 0));
assert_eq!(partial_cursor_query(b"text\x1b["), 2);
assert_eq!(partial_cursor_query(b"text\x1b[6"), 3);
assert_eq!(partial_cursor_query(b"text\x1b[0m"), 0);
assert_eq!(partial_cursor_query(b"text"), 0);
}
#[cfg(unix)]
#[tokio::test]
async fn run_in_terminal_program_reads_typed_input() {
+198 -11
View File
@@ -2,9 +2,9 @@
use crate::Host;
use ide_core::event::NotifyLevel;
use ide_core::settings::{ExternalFormatter, LanguagesSettings};
use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Pos, Range, TextEdit};
use ide_language::LanguageConfig;
use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings};
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
use std::path::Path;
@@ -129,12 +129,101 @@ pub async fn format(
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let settings = project.settings.effective();
let alignment = php_alignment(&settings, &snap.language);
let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone()));
let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else {
return Ok(Vec::new());
};
let Some((language, text)) = original else {
return Ok(edits);
};
let syntax = host.syntax();
tokio::task::spawn_blocking(move || align_formatted(&syntax, &language, &text, edits, range, alignment))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// PHP Code Style › Align key-value pairs / Align consecutive assignments (off by default, as in PhpStorm).
fn php_alignment(settings: &Settings, language: &LanguageId) -> PhpAlignment {
let style = settings.editor.code_style.languages.get(language.as_str());
PhpAlignment {
key_value_pairs: style.and_then(|s| s.align_key_value_pairs).unwrap_or(false),
assignments: style.and_then(|s| s.align_consecutive_assignments).unwrap_or(false),
}
}
/// The formatter's `edits` to `text` followed by the alignment, as one set of edits to `text`.
/// With a `range`, only its lines (where the formatter left them) are aligned.
fn align_formatted(
syntax: &Syntax,
language: &LanguageId,
text: &str,
edits: Vec<TextEdit>,
range: Option<Range>,
alignment: PhpAlignment,
) -> IdeResult<Vec<TextEdit>> {
let mut formatted = ide_text::Document::new(text);
// Edits the editor has to sort out itself (overlapping ones) are passed on unaligned.
let Ok((changes, _)) = formatted.apply_edits(&edits) else {
return Ok(edits);
};
let lines = range.map(|range| {
let original = ide_text::Document::new(text);
let start = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.start), false));
let end = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.end), true));
let last = if end.col == 0 && end.line > start.line { end.line - 1 } else { end.line };
(start.line as usize, last as usize)
});
let Some(aligned) = syntax.align_php(language, &formatted.text(), lines, alignment) else {
return Ok(edits);
};
let original = ide_text::Document::new(text);
Ok(original
.diff(&aligned)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect())
}
/// Where UTF-16 `offset` of the text before `changes` ends up after them; inside a replaced
/// part, at its start or (`end`) its end.
fn map_offset(changes: &ChangeSet, offset: u32, end: bool) -> u32 {
let mut shift: i64 = 0;
for c in &changes.changes {
let inserted = c.insert.encode_utf16().count() as i64;
if c.to < offset || (c.to == offset && (c.from < c.to || end)) {
shift += inserted - i64::from(c.to - c.from);
} else if c.from < offset {
return (i64::from(c.from) + shift + if end { inserted } else { 0 }) as u32;
} else {
break;
}
}
(i64::from(offset) + shift) as u32
}
/// The edits of the formatter that handles the document; `None` when it doesn't run
/// (formatting on save is off for it).
async fn provider_edits(
host: &Host,
window: &str,
project: &crate::Project,
snap: ide_workspace::documents::DocumentInfo,
settings: Settings,
range: Option<Range>,
options: FormatOptions,
) -> IdeResult<Option<Vec<TextEdit>>> {
let doc = snap.id;
let language = project.languages.get(&snap.language);
if options.tool.is_none()
&& let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty())
{
if options.on_save && !settings.editor.format_on_save {
return Ok(Vec::new());
return Ok(None);
}
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
@@ -160,7 +249,8 @@ pub async fn format(
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
.map_err(|e| IdeError::internal(e.to_string()))?
.map(Some);
}
// A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files.
if options.tool.is_none()
@@ -168,7 +258,7 @@ pub async fn format(
&& let Some(fixer) = formatter::php_cs_fixer(&snap.path)
{
if options.on_save && !settings.editor.format_on_save {
return Ok(Vec::new());
return Ok(None);
}
host.require_trust(window)?;
if snap.read_only {
@@ -188,7 +278,7 @@ pub async fn format(
body: Some("PHP-CS-Fixer does not support selection formatting; formatted the whole file".into()),
});
}
return Ok(edits);
return Ok(Some(edits));
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
if let Some(tool) = selected
@@ -200,13 +290,13 @@ pub async fn format(
}
let Some(selected) = selected else {
if options.on_save && !settings.editor.format_on_save {
return Ok(Vec::new());
return Ok(None);
}
return project.lsp.format(doc, range, options).await;
return project.lsp.format(doc, range, options).await.map(Some);
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
return Ok(Vec::new());
return Ok(None);
}
host.require_trust(window)?;
if snap.read_only {
@@ -262,7 +352,7 @@ pub async fn format(
)),
});
}
edits.map_err(|e| e.with_tool(tool))
edits.map(Some).map_err(|e| e.with_tool(tool))
}
#[cfg(test)]
@@ -413,6 +503,103 @@ mod tests {
);
}
fn after(text: &str, edits: &[TextEdit]) -> String {
let mut doc = ide_text::Document::new(text);
doc.apply_edits(edits).unwrap();
doc.text()
}
fn whole_file(text: &str, formatted: &str) -> Vec<TextEdit> {
let doc = ide_text::Document::new(text);
doc.diff(formatted)
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(doc.offset_to_pos(c.from), doc.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect()
}
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
#[test]
fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() {
let php = LanguageId::new("php");
let mut settings = Settings::default();
assert_eq!(php_alignment(&settings, &php), PhpAlignment::default());
let style =
ide_core::editor_settings::LanguageCodeStyle { align_key_value_pairs: Some(true), ..Default::default() };
settings.editor.code_style.languages.insert("php".into(), style);
assert_eq!(php_alignment(&settings, &php), PhpAlignment { key_value_pairs: true, assignments: false });
assert_eq!(php_alignment(&settings, &LanguageId::new("javascript")), PhpAlignment::default());
}
#[test]
fn alignment_follows_the_formatter_edits_even_when_there_are_none() {
let syntax = Syntax::new();
let php = LanguageId::new("php");
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
let edits = align_formatted(&syntax, &php, text, Vec::new(), None, ALIGN).unwrap();
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
// The language server re-indents the array: the alignment applies to its result.
let text = "<?php\n$a = [\n'a' => 1,\n'bbb' => 2,\n];\n";
let formatted = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
let edits = align_formatted(&syntax, &php, text, whole_file(text, formatted), None, ALIGN).unwrap();
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
let unchanged = whole_file(text, formatted);
let off = align_formatted(&syntax, &php, text, unchanged.clone(), None, PhpAlignment::default()).unwrap();
assert_eq!(off, unchanged);
let overlapping = vec![
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 4)), new_text: "x".into() },
TextEdit { range: Range::new(Pos::new(1, 2), Pos::new(1, 6)), new_text: "y".into() },
];
let passed = align_formatted(&syntax, &php, text, overlapping.clone(), None, ALIGN).unwrap();
assert_eq!(passed, overlapping);
}
#[test]
fn a_selection_aligns_only_its_lines_whatever_the_formatter_changed() {
let syntax = Syntax::new();
let php = LanguageId::new("php");
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
);
let range = Range::new(Pos::new(1, 0), Pos::new(2, 9));
let aligned = align_formatted(&syntax, &php, text, Vec::new(), Some(range), ALIGN).unwrap();
assert_eq!(after(text, &aligned), "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
}
#[test]
fn offsets_map_through_changes() {
let changes = ChangeSet {
changes: vec![
ide_core::TextChange { from: 2, to: 2, insert: "ab".into() },
ide_core::TextChange { from: 5, to: 8, insert: "x".into() },
],
};
assert_eq!(map_offset(&changes, 0, false), 0);
assert_eq!(map_offset(&changes, 2, false), 2);
assert_eq!(map_offset(&changes, 2, true), 4);
assert_eq!(map_offset(&changes, 4, false), 6);
assert_eq!(map_offset(&changes, 6, false), 7);
assert_eq!(map_offset(&changes, 6, true), 8);
assert_eq!(map_offset(&changes, 8, false), 8);
assert_eq!(map_offset(&changes, 10, false), 10);
}
#[test]
fn ruff_ranges_are_one_based_unicode_columns() {
let text = ide_text::Document::new("😀x = 1\ny = 2\n");
+10
View File
@@ -253,6 +253,16 @@ impl Host {
self.project(window)?.require_trust()
}
/// [`Self::require_trust`] for IDE-wide toolchain work (SDK detection, tool installs) that
/// also runs from a window without a project, such as Settings opened from the Welcome
/// screen: there is no project there to trust.
pub fn require_trust_if_project(&self, window: &str) -> IdeResult<()> {
match self.project(window) {
Ok(project) => project.require_trust(),
Err(_) => Ok(()),
}
}
/// The window that owns what `window` starts.
pub fn owner_window<'a>(&self, window: &'a str) -> &'a str {
(self.owner)(window)
+216
View File
@@ -356,6 +356,13 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
t.drain(..cut);
}
});
let config = match resolve_jvm_application(call, config, errors).await? {
Ok(config) => config,
Err(reason) => {
errors.process_outputs.push(reason);
return Ok(false);
}
};
let info = crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await?;
let exit = wait_exit(call, info.id, None).await?.flatten();
if exit == Some(0) {
@@ -367,6 +374,177 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
Ok(false)
}
/// Run configuration kinds launched as a JVM main class (`JVM_APPLICATION_KINDS` in the UI).
const JVM_APPLICATION_KINDS: [&str; 2] = ["application", "spring-boot"];
const CLASSPATH: &str = "${classpath}";
const TEST_CLASSPATH: &str = "${testClasspath}";
/// `java` options whose value is the next argument (`parseJavaArgs` in the UI).
const JAVA_OPTIONS_WITH_VALUE: [&str; 13] = [
"-cp",
"-classpath",
"--class-path",
"-p",
"--module-path",
"--upgrade-module-path",
"--add-modules",
"--add-opens",
"--add-exports",
"--add-reads",
"--patch-module",
"--limit-modules",
"--enable-native-access",
];
/// The main class of `java` arguments and which classpath placeholder they use (`Some(true)`:
/// `${testClasspath}`; `None`: an explicit classpath or none).
fn java_main_class(args: &[String]) -> (Option<&str>, Option<bool>) {
let mut test = None;
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
if a == "-jar" {
return (None, test);
}
if matches!(a, "-cp" | "-classpath" | "--class-path") {
match args.get(i + 1).map(String::as_str) {
Some(CLASSPATH) => test = Some(false),
Some(TEST_CLASSPATH) => test = Some(true),
_ => {}
}
i += 2;
continue;
}
if JAVA_OPTIONS_WITH_VALUE.contains(&a) {
i += 2;
continue;
}
if !a.starts_with('-') {
return (Some(a), test);
}
i += 1;
}
(None, test)
}
/// `args` with the classpath placeholders replaced and the module path added (`resolveJavaCommand`).
fn resolved_java_args(args: &[String], info: &ide_lsp::jdtls::JavaLaunchInfo) -> Vec<String> {
let cp = info.class_paths.join(&info.path_list_separator);
let mut out = Vec::with_capacity(args.len() + 2);
if !info.module_paths.is_empty() && !args.iter().any(|a| a == "-p" || a == "--module-path") {
out.push("--module-path".to_owned());
out.push(info.module_paths.join(&info.path_list_separator));
}
out.extend(args.iter().map(|a| if a == CLASSPATH || a == TEST_CLASSPATH { cp.clone() } else { a.clone() }));
out
}
/// The module (relative to the project root) of a JVM source file: the part before
/// `src/<set>/<language>/` (`jvmModuleDir` without a build model).
fn jvm_module_of(rel: &str) -> Option<String> {
let rel = rel.replace('\\', "/");
let parts: Vec<&str> = rel.split('/').collect();
(0..parts.len().saturating_sub(3)).find_map(|i| {
(parts[i] == "src" && matches!(parts[i + 2], "java" | "kotlin" | "scala" | "groovy"))
.then(|| parts[..i].join("/"))
})
}
/// The module of a configuration saved without one, found from its main class's source
/// (`findJavaModule`): `None` unless exactly one module declares it.
async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>> {
let outer = main.split('$').next().unwrap_or(main);
let (pkg, simple) = outer.rsplit_once('.').unwrap_or(("", outer));
let mut names = vec![format!("{simple}.java"), format!("{simple}.kt")];
if let Some(stem) = simple.strip_suffix("Kt") {
names.push(format!("{stem}.kt"));
}
let mut modules = std::collections::BTreeSet::new();
for name in names {
for path in crate::ops::nav::find_files_named(&call.host(), call.window(), name).await? {
let path = std::path::PathBuf::from(path);
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let declared = text
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim())
.unwrap_or("");
if declared != pkg {
continue;
}
let rel = path.strip_prefix(call.root()).unwrap_or(&path).to_string_lossy().into_owned();
modules.insert(jvm_module_of(&rel).unwrap_or_default());
}
}
Ok((modules.len() == 1).then(|| modules.into_iter().next().unwrap_or_default()))
}
/// A JVM application configuration ready to start, as the Run tool window launches it:
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
return Ok(Ok(config));
}
let (main, test) = java_main_class(&config.args);
let Some(main) = main.map(str::to_owned) else {
return Ok(Err(format!("No main class in '{}'", config.name)));
};
let module = match config.extras.module.clone() {
Some(module) => module,
None => match find_java_module(call, &main).await? {
Some(module) => module,
None => return Ok(Err(format!("Cannot determine the module for main class '{main}'"))),
},
};
let policy = config.extras.build_policy.unwrap_or_default();
let cancel = ide_core::CancellationToken::new();
let host = call.host();
let info = crate::ops::java::resolve_launch(
&host,
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
policy,
&cancel,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
if matches!(info.build, Some(JavaBuildStatus::Failed | JavaBuildStatus::WithErrors))
&& policy != ide_run::BuildPolicy::MakeAndContinueOnErrors
{
for e in &info.errors {
errors.errors.push(format!(
"{}:{}: {}",
std::path::PathBuf::from(e.path.clone()).display(),
e.line,
e.message
));
}
let reason = if info.build == Some(JavaBuildStatus::Failed) {
format!("Build failed; '{}' was not started.", config.name)
} else {
format!("Build has compile errors; '{}' was not started.", config.name)
};
return Ok(Err(reason));
}
if test.is_some() && info.class_paths.is_empty() {
return Ok(Err("The classpath is empty: is the module imported by the Java language server?".to_owned()));
}
let args = resolved_java_args(&config.args, &info);
let command = match (&info.java_exec, config.command.as_str()) {
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
Ok(Ok(RunConfig { command, args, ..config }))
}
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
@@ -608,6 +786,10 @@ one by one",
if let Some(reason) = before_launch(&call, &config, &configs, &mut Vec::new(), &mut errors).await? {
return Err(execution_failed(&[errors.text(), Some(reason)]));
}
let config = match resolve_jvm_application(&call, config, &mut errors).await? {
Ok(config) => config,
Err(reason) => return Err(execution_failed(&[errors.text(), Some(reason)])),
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let sink = collector.clone();
@@ -684,6 +866,40 @@ provided, values are merged over existing env.",
mod tests {
use super::*;
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|a| (*a).to_owned()).collect()
}
#[test]
fn java_arguments_name_the_main_class_and_classpath_placeholder() {
let run = strings(&["-Xmx1g", "-cp", CLASSPATH, "--add-opens", "a/b=ALL-UNNAMED", "com.example.App", "x"]);
assert_eq!(java_main_class(&run), (Some("com.example.App"), Some(false)));
assert_eq!(java_main_class(&strings(&["-classpath", TEST_CLASSPATH, "T"])), (Some("T"), Some(true)));
assert_eq!(java_main_class(&strings(&["-cp", "lib/*", "Main"])), (Some("Main"), None));
assert_eq!(java_main_class(&strings(&["-jar", "app.jar"])), (None, None));
}
#[test]
fn resolved_java_arguments_replace_the_placeholder_and_add_the_module_path() {
let info = ide_lsp::jdtls::JavaLaunchInfo {
class_paths: vec!["/p/target/classes".into(), "/m2/a.jar".into()],
module_paths: vec!["/m2/mod.jar".into()],
path_list_separator: ":".into(),
..Default::default()
};
assert_eq!(
resolved_java_args(&strings(&["-cp", CLASSPATH, "App"]), &info),
strings(&["--module-path", "/m2/mod.jar", "-cp", "/p/target/classes:/m2/a.jar", "App"])
);
}
#[test]
fn a_source_file_belongs_to_the_module_before_its_source_set() {
assert_eq!(jvm_module_of("repro-dto/src/main/java/com/example/App.java").as_deref(), Some("repro-dto"));
assert_eq!(jvm_module_of("src/test/kotlin/AppTest.kt").as_deref(), Some(""));
assert_eq!(jvm_module_of("scripts/App.java"), None);
}
fn config() -> RunConfig {
RunConfig {
id: "user:x".into(),
+13
View File
@@ -70,6 +70,18 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
/// An automatic save: `false` (nothing written) when the file changed on disk after the
/// buffer was edited, which only an explicit save overwrites.
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
Ok(saved)
}
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
@@ -109,6 +121,7 @@ ide_command::domain!(
doc_open,
doc_open_untitled,
doc_save,
doc_autosave,
doc_save_all,
doc_save_as,
doc_snapshot,
+5
View File
@@ -311,6 +311,11 @@ async fn shutdown_does_not_wait_forever_for_a_stuck_capture() {
shutdown_within(&f.host, std::time::Duration::from_millis(200)).await;
assert!(started.elapsed() < std::time::Duration::from_secs(5));
assert!(cancel.is_cancelled());
// The cleanup is only waited for briefly and finishes in the background on a busy machine.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while stuck_dir.exists() && std::time::Instant::now() < deadline {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(!stuck_dir.exists(), "its directory is removed once the wait is over");
}
+1 -1
View File
@@ -34,7 +34,7 @@ pub async fn java_resolve_launch(
result
}
async fn resolve_launch(
pub(crate) async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
+12 -12
View File
@@ -34,9 +34,9 @@ pub struct ProjectInterpreter {
}
/// Installed interpreters / toolchains of `kind`; project-local ones first.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let project = host.project(window).ok();
if kind == SdkKind::Jdk {
host.apply_added_jdks();
@@ -63,10 +63,10 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
}
/// The Python interpreters of the recently opened projects, each with its project.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeResult<Vec<ProjectInterpreter>> {
// Newest first. The open project is skipped: `sdk_detect` lists its own.
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let current = host.project(window).ok().map(|p| p.root.clone());
let config = host.config_dir.clone();
// Probing runs the project's interpreter (and its settings may name any program): only
@@ -111,9 +111,9 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
}
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let root = host.project(window).ok().map(|p| p.root.clone());
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
.await
@@ -320,7 +320,7 @@ pub async fn sdk_locate_tools(
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_create_venv(
host: &Host,
window: &str,
@@ -330,7 +330,7 @@ pub async fn sdk_python_create_venv(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
@@ -343,14 +343,14 @@ pub async fn sdk_python_create_venv(
result?
}
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_packages(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
@@ -360,7 +360,7 @@ pub async fn sdk_python_packages(
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_pip(
host: &Host,
window: &str,
@@ -371,7 +371,7 @@ pub async fn sdk_python_pip(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
+5 -5
View File
@@ -11,7 +11,7 @@ use std::path::PathBuf;
/// The installer, reporting the executables chosen in the window's settings.
fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let data = host.local_data_dir.clone();
let (settings, root) = match host.project(window) {
Ok(project) => (project.settings.effective(), project.root.clone()),
@@ -56,7 +56,7 @@ fn reconfigure_servers(host: &Host) {
}
/// Status of every known language server / debug adapter and the languages using it.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = languages(host, window);
@@ -65,7 +65,7 @@ pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
/// `on_event`. Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn tools_install(
host: &Host,
window: &str,
@@ -93,7 +93,7 @@ pub async fn tools_install(
/// Newer versions of the tools the IDE installed (release downloads and npm packages).
/// Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
let tools = tools(host, window)?;
let cancel = host.begin_request(request);
@@ -103,7 +103,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
}
/// Removes a tool the IDE installed.
#[command(trust = trusted)]
#[command(trust = outside_restricted)]
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = languages(host, window);
+10 -3
View File
@@ -47,12 +47,19 @@ pub async fn serves_page(url: &str) -> bool {
response.status().is_success() && html
}
/// The built-in server's URL for `path` (started on first use).
/// The built-in server's URL for `path` (started on first use). A file whose language is
/// HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
#[command(trust = always)]
pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult<String> {
// Under the window's project when it holds the file.
let root = host.project(window).ok().map(|p| p.root.clone());
host.web.url_for(root.as_deref(), &path).await
let project = host.project(window).ok();
let root = project.as_ref().map(|p| p.root.as_path());
let languages = project.as_ref().map_or(&host.languages, |p| &p.languages);
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") {
host.web.page_url_for(root, &path).await
} else {
host.web.url_for(root, &path).await
}
}
#[cfg(test)]
+1
View File
@@ -272,6 +272,7 @@ impl Host {
lombok.jar(),
);
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
ide_sdk::apply::configure_maven_sources(cfg, &effective);
ide_sdk::jdtls::launch_directly(cfg);
}
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
+3
View File
@@ -45,6 +45,9 @@ async fn a_commands_trust_class_decides_where_it_runs() {
assert_eq!(allowed("main", class), in_restricted, "{class:?} in Restricted Mode");
assert_eq!(allowed("welcome", class), without_project, "{class:?} without a project");
}
// Toolchain detection runs from Settings opened on the Welcome screen, but not in Restricted Mode.
assert!(ide_host::ops::sdk::sdk_detect(&host, "welcome", ide_sdk::SdkKind::Zig).await.is_ok());
assert!(ide_host::ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Zig).await.is_err());
// These requests validate the vendor before any network access, independently of project trust.
let error = ide_host::ops::tools::jdk_download_releases(&host, "unknown-vendor".into(), ide_core::RequestId(901))
.await
+1 -1
View File
@@ -28,7 +28,7 @@ pub use syntax::{
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
+2
View File
@@ -10,6 +10,7 @@ mod inheritance;
pub(crate) mod lines;
mod literals;
mod outline;
mod php_align;
mod python_facts;
mod rst;
mod selection;
@@ -28,6 +29,7 @@ pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
use std::collections::HashMap;
+368
View File
@@ -0,0 +1,368 @@
//! PHP Code Style › Align key-value pairs and Align consecutive assignments (PhpStorm's
//! options of the same names), applied to text a formatter has already formatted.
//!
//! A block is a run of array elements, or of assignment statements, on consecutive lines of
//! the same array or statement list, one per line and each on a single line. A blank line,
//! a comment line, another statement or element, or one spanning several lines ends it.
//! Within a block the operators line up one space after the longest left-hand side; nested
//! arrays form blocks of their own. Only the whitespace before an operator token of the
//! syntax tree changes, so `=>` and `=` inside strings and comments are never touched.
use crate::{LanguageId, Syntax};
use tree_sitter::{Node, Tree};
/// Which alignments to apply.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PhpAlignment {
/// `=>` of the elements of multi-line arrays.
pub key_value_pairs: bool,
/// `=` of consecutive assignment statements.
pub assignments: bool,
}
impl PhpAlignment {
pub fn any(self) -> bool {
self.key_value_pairs || self.assignments
}
}
impl Syntax {
/// `text` with its PHP alignment applied, changing only lines `lines` (0-based, inclusive;
/// `None`: all). A block reaching outside them still aligns with its lines there.
/// `None` when nothing changes or `lang` is not parsed with the PHP grammar.
pub fn align_php(
&self,
lang: &LanguageId,
text: &str,
lines: Option<(usize, usize)>,
options: PhpAlignment,
) -> Option<String> {
if !options.any() {
return None;
}
self.analyze(lang, text, |g, tree, text| (g.spec.name == "php").then(|| align(tree, text, lines, options)))
.flatten()
}
}
/// One line's operator: the whitespace `gap` before it and the width of the line up to it.
#[derive(Clone, Copy, Debug)]
struct Entry {
line: usize,
gap: (usize, usize),
/// Characters from the start of the line to the end of the left-hand side.
width: usize,
}
fn align(tree: &Tree, text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> Option<String> {
let mut gaps: Vec<(usize, usize, usize)> = Vec::new();
let mut cursor = tree.walk();
visit(&mut cursor, &mut |node| {
// Error recovery can read string content as code, where whitespace matters.
if node.is_error() {
return;
}
let entries = match node.kind() {
"array_creation_expression" if options.key_value_pairs => run(node, text, key_value),
_ if options.assignments => run(node, text, assignment),
_ => return,
};
for block in blocks(&entries) {
let column = block.iter().map(|e| e.width).max().unwrap_or(0) + 1;
for e in block {
if lines.is_none_or(|(first, last)| (first..=last).contains(&e.line)) {
gaps.push((e.gap.0, e.gap.1, column - e.width));
}
}
}
});
gaps.sort_unstable();
let mut out = String::with_capacity(text.len());
let mut at = 0;
let mut changed = false;
for (from, to, spaces) in gaps {
if text[from..to].len() == spaces && text[from..to].bytes().all(|b| b == b' ') {
continue;
}
out.push_str(&text[at..from]);
out.extend(std::iter::repeat_n(' ', spaces));
at = to;
changed = true;
}
if !changed {
return None;
}
out.push_str(&text[at..]);
Some(out)
}
/// The named children of `parent` as alignment candidates in order: `None` breaks a block.
/// A comment ending the line of the child before it (`'a' => 1, // why`) is skipped; two
/// children sharing a line are both left alone.
fn run(parent: Node, text: &str, entry: fn(Node, &str) -> Option<Entry>) -> Vec<Option<Entry>> {
let mut out: Vec<Option<Entry>> = Vec::new();
let mut previous_end: Option<usize> = None;
let mut cursor = parent.walk();
for child in parent.named_children(&mut cursor) {
let start = child.start_position().row;
let shares_line = previous_end == Some(start);
if child.kind() == "comment" && shares_line {
continue;
}
if shares_line && let Some(last) = out.last_mut() {
*last = None;
}
out.push(if shares_line { None } else { entry(child, text) });
previous_end = Some(child.end_position().row);
}
out
}
/// Runs of entries on consecutive lines.
fn blocks(entries: &[Option<Entry>]) -> Vec<Vec<Entry>> {
let mut out: Vec<Vec<Entry>> = Vec::new();
let mut current: Vec<Entry> = Vec::new();
for entry in entries {
match entry {
Some(e) if current.last().is_none_or(|last| last.line + 1 == e.line) => current.push(*e),
Some(e) => out.push(std::mem::replace(&mut current, vec![*e])),
None if current.is_empty() => {}
None => out.push(std::mem::take(&mut current)),
}
}
if !current.is_empty() {
out.push(current);
}
out
}
/// `'key' => value` alone on one line.
fn key_value(element: Node, text: &str) -> Option<Entry> {
if element.kind() != "array_element_initializer" {
return None;
}
let mut cursor = element.walk();
let arrow = element.children(&mut cursor).find(|c| c.kind() == "=>")?;
let key = arrow.prev_sibling()?;
entry(element, key, arrow, text)
}
/// `$left = value;` (or `= &value`) alone on one line.
fn assignment(statement: Node, text: &str) -> Option<Entry> {
if statement.kind() != "expression_statement" {
return None;
}
let expression = statement.named_child(0)?;
if !matches!(expression.kind(), "assignment_expression" | "reference_assignment_expression") {
return None;
}
let left = expression.child_by_field_name("left")?;
let mut cursor = expression.walk();
let operator = expression.children(&mut cursor).find(|c| c.kind() == "=")?;
entry(statement, left, operator, text)
}
fn entry(whole: Node, left: Node, operator: Node, text: &str) -> Option<Entry> {
let line = whole.start_position().row;
if whole.has_error() || whole.end_position().row != line {
return None;
}
let line_start = whole.start_byte() - whole.start_position().column;
let starts_line = text[line_start..whole.start_byte()].bytes().all(|b| b == b' ' || b == b'\t');
let gap = (left.end_byte(), operator.start_byte());
let blank_gap = text[gap.0..gap.1].bytes().all(|b| b == b' ' || b == b'\t');
(starts_line && blank_gap).then(|| Entry { line, gap, width: text[line_start..gap.0].chars().count() })
}
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::OnceLock;
const BOTH: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
const PAIRS: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: false };
const ASSIGNMENTS: PhpAlignment = PhpAlignment { key_value_pairs: false, assignments: true };
fn syntax() -> &'static Syntax {
static S: OnceLock<Syntax> = OnceLock::new();
S.get_or_init(Syntax::new)
}
fn aligned(text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> String {
let out = syntax().align_php(&LanguageId::new("php"), text, lines, options);
let result = out.clone().unwrap_or_else(|| text.to_owned());
let strip = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
assert_eq!(strip(&result), strip(text), "only whitespace changes");
assert_eq!(
syntax().align_php(&LanguageId::new("php"), &result, lines, options),
None,
"aligning again changes nothing:\n{result}"
);
result
}
fn check(options: PhpAlignment, before: &str, after: &str) {
assert_eq!(aligned(before, None, options), after);
}
#[test]
fn aligns_the_arrows_of_a_multi_line_array() {
check(
PAIRS,
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
);
check(
PAIRS,
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
);
}
#[test]
fn nested_arrays_align_per_level_and_a_multi_line_value_ends_a_block() {
check(
PAIRS,
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
);
}
#[test]
fn blank_lines_comment_lines_and_elements_without_a_key_end_a_block() {
check(
PAIRS,
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
);
}
#[test]
fn a_comment_at_the_end_of_a_line_keeps_the_block() {
check(
PAIRS,
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
);
}
#[test]
fn single_line_arrays_and_elements_sharing_a_line_stay_as_they_are() {
for text in [
"<?php\n$a = ['a' => 1, 'bbb' => 2];\n",
"<?php\n$a = [\n 'a' => 1, 'bbb' => 2,\n 'cc' => 3,\n];\n",
"<?php\n$a = ['a' => 1,\n 'bbb' => 2];\n",
] {
assert_eq!(aligned(text, None, BOTH), text);
}
}
#[test]
fn arrows_and_equals_signs_outside_arrays_and_assignments_are_not_touched() {
let text = "<?php\n\
$s = 'a => b';\n\
$t = \"x = y\";\n\
// 'k' => 1, $v = 2\n\
/* 'kk' => 1 */\n\
foreach ($items as $key => $value) {}\n\
$f = fn($x) => $x;\n\
$m = match ($x) {\n 1 => 'a',\n 100 => 'b',\n};\n\
for ($i = 0; $i < 3; $i++) {}\n\
function g($a = 1, $bbb = 2) {}\n\
g(a: 1, bbb: 2);\n\
$h = <<<EOT\n 'a' => 1,\n 'bbb' => 2,\nEOT;\n";
let out = aligned(text, None, PAIRS);
assert_eq!(out, text);
}
#[test]
fn aligns_consecutive_assignments() {
check(
ASSIGNMENTS,
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
);
}
#[test]
fn other_statements_blank_lines_and_multi_line_assignments_end_a_block() {
check(
ASSIGNMENTS,
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
);
}
#[test]
fn assignments_sharing_a_line_and_declarations_stay_as_they_are() {
let text = "<?php\n$a = 1; $bbb = 2;\n$cc = 3;\nclass C {\n public $x = 1;\n public $yyy = 2;\n const A = 1;\n const BBB = 2;\n}\n";
assert_eq!(aligned(text, None, ASSIGNMENTS), text);
}
#[test]
fn each_option_aligns_only_its_operator() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n";
assert_eq!(
aligned(text, None, PAIRS),
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
);
assert_eq!(
aligned(text, None, ASSIGNMENTS),
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
);
assert_eq!(syntax().align_php(&LanguageId::new("php"), text, None, PhpAlignment::default()), None);
assert_eq!(syntax().align_php(&LanguageId::new("javascript"), "a = {\n b: 1,\n};\n", None, BOTH), None);
}
#[test]
fn only_the_given_lines_change_and_they_align_with_the_whole_block() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n";
assert_eq!(
aligned(text, Some((2, 3)), PAIRS),
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n"
);
assert_eq!(aligned(text, Some((5, 5)), PAIRS), text);
}
#[test]
fn widths_count_characters_not_bytes() {
check(
PAIRS,
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
);
}
#[test]
fn code_with_syntax_errors_is_aligned_only_where_it_parses() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => ,\n 'cc' => 3,\n];\n";
let out = aligned(text, None, PAIRS);
assert!(out.contains("'bbb' => ,"), "{out}");
}
#[test]
fn php_inside_html() {
check(
BOTH,
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
);
}
}
+8
View File
@@ -435,6 +435,14 @@ impl ClientHandler {
.find_map(|base| section.split('.').try_fold(base, |v, key| v.get(key)))
.cloned()
.unwrap_or(Value::Null),
None if self.server.name == "eslint" => {
let mut settings = options.clone();
settings["workspaceFolder"] = json!({
"uri": crate::uri::path_to_uri(&self.server.root),
"name": self.server.root.file_name().map_or_else(|| "root".into(), |name| name.to_string_lossy().into_owned()),
});
settings
}
None => options.clone(),
})
.collect(),
+44 -14
View File
@@ -1833,8 +1833,11 @@ impl LspManager {
/// the same class from its Java model instead, decompiled with method bodies and navigable.
/// Its documents belong to jdtls ([`Self::virtual_document`] records it).
async fn jdt_library_classes(&self, snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
let jar_class = |l: &Location| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"));
if !locs.iter().any(jar_class)
let lib_class = |u: &str| {
(u.starts_with("jar:") && u.ends_with(".class"))
|| (u.starts_with("jdt://contents/") && u.contains(".class"))
};
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(lib_class))
|| !self.servers.lock().iter().any(|s| s.name == jdtls::SERVER && s.running().is_some())
{
return locs;
@@ -1842,27 +1845,54 @@ impl LspManager {
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
let mut out = Vec::with_capacity(locs.len());
for loc in locs {
let entry = loc.uri.as_deref().filter(|_| jar_class(&loc)).and_then(library_source::parse);
let Some(entry) = entry else {
let Some(original) = loc.uri.as_deref().filter(|u| lib_class(u)) else {
out.push(loc);
continue;
};
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
let jdt = original.starts_with("jdt:");
let uri = if !jdt {
let Some(entry) = library_source::parse(original) else {
out.push(loc);
continue;
};
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
}
}
} else {
original.to_owned()
};
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
let doc = self.virtual_document(&uri).await.ok();
let range = match (&name, &doc) {
// jdtls' own class: its range is exact (overloads included) unless it maps a
// Lombok-generated member onto the annotation or class header, which doesn't
// name the member; only then look the declaration up in the source.
(Some(name), Some(doc)) if jdt => {
let line = doc.text.lines().nth(loc.range.start.line as usize).unwrap_or_default();
if library_source::identifier_at(line, loc.range.start.col) == Some(name.as_str()) {
loc.range
} else {
Some(library_source::declaration_range(&doc.text, name))
.filter(|r| *r != Range::default())
.unwrap_or(loc.range)
}
}
(Some(name), Some(doc)) => library_source::declaration_range(&doc.text, name),
_ if jdt => loc.range,
_ => Range::default(),
};
out.push(Location { path: uri.clone().into(), range, uri: Some(uri) });
out.push(if jdt {
Location { range, ..loc }
} else {
Location { path: uri.clone().into(), range, uri: Some(uri) }
});
}
out
}
+62 -1
View File
@@ -180,6 +180,7 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut fallback = None;
let mut field = None;
let mut block_comment = false;
for (line_no, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
@@ -223,9 +224,40 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
if java_member && fallback.is_none() {
fallback = Some(range);
}
// A Java field (`private String name;`, `int age = 5;`): Lombok sources declare only
// the field, the accessors exist solely in the compiled class. A method of that name
// still wins, so a same-named local declared before it is not taken.
let java_field = matches!(line[end..].trim_start().chars().next(), Some(';' | '=' | ','))
&& !head.trim_end().ends_with('.')
&& !head.trim().is_empty()
&& !head.contains(['=', '('])
&& !words.iter().any(|w| matches!(*w, "return" | "throw" | "new" | "yield" | "assert"));
if java_field && field.is_none() {
field = Some(range);
}
}
}
fallback.unwrap_or_default()
if let Some(range) = fallback.or(field) {
return range;
}
accessor_field(name).map(|field| declaration_range(text, &field)).unwrap_or_default()
}
/// The field a Lombok/bean accessor stands for (`getName`/`setName` → `name`,
/// `isActive` → `active`); `None` for names that are not accessors.
fn accessor_field(name: &str) -> Option<String> {
let rest = ["get", "set", "is"]
.iter()
.find_map(|p| name.strip_prefix(p))
.filter(|r| r.chars().next().is_some_and(|c| c.is_uppercase()))?;
let mut chars = rest.chars();
let first = chars.next()?;
// Bean convention: `getURL` → `URL`, `getName` → `name`.
if rest.chars().nth(1).is_some_and(|c| c.is_uppercase()) {
Some(rest.to_owned())
} else {
Some(first.to_lowercase().collect::<String>() + chars.as_str())
}
}
/// The identifier around `col` (UTF-16) of `line`.
@@ -588,6 +620,35 @@ mod tests {
assert_eq!(declared_package("class A"), "");
}
#[test]
fn lombok_accessors_and_java_fields_locate_the_field() {
// Lombok sources declare only the field; the accessors exist only in the
// compiled class, so navigation must fall back to the underlying field.
let lombok = "package example.entity;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@Getter\n@Setter\npublic class UserEntity {\n private String name;\n private int age;\n private boolean active;\n}\n";
for (name, line, col) in [
("getName", 8, 19),
("setName", 8, 19),
("name", 8, 19),
("getAge", 9, 16),
("isActive", 10, 20),
("active", 10, 20),
] {
let r = declaration_range(lombok, name);
assert_eq!((r.start.line, r.start.col), (line, col), "{name}");
}
// An explicitly declared accessor still wins over the field.
let plain = "class Plain {\n private String name;\n public String getName() { return name; }\n}\n";
assert_eq!(declaration_range(plain, "getName").start.line, 2);
// Initialized fields count; a method beats a same-named local declared before it.
let init = "class Init {\n private int count = 0;\n void a() {\n int size = 1;\n }\n int size() { return 2; }\n}\n";
assert_eq!(declaration_range(init, "getCount").start.line, 1);
assert_eq!(declaration_range(init, "size").start.line, 5);
// Bean convention keeps acronyms; non-accessors are not remapped.
assert_eq!(accessor_field("getURL").as_deref(), Some("URL"));
assert_eq!(accessor_field("getter"), None);
assert_eq!(declaration_range(lombok, "missing"), Range::default());
}
#[test]
fn locates_declarations_in_kotlin_and_java_sources() {
let at = |text: &str, name: &str| {
+29
View File
@@ -2568,6 +2568,35 @@ async fn configuration_answer_resyncs_open_documents_of_opted_in_servers() {
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn eslint_configuration_includes_workspace_folder() {
let h = harness_configured("mock", "mk", &[("eslint", incremental_caps()), ("mock", incremental_caps())], |cfg| {
if cfg.name == "eslint" {
cfg.settings = Some(json!({ "workingDirectory": { "mode": "auto" } }));
}
});
h.open("a.mk", "x");
h.wait_status("eslint", ServerStatus::Ready).await;
h.wait_status("mock", ServerStatus::Ready).await;
let items = json!({ "items": [{ "section": "" }] });
let eslint: Value =
h.launcher.state("eslint").peer().request("workspace/configuration", items.clone(), None).await.unwrap();
assert_eq!(
eslint,
json!([{
"flag": true,
"nested": { "deep": 1 },
"workingDirectory": { "mode": "auto" },
"workspaceFolder": {
"uri": uri_of(&h.root),
"name": h.root.file_name().unwrap().to_string_lossy(),
},
}])
);
let other: Value = h.launcher.state("mock").peer().request("workspace/configuration", items, None).await.unwrap();
assert_eq!(other, json!([{ "flag": true, "nested": { "deep": 1 } }]));
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_changes_reach_servers_without_restarts() {
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
+29
View File
@@ -537,6 +537,16 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
}
/// Settings › Build Tools › Maven › Automatically download sources → jdtls
/// `java.maven.downloadSources`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let download = s.languages.java.maven.download_sources;
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
@@ -2350,6 +2360,25 @@ mod maven_linkage_tests {
assert_eq!(default_maven_repository_in(home), Some(home.join(".m2/repository")));
}
#[test]
fn maven_sources_download_follows_the_setting() {
let mut settings = Settings::default();
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
cfg.settings = Some(json!({"java": {"maven": {"downloadSources": true, "updateSnapshots": false}}}));
configure_maven_sources(&mut cfg, &settings);
assert_eq!(
cfg.settings,
Some(json!({"java": {"maven": {"downloadSources": false, "updateSnapshots": false}}}))
);
settings.languages.java.maven.download_sources = true;
configure_maven_sources(&mut cfg, &settings);
assert_eq!(cfg.settings.unwrap()["java"]["maven"]["downloadSources"], json!(true));
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
configure_maven_sources(&mut other, &settings);
assert_eq!(other.settings, None);
}
#[test]
fn gradle_import_runs_the_gradle_the_ide_builds_with() {
let root = Path::new("/p");
+21 -1
View File
@@ -86,5 +86,25 @@ fn excluded_subtrees(c: &mut Criterion) {
group.finish();
}
criterion_group!(benches, bench, excluded_subtrees);
// Lockfile-sized files with a hit on every line, one per folder so every walker
// thread is inside its own dense file when the 10 000-match default limit is reached.
fn dense_files(c: &mut Criterion) {
let dir = tempfile::tempdir().unwrap();
for module in 0..24 {
let sub = dir.path().join(format!("packages/p{module}"));
std::fs::create_dir_all(&sub).unwrap();
let mut text = String::with_capacity(2 << 20);
for i in 0..40_000u32 {
text.push_str(&format!(" \"version\": \"{}.{}.{module}\",\n", i / 100, i % 100));
}
std::fs::write(sub.join("package-lock.json"), text).unwrap();
}
let q = query("version", false);
let mut group = c.benchmark_group("search_dense_files");
group.sample_size(15);
group.bench_function("24x40k_limit", |b| b.iter(|| black_box(run(dir.path(), &q))));
group.finish();
}
criterion_group!(benches, bench, excluded_subtrees, dense_files);
criterion_main!(benches);
+109 -20
View File
@@ -22,6 +22,9 @@ pub(crate) const DEFAULT_MAX_MATCHES: u32 = 10_000;
/// How many matched lines a sink handles between cancellation-token checks
/// (reads from disk check on every buffer refill).
const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -87,6 +90,11 @@ impl Control<'_> {
}
}
}
/// Returns matches claimed for a file whose matches are then dropped.
fn release(&self, n: u32) {
self.matches.fetch_sub(n, Relaxed);
}
}
struct Ctx<'a> {
@@ -322,24 +330,16 @@ impl Ctx<'_> {
None => self.search_disk(path, matcher, searcher, &mut sink),
},
};
if let Err(err) = result {
if !self.ctl.stopped() {
tracing::debug!("search {}: {err}", path.display());
}
if sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
return;
}
if let Err(err) = result
&& !self.ctl.stopped()
{
tracing::debug!("search {}: {err}", path.display());
}
if sink.binary || sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
self.ctl.release(sink.claimed);
return;
}
let found = u32::try_from(sink.count).unwrap_or(u32::MAX);
let granted = self.ctl.reserve(found);
if granted < found {
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut sink.lines, granted as usize);
}
sink.settle();
if sink.lines.is_empty() {
return;
}
@@ -364,14 +364,17 @@ impl Ctx<'_> {
} else {
!reader.is_utf8()
};
if !decode || self.ctl.stopped() {
// A stopped search needs the decoded text only to fill what the byte search claimed.
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
return result;
}
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
sink.binary = true;
return Ok(());
};
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
searcher.search_slice(matcher, text.as_bytes(), sink)
}
}
@@ -389,8 +392,11 @@ struct FileSink<'a> {
matcher: &'a RegexMatcher,
ctl: &'a Control<'a>,
lines: Vec<LineMatch>,
/// Match ranges collected so far.
count: usize,
/// Match ranges kept so far.
count: u32,
/// Matches claimed from the shared budget: up to `count`, or more while a decoded
/// file is searched again under the claim of its byte search.
claimed: u32,
binary: bool,
ticks: u32,
/// Scratch buffers reused across lines.
@@ -411,6 +417,7 @@ impl<'a> FileSink<'a> {
ctl,
lines: Vec::new(),
count: 0,
claimed: 0,
binary: false,
ticks: 0,
found: Vec::new(),
@@ -418,6 +425,36 @@ impl<'a> FileSink<'a> {
context,
}
}
/// Claims the matches kept since the last claim. When the budget cannot take them
/// all, keeps the ones it can, marks the limit hit and returns false.
fn claim(&mut self) -> bool {
if self.count <= self.claimed {
return true;
}
let unclaimed = self.count - self.claimed;
let granted = self.ctl.reserve(unclaimed);
self.claimed += granted;
if granted == unclaimed {
return true;
}
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut self.lines, self.claimed as usize);
self.count = self.claimed;
false
}
/// Makes the claim match the matches kept once the file is done: claims the rest, or
/// gives back the part of a byte search's claim the decoded text did not use.
fn settle(&mut self) {
if self.count < self.claimed {
self.ctl.release(self.claimed - self.count);
self.claimed = self.count;
} else {
self.claim();
}
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
@@ -431,7 +468,9 @@ impl Sink for FileSink<'_> {
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
self.ticks += 1;
if self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop()) {
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
if stop && (self.count >= self.claimed || self.ctl.cancelled.load(Relaxed)) {
return Ok(false);
}
let buffer = m.buffer();
@@ -475,7 +514,7 @@ impl Sink for FileSink<'_> {
ranges.push((a - line_start, b - line_start));
}
if !ranges.is_empty() {
self.count += ranges.len();
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
}
@@ -485,7 +524,8 @@ impl Sink for FileSink<'_> {
self.found = found;
self.ranges = ranges;
// One match beyond the remaining budget is enough to know the limit is hit.
Ok(self.count <= self.ctl.remaining() as usize)
let unclaimed = self.count.saturating_sub(self.claimed);
Ok(if unclaimed >= CLAIM_BATCH || unclaimed > self.ctl.remaining() { self.claim() } else { true })
}
fn binary_data(&mut self, _searcher: &Searcher, _offset: u64) -> Result<bool, io::Error> {
@@ -642,3 +682,52 @@ mod walk_tests {
assert!(seen.lock().unwrap().is_empty());
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
fn control(cancel: &CancellationToken, max: u32) -> Control<'_> {
Control {
cancel,
stop: AtomicBool::new(false),
cancelled: AtomicBool::new(false),
limit_hit: AtomicBool::new(false),
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
}
}
/// Searches `lines` matching lines without finishing the file, like a walker thread mid-file.
fn scan<'a>(ctl: &'a Control<'a>, matcher: &'a RegexMatcher, lines: usize) -> FileSink<'a> {
let mut sink = FileSink::new(matcher, ctl, None);
let mut searcher = SearcherBuilder::new().line_number(true).build();
searcher.search_slice(matcher, "x\n".repeat(lines).as_bytes(), &mut sink).unwrap();
sink
}
#[test]
fn files_in_flight_never_hold_more_matches_than_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 100);
let matcher = RegexMatcher::new("x").unwrap();
let (first, second) = (scan(&ctl, &matcher, 150), scan(&ctl, &matcher, 150));
assert_eq!((first.lines.len(), second.lines.len()), (100, 0));
assert_eq!(ctl.matches.load(Relaxed), 100);
assert!(ctl.limit_hit.load(Relaxed));
}
#[test]
fn unclaimed_matches_of_a_file_in_flight_stay_within_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 1000);
let matcher = RegexMatcher::new("x").unwrap();
let mut first = scan(&ctl, &matcher, 40);
let second = scan(&ctl, &matcher, 2000);
assert_eq!((first.lines.len(), second.lines.len()), (40, 1000));
assert!(!first.claim());
assert_eq!((first.lines.len(), ctl.matches.load(Relaxed)), (0, 1000));
assert!(ctl.limit_hit.load(Relaxed));
}
}
+44
View File
@@ -314,6 +314,25 @@ fn match_limit() {
assert_eq!(summary.matches, 14);
}
#[test]
fn match_limit_across_parallel_files() {
// One file per folder, so several walker threads search at once.
let content = "x\n".repeat(50);
let names: Vec<String> = (0..16).map(|i| format!("m{i}/a.txt")).collect();
let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), content.as_bytes())).collect();
let p = project(&files);
for _ in 0..20 {
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 800, ..query("x") });
assert!(!summary.limit_hit);
assert_eq!((total(&views), summary.matches, summary.files), (800, 800, 16));
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 799, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (799, 799));
assert_eq!(summary.files as usize, views.len());
}
}
#[test]
fn default_limit_is_ten_thousand() {
let content = "a\n".repeat(10_050);
@@ -775,6 +794,31 @@ fn non_utf8_files_are_searched_as_text() {
assert_eq!(views[0].matches[0].ranges, [(13, 20), (21, 28), (29, 36)]);
}
#[test]
fn dropped_matches_give_back_their_budget() {
// Matches claimed before a late NUL (binary) or late GBK bytes (searched again as text).
let head = b"needle\n".repeat(100);
let filler = b"a".repeat(200_000);
let binary = [head.as_slice(), &filler, b"\0\n"].concat();
let late_gbk = [head.as_slice(), &filler, b"\n", &gbk("中文\n")].concat();
// One project each: a thread's searcher keeps its grown buffer for the next file.
for (file, bytes, found) in [("bin.dat", binary, 0), ("late.txt", late_gbk, 100)] {
let p = project(&[(file, &bytes)]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!((total(&views), summary.matches), (found, found as u32), "{file}");
assert!(!summary.limit_hit);
}
}
#[test]
fn non_utf8_files_past_the_limit_show_decoded_text() {
let p = project(&[("a.txt", &gbk(&"x 中文\n".repeat(200)))]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 100, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (100, 100));
assert!(views[0].matches.iter().all(|m| m.text == "x 中文"));
}
#[test]
fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
+12 -6
View File
@@ -1,14 +1,15 @@
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document.
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document
//! (and a 5 MB one where whole-document copies would show).
use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main};
use ide_core::{ChangeSet, Pos, TextChange};
use ide_text::Document;
/// ~1 MB of code-like text with some non-ASCII content.
fn sample_text() -> String {
let mut s = String::with_capacity(1 << 20);
/// ~`bytes` of code-like text with some non-ASCII content.
fn sample_text(bytes: usize) -> String {
let mut s = String::with_capacity(bytes);
let mut i = 0u32;
while s.len() < 1 << 20 {
while s.len() < bytes {
s.push_str(&format!(" let value_{i} = compute(\"héllo 😀\", {i}) + other_{i};\n"));
i += 1;
}
@@ -47,7 +48,7 @@ fn change_set(doc: &Document, rng: &mut Lcg, n: usize) -> ChangeSet {
}
fn bench(c: &mut Criterion) {
let text = sample_text();
let text = sample_text(1 << 20);
c.bench_function("text/open_1mb", |b| b.iter(|| Document::new(black_box(&text))));
let base = Document::new(&text);
@@ -77,6 +78,11 @@ fn bench(c: &mut Criterion) {
c.bench_function("text/diff_two_edits_1mb", |b| b.iter(|| base.diff(black_box(&two_edits))));
let every_line = text.replace("compute", "calculate");
c.bench_function("text/diff_every_line_1mb", |b| b.iter(|| base.diff(black_box(&every_line))));
let large_text = sample_text(5 << 20);
let large = Document::new(&large_text);
let one_edit = large_text.replacen("value_40000 ", "renamed_40000 ", 1);
assert_ne!(one_edit, large_text);
c.bench_function("text/diff_one_edit_5mb", |b| b.iter(|| large.diff(black_box(&one_edit))));
c.bench_function("text/offset_to_pos_round_trip", |b| {
let mut rng = Lcg(3);
let len = base.len_utf16();
+112 -4
View File
@@ -93,6 +93,54 @@ fn common_ends(a: &str, b: &str) -> (usize, usize) {
(prefix, suffix)
}
/// [`common_ends`] of the rope's text and `b`, walking the rope's chunks instead
/// of copying it: whole chunks compare as slices, bytes only around the mismatch.
fn rope_common_ends(rope: &ropey::Rope, b: &str) -> (usize, usize) {
let bb = b.as_bytes();
let mut prefix = 0;
for chunk in rope.chunks() {
let n = common_prefix_len(chunk.as_bytes(), &bb[prefix..]);
prefix += n;
if n < chunk.len() {
break;
}
}
prefix = rope.char_to_byte(rope.byte_to_char(prefix));
let len = rope.len_bytes();
let limit = len.min(bb.len()) - prefix;
let mut suffix = 0;
let mut chunks = rope.chunks_at_byte(len).0.reversed();
while suffix < limit {
let Some(chunk) = chunks.next() else { break };
let n = common_suffix_len(chunk.as_bytes(), &bb[..bb.len() - suffix]).min(limit - suffix);
suffix += n;
if n < chunk.len() {
break;
}
}
let ch = rope.byte_to_char(len - suffix);
if rope.char_to_byte(ch) < len - suffix {
suffix = len - rope.char_to_byte(ch + 1);
}
(prefix, suffix)
}
fn common_prefix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[..n] == b[..n] {
return n;
}
a.iter().zip(b).take_while(|(x, y)| x == y).count()
}
fn common_suffix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[a.len() - n..] == b[b.len() - n..] {
return n;
}
a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count()
}
/// Byte offset of each line, then the total length.
fn line_starts(lines: &[&str]) -> Vec<usize> {
let mut at = 0;
@@ -396,9 +444,8 @@ impl Document {
/// Past `deadline` the regions get coarser, never wrong.
fn diff_until(&self, text: &str, deadline: Instant) -> ChangeSet {
let new = normalize_line_endings(text);
let old = self.rope.to_string();
let (prefix, suffix) = common_ends(&old, &new);
let old_rest = &old[prefix..old.len() - suffix];
let (prefix, suffix) = rope_common_ends(&self.rope, &new);
let old_rest = String::from(self.rope.byte_slice(prefix..self.rope.len_bytes() - suffix));
let new_rest = &new[prefix..new.len() - suffix];
let old_lines: Vec<&str> = old_rest.split_inclusive('\n').collect();
@@ -407,7 +454,7 @@ impl Document {
let new_starts = line_starts(&new_lines);
let mut changes = Vec::new();
let mut utf16_at = utf16_len(&old[..prefix]);
let mut utf16_at = self.byte_to_offset(prefix);
let mut old_at = 0;
let mut region: Option<(LineRange, LineRange)> = None;
let ops =
@@ -710,6 +757,67 @@ mod tests {
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
}
/// The rope scan must trim exactly what `common_ends` trims on the copied text.
fn assert_rope_ends(old: &str, new: &str) {
let doc = Document::new(old);
let (prefix, suffix) = rope_common_ends(&doc.rope, new);
assert_eq!((prefix, suffix), common_ends(old, new), "{old:?} -> {new:?}");
assert_eq!(doc.byte_to_offset(prefix), utf16_len(&old[..prefix]));
}
#[test]
fn rope_common_ends_matches_common_ends() {
let unit = "héllo 😀 wörld, ©\n";
let base = unit.repeat(400);
assert!(Document::new(&base).rope.chunks().count() > 4, "spans several chunks");
for (old, new) in [("", ""), ("", "abc"), ("abc", ""), ("é", "è"), ("😀", "😁"), ("é", "©")] {
assert_rope_ends(old, new);
}
assert_rope_ends(&base, &base);
assert_rope_ends(&base, "");
assert_rope_ends("", &base);
assert_rope_ends(&base, &format!("{base}tail"));
assert_rope_ends(&format!("{base}tail"), &base);
assert_rope_ends(&base, &base[unit.len()..]);
assert_rope_ends(&"a".repeat(5000), &"a".repeat(4999));
assert_rope_ends(&"ab".repeat(3000), &"ab".repeat(3001));
assert_rope_ends(&"😀".repeat(2000), &"😀".repeat(1999));
let boundaries: Vec<usize> = base.char_indices().map(|(i, _)| i).step_by(7).collect();
for at in boundaries {
let c = base[at..].chars().next().unwrap();
let rest = &base[at + c.len_utf8()..];
let swapped = match c {
'é' => 'è', // same lead byte
'😀' => '😁', // differs in the last byte only
'©' => 'é', // same trailing byte
_ => 'X',
};
let swap = format!("{}{swapped}{rest}", &base[..at]);
assert_rope_ends(&base, &swap);
// Deleting a char further on stops the suffix scan far from the prefix.
let mut far = at + (swap.len() - at) / 2;
while !swap.is_char_boundary(far) {
far += 1;
}
let gone = swap[far..].chars().next().unwrap().len_utf8();
assert_rope_ends(&base, &format!("{}{}", &swap[..far], &swap[far + gone..]));
assert_rope_ends(&base, &format!("{}{rest}", &base[..at]));
assert_rope_ends(&base, &format!("{}é{c}{rest}", &base[..at]));
}
}
#[test]
fn diff_of_a_large_document_counts_utf16_and_normalizes_crlf() {
let old = "😀 héllo\n".repeat(2000);
let at = old.len() / 2;
let new = format!("{}X{}", &old[..at], &old[at..]);
let doc = Document::new(&old);
let expected = vec![tc(utf16_len(&old[..at]), utf16_len(&old[..at]), "X")];
assert_eq!(doc.diff(&new).changes, expected);
assert_eq!(doc.diff(&new.replace('\n', "\r\n")).changes, expected);
assert!(doc.diff(&old.replace('\n', "\r\n")).changes.is_empty());
}
#[test]
fn diff_past_its_deadline_is_coarser_but_still_correct() {
let old = numbered_lines(5000);
+44 -5
View File
@@ -1,8 +1,8 @@
use ide_core::{IdeError, IdeResult};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
@@ -42,6 +42,9 @@ struct Root {
dir: PathBuf,
port: u16,
serves: Serves,
/// Files handed out by [`WebServer::page_url_for`], as requested. They stay here until
/// the app quits, even if the file stops being HTML: only its content type depends on it.
pages: Mutex<HashSet<PathBuf>>,
}
/// What of its directory a root serves.
@@ -87,6 +90,18 @@ impl WebServer {
/// A project that is the home folder, or holds it, is no boundary to serve whole: its
/// files are served like files outside a project.
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
Ok(self.locate(root, file).await?.1)
}
/// [`Self::url_for`] of a file that is an HTML page whatever its name (Settings › File
/// Types): it is served as HTML from now on.
pub async fn page_url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
let (served, url) = self.locate(root, file).await?;
served.pages.lock().unwrap_or_else(PoisonError::into_inner).insert(file.to_path_buf());
Ok(url)
}
async fn locate(&self, root: Option<&Path>, file: &Path) -> IdeResult<(Arc<Root>, String)> {
let (base, serves) = match root {
Some(r) if file.starts_with(r) && file != r && self.holds_home(r).await != Some(true) => (r, Serves::All),
_ => {
@@ -102,7 +117,7 @@ impl WebServer {
url.push('/');
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
}
Ok(url)
Ok((root, url))
}
/// Whether `dir` is the home folder or lies above it; `None` when that cannot be told.
@@ -153,6 +168,7 @@ impl WebServer {
dir: dir.to_path_buf(),
port,
serves,
pages: Mutex::default(),
});
tokio::spawn(accept(listener, root.clone()));
tracing::info!("built-in web server on 127.0.0.1:{} for {}", root.port, dir.display());
@@ -320,7 +336,9 @@ async fn resolve(root: &Root, target: &str) -> Response {
_ => NOT_FOUND,
};
}
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
let page = root.pages.lock().unwrap_or_else(PoisonError::into_inner).contains(&file);
let mime = if page { HTML } else { content_type(&file) };
Response::File { path: real, len: meta.len(), mime }
}
/// `path` with every symlink resolved, if `root` serves it: it lies inside `real_root`
@@ -343,10 +361,12 @@ fn dec(s: &str) -> Option<String> {
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
}
const HTML: &str = "text/html; charset=utf-8";
fn content_type(path: &Path) -> &'static str {
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
"html" | "htm" | "xhtml" => HTML,
"css" => "text/css; charset=utf-8",
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
@@ -395,6 +415,25 @@ mod tests {
out
}
#[tokio::test]
async fn a_page_is_html_whatever_its_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("site");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("page.foo"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("other.foo"), "<h1>no</h1>").unwrap();
let server = server();
let plain = server.url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert!(get(&plain, None).await.contains("application/octet-stream"));
let page = server.page_url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert_eq!(page, plain);
assert!(get(&page, None).await.contains("Content-Type: text/html"));
let other = page.replace("page.foo", "other.foo");
assert!(get(&other, None).await.contains("application/octet-stream"), "only the named file");
}
#[tokio::test]
async fn serves_project_files() {
let dir = tempfile::tempdir().unwrap();
+30 -2
View File
@@ -172,6 +172,9 @@ struct DocState {
/// Disk state we last loaded or wrote; changes matching it are our own.
disk_mtime: f64,
disk_len: u64,
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
/// alone until the user saves explicitly or the buffer is reloaded.
disk_conflict: bool,
closed: bool,
/// URI of a virtual document (no file behind it).
uri: Option<String>,
@@ -264,6 +267,7 @@ impl Documents {
st.native_to_ascii = enabled;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
Ok(())
});
if let Err(e) = result {
@@ -457,6 +461,7 @@ impl Documents {
encoding_chosen: false,
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
closed: false,
uri: None,
};
@@ -529,6 +534,7 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(uri.to_owned()),
};
@@ -587,6 +593,7 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(key.to_string_lossy().into_owned()),
};
@@ -653,6 +660,8 @@ impl Documents {
};
let mut st = slot.lock();
st.closed = true;
// A buffer closed with changes (Don't Save) has nothing left to save.
self.set_dirty(doc, &mut st, false);
if st.observed {
for o in self.observers() {
o.closed(doc, &st.path);
@@ -810,7 +819,22 @@ impl Documents {
/// Writes the document with its original encoding, BOM and line ending.
/// A clean document is not rewritten.
pub fn save(&self, doc: DocId) -> IdeResult<()> {
self.with_doc(doc, |st| self.write(doc, st))
}
/// An automatic save (switching tabs, the window losing focus): `false` when the file changed
/// on disk after this buffer was edited, which only an explicit save may overwrite.
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
if st.dirty && st.disk_conflict {
return Ok(false);
}
self.write(doc, st).map(|()| true)
})
}
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
{
if !st.dirty || st.uri.is_some() {
return Ok(());
}
@@ -822,6 +846,7 @@ impl Documents {
};
st.disk_mtime = mtime;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.set_dirty(doc, st, false);
if st.observed {
let text = st.doc.text();
@@ -830,7 +855,7 @@ impl Documents {
}
}
Ok(())
})
}
}
/// Save As for an untitled buffer: writes it to `target` (creating missing
@@ -1090,6 +1115,7 @@ impl Documents {
st.has_bom = loaded.has_bom;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.replace_locked(doc, st, &loaded.text)?;
// Reloading is not an edit: the buffer matches the file again.
self.set_dirty(doc, st, false);
@@ -1262,13 +1288,14 @@ impl Documents {
if st.dirty {
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: format!("{name} changed on disk"),
body: Some(format!(
"{} was modified externally but has unsaved changes in the editor. \
Saving will overwrite the external changes.",
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
st.path.display()
)),
});
@@ -1289,6 +1316,7 @@ impl Documents {
};
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
if loaded.binary || st.binary {
return Ok(());
}
+33
View File
@@ -228,6 +228,39 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&path, "alpha\nbeta external\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
// An explicit save overwrites, as the warning says; autosave works again after it.
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
}
#[test]
fn closing_a_modified_buffer_reports_it_clean() {
let f = fixture();
let info = f.docs.open_untitled(None).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "draft")).unwrap();
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
f.docs.close(info.id);
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
}
#[test]
fn open_edit_save_close() {
let f = fixture();
+1
View File
@@ -97,6 +97,7 @@ Open **Run › Edit Configurations…** (also in the run widget menu). The **Run
| **Gradle** / **Maven** | Gradle tasks or Maven goals, optionally through the wrapper |
| **Application** / **JAR Application** / **Spring Boot** | A Java main class, an executable JAR, a Spring Boot application |
| **Tomcat Server** | A WAR application in a local Tomcat |
| **Python** | A Python script or `-m` module |
| **pytest** / **Django tests** | pytest tests, `manage.py test` |
| **Ruby** / **Rake** / **RSpec** | A Ruby script, a Rake task, RSpec examples |
| **PHPUnit** | PHPUnit tests |
+1
View File
@@ -57,6 +57,7 @@ In a Composer project without `vendor/`, or whose installed packages differ from
- **PHPStan**: when the project has `vendor/bin/phpstan`, saved files are checked with it and its findings appear as diagnostics. The **PHPStan › Configuration file** setting picks the config; empty uses `phpstan.neon`, `phpstan.neon.dist` or `phpstan.dist.neon` in the project root.
- **PHP-CS-Fixer**: when a folder above the file has `.php-cs-fixer.php` or `.php-cs-fixer.dist.php` and the project has `vendor/bin/php-cs-fixer`, **Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses PHP-CS-Fixer instead of the language server.
- **Alignment**: **Settings › Editor › Code Style › PHP › Alignment** has PhpStorm's **Align key-value pairs** (`=>` in multi-line arrays) and **Align consecutive assignments** (`=` in assignment statements on consecutive lines), both off by default. They apply after the language server or PHP-CS-Fixer formats, on save too; for a selection, only to its lines. A blank line, a comment line, another statement or a value spanning several lines starts a new group, and nested arrays align on their own.
## Run and test
+1 -1
View File
@@ -105,7 +105,7 @@ In the editor, gutter icons run or debug:
A test file runs with pytest even when the project declares no test setup (`python -m pytest` with the project interpreter, so pytest must be installed there). In a Django project, `TestCase` tests can also run with `manage.py test`. Results of pytest and of Django's unittest runner appear in the test tree, where **Rerun Failed Tests** runs only the failures.
You can also create **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
You can also create **Python** (a script or module), **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
| Action | macOS | Windows / Linux |
| --------------------------- | ----- | ---------------- |
+4 -1
View File
@@ -238,7 +238,8 @@ The full table is `UI_KEYS` in
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -519,6 +520,8 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
+1
View File
@@ -93,6 +93,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
| **Gradle** / **Maven** | Gradle 任务或 Maven 目标,可选择通过 wrapper 运行 |
| **应用程序** / **JAR 应用程序** / **Spring Boot** | Java 主类、可执行 JAR、Spring Boot 应用 |
| **Tomcat 服务器** | 在本地 Tomcat 里运行 WAR 应用 |
| **Python** | Python 脚本或 `-m` 模块 |
| **pytest** / **Django 测试** | pytest 测试、`manage.py test` |
| **Ruby 语言** / **Rake 任务** / **RSpec 测试** | Ruby 脚本、Rake 任务、RSpec 用例 |
| **PHPUnit** | PHPUnit 测试 |
+1
View File
@@ -57,6 +57,7 @@ Composer 项目没有 `vendor/`,或已安装的包与 `composer.lock` 不一
- **PHPStan**:项目中有 `vendor/bin/phpstan` 时,保存的文件会交给它检查,结果显示为诊断。**PHPStan › 配置文件** 用于指定配置;留空则使用项目根目录下的 `phpstan.neon`、`phpstan.neon.dist` 或 `phpstan.dist.neon`。
- **PHP-CS-Fixer**:当文件上层目录中有 `.php-cs-fixer.php` 或 `.php-cs-fixer.dist.php`,且项目有 `vendor/bin/php-cs-fixer` 时,**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)改用 PHP-CS-Fixer,而不是语言服务器。
- **对齐**:**设置 › 编辑器 › 代码样式 › PHP › 对齐** 提供与 PhpStorm 相同的 **对齐键值对**(多行数组中的 `=>`)和 **对齐连续赋值**(相邻行赋值语句中的 `=`),默认都关闭。它们在语言服务器或 PHP-CS-Fixer 格式化之后生效,保存时格式化也一样;格式化选区时只作用于选中的行。空行、注释行、其他语句或跨多行的值会开始新的一组,嵌套数组单独对齐。
## 运行与测试
+1 -1
View File
@@ -105,7 +105,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
即使项目没有声明任何测试配置,测试文件也可以用 pytest 运行(用项目解释器执行 `python -m pytest`,因此该解释器里要装有 pytest)。在 Django 项目中,`TestCase` 测试也可以用 `manage.py test` 运行。pytest 和 Django unittest 运行器的结果显示在测试树中,**重新运行失败的测试** 只重跑失败的用例。
也可以在 **运行 › 编辑配置…** 中新建 **pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
也可以在 **运行 › 编辑配置…** 中新建 **Python**(脚本或模块)、**pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
| 操作 | macOS | Windows / Linux |
| -------------- | ----- | ---------------- |
+4 -1
View File
@@ -211,7 +211,8 @@ pnpm theme:import-intellij path/to/MyTheme.theme.json path/to/MyTheme.icls --out
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5`(语义高亮) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES`(效果颜色) |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT`(`CONSOLE_DARKGRAY_OUTPUT` 为亮黑,`CONSOLE_GRAY_OUTPUT` 为白色) |
@@ -485,6 +486,8 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light`
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
+1 -1
View File
@@ -47,7 +47,7 @@ moveRefactoringSupport = true
[language-servers.initialization-options.settings.java]
autobuild = { enabled = true }
contentProvider = { preferred = "fernflowerContentProvider" }
maven = { downloadSources = true, updateSnapshots = false }
maven = { downloadSources = false, updateSnapshots = false }
eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
# The editor's usage lenses count usages; the server's own lenses would search every
+2
View File
@@ -116,6 +116,7 @@
"text/apply_100_changes_1mb": 1000,
"text/diff_two_edits_1mb": 10000,
"text/diff_every_line_1mb": 100000,
"text/diff_one_edit_5mb": 2000,
"text/offset_to_pos_round_trip": 5,
"text/pos_to_byte": 5,
"text/text_for_save_crlf_1mb": 1000,
@@ -141,6 +142,7 @@
"search_5k/literal": 100000,
"search_5k/regex": 100000,
"search_5k/dense_limit": 20000,
"search_dense_files/24x40k_limit": 20000,
"plugins/load_50": 20000,
"plugins/cold_activation": 30000,
@@ -104,6 +104,8 @@
"--fg-deprecated": "#8c8f95",
"--bg-identifier-under-caret": "#2e353f",
"--bg-identifier-under-caret-write": "#402f33",
"--fg-identifier-under-caret": "inherit",
"--fg-identifier-under-caret-write": "inherit",
"--fg-inlay": "#75869d",
"--bg-inlay": "#303944",
"--wave-typo": "#59a869",
+5 -2
View File
@@ -232,7 +232,8 @@ The full table is `UI_KEYS` in [`src/features/plugins/intellijTheme.ts`](../src/
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting, rainbow indent guides) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -332,7 +333,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
271 themeable tokens: 125 in the UI theme file, 146 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -528,6 +529,8 @@ a token.
| `--fg-deprecated` | `#8c8f95` | `#6c707e` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
+17
View File
@@ -170,6 +170,23 @@ describe("IntelliJ theme import", () => {
});
});
it("maps the caret identifier foregrounds (#4109)", () => {
const s = convertIcls(`<scheme name="Caret" version="142" parent_scheme="Darcula"><attributes>
<option name="IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="aa0000" /><option name="BACKGROUND" value="220000" />
</value></option>
<option name="WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="00aa00" /><option name="BACKGROUND" value="002200" />
</value></option>
</attributes></scheme>`);
expect(s.tokens).toMatchObject({
"--fg-identifier-under-caret": "#aa0000",
"--bg-identifier-under-caret": "#220000",
"--fg-identifier-under-caret-write": "#00aa00",
"--bg-identifier-under-caret-write": "#002200",
});
});
it("only targets tokens that exist in tokens.css", () => {
const declared = new Set([...css.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((m) => m[1]!));
// Read with a fallback by the editor (no tokens.css default), still themeable.
+11 -10
View File
@@ -194,6 +194,7 @@ deploy_sync trusted project_host bin
deploy_test_connection always project_host bindings async
deploy_upload trusted project_host bindings async
diff_external_tool always desktop bindings async
doc_autosave always project_host bindings async
doc_close always project_host bindings async
doc_edit always project_host bindings async
doc_folding always project_host bindings async
@@ -536,7 +537,7 @@ scaffold_options always project_host bin
scaffold_requirements always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_jdk_at trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
@@ -544,12 +545,12 @@ sdk_php_effective trusted project_host bin
sdk_php_language_level trusted project_host bindings async
sdk_php_xdebug trusted project_host bindings async
sdk_project_libraries trusted project_host bindings async
sdk_python_create_venv trusted project_host bindings async
sdk_python_create_venv outside_restricted project_host bindings async
sdk_python_effective trusted project_host bindings sync
sdk_python_interpreter trusted project_host bindings async
sdk_python_packages trusted project_host bindings async
sdk_python_pip trusted project_host bindings async
sdk_python_project_interpreters trusted project_host bindings async
sdk_python_interpreter outside_restricted project_host bindings async
sdk_python_packages outside_restricted project_host bindings async
sdk_python_pip outside_restricted project_host bindings async
sdk_python_project_interpreters outside_restricted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
@@ -595,10 +596,10 @@ term_resize always project_host bin
term_spawn always project_host bindings async
term_store_image always project_host bindings async
term_write always project_host bindings sync
tools_install trusted project_host bindings async
tools_list trusted project_host bindings async
tools_uninstall trusted project_host bindings async
tools_updates trusted project_host bindings async
tools_install outside_restricted project_host bindings async
tools_list outside_restricted project_host bindings async
tools_uninstall outside_restricted project_host bindings async
tools_updates outside_restricted project_host bindings async
undo_workspace_edit always project_host bindings async
user_font_data always desktop - async
vcs_add_to_ignore trusted project_host bindings async
+23 -1
View File
@@ -452,6 +452,11 @@ export const commands = {
* (a remote window passes the sides as text).
*/
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
/**
* An automatic save: `false` (nothing written) when the file changed on disk after the
* buffer was edited, which only an explicit save overwrites.
*/
docAutosave: (doc: DocId) => typedError<boolean, IdeError>(__TAURI_INVOKE("doc_autosave", { doc })),
docClose: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_close", { doc })),
/**
* Applies a CodeMirror change set; returns the new version. Rejects with
@@ -1810,7 +1815,10 @@ export const commands = {
webServesPage: (url: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("web_serves_page", { url })),
/** Paths in an HTML document or stylesheet that name no existing file. */
webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
/** The built-in server's URL for `path` (started on first use). */
/**
* The built-in server's URL for `path` (started on first use). A file whose language is
* HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
*/
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Release the opening window's reservation after navigation or cancellation. */
@@ -7417,6 +7425,10 @@ export type LanguageCodeStyle_Deserialize = {
lineCommentAtFirstColumn?: boolean | null,
/** Comment Code › Add a space at line comment start. */
lineCommentAddSpace?: boolean | null,
/** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */
alignKeyValuePairs?: boolean | null,
/** PHP: align `=` of consecutive assignment statements after formatting. */
alignConsecutiveAssignments?: boolean | null,
};
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
@@ -7433,6 +7445,10 @@ export type LanguageCodeStyle_Serialize = {
lineCommentAtFirstColumn?: boolean | null,
/** Comment Code › Add a space at line comment start. */
lineCommentAddSpace?: boolean | null,
/** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */
alignKeyValuePairs?: boolean | null,
/** PHP: align `=` of consecutive assignment statements after formatting. */
alignConsecutiveAssignments?: boolean | null,
};
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
@@ -8087,6 +8103,12 @@ export type MavenSettings = {
activeProfiles?: string,
/** Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). */
delegateBuild?: boolean,
/**
* Download `-sources.jar` of dependencies when the Java language server imports the
* project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
* from a library class's Download Sources banner.
*/
downloadSources?: boolean,
};
/** Summary of one server discovered inside an external MCP configuration file. */
+3
View File
@@ -49,6 +49,8 @@ export interface DocBackend {
close(doc: DocId): Promise<void>;
edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise<number>;
save(doc: DocId): Promise<void>;
/** An automatic save; `false` when the file changed on disk after the buffer was edited (nothing written). */
autosave?(doc: DocId): Promise<boolean>;
/** Re-check every open file for external changes missed by file watchers. */
syncFromDisk?(): Promise<void>;
snapshot(doc: DocId): Promise<DocumentInfo>;
@@ -92,6 +94,7 @@ export const ipcBackend: DocBackend = {
close: async (doc) => void (await call(commands.docClose(doc))),
edit: (doc, baseVersion, changes) => call(commands.docEdit(doc, baseVersion, { changes })),
save: async (doc) => void (await call(commands.docSave(doc))),
autosave: (doc) => call(commands.docAutosave(doc)),
syncFromDisk: async () => void (await call(commands.docSyncFromDisk())),
snapshot: (doc) => call(commands.docSnapshot(doc)),
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
+45 -1
View File
@@ -1,10 +1,11 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, Prec } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { setSearchQuery } from "@codemirror/search";
import { StreamLanguage } from "@codemirror/language";
import { literalKindAt } from "./literals";
import { selectionMarks } from "./selectionMarks";
import { findStyles, markWidgetStyles } from "./theme";
import {
countMatches,
findResultLines,
@@ -41,6 +42,49 @@ function make(doc: string, o: Partial<FindOptions>, scope?: { from: number; to:
const sel = (v: EditorView) => [v.state.selection.main.from, v.state.selection.main.to];
class TextWidget extends WidgetType {
toDOM() {
const el = document.createElement("span");
el.className = "widget";
el.textContent = "hint";
return el;
}
}
describe("widgets inside find matches", () => {
it.each([
["before the cursor side", Decoration.widget({ widget: new TextWidget(), side: -1 }).range(3)],
["after the cursor side", Decoration.widget({ widget: new TextWidget(), side: 1 }).range(3)],
["replacing text", Decoration.replace({ widget: new TextWidget() }).range(2, 4)],
])("keep their own colour %s", (_name, widget) => {
const view = new EditorView({
parent: document.body,
doc: "Session",
extensions: [
// At the top precedence, as only then does the match wrap the widget.
Prec.highest(EditorView.decorations.of(Decoration.set(widget))),
findExtension(),
],
});
views.push(view);
view.dispatch({
effects: [
setFindOpen.of(true),
setSearchQuery.of(
makeQuery({ search: "Session", caseSensitive: true, wholeWord: false, regexp: false, replace: "" }),
),
],
});
const el = view.contentDOM.querySelector<HTMLElement>(".cm-openidea-findMatch .widget")!;
// Browsers reflect this property to the attribute; jsdom does not.
el.setAttribute("contenteditable", el.contentEditable);
expect(el.matches(Object.keys(markWidgetStyles)[0]!)).toBe(true);
expect(Object.values(markWidgetStyles)[0]!.WebkitTextFillColor).toBe("currentcolor");
// A text fill of `--fg-search-match` here would reach every widget in the match.
expect(findStyles[".cm-openidea-findMatch"].WebkitTextFillColor).toBe("currentcolor");
});
});
describe("find backgrounds", () => {
it.each([
["semantic", Prec.highest],
+122 -2
View File
@@ -1,12 +1,17 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { codeFolding, foldEffect, foldService, foldedRanges } from "@codemirror/language";
import { codeFolding, foldEffect, foldService, foldable, foldedRanges } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import {
backendFoldingChanged,
backendFolds,
enclosingFoldRange,
expandToLevelEffects,
foldSelectionEffects,
foldToExpand,
foldsFromRanges,
foldingExtension,
foldToExpand,
setBackendFolds,
} from "./folding";
/** Folds `{ … }` blocks whose header line ends with `{`. */
@@ -68,6 +73,29 @@ describe("foldToExpand", () => {
describe("foldsFromRanges", () => {
const fold = (start_line: number, end_line: number) => ({ start_line, end_line, kind: "region" as const });
it("collapses an import group beginning with a multiline statement to import only", () => {
const s = EditorState.create({
doc: [
"import Widget, {",
" Formatter,",
" parseValue,",
"} from './format.js';",
"import { render } from './view.js';",
"",
].join("\n"),
extensions: [foldingExtension(false)],
});
const ranges = [{ start_line: 0, end_line: 4, kind: "imports" as const }];
const [f] = foldsFromRanges(s, ranges);
expect(f).toEqual({ from: "import ".length, to: s.doc.line(5).to, kind: "imports" });
const state = s.update({ effects: setBackendFolds.of(ranges) }).state;
expect(foldable(state, state.doc.line(1).from, state.doc.line(1).to)).toEqual({ from: f!.from, to: f!.to });
const view = new EditorView({ state, parent: document.createElement("div") });
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
expect(view.dom.querySelector(".cm-line")?.textContent).toBe("import …");
view.destroy();
});
it("starts an Allman block's fold on its declaration line", () => {
const s = EditorState.create({ doc: "namespace Demo\n{\n class A\n {\n }\n}\n" });
const folds = foldsFromRanges(s, [fold(1, 5), fold(3, 4)]);
@@ -159,3 +187,95 @@ describe("expandToLevelEffects", () => {
expect(folded(s.update({ effects: expandToLevelEffects(s, 2) }).state)).toEqual([]);
});
});
describe("fold gutter chevrons", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
it("backendFoldingChanged fires when backend folds arrive, not on selection moves", () => {
let changed = false;
const view = new EditorView({
state: EditorState.create({
doc,
extensions: [
foldingExtension(true),
// The same predicate the fold gutter's foldingChanged hook uses.
EditorView.updateListener.of((u) => {
if (backendFoldingChanged(u)) changed = true;
}),
],
}),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
expect(changed).toBe(true);
changed = false;
view.dispatch({ selection: { anchor: 0 } });
expect(changed).toBe(false);
view.destroy();
});
it("the gutter shows a chevron after backend folds arrive", () => {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
const markers = () =>
Array.from(view.dom.querySelectorAll<HTMLElement>(".cm-foldGutter .cm-gutterElement")).map(
(el) => el.firstElementChild?.className ?? "",
);
const before = markers();
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
const after = markers();
expect(after.join("|")).not.toBe(before.join("|"));
view.destroy();
});
});
describe("fold placeholder chip", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
function foldedView() {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
return view;
}
function folded(view: ReturnType<typeof foldedView>) {
const out: Array<[number, number]> = [];
foldedRanges(view.state).between(0, view.state.doc.length, (a, b) => void out.push([a, b]));
return out;
}
function fold(view: ReturnType<typeof foldedView>) {
const [f] = view.state.field(backendFolds);
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
}
it("clicking the chip expands the fold, repeatedly", () => {
const view = foldedView();
for (let i = 0; i < 3; i++) {
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder");
expect(chip, `iteration ${i}`).not.toBeNull();
chip!.click();
expect(folded(view), `iteration ${i}`).toEqual([]);
}
view.destroy();
});
it("a chip whose position is the fold's start line still expands", () => {
const view = foldedView();
const [f] = view.state.field(backendFolds);
// A docstring fold starts at the end of its header line: a chip resolved
// through the line block would land on that line and find no fold.
expect(view.state.doc.lineAt(f!.from).to).toBe(f!.from);
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder")!;
chip.click();
expect(folded(view)).toEqual([]);
view.destroy();
});
});
+27 -7
View File
@@ -12,7 +12,7 @@ import {
type Extension,
type Line,
} from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { EditorView, ViewUpdate } from "@codemirror/view";
import {
codeFolding,
foldEffect,
@@ -64,12 +64,14 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
continue;
}
const start = allmanHeader(state, first);
const importHead = r.kind === "imports" && /^\s*import\s+/.exec(first.text);
const from = importHead && /(?:\{|,)\s*$/.test(first.text) ? first.from + importHead[0].length : start.to;
const trimmed = end.text.trimStart();
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA. An import
// run ending in `} from '…'` hides that whole statement; a bare `)` / `};` still shows.
const delimiter = r.kind === "imports" ? /^[}\])]+[;,]?$/.test(trimmed.trimEnd()) : /^[}\])]/.test(trimmed);
const to = delimiter ? end.from + (end.text.length - trimmed.length) : end.to;
if (to > start.to) out.push({ from: start.to, to, kind: r.kind });
if (to > from) out.push({ from, to, kind: r.kind });
}
return out.sort((a, b) => a.from - b.from || b.to - a.to);
}
@@ -101,8 +103,8 @@ function foldAtLine(folds: readonly BackendFold[], lineStart: number, lineEnd: n
let best: BackendFold | null = null;
for (let i = lo; i < folds.length && folds[i]!.from <= lineEnd; i++) {
const f = folds[i]!;
// Only folds whose header ends on this line (custom regions: on this line); keep the widest.
if ((f.from === lineEnd || f.custom) && (!best || f.to > best.to)) best = f;
// Multiline import groups and custom regions can start within their header line.
if ((f.from === lineEnd || f.custom || f.kind === "imports") && (!best || f.to > best.to)) best = f;
}
return best;
}
@@ -392,22 +394,40 @@ function chevron(open: boolean): HTMLElement {
return span;
}
/**
* Backend folds arrive asynchronously (`setBackendFolds`) and are not a document,
* viewport or language change, so CodeMirror's fold gutter keeps the chevrons it
* built before they arrived. A click then hits a gutter element at a stale line
* and silently does nothing. Rebuild the markers whenever the backend field changes.
*/
export function backendFoldingChanged(update: ViewUpdate): boolean {
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
}
export function foldingExtension(showOutline = true): Extension {
return [
// The chevron column sits right of contributed icon gutters (IDEA new UI).
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron })) : [],
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron, foldingChanged: backendFoldingChanged })) : [],
backendFolds,
backendFoldService,
codeFolding({
// A folded custom region shows its name, as in IDEA.
preparePlaceholder: (state, range) => regionNameAt(state, range.from),
placeholderDOM: (_view, onclick, name: string | null) => {
placeholderDOM: (view, onclick, name: string | null) => {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.textContent = name ?? "…";
el.title = "Expand";
el.setAttribute("aria-label", "folded code");
el.onclick = onclick;
el.onclick = (event) => {
// CodeMirror's own handler resolves the fold through the clicked line
// block, which can miss a fold starting at a line boundary (docstring,
// Allman header). Resolving at the chip's own position cannot miss.
const folded = foldToExpand(view.state, view.posAtDOM(el));
if (folded) view.dispatch({ effects: unfoldEffect.of(folded) });
else onclick(event);
event.preventDefault();
};
return el;
},
}),
+1
View File
@@ -46,6 +46,7 @@ const theme = EditorView.baseTheme({
boxDecorationBreak: "clone",
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
color: "var(--fg-editor-selection)",
WebkitTextFillColor: "var(--fg-editor-selection)",
},
"&.cm-focused .cm-openidea-selected": {
"--openidea-selected-bg": "var(--editor-selection, var(--bg-editor-selection))",
+10
View File
@@ -24,6 +24,8 @@ export const findStyles = {
".cm-openidea-findMatch": {
backgroundColor: "var(--editor-search)",
color: "var(--fg-search-match, inherit)",
// Its own colour, over the text fill of an identifier highlight around the match.
WebkitTextFillColor: "currentcolor",
borderRadius: "2px",
},
".cm-openidea-findExcluded": {
@@ -40,6 +42,11 @@ export const findStyles = {
},
};
/** Marks colour text with an inherited text fill; widgets inside them keep their own colours. */
export const markWidgetStyles = {
'.cm-content [contenteditable="false"]': { WebkitTextFillColor: "currentcolor" },
};
/** The caret and Settings › Editor › General › Appearance caret options (`caretExtension`), also for viewers. */
export const caretStyles = {
".cm-cursor, .cm-dropCursor": {
@@ -219,6 +226,8 @@ export const openideaTheme = EditorView.theme({
".cm-selectionMatch": {
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
},
// IDEA paints these with IDENTIFIER_UNDER_CARET_ATTRIBUTES, except the selection itself.
".cm-selectionMatch:not(.cm-selectionMatch-main)": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
// 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)",
@@ -343,6 +352,7 @@ export const openideaTheme = EditorView.theme({
// Find in file (cm/find.ts)
...findStyles,
...markWidgetStyles,
// Find in Files preview matches (search/find/parts.tsx)
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
+41
View File
@@ -271,6 +271,26 @@ describe("DocumentManager + slots", () => {
}
});
it("keeps the buffer dirty when the backend declines an autosave", async () => {
const { backend, manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(model, "t1", host);
slot.dispatchLocal({ changes: { from: 0, to: 1, insert: "X" } });
backend.autosave = vi.fn(async () => false);
const save = vi.spyOn(backend, "save");
try {
await model.save("auto");
expect(backend.autosave).toHaveBeenCalledTimes(1);
expect(save).not.toHaveBeenCalled();
expect(model.getMeta().dirty).toBe(true);
await model.save("explicit");
expect(save).toHaveBeenCalledTimes(1);
expect(model.getMeta().dirty).toBe(false);
} finally {
manager.stop();
}
});
it("closes the backend document when the last slot goes away", async () => {
const { backend, manager } = setup({ "/p/a.txt": "x" });
const model = await manager.acquire("/p/a.txt");
@@ -328,6 +348,27 @@ describe("DocumentManager + slots", () => {
manager.stop();
});
it("keeps a modified file open when its last tab closes without autosave, and reopens it with the changes", async () => {
const { backend, manager } = setup({ "/p/a.txt": "a\n", "/p/b.txt": "b\n" }, { files: { autoSave: false } });
try {
const a = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(a, "t1", host);
backend.patch(a.doc, [{ from: 0, to: 0, insert: "changed " }]);
slot.dispose();
const b = await manager.acquire("/p/b.txt");
new EditorSlot(b, "t2", host).dispose();
await new Promise((r) => setTimeout(r, 0));
expect(backend.files.get("/p/a.txt")).toBe("a\n");
expect(await manager.acquire("/p/a.txt")).toBe(a);
expect(a.getMeta().dirty).toBe(true);
expect(manager.byPath.has("/p/b.txt")).toBe(false);
await manager.saveAll("explicit");
expect(backend.files.get("/p/a.txt")).toBe("changed a\n");
} finally {
manager.stop();
}
});
it("Save All rejects a failed document save after saving the remaining dirty documents", async () => {
const { backend, manager } = setup({ "/p/a.txt": "a\n", "/p/b.txt": "b\n" }, { files: { autoSave: false } });
try {
+9 -1
View File
@@ -711,7 +711,11 @@ export class DocModel {
if (await this.manager.saveAs(this)) this.modified.clear();
return;
}
await this.manager.backend.save(this.doc);
const backend = this.manager.backend;
// Autosave never overwrites external changes made after the buffer was edited.
if (reason === "auto" && backend.autosave) {
if (!(await backend.autosave(this.doc))) return;
} else await backend.save(this.doc);
this.modified.clear();
this.setMeta({ dirty: false });
_emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path });
@@ -899,6 +903,10 @@ export class DocumentManager {
console.warn(`autosave of ${model.path} failed`, e);
}
}
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
// open without a tab: reopening shows the changes, and Save All and the exit check still
// cover them. An untitled buffer was asked about when its tab closed.
if (model.getMeta().dirty && !isUntitledUri(model.path)) return;
if (model.inUse()) return;
await model.sync.whenIdle();
if (model.inUse()) return;
+7 -1
View File
@@ -1240,6 +1240,12 @@ const marks = {
read: Decoration.mark({ class: KIND_CLASS.read }),
write: Decoration.mark({ class: KIND_CLASS.write }),
};
/** The text a multi-line highlight paints with line backgrounds: a line class would also colour its indent. */
const lineText = {
text: Decoration.mark({ class: "cm-lsp-occurrence-text" }),
read: Decoration.mark({ class: "cm-lsp-occurrence-text" }),
write: Decoration.mark({ class: "cm-lsp-occurrence-text cm-lsp-occurrence-text-write" }),
};
const fullLines = {
text: Decoration.line({ class: KIND_CLASS.text }),
read: Decoration.line({ class: KIND_CLASS.read }),
@@ -1266,7 +1272,7 @@ function highlightDeco(doc: Text, tabSize: number, items: readonly HighlightItem
class: i.kind === "write" ? "cm-lsp-occurrence-tail cm-lsp-occurrence-tail-write" : "cm-lsp-occurrence-tail",
attributes: { style: `--lsp-occurrence-from: calc(${LINE_INSET}px + ${col}ch)` },
});
out.push(tail.range(first.from));
out.push(tail.range(first.from), lineText[i.kind].range(i.from, last.from));
for (let n = first.number + 1; n < last.number; n++) out.push(fullLines[i.kind].range(doc.line(n).from));
if (i.to > last.from) out.push(marks[i.kind].range(last.from, i.to));
}
+7
View File
@@ -314,6 +314,7 @@ export const lspTheme = EditorView.theme({
// --- navigation ---------------------------------------------------------
".cm-lsp-link": {
color: "var(--link)",
WebkitTextFillColor: "currentcolor",
textDecoration: "underline",
textUnderlineOffset: "2px",
cursor: "pointer",
@@ -325,6 +326,12 @@ export const lspTheme = EditorView.theme({
"--lsp-occurrence-bg": "var(--bg-identifier-under-caret-write, color-mix(in srgb, var(--danger) 12%, transparent))",
},
".cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
// Text fill, not `color`: it reaches the syntax and semantic spans nested inside, and with the
// variable unset the declaration drops, so they keep their own colours.
"span.cm-lsp-occurrence, .cm-lsp-occurrence-text": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
"span.cm-lsp-occurrence-write, .cm-lsp-occurrence-text-write": {
WebkitTextFillColor: "var(--fg-identifier-under-caret-write)",
},
// First line of a highlight over several lines: from its start column to the right edge,
// over the line's own background (the caret row's).
".cm-lsp-occurrence-tail": {
+20
View File
@@ -72,6 +72,26 @@ describe("highlights of the element at the caret", () => {
expect(lines(v)[4]!.className).not.toContain("cm-lsp-occurrence");
});
it.each([
["text", ""],
["write", "-write"],
] as const)(
"marks exactly the text of a %s highlight over several lines for its foreground",
async (kind, suffix) => {
cmd.lspDocumentHighlights.mockImplementation(() => ok([{ range: range(1, 4, 3, 13), kind }]));
const v = editor(at(1, 4));
highlightUsages(v);
await vi.waitFor(() => expect(v.contentDOM.querySelector(".cm-lsp-occurrence-text")).not.toBeNull());
const text = (line: number) =>
[...lines(v)[line]!.querySelectorAll(`.cm-lsp-occurrence-text${suffix}`)].map((e) => e.textContent).join("");
// Not the indent before the start column; the last line is the highlight's own mark.
expect(text(1)).toBe("return a");
expect(text(2)).toBe(" .b()");
expect(text(3)).toBe("");
expect(lines(v)[3]!.querySelector(`span.cm-lsp-occurrence${suffix}`)?.textContent).toBe(" .c();");
},
);
it("keeps a single-line highlight on its text", async () => {
cmd.lspDocumentHighlights.mockImplementation(() => ok([{ range: range(6, 11, 6, 12), kind: "read" }]));
const v = editor(at(6, 11));
+62 -31
View File
@@ -40,6 +40,7 @@ import {
producerFor,
sortProblems,
useProblems,
type FileDiagnostics,
type ProblemOrder,
type ProblemsMap,
} from "./problemsStore";
@@ -113,9 +114,8 @@ export function useProblemsHeaderMenu(): MenuItem[] {
const group = (s: Severity): "error" | "warning" | "info" => (s === "hint" ? "info" : s);
type Node =
| { kind: "file"; key: string; path: string; items: Diagnostic[] }
| { kind: "diag"; key: string; path: string; d: Diagnostic };
type FileNode = { kind: "file"; key: string; path: string; items: Diagnostic[]; error: boolean };
type Node = FileNode | { kind: "diag"; key: string; path: string; d: Diagnostic };
/** The inspection that reported `d` (for Disable inspection / Change Severity). */
export function diagInspection(map: ProblemsMap, path: string, d: Diagnostic): InspectionRef | null {
@@ -129,23 +129,64 @@ const plural = (n: number, word: string) => (n ? `${n} ${word}${n === 1 ? "" : "
const SEVERITY_ICON: Record<Severity, string> = { error: "error", warning: "warning", info: "info", hint: "info" };
interface CachedFileNode {
path: string;
show: ViewState["show"];
order: ProblemOrder;
node: FileNode | null;
}
// Keyed by the file's sources map, which the store replaces only when that file's diagnostics
// change: a single-file update re-filters and re-sorts that file alone.
const fileNodes = new WeakMap<FileDiagnostics, CachedFileNode>();
function fileNode(map: ProblemsMap, path: string, show: ViewState["show"], order: ProblemOrder): FileNode | null {
const sources = map.get(path);
if (!sources) return null;
const hit = fileNodes.get(sources);
if (
hit?.path === path &&
hit.show.error === show.error &&
hit.show.warning === show.warning &&
hit.show.info === show.info &&
hit.order.bySeverity === order.bySeverity &&
hit.order.byName === order.byName
)
return hit.node;
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
const node: FileNode | null = items.length
? { kind: "file", key: path, path, items, error: items.some((d) => d.severity === "error") }
: null;
fileNodes.set(sources, { path, show: { ...show }, order: { ...order }, node });
return node;
}
export function buildProblemNodes(
map: ProblemsMap,
paths: readonly string[],
show: ViewState["show"],
order: ProblemOrder = DEFAULT_PROBLEM_ORDER,
): Node[] {
const files: Node[] = [];
): FileNode[] {
const files: FileNode[] = [];
for (const path of paths) {
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
if (!items.length) continue;
files.push({ kind: "file", key: path, path, items });
const node = fileNode(map, path, show, order);
if (node) files.push(node);
}
const rank = (n: Node) => (n.kind === "file" ? (n.items.some((d) => d.severity === "error") ? 0 : 1) : 2);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
return files.sort((a, b) => Number(!a.error) - Number(!b.error) || a.path.localeCompare(b.path));
}
const diagNodes = new WeakMap<FileNode, Node[]>();
function diagChildren(n: FileNode): Node[] {
let children = diagNodes.get(n);
if (!children) {
children = n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }));
diagNodes.set(n, children);
}
return children;
}
function open(path: string, d: Diagnostic, focus = true): Promise<void> {
@@ -200,19 +241,15 @@ export function ProblemsHeaderActions() {
/** Scope tabs in the tool window header: "File: name 2" / "Project Errors". */
export function ProblemsTabs() {
const map = useProblems((s) => s.map);
const tab = useProblemsView((s) => s.tab);
const setTab = useProblemsView((s) => s.setTab);
const current = useCurrentPath();
const fileCount = current
? countSeverities(filePaths(map, current).flatMap((path) => fileDiagnostics(map, path)))
: null;
const projectErrors = useMemo(() => {
let n = 0;
for (const sources of map.values())
for (const items of sources.values()) n += items.filter((d) => d.severity === "error").length;
return n;
}, [map]);
const fileCount = useProblems((s) => {
if (!current) return 0;
const c = countSeverities(filePaths(s.map, current).flatMap((path) => fileDiagnostics(s.map, path)));
return c.error + c.warning;
});
const projectErrors = useProblems((s) => s.counts.error);
return (
<Tabs
variant="compact"
@@ -231,10 +268,7 @@ export function ProblemsTabs() {
"File"
),
text: "File",
trailing:
fileCount && fileCount.error + fileCount.warning > 0 ? (
<span className={styles.tabCount}>{fileCount.error + fileCount.warning}</span>
) : undefined,
trailing: fileCount > 0 ? <span className={styles.tabCount}>{fileCount}</span> : undefined,
},
{
id: "project",
@@ -297,10 +331,7 @@ export function ProblemsView() {
);
const getChildren = useCallback(
(n: Node): Node[] | undefined =>
n.kind === "file"
? n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }) as Node)
: undefined,
(n: Node): Node[] | undefined => (n.kind === "file" ? diagChildren(n) : undefined),
[],
);
+1 -6
View File
@@ -29,12 +29,7 @@ import { installWorkspaceEditUndo } from "./workspaceUndo";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
function useErrorBadge(): number | null {
return useProblems((s) => {
let n = 0;
for (const sources of s.map.values())
for (const items of sources.values()) for (const d of items) if (d.severity === "error") n++;
return n || null;
});
return useProblems((s) => s.counts.error || null);
}
export function activate(): () => void {
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { Diagnostic } from "@/bindings";
import { useProject } from "@/platform/project";
import {
applyDiagnosticsEvent,
clearProblems,
@@ -7,6 +8,7 @@ import {
currentProblemsPath,
fileDiagnostics,
filePaths,
installProblemsEvents,
mergeDiagnostics,
problemsReport,
profiledProblems,
@@ -151,3 +153,53 @@ describe("problemsReport", () => {
expect(problemsReport(mergeDiagnostics(new Map(), "/p/a", "x", [d(0, "info")]), "/p")).toBeNull();
});
});
describe("incremental bookkeeping", () => {
let seed = 7;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const items = (): Diagnostic[] =>
Array.from({ length: random(5) }, () => ({
...d(random(3), SEVERITIES[random(4)]),
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
code: String(random(1000)),
}));
// The merge as it was before it was cached.
const fullMerge = (map: ReturnType<typeof useProblems.getState>["map"], path: string) =>
[...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
it("keeps the project counts and each file's merged list equal to a full rescan", () => {
clearProblems();
useProject.setState({ settings: {} as never });
const off = installProblemsEvents();
try {
for (let step = 0; step < 400; step++) {
if (step === 150)
useProject.setState({
settings: { inspections: { default: { "lsp:eslint": { enabled: false } } } } as never,
});
if (step === 250)
useProject.setState({
settings: { inspections: { default: { "lsp:ra": { severity: "weakWarning" } } } } as never,
});
if (step === 300) clearProblems();
const path = `/p/${random(12)}.rs`;
applyDiagnosticsEvent(path, ["ra", "eslint"][random(2)]!, items());
const { map, counts } = useProblems.getState();
expect(counts).toEqual(projectCounts(map));
for (const p of map.keys()) expect(fileDiagnostics(map, p)).toEqual(fullMerge(map, p));
}
} finally {
off();
useProject.setState({ settings: {} as never });
clearProblems();
}
});
});
+37 -13
View File
@@ -49,18 +49,26 @@ export function mergeDiagnostics(
const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2, hint: 3 };
// A file's sources map is replaced whenever its diagnostics change, so it keys the merged list.
const merged = new WeakMap<FileDiagnostics, readonly Diagnostic[]>();
/** All diagnostics of a file across sources, ordered by position then severity. */
export function fileDiagnostics(map: ProblemsMap, path: string): Diagnostic[] {
export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] {
const sources = map.get(path);
if (!sources) return [];
return [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
let items = merged.get(sources);
if (!items) {
items = [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
merged.set(sources, items);
}
return items;
}
/** The producer (inspection) that reported `d`, one of `path`'s problems in `map`. */
@@ -158,21 +166,34 @@ interface ProblemsState {
raw: ProblemsMap;
/** What the views show. */
map: ProblemsMap;
/** `projectCounts(map)`, kept up to date per event. */
counts: SeverityCounts;
}
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map() }));
const NO_COUNTS: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 };
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map(), counts: NO_COUNTS }));
function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added: readonly Diagnostic[]) {
const c = { ...counts };
for (const d of removed) c[d.severity]--;
for (const d of added) c[d.severity]++;
return c;
}
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
useProblems.setState((s) => {
const raw = mergeDiagnostics(s.raw, path, source, items);
if (raw === s.raw) return s;
const map = mergeDiagnostics(s.map, path, source, applyProfile(inspectionProfile(), source, items));
return { raw, map };
if (map === s.map) return { raw };
const before = s.map.get(path)?.get(source) ?? [];
return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) };
});
}
export function clearProblems() {
useProblems.setState({ raw: new Map(), map: new Map() });
useProblems.setState({ raw: new Map(), map: new Map(), counts: NO_COUNTS });
}
export function installProblemsEvents(): () => void {
@@ -180,7 +201,10 @@ export function installProblemsEvents(): () => void {
// Typo, file references, SQL: inspections the editor runs itself.
const offLocal = onLocalDiagnostics(applyDiagnosticsEvent);
const offProfile = subscribeInspectionProfile(() =>
useProblems.setState((s) => ({ map: profiledProblems(s.raw, inspectionProfile()) })),
useProblems.setState((s) => {
const map = profiledProblems(s.raw, inspectionProfile());
return { map, counts: projectCounts(map) };
}),
);
return () => {
off();
@@ -0,0 +1,92 @@
/**
* Problems tool window under a diagnostics storm: a workspace of 2,000 files with 30,000
* diagnostics, then 200 single-file updates, each rendered by the mounted header tabs and list.
* One sample is the time for all 200 updates; prints each sample and the median.
* Skipped unless asked for:
*
* PROBLEMS_BENCH=1 pnpm vitest run src/features/code-insight/problemsStorm.bench.test.tsx --silent=false
*/
import { act, render } from "@testing-library/react";
import { describe, it } from "vitest";
import type { Diagnostic, Severity } from "@/bindings";
import { ProblemsTabs, ProblemsView, useProblemsView } from "./ProblemsView";
import { applyDiagnosticsEvent, clearProblems } from "./problemsStore";
const FILES = 2000;
const LSP_PER_FILE = 10;
const LINT_PER_FILE = 5;
const UPDATES = 200;
let seed = 1;
const random = () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
const SEVERITIES: Severity[] = ["error", "warning", "warning", "info", "hint"];
function diagnostics(count: number, salt: number): Diagnostic[] {
return Array.from({ length: count }, (_, i) => {
const line = Math.floor(random() * 400);
const col = Math.floor(random() * 80);
return {
range: { start: { line, col }, end: { line, col: col + 4 } },
severity: SEVERITIES[(i + salt) % SEVERITIES.length]!,
message: `Problem ${Math.floor(random() * 500)} near symbol${salt}_${i}`,
source: null,
code: null,
} as Diagnostic;
});
}
const paths = Array.from({ length: FILES }, (_, i) => `/p/src/module${i % 40}/File${i}.ts`);
const initial = paths.map((path, i) => ({
path,
lsp: diagnostics(LSP_PER_FILE, i),
lint: diagnostics(LINT_PER_FILE, i + 1),
}));
const updates = Array.from({ length: UPDATES }, (_, k) => ({
path: paths[Math.floor(random() * FILES)]!,
items: diagnostics(LSP_PER_FILE, k + 7),
}));
function loadWorkspace() {
clearProblems();
for (const f of initial) {
applyDiagnosticsEvent(f.path, "lsp", f.lsp);
applyDiagnosticsEvent(f.path, "eslint", f.lint);
}
}
function storm(tab: "file" | "project") {
loadWorkspace();
useProblemsView.setState({ tab });
const view = render(
<>
<ProblemsTabs />
<ProblemsView />
</>,
);
// Only the updates are timed, not loading the workspace or the first render.
const start = performance.now();
for (const u of updates) act(() => applyDiagnosticsEvent(u.path, "lsp", u.items));
const ms = performance.now() - start;
view.unmount();
return ms;
}
const RUNS = 7;
function measure(tab: "file" | "project") {
storm(tab); // warm-up
const samples = Array.from({ length: RUNS }, () => storm(tab)).sort((a, b) => a - b);
const median = samples[RUNS >> 1]!;
console.log(
`${tab} tab: median ${median.toFixed(1)} ms per ${UPDATES} updates (${(median / UPDATES).toFixed(2)} ms/update); ` +
`samples ${samples.map((s) => s.toFixed(1)).join(", ")}`,
);
}
describe.skipIf(!process.env.PROBLEMS_BENCH)(
`Problems: ${FILES} files, ${FILES * (LSP_PER_FILE + LINT_PER_FILE)} diagnostics, ${UPDATES} single-file updates`,
() => {
it("Project Errors tab", () => measure("project"), 600_000);
it("File tab", () => measure("file"), 600_000);
},
);
+82 -1
View File
@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";
import { groupUsages, trimPreview, usageCount } from "./usages";
import { serversSummary, type ServerEntry } from "./servers";
import { buildProblemNodes } from "./ProblemsView";
import { mergeDiagnostics, sortProblems } from "./problemsStore";
import type { Diagnostic } from "@/bindings";
import { mergeDiagnostics, sortProblems, type ProblemOrder, type ProblemsMap } from "./problemsStore";
import { toggleExcludedUsages } from "./UsagesView";
import { childId, directionLabel } from "./hierarchy";
@@ -66,6 +67,86 @@ describe("buildProblemNodes", () => {
expect(errorsOnly.map((n) => n.key)).toEqual(["/b"]);
expect(errorsOnly[0]!.kind === "file" && errorsOnly[0]!.items.length).toBe(1);
});
it("matches a full rebuild across single-file updates, filters and sort orders", () => {
let seed = 11;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const MESSAGES = ["alpha", "Alpha", "beta 2", "beta 10"];
const items = (): Diagnostic[] =>
Array.from({ length: random(6) }, () => ({
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
severity: SEVERITIES[random(4)]!,
message: MESSAGES[random(4)]!,
source: null,
code: String(random(1000)),
}));
// buildProblemNodes as it was before per-file caching.
const rebuild = (map: ProblemsMap, paths: string[], show: Record<string, boolean>, order: ProblemOrder) => {
const files = paths.flatMap((path) => {
const all = [...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
const shown = sortProblems(
all.filter((d) => show[d.severity === "hint" ? "info" : d.severity]),
order,
);
return shown.length ? [{ path, items: shown }] : [];
});
const rank = (f: { items: Diagnostic[] }) => (f.items.some((d) => d.severity === "error") ? 0 : 1);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
};
// Neighbours differ in one flag, so a cache that ignored any of them would serve stale nodes.
const shows = ["111", "101", "100", "000", "010", "011"].map(([e, w, i]) => ({
error: e === "1",
warning: w === "1",
info: i === "1",
}));
const orders = ["10", "00", "01", "11"].map(([s, n]) => ({ bySeverity: s === "1", byName: n === "1" }));
let map: ProblemsMap = new Map();
for (let step = 0; step < 300; step++) {
const path = `/p/${["b", "A", "a", "c10", "c2"][random(5)]}/${random(4)}.ts`;
map = mergeDiagnostics(map, path, ["lsp", "eslint"][random(2)]!, items());
const show = shows[Math.floor(step / 20) % shows.length]!;
const order = orders[Math.floor(step / 35) % orders.length]!;
const paths = [...map.keys()];
const nodes = buildProblemNodes(map, paths, { ...show }, { ...order });
expect(nodes.map((n) => ({ path: n.path, items: n.items }))).toEqual(rebuild(map, paths, show, order));
const some = paths.filter((_, i) => i % 3 === 0);
expect(buildProblemNodes(map, some, show, order).map((n) => ({ path: n.path, items: n.items }))).toEqual(
rebuild(map, some, show, order),
);
}
});
it("reuses the nodes of files an update didn't touch", () => {
const diag = (line: number) => ({
range: { start: { line, col: 0 }, end: { line, col: 1 } },
severity: "error" as const,
message: "x",
source: null,
code: null,
});
const show = { error: true, warning: true, info: true };
let map = mergeDiagnostics(new Map(), "/a", "s", [diag(1)]);
map = mergeDiagnostics(map, "/b", "s", [diag(2)]);
const [a, b] = buildProblemNodes(map, ["/a", "/b"], show);
map = mergeDiagnostics(map, "/b", "s", [diag(3)]);
const [a2, b2] = buildProblemNodes(map, ["/a", "/b"], show);
expect(a2).toBe(a);
expect(b2).not.toBe(b);
const shared = map.get("/a")!;
const twice = new Map([
["/a", shared],
["/c", shared],
]);
expect(buildProblemNodes(twice, ["/a", "/c"], show).map((n) => n.path)).toEqual(["/a", "/c"]);
});
});
describe("hierarchy", () => {
+33 -5
View File
@@ -39,13 +39,41 @@ const PAGE_SIZES = ["100", "500", "1000", "5000"];
export { tableTitle } from "./tableInput";
/** WHERE, ORDER BY and page of a table tab, kept when a tab that is no longer kept alive mounts again. */
interface TableViewState {
offset: number;
limit: number;
sort: DbSortKey[];
filterText: string;
filter: string;
}
const MAX_VIEW_STATES = 100;
const viewStates = new Map<string, TableViewState>();
function rememberViewState(key: string, state: TableViewState) {
viewStates.delete(key);
viewStates.set(key, state);
if (viewStates.size > MAX_VIEW_STATES) viewStates.delete(viewStates.keys().next().value!);
}
/** Test hook: forget the remembered table view states. */
export function _resetTableViewStates() {
viewStates.clear();
}
export function TableEditor({ input }: { input: EditorInput }) {
const ref = input.data as TableRef;
const [offset, setOffset] = useState(0);
const [limit, setLimit] = useState(500);
const [sort, setSort] = useState<DbSortKey[]>([]);
const [filterText, setFilterText] = useState("");
const [filter, setFilter] = useState("");
const [initial] = useState(() => viewStates.get(input.key));
const [offset, setOffset] = useState(initial?.offset ?? 0);
const [limit, setLimit] = useState(initial?.limit ?? 500);
const [sort, setSort] = useState<DbSortKey[]>(initial?.sort ?? []);
const [filterText, setFilterText] = useState(initial?.filterText ?? "");
const [filter, setFilter] = useState(initial?.filter ?? "");
useEffect(
() => rememberViewState(input.key, { offset, limit, sort, filterText, filter }),
[input.key, offset, limit, sort, filterText, filter],
);
const [nonce, setNonce] = useState(0);
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
const [panel, setPanel] = useState<DataPanel | null>(null);
+2
View File
@@ -111,6 +111,8 @@ export function activate(): () => void {
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
title: tableTitle,
icon: () => "database",
// Switching tabs keeps the rows, filters, page and unsubmitted edits without querying again.
keepAlive: true,
}),
registerOverlay({
id: "database.dialogs",
+24 -1
View File
@@ -4,7 +4,7 @@ import type { DbDriver, DbTablePage } from "@/platform/ipc";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { activeCellGrid, installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { TableEditor } from "./TableEditor";
import { TableEditor, _resetTableViewStates } from "./TableEditor";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { tableInput } from "./tableInput";
@@ -59,6 +59,7 @@ const page: DbTablePage = {
};
beforeEach(() => {
_resetTableViewStates();
backend.driver = "clickhouse";
backend.page.mockResolvedValue({ status: "ok", data: page });
backend.applyEdits.mockClear();
@@ -211,3 +212,25 @@ it("omits a reset inserted cell from Submit instead of writing SQL NULL", async
disposeActions();
}
});
describe("table editor view state", () => {
it("queries with the sort it had when its tab mounts again", async () => {
const input = tableInput("source", "default", "users");
let view!: ReturnType<typeof render>;
await act(async () => {
view = render(<TableEditor input={input} />);
});
await screen.findByRole("gridcell", { name: "Ann" });
await act(async () => {
fireEvent.click(screen.getByRole("columnheader", { name: /name/ }));
});
const sorted = backend.page.mock.calls.at(-1)!;
expect(sorted[5]).toEqual([{ column: "name", descending: false }]);
view.unmount();
backend.page.mockClear();
await act(async () => {
render(<TableEditor input={input} />);
});
expect(backend.page.mock.calls[0]![5]).toEqual(sorted[5]);
});
});
+8 -2
View File
@@ -180,8 +180,14 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
MATCHED_BRACE_ATTRIBUTES: [["BACKGROUND", "--bg-matched-brace"]],
SEARCH_RESULT_ATTRIBUTES: [["BACKGROUND", "--bg-search-result"]],
TEXT_SEARCH_RESULT_ATTRIBUTES: [["BACKGROUND", "--bg-text-search-result"]],
IDENTIFIER_UNDER_CARET_ATTRIBUTES: [["BACKGROUND", "--bg-identifier-under-caret"]],
WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES: [["BACKGROUND", "--bg-identifier-under-caret-write"]],
IDENTIFIER_UNDER_CARET_ATTRIBUTES: [
["FOREGROUND", "--fg-identifier-under-caret"],
["BACKGROUND", "--bg-identifier-under-caret"],
],
WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES: [
["FOREGROUND", "--fg-identifier-under-caret-write"],
["BACKGROUND", "--bg-identifier-under-caret-write"],
],
FOLDED_TEXT_ATTRIBUTES: [
["FOREGROUND", "--fg-fold-placeholder"],
["BACKGROUND", "--bg-fold-placeholder"],
+10
View File
@@ -116,6 +116,16 @@ it("reruns and stops the selected configuration among several running sessions",
expect(useRun.getState().sessions.map((s) => !!s.stopped)).toEqual([true, false]);
});
it("offers Run for another instance of a running configuration that allows multiple instances", () => {
const parallel = { ...app, allowParallel: true };
useRun.setState({ configs: [parallel, npm], sessions: [run(parallel)] });
render(<RunWidget />);
expect(screen.getByRole("button", { name: `Run '${app.name}'` })).toBeTruthy();
expect(screen.getByRole("button", { name: `Debug '${app.name}'` })).toBeTruthy();
expect(screen.queryByRole("button", { name: /Rerun/ })).toBeNull();
expect(screen.getByRole("button", { name: `Stop '${app.name}'` })).toBeTruthy();
});
it("offers Run/Debug for an idle selection and Stop for the other process", () => {
useRun.setState({ sessions: [run(npm)] });
render(<RunWidget />);
+1 -1
View File
@@ -110,7 +110,7 @@ export function RunWidget() {
/>
)}
</>
) : active ? (
) : active && !selected?.allowParallel ? (
<>
{target?.paused && (
<IconButton
+11
View File
@@ -397,6 +397,17 @@ describe("context configuration", () => {
expect(contextConfig("tools/gen.py", uv)).toMatchObject({ command: "uv", args: ["run", "python", "tools/gen.py"] });
});
it("prefers a detected Python config's interpreter over one made by hand", () => {
const configs = [
cfg({ id: "mine", kind: "python", command: "python3", args: ["tool.py"], detected: false }),
cfg({ id: "found", kind: "python", command: "uv", args: ["run", "python", "-m", "app"], detected: true }),
];
expect(contextConfig("tools/gen.py", configs)).toMatchObject({
command: "uv",
args: ["run", "python", "tools/gen.py"],
});
});
it("takes the interpreter from a Django runserver config without its arguments", () => {
const runserver = (command: string, args: string[]) =>
cfg({ id: "django:runserver", kind: "python", command, args: [...args, "manage.py", "runserver"] });
+3 -6
View File
@@ -5,6 +5,7 @@
*/
import type { RunConfig } from "@/platform/ipc";
import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes";
import { systemPython } from "./pythonTypes";
import { phpunitArgs } from "./testing/phpunit";
import { goTestParts } from "./goArguments";
import { goBuildType } from "./goTypes";
@@ -122,7 +123,8 @@ export function projectPython(configs: RunConfig[], relPath?: string): { command
configs.filter((c) => ["python", "pytest", "django-test"].includes(c.kind)),
relPath,
);
const py = configs.find((c) => c.kind === "python");
// A detected configuration says what the project uses; one made by hand only what it runs itself.
const py = configs.find((c) => c.kind === "python" && c.detected) ?? configs.find((c) => c.kind === "python");
if (py) {
// The interpreter part ends where the program starts: `-m`, or the script (`manage.py`). What follows
// (`runserver`, `test`…) belongs to that program, never to the interpreter.
@@ -144,11 +146,6 @@ export function projectPython(configs: RunConfig[], relPath?: string): { command
return null;
}
/** `python` on Windows (where `python3` is not a command), `python3` elsewhere. */
function systemPython(): string {
return isWindows() ? "python" : "python3";
}
/**
* PyCharm runs pytest for a `test_*.py` file even when the project declares no
* test setup: `python -m pytest`, with the project's interpreter when detected.
+5 -1
View File
@@ -157,7 +157,11 @@ async function runSelected() {
useRun.setState({ chooserOpen: true, chooserMode: "run" });
return;
}
const target = selectedTarget(config.id, useRun.getState().sessions, useDebugRunSessions.getState().sessions);
// As in IDEA, Run starts another instance of a configuration that allows multiple instances;
// otherwise it restarts the running one.
const target = config.allowParallel
? null
: selectedTarget(config.id, useRun.getState().sessions, useDebugRunSessions.getState().sessions);
if (target) {
target.rerun?.();
return;
+93
View File
@@ -0,0 +1,93 @@
/**
* Python (PyCharm's "Python" configuration): a script or a `-m` module with its
* arguments. The command is the interpreter (`python3`, `.venv/bin/python`, `uv`),
* the runner args its leading arguments (`run python` for uv / poetry, `-u`). A plain
* `python` / `python3` runs on the project interpreter: the backend swaps it at launch.
*/
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { formatArgs, parseArgs } from "./configs";
import { isWindows } from "./jvmTypes";
/** `python` on Windows (where `python3` is not a command), `python3` elsewhere. */
export const systemPython = () => (isWindows() ? "python" : "python3");
export const pythonType: RunConfigTypeContribution = {
id: "python",
label: "Python",
icon: "file-python",
description: "Run a Python script or module",
// A getter: the host's OS is known only once the project is open.
get defaults() {
return { mode: "script", command: systemPython() };
},
debugAdapter: "debugpy",
fields: [
{
key: "mode",
label: "Execute",
control: "select",
options: [
{ value: "script", label: "Script file" },
{ value: "module", label: "Module" },
],
},
{
key: "script",
label: "Script path",
mono: true,
required: true,
browse: "file",
placeholder: "main.py",
visible: (p) => p.mode !== "module",
},
{
key: "module",
label: "Module",
mono: true,
required: true,
placeholder: "uvicorn",
visible: (p) => p.mode === "module",
},
{ key: "args", label: "Arguments", mono: true, placeholder: "Space separated; quote with ' or \"" },
{
key: "command",
label: "Command",
mono: true,
placeholder: "python3",
required: true,
hint: "e.g. python3, .venv/bin/python, uv, poetry",
},
{
key: "runnerArgs",
label: "Runner arguments",
mono: true,
placeholder: "run python",
hint: "e.g. `run python` for uv/poetry; empty calls the interpreter itself",
},
],
commandLine(p) {
const module = p.mode === "module";
const target = (module ? p.module : p.script)?.trim();
const program = !target ? [] : module ? ["-m", target] : [target];
return {
command: p.command?.trim() || systemPython(),
args: [...parseArgs(p.runnerArgs ?? ""), ...program, ...parseArgs(p.args ?? "")],
};
},
paramsFrom(c) {
if (c.kind !== "python") return null;
// The program starts at `-m` or the script; what precedes it belongs to the interpreter.
const at = c.args.findIndex((a) => a === "-m" || /\.pyw?$/.test(a));
if (at < 0) return null;
const module = c.args[at] === "-m";
const target = c.args[module ? at + 1 : at];
if (!target) return null;
return {
mode: module ? "module" : "script",
[module ? "module" : "script"]: target,
args: formatArgs(c.args.slice(at + (module ? 2 : 1))),
command: c.command,
runnerArgs: formatArgs(c.args.slice(0, at)),
};
},
};
+41
View File
@@ -355,6 +355,47 @@ describe("configuration types", () => {
expect(rake(["-T"])).toMatchObject({ options: "-T", task: "" });
});
it("Python runs a script or module and round-trips detected command lines", () => {
const python = typeFor("python")!;
expect(newConfigOfType(python, [])).toMatchObject({
kind: "python",
command: "python3",
args: [],
isTest: false,
debugAdapter: "debugpy",
});
expect(missingParams(newConfigOfType(python, []), python)).toHaveProperty("script");
expect(
python.commandLine({ mode: "module", module: " uvicorn ", script: "ignored.py", args: "app:app --reload" }),
).toEqual({ command: "python3", args: ["-m", "uvicorn", "app:app", "--reload"] });
const lines: Array<{ command: string; args: string[]; params: Record<string, string> }> = [
{
command: ".venv/bin/python",
args: ["-u", "src/my app.py", "--port", "8000"],
params: { mode: "script", script: "src/my app.py", runnerArgs: "-u", args: "--port 8000" },
},
{
command: "uv",
args: ["run", "python", "manage.py", "runserver"],
params: { mode: "script", script: "manage.py", runnerArgs: "run python", args: "runserver" },
},
{
command: "python3",
args: ["-X", "utf8", "-m", "pkg.cli", "serve"],
params: { mode: "module", module: "pkg.cli", runnerArgs: "-X utf8", args: "serve" },
},
];
for (const { command, args, params } of lines) {
const config = { ...newConfigOfType(python, []), command, args, params: undefined };
expect(formParams(config, python)).toMatchObject({ command, ...params });
}
// No script or module to show in the form: it stays a plain command.
expect(
formParams({ ...newConfigOfType(python, []), args: ["-c", "print(1)"], params: undefined }, python),
).toBeNull();
});
it("Django tests round-trip commandLine / paramsFrom and always report to the test tree", () => {
const django = typeFor("django-test")!;
expect(django.debugAdapter).toBe("debugpy");
+2
View File
@@ -27,6 +27,7 @@ import { goBuildType, goTestType } from "./goTypes";
import { dotnetProjectType, dotnetTestType } from "./dotnetTypes";
import { rakeType, rspecType, rubyScriptType } from "./rubyTypes";
import { djangoTestType } from "./djangoTypes";
import { pythonType } from "./pythonTypes";
import { phpunitType } from "./phpunitTypes";
import { UNITY_CONFIG_KIND } from "./unity";
@@ -491,6 +492,7 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
gradle,
maven,
godot,
pythonType,
pytest,
rubyScriptType,
rakeType,
@@ -122,10 +122,10 @@ describe("theme tokens", () => {
* Tokens the palette themes (Solarized, One) take from their light / dark base
* on purpose: colours the user assigns (project and data source colours), the
* platform's caption close and macOS window buttons, the tint strength, and
* the selection foreground, whose base default preserves syntax colours.
* the selection and caret identifier foregrounds, whose base default preserves syntax colours.
*/
const INHERITED_FROM_BASE =
/^--(project-color-|db-color-|file-color-|caption-close-|fg-caption-close-|tint-strength$|file-tint-strength$|fg-editor-selection$)/;
/^--(project-color-|db-color-|file-color-|caption-close-|fg-caption-close-|tint-strength$|file-tint-strength$|fg-editor-selection$|fg-identifier-under-caret(-write)?$)/;
describe("palette themes", () => {
const ISLANDS = ["light", "dark", "dark-hc"];
@@ -1,12 +1,18 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { LanguageInfo_Serialize as LanguageInfo, Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { effectivePatterns, removePattern, userFileType, validateFileTypes, wildcardMatch } from "@/platform/fileTypes";
import {
effectivePatterns,
overrideKey,
removePattern,
userFileType,
validateFileTypes,
wildcardMatch,
} from "@/platform/fileTypes";
import { DEFAULT_SETTINGS, validateSettings } from "../model/schema";
import { openSettings, stage, stagedValue, useSettingsDialog } from "../model/staging";
import { applyPatternEdit } from "../pages/FileTypes";
import { CODE_STYLE_KEYS, copyScheme } from "../pages/editor/codeStyleScheme";
import { overrideKey } from "../fileTypesRuntime";
const lang = (id: string, extensions: string[], filenames: string[] = []): LanguageInfo => ({
id,
@@ -60,6 +60,7 @@ describe("languages settings", () => {
threads: "2C",
activeProfiles: "",
delegateBuild: false,
downloadSources: false,
});
expect(validateSettings({}).languages).toEqual(DEFAULT_LANGUAGES);
expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe("");
@@ -71,6 +72,7 @@ describe("languages settings", () => {
expect(validateLanguages({ java: { maven: { runnerJre: 21 } } }).java.maven.runnerJre).toBe("");
expect(validateLanguages({ java: { maven: { delegateBuild: true } } }).java.maven.delegateBuild).toBe(true);
expect(validateLanguages({ java: { maven: { delegateBuild: "yes" } } }).java.maven.delegateBuild).toBe(false);
expect(validateLanguages({ java: { maven: { downloadSources: true } } }).java.maven.downloadSources).toBe(true);
const settings = validateSettings({ languages: { java: { maven: { runnerJre: " ./jdks/21 " } } } });
expect(validateSettings(settings).languages.java.maven.runnerJre).toBe("./jdks/21");
});
@@ -0,0 +1,66 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings, stagedValue, useSettingsDialog } from "../model/staging";
import { codeStyleLanguagePages } from "../pages/editor/codeStyle";
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
languages: async () => [
{ id: "php", name: "PHP", indent: { tabSize: 4, insertSpaces: true }, lineComment: "//" },
{ id: "javascript", name: "JavaScript", lineComment: "//" },
],
},
};
});
beforeEach(() => {
useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null });
openSettings("editor.codeStyle.php");
});
afterEach(cleanup);
async function page(language: string) {
const pages = await codeStyleLanguagePages();
const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!;
const Page = spec.component!;
render(
<PageContext.Provider value={{ pageId: spec.id, scope: "global" }}>
<Page />
</PageContext.Provider>,
);
return spec;
}
const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages");
const box = (name: string) => screen.getByRole("checkbox", { name }) as HTMLInputElement;
describe("PHP alignment", () => {
it("is off by default and stages each option on the PHP code style", async () => {
const spec = await page("php");
expect(spec.keywords).toEqual(expect.arrayContaining(["Align key-value pairs", "Align consecutive assignments"]));
expect(box("Align key-value pairs").checked).toBe(false);
expect(box("Align consecutive assignments").checked).toBe(false);
fireEvent.click(box("Align key-value pairs"));
expect(value()).toEqual({ php: { alignKeyValuePairs: true } });
fireEvent.click(box("Align consecutive assignments"));
expect(value()).toEqual({ php: { alignKeyValuePairs: true, alignConsecutiveAssignments: true } });
expect(box("Align key-value pairs").checked).toBe(true);
fireEvent.click(box("Align key-value pairs"));
expect(value()).toEqual({ php: { alignKeyValuePairs: false, alignConsecutiveAssignments: true } });
fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" }));
expect(value()).toEqual({});
});
it("is offered for PHP only", async () => {
const spec = await page("javascript");
expect(screen.queryByRole("checkbox", { name: "Align key-value pairs" })).toBeNull();
expect(spec.keywords).not.toContain("Align key-value pairs");
});
});
@@ -0,0 +1,29 @@
import { act, renderHook } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
sdkDetect: () =>
Promise.resolve({ status: "error", error: { kind: "unavailable", message: "detection failed", data: null } }),
},
};
});
import { detectSdks } from "../languages/api";
import { useDetected } from "../languages/components";
describe("useDetected", () => {
it("stops loading when detection fails", async () => {
const { result } = renderHook(() => useDetected("jdk"));
expect(result.current.loading).toBe(true);
await act(() => detectSdks("jdk"));
expect(result.current.loading).toBe(false);
expect(result.current.list).toEqual([]);
expect(result.current.error).toContain("detection failed");
});
});
+1 -5
View File
@@ -6,6 +6,7 @@
import { executeAction, registerActions } from "@/platform/actions";
import { call, commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import {
overrideKey,
sampleFileName,
userFileType,
validateFileTypeOverrides,
@@ -31,11 +32,6 @@ function loadLanguages(): Promise<LanguageInfo[]> {
}));
}
/** Settings key of a file: project-relative inside the project, else absolute. */
export function overrideKey(path: string, root: string | null): string {
return root && path.startsWith(root + "/") ? path.slice(root.length + 1) : path;
}
function currentOverrides(): Record<string, string> {
return validateFileTypeOverrides(
(useProject.getState().settings?.files as { fileTypeOverrides?: unknown } | undefined)?.fileTypeOverrides,
@@ -554,6 +554,7 @@ export function GradlePage() {
export function MavenPage() {
const [delegateBuild, setDelegateBuild] = useSetting<boolean>("languages.java.maven.delegateBuild");
const [daemon, setDaemon] = useSetting<boolean>("languages.java.maven.daemon");
const [downloadSources, setDownloadSources] = useSetting<boolean>("languages.java.maven.downloadSources");
const [threads, setThreads] = useSetting<string>("languages.java.maven.threads");
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
const id = useId();
@@ -566,6 +567,12 @@ export function MavenPage() {
onChange={setDelegateBuild}
hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server."
/>
<Toggle
label="Automatically download sources"
checked={downloadSources}
onChange={setDownloadSources}
hint="The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only."
/>
<SdkRow
k="languages.java.maven.runnerJre"
label="JRE"
@@ -35,7 +35,8 @@ export function useDetected(kind: SdkKind): { list: Sdk[]; loading: boolean; err
useEffect(() => {
void detectSdks(kind);
}, [kind]);
return { list: list ?? [], loading: loading || !list, error, refresh: () => void detectSdks(kind, true) };
// A failed detection is over too: it shows no choices instead of loading forever.
return { list: list ?? [], loading: loading || (!list && !error), error, refresh: () => void detectSdks(kind, true) };
}
export interface SdkFieldProps {
@@ -204,6 +204,32 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
/>
</Row>
</section>
{lang.id === "php" && (
<section aria-label={tx("Alignment")}>
<div className={styles.previewTitle}>
<T>Alignment</T>
</div>
<div className={styles.check}>
<Checkbox
checked={own.alignKeyValuePairs ?? false}
onChange={(v) => set({ alignKeyValuePairs: v })}
label="Align key-value pairs"
/>
</div>
<div className={styles.check}>
<Checkbox
checked={own.alignConsecutiveAssignments ?? false}
onChange={(v) => set({ alignConsecutiveAssignments: v })}
label="Align consecutive assignments"
/>
</div>
<div className={styles.note}>
{tx(
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.",
)}
</div>
</section>
)}
{lang.lineComment && (
<section aria-label={tx("Comment Code")}>
<div className={styles.previewTitle}>
@@ -321,6 +347,7 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
...(lang.id === "java"
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
: []),
...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []),
],
component: () => <LanguageStyle lang={lang} />,
}));
+2 -1
View File
@@ -42,7 +42,7 @@ import { overviewLane } from "@/editor/core/cm/lanes";
import { LINE_INSET } from "@/editor/core/cm/lineInset";
import { caretExtension } from "@/editor/core/cm/prefs";
import { fontExtension, tooltipBounds } from "@/editor/core/cm/setup";
import { caretStyles, findLocals, findStyles, overviewStyles } from "@/editor/core/cm/theme";
import { caretStyles, findLocals, findStyles, markWidgetStyles, overviewStyles } from "@/editor/core/cm/theme";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { getDiffInsights, hasInnerFragments } from "./diffOptions";
@@ -413,6 +413,7 @@ export const viewerTheme = EditorView.theme(
".cm-panels": { backgroundColor: "var(--bg-elev)", color: "var(--fg)" },
".cm-searchMatch": { backgroundColor: "color-mix(in srgb, var(--accent) 22%, transparent)" },
...findStyles,
...markWidgetStyles,
},
{ dark: true },
);
+11 -2
View File
@@ -1,8 +1,9 @@
/** Which files open in which viewer, and the editor inputs of the viewers. */
import type { EditorInput } from "@/workbench/contributions";
import { wildcardMatch } from "@/platform/fileTypes";
import { hasFileType, wildcardMatch } from "@/platform/fileTypes";
import type { FileProbe } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
export const IMAGE_KIND = "image";
export const BINARY_KIND = "binary";
@@ -18,7 +19,15 @@ function extension(path: string): string {
export const isImagePath = (path: string) => IMAGE_EXTENSIONS.has(extension(path));
export const isSvgPath = (path: string) => extension(path) === "svg";
export const isMarkdownPath = (path: string) => MARKDOWN_EXTENSIONS.has(extension(path));
/**
* Whether `path` gets the Markdown preview, decided synchronously so a tab never opens
* without it first: Markdown by Settings › File Types.
*/
export function isMarkdownPath(path: string): boolean {
const { settings, project } = useProject.getState();
return hasFileType(path, ["markdown"], MARKDOWN_EXTENSIONS, settings?.files, project?.root ?? null);
}
/** Whether the file's name matches one of `patterns` (`*.xlsx`); Windows/macOS match case-insensitively. */
export function associatedApplication(
+3
View File
@@ -8,6 +8,7 @@ import { registerActions, type Action } from "@/platform/actions";
import { call, commands, type FileProbe } from "@/platform/ipc";
import { getContext } from "@/platform/context";
import { openWithSystemApp } from "@/platform/fileManager";
import { onFileTypesChange } from "@/platform/fileTypes";
import { basename, useProject } from "@/platform/project";
import { fileIconName, lazyComponent } from "@/ui";
import {
@@ -85,6 +86,8 @@ function markdownActions(): Action[] {
export function activate(): () => void {
const probes = new Map<string, Promise<FileProbe>>();
const disposers = [
// Open tabs gain or lose the Markdown preview when File Types change.
onFileTypesChange(() => useTextEditorWrappers.setState((w) => ({ wrappers: new Map(w.wrappers) }))),
// Files associated with another application (Settings › Editor › File Types)
// win over the viewers below; a failed launch falls through to them.
registerExternalFileOpenHandler({
@@ -45,9 +45,9 @@ import { modeOf, useMarkdownModes } from "./modes";
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
import {
ANCHOR_PREFIX,
createMarkdownRenderer,
previewLineAtOffset,
previewOffsetForLine,
renderMarkdown,
resolveLink,
slugify,
} from "./render";
@@ -160,7 +160,8 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const editorSelection = useLiveMarkdown((s) => s[path]?.editorSelection ?? "");
const highlightSelection = useEditorPrefs().codeEditing.highlightSelection;
const deferred = useDeferredValue(text ?? "");
const html = useMemo(() => renderMarkdown(deferred), [deferred]);
const [render] = useState(createMarkdownRenderer);
const html = useMemo(() => render(deferred), [render, deferred]);
const ref = useRef<HTMLDivElement>(null);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
+2 -2
View File
@@ -13,7 +13,6 @@ import { MAX_COUNT, findExcluded, findOpen, findScope } from "@/editor/core/cm/f
import { fontZoom, resetConfiguredEditorsFontZoom, stepConfiguredEditorsFontZoom } from "@/editor/core/cm/prefs";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { isMarkdownPath } from "../fileKinds";
export interface LiveMarkdownFind {
search: string;
@@ -264,6 +263,7 @@ function livePlugin(path: string) {
export function registerMarkdownLiveSource(): () => void {
return registerEditorContribution({
id: "viewers.markdownLive",
extensions: (ctx) => (!ctx.virtual && isMarkdownPath(ctx.path) ? [livePlugin(ctx.path)] : []),
// The document's language: contributions are rebuilt when File Types change it.
extensions: (ctx) => (!ctx.virtual && ctx.language === "markdown" ? [livePlugin(ctx.path)] : []),
});
}
@@ -0,0 +1,58 @@
// pnpm vitest bench --run --reporter=verbose src/features/viewers/markdown/render.bench.ts
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { test } from "vitest";
import { createMarkdownRenderer, renderMarkdown } from "./render";
// A large real document: plugins/README.md twice, about 6,200 lines. As written, a bare
// `<title>` in one of its tables swallows everything after it (an unclosed tag the preview keeps
// as the whole-document pass reads it); in backticks the whole document is shown.
const readme = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8");
const asWritten = `${readme}\n\n${readme}`;
const doc = asWritten.replaceAll('"<title> failed', '"`<title>` failed');
/** `text` after one more keystroke in a paragraph in the middle. */
const typing = (text: string) => {
const at = text.indexOf("\n\n", text.length >> 1);
let typed = 0;
return () => `${text.slice(0, at)} x${typed++ % 1000}${text.slice(at)}`;
};
test("Markdown preview: a keystroke in a 6,200-line document", async ({ bench }) => {
const edited = typing(doc);
const render = createMarkdownRenderer();
render(doc);
await bench.compare(
bench("whole document", () => {
renderMarkdown(edited());
}),
bench("changed blocks", () => {
render(edited());
}),
);
});
test("Markdown preview: opening a 6,200-line document", async ({ bench }) => {
await bench.compare(
bench("whole document", () => {
renderMarkdown(doc);
}),
bench("changed blocks", () => {
createMarkdownRenderer()(doc);
}),
);
});
test("Markdown preview: a keystroke in a document with an unclosed tag", async ({ bench }) => {
const edited = typing(asWritten);
const render = createMarkdownRenderer();
render(asWritten);
await bench.compare(
bench("whole document", () => {
renderMarkdown(edited());
}),
bench("changed blocks", () => {
render(edited());
}),
);
});
+138 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
createMarkdownRenderer,
frontMatter,
joinPath,
previewLineAtOffset,
@@ -278,3 +281,137 @@ describe("markdown preview rendering", () => {
expect(previewLineAtOffset([], 50)).toBe(0);
});
});
describe("markdown preview re-rendering", () => {
afterEach(() => vi.restoreAllMocks());
const blocks = [
"---\ntitle: Notes\n---",
"# Title",
"# Title",
"Some *text* with [a ref][r] and a footnote-ish [b].",
"[r]: https://example.com/r\n[b]: ./b.md",
"<details>\n<summary>More</summary>",
"- inside\n- the container",
"</details>",
'<p align="center"><img src="logo.png" alt="logo"></p>',
"```mermaid\ngraph TD; A-->B\n```",
"```ts\nconst a = <div>x</div>;\n```",
"| a | b |\n|---|---|\n| 1 | <b>2</b> |",
'<span is="x-span">custom</span> and <body class="x"> and </body> text',
"> quote\n> more",
"Last paragraph.",
];
const doc = (parts: readonly string[]) => parts.join("\n\n") + "\n";
/** Renders `text` with `render` and checks it against the whole-document render. */
const same = (render: (text: string) => string, text: string) => expect(render(text)).toBe(renderMarkdown(text));
it("renders what the whole document renders, before and after each block is edited", () => {
const render = createMarkdownRenderer();
same(render, doc(blocks));
same(render, doc(blocks));
for (const i of blocks.keys()) {
same(render, doc(blocks.map((b, j) => (j === i ? `${b} edited` : b))));
same(render, doc(blocks.filter((_, j) => j !== i)));
}
same(render, "");
same(render, doc(blocks));
});
it("renders a large document as a whole, sanitizing only what an edit changed", () => {
const asWritten = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8");
// As written, a bare `<title>` swallows the rest of the file, so it is rendered as a whole.
for (const [readme, reuses] of [
[asWritten.replace('"<title> failed', '"`<title>` failed'), true],
[asWritten, false],
] as const) {
const render = createMarkdownRenderer();
same(render, readme);
for (const at of [0.1, 0.5, 0.9]) {
const from = Math.floor(readme.length * at);
const i = from + readme.slice(from).search(/\n\n[A-Z][a-z]/) + 2;
const edited = `${readme.slice(0, i)}Typed ${readme.slice(i)}`;
const parse = vi.spyOn(DOMParser.prototype, "parseFromString");
const html = render(edited);
const sanitized = parse.mock.calls.map(([dirty]) => String(dirty));
parse.mockRestore();
expect(html).toBe(renderMarkdown(edited));
expect(sanitized).toHaveLength(1);
expect(sanitized[0]!.includes("data-marker")).toBe(reuses);
if (reuses) expect(sanitized[0]!.length).toBeLessThan(2000);
}
}
});
it("sanitizes only the blocks an edit changed", () => {
const render = createMarkdownRenderer();
render(doc(blocks));
const parse = vi.spyOn(DOMParser.prototype, "parseFromString");
same(render, doc(blocks.map((b) => (b === "Last paragraph." ? "Last paragraph, edited." : b))));
const sanitized = parse.mock.calls.map(([html]) => String(html));
expect(sanitized.filter((html) => html.includes("Last paragraph, edited."))).toHaveLength(2);
expect(sanitized.filter((html) => html.includes("quote"))).toHaveLength(1);
});
// In one pass, an unclosed tag carries into the blocks after it.
it.each([
["formatting", "Bold <b>starts here"],
["link", '<a href="https://example.com">open link'],
["raw text", "<textarea>"],
["select", "<select><option>a"],
["template", "<template>"],
["comment", "<!-- never closed"],
["object", "<object>"],
["frameset", "<frameset>"],
["plaintext", "<plaintext>"],
["early close", "</div><p>x</p><div>"],
["svg", "<svg><foreignObject>"],
["close of the wrapper", "Text with a stray </div> close."],
])("renders a block that leaks into the next (%s) as the whole document does", (_, leak) => {
const render = createMarkdownRenderer();
const parts = [...blocks.slice(0, 8), leak, ...blocks.slice(8)];
same(render, doc(parts));
same(render, doc(parts));
same(render, doc([...parts, "One more."]));
same(render, doc(blocks));
});
it.each([
["formatting", "Bold <b>starts here", "ends here</b>."],
["link", '<a href="https://example.com">open link', "closed</a> here."],
["raw text", "<textarea>", "</textarea>"],
["object", "<object>", "</object>"],
["comment", "<!-- opens here", "closes here -->"],
])("renders a tag that closes in a later block (%s) as the whole document does", (_, opens, closes) => {
const render = createMarkdownRenderer();
const parts = [...blocks.slice(0, 8), opens, "Between.", closes, ...blocks.slice(8)];
same(render, doc(parts));
same(render, doc(parts.map((b) => (b === "Between." ? "Between, edited." : b))));
same(render, doc(parts.filter((b) => b !== opens)));
same(render, doc(parts.filter((b) => b !== closes)));
same(render, doc(parts));
});
it("renders forms and framesets, which change how the parser reads later blocks, as the whole document does", () => {
const render = createMarkdownRenderer();
same(render, doc(["Text", "<frameset>"]));
same(render, doc(["<frameset>"]));
same(render, doc(["<p>one<form>two", "<p>three<form>four"]));
same(render, doc(["<p>three<form>four"]));
same(render, doc(["Text", "<p>three<form>four"]));
});
it("renders the whole document in one pass while a block leaks", () => {
const render = createMarkdownRenderer();
const text = doc(["Bold <b>starts here", "Still bold."]);
render(text);
const parse = vi.spyOn(DOMParser.prototype, "parseFromString");
const html = render(text);
expect(parse.mock.calls.map(([dirty]) => String(dirty))).toEqual([
expect.stringMatching(/starts here[\s\S]*Still bold/),
]);
const root = document.createElement("div");
root.innerHTML = html;
expect(root.querySelector('[data-line="2"] b')?.textContent).toBe("Still bold.");
});
});
+97 -11
View File
@@ -143,13 +143,14 @@ function trackContainers(raw: string, open: string[]) {
}
}
export function renderMarkdown(text: string): string {
/** The preview's blocks: each top-level block, or run of blocks inside one HTML container, as unsanitized HTML. */
function blocks(text: string): { line: number; html: string }[] {
const front = frontMatter(text);
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
const tokens = marked.lexer(body);
const slugs = new Map<string, number>();
let line = front?.lines ?? 0;
let html = front ? `<div data-line="0">${frontMatterTable(front.fields)}</div>` : "";
const out = front ? [{ line: 0, html: frontMatterTable(front.fields) }] : [];
// Blocks inside an HTML container left open (`<details>`, `<div>`…) share its wrapper up to
// the close: a wrapper per block would end the container early and spill its content out.
const open: string[] = [];
@@ -170,18 +171,103 @@ export function renderMarkdown(text: string): string {
group.html += body;
if (token.type === "html") trackContainers(token.raw, open);
if (open.length) continue;
html += `<div data-line="${group.line}">${group.html}</div>`;
out.push(group);
group = null;
}
if (group) html += `<div data-line="${group.line}">${group.html}</div>`;
if (group) out.push(group);
return out;
}
const SANITIZE = {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
// The preview shares the IDE's document: a `<style>` in a file would restyle the whole IDE.
return purify().sanitize(html, {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
// `srcset` and `<source>` would pick an image past the one the preview loads.
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
});
// `srcset` and `<source>` would pick an image past the one the preview loads.
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
};
const wrap = (line: number, html: string) => `<div data-line="${line}">${html}</div>`;
const sanitizeWhole = (all: readonly { line: number; html: string }[]) =>
purify().sanitize(all.map((b) => wrap(b.line, b.html)).join(""), SANITIZE);
export function renderMarkdown(text: string): string {
return sanitizeWhole(blocks(text));
}
/**
* `renderMarkdown` for a preview that re-renders as the file is edited: blocks sanitized for an
* earlier render are reused, so an edit sanitizes only the blocks it changed. Same output.
*/
export function createMarkdownRenderer(): (text: string) => string {
// Sanitized wrapper contents by unsanitized block HTML; `null` for a block that leaks.
let cache = new Map<string, string | null>();
return (text) => {
const all = blocks(text);
const misses = [...new Set(all.map((b) => b.html).filter((html) => !cache.has(html)))];
for (const html of misses) if (PARSER_STATE.test(html)) cache.set(html, null);
if (misses.length && !all.some((b) => cache.get(b.html) === null)) sanitizeApart(misses, cache);
const kept = new Map<string, string | null>();
for (const b of all) {
const clean = cache.get(b.html);
if (clean !== undefined) kept.set(b.html, clean);
}
cache = kept;
const parts = all.map((b) => cache.get(b.html));
if (parts.some((part) => typeof part !== "string")) return sanitizeWhole(all);
return all.map((b, i) => wrap(b.line, parts[i]!)).join("");
};
}
const WRAPPER_OPEN = '<div data-line="0">';
// Tags that change how the parser reads the blocks after them without moving the markers.
const PARSER_STATE = /<(?:form|frameset)(?=[\s/>]|$)/i;
/**
* Sanitizes `blocks` in one pass, a marker after each, and records what each one sanitizes to
* in `cache`. That equals its part of the whole document only if the HTML parser reads it the
* same way on its own: an unclosed `<b>`, `<textarea>`, `<table>` or `<!--` carries into the
* blocks after it, which moves or swallows the marker. The first block that does is recorded
* as `null`; the blocks after it are not recorded.
*/
function sanitizeApart(blocks: readonly string[], cache: Map<string, string | null>) {
const nonce = Array.from(crypto.getRandomValues(new Uint32Array(4)), (n) => n.toString(36)).join("");
const marker = `<p data-marker="${nonce}">.</p>`;
const isMarker = (node: Node | undefined) =>
node instanceof Element &&
node.tagName === "P" &&
node.attributes.length === 1 &&
node.getAttribute("data-marker") === nonce &&
node.childNodes.length === 1 &&
node.firstChild!.nodeType === Node.TEXT_NODE &&
node.textContent === ".";
// Blocks the parser read on their own: each a top-level wrapper with its marker right after it.
let apart = 0;
const checkParse = (node: Node) => {
if (node.nodeName !== "BODY") return;
const nodes = node.childNodes;
while (apart < blocks.length && nodes[2 * apart]?.nodeName === "DIV" && isMarker(nodes[2 * apart + 1])) apart++;
if (apart === blocks.length && nodes.length !== 2 * blocks.length) apart--;
};
const p = purify();
p.addHook("beforeSanitizeElements", checkParse);
let html: string;
try {
html = p.sanitize(blocks.map((b) => wrap(0, b) + marker).join(""), SANITIZE);
} finally {
p.removeHook("beforeSanitizeElements", checkParse);
}
const parts = html.split(marker);
for (let i = 0; i < apart; i++) {
const part = parts[i]!;
if (!part.startsWith(WRAPPER_OPEN) || !part.endsWith("</div>")) {
cache.set(blocks[i]!, null);
return;
}
cache.set(blocks[i]!, part.slice(WRAPPER_OPEN.length, -"</div>".length));
}
if (apart < blocks.length) cache.set(blocks[apart]!, null);
}
export type LinkTarget =
+92 -2
View File
@@ -1,5 +1,13 @@
import { describe, expect, it } from "vitest";
import { registerTextEditorWrapper, resolveFileEditor } from "@/workbench/contributions";
import { afterEach, describe, expect, it } from "vitest";
import { editorContributions, type EditorDocContext } from "@/editor/api";
import type { ProjectInfo, Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import {
registerTextEditorWrapper,
resolveFileEditor,
textEditorWrapperFor,
useTextEditorWrappers,
} from "@/workbench/contributions";
import { activate as activateViewers } from "./index";
import {
associatedApplication,
@@ -85,6 +93,88 @@ describe("file kinds", () => {
});
});
describe("Markdown files follow File Types", () => {
const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] });
const setFiles = (files: object) =>
useProject.setState({ project: { root: "/p" } as ProjectInfo, settings: { files } as Settings });
const toMmd = { fileTypes: { markdown: types(["*.mmd"]) } };
afterEach(() => useProject.setState({ project: null, settings: null }));
it.each<[string, object, string, boolean]>([
["default .md", {}, "/p/a.md", true],
["default .markdown", {}, "/p/a.markdown", true],
["default .mdown", {}, "/p/a.mdown", true],
["default .mkd", {}, "/p/a.mkd", true],
["default .mkdn", {}, "/p/a.mkdn", true],
["default .mdwn", {}, "/p/a.mdwn", true],
["upper-case default", {}, "/p/A.MD", true],
["no association", {}, "/p/a.mmd", false],
["added extension", toMmd, "/p/diagram.mmd", true],
["added extension, other case", toMmd, "/p/DIAGRAM.MMD", true],
["added file name", { fileTypes: { markdown: types(["NOTES"]) } }, "/p/NOTES", true],
["added glob", { fileTypes: { markdown: types(["notes.*"]) } }, "/p/notes.txt", true],
["extension given to another language", { fileTypes: { plaintext: types(["*.mmd"]) } }, "/p/a.mmd", false],
[
"*.md moved to another language",
{ fileTypes: { markdown: types([], ["*.md"]), plaintext: types(["*.md"]) } },
"/p/a.md",
false,
],
["*.md removed", { fileTypes: { markdown: types([], ["*.md"]) } }, "/p/a.md", false],
["*.md removed keeps the others", { fileTypes: { markdown: types([], ["*.md"]) } }, "/p/a.markdown", true],
["override to Markdown", { fileTypeOverrides: { "docs/a.txt": "markdown" } }, "/p/docs/a.txt", true],
["override outside the project", { fileTypeOverrides: { "/x/a.txt": "markdown" } }, "/x/a.txt", true],
["override away from Markdown", { fileTypeOverrides: { "a.md": "plaintext" } }, "/p/a.md", false],
["override beats a pattern", { ...toMmd, fileTypeOverrides: { "a.mmd": "plaintext" } }, "/p/a.mmd", false],
])("%s", (_name, files, path, expected) => {
setFiles(files);
expect(isMarkdownPath(path)).toBe(expected);
});
it("updates open tabs only when File Types change", () => {
const off = activateViewers();
const wrappers = () => useTextEditorWrappers.getState().wrappers;
try {
setFiles({});
const before = wrappers();
expect(textEditorWrapperFor(before, "/p/a.mmd")).toBeUndefined();
setFiles({ autoSave: true });
expect(wrappers()).toBe(before);
setFiles(toMmd);
expect(wrappers()).not.toBe(before);
expect(textEditorWrapperFor(wrappers(), "/p/a.mmd")?.id).toBe("viewers.markdown");
setFiles({});
expect(textEditorWrapperFor(wrappers(), "/p/a.mmd")).toBeUndefined();
} finally {
off();
}
});
it("publishes the live text of Markdown documents only", () => {
const off = activateViewers();
try {
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const ctx = (language: string, virtual = false): EditorDocContext => ({
doc: 1,
path: "/p/a.mmd",
language,
uiMode: null,
readOnly: false,
virtual,
});
expect(live.extensions(ctx("markdown"))).toHaveLength(1);
expect(live.extensions(ctx("plaintext"))).toHaveLength(0);
expect(live.extensions(ctx("markdown", true))).toHaveLength(0);
} finally {
off();
}
});
});
describe("hex model", () => {
it("decodes base64 and formats bytes", () => {
expect([...decodeBase64("AAH/")]).toEqual([0, 1, 255]);
+71
View File
@@ -0,0 +1,71 @@
import { afterEach, describe, expect, it } from "vitest";
import type { ProjectInfo, Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { textEditorWrapperFor, useTextEditorWrappers } from "@/workbench/contributions";
import { isHtmlPath, isWebPath } from "./browsers";
import { activate } from "./index";
const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] });
const setFiles = (files: object) =>
useProject.setState({ project: { root: "/p" } as ProjectInfo, settings: { files } as Settings });
const toFoo = { fileTypes: { html: types(["*.foo"]) } };
const movedAway = { fileTypes: { html: types([], ["*.html"]), plaintext: types(["*.html"]) } };
afterEach(() => useProject.setState({ project: null, settings: null }));
describe("HTML files follow File Types", () => {
it.each<[string, object, string, boolean]>([
["default .html", {}, "/p/a.html", true],
["default .htm", {}, "/p/a.htm", true],
["default .xhtml", {}, "/p/a.xhtml", true],
["default .shtml", {}, "/p/a.shtml", true],
["upper-case default", {}, "/p/A.HTML", true],
["no association", {}, "/p/a.foo", false],
["a name without a dot", {}, "/p/html", false],
["added extension", toFoo, "/p/a.foo", true],
["added extension, other case", toFoo, "/p/A.FOO", true],
["added file name", { fileTypes: { html: types(["PAGE"]) } }, "/p/PAGE", true],
["added glob", { fileTypes: { html: types(["page.*"]) } }, "/p/page.txt", true],
["extension given to another language", { fileTypes: { plaintext: types(["*.foo"]) } }, "/p/a.foo", false],
["*.html moved to another language", movedAway, "/p/a.html", false],
["*.html removed", { fileTypes: { html: types([], ["*.html"]) } }, "/p/a.html", false],
["*.html removed keeps the others", { fileTypes: { html: types([], ["*.html"]) } }, "/p/a.htm", true],
["override to HTML", { fileTypeOverrides: { "docs/a.txt": "html" } }, "/p/docs/a.txt", true],
["override outside the project", { fileTypeOverrides: { "/x/a.txt": "html" } }, "/x/a.txt", true],
["override to Django Template", { fileTypeOverrides: { "a.html": "django-html" } }, "/p/a.html", true],
["override away from HTML", { fileTypeOverrides: { "a.html": "plaintext" } }, "/p/a.html", false],
["override beats a pattern", { ...toFoo, fileTypeOverrides: { "a.foo": "plaintext" } }, "/p/a.foo", false],
])("%s", (_name, files, path, expected) => {
setFiles(files);
expect(isHtmlPath(path)).toBe(expected);
expect(isWebPath(path)).toBe(expected);
});
it("keeps SVG files openable in a browser", () => {
setFiles({});
expect(isHtmlPath("/p/a.svg")).toBe(false);
expect(isWebPath("/p/A.SVG")).toBe(true);
});
it("updates open tabs only when File Types change", () => {
const off = activate();
const wrappers = () => useTextEditorWrappers.getState().wrappers;
try {
setFiles({});
const before = wrappers();
expect(textEditorWrapperFor(before, "/p/a.foo")).toBeUndefined();
setFiles({ autoSave: true });
expect(wrappers()).toBe(before);
setFiles(toFoo);
expect(wrappers()).not.toBe(before);
expect(textEditorWrapperFor(wrappers(), "/p/a.foo")?.id).toBe("web.html");
setFiles(movedAway);
expect(textEditorWrapperFor(wrappers(), "/p/a.html")).toBeUndefined();
} finally {
off();
}
});
});
+13 -3
View File
@@ -1,14 +1,24 @@
/** Installed browsers, the built-in server's URLs, and per-file preview state. */
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { hasFileType } from "@/platform/fileTypes";
import { call, commands, isTauri, type Browser } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { hasIcon } from "@/ui";
import { notifications } from "@/workbench/contributions";
/** A Django template is an HTML file the banner in `djangoTemplates.ts` retyped: it keeps the preview. */
const HTML_LANGUAGES = ["html", "django-html"];
const HTML_EXTENSIONS = new Set(["html", "htm", "xhtml", "shtml"]);
/** Files that get the browser bar and the built-in preview: HTML by Settings › File Types. */
export function isHtmlPath(path: string): boolean {
const { settings, project } = useProject.getState();
return hasFileType(path, HTML_LANGUAGES, HTML_EXTENSIONS, settings?.files, project?.root ?? null);
}
/** Files a browser can show (Open In › Browser). */
export const isWebPath = (path: string) => /\.(html?|xhtml|shtml|svg)$/i.test(path);
/** Files that get the browser bar and the built-in preview. */
export const isHtmlPath = (path: string) => /\.(html?|xhtml|shtml)$/i.test(path);
export const isWebPath = (path: string) => isHtmlPath(path) || /\.svg$/i.test(path);
export const useBrowsers = create<{ list: Browser[] }>(() => ({ list: [] }));
+4
View File
@@ -7,6 +7,7 @@
*/
import { registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { onFileTypesChange } from "@/platform/fileTypes";
import { basename } from "@/platform/project";
import { lazyComponent, type MenuItem } from "@/ui";
import {
@@ -14,6 +15,7 @@ import {
registerEditorBanner,
registerMenuGroup,
registerTextEditorWrapper,
useTextEditorWrappers,
} from "@/workbench/contributions";
import { registerEditorContribution } from "@/editor/api";
import { djangoContentWatcher, djangoTemplateBanner } from "./djangoTemplates";
@@ -67,6 +69,8 @@ function browserMenu(path: string): MenuItem {
export function activate(): () => void {
void loadBrowsers();
const disposers = [
// Open tabs gain or lose the browser bar and preview when File Types change.
onFileTypesChange(() => useTextEditorWrappers.setState((w) => ({ wrappers: new Map(w.wrappers) }))),
registerEditorBanner(djangoTemplateBanner),
registerEditorContribution({ id: "web.djangoContent", order: 57, extensions: djangoContentWatcher }),
registerTextEditorWrapper({
+15
View File
@@ -3,6 +3,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import {
ATTRIBUTES,
CLEAR_COLOR,
SCHEMES,
_setSchemeSource,
overrideDeclarations,
resolvedAttribute,
@@ -221,6 +222,20 @@ describe("color schemes", () => {
);
});
it.each([
["identifierUnderCaret", "--fg-identifier-under-caret"],
["identifierUnderCaretWrite", "--fg-identifier-under-caret-write"],
])("lets %s set a foreground over the syntax colours (#4109)", (id, token) => {
expect(ATTRIBUTES.find((a) => a.id === id)?.fg).toBe(token);
// The `inherit` default is no colour: every built-in scheme keeps the syntax colours.
for (const scheme of SCHEMES) expect(resolvedAttribute(scheme.id, id).foreground).toBeUndefined();
expect(schemeCss("dark", { dark: { [id]: { foreground: "#112233" } } })).toContain(`${token}: #112233 !important`);
// Unticked, the syntax colours show again rather than one flat default text colour.
expect(schemeCss("dark", { dark: { [id]: { foreground: CLEAR_COLOR } } })).toContain(
`${token}: inherit !important`,
);
});
// #3851: the editor showed the red-green colours while Color Scheme showed the plain ones.
it("resolves the red-green variant of the bundled schemes only", () => {
const rg = (id: Parameters<typeof schemeTokens>[0], name: string) => schemeTokens(id, undefined, true).get(name);
+8 -1
View File
@@ -25,6 +25,8 @@ export interface AttributeDef {
path: string[];
/** CSS variable of the foreground / background / effect colour, if editable. */
fg?: string;
/** `fg` paints over the syntax colours: without one, they show through. */
fgOverlay?: true;
bg?: string;
effect?: string;
/** Syntax token: bold / italic / background / effect come from `--syn-<token>-*`. */
@@ -112,12 +114,16 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [
id: "identifierUnderCaret",
name: "Identifier under caret",
path: ["General", "Code"],
fg: "--fg-identifier-under-caret",
fgOverlay: true,
bg: "--bg-identifier-under-caret",
},
{
id: "identifierUnderCaretWrite",
name: "Identifier under caret (write)",
path: ["General", "Code"],
fg: "--fg-identifier-under-caret-write",
fgOverlay: true,
bg: "--bg-identifier-under-caret-write",
},
{ id: "inlay", name: "Inlay hints", path: ["General", "Code"], fg: "--fg-inlay", bg: "--bg-inlay" },
@@ -606,7 +612,8 @@ export function overrideDeclarations(
if (!o) continue;
if (setOrCleared(o.foreground) && attr.fg) {
// No foreground means the default text colour, not invisible text.
const fg = o.foreground === CLEAR_COLOR && attr.id !== "text" ? "var(--fg-editor)" : o.foreground!;
const cleared = attr.fgOverlay ? "inherit" : attr.id === "text" ? CLEAR_COLOR : "var(--fg-editor)";
const fg = o.foreground === CLEAR_COLOR ? cleared : o.foreground!;
out.push([attr.fg, fg]);
// Terminal prefers `--terminal-ansi-*`; keep it in sync with console `--ansi-*`.
if (attr.fg.startsWith("--ansi-")) out.push([`--terminal-ansi-${attr.fg.slice("--ansi-".length)}`, fg]);
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more