Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7eed99745a test(plugins): keep the editor panel's problem levels out of the text catalog
The severity map's `hint: "weakWarning"` entry read as UI text to the
text-catalog check (`hint` is a text property), failing it on main since #3885.
A function maps the levels instead.
2026-11-17 12:33:43 +08:00
LU XIANGRUIтаwildcatDownstairs ebc879dc8b feat(plugins): folded ranges and wrapped rows for editor panels (#3890)
An editor panel's page could not tell which lines are folded or how many rows a soft-wrapped line takes, so a minimap drew folded code and drifted from the editor. openidea.editor now has folded() ([{ fromLine, toLine }], nested folds merged), wrapped(fromLine, toLine) (visual rows per line, 0 for folded-away lines, null without soft wrap, at most 2000 lines) and onLayout(fn) with { folded, softWrap }, at most once a frame. Folds come from foldedRanges and rows from the editor's own line blocks.

Closes #3867

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:32:03 +08:00
LU XIANGRUIтаwildcatDownstairs 7096a1c374 feat(plugins): include semantic highlighting in editor panels' highlights() (#3887)
openidea.editor.highlights() returned only the Lezer syntax colours, so a minimap drew semantic tokens (cm-sem-* marks, rainbow identifiers) in the wrong colour. It now layers the editor's semantic marks over the syntax spans the way the editor does, and onHighlights reports the lines whose semantic marks changed (RangeSet.compare on the semantic field, so mapped marks report nothing extra). The page API is unchanged.

Closes #3866

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:42 +08:00
LU XIANGRUIтаwildcatDownstairs a1d4d6fb7f feat(plugins): the marker bar's problems in editor panels (#3885)
An editor panel's page can now read the problems the marker bar shows: openidea.editor.problems() returns [{ line, lastLine, severity }] (0-based lines; error, warning or weakWarning) and onProblems(fn) reports changes at most once a frame. The data is the marker bar's own diagnostics marks field, exported as markerBarProblems(state), so positions follow edits the same way. Covered by editor.read; the minimap fixture draws them.

Closes #3865

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:20 +08:00
Muuтаmuutot 7596e95b76 fix(spell): raw strings keep the letter after a backslash (#3886)
Typo checking treated every backslash in a string literal as an escape and skipped the letter after it, so r"\user" was checked as "ser" and flagged. The syntax layer now marks raw / verbatim strings (Python r/R prefixes with b/f/u combinations, Rust and C++ raw strings, C# verbatim strings, Go backtick strings), and the spelling layer checks them without escape handling.

Co-authored-by: muutot <[email protected]>
2026-11-17 12:30:01 +08:00
Gabriel Gondim cc471029d2 fix(xml): map Doctrine ORM XSD through a LemMinX catalog (#3881)
Doctrine ORM XML mappings that follow Doctrine's docs and point xsi:schemaLocation at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd failed validation (TargetNamespace.1, cvc-elt.1.a): the hosted XSD declares the schema URL as its targetNamespace after an http→https rewrite. The upstream schema (MIT) is bundled and an OASIS catalog, written to a private per-process directory, is prepended to LemMinX's xml.catalogs so the namespace and both system IDs resolve to it.

Closes #3843

Co-authored-by: GGVidal <[email protected]>
2026-11-17 12:28:31 +08:00
LU XIANGRUIтаwildcatDownstairs ee8afe39a2 fix(build): make the injected WAR and resource init scripts work with the configuration cache (#3877)
With org.gradle.configuration-cache=true, Tomcat WAR deployment and Spring Boot resource update failed: the doLast actions of war.init.gradle and resources.init.gradle referred to the Project and other tasks, which the configuration cache cannot serialize. The values they need (the war archive provider or file, processResources' destination, the manifest file) are now resolved at configuration time. The other injected scripts only configure tasks and have no task actions.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:36 +08:00
LU XIANGRUIтаwildcatDownstairs 5f606219b2 fix(run): make the injected Gradle init scripts work on Gradle 4.6–6.3 (#3875)
Run/Debug, tests, bootRun debug, VM options, coverage, resource update and WAR deployment failed on Gradle before 6.4 because the injected init scripts used newer API without a version check: JavaExec.mainClass (6.4+), tasks.register/named/configureEach (4.9+), debugOptions (5.6+), Report.required (6.1+), archiveFile (5.1+), and sourceSets as an extension (4.10+). Each use now falls back to the older API, with Gradle 4.6 as the oldest supported version; newer Gradle keeps the lazy API.

Closes #3864

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:07 +08:00
l0ng-ai 0590a255e8 chore: v0.1.47 2026-11-17 10:51:26 +08:00
l0ng-ai 32d5232010 fix(vcs): the navigation path of a file at a Git revision shows the revision and its folders
The status bar path of a file opened with Show File at Revision showed the hex-encoded location and lost the file's folders. It now shows the short revision, the folders of the file in the working tree and the file name (`617f744a › web › src › app.ts`).
2026-11-17 10:50:33 +08:00
l0ng-ai 382f5d71fa fix(debugger): stream trace from an else-if line, of a stream made parallel earlier, and its cleanup
- At a stop on an `} else if` line, the earlier conditions have already run: their calls no longer count as exits to skip before the chain's root. The trace used to wait for a second `stream()` that never came. Conditions on the same line still count.
- A stream that was parallel before the traced statement (`Stream<T> s = list.parallelStream(); … s.map(…)`) is checked with `isParallel()` when the trace arms and made sequential like a chain with `parallel()`, so its records link correctly; the result says it ran sequentially.
- `arm` carries a token. When its reply times out, the client releases the trace armed with that token, so a slow arm no longer leaves breakpoints off and the next trace busy.
- A finished trace's records keep their objects from being collected until the stop they were read in ends: they are released on the next resume, step or `continued` event instead of the next trace.

The bundle is rebuilt; `tests/stream.py` (JDT LS 1.63.0, JDK 25) passes, with new cases for the three bundle changes.
2026-11-17 10:05:41 +08:00
l0ng-ai 0cd7d9c30e fix(agents): the generated commit message describes exactly what would be committed
The diff sent to the agent was every included file's whole working-tree change. With the staging area, or blocks left out of a partial commit, it also held changes the commit leaves out. It is now made the way Commit makes the commit (the index with the selection applied, partial files' chosen blocks only), through the new `vcs_pending_patch` command.

Before filling in the message, the changes are read again: a file edited and saved while the agent worked, which changes neither the message nor the inclusion, no longer gets a message written for its earlier content.
2026-11-17 09:57:58 +08:00
l0ng-ai dfbe87161b fix(vcs): a file opened at a Git revision shows the revision, not its encoded location
Show File at Revision opens `git-revision:<hex of the target>/<name>`. The tab's directory hint and the status bar path showed the hex string, and the banner called the file a library source. The tab hint is now the short revision, the path shows the revision and the file's folders (`c74989a1 › web › src`), and the banner says it is a file at a Git revision.
2026-11-17 09:53:04 +08:00
l0ng-ai 7a351fe4b0 fix(plugins): name the Failed and Needs permission status dots (#3872)
The status dot of a failed plugin, or one waiting for consent, was announced as "[object Object]": the dot's label is its text, and it was given an element. It is given the translated text now.
2026-11-17 09:51:27 +08:00
l0ng-ai 153a184eac fix(python): an interpreter chosen but not applied yet is not reported missing (#3871)
The interpreter page compared the chosen interpreter with the one the backend resolves, which follows the applied setting. A virtualenv just created (or any other choice before Apply) showed "The configured Python interpreter no longer exists" until the page was opened again. Only the applied interpreter is judged now, and the check runs again once a choice is applied.
2026-11-17 09:51:21 +08:00
l0ng-ai 868f5b18d0 fix(editor): Back reopens a diff closed without leaving it first (#3870)
A diff was recorded as a place only when a file was opened from it. Opening a diff and closing it straight away left the history at the file before it, so Back opened that file instead of the diff. Closing the active diff now records it as the place left.
2026-11-17 09:51:16 +08:00
l0ng-ai 8d87b0de6e fix(java): allow a slow first java -version before excluding a JDK (#3868)
A JDK whose java -version took longer than 5 seconds was treated as unable to run and left out of the jdtls runtimes until the server restarted. The first run of an x86_64 JDK 8 under Rosetta, or of a freshly downloaded JDK being scanned, can take that long, so a Java 8 project compiled against a newer JDK and jdk.nashorn stopped resolving. The probe now waits up to 30 seconds; a java that never answers is still rejected.

Fixes #3684
2026-11-17 09:45:28 +08:00
l0ng-ai c791f2c34c fix(mcp): check scope before touching the file system, and apply it to every symbol result (#3853)
- `scope` is checked to be on a local drive or the project's share before it is resolved: on Windows, resolving `\\host\share` would sign in to that host before the tool refused it as outside the project.
- `search_symbol` with a `scope` filters in the index: the fixed candidate pool was cut before the filter, so matches in the scope ranked past it were dropped without a "more" marker.
- Language server results in attached projects or content roots obey `scope` and `paths` like project files instead of passing as library symbols.
2026-11-17 09:34:11 +08:00
l0ng-ai a52e416ad5 fix(run): a run closed or restarted while starting does not leave its process behind (#3862)
Closing a Java run tab while the plugin list for remote Java agents was loading still started the process, and nothing owned it afterwards. The start is now abandoned when the session was stopped, closed or started again meanwhile, and a process that started anyway is stopped.
2026-11-17 09:34:04 +08:00
l0ng-ai a7464bf631 fix(plugins): translate the Java Agents section title (#3861)
The section listing a plugin's Java agents had no catalog entry and stayed English in the Chinese UI.
2026-11-17 09:33:59 +08:00
l0ng-ai 26810fbcbd fix(welcome): a recent WSL project stored with forward slashes is not shown as missing (#3860)
Recent projects are stored as `//wsl.localhost/Ubuntu/...`; the exemption for WSL shares (a stopped distribution only hides them) recognised the backslash form only.
2026-11-17 09:33:54 +08:00
l0ng-ai 72b17683c9 fix(terminal): open terminals pick up a Nerd Font found in the font catalog (#3859)
Open terminals re-apply their font stack when the native font catalog loads, but the Nerd Fonts outside the known list were picked from it only afterwards, so the terminal kept showing boxes for prompt icons. The catalog now records them before notifying.
2026-11-17 09:33:49 +08:00
l0ng-ai e916af15d4 fix(analysis): Reformat / Code Cleanup on several files saves each file as cleaned (#3858)
The batch saved with Save All after each file. That ran save actions (format on save reformatted the whole file after "only VCS changed text") and saved unrelated unsaved files. Each file is now saved as it is, without save actions, and other files are left alone.
2026-11-17 09:33:43 +08:00
l0ng-ai 88eeb57000 fix(remote): stop reconnecting on its own once a file is edited while waiting (#3857)
Automatic reconnection checked for unsaved edits only when the connection was lost. Edits made during the back-off were dropped when the window reopened the project. Each attempt now checks again and leaves the reconnect to the user (who is asked first) once anything is unsaved.
2026-11-17 09:33:38 +08:00
l0ng-ai ba5c56ade8 fix(agents): switching a saved task to a model of a legacy ACP agent no longer fails (#3856)
An agent that lists models through the legacy `models` field and reports no settings after `session/set_model` made the discovery wait five seconds and fail, and the model choice was reverted. Such a model now has no per-model settings instead. Agents with `configOptions` still report a missing answer as before.
2026-11-17 09:33:33 +08:00
l0ng-ai 88a5602239 fix(agents): generate the commit message in a read-only mode when the agent has one (#3855)
The commit message task picked `default` / `ask` before `read-only`, and Codex runs `ask` with workspace write access. The diff it reads is repository text, so the task now prefers a read-only mode and only falls back to one that asks before writing.
2026-11-17 09:33:28 +08:00
l0ng-ai 907ed1d85f fix(completion): repeat an item at other carets only where it fits, and sync it to the document (#3854)
- A server-inserted item (kotlin-lsp) repeated at the other carets was folded into the server's own transaction, which is never sent back to the document model: the copies vanished after saving and reopening. They now go in as a separate local edit.
- That repetition only goes to carets after the same typed text; a zero-length server edit used to land at every other empty caret.
- Automatic parentheses are decided per caret: `b.cr|()` no longer becomes `b.create()()` when the main caret is at `a.cr|`.
2026-11-17 09:33:10 +08:00
l0ng-ai 7f229acbd9 fix(database): keep dump / restore connections on the chosen database (#3852)
A database named like connection parameters (`host=… dbname=…` or a `postgresql://` URI) went to `--dbname` as is, which pg_dump / pg_restore / psql read as a connection string: it could point the tool, and the data source's password, at another host. Such a name now goes in quoted as the string's `dbname`.

psql restores now run with `--no-psqlrc`, so a `\connect` or setting in `~/.psqlrc` cannot redirect a restore to another database.

Quoted names in the schema and table fields (`public."Order Items"`, as the dialog fills them in for a table node) are no longer split at their spaces or commas.
2026-11-17 09:32:55 +08:00
l0ng-ai 41bae970e0 docs(plugins): regenerate the theme token reference (#3849)
Two editor colour scheme tokens landed without regenerating plugins/themes.md, so the is-current check failed on every branch.
2026-11-17 08:46:13 +08:00
Deng Liuтаdengliu 44b5515432 fix(markdown): honor container align attributes on Mermaid diagrams (#3847)
A Mermaid diagram inside <div align="left"> (or right / center, or <center>) stayed centered in the Markdown preview and agent chat: DOMPurify drops inline style, and .mermaid-output's text-align: center plus the SVG's margin: 0 auto overrode the kept align attribute. Aligned containers now set inherited --mermaid-align / margin properties that the diagram output uses; unaligned diagrams stay centered.

Co-authored-by: dengliu <[email protected]>
2026-11-17 08:09:14 +08:00
l0ng-ai 64d5618cc7 feat(welcome): show recent projects whose folder no longer exists as unavailable (#3845)
When the recent list is read, a local project whose folder is gone is marked
`missing` and loses its stale branch (a deleted repository or a removed git
worktree kept the branch it had). Remote locations (ssh://, wsl://,
devcontainer://) and WSL shares are not checked. The welcome screen, the
project switcher and the recent-projects popup show such an entry with a dimmed
name and badge and a "<path> (unavailable)" tooltip; opening one still offers
to remove it from the list.
2026-11-17 07:56:32 +08:00
l0ng-ai 1a21efa4aa feat(plugins): a plugin command can answer Escape in the editor (API 1.10) (#3844)
`[[contributes.keymaps]]` accepts `key = "Escape"` with a required `when`.
Plain keys stayed out of plugin shortcuts, and Escape could not be added as a
shortcut anyway: the IDE's own keymap uses it, so the binding would be dropped.
It becomes the editor's lowest-precedence Escape handler instead: the command
runs once popups, completion, rename, selection, extra carets and Vim had no
use for the key, and only while its `when` holds (the latest plugin's binding
first). `when` is accepted only on such a binding; manifests that set it
elsewhere, or bind Escape on one platform only, are refused.
2026-11-17 07:15:11 +08:00
l0ng-ai 72cf2f488e test: fix the Windows ui_points and debugger stop tests, and a tight plugin budget (#3842)
- ui_points: a Windows checkout has CRLF line ends, so removing
  "width = 110\n" from the fixture did nothing and the missing-width case
  passed. The fixture text is normalized to LF first.
- ide-dap: the fake adapter stops at a breakpoint after launch, and since
  Stop kills a suspended program's tree at once (#3658), the Windows stop
  test no longer saw the wait it checks. The adapter now continues right
  after that stop, so Stop meets a running program.
- plugin_data_tools: database_calls_enforce_grants… ran its plugin commands
  under a 250 ms budget it does not test; a slow runner's first call timed
  out. It gets 10 s.
2026-11-17 06:23:51 +08:00
时雨遥 53495fbc26 fix(terminal): tab spinner stops while an interactive program without a progress report waits for input (#3838)
Closes #3831

An interactive program is one long command to the shell, so OSC 133 C/D kept the tab spinning from launch to exit for programs that send no OSC 9;4 report (Claude Code, Codex). A running command that turned on bracketed paste or the alternate screen reads the keyboard itself; its tab now spins only while it keeps drawing (output at most 400 ms apart for 500 ms, until 1.5 s of silence; typing echo excluded). A progress report still decides when present, and plain commands spin from start to end as before.

Co-authored-by: StarryKira <[email protected]>
2026-11-17 04:37:15 +08:00
l0ng-ai 224099992a feat(python): create a Conda environment by name in conda's envs directory (#3839)
The Add Python Interpreter dialog asks for a Conda environment's name (the
project folder's by default) instead of a location. The backend runs
`conda create -n <name>` for a bare name, refuses a name conda already lists,
and finds the new prefix from `conda env list`; a path still creates the
environment at that prefix with `-p`.
2026-11-17 04:29:39 +08:00
l0ng-ai 0dafd649da fix(python): readable environment creation log and status refresh after creating one (#3837)
Tool output is shown as a terminal would show the line: backspaces erase
(conda's spinner), a carriage return rewrites the line (pip progress) and
ANSI sequences are dropped.

The interpreter status widget re-reads interpreters when one is created or
added in Settings. A conda environment lives outside the project, so no file
event announced it, and when the configured path was already set the widget
kept showing "Invalid interpreter" and an interpreter list without it.
2026-11-17 04:24:28 +08:00
l0ng-ai d2c5532ccb fix(completion): complete at every caret (#3836)
With several carets, picking a completion inserted it at the main caret only
and collapsed the selection. The item now goes in at each caret whose text
around it matches the main caret's (the typed prefix, and what a replacing
edit overwrites). Snippets go in as plain text with each caret at the first
stop. Items the server inserts itself (kotlin-lsp) keep the carets, and the
server's edit is repeated at the others when it lands.
2026-11-17 04:18:31 +08:00
l0ng-ai a03923f744 fix(fonts): editor popups and consoles follow the configured fonts (#3835)
- Completion, parameter info and hover docs render in a tooltip container
  outside the editor, which carries its theme classes but not its inline
  style, so they used the default mono font at 13px. The editor font
  variables are now also provided as a theme; completion rows grow with
  the font size.
- The Run and Debug consoles use the terminal's weights (the editor's main
  and bold weights when the terminal follows the editor font).
- "Show only monospaced fonts" is a setting shared by Editor › Font and
  Tools › Terminal instead of resetting every time the page opens.

Fixes #3621
2026-11-17 04:09:12 +08:00
174 змінених файлів з 4027 додано та 426 видалено

No files matched your search

Створено
+45 -45
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4254,7 +4254,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-run",
@@ -4268,7 +4268,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4297,7 +4297,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4333,7 +4333,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4346,7 +4346,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4367,7 +4367,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4379,7 +4379,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4392,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4410,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4483,7 +4483,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4502,7 +4502,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4524,7 +4524,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4536,7 +4536,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"encoding_rs",
"futures",
@@ -4553,7 +4553,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"libc",
"tempfile",
@@ -4562,7 +4562,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"futures",
"serde",
@@ -4573,7 +4573,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4631,7 +4631,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4659,7 +4659,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"bytes",
"dunce",
@@ -4678,7 +4678,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"futures",
"ide-core",
@@ -4701,7 +4701,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4724,7 +4724,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4738,7 +4738,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"futures",
@@ -4758,7 +4758,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4782,7 +4782,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-tools",
@@ -4798,7 +4798,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"flate2",
@@ -4821,7 +4821,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"encoding_rs",
@@ -4842,7 +4842,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"parking_lot",
@@ -4855,7 +4855,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4880,7 +4880,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4893,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4908,7 +4908,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"libc",
@@ -4921,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4934,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"flate2",
"hex",
@@ -4955,7 +4955,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4976,7 +4976,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"chardetng",
"dunce",
@@ -5002,7 +5002,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5018,7 +5018,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.46"
version = "0.1.47"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+11 -6
Переглянути файл
@@ -72,9 +72,8 @@ async fn run_once(
config::add_client_options(&launch.id, &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let mut levels = BTreeMap::new();
if new.get("configOptions").is_some_and(Value::is_array)
&& let Some(model) = model_option.and_then(|o| o.current.as_ref())
{
let has_config = new.get("configOptions").is_some_and(Value::is_array);
if has_config && let Some(model) = model_option.and_then(|o| o.current.as_ref()) {
levels.insert(model.clone(), levels_for_model_from_slice(&options));
}
if let Some(selected) = selected_model
@@ -88,7 +87,7 @@ async fn run_once(
updates.config.lock().session = Some(session.to_owned());
let response: Value = conn.request(method, params, None).await.map_err(discovery_error)?;
let settings = if let Some(settings) = selected_settings(&response, selected) {
settings
Some(settings)
} else {
tokio::time::timeout(CONFIG_UPDATE_TIMEOUT, async {
loop {
@@ -106,9 +105,15 @@ async fn run_once(
}
})
.await
.map_err(|_| "The agent did not report settings for the selected model".to_owned())?
.ok()
};
match settings {
Some(settings) => levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings)),
// An agent on the legacy `models` field that says nothing more: the model has
// no settings of its own, and switching to it must not fail.
None if !has_config => levels.insert(selected.to_owned(), Vec::new()),
None => return Err("The agent did not report settings for the selected model".to_owned()),
};
levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings));
}
let commands = updates
.commands
+27
Переглянути файл
@@ -774,6 +774,33 @@ async fn selected_model_uses_legacy_set_model_and_authoritative_notifications()
assert!(!catalog.thought_levels.contains_key("default"), "legacy model lists alone do not assert no controls");
}
#[tokio::test]
async fn selected_legacy_model_without_settings_has_no_levels_instead_of_failing() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false, Some("second")).unwrap();
harness
.next()
.await
.reply
.send(Ok(json!({
"sessionId": "discovery-only",
"models": { "currentModelId": "default", "availableModels": [
{ "modelId": "default", "name": "Default" }, { "modelId": "second", "name": "Second" }
] }
})))
.unwrap();
let selected = harness.next().await;
assert_eq!(selected.method, "session/set_model");
selected.reply.send(Ok(json!({}))).unwrap();
let catalog = completed(&mut events).await;
assert!(catalog.error.is_none(), "{:?}", catalog.error);
assert_eq!(catalog.thought_levels.get("second"), Some(&Vec::new()));
}
#[tokio::test]
async fn catalog_replacement_removes_selected_metadata_for_models_no_longer_listed() {
let tmp = tempfile::tempdir().unwrap();
+22 -6
Переглянути файл
@@ -47,13 +47,20 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
fs::write(
&script,
format!(
r#"gradle.projectsEvaluated {{
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def resources = p.tasks.named('processResources')
p.tasks.register('openideaUpdateResources') {{
dependsOn resources
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
def dir = p.tasks.getByName('processResources').destinationDir
def manifest = new File({})
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
"#,
literal(&p.path),
@@ -172,7 +179,16 @@ mod tests {
assert_eq!(gradle.command, "/tools/gradlew");
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
assert!(
script.contains("processResources")
&& script.contains(".destinationDir\n")
&& script.contains("setText(dir.absolutePath")
);
// `register` is Gradle 4.9+ (#3864).
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
+7 -3
Переглянути файл
@@ -30,7 +30,8 @@ def processedResources = { Project p, s ->
def describe = { Project p ->
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
if (p.gradle.parent != null) m.build = identity(p.rootProject)
def sets = p.extensions.findByName('sourceSets')
// Gradle 4.x has it as a convention property, not an extension.
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
if (sets != null) {
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
// and sets whose folders the `idea` plugin lists as test sources.
@@ -51,9 +52,12 @@ def describe = { Project p ->
}
}
try {
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
def java = p.extensions.findByName('java')
def lv = java?.toolchain?.languageVersion?.getOrNull()
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
println '@openidea-model\t' + JsonOutput.toJson(m)
}
+26 -7
Переглянути файл
@@ -172,13 +172,25 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
fs::write(
&script,
format!(
r#"gradle.projectsEvaluated {{
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def warTask = p.tasks.named('war')
p.tasks.register('openideaTomcatArtifact') {{
dependsOn warTask
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
def war = p.tasks.getByName('war')
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
def manifest = new File({})
t.doLast {{
def file = archive instanceof File ? archive : archive.get().asFile
manifest.setText(file.absolutePath, 'UTF-8')
}}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
"#,
groovy_literal(path),
@@ -270,7 +282,7 @@ mod tests {
assert_eq!(a.len(), 1);
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
@@ -297,7 +309,14 @@ mod tests {
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
assert!(script.contains(&format!("rootProject.project('{}')", module)));
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
assert!(
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
);
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
}
}
}
+8 -5
Переглянути файл
@@ -167,10 +167,11 @@ const GRADLE: &[&str] = &["gradle", "gradlew"];
/// Gradle's own JVM and the compiler's source encoding are untouched.
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
tasks.withType(JavaExec).configureEach {
defaultCharacterEncoding = 'UTF-8'
}
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
}
";
@@ -621,10 +622,12 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(s.contains("? tasks.configureEach(action) : tasks.all(action)"), "{s}");
}
#[test]
+15
Переглянути файл
@@ -920,6 +920,8 @@ pub struct EditorSettings {
/// Colours the rainbow bracket depth cycles through (2–5).
pub rainbow_bracket_colors: u32,
pub ligatures: bool,
/// Editor › Font and Tools › Terminal › Font: the font pickers list only monospaced fonts.
pub only_monospaced_fonts: bool,
/// Fallback font for glyphs the main font lacks; empty = none.
pub fallback_font: String,
/// Typography Settings › Main font weight (CSS 100–900), as IDEA.
@@ -966,6 +968,7 @@ impl Default for EditorSettings {
rainbow_bracket_kinds: RainbowBracketKinds::default(),
rainbow_bracket_colors: 3,
ligatures: false,
only_monospaced_fonts: true,
fallback_font: String::new(),
font_weight: 400,
bold_font_weight: 700,
@@ -1820,6 +1823,18 @@ mod tests {
assert_eq!(restored.editor.rainbow_bracket_colors, 5);
}
#[test]
fn only_monospaced_fonts_defaults_on_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"editor":{"ligatures":true}}"#).unwrap();
assert!(old.editor.only_monospaced_fonts);
let mut settings = Settings::default();
settings.editor.only_monospaced_fonts = false;
let json = serde_json::to_value(&settings).unwrap();
assert_eq!(json["editor"]["onlyMonospacedFonts"], false);
let restored: Settings = serde_json::from_value(json).unwrap();
assert!(!restored.editor.only_monospaced_fonts);
}
#[test]
fn docstring_format_defaults_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
+14 -6
Переглянути файл
@@ -6,11 +6,16 @@ use ide_run::wrap::{self, program_name};
use std::path::Path;
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
allprojects {
plugins.withId('java') {
apply plugin: 'jacoco'
tasks.withType(Test).configureEach { t -> t.finalizedBy(tasks.named('jacocoTestReport')) }
tasks.named('jacocoTestReport') { r -> r.reports { xml.required.set(true) } }
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
def xml = p.tasks.getByName('jacocoTestReport').reports.xml
// `Report.required` is Gradle 6.1+, `enabled` is gone in 8.0.
if (xml.hasProperty('required')) xml.required.set(true) else xml.enabled = true
}
}
"#;
@@ -391,7 +396,10 @@ mod tests {
let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args[0], "--init-script");
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco"));
let script = std::fs::read_to_string(&l.args[1]).unwrap();
assert!(script.contains("p.apply plugin: 'jacoco'"), "{script}");
// `Report.required` is Gradle 6.1+, `configureEach` 4.9+ (#3864).
assert!(script.contains("else xml.enabled = true") && script.contains(": tasks.all(action)"), "{script}");
assert!(matches!(report, CoverageReportSpec::Jacoco { .. }));
}
+3
Переглянути файл
@@ -1624,6 +1624,7 @@ impl DebugManager {
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
Ok(())
}
@@ -1672,6 +1673,7 @@ impl DebugManager {
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
@@ -1783,6 +1785,7 @@ impl DebugManager {
.await;
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
+4
Переглянути файл
@@ -116,6 +116,8 @@ pub(crate) struct Session {
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
/// The last trace that finished, until the stop its records were read in ends.
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
@@ -281,6 +283,7 @@ impl Session {
jvm_memory: tokio::sync::Mutex::default(),
stream_tracer: parking_lot::Mutex::new(None),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
}
@@ -774,6 +777,7 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
+64 -8
Переглянути файл
@@ -88,6 +88,32 @@ pub enum TraceUnavailable {
},
}
/// A trace that finished. Its records keep their objects from being collected until the stop they
/// were read in ends; then the UI no longer shows them and [`release_done`] lets them go.
pub(crate) struct DoneTrace {
tracer: Arc<dyn StreamTracer>,
target: VmTarget,
id: TraceId,
}
/// The stop a finished trace was read in ended (a resume, a step, a `continued` event).
pub(crate) fn release_done(s: &Session) {
let Some(done) = s.stream_trace_done.lock().take() else { return };
let ended = s.ended.clone();
let session = s.id.0;
tokio::spawn(async move {
tokio::select! {
biased;
() = ended.cancelled() => {}
result = done.tracer.release(&done.target, done.id) => {
if let Err(e) = result {
tracing::debug!(session, trace = done.id, "releasing a finished stream trace: {e}");
}
}
}
});
}
/// The session's running trace; `id` is `None` until `arm` answers.
pub(crate) struct ActiveTrace {
tracer: Arc<dyn StreamTracer>,
@@ -181,10 +207,30 @@ pub(crate) async fn run(
if !s.suspended.get() {
return unavailable(TraceUnavailable::NotSuspended);
}
let mut trace =
Trace { mgr, s, tracer: &*tracer, target: &target, thread_id, progress, id: None, last: Counts::default() };
// The bundle releases the previous trace itself when this one arms.
s.stream_trace_done.lock().take();
static TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let token =
format!("{}-{}-{}", std::process::id(), s.id.0, TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let mut trace = Trace {
mgr,
s,
tracer: &*tracer,
target: &target,
thread_id,
progress,
token,
arm_sent: false,
id: None,
last: Counts::default(),
};
match trace.drive(plan, cancel).await {
Ok(run) => run,
Ok(run) => {
if let (TraceRun::Done { .. }, Some(id)) = (&run, trace.id) {
*s.stream_trace_done.lock() = Some(DoneTrace { tracer: tracer.clone(), target: target.clone(), id });
}
run
}
Err(run) => {
// A stop from now on is the user's to see.
set_running(s, false);
@@ -231,6 +277,9 @@ struct Trace<'a, P> {
target: &'a VmTarget,
thread_id: i64,
progress: &'a P,
/// Names the trace to the bundle before `arm` answers (see [`StreamTracer::release_armed`]).
token: String,
arm_sent: bool,
/// Set once `arm` answers.
id: Option<TraceId>,
last: Counts,
@@ -241,8 +290,9 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
async fn drive(&mut self, plan: &Value, cancel: &CancellationToken) -> Result<TraceRun, TraceRun> {
let (s, tracer, target) = (self.s, self.tracer, self.target);
self.report(TracePhase::Arming);
self.arm_sent = true;
let id = self
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET))
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET, &self.token))
.await?
.map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?;
self.id = Some(id);
@@ -313,14 +363,20 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
/// After a trace that ended early. Left to the bundle, an armed trace would keep every
/// breakpoint off and a parked one its thread suspended behind java-debug's back; the bundle
/// undoes either, or does so once a terminal still running returns. Not after a finished
/// trace: the records it unpins are the values the result shows.
/// trace: the records it unpins are the values the result shows ([`release_done`] does, once
/// that stop ends). An `arm` that never answered (it timed out) may still have armed: released
/// by its token.
async fn release(&self) {
let Some(id) = self.id else { return };
if self.s.ended.is_cancelled() {
return;
}
if let Ok(Err(e)) = self.until_ended(self.tracer.release(self.target, id)).await {
tracing::debug!(session = self.s.id.0, trace = id, "stream trace release: {e}");
let work = match self.id {
Some(id) => self.tracer.release(self.target, id),
None if self.arm_sent => self.tracer.release_armed(self.target, &self.token),
None => return,
};
if let Ok(Err(e)) = self.until_ended(work).await {
tracing::debug!(session = self.s.id.0, trace = ?self.id, "stream trace release: {e}");
}
}
+13 -2
Переглянути файл
@@ -72,10 +72,21 @@ async fn windows_stop_releases_the_debuggees_port_before_returning() {
.unwrap();
let pid = child.0.id();
child.1 = Some(ide_core::process::ProcessTree::capture(pid));
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate, ..Default::default() });
// A running program: one suspended at a breakpoint is killed at once (#3658), without the
// wait for its tree this test is about.
let h = harness(Script {
debuggee_pid: Some(pid),
supports_terminate,
continued_after_stop: true,
..Default::default()
});
let id = h.start(config()).await.unwrap();
let session = h.manager.session(id).unwrap();
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
// The pid, then the stop at launch and the `continued` that ends it.
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid)
|| session.suspended.ticket() == 0
|| session.suspended.get()
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stop = tokio::spawn({
+36
Переглянути файл
@@ -55,6 +55,7 @@ impl StreamTracer for FakeTracer {
_thread_id: i64,
_plan: &'a Value,
_budget: u32,
_token: &'a str,
) -> InspectFuture<'a, TraceId> {
self.record("arm", target);
let error = self.arm_error.lock().clone();
@@ -96,6 +97,11 @@ impl StreamTracer for FakeTracer {
self.record("release", target);
Box::pin(async { Ok(()) })
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, _token: &'a str) -> InspectFuture<'a, ()> {
self.record("releaseArmed", target);
Box::pin(async { Ok(()) })
}
}
fn collected() -> TraceCollected {
@@ -443,6 +449,36 @@ async fn a_finished_trace_is_not_released() {
assert!(!tracer.names().contains(&"release"), "{:?}", tracer.names());
}
#[tokio::test]
async fn a_finished_trace_is_released_once_the_program_runs_on() {
let h = harness(java_debug());
let tracer = FakeTracer::scripted([parked()]);
let id = stopped_java(&h, &tracer).await;
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Done { .. }));
h.manager.resume(id, 1).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !tracer.names().contains(&"release") {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the finished trace was not released");
assert_eq!(tracer.names().iter().filter(|n| **n == "release").count(), 1);
}
#[tokio::test]
async fn an_arm_without_a_reply_is_released_by_its_token() {
// The bundle may still finish arming after the reply timed out: its breakpoints would stay off.
let h = harness(java_debug());
let tracer = FakeTracer::scripted([]);
let id = stopped_java(&h, &tracer).await;
*tracer.arm_error.lock() = Some(InspectError::TimedOut);
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Failed { .. }));
assert_eq!(tracer.names(), ["arm", "releaseArmed"]);
}
#[tokio::test]
async fn refused_stop_leaves_the_outcome_to_wait() {
let h = harness(java_debug());
+4 -2
Переглянути файл
@@ -179,7 +179,9 @@ fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
}
fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
let mut args: Vec<String> = (!file.is_empty()).then(|| format!("--file={file}")).into_iter().collect();
// `~/.psqlrc` could switch databases or change settings before the dump runs.
let mut args = vec!["--no-psqlrc".to_owned()];
args.extend((!file.is_empty()).then(|| format!("--file={file}")));
args.extend(flag(o.single_transaction, "--single-transaction"));
args.extend(flag(o.stop_on_error, "--set=ON_ERROR_STOP=1"));
args
@@ -317,7 +319,7 @@ mod tests {
let options = DbPsqlOptions { single_transaction: true, stop_on_error: true };
assert_eq!(
args(DbToolJob::Psql { file: "/tmp/shop.sql".into(), options }),
["--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
["--no-psqlrc", "--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
);
}
+23 -1
Переглянути файл
@@ -237,7 +237,7 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
args.push(format!("--username={}", source.user.trim()));
}
if !source.database.is_empty() {
args.push(format!("--dbname={}", source.database));
args.push(format!("--dbname={}", dbname_arg(&source.database)));
}
// Without a terminal a password prompt would wait forever: fail instead.
args.push("--no-password".into());
@@ -271,6 +271,16 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
(args, env)
}
/// `--dbname` reads a connection string or URI as connection parameters: such a database name
/// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials.
fn dbname_arg(name: &str) -> String {
if name.contains('=') || name.starts_with("postgresql://") || name.starts_with("postgres://") {
format!("dbname='{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
} else {
name.to_owned()
}
}
/// How a tool is started: connection arguments, then the job's, and the environment.
pub struct Prepared {
pub args: Vec<String>,
@@ -404,6 +414,18 @@ mod tests {
assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS"));
}
#[test]
fn a_database_named_like_connection_parameters_stays_a_name() {
for (name, arg) in [
("host=evil.example dbname=p", r"--dbname=dbname='host=evil.example dbname=p'"),
(r"it's=\x", r"--dbname=dbname='it\'s=\\x'"),
("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"),
] {
let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() });
assert!(args.contains(&arg.to_owned()), "{args:?}");
}
}
#[test]
fn default_port_and_optional_fields() {
let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() };
+7 -2
Переглянути файл
@@ -25,12 +25,17 @@ impl Scope {
} else {
call.root().join(given)
});
let roots: Vec<PathBuf> =
std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots()).collect();
// Before touching the file system: on Windows, resolving `\\host\share` signs in to that host.
if !ide_vfs::content_path_allowed(&path, &roots) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
let path = dunce::canonicalize(&path).unwrap_or(path);
if !path.is_dir() {
return Err(IdeError::not_found(format!("scope {raw} is not a directory")));
}
let roots = std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots());
if !roots.into_iter().any(|root| path.starts_with(root)) {
if !roots.iter().any(|root| path.starts_with(root)) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
Ok(Self(Some(path)))
+19 -9
Переглянути файл
@@ -883,14 +883,20 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let host = call.host();
let project = call.project().clone();
let indexing_before = project.index.status().indexing;
let pool = if scope.is_all() && dir.dir().is_none() {
limit + 1
} else {
((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL)
};
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
let found = {
let (project, q) = (project.clone(), q.clone());
host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await?
let (project, q, dir) = (project.clone(), q.clone(), dir.dir().map(Path::to_path_buf));
host.blocking(move || {
Ok(match dir {
// Filtered in the index: a pool cut before the filter could miss every match.
Some(dir) => project
.index
.find_symbols_until(&q, ide_index::SymbolFilter::All, pool, &|p| p.starts_with(&dir), &|| false)
.unwrap_or_default(),
None => project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool),
})
})
.await?
};
let mut items: Vec<SearchItem> = found
.into_iter()
@@ -910,10 +916,14 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let budget = MEDIUM_TIMEOUT.saturating_sub(started.elapsed());
let (symbols, out_of_time) = workspace_symbols(&call, &q, budget).await;
timed_out = out_of_time;
let mut roots = project.content_roots();
roots.extend(crate::mcp::tool::attached_projects(call.root()));
for (name, container, location) in symbols {
let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path));
// Project files obey `scope` and `paths`; library symbols are what was asked for.
let inside = location.uri.is_none() && !Path::new(&path).is_absolute();
// Project files (attached projects' too) obey `scope` and `paths`; library symbols
// are what was asked for.
let inside = location.uri.is_none()
&& (!Path::new(&path).is_absolute() || roots.iter().any(|r| location.path.starts_with(r)));
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
continue;
}
+1
Переглянути файл
@@ -65,6 +65,7 @@ pub async fn spell_check(
end: r.end,
kind: match r.kind {
SpellingKind::Comment => RegionKind::Comment,
SpellingKind::String if r.raw => RegionKind::RawString,
SpellingKind::String => RegionKind::String,
SpellingKind::Name => RegionKind::Name,
},
+4
Переглянути файл
@@ -379,6 +379,10 @@ fn ready(
},
};
let mut linked = link_trace(plan, &recording, collected.skipped_breakpoints);
// A stream made parallel before the chain's statement, which the bundle found so at run time.
if collected.sequentialized && !plan.sequentialize {
linked.banners.push(TraceBanner::Sequentialized);
}
if resumed_stops > 0 {
linked.banners.push(TraceBanner::BreakpointsResumed { count: resumed_stops });
}
+17
Переглянути файл
@@ -442,3 +442,20 @@ fn chain_info_steps_keep_modifiers() {
let found = chains_at(service(), &snap, &frame(1), true, true, &CancellationToken::new()).unwrap();
assert_eq!(found[0].info.steps, ["filter", "unordered", "map"]);
}
#[test]
fn ready_says_a_stream_found_parallel_at_run_time_ran_sequentially() {
let java = LanguageId::new("java");
let snap = Snapshot::text(&java, SOURCE);
let found = chains_at(service(), &snap, &frame(line_of("C_SPIKE")), true, true, &CancellationToken::new()).unwrap();
let Candidate { info, chain } = found.into_iter().next().unwrap();
let chain = chain.unwrap();
let plan = real_run_plan(&chain).unwrap();
assert!(!plan.sequentialize);
let collected = TraceCollected { sequentialized: true, ..spike_collected() };
let StreamTraceResult::Ready { banners, .. } = ready(info, &chain, &plan, collected, 9, 0) else {
panic!("not ready");
};
assert!(banners.contains(&TraceBanner::Sequentialized), "{banners:?}");
}
+22
Переглянути файл
@@ -1304,6 +1304,25 @@ pub async fn vcs_create_patch(
.await
}
/// The changes a commit with `options` would make in `repo`, as one patch (what Commit
/// commits: the index with the selection applied, partial files' chosen hunks only).
pub async fn vcs_pending_patch(
host: &Host,
window: &str,
repo: Option<PathBuf>,
options: CommitOptions,
) -> IdeResult<String> {
const MAX_PATCH: usize = 1 << 20;
let project = host.project(window)?;
blocking(move || {
project.with_repo_at(repo.as_deref(), |r| {
let changes = r.pending_changes(&options, MAX_PATCH, &|path| project.vcs_encoding(path, None))?;
Ok(changes.into_iter().filter_map(|c| c.diff).collect())
})
})
.await
}
pub async fn vcs_patch_preview(
host: &Host,
window: &str,
@@ -1663,6 +1682,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_create_patch", |c| async move {
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
});
d.add("vcs_pending_patch", |c| async move {
vcs_pending_patch(&c.host, &c.window, c.arg("repo")?, c.arg("options")?).await
});
d.add("vcs_patch_preview", |c| async move {
vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await
});
+57 -4
Переглянути файл
@@ -13,6 +13,7 @@
//! [[contributes.keymaps]]
//! command = "check"
//! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`)
//! # key = "Escape" + when = "…" # API 1.10: Escape in an editor that the IDE had no use for
//!
//! [[contributes.statusBar]]
//! id = "branch"
@@ -203,8 +204,16 @@ struct KeymapDecl {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
mac: Option<String>,
/// Only with an `Escape` binding (API 1.10): when the command clears something.
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
}
/// The one plain key a plugin may bind (API 1.10): in a focused editor, after the IDE's own uses of
/// Escape (popups, completion, rename, selection, extra carets, Vim) found nothing to do, like a
/// handler at the end of IDEA's EditorEscape chain.
const ESCAPE: &str = "Escape";
const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"];
const NAMED_KEYS: [&str; 22] = [
"Enter",
@@ -262,9 +271,21 @@ pub fn validate_binding(binding: &str) -> Result<(), String> {
pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: KeymapDecl = decode(KEYMAPS, decl)?;
declared_command(pkg, KEYMAPS, &d.command)?;
validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?;
if let Some(m) = &d.mac {
validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?;
let escape = d.key == ESCAPE || d.mac.as_deref() == Some(ESCAPE);
if escape {
if d.key != ESCAPE || d.mac.as_deref().is_some_and(|m| m != ESCAPE) {
return Err("contributes.keymaps: an Escape binding is Escape on every platform".into());
}
pkg.manifest.needs_api("contributes.keymaps key = \"Escape\"", 10)?;
let when = d.when.as_deref().ok_or("contributes.keymaps: an Escape binding needs a `when` clause")?;
validate_when(when).map_err(|e| format!("contributes.keymaps: {e}"))?;
} else if d.when.is_some() {
return Err("contributes.keymaps: `when` is only for an Escape binding".into());
}
for binding in std::iter::once(&d.key).chain(&d.mac) {
if binding != ESCAPE {
validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?;
}
}
Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?))
}
@@ -1114,6 +1135,37 @@ mod tests {
}
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
let manifest = ide_extension::Manifest::parse(&format!(
"id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='clear'\ntitle='Clear'"
))
.unwrap();
Package::new(manifest, std::path::PathBuf::from("/unused"))
};
let check = |api: &str, decl: &str| keymap(&pkg(api), toml::from_str(decl).unwrap());
let escape = "command='clear'\nkey='Escape'\nwhen='plugin.test.active'";
let ok = check("^1.10", escape).unwrap();
assert_eq!(ok.json["when"], "plugin.test.active");
assert!(check("^1.10", &format!("{escape}\nmac='Escape'")).is_ok());
for (api, decl, error) in [
("^1.9", escape, "1.10"),
("^1.10", "command='clear'\nkey='Escape'", "when"),
("^1.10", "command='clear'\nkey='Escape'\nwhen='a &&'", "when"),
("^1.10", &format!("{escape}\nmac='Meta+K'") as &str, "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nmac='Escape'\nwhen='x'", "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nwhen='x'", "only for an Escape"),
("^1.10", "command='clear'\nkey='Enter'", "needs Ctrl"),
("^1.10", "command='clear'\nkey='Shift+Escape'", "needs Ctrl"),
] {
let err = check(api, decl).unwrap_err();
assert!(err.contains(error), "{api} {decl}\n→ {err}");
}
// Other bindings are unchanged.
assert!(check("^1.9", "command='clear'\nkey='Ctrl+Alt+C'").is_ok());
}
#[test]
fn bindings_need_a_modifier() {
for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] {
@@ -1243,7 +1295,8 @@ mod tests {
#[test]
fn editor_panels_validate_api_width_when_capability_and_page() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/editor-panel");
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
// A Windows checkout may have CRLF line ends; the edits below match on `\n`.
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap().replace("\r\n", "\n");
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(EDITOR_PANELS).into_iter().next().unwrap();
+21
Переглянути файл
@@ -481,6 +481,27 @@ async fn scope_limits_the_query_tools_to_a_directory() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_scoped_symbol_search_finds_matches_past_the_unscoped_ones() {
let h = Harness::new();
std::fs::create_dir_all(h.root.join("many")).unwrap();
for i in 0..60 {
std::fs::write(h.root.join(format!("many/m{i:02}.rs")), "pub fn pool_marker() {}\n").unwrap();
}
std::fs::create_dir_all(h.root.join("zz")).unwrap();
std::fs::write(h.root.join("zz/last.rs"), "pub fn pool_marker() {}\n").unwrap();
// Files written after the project opened reach the index through the watcher.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while h.json("search_symbol", json!({"q":"pool_marker","limit":100})).await["items"].as_array().map_or(0, Vec::len)
< 61
{
assert!(std::time::Instant::now() < deadline, "the files were never indexed");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let found = h.json("search_symbol", json!({"q":"pool_marker","scope":"zz","limit":1})).await;
assert_eq!(found["items"][0]["filePath"], "zz/last.rs", "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
let h = Harness::new();
+2 -1
Переглянути файл
@@ -80,7 +80,8 @@ impl Harness {
}
#[tokio::test(flavor = "multi_thread")]
async fn database_calls_enforce_grants_trust_ownership_and_uninstall_lifetime() {
let f = Harness::new();
// Nothing here tests the command budget, and a slow runner's first calls can exceed 250 ms.
let f = Harness::with_timeout(Duration::from_secs(10));
assert!(f.run("sources", None).is_err());
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let source = f.source();
+6 -1
Переглянути файл
@@ -64,13 +64,15 @@ pub struct TraceCollected {
}
pub trait StreamTracer: Send + Sync {
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept.
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. `token`
/// names the trace for [`release_armed`](Self::release_armed) when no reply arrives.
fn arm<'a>(
&'a self,
target: &'a VmTarget,
thread_id: i64,
plan: &'a serde_json::Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId>;
/// Blocks up to `ms` milliseconds for the trace to leave `Running`.
fn wait<'a>(&'a self, target: &'a VmTarget, trace: TraceId, ms: u32) -> InspectFuture<'a, TraceState>;
@@ -81,4 +83,7 @@ pub trait StreamTracer: Send + Sync {
/// with; reading each takes a round trip to the JVM, so the time allowed grows with them.
fn collect<'a>(&'a self, target: &'a VmTarget, trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected>;
fn release<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, ()>;
/// Releases the trace armed with `token` whose `arm` reply never came (it timed out); nothing
/// when there is none.
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()>;
}
+34 -3
Переглянути файл
@@ -73,6 +73,33 @@ pub struct SpellingRegion {
pub start: usize,
pub end: usize,
pub kind: SpellingKind,
/// A raw / verbatim string: backslashes are literal text, not escapes
/// (`r"\user"`, `r#"…"#`, `` `…` ``, `@"…"`). The spelling layer must not
/// skip the character after a `\` in one of these.
pub raw: bool,
}
/// Whether `node` is a string literal whose backslashes are not escapes.
fn is_raw_string(node: &Node<'_>, text: &str) -> bool {
let kind = node.kind();
// Rust/C++/C# grammars name the node directly.
if kind == "raw_string_literal" || kind == "verbatim_string_literal" || kind.contains("raw_string") {
return true;
}
// Go backtick strings and Python `r`/`fr`/`rb` prefixes: the grammar uses
// the generic `string` node, so inspect the literal's own prefix.
if kind == "string" || kind == "string_literal" {
let literal = &text[node.start_byte()..node.end_byte()];
if literal.starts_with('`') {
return true;
}
let quote = literal.find(['"', '\'']);
let prefix = quote.map_or("", |i| &literal[..i]);
return !prefix.is_empty()
&& prefix.chars().any(|c| c == 'r' || c == 'R')
&& prefix.chars().all(|c| matches!(c, 'r' | 'R' | 'b' | 'B' | 'f' | 'F' | 'u' | 'U'));
}
false
}
fn is_name_leaf(kind: &str) -> bool {
@@ -101,16 +128,20 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
}
/// Comments, string literals and declared names, for spell checking.
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> Vec<SpellingRegion> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let literal = kind_of(&node);
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
match literal {
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
Some(LiteralKind::String) => {
let mut r = region(SpellingKind::String);
r.raw = is_raw_string(&node, text);
out.push(r);
}
None if node.is_named()
&& node.child_count() == 0
&& is_name_leaf(node.kind())
+1 -1
Переглянути файл
@@ -294,7 +294,7 @@ impl Syntax {
/// Comments, string literals and declared names (byte ranges, document
/// order) for the Typo inspection; `None` like [`Self::literals`].
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
+29
Переглянути файл
@@ -1422,6 +1422,35 @@ fn spelling_regions_cover_declared_names_only() {
assert_eq!(names, ["Bird", "fly", "text"]);
}
#[test]
fn spelling_regions_mark_raw_strings() {
let py = r#"a = r"\user" + R'\mesage' + fr"\wrd" + rb"\foo" + "\user""#;
let found: Vec<(&str, bool)> = syntax()
.spelling_regions(&lang("python"), py)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::String)
.map(|r| (&py[r.start..r.end], r.raw))
.collect();
assert_eq!(
found,
vec![
(r#"r"\user""#, true),
(r"R'\mesage'", true),
(r#"fr"\wrd""#, true),
(r#"rb"\foo""#, true),
(r#""\user""#, false),
]
);
// C# verbatim / Rust raw literals are named by the grammar itself.
let cs = r#"var s = @"C:\mesage";"#;
let raw = syntax().spelling_regions(&lang("csharp"), cs).unwrap().iter().any(|r| r.raw);
assert!(raw, "C# verbatim string should be raw");
let rs = r#"let s = r"\mesage";"#;
let raw = syntax().spelling_regions(&lang("rust"), rs).unwrap().iter().any(|r| r.raw);
assert!(raw, "Rust raw string should be raw");
}
// ---------------------------------------------------------------------------
// Script regions of Vue SFCs and HTML documents
+5
Переглянути файл
@@ -0,0 +1,5 @@
doctrine-mapping.xsd is from Doctrine ORM (https://github.com/doctrine/orm),
MIT License. Copyright (c) Doctrine Project.
The copy published at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd
is broken (wrong targetNamespace / XMLSchema URI after an http→https rewrite);
this file is the upstream schema with the correct namespace.
+643
Переглянути файл
@@ -0,0 +1,643 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:orm="http://doctrine-project.org/schemas/orm/doctrine-mapping"
elementFormDefault="qualified">
<xs:annotation>
<xs:documentation><![CDATA[
This is the XML Schema for the object/relational
mapping file used by the Doctrine ORM.
]]></xs:documentation>
</xs:annotation>
<xs:element name="doctrine-mapping">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="mapped-superclass" type="orm:mapped-superclass" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="entity" type="orm:entity" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="embeddable" type="orm:embeddable" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:element>
<xs:complexType name="emptyType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="cascade-type">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cascade-all" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-persist" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-merge" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-remove" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-refresh" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-detach" type="orm:emptyType" minOccurs="0"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="lifecycle-callback-type">
<xs:restriction base="xs:token">
<xs:enumeration value="prePersist"/>
<xs:enumeration value="postPersist"/>
<xs:enumeration value="preUpdate"/>
<xs:enumeration value="postUpdate"/>
<xs:enumeration value="preRemove"/>
<xs:enumeration value="postRemove"/>
<xs:enumeration value="postLoad"/>
<xs:enumeration value="preFlush"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cache-usage-type">
<xs:restriction base="xs:token">
<xs:enumeration value="READ_ONLY"/>
<xs:enumeration value="READ_WRITE"/>
<xs:enumeration value="NONSTRICT_READ_WRITE"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="lifecycle-callback">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:lifecycle-callback-type" use="required" />
<xs:attribute name="method" type="xs:NMTOKEN" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="lifecycle-callbacks">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-query">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="query" type="xs:string" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-queries">
<xs:sequence>
<xs:element name="named-query" type="orm:named-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="named-native-query">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="query" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="result-class" type="orm:fqcn" />
<xs:attribute name="result-set-mapping" type="xs:string" />
</xs:complexType>
<xs:complexType name="named-native-queries">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="named-native-query" type="orm:named-native-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="entity-listener">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn"/>
</xs:complexType>
<xs:complexType name="entity-listeners">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-listener" type="orm:entity-listener" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="column-result">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="field-result">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="column" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity-result">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field-result" type="orm:field-result" minOccurs="0" maxOccurs="unbounded" />
</xs:choice>
<xs:attribute name="entity-class" type="orm:fqcn" use="required" />
<xs:attribute name="discriminator-column" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="sql-result-set-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-result" type="orm:entity-result"/>
<xs:element name="column-result" type="orm:column-result"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="sql-result-set-mappings">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="cache">
<xs:attribute name="usage" type="orm:cache-usage-type" />
<xs:attribute name="region" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:element name="indexes" type="orm:indexes" minOccurs="0"/>
<xs:element name="unique-constraints" type="orm:unique-constraints" minOccurs="0"/>
<xs:element name="discriminator-column" type="orm:discriminator-column" minOccurs="0"/>
<xs:element name="discriminator-map" type="orm:discriminator-map" minOccurs="0"/>
<xs:element name="lifecycle-callbacks" type="orm:lifecycle-callbacks" minOccurs="0" maxOccurs="1" />
<xs:element name="entity-listeners" type="orm:entity-listeners" minOccurs="0" maxOccurs="1" />
<xs:element name="named-queries" type="orm:named-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="named-native-queries" type="orm:named-native-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="sql-result-set-mappings" type="orm:sql-result-set-mappings" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="id" type="orm:id" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="field" type="orm:field" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="embedded" type="orm:embedded" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-one" type="orm:one-to-one" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-many" type="orm:one-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-one" type="orm:many-to-one" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-many" type="orm:many-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="association-overrides" type="orm:association-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="attribute-overrides" type="orm:attribute-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="table" type="orm:tablename" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:attribute name="repository-class" type="orm:fqcn"/>
<xs:attribute name="inheritance-type" type="orm:inheritance-type"/>
<xs:attribute name="change-tracking-policy" type="orm:change-tracking-policy" />
<xs:attribute name="read-only" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="tablename" id="tablename">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff.]+" id="tablename.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="option" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="options">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="mapped-superclass" >
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="embeddable">
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="change-tracking-policy">
<xs:restriction base="xs:token">
<xs:enumeration value="DEFERRED_IMPLICIT"/>
<xs:enumeration value="DEFERRED_EXPLICIT"/>
<xs:enumeration value="NOTIFY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="inheritance-type">
<xs:restriction base="xs:token">
<xs:enumeration value="SINGLE_TABLE"/>
<xs:enumeration value="JOINED"/>
<xs:enumeration value="TABLE_PER_CLASS"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generator-strategy">
<xs:restriction base="xs:token">
<xs:enumeration value="NONE"/>
<xs:enumeration value="SEQUENCE"/>
<xs:enumeration value="IDENTITY"/>
<xs:enumeration value="AUTO"/>
<xs:enumeration value="UUID"/>
<xs:enumeration value="CUSTOM" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fk-action">
<xs:restriction base="xs:token">
<xs:enumeration value="CASCADE"/>
<xs:enumeration value="RESTRICT"/>
<xs:enumeration value="SET NULL"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fetch-type">
<xs:restriction base="xs:token">
<xs:enumeration value="EAGER"/>
<xs:enumeration value="LAZY"/>
<xs:enumeration value="EXTRA_LAZY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generated-type">
<xs:restriction base="xs:token">
<xs:enumeration value="NEVER"/>
<xs:enumeration value="INSERT"/>
<xs:enumeration value="ALWAYS"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updatable" type="xs:boolean" default="true" />
<xs:attribute name="generated" type="orm:generated-type" default="NEVER" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="embedded">
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="optional" />
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
</xs:complexType>
<xs:complexType name="discriminator-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="xs:NMTOKEN"/>
<xs:attribute name="field-name" type="xs:NMTOKEN" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraint">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraints">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="unique-constraint" type="orm:unique-constraint" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="index">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:attribute name="flags" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="indexes">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="index" type="orm:index" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="value" type="orm:type" use="required"/>
<xs:attribute name="class" type="orm:fqcn" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-map">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="discriminator-mapping" type="orm:discriminator-mapping" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="strategy" type="orm:generator-strategy" use="optional" default="AUTO" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="id">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="generator" type="orm:generator" minOccurs="0" />
<xs:element name="sequence-generator" type="orm:sequence-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="custom-id-generator" type="orm:custom-id-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="association-key" type="xs:boolean" default="false" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="sequence-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="sequence-name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="allocation-size" type="xs:integer" use="optional" default="1" />
<xs:attribute name="initial-value" type="xs:integer" use="optional" default="1" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="custom-id-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn" use="required" />
</xs:complexType>
<xs:simpleType name="fqcn" id="fqcn">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+" id="fqcn.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="type" id="type">
<xs:restriction base="xs:token">
<xs:pattern value="([a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+)|(\c+)" id="type.class.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="inverse-join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional" />
<xs:attribute name="referenced-column-name" type="xs:NMTOKEN" use="optional" default="id" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="true" />
<xs:attribute name="on-delete" type="orm:fk-action" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-table">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-columns" type="orm:join-columns" />
<xs:element name="inverse-join-columns" type="orm:join-columns" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="order-by-field" type="orm:order-by-field" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="direction" type="orm:order-by-direction" default="ASC" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="order-by-direction">
<xs:restriction base="xs:token">
<xs:enumeration value="ASC"/>
<xs:enumeration value="DESC"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="columntoken" id="columntoken">
<xs:restriction base="xs:token">
<xs:pattern value="[-._:A-Za-z0-9`]+" id="columntoken.pattern"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="many-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" use="required" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="many-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="association-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="association-override" type="orm:association-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="association-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="join-columns" type="orm:join-columns" minOccurs="0" />
<xs:element name="inversed-by" type="orm:inversed-by-override" minOccurs="0" maxOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="fetch" type="orm:fetch-type" use="optional" />
</xs:complexType>
<xs:complexType name="inversed-by-override">
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="attribute-override" type="orm:attribute-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="attribute-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field" type="orm:attribute-override-field" minOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-override-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updateable" type="xs:boolean" default="true" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:schema>
+9 -1
Переглянути файл
@@ -182,9 +182,10 @@ impl StreamTracer for JdtStreamTracer {
thread_id: i64,
plan: &'a Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId> {
Box::pin(async move {
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget});
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget, "token": token});
Ok(self.call::<Armed>("arm", target, args, COMMAND_TIMEOUT).await?.trace_id)
})
}
@@ -223,6 +224,13 @@ impl StreamTracer for JdtStreamTracer {
self.call::<Value>("release", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await.map(drop)
})
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()> {
Box::pin(async move {
// Waits for an arm still setting up: as long as an arm may take.
self.call::<Value>("release", target, json!({"token": token}), COMMAND_TIMEOUT).await.map(drop)
})
}
}
#[cfg(test)]
+4
Переглянути файл
@@ -40,6 +40,7 @@ mod uri;
mod virtual_doc;
mod vue_navigation;
mod vue_refs;
mod xml_catalog;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
@@ -3795,6 +3796,9 @@ impl LspManager {
if cfg.name == compose::SERVER {
compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files());
}
if cfg.name == xml_catalog::SERVER {
xml_catalog::configure_lemminx_catalogs(&mut cfg);
}
cfg
}
+149
Переглянути файл
@@ -0,0 +1,149 @@
//! Bundled XML catalogs for LemMinX so known-broken remote XSDs resolve locally.
//!
//! Doctrine's hosted `doctrine-mapping.xsd` advertises the wrong `targetNamespace`
//! (the schema URL itself) after an http→https rewrite, so any mapping file that
//! points `xsi:schemaLocation` at that URL fails with `TargetNamespace.1` /
//! `cvc-elt.1.a`. An OASIS catalog maps the namespace and those system IDs to the
//! correct upstream schema we ship.
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const SERVER: &str = "lemminx";
const DOCTRINE_XSD: &str = include_str!("../schemas/xml/doctrine-mapping.xsd");
const CATALOG_TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://doctrine-project.org/schemas/orm/doctrine-mapping" uri="doctrine-mapping.xsd"/>
<uri name="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
</catalog>
"#;
/// Writes the bundled catalog (idempotent) and prepends it to LemMinX `xml.catalogs`.
pub fn configure_lemminx_catalogs(cfg: &mut LanguageServerConfig) {
if cfg.name != SERVER {
return;
}
let Some(catalog) = ensure_catalog() else { return };
let catalog = path_for_settings(&catalog);
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
let Some(root) = settings.as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(xml) = root.entry("xml").or_insert_with(|| json!({})).as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(catalogs) = xml.entry("catalogs").or_insert_with(|| json!([])).as_array_mut() else {
cfg.settings = Some(settings);
return;
};
if catalogs.iter().any(|v| v.as_str() == Some(catalog.as_str())) {
cfg.settings = Some(settings);
return;
}
catalogs.insert(0, Value::String(catalog));
cfg.settings = Some(settings);
}
fn ensure_catalog() -> Option<PathBuf> {
// Per-pid directory: shared `/tmp/openidea-xml-catalog` would let another
// local user plant a catalog that remaps arbitrary schema URIs.
let dir = std::env::temp_dir().join(format!("openidea-xml-catalog-{}", std::process::id()));
if let Err(e) = ide_vfs::create_private_dir(&dir) {
tracing::warn!("xml catalog: cannot create {}: {e}", dir.display());
return None;
}
let xsd = dir.join("doctrine-mapping.xsd");
if !write_if_changed(&xsd, DOCTRINE_XSD.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", xsd.display());
return None;
}
let catalog = dir.join("catalog.xml");
if !write_if_changed(&catalog, CATALOG_TEMPLATE.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", catalog.display());
return None;
}
Some(catalog)
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> bool {
if std::fs::read(path).ok().as_deref() == Some(bytes) {
return true;
}
ide_vfs::write_atomic_private(path, bytes).is_ok()
}
fn path_for_settings(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use ide_language::LanguageRegistry;
const DOCTRINE_NS: &str = "http://doctrine-project.org/schemas/orm/doctrine-mapping";
const DOCTRINE_SCHEMA_HTTPS: &str = "https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
const DOCTRINE_SCHEMA_HTTP: &str = "http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
#[test]
fn bundled_xsd_keeps_http_namespace() {
assert!(DOCTRINE_XSD.contains(&format!("targetNamespace=\"{DOCTRINE_NS}\"")));
assert!(!DOCTRINE_XSD.contains("xmlns:xs=\"https://www.w3.org/2001/XMLSchema\""));
assert!(!DOCTRINE_XSD.contains("targetNamespace=\"https://www.doctrine-project.org"));
}
#[test]
fn catalog_maps_namespace_and_system_ids() {
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTP}""#)));
assert_eq!(CATALOG_TEMPLATE.matches(r#"uri="doctrine-mapping.xsd""#).count(), 4);
}
#[test]
fn prepends_catalog_without_dropping_user_entries() {
let reg = LanguageRegistry::load(None).unwrap();
let xml = reg.get(&ide_core::LanguageId::new("xml")).unwrap();
let mut cfg = xml.language_servers[0].clone();
cfg.settings = Some(json!({"xml": {"catalogs": ["/user/catalog.xml"]}}));
configure_lemminx_catalogs(&mut cfg);
let list: Vec<String> = cfg.settings.as_ref().unwrap()["xml"]["catalogs"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
assert_eq!(list.len(), 2);
assert!(list[0].ends_with("catalog.xml"));
assert!(list[0].contains(&format!("openidea-xml-catalog-{}", std::process::id())));
assert_eq!(list[1], "/user/catalog.xml");
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings.as_ref().unwrap()["xml"]["catalogs"].as_array().unwrap().len(), 2);
let catalog = PathBuf::from(&list[0]);
let body = std::fs::read_to_string(&catalog).unwrap();
assert_eq!(body, CATALOG_TEMPLATE);
assert!(body.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
let xsd = catalog.with_file_name("doctrine-mapping.xsd");
assert_eq!(std::fs::read_to_string(xsd).unwrap(), DOCTRINE_XSD);
}
#[test]
fn ignores_other_servers() {
let reg = LanguageRegistry::load(None).unwrap();
let yaml = reg.get(&ide_core::LanguageId::new("yaml")).unwrap();
let mut cfg = yaml.language_servers[0].clone();
let before = cfg.settings.clone();
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings, before);
}
}
+9 -3
Переглянути файл
@@ -3193,7 +3193,7 @@ async fn stream_commands_send_target_then_named_fields() {
let plan = json!({"root": {"line": 14}});
s.respond("workspace/executeCommand", json!({"ok": {"traceId": 3}}));
assert_eq!(tracer.arm(&target, 7, &plan, 500).await.unwrap(), 3);
assert_eq!(tracer.arm(&target, 7, &plan, 500, "t1").await.unwrap(), 3);
s.respond(
"workspace/executeCommand",
json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}),
@@ -3211,18 +3211,24 @@ async fn stream_commands_send_target_then_named_fields() {
tracer.collect(&target, 3, 2).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release(&target, 3).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release_armed(&target, "t1").await.unwrap();
let asked = s.requested("workspace/executeCommand");
let seen: Vec<_> = asked.iter().map(|p| (p["command"].clone(), p["arguments"].clone())).collect();
assert_eq!(
seen,
vec![
(json!("openidea.jvm.stream.arm"), json!([target_json, {"threadId": 7, "plan": plan, "budget": 500}])),
(
json!("openidea.jvm.stream.arm"),
json!([target_json, {"threadId": 7, "plan": plan, "budget": 500, "token": "t1"}])
),
(json!("openidea.jvm.stream.wait"), json!([target_json, {"traceId": 3, "ms": 250}])),
(json!("openidea.jvm.stream.stop"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.abort"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.collect"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"token": "t1"}])),
]
);
}
@@ -3303,7 +3309,7 @@ async fn stream_errors_map() {
];
for (reply, expected) in cases {
s.respond("workspace/executeCommand", reply.clone());
assert_eq!(tracer.arm(&target, 1, &json!({}), 10).await.unwrap_err(), expected, "{reply}");
assert_eq!(tracer.arm(&target, 1, &json!({}), 10, "t").await.unwrap_err(), expected, "{reply}");
}
}
+57 -9
Переглянути файл
@@ -23,7 +23,7 @@
<script>
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
// in its highlight colour; the visible area as a frame that can be dragged; the wheel
// scrolls the editor.
// scrolls the editor; the marker bar's problems as bars at the right edge; folded lines left out.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -33,6 +33,10 @@
let colors = new Map();
let loading = new Set();
let view = null;
let problems = [];
let folds = [];
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
let queued = false;
@@ -42,17 +46,39 @@
};
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
const rowOf = (line) => {
let hidden = 0;
for (const f of folds) {
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
else break;
}
return line - hidden;
};
const lineOfRow = (row) => {
let hidden = 0;
for (const f of folds) {
const r = f.fromLine - hidden;
if (row >= r + 1) hidden += f.toLine - f.fromLine;
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
else break;
}
return row + hidden;
};
function layout() {
const H = canvas.clientHeight;
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
const L = Math.max(1, view.lineCount);
const visible = Math.max(0, view.lastLine - view.firstLine);
const L = Math.max(1, rowOf(view.lineCount));
const firstRow = rowOf(view.firstLine);
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
const mapH = L * LINE;
const offset = p * Math.max(0, mapH - H);
const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
}
function redraw() {
@@ -65,7 +91,7 @@
queued = false;
const dpr = window.devicePixelRatio || 1;
const W = canvas.clientWidth;
const { H, offset, top, height } = layout();
const { H, offset, top, height, L } = layout();
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
@@ -74,11 +100,12 @@
ctx.clearRect(0, 0, W, H);
if (!view) return;
const first = Math.floor(offset / LINE);
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
const last = Math.min(L, Math.ceil((offset + H) / LINE));
const missing = [];
const muted = cssVar("--openidea-fg-muted");
for (let i = first; i < last; i++) {
const y = i * LINE - offset;
for (let row = first; row < last; row++) {
const i = lineOfRow(row);
const y = row * LINE - offset;
const line = text[i] || "";
// Text without a syntax colour: faint, so the coloured spans stand out.
ctx.globalAlpha = 0.2;
@@ -95,6 +122,13 @@
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
}
}
// Problems: errors drawn last, on top; weak warnings in the muted colour.
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
const y = Math.floor(rowOf(p.line));
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
}
// The visible area: a light accent tint and a 1px border, stronger while dragged.
const frameH = Math.max(height, 4);
ctx.fillStyle = cssVar("--openidea-accent");
@@ -134,6 +168,9 @@
}
const doc = await editor.document.get();
text = doc.text.split("\n");
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -151,6 +188,17 @@
for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k);
redraw();
});
if (editor.onProblems)
editor.onProblems((p) => {
problems = p;
redraw();
});
// `onLayout` is API 1.10.
if (editor.onLayout)
editor.onLayout((l) => {
folds = l.folded;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
@@ -158,7 +206,7 @@
const scrollToFrameTop = (frameTop) => {
const { range, visible, L } = layout();
const p = Math.min(1, Math.max(0, frameTop / range));
void editor.scrollTo(p * Math.max(0, L - visible));
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
};
canvas.addEventListener("pointerdown", (e) => {
if (!view) return;
+10 -4
Переглянути файл
@@ -26,9 +26,13 @@ pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
}}\n"
)
}
@@ -75,8 +79,10 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
}
#[test]
+1 -1
Переглянути файл
@@ -116,7 +116,7 @@ fn is_python_name(name: &str) -> bool {
/// Prefixes named by `conda env list`: `base * /opt/conda`, `myenv /opt/conda/envs/myenv`,
/// a `--prefix` env shown as a bare path, comment lines skipped (#2240).
fn conda_env_list_prefixes(output: &str) -> Vec<PathBuf> {
pub(crate) fn conda_env_list_prefixes(output: &str) -> Vec<PathBuf> {
output
.lines()
.map(|l| l.trim_start_matches(['#', '*', ' ']).trim_end())
+27 -1
Переглянути файл
@@ -53,6 +53,12 @@ struct JavaProbe {
static JAVA_PROBES: Mutex<BTreeMap<PathBuf, JavaProbe>> = Mutex::new(BTreeMap::new());
/// How long `java -version` may take before the JDK counts as unable to run. The first
/// run of a JDK can be slow: Rosetta translates an x86_64 JDK on Apple silicon, and
/// malware scans check a freshly downloaded one. Excluded, a project's JDK 8 leaves its
/// `JavaSE-1.8` to a newer JDK, and APIs JDK 8 has (`jdk.nashorn`) stop resolving.
const JAVA_PROBE_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(8) } else { Duration::from_secs(30) };
/// Metadata can describe a JDK built for another architecture. Probe the executable
/// before giving it to JDT, with a short cache shared by server and project selection.
pub(crate) fn java_runs(java: &Path) -> bool {
@@ -72,7 +78,7 @@ pub(crate) fn java_runs(java: &Path) -> bool {
return probe.runnable;
}
}
let runnable = crate::exec::query(java, &["-version"], Duration::from_secs(5)).is_some();
let runnable = crate::exec::query(java, &["-version"], JAVA_PROBE_TIMEOUT).is_some();
JAVA_PROBES.lock().unwrap_or_else(|e| e.into_inner()).insert(
java.to_path_buf(),
JavaProbe { modified, len: metadata.len(), permissions: metadata.permissions(), at: Instant::now(), runnable },
@@ -980,6 +986,26 @@ mod tests {
assert_eq!(std::fs::read_to_string(&probes).unwrap().lines().count(), 1, "probed once");
}
#[cfg(unix)]
#[test]
fn a_jdk_8_slow_on_its_first_run_stays_the_java_8_runtime() {
let tmp = tempfile::tempdir().unwrap();
let jdk8 = test_jdk(tmp.path(), 8, "rosetta8");
let jdk25 = test_jdk(tmp.path(), 25, "native25");
// Longer than the 5 seconds a first run under Rosetta used to be allowed.
std::fs::write(
java_executable(&jdk8.home),
"#!/bin/sh
/bin/sleep 6
echo 'openjdk version 1.8'
",
)
.unwrap();
let rt = runtimes(&[jdk8.clone(), jdk25.clone()]);
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": jdk8.home }));
assert_eq!(rt[1]["name"], "JavaSE-25");
}
#[cfg(unix)]
#[test]
fn slow_java_probe_does_not_hold_the_cache_lock() {
+52 -17
Переглянути файл
@@ -26,7 +26,7 @@ pub enum VenvTool {
Uv,
/// `poetry env use <base>` in the project, then `poetry env info --path`.
Poetry,
/// `conda create -p <location> -y` (conda must be on PATH).
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH).
Conda,
}
@@ -121,7 +121,8 @@ fn create_poetry_env(
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// `conda create -p <location> -y` builds an environment at the requested prefix.
/// `conda create -n <name> -y` builds a named environment in conda's envs directory when
/// `location` is a bare name, `conda create -p <location> -y` one at that prefix otherwise.
/// `base` pins the Python version (`python=<major.minor>`) when it reports one, so the
/// created env matches the interpreter the user picked rather than conda's default.
fn create_conda_env(
@@ -131,7 +132,9 @@ fn create_conda_env(
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
if location.join("conda-meta").is_dir() {
// A bare name is a named environment in conda's own envs directory (`conda create -n`).
let name = conda_env_name(location);
if name.is_none() && location.join("conda-meta").is_dir() {
return Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!("{} already contains a conda environment", location.display()),
@@ -139,28 +142,60 @@ fn create_conda_env(
}
let conda = which("conda")
.ok_or_else(|| IdeError::unavailable("conda is not installed (install it from https://docs.conda.io)"))?;
if let Some(parent) = location.parent() {
let prefixes = || {
query_in(&conda, &["env", "list"], None, &[], Duration::from_secs(15))
.map(|list| crate::discover::conda_env_list_prefixes(&list))
.unwrap_or_default()
};
if let Some(name) = name {
if prefixes().iter().any(|p| p.file_name().is_some_and(|n| n == name)) {
return Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!("A conda environment named {name} already exists"),
));
}
} else if let Some(parent) = location.parent() {
std::fs::create_dir_all(parent)?;
}
let mut args = vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned(), "-y".to_owned()];
if let Some(version) = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned))
{
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
if !short.is_empty() {
args.push(format!("python={short}"));
}
}
stream(&conda, &args, None, &[], cancel, on_line)?;
let version = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
stream(&conda, &conda_create_args(location, version.as_deref()), None, &[], cancel, on_line)?;
let prefix = match name {
Some(name) => prefixes()
.into_iter()
.find(|p| p.file_name().is_some_and(|n| n == name))
.ok_or_else(|| IdeError::internal(format!("conda did not report the environment {name}")))?,
None => location.to_path_buf(),
};
// Conda keeps `python.exe` at the prefix root on Windows, not under Scripts/.
let python = [location.join(exe("python")), location.join(bin_dir()).join(exe("python"))]
let python = [prefix.join(exe("python")), prefix.join(bin_dir()).join(exe("python"))]
.into_iter()
.find(|p| p.is_file())
.unwrap_or_else(|| location.join(bin_dir()).join(exe("python")));
crate::discover::python_sdk(&python, "conda", location.parent().and_then(Path::parent))
.unwrap_or_else(|| prefix.join(bin_dir()).join(exe("python")));
crate::discover::python_sdk(&python, "conda", prefix.parent().and_then(Path::parent))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// The environment name when `location` is a bare name rather than a path.
fn conda_env_name(location: &Path) -> Option<&str> {
let text = location.to_str()?;
(!text.is_empty() && !text.contains(['/', '\\', ':']) && text != "." && text != "..").then_some(text)
}
/// `conda create -n <name>` for a bare name, `-p <prefix>` for a path, with the base's `major.minor` Python.
pub(crate) fn conda_create_args(location: &Path, version: Option<&str>) -> Vec<String> {
let mut args = match conda_env_name(location) {
Some(name) => vec!["create".to_owned(), "-n".to_owned(), name.to_owned()],
None => vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned()],
};
args.push("-y".to_owned());
let short = version.map(|v| v.split('.').take(2).collect::<Vec<_>>().join(".")).unwrap_or_default();
if !short.is_empty() {
args.push(format!("python={short}"));
}
args
}
/// Arguments of `base -m venv location`. `-I` (isolated mode) keeps the working
/// directory off `sys.path`: a project's `logging.py` or `typing.py` there would
/// otherwise shadow the standard library modules venv imports. (`-P` does just
+53
Переглянути файл
@@ -1319,6 +1319,59 @@ fn an_existing_conda_environment_is_not_recreated() {
assert!(err.message.contains("already contains a conda environment"), "{}", err.message);
}
#[test]
fn conda_creates_named_environments_in_its_envs_directory() {
use crate::python::conda_create_args;
use std::path::Path;
assert_eq!(conda_create_args(Path::new("demo"), Some("3.12.4")), ["create", "-n", "demo", "-y", "python=3.12"]);
assert_eq!(conda_create_args(Path::new("/work/app/.conda"), None), ["create", "-p", "/work/app/.conda", "-y"]);
for path in [r"C:\envs\demo", "envs/demo", "D:demo", ".."] {
assert_eq!(conda_create_args(Path::new(path), None)[1], "-p", "{path}");
}
}
#[test]
#[cfg(unix)]
fn a_named_conda_environment_is_found_where_conda_put_it() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("miniconda3");
let conda = tmp.path().join("conda");
// `create -n <name>` makes <root>/envs/<name> with a copy of the base python; `env list` names every env.
let python = tmp.path().join("python");
std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap();
std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(
&conda,
format!(
"#!/bin/sh\nroot='{root}'\nif [ \"$1\" = env ]; then echo '# conda environments:'; echo \"base $root\"; \
for e in \"$root\"/envs/*/; do [ -d \"$e\" ] && echo \"$(basename \"$e\") ${{e%/}}\"; done; exit 0; fi\n\
[ \"$1 $2\" = 'create -n' ] || exit 2\nmkdir -p \"$root/envs/$3/bin\"\ncp '{python}' \"$root/envs/$3/bin/python\"\necho created\n",
root = root.display(),
python = python.display()
),
)
.unwrap();
std::fs::set_permissions(&conda, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::create_dir_all(&root).unwrap();
let base = python.clone();
let which = |tool: &str| (tool == "conda").then(|| conda.clone());
let create = || {
crate::python::create_venv_with(
crate::python::VenvTool::Conda,
&base,
Path::new("ds"),
which,
&Default::default(),
&|_| {},
)
};
let sdk = create().unwrap();
assert_eq!(&*sdk.path, root.join("envs/ds/bin/python").as_path());
let again = create().unwrap_err();
assert!(again.message.contains("named ds already exists"), "{}", again.message);
}
#[test]
fn neutral_dir_is_fresh_and_empty() {
let a = crate::python::neutral_dir().unwrap();
+13 -2
Переглянути файл
@@ -24,6 +24,8 @@ pub use words::{MIN_WORD_CHARS, WordSpan, words};
pub enum RegionKind {
Comment,
String,
/// A raw / verbatim string: `\` is literal text, not an escape (`r"\user"`).
RawString,
/// A declared identifier (`camelCase` / `snake_case` split).
Name,
/// Plain text / Markdown prose.
@@ -53,7 +55,7 @@ impl From<RegionKind> for TypoContext {
fn from(kind: RegionKind) -> Self {
match kind {
RegionKind::Name => Self::Code,
RegionKind::String => Self::Literal,
RegionKind::String | RegionKind::RawString => Self::Literal,
RegionKind::Comment => Self::Comment,
RegionKind::Prose => Self::Prose,
}
@@ -89,7 +91,7 @@ impl SpellScope {
pub fn includes(&self, kind: RegionKind) -> bool {
match kind {
RegionKind::Name => self.code,
RegionKind::String => self.literals,
RegionKind::String | RegionKind::RawString => self.literals,
RegionKind::Comment => self.comments,
RegionKind::Prose => true,
}
@@ -678,6 +680,15 @@ mod tests {
assert_eq!(found, [("mesage", TypoContext::Code)]);
}
#[test]
fn raw_strings_do_not_lose_the_letter_after_a_backslash() {
let s = Speller::default();
let text = r#"r"\user \mesage""#;
let regions = [Region { start: 0, end: text.len(), kind: RegionKind::RawString }];
let typos = s.check(text, &regions, &|| false).unwrap();
assert_eq!(typos.iter().map(|t| t.word.as_str()).collect::<Vec<_>>(), ["mesage"]);
}
#[test]
fn scope_filters_region_kinds() {
let comments_only = SpellScope { code: false, literals: false, comments: true };
+12 -1
Переглянути файл
@@ -18,7 +18,7 @@ pub struct WordSpan {
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
let Some(slice) = text.get(start..end) else { return };
let escapes = match kind {
RegionKind::Name => Escapes::None,
RegionKind::Name | RegionKind::RawString => Escapes::None,
RegionKind::String => Escapes::Char,
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
};
@@ -186,6 +186,17 @@ mod tests {
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
}
#[test]
fn raw_strings_keep_the_letter_after_a_backslash() {
// `\u` in a normal string is an escape: the letter is consumed and only
// `ser` is prose. In a raw string the backslash is literal, so `user`
// must be checked whole (issue: r"\user" flagged as typo 'ser').
assert_eq!(split(r#""\user""#, RegionKind::String), ["ser"]);
assert_eq!(split(r#""\user""#, RegionKind::RawString), ["user"]);
assert_eq!(split(r"\n\t \wrd", RegionKind::RawString), ["wrd"]);
assert_eq!(split(r"C:\Users\mesage", RegionKind::RawString), ["Users", "mesage"]);
}
#[test]
fn skips_backslash_commands_in_comments() {
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
+6 -4
Переглянути файл
@@ -332,9 +332,10 @@ impl<'t> Finder<'_, 't> {
/// Subtrees where calls that exit before the root can be: the statement holding
/// the chain, or, for a chain in a compound statement's header, that statement.
/// For an `else if` also the conditions of the `if`s before it, which all ran;
/// their branch bodies did not, since the later condition is only reached when
/// they were skipped.
/// For an `else if` also the conditions of the `if`s before it that start on the
/// line the trace starts from (`} else if` on a line of its own stops after they
/// ran); their branch bodies never count, since the later condition is only
/// reached when they were skipped.
fn skip_regions(&self, anchor: Node<'t>, scope: Node<'t>) -> Vec<Node<'t>> {
let is_statement = |n: Node| n.kind().ends_with("_statement") || n.kind() == "switch_expression";
if anchor.kind() != "method_invocation" {
@@ -344,12 +345,13 @@ impl<'t> Finder<'_, 't> {
.take_while(|n| *n != scope)
.find(|n| is_statement(*n))
.unwrap_or(anchor);
let stop_row = anchor.start_position().row;
let mut regions = vec![region];
while let Some(outer) = region
.parent()
.filter(|p| p.kind() == "if_statement" && p.child_by_field_name("alternative") == Some(region))
{
regions.extend(outer.child_by_field_name("condition"));
regions.extend(outer.child_by_field_name("condition").filter(|c| c.start_position().row >= stop_row));
region = outer;
}
regions
+1
Переглянути файл
@@ -125,6 +125,7 @@ public class Chains {
} else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF_BODY
base--;
}
if (names.stream().anyMatch(x -> x.isEmpty())) base++; else if (list.stream().noneMatch(x -> x.isEmpty())) base--; // C_PLAN_ELSE_IF_ONE_LINE
List<String> out = nums.stream() // C_PLAN_FIRST_LINE
.filter(x -> x > 0)
.map(x -> x * 2)
+10 -2
Переглянути файл
@@ -172,9 +172,17 @@ fn root_skip_counts_sibling_chain_in_if_header() {
}
#[test]
fn root_skip_counts_earlier_condition_of_else_if() {
fn root_skip_leaves_out_an_earlier_condition_that_ran_before_the_stop() {
// Stopped on the `} else if` line, the first condition has already returned.
let root = plan_of("C_PLAN_ELSE_IF").root.unwrap();
assert_eq!(root, spec("stream", 0, 1));
assert_eq!(root, spec("stream", 0, 0));
}
#[test]
fn root_skip_counts_an_earlier_condition_on_the_same_line() {
let chains = chains_at("C_PLAN_ELSE_IF_ONE_LINE");
let later = chains.iter().find(|c| c.terminal.name == "noneMatch").expect("else-if chain");
assert_eq!(real_run_plan(later).unwrap().root, Some(spec("stream", 0, 1)));
}
#[test]
+55 -1
Переглянути файл
@@ -13,6 +13,10 @@ pub struct RecentProject {
/// Git branch shown on the welcome screen. Persisted as of last open; [`RecentProjects::list_live`]
/// refreshes it from `.git/HEAD` when the list is shown.
pub branch: Option<String>,
/// The local folder no longer exists (set by [`with_live_branches`] when the list is shown): the
/// welcome screen shows the entry as unavailable.
#[serde(default)]
pub missing: bool,
}
pub const MAX_RECENT_PROJECTS: usize = 30;
@@ -139,11 +143,25 @@ pub fn with_live_branches(mut items: Vec<RecentProject>) -> Vec<RecentProject> {
for item in &mut items {
if let Ok(branch) = read_head_branch(item.path.as_ref()) {
item.branch = branch;
} else if is_missing(item.path.as_ref()) {
// A deleted repository has no branch to show.
item.missing = true;
item.branch = None;
}
}
items
}
/// A local project folder that is gone. Remote locations (`ssh://`, `wsl://`, `devcontainer://`)
/// and WSL shares, which a stopped distribution only hides, never count as missing.
fn is_missing(path: &Path) -> bool {
let text = path.to_string_lossy();
// Stored paths may use `/` (`//wsl.localhost/Ubuntu/...`); host names ignore case.
let unc = text.replace('/', r"\").to_ascii_lowercase();
let wsl = unc.starts_with(r"\\wsl$") || unc.starts_with(r"\\wsl.localhost");
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -192,7 +210,7 @@ impl RecentProjects {
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch });
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
cap(&mut items, &self.groups.lock());
self.persist(&items)
}
@@ -242,6 +260,15 @@ impl RecentProjects {
mod tests {
use super::*;
#[test]
fn wsl_shares_stored_with_forward_slashes_are_never_missing() {
for path in
[r"\\wsl.localhost\Ubuntu\home\me\gone", "//wsl.localhost/Ubuntu/home/me/gone", "//WSL$/Ubuntu/gone"]
{
assert!(!is_missing(Path::new(path)), "{path}");
}
}
#[test]
fn newest_first_capped_and_persisted() {
let tmp = tempfile::tempdir().unwrap();
@@ -341,6 +368,33 @@ mod tests {
assert_eq!(recent.list().iter().find(|i| i.path.as_ref() == repo).unwrap().branch.as_deref(), Some("stale"));
}
#[test]
fn list_live_marks_deleted_folders_missing_without_their_branch() {
let tmp = tempfile::tempdir().unwrap();
let gone = tmp.path().join("removed-worktree");
write_head(&gone.join(".git"), "ref: refs/heads/feature-x\n");
let plain = tmp.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
let recent = RecentProjects::load(tmp.path().join("config").as_path());
recent.touch(&gone, Some("feature-x".into())).unwrap();
recent.touch(&plain, Some("kept".into())).unwrap();
recent.touch(Path::new("ssh://server/home/me/app"), None).unwrap();
std::fs::remove_dir_all(&gone).unwrap();
let live = recent.list_live();
let by_path = |p: &Path| live.iter().find(|i| i.path.as_ref() == p).unwrap();
assert!(by_path(&gone).missing);
assert_eq!(by_path(&gone).branch, None);
assert!(!by_path(&plain).missing);
assert_eq!(by_path(&plain).branch.as_deref(), Some("kept"));
assert!(!by_path(Path::new("ssh://server/home/me/app")).missing, "remote locations are not checked");
// Only the shown list: the saved one keeps the last branch.
let stored = recent.list();
let stored = stored.iter().find(|i| i.path.as_ref() == gone).unwrap();
assert!(!stored.missing);
assert_eq!(stored.branch.as_deref(), Some("feature-x"));
}
#[test]
fn list_live_follows_worktree_gitdir_and_shows_short_detached_head() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add
- **Virtualenv Environment**: `python -m venv` from the base interpreter you pick.
- **uv Environment**: `uv venv <location> --python <base>` (uv must be on `PATH`).
- **Poetry Environment**: `poetry env use <base>` in the project.
- **Conda Environment**: `conda create -p <location>`, with the base interpreter's Python version.
- **Conda Environment**: `conda create -n <name>` in conda's envs directory, with the chosen Python version.
You can also select an existing interpreter or environment folder. The new interpreter becomes the project interpreter.
+18
Переглянути файл
@@ -132,6 +132,24 @@ mac = "Meta+Alt+C" # optional; macOS uses `key` as written when it is mis
the user already uses that keystroke, or when the action already has a binding. The user
can rebind it in **Settings › Keymap**.
### Escape in the editor
API 1.10 lets a command answer a plain <kbd>Escape</kbd> in a focused editor, to clear
something the plugin shows there (a highlight, a mode):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # required; set it with set-context while there is something to clear
```
- It runs only after everything the IDE does with Escape in the editor found nothing to do:
closing a popup, completion or rename, collapsing a selection or extra carets, Vim.
- `when` is required and `key` (and `mac`, if given) must be `Escape`. Escape is the only plain
key a plugin can bind, and `when` is accepted only on such a binding.
- When several plugins' `when` hold, the most recently loaded one runs.
## Menus
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
+1
Переглянути файл
@@ -123,6 +123,7 @@ Settings › Appearance & Behavior › Appearance, unless noted.
| ---------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `fontFamily` / `fontSize` / `lineHeight` | `"JetBrains Mono"` / `13` / `22` | Editor › Font. |
| `ligatures` | `false` | **Enable ligatures**. |
| `onlyMonospacedFonts` | `true` | **Show only monospaced fonts** in the Editor › Font and Terminal font pickers. |
| `fallbackFont` | `""` | **Fallback font**. |
| `fontWeight` / `boldFontWeight` | `400` / `700` | **Main font weight**, **Bold font weight**. |
| `colorScheme` | `"theme-default"` | Editor color scheme; `theme-default` follows the UI theme, otherwise a theme id or an imported scheme. |
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
- **Conda 环境**:执行 `conda create -p <location>`,Python 版本与基础解释器一致。
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
+15
Переглянути файл
@@ -119,6 +119,21 @@ mac = "Meta+Alt+C" # 可选;缺省时 macOS 原样使用 `key`
- 插件快捷键只是默认值,优先级低于 IDE:按键映射预设或用户已经占用该按键、或该动作已有绑定时,
插件的快捷键会被丢弃。用户可以在 **设置 › 按键映射** 中重新绑定。
### 编辑器中的 Escape
API 1.10 起,命令可以响应焦点编辑器中单独按下的 <kbd>Escape</kbd>,用来清除插件在编辑器里显示的内容(高亮、某种模式):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # 必填;有内容可清除时用 set-context 设置
```
- 只有 IDE 在编辑器里对 Escape 的处理都没有生效时才会执行:关闭弹窗、补全或重命名,收起选区或多余的光标,Vim。
- 必须写 `when`,且 `key`(以及给出的 `mac`)必须是 `Escape`。Escape 是插件唯一能绑定的单独按键,`when` 也只用于这种绑定。
- 多个插件的 `when` 同时成立时,执行最后加载的那个插件的命令。
## 菜单
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ optional = ["net:api.openai.com", "secrets"]
| ------------------- | ---------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
+1
Переглянути файл
@@ -123,6 +123,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| ---------------------------------------- | -------------------------------- | ---------------------------------------------------------------------------------- |
| `fontFamily` / `fontSize` / `lineHeight` | `"JetBrains Mono"` / `13` / `22` | 编辑器 › 字体。 |
| `ligatures` | `false` | **启用连字**。 |
| `onlyMonospacedFonts` | `true` | **仅显示等宽字体**(编辑器 › 字体和终端字体的选择列表)。 |
| `fallbackFont` | `""` | **备用字体**。 |
| `fontWeight` / `boldFontWeight` | `400` / `700` | **主字重**、**粗体字重**。 |
| `colorScheme` | `"theme-default"` | 编辑器配色方案;`theme-default` 跟随界面主题,也可以是主题 id 或导入的方案。 |
+58
Переглянути файл
@@ -902,3 +902,61 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
// Output-less running tool rows align their kind icon with expandable tool rows.
expect(layout.iconLeftDiff).toBeLessThanOrEqual(1);
});
test("aligns Mermaid diagrams in replies to their container align attribute", async ({ page }) => {
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await openReply(
page,
[
"Summary across the full width of the reply column so diagrams sit inside a wider message body.",
"",
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
store.openTaskInEditorLocation(id);
}, TASK.id);
const reply = page.locator("[class*='_stream_']:visible [class*='_markdown_']").first();
const outputs = reply.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
+6 -4
Переглянути файл
@@ -70,7 +70,7 @@ async function stubRepositoryAndAgent(page: Page, reply: string) {
operation: null,
});
h.vcs_status = () => changes;
h.vcs_create_patch = () => patch;
h.vcs_pending_patch = () => patch;
h.vcs_log = () => [{ id: "1111111", summary: "Bump the wrapper" }];
h.agent_create = (args) => {
const created = { ...task, id: "new", title: "Write a commit message", status: "starting", updatedMs: 9 };
@@ -131,9 +131,11 @@ test("the agent of the latest task writes the commit message of the included cha
// Only the included file's diff, and the style of the latest commits, go to the agent.
expect(created.prompt.text).toContain("+++ b/build.gradle.kts");
expect(created.prompt.text).toContain("- Bump the wrapper");
expect(await ipcCalls(page, "vcs_create_patch")).toEqual([
expect.objectContaining({ source: { from: "changes", paths: [`${ROOT}/build.gradle.kts`], reverse: false } }),
]);
// What Commit would commit: the included file only (read again before the message is filled in).
const pending = await ipcCalls(page, "vcs_pending_patch");
expect(pending.length).toBeGreaterThan(0);
for (const call of pending)
expect(call).toMatchObject({ options: expect.objectContaining({ stage: [`${ROOT}/build.gradle.kts`] }) });
// The task ran for the message only: it is gone again, and nothing was left to read.
expect(await ipcCalls(page, "agent_delete")).toEqual([expect.objectContaining({ task: "new" })]);
await expect(page.getByRole("alert")).toHaveCount(0);
+54
Переглянути файл
@@ -273,6 +273,60 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await page.keyboard.insertText(
[
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
const outputs = preview.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const column = editor.locator(".cm-gutter.cm-openidea-bookmarks");
Бінарний файл не відображається.
+15 -3
Переглянути файл
@@ -6,6 +6,7 @@ import ai.openidea.jvminspect.JavaDebugSessions.HubEvent;
import ai.openidea.jvminspect.RealRunPlan.StepSpec;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.ArrayReference;
import com.sun.jdi.BooleanValue;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.IncompatibleThreadStateException;
@@ -162,6 +163,8 @@ final class RealRunTrace {
/** Recorder number of the next wrapped op; modifiers take none. */
private int nextStep;
private ObjectReference lastWrapped;
/** Whether the stream was made sequential: the plan asked, or the stream the chain starts from was parallel. */
private volatile boolean sequentialized;
/** {@code forceEarlyReturn} at a method exit makes that frame exit once more, returning the forced value. */
private Method echoMethod;
private Value echoValue;
@@ -240,11 +243,14 @@ final class RealRunTrace {
subscription = hub.subscribe(this::onEvent, e -> errors.add("event listener: " + e));
if (held != null) {
// Not put back: the program consumes the stream right after.
lastWrapped = wrap(held, nextStep++, plan.sequentialize());
// A stream made parallel before this statement shows no `parallel` in the chain.
sequentialized = plan.sequentialize() || isParallel(held);
lastWrapped = wrap(held, nextStep++, sequentialized);
// The invokes resumed the thread, which invalidated the frame read before them.
thread.frame(0).setValue(local, lastWrapped);
} else {
rootSkip = plan.root().skip();
sequentialized = plan.sequentialize();
}
// Last: with these on, an invoke into the thread would raise the trace's own events inside it.
// The step out of the frame never fires inside an invoke, which runs above it.
@@ -402,7 +408,8 @@ final class RealRunTrace {
}
ObjectReference stream = returned(exit, root);
setEnabled(false);
replace(exit, wrap(stream, nextStep++, plan.sequentialize()));
if (!sequentialized && isParallel(stream)) sequentialized = true;
replace(exit, wrap(stream, nextStep++, sequentialized));
return;
}
if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return;
@@ -597,6 +604,11 @@ final class RealRunTrace {
return sequentialize ? invoke(wrapped, "sequential") : wrapped;
}
private boolean isParallel(ObjectReference stream) throws Exception {
Method method = streamMethod(stream.referenceType(), "isParallel", 0);
return stream.invokeMethod(thread, method, List.of(), INVOKE) instanceof BooleanValue b && b.value();
}
private ObjectReference invoke(ObjectReference stream, String name, Value... arguments) throws Exception {
Method method = streamMethod(stream.referenceType(), name, arguments.length);
return keep(RecorderLoader.pin(() -> (ObjectReference) stream.invokeMethod(thread, method, List.of(arguments), INVOKE)));
@@ -1008,7 +1020,7 @@ final class RealRunTrace {
};
int skipped = silencers.stream().mapToInt(Silencer::silencedBreakpoints).sum();
return Values.json("records", records, "dropped", longOf(fields.get(field("dropped"))), "terminal", terminal,
"skippedBreakpoints", skipped, "sequentialized", plan.sequentialize());
"skippedBreakpoints", skipped, "sequentialized", sequentialized);
}
/**
+24 -1
Переглянути файл
@@ -40,6 +40,8 @@ public final class StreamCommand implements IDelegateCommandHandler {
private static final int GONE_KEPT = 16;
private static final AtomicLong IDS = new AtomicLong();
private static final Map<VirtualMachine, RealRunTrace> TRACES = new IdentityHashMap<>();
/** The {@code token} each trace was armed with: a client whose {@code arm} timed out releases by it. */
private static final Map<RealRunTrace, String> TOKENS = new IdentityHashMap<>();
/** By trace id, the answer {@link RealRunTrace#ended} gave: the trace itself would keep its dead VM's mirrors. */
private static final Map<Long, Map<String, Object>> GONE = new LinkedHashMap<>() {
private static final long serialVersionUID = 1L;
@@ -64,6 +66,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
} catch (Failure e) {
Map<String, Object> gone = name.equals("arm") ? null : gone(args);
if (gone == null) throw e;
if (name.equals("release") && args.get("token") instanceof String) return InspectCommand.ok(Map.of());
return InspectCommand.ok(switch (name) {
case "wait" -> gone;
case "release" -> Map.of();
@@ -76,7 +79,9 @@ public final class StreamCommand implements IDelegateCommandHandler {
case "stop" -> Values.json("records", trace(vm, args).stopRecording());
case "abort" -> trace(vm, args).abort();
case "collect" -> collect(vm, target, trace(vm, args));
case "release" -> release(vm, trace(vm, args));
case "release" -> args.get("token") instanceof String token && !(args.get("traceId") instanceof Number)
? releaseArmed(vm, token)
: release(vm, trace(vm, args));
default -> throw new IllegalArgumentException("unknown command " + command);
});
} catch (Failure e) {
@@ -131,6 +136,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
RealRunTrace trace = RealRunTrace.arm(IDS.incrementAndGet(), vm, thread, plan, budget, target.generation(), hub);
synchronized (TRACES) {
TRACES.put(vm, trace);
if (args.get("token") instanceof String token) TOKENS.put(trace, token);
}
return trace.id;
}
@@ -166,11 +172,27 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (!trace.state().wire.equals("running")) {
synchronized (TRACES) {
TRACES.remove(vm, trace);
TOKENS.remove(trace);
}
}
return Map.of();
}
/**
* The trace armed with {@code token}, whose {@code arm} reply the client gave up on: released,
* so its breakpoints come back on. Under the arm lock, so an arm still setting up finishes first.
*/
private static Map<String, Object> releaseArmed(VirtualMachine vm, String token) {
synchronized (InspectCommand.handlesFor(vm)) {
RealRunTrace current;
synchronized (TRACES) {
current = TRACES.get(vm);
if (current == null || !token.equals(TOKENS.get(current))) return Map.of();
}
return release(vm, current);
}
}
/** Releases the traces of VMs java-debug no longer has; their requests and objects went with the VM. */
private static void forgetGone(List<VmInfo> vms) {
Set<VirtualMachine> live = Collections.newSetFromMap(new IdentityHashMap<>());
@@ -182,6 +204,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (live.contains(e.getKey())) continue;
RealRunTrace trace = e.getValue();
trace.vmGone();
TOKENS.remove(trace);
GONE.put(trace.id, trace.ended());
gone.add(trace);
i.remove();
+71
Переглянути файл
@@ -91,6 +91,8 @@ public class Real {
case "H": h(); break;
case "local": local(); break;
case "parallel": parallel(); break;
case "plocal": parallelLocal(); break;
case "elif": elseIf(); break;
case "nested": nested(); break;
case "hostile": hostile(); break;
case "sr": stopRecording(Integer.parseInt(a[1])); break;
@@ -167,6 +169,20 @@ public class Real {
System.out.println("P " + p + " " + q);
}
static void parallelLocal() {
Stream<Integer> s = nums.parallelStream();
List<Integer> r = s.map(x -> x + 1).collect(Collectors.toList()); // @plocal
System.out.println("PL " + r);
}
static void elseIf() {
if (nums.stream().anyMatch(x -> x > 100)) {
System.out.println("ELIF no");
} else if (nums.stream().anyMatch(x -> x == 8)) { // @elif
System.out.println("ELIF yes");
}
}
static void nested() {
long n = nums.stream().flatMap(x -> Stream.of(x, x)).count(); // @nested
System.out.println("NESTED " + n);
@@ -833,6 +849,61 @@ def real_run_parallel():
dbg.end()
@case
def real_run_parallel_local():
dbg = real('plocal')
try:
# No `parallel` in the chain: the stream was made parallel before the statement.
trace, state, _ = run_until_parked(dbg, 'plocal', root=None, local='s', steps=(spec('map', 1),), step_kinds=('sync',),
class_filters=('java.util.stream.*',))
c = step_out_and_collect(dbg, trace)
collected_ok('parallel local', c, records='0=5 1=6 0=3 1=4 0=8 1=9 0=1 1=2 0=4 1=5 0=2 1=3 0=9 1=10 0=6 1=7'.split())
check('parallel local: sequentialized', c['sequentialized'] is True, c['sequentialized'])
resume(dbg)
check('parallel local: program output', output_line(dbg, 'PL ') == 'PL [6, 4, 9, 2, 5, 3, 10, 7]')
finally:
dbg.end()
@case
def real_run_else_if():
dbg = real('elif')
try:
# Stopped on the `else if` line, the first condition's `stream()` has already returned.
trace, state, _ = run_until_parked(dbg, 'elif', steps=(), terminal=spec('anyMatch', 1), step_kinds=(), timeout=20)
check('else if: the trace parks with nothing skipped', state['state'] == 'parked', state)
c = step_out_and_collect(dbg, trace)
collected_ok('else if', c, terminal='true')
resume(dbg)
check('else if: program output', output_line(dbg, 'ELIF ') == 'ELIF yes')
finally:
dbg.end()
@case
def release_by_arm_token():
dbg = launch()
try:
def arm_with(token):
return stream('arm', dbg, threadId=dbg.thread, plan=plan('loop'), budget=50_000, token=token)
ok(arm_with('first'))
check('release by another token leaves the trace', ok(stream('release', dbg, token='other')) == {})
check('so the next arm is busy', error(arm_with('second')) == 'busy')
check('release by the arm\'s token answers {}', ok(stream('release', dbg, token='first')) == {})
trace = ok(arm_with('third'))['traceId']
check('arm works again after it', trace is not None, trace)
ok(stream('release', dbg, traceId=trace))
resume(dbg)
try:
body = expect_stop(dbg, 10, 'stop after release')
check('breakpoints are back after a release by token', body.get('reason') == 'breakpoint', body)
except TimeoutError:
check('breakpoints are back after a release by token', False, 'no stop within 10 s')
finally:
dbg.end()
@case
def real_run_nested():
dbg = real('nested')
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.46",
"version": "0.1.47",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+40 -15
Переглянути файл
@@ -150,7 +150,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` |
@@ -443,6 +443,21 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
`build.dependencies`) returns the Maven / Gradle graph the Dependency Analyzer
has, as a flat list with conflict and omission status, behind the low-risk
`build.read` capability. No build tool runs. See _Build dependency graph_.
- **Escape in the editor.** `[[contributes.keymaps]]` takes `key = "Escape"` with a
required `when`: the command runs on a plain Escape in a focused editor once the
IDE's own Escape handling (popups, completion, rename, selection, extra carets,
Vim) found nothing to do.
- **The marker bar's problems in editor panels.** An editor panel's page reads
the problems its group's marker bar shows with `openidea.editor.problems()`
and hears them change through `onProblems`. See _Editor panels_.
- **Semantic highlighting in editor panels.** `openidea.editor.highlights()`
returns the colours the editor shows, semantic highlighting from the language
server layered over the syntax colours, and `onHighlights` reports the lines
whose colours change when semantic tokens arrive. See _Editor panels_.
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
lines are folded with `openidea.editor.folded()`, how many rows each line takes
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
through `onLayout`. See _Editor panels_.
### API 1.9
@@ -1908,22 +1923,32 @@ sit side by side.
The page gets `openidea.editor` (only an editor panel's page has it). Lines are
0-based, columns UTF-16:
| `openidea.editor` | What it does |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the syntax colour in the current scheme (a CSS colour) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed |
| `openidea.editor` | What it does |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the colour the editor shows in the current scheme (a CSS colour; API 1.10: semantic highlighting included) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
Colours come from syntax highlighting only (no semantic highlighting yet); the
Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
highlighting over it (a semantic colour wins where both apply). The
panel's other colours are the frame's theme variables (`openidea.theme`,
`onThemeChange`). Not there yet: the caret and selections, and the marker bar's
problems and changes. `crates/ide-plugin/tests/fixtures/editor-panel` is a
minimal minimap (each line 2 px, its frame draggable) to install and try.
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped` or
`onLayout`: check for them (`if (editor.problems)`) when the page also runs in
older IDEs. Outside the visible area the editor estimates wrapped rows from the
line's length until it lays the line out; `onLayout` follows when it does. Not
there yet: the caret and selections, and the marker bar's changes.
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
2 px, its frame draggable, problems marked at its right edge, folded lines left out) to install and try.
### Web frame PTYs (API 1.3)
+1 -1
Переглянути файл
@@ -332,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
267 themeable tokens: 125 in the UI theme file, 142 in the editor colour scheme file.
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
### Surfaces (UI theme)
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+2 -1
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
world plugin {
import log;
@@ -20,6 +20,7 @@ world plugin {
import decorations;
import invocation;
import vcs;
import build;
import commit;
import events;
import tasks;
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+10 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -135,6 +135,10 @@ interface views {
}
/// A comparison opened by a content action reply.
record content-diff { left: string, right: string, left-label: option<string>, right-label: option<string>, title: option<string> }
/// A file's before and after for `open-file-diff` (API 1.10): none is a side
/// where the file doesn't exist (an added file has no left side, a deleted
/// one no right side).
record file-diff { left: option<string>, right: option<string>, left-label: option<string>, right-label: option<string>, title: option<string> }
/// Optional updates to an outstanding action or Save request.
record content-tab-reply {
content: option<string>, saved: option<bool>, read-only: option<bool>,
@@ -156,6 +160,11 @@ interface views {
/// of a window. Each side at most 8 MiB (earlier hosts: 1 MiB); a larger
/// side fails with `invalid("diff too large: …")`.
open-diff: func(diff: content-diff, file-name: option<string>) -> result<_, error>;
/// `open-diff` for a file that may not exist on one side (API 1.10): the
/// diff viewer shows the existing side alone, as for the IDE's own added
/// and deleted files, instead of next to an empty text. Both sides none is
/// `invalid`.
open-file-diff: func(diff: file-diff, file-name: option<string>) -> result<_, error>;
/// The view (or every custom editor of that id) shows outdated content:
/// the IDE renders it again.
+63 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
interface workspace {
use types.{error, location};
@@ -227,3 +227,65 @@ interface vcs {
/// Long-running: call it inside a task.
fetch: func(project: borrow<project>) -> result<_, error>;
}
/// The Maven / Gradle dependency graph of a project, as the Dependency Analyzer
/// has it (API 1.10). Read-only: no call runs a build tool.
interface build {
use types.{error};
use workspace.{project};
/// How an occurrence of a dependency was resolved.
enum dependency-status {
/// Part of the resolved graph.
resolved,
/// Another version won (Maven: nearer the root; Gradle: the version the
/// build selected). `version` is the winner, `requested-version` what
/// this occurrence asked for.
omitted-for-conflict,
/// Listed with its dependencies elsewhere in the graph (Maven: a
/// duplicate or a cycle; Gradle: `(*)`); its children are not repeated.
omitted-for-duplicate,
/// The version comes from dependency management (Maven
/// `<dependencyManagement>`, a Gradle platform or constraint);
/// `requested-version` is the one declared here, when there is one.
version-managed,
}
/// One occurrence in the graph. Records don't nest, so the graph is a flat
/// list: `parent` is the index of the occurrence that brings this one in.
/// Each module is a root (`parent` none, empty `scope`) with its direct
/// dependencies under it, so walking `parent` up answers "why is this
/// artifact here".
record dependency-node {
/// Empty for a Gradle project of the build.
group: string,
/// Artifact id; a Gradle project's path (`:core`).
artifact: string,
/// The version in use; empty when there is none (a Gradle project of
/// the build) or it could not be resolved (Gradle `FAILED`).
version: string,
/// Maven scope (`compile`, `test`, …); the Gradle configuration
/// (`runtimeClasspath`, …).
scope: string,
status: dependency-status,
/// What this occurrence asked for, when it differs from `version`.
requested-version: option<string>,
parent: option<u32>,
}
/// The dependency graph of `module` (a Maven module's `groupId:artifactId`
/// or a Gradle project's path, `:` for the root project), or of every
/// module of the project's builds with `none`; an unknown module is
/// `not-found`. Answered from what the IDE already resolved:
///
/// - Maven: the trees of the last Reload in the Maven tool window (with
/// the occurrences Maven omitted); before one, or after a POM changed,
/// only the dependencies the POMs declare.
/// - Gradle: the configurations the Dependency Analyzer has read for the
/// project, until a build file changes; none read yet is the module's
/// own node only.
///
/// At most 100,000 nodes (else `failed`: ask for one module). Trusted
/// projects only; requires `build.read`.
dependencies: func(project: borrow<project>, module: option<string>) -> result<list<dependency-node>, error>;
}
+1
Переглянути файл
@@ -402,6 +402,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_has_hook,
vcs::vcs_merge_base,
vcs::vcs_create_patch,
vcs::vcs_pending_patch,
vcs::vcs_patch_preview,
vcs::vcs_apply_patch,
vcs::vcs_shelve,
+11
Переглянути файл
@@ -803,6 +803,17 @@ pub async fn vcs_create_patch(
ide_host::ops::vcs::vcs_create_patch(&state.host, window.label(), repo, source).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_pending_patch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
options: CommitOptions,
) -> IdeResult<String> {
ide_host::ops::vcs::vcs_pending_patch(&state.host, window.label(), repo, options).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_patch_preview(
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ mod tests {
use ide_core::IpcPath;
fn item(name: &str, path: &str) -> RecentProject {
RecentProject { path: IpcPath::from(path), name: name.into(), opened_at_ms: 0.0, branch: None }
RecentProject { path: IpcPath::from(path), name: name.into(), opened_at_ms: 0.0, branch: None, missing: false }
}
#[test]
+1
Переглянути файл
@@ -2056,6 +2056,7 @@ mod tests {
name: "openidea".into(),
opened_at_ms: 0.0,
branch: None,
missing: false,
}];
let items = recent_items(&recent, Some(Path::new("/home/me")));
assert_eq!(items[0].label, "openidea — ~/code/openidea");
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.46",
"version": "0.1.47",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+1
Переглянути файл
@@ -649,6 +649,7 @@ vcs_move_worktree trusted project_host bin
vcs_open_external_log always project_host bindings async
vcs_operation trusted project_host bindings async
vcs_patch_preview trusted project_host bindings async
vcs_pending_patch trusted project_host bindings async
vcs_rebase trusted project_host bindings async
vcs_rebase_with trusted project_host bindings async
vcs_remote trusted project_host bindings async
+11 -1
Переглянути файл
@@ -841,6 +841,7 @@ export const commands = {
/** The best common ancestor of `a` and `b` (`git merge-base`), if any. */
vcsMergeBase: (repo: string | null, a: string, b: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })),
vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { repo, source })),
vcsPendingPatch: (repo: string | null, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_pending_patch", { repo, options })),
vcsPatchPreview: (repo: string | null, patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })),
vcsApplyPatch: (repo: string | null, patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })),
/** Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. */
@@ -5268,6 +5269,8 @@ export type EditorSettings_Deserialize = {
/** Colours the rainbow bracket depth cycles through (2–5). */
rainbowBracketColors?: number,
ligatures?: boolean,
/** Editor › Font and Tools › Terminal › Font: the font pickers list only monospaced fonts. */
onlyMonospacedFonts?: boolean,
/** Fallback font for glyphs the main font lacks; empty = none. */
fallbackFont?: string,
/** Typography Settings › Main font weight (CSS 100–900), as IDEA. */
@@ -5326,6 +5329,8 @@ export type EditorSettings_Serialize = {
/** Colours the rainbow bracket depth cycles through (2–5). */
rainbowBracketColors: number,
ligatures: boolean,
/** Editor › Font and Tools › Terminal › Font: the font pickers list only monospaced fonts. */
onlyMonospacedFonts: boolean,
/** Fallback font for glyphs the main font lacks; empty = none. */
fallbackFont: string,
/** Typography Settings › Main font weight (CSS 100–900), as IDEA. */
@@ -9583,6 +9588,11 @@ export type RecentProject = {
* refreshes it from `.git/HEAD` when the list is shown.
*/
branch: string | null,
/**
* The local folder no longer exists (set by [`with_live_branches`] when the list is shown): the
* welcome screen shows the entry as unavailable.
*/
missing?: boolean,
};
/** A named group of recent projects on the welcome screen (New Project Group…, Move to Group). */
@@ -11527,7 +11537,7 @@ export type VenvTool =
"uv" |
/** `poetry env use <base>` in the project, then `poetry env info --path`. */
"poetry" |
/** `conda create -p <location> -y` (conda must be on PATH). */
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
"conda";
/** What a view or custom editor shows. */
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more