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

...
29 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai 294198a727 chore: v0.1.13 2026-10-25 09:45:20 +08:00
l0ng-ai 82b6980a59 feat: Second pass aligning interactions with IntelliJ IDEA (#23)
* feat: Second pass aligning interactions with IntelliJ IDEA

Result tool windows
- Next/Previous Occurrence (⌥⌘↓/↑) across Find, Usages, Problems, TODO,
  Inspection and Hierarchy, with an "N of M" status hint
- Find: reuse the unpinned tab, Pin Tab, source preview, group by file or
  directory, exclude moves to the next result, Rerun
- Usages: tabs with pinning, exclude and preview
- Problems, TODO, Inspection: no autoscroll by default, severity-first sorting,
  context menu with quick fixes and copy description
- Trees: F4/⌘↓ jump to source; speed search Home/End and arrow handling

Find in Files, bookmarks, navigation
- Replace mode: Enter replaces the selection, ⇧⌥Enter replaces all, multi-select
- Pin Window toggle, highlighted read-only preview, search/replace history (⌥↓),
  Alt mnemonics, search context filter (comments / string literals)
- Mnemonic bookmarks (⌥F3, ⌃⇧digit, ⌃digit), ⌘F3 bookmarks popup, descriptions,
  ⌘-click gutter toggles a bookmark
- Select In popup (⌥F1); Recent Locations double-click and Delete;
  Search Everywhere remembers the query per tab

Code insight and refactoring
- Extract/Introduce continue with in-place rename and name suggestions;
  expression and occurrence choosers with live highlighting
- Safe Delete confirms first; numbered Refactor This
- Quick Documentation history, in-popup links and a Documentation tool window;
  Quick Definition switches between targets and shows the whole declaration
- Goto chooser lists symbol names and can pin to the Find window
- Parameter Info Tab/⇧Tab, intention preview, Reformat dialog and summary,
  inlay hint ⌘-click and context menu
- Live templates: Enter moves to the next field, two-step Esc, ⌘J as a lookup,
  language surrounders with mnemonics
- File Structure popup as a filterable tree; Show Usages filter and preview;
  call hierarchy jumps to call sites

Editor
- Paste re-indents each line by default; Move Statement moves whole statements
  in and out of blocks and re-indents
- Type over closing quotes of existing strings; ⌘D/⌘⌫ cover folded regions;
  ⌥⌫ deletes the preceding word
- ⌃G / ⌃⌘G whole-word rules and wrap hint; double-modifier caret cloning
- Visual-column block selection, nested Collapse All, recursive folding,
  fold selection toggle, Go to Matching Brace, gutter drag selects lines,
  sticky line and error stripe clicks, Insert toggles overwrite mode

Run, VCS, workbench
- Gutter icons show the last test result; Modify Run Configuration; test tree
  hides passed tests, context menu and assertion diff
- Stack frames resolve by fully qualified class name; context run chooser
- Inline Smart Step Into
- Git Log multi-select filters, "me" and date range; favourite branches,
  Fetch and tags in the branch popup; stash Keep index and Unstash options
- Terminal tab titles follow the shell; Distraction Free persists; gear menu;
  sticky balloons move to the notifications tool window after a while

* fix(vcs): Label restored local changes as yours after Smart Checkout; name the branch checked out

Conflicts from restoring stashed changes show the user's uncommitted
changes on the left like other operations, and the checkout notification
names the new branch instead of the previous one.

* fix: Close the merge editor on Apply; confirm before terminating a running Run tab

Like IDEA, applying a merge result closes its tab, and closing a Run tab
whose process still runs asks before terminating it (with a Settings
toggle and "Do not ask again").

* fix(terminal): Don't start a new session in the background after closing the last tab

The hidden Terminal window stays mounted, so it reopened a session as soon
as the last tab closed. It now opens the Local tab only once the window is
shown again, as IDEA does.

* fix(vcs): Start the merge result from a three-way merge; close the editor on Apply

The result pane now begins with non-conflicting changes merged and each
conflict showing the base text, resolved from the side panes, instead of
raw conflict markers. Apply now reports success, so the tab closes.

fix(search): Match File Structure filter on word starts

* fix: Limit Smart Step Into to the paused line; drop usages hints on callbacks; show full intention titles

Adapters that list every remaining call in the function (debugpy) made Smart
Step Into fall back to a chooser that offered calls from later lines. Targets
are now narrowed to the calls on the paused line, so they are picked in place.

Anonymous functions and callbacks no longer get a 'no usages' hint, and
intention titles are no longer cut short when there is room for them.

* fix: Undo / Redo from the Edit menu and Find Action use the editor's history

They ran the webview's native undo, which misses programmatic edits such as
templates, completion and refactorings, so nothing happened in the editor.
2026-10-25 09:44:46 +08:00
l0ng-ai 81e0e8e2d0 feat: Align interactions with IntelliJ IDEA (#22)
* feat(nav): Complete file paths and flag unresolved web file references

Path completion in href/src/url()/@import, Markdown links and path-like strings, folders first. HTML and CSS paths that name no file get a 'Cannot resolve file' warning. File references resolve in the backend like IDEA's: relative to the file, /-rooted against the project and resource roots.

* feat: Align editor, workbench, run/debug and VCS interactions with IntelliJ IDEA

Keymap
- Let AltGr characters through instead of firing Ctrl+Alt shortcuts (Windows/Linux)
- Double Shift: strict press/release timing, ignored while typing or after Shift+click
- Chords wait 2s and swallow an unmatched second stroke
- Drop CodeMirror defaults that clash with IDEA keys; ⌘Enter is Split Line, add
  Scroll to Center and Code Block Start/End
- Add missing IDEA defaults (⌃J, ⌘Y, ⇧⌘C, ⌥⌘Y, ⇧⌘M, F9 Resume, ⌘R Rerun, …)

Editor
- Tab inserts at the caret; smart Backspace to the proper indent; Enter continues
  a `//` comment; per-language line comment placement
- Back/Forward records navigations only; ⌘F searches the selected text
- In-place rename; ⌃Space inserts a sole candidate; commit characters only for a
  focused lookup; usage highlighting survives edits; ⌥Enter offers fixes from the
  caret line; ⌘-hover shows declaration info only for navigable targets

Workbench
- Tool windows: primary and split area per side, six Move To anchors, layout migration
- ⌘W closes tool window content; Shift+Esc from the editor; closing a tab
  activates the left neighbour; preview tab and tab limit follow IDEA defaults
- Switcher lists open editors and tool windows; Recent Files Delete removes items
- Search Everywhere tab/scope behaviour; popups close when the window deactivates
- Project view: Copy/Move dialogs on paste, skippable usage search on delete,
  new-file input cancels on blur; Settings search Esc clears the filter
- Status bar breadcrumbs open a children popup; notification timeouts

Run / Debug / Build / Terminal
- Run asks to stop a running single-instance config; Rerun restarts silently;
  "Allow multiple instances" option
- Run chooser: Enter runs, Shift debugs, F4/Delete/digits
- Type into the console for stdin; Stop covers debug sessions
- Log (Shift+click) and temporary (Alt+click) breakpoints; independent suspend/log
  options; Evaluate prefill and history; changed-value highlighting; expandable hints
- Build window opens on failure and jumps to the first error
- Terminal confirms closing a busy tab and lets IDE shortcuts through

VCS
- Correct ours/theirs labels during rebase, cherry-pick and revert
- Smart/Force Checkout; remote branch checkout updates the local branch
- Partial commit by changed block; inline before-commit check results
- F7 continues into the next file; Rollback Lines; Commit and Push; Amend message swap
- Branch delete with Restore; force push confirmation; editable push target;
  update summary with the incoming commits

* chore: Regenerate bindings
2026-10-25 09:34:02 +08:00
l0ng-ai 87b463990c feat(nav): Follow links, file paths and CSS references with Go to Declaration
Go to Declaration and Cmd-click said "Cannot find declaration" on HTML href/src, CSS url() and @import, Markdown links and CSS selectors: language servers expose paths as document links, not definitions, and none resolves class/id to selectors.

- ide-lsp: textDocument/documentLink (lsp_document_links), resolving links that lack a target.
- Editor: when the server has no definition, follow its document links, then URLs and quoted / Markdown / url() paths in any language. Server file links are checked to exist; root-relative paths also resolve against resource roots. Cmd-hover underlines the whole link.
- ide-language: tree-sitter web references (class / id attributes, href="#id", var(--x)) and .class / #id / --var definitions from stylesheets and <style> elements, indexed as symbols. web_goto looks them up by exact name (ProjectIndex::symbols_named), using the open document's unsaved text.
- Detect public/ of package.json modules as a resource root (Vite, Next, CRA serve it at /).
2026-10-24 22:58:23 +08:00
l0ng-ai 046fd37064 fix(ui): Match PyCharm project view, matched tags and text weight
- Project widget initials follow IDEA's AvatarUtils.initials ("idea" → "I").
- "Show directories with changed descendants" is off by default, as in IDEA.
- FileEntry gains `excluded`: only excluded folders get the excluded icon and
  dimming; git-ignored ones keep the plain icon and the ignored colour.
- `.github` folders get IDEA's GitHub folder icon.
- Matched tag names are never bold and use their own background
  (MATCHED_TAG_NAME); matched braces are bold in dark schemes only.
- Revert Greyscale antialiasing to `antialiased` for UI and editor; `auto`
  rendered text heavier than PyCharm.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:56:48 +08:00
l0ng-ai cacddee19d feat(web): Open HTML in browsers with a built-in server; add Emmet
- ide-web: built-in static server on 127.0.0.1 that serves project files,
  plus detection and launching of installed browsers.
- Open In › Browser in the editor, project view and tab menus; browser bar
  and built-in preview beside HTML editors; ⌃⇧R opens the default browser.
- Emmet: Tab expansion in markup editors and Update Tag with Emmet.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:16:28 +08:00
l0ng-ai c8cea62eab fix(editor): Match PyCharm syntax colours and text weight
Greyscale antialiasing mapped to `-webkit-font-smoothing: antialiased`,
which drops macOS stem darkening, so editor and UI text rendered thinner
and syntax colours looked lighter than PyCharm's. Use `auto` instead.

Align lezer tag mappings with PyCharm's Light scheme:
- HTML/XML: `<!doctype>` is plain text (documentMeta is a sub-tag of meta).
- CSS/SCSS/Sass: property names use the attribute colour; values and units
  the attribute-value colour; class, id, pseudo, colour and url() the tag colour.
- YAML: keys are keywords.
- Markdown: quotes are strings with keyword markers, link destinations
  italic function colour, titles strings, horizontal rules keywords.

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 22:16:16 +08:00
l0ng-ai 4a2d5c9599 chore: v0.1.12
Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 18:26:59 +08:00
l0ng-ai 059f25f13e feat(java): Separate the jdtls JDK and add Settings for New Projects (#21)
- Languages & Frameworks › Java › Language Server › JDK (languages.java.jdtlsJdk) runs jdtls on its own JDK, like IDEA's JDK for importer; the project keeps compiling and running with the Project JDK.
- Toolchain pages get the Global / This project switch (default This project); Global shows and edits the global layer.
- File › New Projects Setup › Settings for New Projects… edits only the global layer, which new projects inherit.
- Configuration errors (launch_error) show as "Not started" instead of "Crashed".

Fixes #18
Fixes #19

Claude-Session: https://claude.ai/code/session_01SaPPsVPuk6ZTNsoUCNCbMv
2026-10-24 18:26:31 +08:00
@鹿таl0ng-ai a765959d48 fix(process): Spawn child processes without a console window (#17)
- The IDE is a GUI-subsystem binary, so Windows allocated a fresh console
  window for every console-subsystem child it started: one black window per
  language server, per settings-driven restart, per debug adapter and per
  toolchain probe, titled with the child's own path. Closing it killed the
  child, which is how editing the language-server settings broke highlighting.
- Peer::spawn, the spawn point for every language server, wired stdio but never
  passed CREATE_NO_WINDOW. The rustup-proxy probe, the DAP adapter, debugpy
  probe, runInTerminal and cargo spawns, the SDK probes, the run-configuration
  probes, the coverage exporter and tool diagnostics/downloads (curl, tar) had
  the same gap, while git, cargo builds, gh, docker and run configurations
  passed the flag inline — five copies of the magic constant, six subsystems
  without it.
- Add ide_core::process::{CREATE_NO_WINDOW, hide_console_window} as the single
  definition, route every spawn through it (tokio commands via as_std_mut()) and
  fold the inline copies into it.
- Verified locally on Windows with a console-detached harness: a plain spawn
  reports a visible console window (GetConsoleWindow + IsWindowVisible), the
  patched Peer::spawn reports a console without a window. cargo check, cargo
  clippy --all-targets and the affected test suites (249 tests) are green.

Co-authored-by: l0ng-ai <[email protected]>
2026-10-24 16:57:34 +08:00
l0ng-ai efbb48c3cb chore: v0.1.11 2026-10-24 16:32:25 +08:00
l0ng-ai bb9486c758 fix(app): Stop console tools from opening cmd windows on Windows (#20)
Release builds use the GUI subsystem, so a console child spawned without
CREATE_NO_WINDOW gets its own console window. git, gh, docker, builds and
run configurations already set the flag; language servers, SDK and tool
probes, debug adapters, tool downloads, coverage export and perf did not.
Add ide_core::process::no_window and use it at every remaining spawn.

Fixes #16
2026-10-24 16:31:50 +08:00
l0ng-ai 5c0c3a009c docs: Keep the demo video as the README's only hero 2026-10-24 14:50:08 +08:00
l0ng-ai ef667f6e21 chore: v0.1.10 2026-10-24 14:48:53 +08:00
l0ng-ai 81b43a52b4 docs: Trim the README to a link row, screenshots and the benchmark 2026-10-24 14:48:31 +08:00
l0ng-ai 0bb730039d feat(search): Bring Search Everywhere closer to IDEA's popup
- All tab interleaves classes, files, symbols, actions and text by match
  degree, keeping each source's own order; Enter waits for every source
  except a text search the top row already beats.
- Preview pane under the list (remembered toggle), reusing CodePreview.
- "/" lists scope commands; "/files q" switches scope and searches q.
- Per-tab search history: magnifier dropdown and ⌥↑ / ⌥↓.
- Text hits: syntax colouring, IDEA's boxed-T icon, dimmed repeated file
  names, collapsed indentation.
- Flat scope chooser, IDEA header icons, wider popup with a stable list
  height; the list shrinks so the footer stays visible.
2026-10-24 14:47:45 +08:00
l0ng-ai 709e1eb855 docs: Drop the feature list from the README 2026-10-24 14:46:31 +08:00
l0ng-ai 4473324822 docs: Recapture the README editor screenshot with a focused window 2026-10-24 14:45:35 +08:00
l0ng-ai 5d5b3e4791 docs: Recapture README screenshots with the native window frame 2026-10-24 14:36:44 +08:00
l0ng-ai c5b4b71e30 docs: Lay out README screenshots as a hero plus an even pair 2026-10-24 14:34:29 +08:00
l0ng-ai 0e299ad936 docs: Add download links, screenshots and a feature list to the README 2026-10-24 14:31:17 +08:00
Richardтаl0ng-ai 5b8e0b9659 feat(i18n): 新增简体中文界面翻译 (#15)
* feat(i18n): 新增简体中文界面翻译

* test(i18n): 补充中文界面截图与端到端验证

* fix(i18n): Translate notifications and usages through catalog templates

Move the hard-coded Chinese notification patterns into source-text
templates (`{name} failed`) applied at render time, so text follows
locale switches and stays English under en. Use useTx in Search
Everywhere and add its missing zh strings.

* chore: Drop i18n screenshots

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-10-24 14:14:43 +08:00
l0ng-ai 3d8a6f07b4 feat(app): Enable signed auto-updates from GitHub releases
Configure the updater public key and the releases/latest latest.json
endpoint, and build updater artifacts so tauri-action uploads signatures
and latest.json. Check for updates once per app start (release builds
only) and offer Install and Restart when one is available.
2026-10-24 14:13:12 +08:00
l0ng-ai 99b4f8bdf6 fix(terminal): Render with xterm's DOM renderer
The WebGL renderer rasterizes each glyph against its cell background, so
text over the selection came out at a visibly lighter weight than the
rest and looked like a different font. The DOM renderer draws text like
the editor does, selected or not.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:42:07 +08:00
l0ng-ai 86f1f666d7 chore: v0.1.9
Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:15:41 +08:00
l0ng-ai be49490153 feat(terminal): Align the terminal with IDEA's tabs, menu and settings
- ⌘T (Ctrl+Shift+T on Windows) opens a terminal tab while the terminal
  has focus; elsewhere the key keeps its IDE action.
- The tab bar's ▾ menu lists installed shells under "New Predefined
  Session" (login shell, shell integration) and links to Settings.
- Settings › Tools › Terminal: pick the shell path from the installed
  shells or browse for one, "Move focus to the Editor with Escape",
  fallback font, column width and a link to the Terminal keymap.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 13:02:52 +08:00
l0ng-ai 1f5fcb477d fix(terminal): Default to the account's login shell
$SHELL is inherited from whatever launched the app, so starting it from a
terminal running bash opened bash even when the login shell is zsh. Read
the passwd entry first and fall back to $SHELL.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:36:40 +08:00
l0ng-ai 1bb454bd2f fix(terminal): Match the xterm scrollbar to the IDE's
Style xterm's own scrollbar slider with the scrollbar tokens, narrow it to
10px and blend the overview ruler border into the background.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:36:40 +08:00
l0ng-ai f38f63e397 test(e2e): Drive the Language Servers page through its list and details
The page is no longer a table: pick the tool in the list, then act in
its details pane. Fixes the Frontend CI failures since v0.1.7.

Claude-Session: https://claude.ai/code/session_01B65qLEKnkeYTGdbwhLpjCu
2026-10-24 12:11:21 +08:00
495 змінених файлів з 26709 додано та 3214 видалено

No files matched your search

Створено
+43 -26
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-analysis"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3976,7 +3976,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -3991,7 +3991,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dunce",
"serde",
@@ -4003,7 +4003,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-run",
@@ -4017,7 +4017,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4034,7 +4034,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4054,7 +4054,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"libc",
@@ -4067,7 +4067,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4081,7 +4081,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"parking_lot",
@@ -4099,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"blake3",
"criterion",
@@ -4121,7 +4121,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"futures",
"ide-core",
@@ -4136,7 +4136,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"blake3",
"criterion",
@@ -4188,7 +4188,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"futures",
"globset",
@@ -4211,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-language",
@@ -4229,7 +4229,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-run",
@@ -4242,7 +4242,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4260,7 +4260,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dunce",
"ide-core",
@@ -4277,7 +4277,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"criterion",
"globset",
@@ -4296,7 +4296,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"ide-language",
@@ -4311,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"ide-core",
"libc",
@@ -4324,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"criterion",
"ide-core",
@@ -4336,7 +4336,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"flate2",
"hex",
@@ -4356,7 +4356,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dunce",
"gix",
@@ -4373,7 +4373,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"chardetng",
"dunce",
@@ -4391,9 +4391,25 @@ dependencies = [
"trash",
]
[[package]]
name = "ide-web"
version = "0.1.13"
dependencies = [
"ide-core",
"open",
"parking_lot",
"percent-encoding",
"serde",
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-workspace"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"blake3",
"dunce",
@@ -5817,7 +5833,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.8"
version = "0.1.13"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -5844,6 +5860,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"ide-web",
"ide-workspace",
"parking_lot",
"serde",
+2 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.8"
version = "0.1.13"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -32,6 +32,7 @@ ide-coverage = { path = "crates/ide-coverage" }
ide-profiler = { path = "crates/ide-profiler" }
ide-http = { path = "crates/ide-http" }
ide-db = { path = "crates/ide-db" }
ide-web = { path = "crates/ide-web" }
# serialization & IPC typing
serde = { version = "1", features = ["derive"] }
+9 -1
Переглянути файл
@@ -9,13 +9,21 @@
The IDE you know, rebuilt in Rust.
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
&nbsp;·&nbsp;
<a href="#benchmark">Benchmark</a>
&nbsp;·&nbsp;
<a href="#build">Build</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool windows,
its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages.
for 60+ languages. Builds for macOS, Windows and Linux.
## Benchmark
+1 -6
Переглянути файл
@@ -52,12 +52,7 @@ pub(crate) fn run(
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
ide_core::process::no_window(&mut command);
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
+17 -11
Переглянути файл
@@ -39,7 +39,7 @@ impl Default for EditorGeneralSettings {
caret_scroll: "minimize".into(),
soft_wrap_files: "*.md; *.txt; *.rst; *.adoc".into(),
soft_wrap_indent: true,
scroll_past_end: true,
scroll_past_end: false,
strip_trailing_scope: "modified".into(),
keep_trailing_on_caret_line: true,
remove_trailing_blank_lines: false,
@@ -102,7 +102,7 @@ pub struct BreadcrumbsSettings {
impl Default for BreadcrumbsSettings {
fn default() -> Self {
Self { show: false, placement: "bottom".into(), disabled_languages: Vec::new() }
Self { show: true, placement: "bottom".into(), disabled_languages: Vec::new() }
}
}
@@ -130,10 +130,10 @@ impl Default for CompletionSettings {
case_sensitivity: "first".into(),
auto_popup: true,
insert_on_special_keys: false,
show_documentation: true,
show_documentation: false,
documentation_delay: 500,
parameter_info: true,
parameter_info_delay: 300,
parameter_info_delay: 1000,
}
}
}
@@ -192,9 +192,9 @@ impl Default for EditorTabsSettings {
show_close_button: true,
preview_tab: true,
open_at_end: false,
tab_limit: 10,
closing_policy: "unchanged".into(),
activate_on_close: "mru".into(),
tab_limit: 30,
closing_policy: "lru".into(),
activate_on_close: "left".into(),
}
}
}
@@ -214,7 +214,7 @@ pub struct SmartKeysSettings {
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String,
pub smart_indent: bool,
/// Backspace › Unindent: `nearest` indent position | `none`.
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
pub backspace_unindent: String,
}
@@ -226,10 +226,10 @@ impl Default for SmartKeysSettings {
pair_brackets: true,
pair_quotes: true,
surround_selection: true,
tab_out_of_pair: false,
reformat_on_paste: "indentBlock".into(),
tab_out_of_pair: true,
reformat_on_paste: "indentEachLine".into(),
smart_indent: true,
backspace_unindent: "nearest".into(),
backspace_unindent: "autoindent".into(),
}
}
}
@@ -314,6 +314,12 @@ pub struct LanguageCodeStyle {
pub indent: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hard_wrap_at: Option<u32>,
/// Comment Code › Line comment at first column.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_at_first_column: Option<bool>,
/// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
+3
Переглянути файл
@@ -106,6 +106,9 @@ pub enum ServerStatus {
Crashed,
Stopped,
Missing,
/// Not started: its configuration can't launch it (e.g. no JDK new enough);
/// the message says what to change, and a settings change retries.
Misconfigured,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1
Переглянути файл
@@ -10,6 +10,7 @@ pub mod event;
pub mod ids;
pub mod ignored;
pub mod ipc_path;
pub mod process;
pub mod project_dir;
pub mod settings;
pub mod text;
+20
Переглянути файл
@@ -0,0 +1,20 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::process::Command;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Keeps a console child (java, node, curl, a language server, ...) from
/// opening its own console window on Windows. Release builds use the GUI
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
pub fn no_window(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW);
}
cmd
}
+4
Переглянути файл
@@ -422,6 +422,10 @@ pub struct JavaSettings {
/// Project JDK home; empty = per module, the installed JDK matching the
/// Java version it targets.
pub jdk: String,
/// JDK home the Java language server (jdtls) runs on, apart from the project
/// JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
/// else the first installed one that is.
pub jdtls_jdk: String,
/// Extra JVM options for the Java language server (jdtls), space-separated
/// (VS Code's `java.jdt.ls.vmargs`).
pub jdtls_vm_args: String,
+14 -2
Переглянути файл
@@ -24,7 +24,8 @@ pub struct VcsSettings {
impl Default for VcsSettings {
fn default() -> Self {
Self {
show_dirty_directories: true,
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
show_dirty_directories: false,
limit_history: true,
history_limit: 1000,
git: GitSettings::default(),
@@ -211,6 +212,8 @@ impl Default for PythonDebuggerSettings {
#[serde(default, rename_all = "camelCase")]
pub struct RunSettings {
pub confirm_rerun: bool,
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
pub show_on_start: bool,
/// Grace period between interrupt and kill when stopping a process.
pub termination_timeout_ms: u32,
@@ -218,7 +221,7 @@ pub struct RunSettings {
impl Default for RunSettings {
fn default() -> Self {
Self { confirm_rerun: true, show_on_start: true, termination_timeout_ms: 3000 }
Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 }
}
}
@@ -241,6 +244,8 @@ pub struct TerminalSettings {
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
pub option_as_meta: bool,
/// Escape moves focus to the editor instead of reaching the shell.
pub escape_to_editor: bool,
/// `block` | `underline` | `bar`.
pub cursor_shape: String,
pub cursor_blink: bool,
@@ -249,6 +254,10 @@ pub struct TerminalSettings {
pub font_size: f32,
/// Multiple of the cell height.
pub line_height: f32,
/// Font tried for glyphs the main font lacks; empty = none.
pub fallback_font_family: String,
/// Multiple of the cell width.
pub column_width: f32,
}
impl Default for TerminalSettings {
@@ -267,12 +276,15 @@ impl Default for TerminalSettings {
shell_integration: true,
highlight_hyperlinks: true,
option_as_meta: false,
escape_to_editor: false,
cursor_shape: "block".into(),
cursor_blink: true,
use_editor_font: true,
font_family: "JetBrains Mono".into(),
font_size: 13.0,
line_height: 1.0,
fallback_font_family: String::new(),
column_width: 1.0,
}
}
}
+1 -1
Переглянути файл
@@ -204,7 +204,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
let (program, args) =
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
let out = Command::new(program)
let out = ide_core::process::no_window(&mut Command::new(program))
.args(args)
.current_dir(cwd)
.envs(env)
+1
Переглянути файл
@@ -287,6 +287,7 @@ mod tests {
detected: true,
is_test: true,
debug_adapter: None,
allow_parallel: false,
}
}
+4 -1
Переглянути файл
@@ -233,7 +233,9 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
let probe = Command::new(&python)
let mut probe = Command::new(&python);
ide_core::process::no_window(probe.as_std_mut());
let probe = probe
.args(["-c", "import debugpy.adapter"])
.current_dir(&spec.cwd)
.stdin(Stdio::null())
@@ -335,6 +337,7 @@ impl AdapterLauncher for ProcessLauncher {
None => spec.args.clone(),
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
+1
Переглянути файл
@@ -55,6 +55,7 @@ pub async fn build(
) -> IdeResult<PathBuf> {
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.current_dir(cwd)
+1
Переглянути файл
@@ -390,6 +390,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
return Err("runInTerminal without args".into());
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+25
Переглянути файл
@@ -121,6 +121,11 @@ impl ProjectIndex {
matching::find_symbols(&d, &matching::Recents { paths: &recent }, query, filter, limit)
}
/// Symbols named exactly `name` (of `kind`, if given): `.card` selectors for `class="card"`.
pub fn symbols_named(&self, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
matching::symbols_named(&self.shared.data.read(), name, kind, limit)
}
/// Incrementally re-indexes changed paths (called from the vfs watcher).
/// Cheap: the work is queued for the indexing thread.
pub fn update(&self, changed: &[PathBuf], removed: &[PathBuf]) {
@@ -154,6 +159,26 @@ impl ProjectIndex {
self.shared.enqueue(Job::SaveRecent);
}
/// Drops a file from Recent Files (Delete in the ⌘E popup).
pub fn remove_recent(&self, path: &Path) {
let path = match path.to_str() {
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
_ => match self.normalize(path) {
Some(p) => p,
None => return,
},
};
{
let mut r = self.shared.recent.lock();
let before = r.len();
r.retain(|p| p != &path);
if r.len() == before {
return;
}
}
self.shared.enqueue(Job::SaveRecent);
}
/// Recently opened files, most recent first.
pub fn recent_files(&self) -> Vec<PathBuf> {
self.shared.recent.lock().clone()
+28
Переглянути файл
@@ -7,6 +7,7 @@
use crate::data::{FileEntry, IndexData, char_mask};
use crate::{FileMatch, SymbolFilter, SymbolMatch};
use ide_core::SymbolKind;
use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
use rayon::prelude::*;
use std::cell::RefCell;
@@ -419,6 +420,33 @@ pub(crate) fn find_symbols(
.collect()
}
/// Symbols named exactly `name` (and of `kind`, when given), by path then position.
pub(crate) fn symbols_named(data: &IndexData, name: &str, kind: Option<SymbolKind>, limit: usize) -> Vec<SymbolMatch> {
let mask = char_mask(name);
let mut out: Vec<SymbolMatch> = data
.files
.iter()
.flatten()
.flat_map(|e| {
e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map(
move |s| SymbolMatch {
name: s.name.to_string(),
kind: s.kind,
container: s.container.as_deref().map(str::to_owned),
path: e.path.clone().into(),
rel_path: e.rel.to_string(),
range: s.range,
score: 0,
indices: Vec::new(),
},
)
})
.collect();
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
out.truncate(limit);
out
}
#[cfg(test)]
mod tests {
use super::*;
+22
Переглянути файл
@@ -192,7 +192,11 @@ fn persistence_skips_unchanged_files_on_reopen() {
assert_eq!(idx.status().files, 8);
assert_eq!(symbols(&idx, "OrderController", SymbolFilter::Types)[0], "OrderController");
assert_eq!(idx.recent_files(), vec![fx.root.join("web/app.py")]);
idx.remove_recent(&fx.root.join("web/app.py"));
assert!(idx.recent_files().is_empty());
assert!(idx.wait_idle(WAIT));
}
assert!(fx.open().recent_files().is_empty(), "removal is persisted");
std::thread::sleep(Duration::from_millis(20));
fx.write("src/main.rs", "fn main() {}\nfn renamed_fn() {}\n");
std::fs::remove_file(fx.root.join("docs/maintenance.md")).unwrap();
@@ -381,3 +385,21 @@ fn synthetic_index_answers_queries() {
assert!(!s.find_symbols("PaySe", SymbolFilter::All, 20).is_empty());
assert!(s.find_symbols("PaySe", SymbolFilter::Types, 20).iter().all(|m| m.kind == SymbolKind::Class));
}
#[test]
fn css_selectors_are_found_by_exact_name() {
let f = Fixture::new(&[
("web/a.css", ".card { --gap: 1px }\n.cardigan {}\n"),
("web/b.scss", ".list { .card { } }\n"),
("web/index.html", "<style>.card{}</style>\n<div class=\"card\"></div>\n"),
]);
let idx = f.open();
let found: Vec<(String, u32)> = idx
.symbols_named(".card", Some(SymbolKind::Class), 10)
.into_iter()
.map(|m| (m.rel_path, m.range.start.line))
.collect();
assert_eq!(found, vec![("web/a.css".into(), 0), ("web/b.scss".into(), 0), ("web/index.html".into(), 0)]);
assert_eq!(idx.symbols_named("--gap", None, 10).len(), 1);
assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty());
}
+1
Переглянути файл
@@ -241,6 +241,7 @@ impl Peer {
) -> std::io::Result<Self> {
use std::process::Stdio;
let mut cmd = tokio::process::Command::new(command);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
+3 -2
Переглянути файл
@@ -13,8 +13,9 @@ mod registry;
mod syntax;
pub use registry::LanguageRegistry;
pub use syntax::{
MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind,
SyntaxHighlights, TreeError,
CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES,
ParsedTree, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference,
WebReferenceKind,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
+59
Переглянути файл
@@ -0,0 +1,59 @@
//! Comments and string literals of a text, for Find in Files' search context
//! filter ("In comments", "Except string literals", …).
use super::folding::is_comment;
use tree_sitter::{Node, Tree};
/// What a [`Literal`] range is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiteralKind {
Comment,
String,
}
/// A comment or string literal: byte range of the outermost node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Literal {
pub start: usize,
pub end: usize,
pub kind: LiteralKind,
}
fn kind_of(node: &Node<'_>) -> Option<LiteralKind> {
if !node.is_named() {
return None;
}
let kind = node.kind();
if is_comment(kind) {
Some(LiteralKind::Comment)
} else if kind.contains("string") || matches!(kind, "char_literal" | "character_literal" | "rune_literal") {
Some(LiteralKind::String)
} else {
None
}
}
/// Comments and string literals in document order; nested ones (a string in a
/// comment, interpolations) are covered by the outermost.
pub(crate) fn literals(tree: &Tree) -> Vec<Literal> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let kind = kind_of(&node);
if let Some(kind) = kind {
out.push(Literal { start: node.start_byte(), end: node.end_byte(), kind });
}
if kind.is_none() && cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return out;
}
}
}
}
+70 -7
Переглянути файл
@@ -5,18 +5,22 @@ mod folding;
mod grammars;
mod highlight;
pub(crate) mod lines;
mod literals;
mod outline;
mod selection;
mod web;
use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag};
pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats};
use grammars::{SPECS, Spec};
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
use ide_core::{LanguageId, OutlineItem, Range};
use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use literals::{Literal, LiteralKind};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
use tree_sitter::{Language, Parser, Tree};
pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind};
/// Texts larger than this are not parsed (minified bundles, generated dumps).
pub const MAX_PARSE_BYTES: usize = 16 * 1024 * 1024;
@@ -117,6 +121,8 @@ impl Syntax {
FP.get_or_init(|| {
let mut h = blake3::Hasher::new();
h.update(env!("CARGO_PKG_VERSION").as_bytes());
// Bump when web definitions (`.class`, `#id`, `--var` tags) change.
h.update(b"web-definitions-1");
for s in SPECS {
h.update(s.name.as_bytes());
h.update(&Language::new(s.language).abi_version().to_le_bytes());
@@ -141,7 +147,8 @@ impl Syntax {
/// Whether [`Syntax::tags`] can return anything for this language (data
/// formats such as JSON only have an outline). Lets indexers skip parsing.
pub fn has_symbols(&self, lang: &LanguageId) -> bool {
self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
self.web_grammar(lang).is_some()
|| self.grammar(lang).and_then(Grammar::outline_query).is_some_and(|q| q.has_tags)
}
pub fn outline(&self, lang: &LanguageId, text: &str) -> Vec<OutlineItem> {
@@ -158,11 +165,61 @@ impl Syntax {
}
pub fn tags(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
self.analyze(lang, text, |g, tree, text| {
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
})
.unwrap_or_default()
let mut tags = self
.analyze(lang, text, |g, tree, text| {
let query = g.outline_query()?;
Some(outline::tags(g, query, tree, text))
})
.unwrap_or_default();
tags.extend(self.web_definitions(lang, text));
tags
}
/// The grammar web features parse `lang` with: its own for HTML and CSS, the
/// CSS grammar for SCSS / Less (selectors and custom properties parse alike),
/// HTML for Vue / Svelte single-file components.
fn web_grammar(&self, lang: &LanguageId) -> Option<&Grammar> {
let name = match lang.as_str() {
"scss" | "less" => "css",
"vue" | "svelte" => "html",
_ => self.grammar(lang).map(|g| g.spec.name)?,
};
web::is_web_grammar(name).then(|| self.grammar(&LanguageId::new(name))).flatten()
}
fn with_web_tree<R>(
&self,
lang: &LanguageId,
text: &str,
f: impl FnOnce(&Grammar, Option<&Grammar>, &Tree) -> R,
) -> Option<R> {
let g = self.web_grammar(lang)?;
if text.len() > MAX_PARSE_BYTES {
return None;
}
let tree = parse(&g.language, text, None)?;
Some(f(g, self.grammar(&LanguageId::new("css")), &tree))
}
/// CSS class (`.card`), id (`#main`) and custom property (`--accent`)
/// definitions of a stylesheet or of the `<style>` elements of a document.
pub fn web_definitions(&self, lang: &LanguageId, text: &str) -> Vec<SymbolTag> {
self.with_web_tree(lang, text, |g, css, tree| web::definitions(g, css, tree, text)).unwrap_or_default()
}
/// The `class` / `id` / `href="#…"` / `var(--…)` reference at `pos`.
pub fn web_reference_at(&self, lang: &LanguageId, text: &str, pos: Pos) -> Option<WebReference> {
self.with_web_tree(lang, text, |g, css, tree| web::reference_at(g, css, tree, text, pos)).flatten()
}
/// File paths written in an HTML document or stylesheet (`href`, `src`, `srcset`, `url()`, `@import`).
pub fn web_file_references(&self, lang: &LanguageId, text: &str) -> Vec<FileReference> {
self.with_web_tree(lang, text, |g, css, tree| web::file_references(g, css, tree, text)).unwrap_or_default()
}
/// Value ranges of the `id="name"` / `name="name"` attributes in an HTML document.
pub fn web_anchors(&self, lang: &LanguageId, text: &str, name: &str) -> Vec<Range> {
self.with_web_tree(lang, text, |_, _, tree| web::anchors(tree, text, name)).unwrap_or_default()
}
/// Highlighting from the grammar's own query; `None` without one.
@@ -172,6 +229,12 @@ impl Syntax {
})
}
/// Comments and string literals of `text` (byte ranges, document order);
/// `None` without a grammar for `lang` or for texts too large to parse.
pub fn literals(&self, lang: &LanguageId, text: &str) -> Option<Vec<Literal>> {
self.analyze(lang, text, |_, tree, _| Some(literals::literals(tree)))
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
pub fn selection_ranges(&self, lang: &LanguageId, text: &str, offset_utf16: u32) -> Vec<Range> {
match self.analyze(lang, text, |_, tree, text| Some(selection::selection_ranges(tree, text, offset_utf16))) {
+102
Переглянути файл
@@ -1085,3 +1085,105 @@ fn large_input_is_not_parsed() {
let big = "a".repeat(MAX_PARSE_BYTES + 1);
assert!(syntax().outline(&lang("rust"), &big).is_empty());
}
// --- web references -------------------------------------------------------------
fn web_defs(id: &str, src: &str) -> Vec<(String, SymbolKind, u32, u32)> {
syntax()
.web_definitions(&lang(id), src)
.into_iter()
.map(|t| (t.name, t.kind, t.range.start.line, t.range.start.col))
.collect()
}
fn web_ref(id: &str, src: &str) -> Option<(WebReferenceKind, String, u32, u32)> {
let at = src.find('|').expect("caret marker");
let text = src.replace('|', "");
let line = text[..at].matches('\n').count() as u32;
let col = (at - text[..at].rfind('\n').map_or(0, |i| i + 1)) as u32;
syntax()
.web_reference_at(&lang(id), &text, Pos::new(line, col))
.map(|r| (r.kind, r.name, r.range.start.col, r.range.end.col))
}
#[test]
fn web_definitions_of_stylesheets_and_style_elements() {
let css = ".a.b, div#main > .c:hover { color: var(--x); --y: 1px; }\n@media (x) { .d {} }\n";
assert_eq!(
web_defs("css", css),
vec![
(".a".into(), CSS_CLASS, 0, 1),
(".b".into(), CSS_CLASS, 0, 3),
("#main".into(), CSS_ID, 0, 10),
(".c".into(), CSS_CLASS, 0, 18),
("--y".into(), CSS_VARIABLE, 0, 45),
(".d".into(), CSS_CLASS, 1, 14),
]
);
// Pseudo-classes (`:hover`) are not classes; nested SCSS rules parse with the CSS grammar.
assert!(!web_defs("css", css).iter().any(|d| d.0 == ".hover"));
assert!(web_defs("scss", ".card { &:hover { } .title { } }").iter().any(|d| d.0 == ".title"));
let html = "<p class=\"x\">\n<style>\n .card { --gap: 2px }\n</style>";
assert_eq!(web_defs("html", html), vec![(".card".into(), CSS_CLASS, 2, 3), ("--gap".into(), CSS_VARIABLE, 2, 10)]);
assert!(syntax().tags(&lang("css"), css).iter().any(|t| t.name == ".a"));
assert!(syntax().has_symbols(&lang("css")) && syntax().has_symbols(&lang("vue")));
}
#[test]
fn web_references_in_attributes_and_stylesheets() {
use WebReferenceKind::*;
assert_eq!(web_ref("html", r##"<div class="card bi|g">"##), Some((Class, "big".into(), 17, 20)));
assert_eq!(web_ref("html", r##"<div class="|card big">"##), Some((Class, "card".into(), 12, 16)));
assert_eq!(web_ref("html", r##"<div id="ma|in">"##), Some((Id, "main".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="#to|p">"##), Some((Anchor, "top".into(), 9, 13)));
assert_eq!(web_ref("html", r##"<a href="page.ht|ml">"##), None);
assert_eq!(
web_ref("html", r##"<p style="color: var(--ac|cent)">"##),
Some((CssVariable, "--accent".into(), 21, 29))
);
assert_eq!(web_ref("html", "<style>\n.a { color: var(--x|) }\n</style>").map(|r| r.1), Some("--x".into()));
assert_eq!(web_ref("css", ".a { color: var(--a|ccent, red) }"), Some((CssVariable, "--accent".into(), 16, 24)));
assert_eq!(web_ref("css", ".a { color: re|d }"), None);
assert_eq!(web_ref("vue", r##"<template><div class="ti|tle"/></template>"##).map(|r| r.0), Some(Class));
}
#[test]
fn web_anchors_find_ids_and_names() {
let html = "<h2 id=\"top\">x</h2>\n<a name=\"top\"></a>\n<p class=\"top\">";
let found: Vec<(u32, u32)> =
syntax().web_anchors(&lang("html"), html, "top").into_iter().map(|r| (r.start.line, r.start.col)).collect();
assert_eq!(found, vec![(0, 8), (1, 9)]);
}
#[test]
fn web_file_references_in_attributes_and_stylesheets() {
let refs = |id: &str, src: &str| -> Vec<String> {
syntax().web_file_references(&lang(id), src).into_iter().map(|r| r.value).collect()
};
let html = concat!(
"<link href=\"css/a.css\"><img srcset=\"a.png 1x, b.png 2x\" src=img/c.png alt=\"x\">\n",
"<a href=\"#top\" class=\"k\">t</a><div style=\"background: url(d.svg)\"></div>\n",
"<style>@import \"e.css\"; .x { background: url('f.png') }</style>",
);
assert_eq!(refs("html", html), ["css/a.css", "a.png", "b.png", "img/c.png", "#top", "d.svg", "e.css", "f.png"]);
assert_eq!(refs("css", "@import url(g.css);\n.y { mask: url(\"h.svg#i\") }"), ["g.css", "h.svg#i"]);
let first = &syntax().web_file_references(&lang("html"), html)[0];
assert_eq!((first.range.start.col, first.range.end.col), (12, 21));
}
#[test]
fn literals_are_outermost_comments_and_strings() {
let src = "// note \"q\"\nfn main() { let s = \"a // b\"; /* c */ let c = 'x'; }\n";
let found: Vec<(&str, LiteralKind)> =
syntax().literals(&lang("rust"), src).unwrap().iter().map(|l| (&src[l.start..l.end], l.kind)).collect();
assert_eq!(
found,
vec![
("// note \"q\"", LiteralKind::Comment),
("\"a // b\"", LiteralKind::String),
("/* c */", LiteralKind::Comment),
("'x'", LiteralKind::String),
]
);
assert!(syntax().literals(&lang("plaintext"), "// x").is_none());
}
+374
Переглянути файл
@@ -0,0 +1,374 @@
//! Web references that no language server resolves: HTML `class` / `id`
//! attributes to the CSS selectors that style them, `href="#id"` to the element
//! with that id, and `var(--x)` to the custom property's declarations.
//!
//! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the
//! `<style>` elements of HTML documents and feed the symbol index (see
//! [`super::Syntax::tags`]), so a lookup is an exact index query.
use super::lines::{LineIndex, utf16_to_byte};
use super::{Grammar, parse};
use crate::SymbolTag;
use ide_core::{Pos, Range, SymbolKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use tree_sitter::{Node, Tree};
/// Index symbol kinds of web definitions; names carry the CSS sigil.
pub const CSS_CLASS: SymbolKind = SymbolKind::Class;
pub const CSS_ID: SymbolKind = SymbolKind::Field;
pub const CSS_VARIABLE: SymbolKind = SymbolKind::Variable;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum WebReferenceKind {
/// A class in a `class` / `className` attribute: `.name` selectors.
Class,
/// An `id` attribute value: `#name` selectors.
Id,
/// `href="#name"`: the element with that id in the same document.
Anchor,
/// `var(--name)`: the custom property's declarations.
CssVariable,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebReference {
pub kind: WebReferenceKind,
/// Without sigil: `card`, `main`, `--accent`.
pub name: String,
pub range: Range,
}
impl WebReference {
/// The index symbol a reference resolves to: `.card`, `#main`, `--accent`.
pub fn symbol(&self) -> Option<(String, SymbolKind)> {
match self.kind {
WebReferenceKind::Class => Some((format!(".{}", self.name), CSS_CLASS)),
WebReferenceKind::Id => Some((format!("#{}", self.name), CSS_ID)),
WebReferenceKind::CssVariable => Some((self.name.clone(), CSS_VARIABLE)),
WebReferenceKind::Anchor => None,
}
}
}
/// Grammars whose documents carry web definitions and references.
pub(crate) fn is_web_grammar(name: &str) -> bool {
matches!(name, "css" | "html")
}
/// Stylesheet text embedded in a document: `(byte offset, text)`.
fn css_regions<'t>(grammar: &str, tree: &Tree, text: &'t str) -> Vec<(usize, &'t str)> {
match grammar {
"css" => vec![(0, text)],
"html" => {
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "style_element" {
let mut c = n.walk();
for raw in n.children(&mut c).filter(|c| c.kind() == "raw_text") {
out.push((raw.start_byte(), &text[raw.start_byte()..raw.end_byte()]));
}
return false;
}
true
});
out
}
_ => Vec::new(),
}
}
/// Pre-order walk; `f` returns whether to descend.
fn walk<'t>(n: Node<'t>, f: &mut dyn FnMut(Node<'t>) -> bool) {
if !f(n) {
return;
}
let mut c = n.walk();
for child in n.children(&mut c) {
walk(child, f);
}
}
fn text_of<'t>(n: Node, text: &'t str) -> &'t str {
text.get(n.start_byte()..n.end_byte()).unwrap_or_default()
}
/// `.name`, `#name` and `--name` definitions in `text` (a stylesheet, or a document with `<style>`).
pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<SymbolTag> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if base == 0 && g.spec.name == "css" {
tree
} else {
let Some(css) = css else { continue };
let Some(t) = parse(&css.language, css_text, None) else { continue };
parsed = t;
&parsed
};
walk(css_tree.root_node(), &mut |n| {
let def = match n.kind() {
"class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => {
Some((format!(".{}", text_of(n, css_text)), CSS_CLASS))
}
"id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)),
"property_name" if text_of(n, css_text).starts_with("--") => {
Some((text_of(n, css_text).to_owned(), CSS_VARIABLE))
}
_ => None,
};
if let Some((name, kind)) = def {
let range = idx.range(base + n.start_byte(), base + n.end_byte());
out.push(SymbolTag { name, kind, container: None, range });
}
true
});
}
out
}
fn byte_at(text: &str, pos: Pos) -> Option<usize> {
let mut start = 0;
for _ in 0..pos.line {
start += text[start..].find('\n')? + 1;
}
let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
Some(start + utf16_to_byte(&text[start..line_end], pos.col as usize))
}
/// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`.
fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> {
let rel = at.checked_sub(base)?;
let start = value[..rel.min(value.len())].rfind(char::is_whitespace).map_or(0, |i| i + 1);
let end = value[rel.min(value.len())..].find(char::is_whitespace).map_or(value.len(), |i| rel + i);
(start < end).then(|| (base + start, &value[start..end]))
}
/// `var(--name)` around byte `at` of a stylesheet tree.
fn css_variable_at(tree: &Tree, css_text: &str, at: usize) -> Option<(usize, usize, String)> {
let mut n = tree.root_node().descendant_for_byte_range(at, at)?;
if n.kind() != "plain_value" {
// The caret right after `--x` in `var(--x)`.
n = tree.root_node().descendant_for_byte_range(at.saturating_sub(1), at.saturating_sub(1))?;
}
let name = text_of(n, css_text);
let call = n.parent()?.parent()?;
let is_var = call.kind() == "call_expression"
&& call
.child_by_field_name("function_name")
.or_else(|| call.child(0))
.is_some_and(|f| text_of(f, css_text) == "var");
(n.kind() == "plain_value" && name.starts_with("--") && is_var)
.then(|| (n.start_byte(), n.end_byte(), name.to_owned()))
}
/// The web reference at `pos` of a document parsed as `tree`.
pub(crate) fn reference_at(
g: &Grammar,
css: Option<&Grammar>,
tree: &Tree,
text: &str,
pos: Pos,
) -> Option<WebReference> {
let at = byte_at(text, pos)?;
let idx = LineIndex::new(text);
let make = |kind, from: usize, to: usize, name: String| WebReference { kind, name, range: idx.range(from, to) };
// Stylesheet regions: `var(--x)`.
for (base, css_text) in css_regions(g.spec.name, tree, text) {
if at < base || at > base + css_text.len() {
continue;
}
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
parsed = parse(&css?.language, css_text, None)?;
&parsed
};
let (from, to, name) = css_variable_at(css_tree, css_text, at - base)?;
return Some(make(WebReferenceKind::CssVariable, base + from, base + to, name));
}
if g.spec.name != "html" {
return None;
}
// HTML attribute values.
let node = tree.root_node().descendant_for_byte_range(at, at)?;
let value = std::iter::successors(Some(node), |n| n.parent()).find(|n| n.kind() == "attribute_value")?;
let attribute = std::iter::successors(value.parent(), |n| n.parent()).find(|n| n.kind() == "attribute")?;
let attr_name = attribute.child(0).map(|n| text_of(n, text).to_ascii_lowercase())?;
let (vs, vtext) = (value.start_byte(), text_of(value, text));
match attr_name.as_str() {
"class" | "classname" | "class:list" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Class, from, from + token.len(), token.to_owned()))
}
"id" => {
let (from, token) = token_at(vtext, vs, at)?;
Some(make(WebReferenceKind::Id, from, from + token.len(), token.to_owned()))
}
"href" | "xlink:href" if vtext.len() > 1 && vtext.starts_with('#') => {
Some(make(WebReferenceKind::Anchor, vs, vs + vtext.len(), vtext[1..].to_owned()))
}
"style" => {
// An inline declaration list: parse it as the block of a rule.
let wrapped = format!("x{{{vtext}}}");
let t = parse(&css?.language, &wrapped, None)?;
let (from, to, name) = css_variable_at(&t, &wrapped, at - vs + 2)?;
Some(make(WebReferenceKind::CssVariable, vs + from - 2, vs + to - 2, name))
}
_ => None,
}
}
/// Elements whose `id` (or `<a name>`) is `name`: the targets of `href="#name"`.
pub(crate) fn anchors(tree: &Tree, text: &str, name: &str) -> Vec<Range> {
let idx = LineIndex::new(text);
let mut out = Vec::new();
walk(tree.root_node(), &mut |n| {
if n.kind() == "attribute" {
let attr = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase());
if matches!(attr.as_deref(), Some("id" | "name")) {
let mut found = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" && text_of(v, text) == name {
found = Some(v);
}
found.is_none()
});
if let Some(v) = found {
out.push(idx.range(v.start_byte(), v.end_byte()));
}
}
return false;
}
true
});
out
}
/// A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileReference {
pub range: Range,
pub value: String,
}
/// HTML attributes whose value is a URL.
const URL_ATTRIBUTES: &[&str] = &[
"href",
"src",
"srcset",
"action",
"formaction",
"poster",
"data",
"cite",
"background",
"manifest",
"xlink:href",
"longdesc",
"icon",
];
/// `url(…)` arguments and `@import` targets of a stylesheet: `(start, end)` byte ranges.
fn css_paths(tree: &Tree, css_text: &str, out: &mut Vec<(usize, usize)>) {
let target = |n: Node| -> Option<(usize, usize)> {
let n =
if n.kind() == "string_value" { n.named_child(0).filter(|c| c.kind() == "string_content")? } else { n };
matches!(n.kind(), "plain_value" | "string_content").then(|| (n.start_byte(), n.end_byte()))
};
walk(tree.root_node(), &mut |n| {
match n.kind() {
"import_statement" => {
if let Some(first) = n.named_child(0)
&& first.kind() == "string_value"
{
out.extend(target(first));
}
}
"call_expression" => {
let is_url =
n.named_child(0).is_some_and(|f| f.kind() == "function_name" && text_of(f, css_text) == "url");
if is_url
&& let Some(args) = n.child_by_field_name("arguments").or_else(|| n.named_child(1))
&& let Some(arg) = args.named_child(0)
{
out.extend(target(arg));
}
}
_ => {}
}
true
});
}
/// File paths written in an HTML document or a stylesheet.
pub(crate) fn file_references(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: &str) -> Vec<FileReference> {
let idx = LineIndex::new(text);
let mut spans: Vec<(usize, usize)> = Vec::new();
for (base, css_text) in css_regions(g.spec.name, tree, text) {
let parsed;
let css_tree = if g.spec.name == "css" {
tree
} else {
let Some(t) = css.and_then(|c| parse(&c.language, css_text, None)) else { continue };
parsed = t;
&parsed
};
let mut found = Vec::new();
css_paths(css_tree, css_text, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (base + s, base + e)));
}
if g.spec.name == "html" {
walk(tree.root_node(), &mut |n| {
if n.kind() != "attribute" {
return true;
}
let name = n.child(0).map(|a| text_of(a, text).to_ascii_lowercase()).unwrap_or_default();
let mut value = None;
walk(n, &mut |v| {
if v.kind() == "attribute_value" {
value = Some(v);
}
value.is_none()
});
let Some(v) = value else { return false };
let (vs, vtext) = (v.start_byte(), text_of(v, text));
match name.as_str() {
"srcset" => {
// `a.png 1x, b.png 2x`: the URL of each candidate.
let mut at = 0;
for part in vtext.split(',') {
let lead = part.len() - part.trim_start().len();
let url = part.split_whitespace().next().unwrap_or_default();
if !url.is_empty() {
spans.push((vs + at + lead, vs + at + lead + url.len()));
}
at += part.len() + 1;
}
}
"style" => {
let wrapped = format!("x{{{vtext}}}");
if let Some(t) = css.and_then(|c| parse(&c.language, &wrapped, None)) {
let mut found = Vec::new();
css_paths(&t, &wrapped, &mut found);
spans.extend(found.into_iter().map(|(s, e)| (vs + s - 2, vs + e - 2)));
}
}
_ if URL_ATTRIBUTES.contains(&name.as_str()) && !vtext.trim().is_empty() => {
spans.push((vs, vs + vtext.len()));
}
_ => {}
}
false
});
}
spans.sort_unstable();
spans.into_iter().map(|(s, e)| FileReference { range: idx.range(s, e), value: text[s..e].to_owned() }).collect()
}
+2
Переглянути файл
@@ -121,6 +121,7 @@ pub fn client_capabilities() -> Value {
"honorsChangeAnnotations": false
},
"codeLens": { "dynamicRegistration": false },
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
"formatting": { "dynamicRegistration": false },
"rangeFormatting": { "dynamicRegistration": false },
"rename": {
@@ -205,6 +206,7 @@ pub fn capability_key(method: &str) -> Option<&'static str> {
"textDocument/inlayHint" => "inlayHintProvider",
"textDocument/semanticTokens" | "textDocument/semanticTokens/full" => "semanticTokensProvider",
"textDocument/codeLens" => "codeLensProvider",
"textDocument/documentLink" => "documentLinkProvider",
"textDocument/prepareCallHierarchy" => "callHierarchyProvider",
"textDocument/prepareTypeHierarchy" => "typeHierarchyProvider",
_ => return None,
+91 -7
Переглянути файл
@@ -733,19 +733,34 @@ pub fn signature_help(conv_enc: Encoding, h: lsp::SignatureHelp) -> Option<Signa
// ---------------------------------------------------------------- decorations
pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
let label = match h.label {
lsp::InlayHintLabel::String(s) => s,
lsp::InlayHintLabel::LabelParts(parts) => parts.into_iter().map(|p| p.value).collect(),
let tooltip_text = |t: lsp::InlayHintTooltip| match t {
lsp::InlayHintTooltip::String(s) => s,
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
};
let (label, parts) = match h.label {
lsp::InlayHintLabel::String(s) => (s, Vec::new()),
lsp::InlayHintLabel::LabelParts(parts) => {
let label = parts.iter().map(|p| p.value.as_str()).collect();
let parts = parts
.into_iter()
.map(|p| InlayLabelPart {
value: p.value,
tooltip: p.tooltip.map(|t| match t {
lsp::InlayHintLabelPartTooltip::String(s) => s,
lsp::InlayHintLabelPartTooltip::MarkupContent(m) => m.value,
}),
location: p.location.as_ref().and_then(|l| conv.location(l)),
})
.collect();
(label, parts)
}
};
let kind = match h.kind {
Some(lsp::InlayHintKind::TYPE) => InlayKind::Type,
Some(lsp::InlayHintKind::PARAMETER) => InlayKind::Parameter,
_ => InlayKind::Other,
};
let tooltip = h.tooltip.map(|t| match t {
lsp::InlayHintTooltip::String(s) => s,
lsp::InlayHintTooltip::MarkupContent(m) => m.value,
});
let tooltip = h.tooltip.map(tooltip_text);
InlayHint {
position: conv.pos(path, h.position),
label,
@@ -753,6 +768,7 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
padding_left: h.padding_left.unwrap_or(false),
padding_right: h.padding_right.unwrap_or(false),
tooltip,
parts,
}
}
@@ -783,6 +799,27 @@ pub fn code_lens(conv: &Conv, path: &Path, l: lsp::CodeLens) -> CodeLens {
CodeLens { range: conv.range(path, l.range), command: l.command.map(command) }
}
pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<DocumentLink> {
let target = l.target?;
let target = target.as_str();
let (file, url) = match uri_to_path(target) {
Some(p) => (Some(p), None),
None => (None, Some(target.to_owned())),
};
let fragment = file
.as_ref()
.and_then(|_| target.split_once('#'))
.map(|(_, f)| percent_encoding::percent_decode_str(f).decode_utf8_lossy().into_owned())
.filter(|f| !f.is_empty());
Some(DocumentLink {
range: conv.range(path, l.range),
path: file.map(Into::into),
fragment,
url,
tooltip: l.tooltip,
})
}
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
let (path, uri) = uri_target(item.uri.as_str());
Some(HierarchyItem {
@@ -1111,5 +1148,52 @@ mod tests {
assert_eq!(h.label, ": Vec<u8>");
assert_eq!(h.kind, InlayKind::Type);
assert!(h.padding_left && !h.padding_right);
assert_eq!(h.parts.len(), 2);
assert!(h.parts.iter().all(|p| p.location.is_none()));
}
#[cfg(unix)]
#[test]
fn inlay_label_parts_keep_locations() {
let conv = Conv::utf16();
let h: lsp::InlayHint = serde_json::from_value(json!({
"position": {"line": 0, "character": 3},
"label": [
{"value": ": "},
{"value": "Foo", "tooltip": "struct Foo",
"location": {"uri": "file:///p/foo.rs", "range": {"start": {"line": 4, "character": 7}, "end": {"line": 4, "character": 10}}}}
]
}))
.unwrap();
let h = inlay_hint(&conv, Path::new("/a"), h);
assert_eq!(h.label, ": Foo");
let part = &h.parts[1];
assert_eq!(part.value, "Foo");
assert_eq!(part.tooltip.as_deref(), Some("struct Foo"));
let loc = part.location.as_ref().unwrap();
assert_eq!(loc.path, PathBuf::from("/p/foo.rs"));
assert_eq!(loc.range.start, p(4, 7));
assert_eq!(h.kind, InlayKind::Other);
}
#[cfg(unix)]
#[test]
fn document_links_split_file_targets_and_urls() {
let conv = Conv::utf16();
let link = |target: Option<&str>| {
serde_json::from_value::<lsp::DocumentLink>(json!({
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 15 } },
"target": target,
}))
.unwrap()
};
let here = Path::new("/p/index.html");
let file = document_link(&conv, here, link(Some("file:///p/a%20b.md#L12"))).unwrap();
assert_eq!(file.path.as_deref(), Some(Path::new("/p/a b.md")));
assert_eq!(file.fragment.as_deref(), Some("L12"));
assert_eq!(file.range, Range::new(p(0, 6), p(0, 15)));
let web = document_link(&conv, here, link(Some("https://example.com/#top"))).unwrap();
assert_eq!((web.path, web.url.as_deref(), web.fragment), (None, Some("https://example.com/#top"), None));
assert!(document_link(&conv, here, link(None)).is_none());
}
}
+3
Переглянути файл
@@ -179,6 +179,9 @@ impl LspManager {
ide_core::event::ServerStatus::Missing => {
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
}
ide_core::event::ServerStatus::Misconfigured => {
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
}
_ => format!("jdtls is not ready ({status:?})"),
}))
}
+3 -1
Переглянути файл
@@ -10,6 +10,8 @@ use std::sync::{Arc, OnceLock};
pub enum LaunchError {
/// The server binary is not installed / not on `PATH`.
Missing,
/// The configuration can't be launched (`LanguageServerConfig::launch_error`).
Config(String),
Failed(String),
}
@@ -72,7 +74,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
if !is_proxy || command.contains('/') {
return binary;
}
let works = std::process::Command::new(&binary)
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
.arg("--version")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
+68 -5
Переглянути файл
@@ -339,7 +339,7 @@ impl LspManager {
if let Some(message) = &cfg.launch_error {
// A missing binary still asks to be installed first.
let missing = !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Failed(message.clone()) });
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
})
@@ -358,6 +358,13 @@ impl LspManager {
}
return;
}
Err(LaunchError::Config(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
server.set_status(&self.sink, ide_core::event::ServerStatus::Misconfigured, Some(message));
}
return;
}
Err(LaunchError::Failed(message)) => {
tracing::warn!("{}: {message}", server.name);
if server.finish_start(generation, Conn::Failed) {
@@ -1415,6 +1422,52 @@ impl LspManager {
out.finish(Vec::new())
}
/// The document's links; ones without a target are resolved when the server can.
pub async fn document_links(&self, doc: DocId) -> IdeResult<Vec<DocumentLink>> {
let (snap, targets) = self.doc_targets(doc, "document links", |c| c.has("documentLinkProvider")).await?;
let requests = targets.iter().map(|t| {
let params = json!({ "textDocument": snap.ident() });
async move {
let links = self
.call::<_, Option<Vec<lsp::DocumentLink>>>(
t,
"textDocument/documentLink",
params,
None,
DEFAULT_TIMEOUT,
)
.await?
.unwrap_or_default();
if !t.caps().has_sub("documentLinkProvider", "resolveProvider") {
return Ok::<_, IdeError>((t, links));
}
let resolved = join_all(links.into_iter().map(|l| async move {
if l.target.is_some() {
return l;
}
let original = l.clone();
self.call::<_, lsp::DocumentLink>(t, "documentLink/resolve", l, None, DEFAULT_TIMEOUT)
.await
.unwrap_or(original)
}))
.await;
Ok((t, resolved))
}
});
let mut out = Outcome::new();
for r in join_all(requests).await {
match r {
Ok((t, links)) => {
let conv = self.conv(t.enc());
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(links.into_iter().filter_map(|l| convert::document_link(&conv, &snap.path, l)));
}
Err(e) => out.fail(e),
}
}
out.finish(Vec::new())
}
pub async fn call_hierarchy(
&self,
doc: DocId,
@@ -1425,8 +1478,9 @@ impl LspManager {
let t = &targets[0];
let items: Option<Vec<lsp::CallHierarchyItem>> =
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let mut out = Vec::new();
for item in items.unwrap_or_default() {
for item in items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
@@ -1467,12 +1521,13 @@ impl LspManager {
// and lsp-types mistypes `tags` (jdtls sends an array).
let items: Option<Vec<serde_json::Value>> =
self.call(t, "textDocument/prepareTypeHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let method = match direction {
HierarchyDirection::Incoming => "typeHierarchy/supertypes",
HierarchyDirection::Outgoing => "typeHierarchy/subtypes",
};
let mut out = Vec::new();
for item in items.unwrap_or_default() {
for item in items {
let related: Option<Vec<serde_json::Value>> =
self.call(t, method, json!({ "item": item }), None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
@@ -1604,8 +1659,10 @@ impl LspManager {
s.reset_for_restart();
self.ensure_started(&s);
}
// Missing / crashed servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing | ide_core::event::ServerStatus::Crashed => {
// Missing / crashed / misconfigured servers retry with the new configuration (e.g. a new PATH).
ide_core::event::ServerStatus::Missing
| ide_core::event::ServerStatus::Crashed
| ide_core::event::ServerStatus::Misconfigured => {
s.reset_for_restart();
self.ensure_started(&s);
}
@@ -1726,6 +1783,12 @@ fn source_actions_only(only: &[String]) -> bool {
!only.is_empty() && only.iter().all(|k| k == "source" || k.starts_with("source."))
}
/// Preparing a call / type hierarchy found no symbol at the position: the UI
/// then retries at the enclosing declaration.
fn no_hierarchy_target() -> IdeError {
IdeError::not_found("No symbol to show the hierarchy of at the caret")
}
#[cfg(test)]
mod send_check {
use super::*;
+28
Переглянути файл
@@ -195,6 +195,19 @@ pub struct InlayHint {
pub padding_left: bool,
pub padding_right: bool,
pub tooltip: Option<String>,
/// The label's parts when the server split it (empty for a plain label);
/// their values concatenate to `label`.
pub parts: Vec<InlayLabelPart>,
}
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InlayLabelPart {
pub value: String,
pub tooltip: Option<String>,
/// Declaration the part stands for (⌘-click navigates there).
pub location: Option<Location>,
}
/// Decoded semantic tokens (absolute positions) with the server legend applied.
@@ -214,6 +227,21 @@ pub struct CodeLens {
pub command: Option<Command>,
}
/// A link in a document (`textDocument/documentLink`): an HTML `href`, a
/// Markdown link, an `#include`, a JSON `$schema`…
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentLink {
pub range: Range,
/// A `file:` target.
pub path: Option<ide_core::IpcPath>,
/// The `#fragment` of a `file:` target (`L12`, `L12,5`, a heading or element id).
pub fragment: Option<String>,
/// Any other target (`https:`, …).
pub url: Option<String>,
pub tooltip: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HierarchyDirection {
+11 -4
Переглянути файл
@@ -710,13 +710,15 @@ async fn launch_error_fails_without_starting_the_server() {
h.mgr.set_config_hook(Box::new(|cfg, _| cfg.launch_error = Some("needs JDK 21".into())));
assert!(!h.mgr.serves_path(&h.root.join("a.mk")), "batch inspection skips it");
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Crashed).await;
// Not a crash: nothing ran, the configuration has to change.
h.wait_status("mock", ServerStatus::Misconfigured).await;
assert_eq!(h.launcher.state("mock").launches.load(Ordering::SeqCst), 0);
let crashed = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Crashed, message, .. } => message.clone(),
let reason = h.events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Misconfigured, message, .. } => message.clone(),
_ => None,
});
assert_eq!(crashed.as_deref(), Some("needs JDK 21"));
assert_eq!(reason.as_deref(), Some("needs JDK 21"));
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
}
#[tokio::test(flavor = "multi_thread")]
@@ -804,6 +806,11 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(hints[0].label, "x:");
assert_eq!(hints[0].kind, InlayKind::Parameter);
// Nothing to prepare at the position: NotFound, so the UI can retry at the enclosing declaration.
s.respond("textDocument/prepareCallHierarchy", json!(null));
let err = h.mgr.call_hierarchy(doc, Pos::new(0, 1), HierarchyDirection::Incoming).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
s.respond("textDocument/prepareCallHierarchy", json!([item]));
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
+1 -1
Переглянути файл
@@ -124,7 +124,7 @@ async fn rust_analyzer_end_to_end() {
mgr.did_open(doc, &main, &LanguageId::new("rust"), 1, MAIN_RS);
retry("rust-analyzer ready", Duration::from_secs(60), || {
let s = last_status(&events, "rust-analyzer");
if let Some((ServerStatus::Crashed | ServerStatus::Missing, msg)) = &s {
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &s {
panic!("rust-analyzer failed: {msg:?}");
}
async move { matches!(s, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
+1 -1
Переглянути файл
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
if !data.is_file() {
return Err(nothing_recorded("perf wrote no data"));
}
let out = Command::new(perf)
let out = ide_core::process::no_window(&mut Command::new(perf))
.args(["script", "-i"])
.arg(data.as_ref() as &Path)
.current_dir(cwd)
+1
Переглянути файл
@@ -232,6 +232,7 @@ mod tests {
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+7
Переглянути файл
@@ -11,6 +11,7 @@
//! env = { RUST_LOG = "debug" }
//! is-test = false
//! debug-adapter = "codelldb"
//! allow-parallel = true
//! ```
use crate::RunConfig;
@@ -51,6 +52,8 @@ struct FileConfig {
is_test: bool,
#[serde(alias = "debugAdapter", alias = "debug_adapter")]
debug_adapter: Option<String>,
#[serde(default, alias = "allowParallel", alias = "allow_parallel")]
allow_parallel: bool,
}
fn slug(s: &str) -> String {
@@ -91,6 +94,7 @@ pub(crate) fn load(root: &Path) -> IdeResult<Vec<RunConfig>> {
detected: false,
is_test: c.is_test,
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
allow_parallel: c.allow_parallel,
});
}
Ok(out)
@@ -121,6 +125,9 @@ fn to_table(c: &RunConfig) -> Table {
if let Some(adapter) = &c.debug_adapter {
t.insert("debug-adapter", value(adapter));
}
if c.allow_parallel {
t.insert("allow-parallel", value(true));
}
t
}
+1
Переглянути файл
@@ -37,6 +37,7 @@ fn config(id: impl Into<String>, name: impl Into<String>, kind: &str, command: &
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+4
Переглянути файл
@@ -34,6 +34,10 @@ pub struct RunConfig {
pub is_test: bool,
/// DAP adapter that can debug this config, if any.
pub debug_adapter: Option<String>,
/// "Allow multiple instances": Run on a running config starts another one instead of restarting it.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub allow_parallel: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+2 -3
Переглянути файл
@@ -205,8 +205,7 @@ impl ProcessManager {
{
use std::os::windows::process::CommandExt;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | ide_core::process::CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().map_err(|e| match e.kind() {
@@ -400,7 +399,7 @@ fn kill_tree(pid: u32, _force: bool) {
// Console children have no reliable graceful signal from outside their console.
let _ = Command::new("taskkill")
.args(["/T", "/F", "/PID", &pid.to_string()])
.creation_flags(0x0800_0000)
.creation_flags(ide_core::process::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
+2 -1
Переглянути файл
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
let Some((program, args)) = argv.split_first() else { return false };
let program = resolve(program, config);
Command::new(program)
ide_core::process::no_window(&mut Command::new(program))
.args(args)
.current_dir(dir)
.envs(&config.env)
@@ -260,6 +260,7 @@ mod tests {
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+2
Переглянути файл
@@ -16,6 +16,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: false,
debug_adapter: Some("codelldb".into()),
allow_parallel: true,
},
RunConfig {
id: "user:tests".into(),
@@ -28,6 +29,7 @@ fn sample() -> Vec<RunConfig> {
detected: false,
is_test: true,
debug_adapter: None,
allow_parallel: false,
},
]
}
+1
Переглянути файл
@@ -42,6 +42,7 @@ fn cfg(id: &str, command: &str, args: &[&str]) -> RunConfig {
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
+22 -6
Переглянути файл
@@ -56,14 +56,30 @@ fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.go.goroot)
}
/// The project JDK (`languages.java.jdk`): a JDK home, its `bin` or its `bin/java`.
/// A JDK setting: a JDK home, its `bin` or its `bin/java`.
fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathBuf>> {
let p = setting_path(root, value)?;
Some(p.ancestors().take(3).find_map(crate::java::jdk_at).ok_or(p))
}
/// The project JDK (`languages.java.jdk`).
pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {
let p = setting_path(root, &s.languages.java.jdk)?;
let jdk = p.ancestors().take(3).find_map(crate::java::jdk_at);
if jdk.is_none() {
tracing::warn!("project JDK {} is not a JDK home", p.display());
jdk_setting(root, &s.languages.java.jdk)?
.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display()))
.ok()
}
/// The JDK chosen to run jdtls (`languages.java.jdtlsJdk`): `Ok(None)` when not
/// set, `Err` (the message) when it is not a JDK home.
pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>, String> {
match jdk_setting(root, &s.languages.java.jdtls_jdk) {
None => Ok(None),
Some(Ok(jdk)) => Ok(Some(jdk)),
Some(Err(p)) => Err(format!(
"The language server JDK {} is not a JDK home (Settings › Languages & Frameworks › Java).",
p.display()
)),
}
jdk
}
/// `mvn` of the configured Maven home (`languages.java.maven.home`): the
+2 -1
Переглянути файл
@@ -44,7 +44,7 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
/// on success; `None` on failure or after `timeout`.
pub(crate) fn query(program: &Path, args: &[&str], timeout: Duration) -> Option<String> {
let mut child = Command::new(program)
let mut child = ide_core::process::no_window(&mut Command::new(program))
.args(args)
.env("PATH", search_path())
.stdin(Stdio::null())
@@ -96,6 +96,7 @@ pub(crate) fn stream(
on_line: &dyn Fn(String),
) -> IdeResult<String> {
let mut cmd = Command::new(program);
ide_core::process::no_window(&mut cmd);
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.envs(env.iter().map(|(k, v)| (k, v)));
if let Some(cwd) = cwd {
+94 -17
Переглянути файл
@@ -265,7 +265,8 @@ const METADATA_PROPERTY: &str = "java.import.generatesMetadataFilesAtProjectRoot
/// the project; it runs on a JDK `min_java`+ (via `JAVA_HOME`, which its
/// launcher reads), installed JDKs are registered as runtimes and `bundles`
/// (e.g. the java-debug plugin jar) are loaded into the server. The project
/// JDK, when set, is the default runtime and preferred for running the server.
/// JDK, when set, is the default runtime and preferred for running the server;
/// `server_jdk` (the user's choice for the server alone) overrides that.
#[allow(clippy::too_many_arguments)]
pub fn configure_jdtls(
cfg: &mut LanguageServerConfig,
@@ -273,6 +274,7 @@ pub fn configure_jdtls(
data_dir: &Path,
jdks: &[Jdk],
project_jdk: Option<&Jdk>,
server_jdk: Option<&Jdk>,
min_java: u32,
bundles: &[PathBuf],
lombok: Option<&Path>,
@@ -303,15 +305,24 @@ pub fn configure_jdtls(
{
cfg.args.push(format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy()));
}
let jdks: Vec<Jdk> =
project_jdk.into_iter().chain(jdks.iter().filter(|j| Some(*j) != project_jdk)).cloned().collect();
let jdks = jdks.as_slice();
let mut all: Vec<Jdk> = Vec::new();
for j in project_jdk.into_iter().chain(jdks).chain(server_jdk) {
if !all.contains(j) {
all.push(j.clone());
}
}
let jdks = all.as_slice();
if !cfg.env.contains_key("JAVA_HOME") {
match jdtls_runtime(jdks, min_java) {
Some(jdk) => {
let runtime = match server_jdk {
Some(jdk) if jdk.major < min_java => Err(server_jdk_too_old_message(jdk, min_java)),
Some(jdk) => Ok(jdk),
None => jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java)),
};
match runtime {
Ok(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
}
None => cfg.launch_error = Some(missing_runtime_message(jdks, min_java)),
Err(e) => cfg.launch_error = Some(e),
}
}
let mut runtimes = runtimes(jdks);
@@ -348,6 +359,15 @@ fn missing_runtime_message(jdks: &[Jdk], min_java: u32) -> String {
)
}
fn server_jdk_too_old_message(jdk: &Jdk, min_java: u32) -> String {
format!(
"The language server JDK ({}, JDK {}) is too old: jdtls needs JDK {min_java} or newer. Choose another \
one in Settings › Languages & Frameworks › Java, or set it to Auto.",
jdk.home.display(),
jdk.major
)
}
/// The `java` launcher of a JDK home.
pub fn java_executable(home: &Path) -> PathBuf {
home.join("bin").join(crate::exe("java"))
@@ -450,6 +470,7 @@ mod tests {
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
@@ -474,6 +495,7 @@ mod tests {
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
@@ -489,6 +511,7 @@ mod tests {
Path::new("/data"),
&jdks,
Some(&project),
None,
JDTLS_MIN_JAVA,
&[],
None,
@@ -499,7 +522,17 @@ mod tests {
assert_eq!(cfg.env["JAVA_HOME"], "/jdk21b");
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(&mut other, Path::new("/p"), Path::new("/data"), &jdks, None, JDTLS_MIN_JAVA, &bundles, None);
configure_jdtls(
&mut other,
Path::new("/p"),
Path::new("/data"),
&jdks,
None,
None,
JDTLS_MIN_JAVA,
&bundles,
None,
);
assert!(other.args.is_empty() && other.initialization_options.is_none());
}
@@ -508,23 +541,23 @@ mod tests {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jar = Path::new("/m2/lombok-1.18.48.jar");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
let agent = format!("--jvm-arg=-javaagent:{}", jar.to_string_lossy());
assert!(cfg.args.contains(&agent), "{:?}", cfg.args);
let mut plain = jdtls();
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert_ne!(cfg.args[1], plain.args[1], "a separate workspace, so everything is rebuilt with the agent");
let before = cfg.clone();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
assert_eq!(cfg, before, "idempotent");
let mut cfg = jdtls();
cfg.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], Some(jar));
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
assert!(!cfg.args.contains(&agent), "the user's agent wins");
let mut own = jdtls();
own.args.push("--jvm-arg=-javaagent:/own/lombok.jar".into());
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut own, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!(cfg.args, own.args, "its workspace follows the agent in use");
}
@@ -533,19 +566,19 @@ mod tests {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let old = [Jdk { major: 17, home: PathBuf::from("/jdk17") }, Jdk { major: 8, home: PathBuf::from("/jdk8") }];
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 21 or newer") && err.contains("found JDK 8, 17"), "{err}");
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
assert!(cfg.launch_error.unwrap().contains("no JDK was found"));
// An explicit JAVA_HOME is the user's call.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), "/custom".into());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, JDTLS_MIN_JAVA, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &old, None, None, JDTLS_MIN_JAVA, &[], None);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/custom", None));
let mixed = [old[0].clone(), Jdk { major: 21, home: PathBuf::from("/jdk21") }];
@@ -553,11 +586,55 @@ mod tests {
// A jdtls whose bundles need 25 doesn't start on 21, and says what it needs.
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, 25, &[], None);
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &mixed, None, None, 25, &[], None);
let err = cfg.launch_error.unwrap();
assert!(err.contains("JDK 25 or newer") && err.contains("found JDK 17, 21"), "{err}");
}
#[test]
fn jdtls_runs_on_the_chosen_server_jdk() {
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let jdk = |major: u32, home: &str| Jdk { major, home: PathBuf::from(home) };
let installed = [jdk(25, "/jdk25"), jdk(21, "/jdk21"), jdk(17, "/jdk17")];
let project = jdk(17, "/jdk17");
let run = |server: Option<&Jdk>, min_java: u32| {
let mut cfg = jdtls();
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
&installed,
Some(&project),
server,
min_java,
&[],
None,
);
cfg
};
// Project on JDK 17, server on the chosen 21: each keeps its own JDK.
let cfg = run(Some(&jdk(21, "/jdk21")), JDTLS_MIN_JAVA);
assert_eq!((cfg.env["JAVA_HOME"].as_str(), cfg.launch_error), ("/jdk21", None));
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[0], json!({ "name": "JavaSE-17", "path": "/jdk17", "default": true }), "still compiles on 17");
// Not set: the first installed JDK new enough, as before.
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], "/jdk25");
// A chosen JDK outside the scanned locations.
let own = jdk(25, "/opt/own-jdk");
let cfg = run(Some(&own), 25);
assert_eq!(cfg.env["JAVA_HOME"], "/opt/own-jdk");
// Too old for this jdtls: the user's choice is not overridden, it is explained.
let cfg = run(Some(&jdk(21, "/jdk21")), 25);
assert!(!cfg.env.contains_key("JAVA_HOME"));
let err = cfg.launch_error.unwrap();
assert!(err.contains("/jdk21") && err.contains("JDK 25 or newer"), "{err}");
}
#[test]
fn bundle_manifests_give_the_java_jdtls_needs() {
let ee = |m: &str| manifest_min_java(m);
+21 -1
Переглянути файл
@@ -1,5 +1,5 @@
use crate::apply::{
apply_to_run_configs, configure_server, maven_command, maven_options, project_jdk, python_interpreter,
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
terminal_activation, tsdk,
};
use crate::python::parse_pip_list;
@@ -46,6 +46,7 @@ fn run(kind: &str, command: &str, args: &[&str]) -> RunConfig {
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
}
}
@@ -202,6 +203,25 @@ fn project_jdk_and_maven_settings() {
assert_eq!(project_jdk(tmp.path(), &s), None);
}
#[test]
fn jdtls_jdk_setting() {
if cfg!(windows) {
return; // Unix paths
}
let tmp = tempfile::tempdir().unwrap();
fake_jdk(&tmp.path().join("jdk17"));
let mut s = Settings::default();
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
// Separate from the project JDK, which run configurations keep using.
s.languages.java.jdk = "jdk17".into();
assert_eq!(jdtls_jdk(tmp.path(), &s), Ok(None));
s.languages.java.jdtls_jdk = "jdk17/bin".into();
assert_eq!(jdtls_jdk(tmp.path(), &s).unwrap().map(|j| j.major), Some(17));
// A chosen path that is not a JDK is an error, not a silent fallback.
s.languages.java.jdtls_jdk = "missing".into();
assert!(jdtls_jdk(tmp.path(), &s).unwrap_err().contains("is not a JDK home"));
}
#[test]
fn terminal_activation_for_project_venv() {
if cfg!(windows) {
+1
Переглянути файл
@@ -35,6 +35,7 @@ fn query(pattern: &str, is_regex: bool) -> SearchQuery {
exclude: vec![],
scope: SearchScope::Project,
max_matches: 0,
context: Default::default(),
}
}
+50 -6
Переглянути файл
@@ -4,7 +4,10 @@ use crate::iter::for_each_match;
use crate::line::line_match;
use crate::mask::FileMask;
use crate::query::{Compiled, line_terminator};
use crate::{FileMatches, LineMatch, Overlay, PathFilter, SearchScope, SearchSummary};
use crate::{
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, Overlay, PathFilter, SearchContext, SearchScope,
SearchSummary,
};
use grep_regex::RegexMatcher;
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
use ide_core::{CancellationToken, IdeError, IdeResult};
@@ -25,6 +28,8 @@ pub(crate) struct Request<'a> {
pub compiled: Compiled,
pub mask: FileMask,
pub filter: Option<PathFilter<'a>>,
pub context: SearchContext,
pub literals: Option<Literals<'a>>,
pub max_matches: u32,
pub overlay: Overlay<'a>,
pub cancel: &'a CancellationToken,
@@ -86,6 +91,8 @@ struct Ctx<'a> {
root: &'a Path,
mask: &'a FileMask,
filter: Option<PathFilter<'a>>,
context: SearchContext,
literals: Option<Literals<'a>>,
overlay: Overlay<'a>,
on_file: &'a (dyn Fn(FileMatches) + Sync),
ctl: Control<'a>,
@@ -98,6 +105,8 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
root: req.root,
mask: &req.mask,
filter: req.filter,
context: req.context,
literals: if req.context == SearchContext::Any { None } else { req.literals },
overlay: req.overlay,
on_file: req.on_file,
ctl: Control {
@@ -225,6 +234,25 @@ impl Ctx<'_> {
if !self.mask.matches(&rel) || self.filter.is_some_and(|keep| !keep(&rel)) {
return;
}
// The search context needs the whole text to find comments and string literals.
let in_context = match self.literals {
Some(literals) => {
let text = match (self.overlay)(path) {
Some(text) => text,
// Unreadable or not UTF-8 (binary): nothing to classify.
None => match std::fs::read_to_string(path) {
Ok(text) => text,
Err(_) => return,
},
};
let ranges = literals(path, &text);
if ranges.is_none() && self.context.needs_literals() {
return;
}
Some((text, ranges.unwrap_or_default()))
}
None => None,
};
let mut sink = FileSink {
matcher,
ctl: &self.ctl,
@@ -234,12 +262,16 @@ impl Ctx<'_> {
ticks: 0,
found: Vec::new(),
ranges: Vec::new(),
context: in_context.as_ref().map(|(_, ranges)| (self.context, ranges.as_slice())),
};
let result = match (self.overlay)(path) {
Some(text) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
None => match std::fs::File::open(path) {
Ok(file) => searcher.search_reader(matcher, StopReader { inner: file, ctl: &self.ctl }, &mut sink),
Err(err) => Err(err),
let result = match &in_context {
Some((text, _)) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
None => match (self.overlay)(path) {
Some(text) => searcher.search_slice(matcher, text.as_bytes(), &mut sink),
None => match std::fs::File::open(path) {
Ok(file) => searcher.search_reader(matcher, StopReader { inner: file, ctl: &self.ctl }, &mut sink),
Err(err) => Err(err),
},
},
};
if let Err(err) = result {
@@ -288,6 +320,14 @@ struct FileSink<'a> {
/// Scratch buffers reused across lines.
found: Vec<(usize, usize)>,
ranges: Vec<(usize, usize)>,
/// Search context filter and the file's comments / string literals.
context: Option<(SearchContext, &'a [LiteralRange])>,
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
let i = literals.partition_point(|l| l.start <= pos);
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
}
impl Sink for FileSink<'_> {
@@ -311,6 +351,10 @@ impl Sink for FileSink<'_> {
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
found.push((mm.start() - range.start, mm.end() - range.start));
});
if let Some((context, literals)) = self.context {
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
}
let mut next = found.iter().copied().peekable();
let mut line_start = 0;
+72
Переглянути файл
@@ -41,8 +41,64 @@ pub struct SearchQuery {
pub scope: SearchScope,
/// Stop after this many matches overall (0 = 10 000).
pub max_matches: u32,
/// Where in the code a match may lie (IDEA's search context filter).
#[serde(default)]
#[specta(optional)]
pub context: SearchContext,
}
/// IDEA's search context: matches anywhere, only in, or outside comments and
/// string literals. Files whose language has no syntax tree contain neither.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SearchContext {
#[default]
Any,
InComments,
InStringLiterals,
ExceptComments,
ExceptStringLiterals,
ExceptCommentsAndStringLiterals,
}
/// What a [`LiteralRange`] is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiteralKind {
Comment,
String,
}
/// Byte range of a comment or string literal in a file's text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LiteralRange {
pub start: usize,
pub end: usize,
pub kind: LiteralKind,
}
impl SearchContext {
/// Whether a match starting in `kind` (`None`: plain code) is kept.
pub fn accepts(self, kind: Option<LiteralKind>) -> bool {
match self {
Self::Any => true,
Self::InComments => kind == Some(LiteralKind::Comment),
Self::InStringLiterals => kind == Some(LiteralKind::String),
Self::ExceptComments => kind != Some(LiteralKind::Comment),
Self::ExceptStringLiterals => kind != Some(LiteralKind::String),
Self::ExceptCommentsAndStringLiterals => kind.is_none(),
}
}
/// Only matches inside comments / string literals: files without any are skipped.
fn needs_literals(self) -> bool {
matches!(self, Self::InComments | Self::InStringLiterals)
}
}
/// Comments and string literals of a file's text (sorted, non-overlapping),
/// or `None` when its language has no syntax tree.
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SearchScope {
@@ -131,6 +187,20 @@ pub fn search_filtered(
overlay: Overlay<'_>,
cancel: &CancellationToken,
on_file: &(dyn Fn(FileMatches) + Sync),
) -> IdeResult<SearchSummary> {
search_in_context(root, query, filter, None, overlay, cancel, on_file)
}
/// [`search_filtered`] honouring [`SearchQuery::context`] with the comments and
/// string literals `literals` finds; without it every match is plain code.
pub fn search_in_context(
root: &Path,
query: &SearchQuery,
filter: Option<PathFilter<'_>>,
literals: Option<Literals<'_>>,
overlay: Overlay<'_>,
cancel: &CancellationToken,
on_file: &(dyn Fn(FileMatches) + Sync),
) -> IdeResult<SearchSummary> {
let mask = FileMask::new(&query.include, &query.exclude)?;
if query.pattern.is_empty() {
@@ -142,6 +212,8 @@ pub fn search_filtered(
compiled: query::compile(query)?,
mask,
filter,
context: query.context,
literals,
max_matches: query.max_matches,
overlay,
cancel,
+1
Переглянути файл
@@ -97,6 +97,7 @@ mod tests {
exclude: vec![],
scope: SearchScope::Project,
max_matches: 0,
context: Default::default(),
}
}
+1
Переглянути файл
@@ -17,6 +17,7 @@ fn query(pattern: &str) -> SearchQuery {
exclude: vec![],
scope: SearchScope::Project,
max_matches: 0,
context: Default::default(),
}
}
+73
Переглянути файл
@@ -27,6 +27,7 @@ fn query(pattern: &str) -> SearchQuery {
exclude: vec![],
scope: SearchScope::Project,
max_matches: 0,
context: Default::default(),
}
}
@@ -548,3 +549,75 @@ fn file_set_scope_applies_the_path_filter() {
let (all, _) = run(p.path(), &q);
assert_eq!(paths(&all), vec!["README.md", "src/main/java/App.java", "src/test/java/AppTest.java"]);
}
/// Test classifier: `//` to end of line is a comment, `"…"` a string (only in `.rs` files).
fn toy_literals(path: &Path, text: &str) -> Option<Vec<ide_search::LiteralRange>> {
use ide_search::{LiteralKind, LiteralRange};
if path.extension().is_none_or(|e| e != "rs") {
return None;
}
let mut out = Vec::new();
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i..].starts_with(b"//") {
let end = memchr_newline(bytes, i);
out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment });
i = end;
} else if bytes[i] == b'"' {
let end = bytes[i + 1..].iter().position(|&b| b == b'"').map_or(bytes.len(), |p| i + p + 2);
out.push(LiteralRange { start: i, end, kind: LiteralKind::String });
i = end;
} else {
i += 1;
}
}
Some(out)
}
fn memchr_newline(bytes: &[u8], from: usize) -> usize {
bytes[from..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |p| from + p)
}
/// `(rel_path, line, ranges)` of every matched line.
type Row = (String, u32, Vec<(u32, u32)>);
fn run_context(root: &Path, context: ide_search::SearchContext) -> Vec<Row> {
let out = Mutex::new(Vec::new());
let q = SearchQuery { context, ..query("foo") };
ide_search::search_in_context(root, &q, None, Some(&toy_literals), &|_| None, &CancellationToken::new(), &|f| {
out.lock().unwrap().push(f)
})
.unwrap();
let mut rows: Vec<_> = out
.into_inner()
.unwrap()
.into_iter()
.flat_map(|f| f.matches.into_iter().map(move |m| (f.rel_path.clone(), m.line, m.ranges)))
.collect();
rows.sort();
rows
}
#[test]
fn search_context_filters_comments_and_strings() {
use ide_search::SearchContext as C;
let p = project(&[("a.rs", b"foo(\"foo\"); // foo\nfoo\n"), ("b.txt", b"foo // foo\n")]);
let rows = |c| run_context(p.path(), c);
let s = |r: &str, l: u32, ranges: &[(u32, u32)]| (r.to_owned(), l, ranges.to_vec());
assert_eq!(
rows(C::Any),
vec![s("a.rs", 0, &[(0, 3), (5, 8), (15, 18)]), s("a.rs", 1, &[(0, 3)]), s("b.txt", 0, &[(0, 3), (7, 10)])]
);
assert_eq!(rows(C::InComments), vec![s("a.rs", 0, &[(15, 18)])]);
assert_eq!(rows(C::InStringLiterals), vec![s("a.rs", 0, &[(5, 8)])]);
// Files without a syntax tree have no comments or strings.
assert_eq!(
rows(C::ExceptComments),
vec![s("a.rs", 0, &[(0, 3), (5, 8)]), s("a.rs", 1, &[(0, 3)]), s("b.txt", 0, &[(0, 3), (7, 10)])]
);
assert_eq!(
rows(C::ExceptCommentsAndStringLiterals),
vec![s("a.rs", 0, &[(0, 3)]), s("a.rs", 1, &[(0, 3)]), s("b.txt", 0, &[(0, 3), (7, 10)])]
);
}
+188 -3
Переглянути файл
@@ -32,7 +32,7 @@ const KILL_GRACE: Duration = Duration::from_millis(1500);
#[serde(rename_all = "camelCase")]
pub struct TerminalOptions {
pub cwd: ide_core::IpcPath,
/// Defaults to the user's login shell (`$SHELL`, or `COMSPEC` on Windows).
/// Defaults to the user's login shell (passwd entry, then `$SHELL`; PowerShell or `COMSPEC` on Windows).
pub shell: Option<String>,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
@@ -160,6 +160,19 @@ impl TerminalManager {
Ok(())
}
/// Whether the shell is running a command, so closing its tab should ask first
/// (as IDEA does). On Unix: the PTY's foreground process
/// group isn't the shell's, i.e. a job is in the foreground (background helpers
/// such as prompt daemons don't count). On Windows: the shell has child processes.
pub fn is_busy(&self, id: TerminalId) -> IdeResult<bool> {
let session = self.session(id)?;
if session.exited.load(Ordering::Acquire) {
return Ok(false);
}
let Some(pid) = session.info.pid else { return Ok(false) };
Ok(foreground_busy(&session, pid))
}
pub fn list(&self) -> Vec<TerminalInfo> {
let mut out: Vec<TerminalInfo> = self.sessions.lock().values().map(|s| s.info.clone()).collect();
out.sort_by_key(|i| i.id);
@@ -191,6 +204,76 @@ fn not_found(id: TerminalId) -> IdeError {
IdeError::not_found(format!("no such terminal: {id}"))
}
#[cfg(unix)]
fn foreground_busy(session: &Session, pid: u32) -> bool {
let leader = session.master.lock().process_group_leader();
leader.is_some_and(|fg| u32::try_from(fg).ok() != Some(pid))
}
#[cfg(windows)]
fn foreground_busy(_session: &Session, pid: u32) -> bool {
win::has_child_processes(pid)
}
#[cfg(not(any(unix, windows)))]
fn foreground_busy(_session: &Session, _pid: u32) -> bool {
false
}
#[cfg(windows)]
mod win {
use std::ffi::c_void;
const TH32CS_SNAPPROCESS: u32 = 0x2;
const INVALID_HANDLE_VALUE: isize = -1;
/// `PROCESSENTRY32W` from `<tlhelp32.h>`.
#[repr(C)]
struct ProcessEntry32W {
dw_size: u32,
cnt_usage: u32,
th32_process_id: u32,
th32_default_heap_id: usize,
th32_module_id: u32,
cnt_threads: u32,
th32_parent_process_id: u32,
pc_pri_class_base: i32,
dw_flags: u32,
sz_exe_file: [u16; 260],
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> *mut c_void;
fn Process32FirstW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
fn Process32NextW(snapshot: *mut c_void, entry: *mut ProcessEntry32W) -> i32;
fn CloseHandle(handle: *mut c_void) -> i32;
}
pub fn has_child_processes(pid: u32) -> bool {
// SAFETY: plain Win32 calls on a locally owned snapshot handle and entry buffer.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if snapshot.is_null() || snapshot as isize == INVALID_HANDLE_VALUE {
return false;
}
let mut entry: ProcessEntry32W = std::mem::zeroed();
entry.dw_size = std::mem::size_of::<ProcessEntry32W>() as u32;
let mut found = false;
let mut ok = Process32FirstW(snapshot, &mut entry);
while ok != 0 {
if entry.th32_parent_process_id == pid && entry.th32_process_id != pid {
found = true;
break;
}
ok = Process32NextW(snapshot, &mut entry);
}
CloseHandle(snapshot);
found
}
}
}
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
if session.exited.load(Ordering::Acquire) {
@@ -359,6 +442,48 @@ pub fn default_shell_path() -> String {
default_shell()
}
/// Installed shells for "New Predefined Session", the login shell first. On
/// Unix: `/etc/shells` plus `$PATH`, so Homebrew shells show up too.
pub fn available_shells() -> Vec<String> {
let mut found: Vec<PathBuf> = Vec::new();
let mut add = |p: PathBuf| {
let key = p.canonicalize().unwrap_or_else(|_| p.clone());
if p.is_file() && !found.iter().any(|f| f.canonicalize().unwrap_or_else(|_| f.clone()) == key) {
found.push(p);
}
};
add(PathBuf::from(default_shell()));
#[cfg(unix)]
{
const NAMES: [&str; 5] = ["zsh", "bash", "fish", "nu", "pwsh"];
let listed = std::fs::read_to_string("/etc/shells").unwrap_or_default();
for name in NAMES {
for line in listed.lines().map(str::trim).filter(|l| l.starts_with('/')) {
if shell_title(line) == name {
add(PathBuf::from(line));
}
}
if let Some(p) = find_in_path(name) {
add(p);
}
}
}
#[cfg(windows)]
{
for exe in ["pwsh.exe", "powershell.exe", "cmd.exe", "wsl.exe"] {
if let Some(p) = find_in_path(exe) {
add(p);
}
}
for var in ["ProgramFiles", "ProgramW6432"] {
if let Some(dir) = std::env::var_os(var) {
add(PathBuf::from(dir).join("Git").join("bin").join("bash.exe"));
}
}
}
found.into_iter().map(|p| p.to_string_lossy().into_owned()).collect()
}
/// Picks the shell binary and its arguments. A default (or explicitly chosen but
/// argument-less) POSIX shell is started as a login shell, like Terminal.app/IDEA.
fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>) {
@@ -372,14 +497,34 @@ fn resolve_shell(shell: Option<&str>, args: &[String]) -> (String, Vec<String>)
(shell, args)
}
/// The account's login shell comes first: `$SHELL` is inherited from whatever
/// launched the app (a terminal running another shell, `tauri dev`), so it may
/// not be the shell the user picked.
#[cfg(unix)]
fn default_shell() -> String {
if let Some(shell) = std::env::var("SHELL").ok().filter(|s| !s.is_empty() && Path::new(s).exists()) {
let usable = |s: &String| !s.is_empty() && Path::new(s).exists();
if let Some(shell) = login_shell().filter(usable).or_else(|| std::env::var("SHELL").ok().filter(usable)) {
return shell;
}
["/bin/zsh", "/bin/bash", "/bin/sh"].into_iter().find(|p| Path::new(p).exists()).unwrap_or("/bin/sh").to_owned()
}
/// `pw_shell` of the current user's passwd entry.
#[cfg(unix)]
fn login_shell() -> Option<String> {
let mut buf = vec![0 as libc::c_char; 4096];
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut result: *mut libc::passwd = std::ptr::null_mut();
// SAFETY: every pointer refers to a live local buffer of the stated size.
let rc = unsafe { libc::getpwuid_r(libc::getuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result) };
if rc != 0 || result.is_null() || pwd.pw_shell.is_null() {
return None;
}
// SAFETY: on success `pw_shell` is a NUL-terminated string inside `buf`.
let shell = unsafe { std::ffi::CStr::from_ptr(pwd.pw_shell) };
Some(shell.to_string_lossy().into_owned())
}
#[cfg(windows)]
fn default_shell() -> String {
for candidate in ["pwsh.exe", "powershell.exe"] {
@@ -390,7 +535,6 @@ fn default_shell() -> String {
std::env::var("COMSPEC").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "cmd.exe".to_owned())
}
#[cfg(windows)]
fn find_in_path(exe: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|dir| dir.join(exe)).find(|p| p.is_file())
@@ -421,6 +565,22 @@ fn terminal_env(user: &BTreeMap<String, String>) -> BTreeMap<String, String> {
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn login_shell_reads_the_passwd_entry() {
let shell = login_shell().expect("passwd entry");
assert!(shell.starts_with('/'), "{shell}");
}
#[cfg(unix)]
#[test]
fn available_shells_start_with_the_default_and_are_distinct() {
let shells = available_shells();
assert_eq!(shells.first(), Some(&default_shell_path()));
let unique: std::collections::HashSet<_> = shells.iter().collect();
assert_eq!(unique.len(), shells.len());
}
use std::sync::mpsc::Receiver;
struct Harness {
@@ -573,6 +733,31 @@ mod tests {
assert!(h.manager.kill(info.id).is_err());
}
#[test]
fn busy_while_a_command_runs_in_the_foreground() {
let h = harness();
let mut opts = sh("");
opts.args = vec!["-i".into()];
opts.env.insert("PS1".into(), "$ ".into());
opts.env.insert("ENV".into(), "/dev/null".into());
let (info, _rx) = spawn_collect(&h, opts);
let wait_for = |want: bool| {
let deadline = Instant::now() + Duration::from_secs(10);
while h.manager.is_busy(info.id).unwrap() != want {
assert!(Instant::now() < deadline, "is_busy never became {want}");
std::thread::sleep(Duration::from_millis(20));
}
};
wait_for(false);
h.manager.write(info.id, "sleep 30\n").unwrap();
wait_for(true);
h.manager.write(info.id, "\u{3}").unwrap();
wait_for(false);
h.manager.write(info.id, "exit\n").unwrap();
let _ = wait_exit(&h, info.id);
assert!(h.manager.is_busy(info.id).is_err());
}
#[test]
fn large_output_is_batched_and_complete() {
let h = harness();
+1 -1
Переглянути файл
@@ -113,7 +113,7 @@ fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
/// `.tar.xz` goes through the system `tar` (bsdtar on macOS/Windows, GNU tar + xz on Linux).
fn extract_tar_xz(archive: &Path, dest: &Path) -> IdeResult<()> {
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack .tar.xz archives"))?;
let out = std::process::Command::new(tar)
let out = ide_core::process::no_window(&mut std::process::Command::new(tar))
.arg("-xJf")
.arg(archive)
.arg("-C")
+1 -1
Переглянути файл
@@ -311,7 +311,7 @@ impl Tools {
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
cmd.env("PATH", &self.child_path);
ide_core::process::no_window(&mut cmd).env("PATH", &self.child_path);
cmd
}
+3 -2
Переглянути файл
@@ -48,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
let (tx, rx) = mpsc::channel::<String>();
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
@@ -94,7 +94,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
/// Runs `cmd` to completion within `timeout`; returns (success, stdout + stderr).
pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)> {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().ok()?;
let mut stdout = child.stdout.take()?;
let mut stderr = child.stderr.take()?;
@@ -161,6 +161,7 @@ impl Http {
fn base(&self, url: &str) -> Command {
let mut cmd = Command::new(&self.curl);
ide_core::process::no_window(&mut cmd);
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
if url.starts_with("https://api.github.com/")
&& let Ok(token) = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN"))
+2 -11
Переглянути файл
@@ -64,11 +64,7 @@ pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
};
let mut cmd = Command::new(&exe);
cmd.arg("--version").stdin(Stdio::null()).env("LC_ALL", "C");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000);
}
ide_core::process::no_window(&mut cmd);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", exe.display())))?;
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !out.status.success() || !text.starts_with("git version") {
@@ -99,12 +95,7 @@ pub(crate) fn command(root: &Path) -> IdeResult<Command> {
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
ide_core::process::no_window(&mut cmd);
Ok(cmd)
}
+21 -14
Переглянути файл
@@ -53,7 +53,8 @@ impl TextFilter {
pub(crate) fn log(r: &Repo, q: &LogQuery) -> IdeResult<Vec<Commit>> {
let repo = r.gix()?;
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
let tips = if range.is_some() { Vec::new() } else { tips(&repo, q.branch.as_deref())? };
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
let tips = if range.is_some() { Vec::new() } else { tips(&repo, &revs)? };
if tips.is_empty() && range.is_none() {
return Ok(Vec::new());
}
@@ -65,7 +66,8 @@ pub(crate) fn log(r: &Repo, q: &LogQuery) -> IdeResult<Vec<Commit>> {
}
None => None,
};
let author = q.author.as_deref().map(str::to_lowercase).filter(|s| !s.is_empty());
let authors: Vec<String> =
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
let text = q.text.as_deref().map(|t| TextFilter::new(t, q.text_regex, q.text_match_case)).transpose()?.flatten();
let limit = if q.limit == 0 { usize::MAX } else { q.limit as usize };
let mut to_skip = q.skip as usize;
@@ -105,11 +107,11 @@ pub(crate) fn log(r: &Repo, q: &LogQuery) -> IdeResult<Vec<Commit>> {
let sig = commit.author().map_err(gx)?;
let name = to_string(sig.name.trim().as_bstr());
let email = to_string(sig.email.trim().as_bstr());
if let Some(needle) = author.as_deref()
&& !name.to_lowercase().contains(needle)
&& !email.to_lowercase().contains(needle)
{
continue;
if !authors.is_empty() {
let (name, email) = (name.to_lowercase(), email.to_lowercase());
if !authors.iter().any(|a| name.contains(a.as_str()) || email.contains(a.as_str())) {
continue;
}
}
let message = to_string(commit.message_raw_sloppy());
if let Some(filter) = text.as_ref()
@@ -163,14 +165,19 @@ fn range_ids(r: &Repo, range: &str, path: Option<&str>) -> IdeResult<Vec<ObjectI
.collect()
}
/// Starting points of the walk: the given revision, or HEAD + all branches.
fn tips(repo: &gix::Repository, branch: Option<&str>) -> IdeResult<Vec<ObjectId>> {
if let Some(rev) = branch.filter(|b| !b.trim().is_empty()) {
let id = resolve(repo, rev)?;
let commit = repo.find_object(id).map_err(gx)?.peel_to_commit().map_err(gx)?;
return Ok(vec![commit.id]);
}
/// Starting points of the walk: the given revisions, or HEAD + all branches.
fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
let mut tips = Vec::new();
if !revs.is_empty() {
for rev in revs {
let id = resolve(repo, rev)?;
let commit = repo.find_object(id).map_err(gx)?.peel_to_commit().map_err(gx)?;
if !tips.contains(&commit.id) {
tips.push(commit.id);
}
}
return Ok(tips);
}
if let Ok(id) = repo.head_id() {
tips.push(id.detach());
}
+197 -6
Переглянути файл
@@ -109,6 +109,12 @@ pub struct LogQuery {
/// `text` matches case-sensitively (Log filter `Cc`).
#[serde(default)]
pub text_match_case: bool,
/// More starting revisions next to `branch` (Log Branch filter with several branches).
#[serde(default)]
pub branches: Vec<String>,
/// More author needles next to `author`; a commit matches any of them (Log User filter).
#[serde(default)]
pub authors: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -136,6 +142,30 @@ pub struct CommitOptions {
pub author: Option<String>,
/// False skips the pre-commit and commit-msg hooks (`--no-verify`).
pub run_hooks: bool,
/// Files committed with only some of their changes (IDEA's partial commit). They are
/// committed through a temporary index, so neither the working tree nor the other
/// entries of the index change; afterwards their index entries match the new commit.
#[serde(default)]
pub partial: Vec<PartialCommitFile>,
}
/// A file of a partial commit: which of its changes against HEAD to commit.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PartialCommitFile {
pub path: ide_core::IpcPath,
/// The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them.
pub hunks: Vec<HunkRange>,
}
/// A hunk identified by its line ranges (0-based), see [`LineHunk`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HunkRange {
pub start: u32,
pub lines: u32,
pub old_start: u32,
pub old_lines: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -237,6 +267,110 @@ pub struct ApplyOutcome {
pub conflicts: Vec<String>,
}
/// How Checkout treats local changes that the switch would overwrite (IDEA's Smart
/// Checkout dialog).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum CheckoutMode {
/// Fail with [`CheckoutOutcome::LocalChanges`] and change nothing.
#[default]
Normal,
/// Stash local changes, switch, and restore them (conflicts are left to resolve).
Smart,
/// Discard the local changes in the way (`git switch --discard-changes`).
Force,
}
/// Checking out remote `origin/x` while local `x` has commits `origin/x` lacks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DivergedLocal {
/// Rebase local `x` onto `origin/x` (IDEA "Rebase onto Remote").
Rebase,
/// Reset local `x` to `origin/x` (IDEA "Drop Local Commits").
Reset,
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutOptions {
#[serde(default)]
pub mode: CheckoutMode,
/// Required when checking out a remote branch whose local namesake is ahead of it.
#[serde(default)]
pub diverged: Option<DivergedLocal>,
}
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
/// left the repository untouched.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum CheckoutOutcome {
Done,
/// These local changes (repository-relative paths) would be overwritten.
LocalChanges {
files: Vec<String>,
},
/// Local branch `local` has commits that remote branch `remote` does not.
LocalBranchAhead {
local: String,
remote: String,
},
/// Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
/// on conflicts in these files.
Conflicts {
files: Vec<String>,
},
}
/// A deleted local branch, enough to restore it (IDEA's "Restore" notification action).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DeletedBranch {
pub name: String,
/// The commit the branch pointed at.
pub tip: String,
/// Its upstream (`origin/x`), restored with it.
pub upstream: Option<String>,
/// It was not fully merged: its own commits are now unreachable from any branch.
pub unmerged: bool,
}
/// Who stands on each side of the conflicts of the operation in progress (merge editor
/// titles, as IDEA labels them).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MergeSides {
/// `merge`, `rebase`, `cherry-pick`, `revert`…; `None` outside an operation.
pub operation: Option<String>,
/// Git's "ours" is not the user's work: during a rebase stage 2 holds the commits
/// rebased onto and stage 3 the user's commit being replayed. [`MergeVersions`] is
/// already swapped; conflict markers in the file are not.
pub reversed: bool,
/// The current branch (for a rebase: the branch being rebased).
pub branch: Option<String>,
/// Short id of the commit being applied (REBASE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD)
/// or merged (MERGE_HEAD).
pub commit: Option<String>,
/// The other branch: the one being merged, or the one rebased onto.
pub other_branch: Option<String>,
}
/// The versions of a conflicted file as the merge editor shows them.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MergeVersions {
pub base: Option<String>,
/// The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`.
pub ours: Option<String>,
pub theirs: Option<String>,
pub sides: MergeSides,
/// Three-way merge of the versions above: non-conflicting changes merged, each
/// conflict left as a diff3 block (yours / base / theirs). `None` when a side is
/// missing (deleted on one side).
pub merged: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Changelist {
@@ -416,7 +550,7 @@ impl Repo {
/// Commits the index; returns the new HEAD commit id. An empty message with
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true };
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
write::commit(self, message, &options)
}
/// Commits with the Commit Options popup's choices.
@@ -429,6 +563,13 @@ impl Repo {
pub fn checkout(&self, branch: &str, create: bool) -> IdeResult<()> {
write::checkout(self, branch, create)
}
/// [`Repo::checkout`] as IDEA does it: local changes in the way are reported (or
/// stashed / discarded per `options.mode`), and a remote branch whose local namesake
/// is behind fast-forwards that branch, while one that is ahead is reported (or
/// rebased / reset per `options.diverged`).
pub fn checkout_with(&self, branch: &str, create: bool, options: &CheckoutOptions) -> IdeResult<CheckoutOutcome> {
write::checkout_with(self, branch, create, options)
}
/// Creates branch `name` at `start` (default HEAD), optionally switching to it. A
/// remote-tracking start point (`origin/x`) becomes the new branch's upstream.
pub fn create_branch(&self, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
@@ -444,6 +585,16 @@ impl Repo {
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
write::delete_branch(self, branch, force)
}
/// Deletes a local branch as IDEA does: without asking, force-deleting one that is not
/// fully merged (reported as `unmerged`), and returning what [`Repo::restore_branch`]
/// needs to undo it.
pub fn delete_branch_restorable(&self, branch: &str) -> IdeResult<DeletedBranch> {
write::delete_branch_restorable(self, branch)
}
/// Recreates a deleted branch at its old tip, with its upstream.
pub fn restore_branch(&self, deleted: &DeletedBranch) -> IdeResult<()> {
write::restore_branch(self, deleted)
}
/// Renames a local branch (`git branch -m`); its upstream configuration moves with it.
pub fn rename_branch(&self, from: &str, to: &str) -> IdeResult<()> {
write::rename_branch(self, from, to)
@@ -458,11 +609,18 @@ impl Repo {
pub fn rebase(&self, onto: &str) -> IdeResult<()> {
write::rebase(self, onto)
}
pub fn stash_push(&self, message: Option<&str>, include_untracked: bool) -> IdeResult<()> {
write::stash_push(self, message, include_untracked)
/// `keep_index`: changes already staged stay in the index (and the working tree).
pub fn stash_push(&self, message: Option<&str>, include_untracked: bool, keep_index: bool) -> IdeResult<()> {
write::stash_push(self, message, include_untracked, keep_index)
}
pub fn stash_apply(&self, index: u32, pop: bool) -> IdeResult<()> {
write::stash_apply(self, index, pop)
/// `reinstate_index`: also restore what was staged when the stash was made.
pub fn stash_apply(&self, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> {
write::stash_apply(self, index, pop, reinstate_index)
}
/// Creates and checks out `branch` at the commit the stash was made on, applies the
/// stash there (index included) and drops it.
pub fn stash_branch(&self, index: u32, branch: &str) -> IdeResult<()> {
write::stash_branch(self, index, branch)
}
/// Removes `stash@{index}` without applying it.
pub fn stash_drop(&self, index: u32) -> IdeResult<()> {
@@ -523,7 +681,20 @@ impl Repo {
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
write::push_branch(self, branch, revision, force_with_lease, cancel, on_output)
write::push_branch(self, branch, revision, None, force_with_lease, cancel, on_output)
}
/// [`Repo::push_branch`] to remote branch `target` instead of the upstream's name (the
/// Push dialog's editable target).
pub fn push_branch_to(
&self,
branch: &str,
revision: Option<&str>,
target: &str,
force_with_lease: bool,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
write::push_branch(self, branch, revision, Some(target), force_with_lease, cancel, on_output)
}
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
/// Update). Fails when the branch has diverged.
@@ -586,6 +757,10 @@ impl Repo {
pub fn tags(&self) -> IdeResult<Vec<String>> {
ops::tags(self)
}
/// Files that differ between revisions `from` and `to`.
pub fn diff_revisions(&self, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_revisions(self, from, to)
}
/// Tracked files whose working-tree content differs from `rev`.
pub fn diff_with_worktree(&self, rev: &str) -> IdeResult<Vec<ChangedFile>> {
ops::diff_with_worktree(self, rev)
@@ -618,6 +793,22 @@ impl Repo {
shelf::unshelve(self, shelf_dir, id, remove)
}
/// Who is on each side of the conflicts of the operation in progress.
pub fn merge_sides(&self) -> IdeResult<MergeSides> {
ops::merge_sides(self)
}
/// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
/// dialog shows them (sides swapped during a rebase).
pub fn merge_versions(&self, path: &Path) -> IdeResult<MergeVersions> {
let (base, ours, theirs) = self.conflict_versions(path)?;
let sides = self.merge_sides()?;
let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
let merged = match (&ours, &theirs) {
(Some(o), Some(t)) => Some(ops::merge_file(self, o, base.as_deref().unwrap_or(""), t)?),
_ => None,
};
Ok(MergeVersions { base, ours, theirs, sides, merged })
}
/// For conflict resolution: (base, ours, theirs) versions of a conflicted file.
pub fn conflict_versions(&self, path: &Path) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
let rel = self.rel_path(path)?;
+98 -1
Переглянути файл
@@ -3,7 +3,7 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::{ChangeKind, ChangedFile, RebaseAction, RebaseEntry, Repo, ResetMode};
use crate::{ChangeKind, ChangedFile, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode};
use ide_core::{CancellationToken, IdeError, IdeResult};
/// The in-progress operation git can continue / abort / skip.
@@ -20,6 +20,96 @@ fn sequencer(r: &Repo) -> IdeResult<&'static str> {
use crate::write::unmerged_paths;
/// The sides of the operation in progress, read from the files git keeps in `.git`.
pub(crate) fn merge_sides(r: &Repo) -> IdeResult<MergeSides> {
let repo = r.gix()?;
let operation = crate::refs::operation(&repo);
let read = |name: &str| {
std::fs::read_to_string(r.git_dir.join(name))
.ok()
.and_then(|s| s.lines().next().map(|l| l.trim().to_string()))
.filter(|s| !s.is_empty())
};
let short = |id: String| id.chars().take(8).collect::<String>();
let head_branch = repo.head_name().map_err(gx)?.map(|n| crate::repo::to_string(n.as_ref().shorten()));
let mut sides = MergeSides { operation: operation.clone(), branch: head_branch, ..Default::default() };
match operation.as_deref() {
Some("rebase") => {
sides.reversed = true;
let dir = ["rebase-merge", "rebase-apply"].into_iter().find(|d| r.git_dir.join(d).is_dir());
if let Some(dir) = dir {
if let Some(head) = read(&format!("{dir}/head-name")) {
sides.branch = Some(head.strip_prefix("refs/heads/").unwrap_or(&head).to_string());
}
sides.other_branch = read(&format!("{dir}/onto")).and_then(|onto| branch_at(r, &onto));
}
sides.commit = read("REBASE_HEAD").map(short);
}
Some("merge") => {
let head = read("MERGE_HEAD");
// git quotes the merged ref on the first line: `Merge branch 'main' into feature`.
sides.other_branch = read("MERGE_MSG")
.and_then(|m| m.split('\'').nth(1).map(str::to_string))
.filter(|b| !b.is_empty())
.or_else(|| head.as_deref().and_then(|h| branch_at(r, h)));
sides.commit = head.map(short);
}
Some("cherry-pick") => sides.commit = read("CHERRY_PICK_HEAD").map(short),
Some("revert") => sides.commit = read("REVERT_HEAD").map(short),
// Conflicts outside an operation come from restoring stashed changes (Smart
// Checkout, update with autostash): stage 2 is the new HEAD, stage 3 the user's.
None if !crate::write::unmerged_paths(r)?.is_empty() => {
sides.operation = Some("unstash".into());
sides.reversed = true;
}
_ => {}
}
Ok(sides)
}
/// Three-way merge of file contents (`git merge-file --diff3`): changes that don't
/// conflict are merged, each conflict is left as a diff3 block.
pub(crate) fn merge_file(r: &Repo, ours: &str, base: &str, theirs: &str) -> IdeResult<String> {
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = TempDir(r.git_dir.join(format!("openidea-merge-{}", std::process::id())));
std::fs::create_dir_all(&dir.0)?;
let file = |name: &str, text: &str| -> IdeResult<String> {
let path = dir.0.join(name);
std::fs::write(&path, text)?;
Ok(path.to_string_lossy().into_owned())
};
let (o, b, t) = (file("ours", ours)?, file("base", base)?, file("theirs", theirs)?);
let args = ["merge-file", "-p", "--diff3", "-L", "yours", "-L", "base", "-L", "theirs", &o, &b, &t];
let out = cli::run_raw(r.root(), &args, None)?;
// The exit status is the number of conflicts; only a negative one is a failure.
match out.code {
Some(code) if code >= 0 => Ok(String::from_utf8_lossy(&out.stdout).into_owned()),
code => Err(cli::failure(&args, &out.stderr, &out.stdout, code)),
}
}
/// The single branch (local first, then remote) pointing at `commit`.
fn branch_at(r: &Repo, commit: &str) -> Option<String> {
if commit.starts_with('-') {
return None;
}
["refs/heads", "refs/remotes"].into_iter().find_map(|refs| {
let out =
run(r.root(), &["for-each-ref", "--points-at", commit, "--format=%(refname:short)", refs], None).ok()?;
let names: Vec<String> =
out.stdout_str().lines().filter(|l| !l.is_empty() && !l.ends_with("/HEAD")).map(str::to_string).collect();
match names.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
})
}
fn check_commits(commits: &[String]) -> IdeResult<()> {
if commits.is_empty() {
return Err(IdeError::invalid("no commits selected"));
@@ -259,6 +349,13 @@ pub(crate) fn diff_with_worktree(r: &Repo, rev: &str) -> IdeResult<Vec<ChangedFi
Ok(parse_name_status(&out.stdout_str()))
}
/// Files that differ between two revisions (Update Project's "N files updated").
pub(crate) fn diff_revisions(r: &Repo, from: &str, to: &str) -> IdeResult<Vec<ChangedFile>> {
check_commits(&[from.to_string(), to.to_string()])?;
let out = run(r.root(), &["diff", "--name-status", "-z", "-M", "--no-ext-diff", from, to, "--"], None)?;
Ok(parse_name_status(&out.stdout_str()))
}
/// Parses `git diff --name-status -z` output.
pub(crate) fn parse_name_status(text: &str) -> Vec<ChangedFile> {
let mut parts = text.split('\0').filter(|s| !s.is_empty());
+267 -6
Переглянути файл
@@ -2,7 +2,9 @@
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::{BlameLine, CommitOptions, Repo};
use crate::{
BlameLine, CheckoutMode, CheckoutOptions, CheckoutOutcome, CommitOptions, DeletedBranch, DivergedLocal, Repo,
};
use gix::bstr::{BStr, ByteSlice};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -247,11 +249,85 @@ pub(crate) fn commit(r: &Repo, message: &str, options: &CommitOptions) -> IdeRes
args.extend(["-F", "-"]);
Some(message.as_bytes())
};
run(r.root(), &args, stdin)?;
if options.partial.is_empty() {
run(r.root(), &args, stdin)?;
} else {
commit_partial(r, &args, stdin, &options.partial)?;
}
let repo = r.gix()?;
Ok(repo.head_id().map_err(gx)?.detach().to_string())
}
/// Removes the temporary index however the partial commit ends.
struct TempIndex(PathBuf);
impl Drop for TempIndex {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
let _ = std::fs::remove_file(self.0.with_extension("lock"));
}
}
/// Commits the index with only the chosen hunks of `partial` files, through a copy of the
/// index (`GIT_INDEX_FILE`), as IDEA's partial commit does: the working tree and the
/// user's index are left alone except that the partial files' entries end up matching
/// the new commit.
fn commit_partial(
r: &Repo,
commit_args: &[&str],
stdin: Option<&[u8]>,
partial: &[crate::PartialCommitFile],
) -> IdeResult<()> {
let tmp = TempIndex(r.git_dir.join("openidea-partial-index"));
let index = r.git_dir.join("index");
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
let mut rels = Vec::new();
for file in partial {
let rel = r.rel_path(&file.path.0)?;
let head = {
let repo = r.gix()?;
crate::repo::blob_at(&repo, &rel, "HEAD")?
}
.ok_or_else(|| {
IdeError::invalid(format!("{rel}: only changes of a file in HEAD can be committed partially"))
})?;
let disk = std::fs::read(r.abs_path(&rel))?;
if head.contains(&0) || disk.contains(&0) {
return Err(IdeError::invalid(format!("{rel}: binary files cannot be committed partially")));
}
let (head, disk) = (String::from_utf8_lossy(&head), String::from_utf8_lossy(&disk));
let hunks = crate::diff::line_hunks(&head, &disk);
let mut selected = Vec::new();
for want in &file.hunks {
let found = hunks.iter().position(|h| {
(h.start, h.lines, h.old_start, h.old_lines) == (want.start, want.lines, want.old_start, want.old_lines)
});
match found {
Some(i) => selected.push(i),
None => return Err(IdeError::invalid(format!("{rel} changed on disk; review its changes again"))),
}
}
cli::run_env(r.root(), &["--literal-pathspecs", "reset", "-q", "HEAD", "--", &rel], None, &env)?;
let patch = crate::diff::build_partial_patch(&rel, &head, &disk, &selected);
if !patch.is_empty() {
cli::run_env(
r.root(),
&["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"],
Some(patch.as_bytes()),
&env,
)?;
}
rels.push(rel);
}
cli::run_env(r.root(), commit_args, stdin, &env)?;
// The user's index still holds the partial files' previous entries: align them with
// the commit so the remaining changes show as unstaged, nothing as staged.
run_paths(r, &["reset", "-q", "HEAD"], &rels)
}
pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
let branch = branch.trim();
if branch.is_empty() {
@@ -280,6 +356,128 @@ pub(crate) fn checkout(r: &Repo, branch: &str, create: bool) -> IdeResult<()> {
run(r.root(), &["switch", "--detach", branch], None).map(|_| ())
}
/// What a checkout of `branch` runs.
enum SwitchPlan {
Switch(Vec<String>),
/// `git rebase <remote> <local>`.
Rebase {
local: String,
remote: String,
},
Ahead {
local: String,
remote: String,
},
}
fn switch_plan(r: &Repo, branch: &str, create: bool, diverged: Option<DivergedLocal>) -> IdeResult<SwitchPlan> {
let args = |a: &[&str]| SwitchPlan::Switch(a.iter().map(|s| s.to_string()).collect());
if create {
return Ok(args(&["switch", "-c", branch]));
}
let repo = r.gix()?;
let exists = |name: &str| repo.try_find_reference(name).map_err(gx).map(|r| r.is_some());
if exists(&format!("refs/heads/{branch}"))? {
return Ok(args(&["switch", branch]));
}
if exists(&format!("refs/remotes/{branch}"))?
&& let Some((_, name)) = branch.split_once('/')
{
if !exists(&format!("refs/heads/{name}"))? {
return Ok(args(&["switch", "-c", name, "--track", branch]));
}
// IDEA: a local namesake that is merely behind is fast-forwarded; one with commits
// of its own needs the user's choice.
let range = format!("{branch}..refs/heads/{name}");
let ahead = run(r.root(), &["rev-list", "--count", &range], None)?.stdout_str().trim() != "0";
return Ok(match (ahead, diverged) {
(true, None) => SwitchPlan::Ahead { local: name.to_string(), remote: branch.to_string() },
(true, Some(DivergedLocal::Rebase)) => {
SwitchPlan::Rebase { local: name.to_string(), remote: branch.to_string() }
}
_ => args(&["switch", "-C", name, "--track", branch]),
});
}
// A tag or commit: detached HEAD.
resolve(&repo, branch)?;
Ok(args(&["switch", "--detach", branch]))
}
/// Files git refuses to overwrite with local changes, from its error message.
fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
let mut lines =
stderr.lines().skip_while(|l| !l.contains("local changes to the following files would be overwritten"));
lines.next()?;
Some(lines.take_while(|l| l.starts_with('\t')).map(|l| l.trim().to_string()).collect())
}
pub(crate) fn checkout_with(
r: &Repo,
branch: &str,
create: bool,
options: &CheckoutOptions,
) -> IdeResult<CheckoutOutcome> {
let branch = branch.trim();
if branch.is_empty() {
return Err(IdeError::invalid("branch name is empty"));
}
if branch.starts_with('-') {
return Err(IdeError::invalid(format!("invalid revision '{branch}'")));
}
let mut args = match switch_plan(r, branch, create, options.diverged)? {
SwitchPlan::Ahead { local, remote } => return Ok(CheckoutOutcome::LocalBranchAhead { local, remote }),
SwitchPlan::Rebase { local, remote } => {
let out = cli::run_raw(r.root(), &["rebase", "--autostash", &remote, &local], None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let files = unmerged_paths(r)?;
if files.is_empty() {
return Err(cli::failure(&["rebase"], &out.stderr, &out.stdout, out.code));
}
return Ok(CheckoutOutcome::Conflicts { files });
}
SwitchPlan::Switch(args) => args,
};
if options.mode == CheckoutMode::Force {
args.push("--discard-changes".into());
}
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
let out = cli::run_raw(r.root(), &argv, None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let Some(files) = overwritten_files(&String::from_utf8_lossy(&out.stderr)) else {
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
};
if options.mode != CheckoutMode::Smart {
return Ok(CheckoutOutcome::LocalChanges { files });
}
// Smart Checkout: stash → switch → unstash, like IDEA.
let before = stash_count(r)?;
run(r.root(), &["stash", "push", "-q", "-m", &format!("Uncommitted changes before checkout of {branch}")], None)?;
if stash_count(r)? == before {
return Err(IdeError::invalid("could not save the local changes"));
}
if let Err(e) = run(r.root(), &argv, None) {
run(r.root(), &["stash", "pop", "-q", "--index"], None)?;
return Err(e);
}
let pop = cli::run_raw(r.root(), &["stash", "pop", "-q"], None)?;
if pop.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let files = unmerged_paths(r)?;
if files.is_empty() {
return Err(cli::failure(&["stash", "pop"], &pop.stderr, &pop.stdout, pop.code));
}
Ok(CheckoutOutcome::Conflicts { files })
}
fn stash_count(r: &Repo) -> IdeResult<usize> {
Ok(run(r.root(), &["stash", "list"], None)?.stdout_str().lines().count())
}
/// Creates `name` at `start` (default HEAD); a remote-tracking start point is tracked.
pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout: bool) -> IdeResult<()> {
let name = name.trim();
@@ -342,6 +540,39 @@ pub(crate) fn delete_branch(r: &Repo, branch: &str, force: bool) -> IdeResult<()
run(r.root(), &["branch", if force { "-D" } else { "-d" }, "--", branch], None).map(|_| ())
}
pub(crate) fn delete_branch_restorable(r: &Repo, branch: &str) -> IdeResult<DeletedBranch> {
check_local_branch(r, branch)?;
let tip = run(r.root(), &["rev-parse", "--verify", "-q", &format!("refs/heads/{branch}^{{commit}}")], None)?
.stdout_str()
.trim()
.to_string();
let upstream =
cli::run_raw(r.root(), &["for-each-ref", "--format=%(upstream:short)", &format!("refs/heads/{branch}")], None)?
.stdout_str()
.trim()
.to_string();
let out = cli::run_raw(r.root(), &["branch", "-d", "--", branch], None)?;
let unmerged = match out.code {
Some(0) => false,
_ if String::from_utf8_lossy(&out.stderr).contains("not fully merged") => {
run(r.root(), &["branch", "-D", "--", branch], None)?;
true
}
code => return Err(cli::failure(&["branch"], &out.stderr, &out.stdout, code)),
};
Ok(DeletedBranch { name: branch.to_string(), tip, upstream: (!upstream.is_empty()).then_some(upstream), unmerged })
}
pub(crate) fn restore_branch(r: &Repo, deleted: &DeletedBranch) -> IdeResult<()> {
let tip = check_rev(&deleted.tip)?;
run(r.root(), &["branch", "--", &deleted.name, tip], None)?;
if let Some(upstream) = &deleted.upstream {
let target = format!("--set-upstream-to={upstream}");
run(r.root(), &["branch", &target, "--", &deleted.name], None)?;
}
Ok(())
}
pub(crate) fn rename_branch(r: &Repo, from: &str, to: &str) -> IdeResult<()> {
let to = to.trim();
if to.is_empty() {
@@ -367,20 +598,40 @@ pub(crate) fn rebase(r: &Repo, onto: &str) -> IdeResult<()> {
run(r.root(), &["rebase", "--autostash", check_rev(onto)?], None).map(|_| ())
}
pub(crate) fn stash_push(r: &Repo, message: Option<&str>, include_untracked: bool) -> IdeResult<()> {
pub(crate) fn stash_push(r: &Repo, message: Option<&str>, include_untracked: bool, keep_index: bool) -> IdeResult<()> {
let mut args = vec!["stash", "push", "-q"];
if include_untracked {
args.push("--include-untracked");
}
if keep_index {
args.push("--keep-index");
}
if let Some(m) = message.filter(|m| !m.trim().is_empty()) {
args.extend(["-m", m]);
}
run(r.root(), &args, None).map(|_| ())
}
pub(crate) fn stash_apply(r: &Repo, index: u32, pop: bool) -> IdeResult<()> {
pub(crate) fn stash_apply(r: &Repo, index: u32, pop: bool, reinstate_index: bool) -> IdeResult<()> {
let spec = format!("stash@{{{index}}}");
run(r.root(), &["stash", if pop { "pop" } else { "apply" }, "-q", &spec], None).map(|_| ())
let mut args = vec!["stash", if pop { "pop" } else { "apply" }, "-q"];
if reinstate_index {
args.push("--index");
}
args.push(&spec);
run(r.root(), &args, None).map(|_| ())
}
pub(crate) fn stash_branch(r: &Repo, index: u32, branch: &str) -> IdeResult<()> {
let branch = branch.trim();
let valid = !branch.is_empty()
&& !branch.starts_with('-')
&& cli::run_raw(r.root(), &["check-ref-format", "--branch", branch], None)?.code == Some(0);
if !valid {
return Err(IdeError::invalid(format!("'{branch}' is not a valid branch name")));
}
let spec = format!("stash@{{{index}}}");
run(r.root(), &["stash", "branch", branch, &spec], None).map(|_| ())
}
pub(crate) fn stash_drop(r: &Repo, index: u32) -> IdeResult<()> {
@@ -479,15 +730,25 @@ pub(crate) fn push_branch(
r: &Repo,
branch: &str,
revision: Option<&str>,
target: Option<&str>,
force_with_lease: bool,
cancel: &CancellationToken,
on_output: &dyn Fn(String),
) -> IdeResult<()> {
check_local_branch(r, branch)?;
let (remote, target, set_upstream) = match branch_upstream(r, branch) {
let (remote, mut name, set_upstream) = match branch_upstream(r, branch) {
Some((remote, name)) => (remote, name, false),
None => (push_remote(r)?, branch.to_string(), revision.is_none()),
};
if let Some(t) = target.map(str::trim).filter(|t| !t.is_empty()) {
let valid =
!t.starts_with('-') && cli::run_raw(r.root(), &["check-ref-format", "--branch", t], None)?.code == Some(0);
if !valid {
return Err(IdeError::invalid(format!("'{t}' is not a valid branch name")));
}
name = t.to_string();
}
let target = name;
let source = match revision {
Some(rev) => check_rev(rev)?.to_string(),
None => format!("refs/heads/{branch}"),
+54
Переглянути файл
@@ -106,6 +106,49 @@ fn rebase_conflict_then_continue() {
assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), fx.git(&["rev-parse", "main"]));
}
#[test]
fn merge_versions_put_the_users_work_on_the_left() {
// Rebase: git's "ours" is main; the user's commit (topic) must be `ours` here.
let fx = diverged();
let repo = fx.repo();
let topic = fx.git(&["rev-parse", "topic"]);
assert!(repo.rebase("main").is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert_eq!(v.theirs.as_deref(), Some("main\n"));
assert_eq!(v.base.as_deref(), Some("base\n"));
assert!(v.sides.reversed);
assert_eq!(v.sides.operation.as_deref(), Some("rebase"));
assert_eq!(v.sides.branch.as_deref(), Some("topic"));
assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
assert_eq!(v.sides.commit.as_deref(), Some(&topic[..8]));
// The merged text puts the user's side first, whatever git's stage order.
assert_eq!(v.merged.as_deref(), Some("<<<<<<< yours\ntopic\n||||||| base\nbase\n=======\nmain\n>>>>>>> theirs\n"));
let (cancel, out) = quiet();
repo.abort_operation(&cancel, &out).unwrap();
// Merge: not swapped; the merged branch is named.
assert!(repo.merge("main").is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert_eq!(v.theirs.as_deref(), Some("main\n"));
assert!(!v.sides.reversed);
assert_eq!(v.sides.branch.as_deref(), Some("topic"));
assert_eq!(v.sides.other_branch.as_deref(), Some("main"));
repo.abort_operation(&cancel, &out).unwrap();
// Cherry-pick: not swapped; the picked commit is named.
let main = fx.git(&["rev-parse", "main"]);
assert!(repo.cherry_pick(std::slice::from_ref(&main), &cancel, &out).is_err());
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.ours.as_deref(), Some("topic\n"));
assert!(!v.sides.reversed);
assert_eq!(v.sides.operation.as_deref(), Some("cherry-pick"));
assert_eq!(v.sides.commit.as_deref(), Some(&main[..8]));
repo.abort_operation(&cancel, &out).unwrap();
assert_eq!(repo.merge_sides().unwrap(), MergeSides { branch: Some("topic".into()), ..Default::default() });
}
#[test]
fn rebase_conflict_then_abort_and_skip() {
let fx = diverged();
@@ -262,6 +305,11 @@ fn compare_with_local_lists_differences() {
got,
vec![("a.txt", ChangeKind::Modified), ("b.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]
);
// Between two revisions the working tree does not count.
let files = fx.repo().diff_revisions(&one, "HEAD").unwrap();
let got: Vec<(&str, ChangeKind)> = files.iter().map(|f| (f.path.as_str(), f.kind)).collect();
assert_eq!(got, vec![("a.txt", ChangeKind::Modified), ("c.txt", ChangeKind::Added)]);
assert!(fx.repo().diff_revisions("-x", "HEAD").is_err());
}
#[test]
@@ -448,6 +496,12 @@ fn push_branch_and_up_to_revision() {
assert_eq!(git_in(&bare, &["rev-parse", "side"]), c2);
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "side@{upstream}"]), "origin/side");
assert!(repo.push_branch("nope", None, false, &cancel, &out).is_err());
// An edited target: same remote, another branch name; the upstream stays as it was.
repo.push_branch_to("main", None, "review/main", false, &cancel, &out).unwrap();
assert_eq!(git_in(&bare, &["rev-parse", "review/main"]), c3);
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "main@{upstream}"]), "origin/main");
assert!(repo.push_branch_to("main", None, "bad..name", false, &cancel, &out).is_err());
}
#[test]
+283 -5
Переглянути файл
@@ -615,11 +615,11 @@ fn stash_push_list_apply_pop() {
let repo = fx.repo();
fx.write("s.txt", "change 1\n");
repo.stash_push(Some("first stash"), false).unwrap();
repo.stash_push(Some("first stash"), false, false).unwrap();
assert_eq!(fx.read("s.txt"), "base\n");
fx.write("s.txt", "change 2\n");
fx.write("u.txt", "untracked\n");
repo.stash_push(None, true).unwrap();
repo.stash_push(None, true, false).unwrap();
assert!(!fx.path("u.txt").exists());
let stashes = repo.stashes().unwrap();
@@ -629,11 +629,11 @@ fn stash_push_list_apply_pop() {
assert!(stashes[1].message.contains("first stash"), "{stashes:?}");
assert!(stashes[0].time_ms > 0.0);
repo.stash_apply(1, false).unwrap();
repo.stash_apply(1, false, false).unwrap();
assert_eq!(fx.read("s.txt"), "change 1\n");
assert_eq!(repo.stashes().unwrap().len(), 2);
repo.discard(&[fx.path("s.txt")]).unwrap();
repo.stash_apply(0, true).unwrap();
repo.stash_apply(0, true, false).unwrap();
assert_eq!(fx.read("s.txt"), "change 2\n");
assert!(fx.path("u.txt").exists());
assert_eq!(repo.stashes().unwrap().len(), 1);
@@ -642,6 +642,72 @@ fn stash_push_list_apply_pop() {
assert!(repo.stash_drop(0).is_err());
}
#[test]
fn stash_keep_index_reinstate_index_and_branch() {
let fx = Fixture::new();
fx.write("a.txt", "a\n");
fx.write("b.txt", "b\n");
fx.commit_all("base");
let repo = fx.repo();
let staged = |fx: &Fixture| fx.git(&["diff", "--cached", "--name-only"]).trim().to_string();
fx.write("a.txt", "a staged\n");
fx.git(&["add", "a.txt"]);
fx.write("b.txt", "b unstaged\n");
repo.stash_push(Some("keep"), false, true).unwrap();
// Keep index: the staged change stays, the unstaged one is stashed.
assert_eq!(fx.read("a.txt"), "a staged\n");
assert_eq!(fx.read("b.txt"), "b\n");
assert_eq!(staged(&fx), "a.txt");
fx.git(&["reset", "-q", "--hard"]);
repo.stash_apply(0, false, true).unwrap();
// Reinstate index: what was staged is staged again.
assert_eq!(staged(&fx), "a.txt");
assert_eq!(fx.read("b.txt"), "b unstaged\n");
fx.git(&["reset", "-q", "--hard"]);
repo.stash_apply(0, false, false).unwrap();
assert_eq!(staged(&fx), "");
fx.git(&["reset", "-q", "--hard"]);
assert!(repo.stash_branch(0, "-bad").is_err());
repo.stash_branch(0, "from-stash").unwrap();
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "HEAD"]).trim(), "from-stash");
assert_eq!(fx.read("b.txt"), "b unstaged\n");
assert!(repo.stashes().unwrap().is_empty());
}
#[test]
fn log_filters_several_branches_and_authors() {
let fx = Fixture::new();
fx.write("a.txt", "1\n");
let c1 = fx.commit_all("one");
fx.git(&["checkout", "-q", "-b", "left"]);
fx.write("l.txt", "l\n");
let left = fx.commit_all("left");
fx.git(&["checkout", "-q", "-b", "right", &c1]);
fx.write("r.txt", "r\n");
fx.git(&["add", "-A"]);
fx.git(&["-c", "user.name=Someone Else", "-c", "[email protected]", "commit", "-q", "-m", "right"]);
let right = fx.git(&["rev-parse", "HEAD"]).trim().to_string();
fx.git(&["checkout", "-q", "-b", "third", &c1]);
fx.write("t.txt", "t\n");
let third = fx.commit_all("third");
let repo = fx.repo();
let ids = |q: LogQuery| repo.log(&q).unwrap().into_iter().map(|c| c.id).collect::<Vec<_>>();
let two = ids(LogQuery { branch: Some("left".into()), branches: vec!["right".into()], ..Default::default() });
assert!(two.contains(&left) && two.contains(&right) && two.contains(&c1));
assert!(!two.contains(&third));
let only = ids(LogQuery { branches: vec!["third".into()], ..Default::default() });
assert_eq!(only, vec![third.clone(), c1.clone()]);
let everyone = ids(LogQuery { authors: vec!["else@corp".into(), "nobody".into()], ..Default::default() });
assert_eq!(everyone, vec![right.clone()]);
let both = ids(LogQuery { author: Some("ELSE".into()), authors: vec!["test@".into()], ..Default::default() });
assert!(both.contains(&right) && both.len() > 1);
}
#[test]
fn log_range_lists_outgoing_commits() {
let (fx, _bare) = with_remote();
@@ -770,6 +836,218 @@ fn checkout_create_detached_delete_rebase() {
assert!(repo.checkout("does-not-exist", false).is_err());
}
#[test]
fn smart_and_force_checkout_with_local_changes_in_the_way() {
let fx = Fixture::new();
fx.write("f.txt", "1\n2\n3\n4\n5\n");
fx.commit_all("base");
fx.git(&["checkout", "-q", "-b", "other"]);
fx.write("f.txt", "1\nother\n3\n4\n5\n");
fx.commit_all("other edit");
fx.git(&["checkout", "-q", "main"]);
let repo = fx.repo();
let opts = |mode| CheckoutOptions { mode, diverged: None };
// A non-conflicting local edit to a file the switch rewrites.
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Normal)).unwrap();
assert_eq!(outcome, CheckoutOutcome::LocalChanges { files: vec!["f.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\nlocal\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n", "local change carried over");
assert!(repo.stashes().unwrap().is_empty(), "stash restored and dropped");
// A local edit that conflicts with the target: smart checkout leaves a conflict.
fx.git(&["checkout", "-q", "-f", "main"]);
fx.write("f.txt", "1\nmine\n3\n4\n5\n");
let outcome = repo.checkout_with("other", false, &opts(CheckoutMode::Smart)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Conflicts { files: vec!["f.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(repo.stashes().unwrap().len(), 1, "git keeps the stash after a conflicting pop");
// The stashed edit is the user's side of the merge, the checked-out branch the other.
let v = repo.merge_versions(&fx.path("f.txt")).unwrap();
assert_eq!(v.sides.operation.as_deref(), Some("unstash"));
assert!(v.sides.reversed);
assert_eq!(v.ours.as_deref(), Some("1\nmine\n3\n4\n5\n"));
// Force discards the change in the way.
fx.git(&["reset", "-q", "--hard"]);
fx.git(&["stash", "drop", "-q"]);
fx.write("f.txt", "1\nmine\n3\n4\n5\n");
fx.write("untouched.txt", "new\n");
let outcome = repo.checkout_with("main", false, &opts(CheckoutMode::Force)).unwrap();
assert_eq!(outcome, CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.read("f.txt"), "1\n2\n3\n4\n5\n");
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
}
#[test]
fn checkout_remote_branch_with_existing_local_namesake() {
let (fx, bare) = with_remote();
let repo = fx.repo();
// Another clone advances origin/main.
let other = fx._tmp.path().join("other");
git_in(fx._tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]);
configure(&other);
std::fs::write(other.join("b.txt"), "remote\n").unwrap();
git_in(&other, &["add", "-A"]);
git_in(&other, &["commit", "-q", "-m", "remote work"]);
git_in(&other, &["push", "-q", "origin", "main"]);
fx.git(&["fetch", "-q"]);
fx.git(&["checkout", "-q", "-b", "topic"]);
let none = CheckoutOptions::default();
// Local main is only behind: it is fast-forwarded and checked out.
assert_eq!(repo.checkout_with("origin/main", false, &none).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
// Local main has its own commit: the user must choose; nothing changes meanwhile.
fx.write("c.txt", "local\n");
let local_tip = fx.commit_all("local work");
fx.git(&["checkout", "-q", "topic"]);
let outcome = repo.checkout_with("origin/main", false, &none).unwrap();
assert_eq!(outcome, CheckoutOutcome::LocalBranchAhead { local: "main".into(), remote: "origin/main".into() });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
// Rebase onto Remote keeps the local commit on top of origin/main.
let rebase = CheckoutOptions { diverged: Some(DivergedLocal::Rebase), ..Default::default() };
assert_eq!(repo.checkout_with("origin/main", false, &rebase).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
assert_eq!(fx.git(&["rev-parse", "main~1"]), fx.git(&["rev-parse", "origin/main"]));
assert_eq!(fx.git(&["log", "-1", "--format=%s"]), "local work");
// Drop Local Commits resets main to origin/main.
fx.git(&["checkout", "-q", "topic"]);
let reset = CheckoutOptions { diverged: Some(DivergedLocal::Reset), ..Default::default() };
assert_eq!(repo.checkout_with("origin/main", false, &reset).unwrap(), CheckoutOutcome::Done);
assert_eq!(fx.git(&["rev-parse", "main"]), fx.git(&["rev-parse", "origin/main"]));
assert_ne!(fx.git(&["rev-parse", "main"]), local_tip);
assert_eq!(repo.branch_info().unwrap().upstream.as_deref(), Some("origin/main"));
}
#[test]
fn delete_branch_without_asking_and_restore_it() {
let (fx, _bare) = with_remote();
let repo = fx.repo();
fx.git(&["checkout", "-q", "-b", "merged", "--track", "origin/main"]);
fx.git(&["checkout", "-q", "-b", "work"]);
fx.write("w.txt", "work\n");
let work_tip = fx.commit_all("work");
fx.git(&["checkout", "-q", "main"]);
let merged = repo.delete_branch_restorable("merged").unwrap();
assert!(!merged.unmerged);
assert_eq!(merged.upstream.as_deref(), Some("origin/main"));
let work = repo.delete_branch_restorable("work").unwrap();
assert!(work.unmerged, "not fully merged branches are force-deleted and reported");
assert_eq!(work.tip, work_tip);
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "work"));
assert!(repo.delete_branch_restorable("main").is_err(), "the current branch cannot be deleted");
repo.restore_branch(&work).unwrap();
repo.restore_branch(&merged).unwrap();
let branches = repo.branches().unwrap();
let find = |n: &str| branches.iter().find(|b| !b.remote && b.name == n).unwrap().clone();
assert_eq!(find("work").commit, work_tip);
assert_eq!(find("merged").upstream.as_deref(), Some("origin/main"));
}
fn range(h: &LineHunk) -> HunkRange {
HunkRange { start: h.start, lines: h.lines, old_start: h.old_start, old_lines: h.old_lines }
}
#[test]
fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
let fx = Fixture::new();
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
fx.write("f.txt", base);
fx.write("other.txt", "o\n");
fx.write("staged.txt", "s\n");
fx.commit_all("base");
let repo = fx.repo();
let edited = "A\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\n";
fx.write("f.txt", edited);
fx.write("other.txt", "o2\n");
fx.write("staged.txt", "s2\n");
repo.stage(&[fx.path("other.txt")]).unwrap();
let hunks = diff_hunks(base, edited);
assert_eq!(hunks.len(), 2);
// Commit the first hunk of f.txt plus the staged other.txt; staged.txt is not staged.
let options = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
repo.commit_with("partial", &options).unwrap();
assert_eq!(fx.git(&["show", "HEAD:f.txt"]), "A\nb\nc\nd\ne\nf\ng\nh\ni\nj");
assert_eq!(fx.git(&["show", "HEAD:other.txt"]), "o2");
assert_eq!(fx.git(&["show", "HEAD:staged.txt"]), "s");
// The working tree is untouched.
assert_eq!(fx.read("f.txt"), edited);
assert_eq!(fx.read("staged.txt"), "s2\n");
// The index matches the commit; the rest of f.txt is an unstaged change.
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
let st = repo.status().unwrap();
assert_eq!(status_of(&st, "f.txt").unstaged, Some(ChangeKind::Modified));
assert_eq!(status_of(&st, "f.txt").staged, None);
assert!(!fx.dir.join(".git/openidea-partial-index").exists());
// A stale hunk (the file changed since the UI computed it) refuses to commit anything.
let before = fx.git(&["rev-parse", "HEAD"]);
let stale = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
let err = repo.commit_with("stale", &stale).unwrap_err();
assert!(err.message.contains("changed"), "{}", err.message);
assert_eq!(fx.git(&["rev-parse", "HEAD"]), before);
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
assert!(!fx.dir.join(".git/openidea-partial-index").exists());
// The remaining hunk commits on its own; then nothing is left.
let rest = diff_hunks(&repo.file_at(&fx.path("f.txt"), None).unwrap().unwrap(), edited);
assert_eq!(rest.len(), 1);
let options = CommitOptions {
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&rest[0])] }],
..Default::default()
};
repo.commit_with("rest", &options).unwrap();
assert_eq!(repo.file_at(&fx.path("f.txt"), None).unwrap().as_deref(), Some(edited));
assert!(repo.status().unwrap().iter().all(|f| f.rel_path != "f.txt"));
assert_eq!(fx.read("staged.txt"), "s2\n");
// A failing pre-commit hook leaves everything as it was.
fx.write("f.txt", "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
let hook = fx.dir.join(".git/hooks/pre-commit");
std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
std::fs::write(&hook, "#!/bin/sh\nexit 1\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let head = fx.git(&["rev-parse", "HEAD"]);
let hunks = diff_hunks(edited, &fx.read("f.txt"));
let options = CommitOptions {
run_hooks: true,
partial: vec![PartialCommitFile { path: fx.path("f.txt").into(), hunks: vec![range(&hunks[0])] }],
..Default::default()
};
assert!(repo.commit_with("hooked", &options).is_err());
assert_eq!(fx.git(&["rev-parse", "HEAD"]), head);
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "");
assert_eq!(fx.read("f.txt"), "Z\nb\nc\nd\ne\nf\ng\nh\ni\nJ\nk\nl\n");
}
#[test]
fn partial_staging_with_built_patch() {
let fx = Fixture::new();
@@ -859,7 +1137,7 @@ fn errors_carry_git_messages() {
assert!(!err.message.is_empty());
let err = repo.stage(&[PathBuf::from("../outside")]).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
assert!(repo.stash_apply(5, false).is_err());
assert!(repo.stash_apply(5, false, false).is_err());
}
#[test]
+8 -4
Переглянути файл
@@ -37,8 +37,10 @@ pub struct FileEntry {
pub size: u64,
/// Milliseconds since the Unix epoch.
pub mtime_ms: f64,
/// Matched by .gitignore / exclude settings (shown dimmed, like IDEA "excluded").
/// Matched by .gitignore or the exclude settings.
pub ignored: bool,
/// Matched by the exclude settings (IDEA's "excluded": dimmed, excluded-folder icon).
pub excluded: bool,
pub hidden: bool,
/// For symlinks: what the link points to (`None` when dangling); `None`
/// for other entries.
@@ -96,8 +98,8 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
/// case-insensitively with natural number ordering.
///
/// Symlinks are reported as [`EntryKind::Symlink`] but sorted (and sized) by
/// what they point to. `ignored` reflects `excludes` (relative to the enclosing
/// repository root, else to `dir`) and the applicable `.gitignore`/`.ignore` files.
/// what they point to. `excluded` reflects `excludes` (relative to the enclosing
/// repository root, else to `dir`); `ignored` also the applicable `.gitignore`/`.ignore` files.
pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
if !fs::metadata(dir)?.is_dir() {
return Err(IdeError::invalid(format!("{} is not a directory", dir.display())));
@@ -133,7 +135,8 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let ignored = excludes.is_excluded(rel) || gitignore.is_ignored(&path, is_dir);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
entries.push((
is_dir,
FileEntry {
@@ -144,6 +147,7 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
));
+4 -1
Переглянути файл
@@ -71,6 +71,9 @@ fn read_dir_sorting_and_flags() {
assert!(get("build").ignored);
assert!(get("a.log").ignored);
assert!(get("node_modules").ignored);
// Excluded (settings) vs only git-ignored, like IDEA's excluded folders.
assert!(get("node_modules").excluded && get(".git").excluded);
assert!(!get("build").excluded && !get("a.log").excluded);
assert!(!get("src").ignored && !get("B.md").ignored && !get(".gitignore").ignored);
assert_eq!(get("src").kind, EntryKind::Dir);
assert_eq!(get("B.md").kind, EntryKind::File);
@@ -99,7 +102,7 @@ fn read_dir_sorting_and_flags() {
assert_eq!(ignored, BTreeSet::from(["local.txt", "other.log"]));
let nm = read_dir(&r.join("node_modules"), &excludes).unwrap();
assert!(nm.iter().all(|e| e.ignored), "children of excluded dirs are excluded");
assert!(nm.iter().all(|e| e.ignored && e.excluded), "children of excluded dirs are excluded");
assert_eq!(read_dir(&r.join("B.md"), &excludes).unwrap_err().kind, ErrorKind::InvalidInput);
assert_eq!(read_dir(&r.join("missing"), &excludes).unwrap_err().kind, ErrorKind::NotFound);
+21
Переглянути файл
@@ -0,0 +1,21 @@
[package]
name = "ide-web"
description = "Web browsers: the built-in static web server that serves project files on 127.0.0.1 (IDEA's built-in server) and detection / launching of installed browsers"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ide-core.workspace = true
open = "5"
parking_lot.workspace = true
percent-encoding = "2"
serde.workspace = true
specta.workspace = true
tokio = { workspace = true, features = ["net"] }
tracing.workspace = true
uuid.workspace = true
[dev-dependencies]
tempfile.workspace = true
tokio = { workspace = true, features = ["net", "rt-multi-thread", "macros"] }
+129
Переглянути файл
@@ -0,0 +1,129 @@
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
/// An installed browser.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Browser {
/// `chrome`, `firefox`, `safari`, `edge`, `brave`, `chromium`.
pub id: String,
pub name: String,
}
struct Known {
id: &'static str,
name: &'static str,
/// macOS application bundle names.
mac: &'static [&'static str],
/// Windows executables relative to Program Files / Local AppData.
windows: &'static [&'static str],
/// Linux commands on `PATH`.
linux: &'static [&'static str],
}
const KNOWN: &[Known] = &[
Known {
id: "chrome",
name: "Chrome",
mac: &["Google Chrome"],
windows: &[r"Google\Chrome\Application\chrome.exe"],
linux: &["google-chrome", "google-chrome-stable"],
},
Known {
id: "firefox",
name: "Firefox",
mac: &["Firefox", "Firefox Developer Edition"],
windows: &[r"Mozilla Firefox\firefox.exe"],
linux: &["firefox"],
},
Known { id: "safari", name: "Safari", mac: &["Safari"], windows: &[], linux: &[] },
Known {
id: "edge",
name: "Edge",
mac: &["Microsoft Edge"],
windows: &[r"Microsoft\Edge\Application\msedge.exe"],
linux: &["microsoft-edge", "microsoft-edge-stable"],
},
Known {
id: "brave",
name: "Brave",
mac: &["Brave Browser"],
windows: &[r"BraveSoftware\Brave-Browser\Application\brave.exe"],
linux: &["brave-browser", "brave"],
},
Known {
id: "chromium",
name: "Chromium",
mac: &["Chromium"],
windows: &[r"Chromium\Application\chrome.exe"],
linux: &["chromium", "chromium-browser"],
},
];
/// Where browser `k` is installed, if it is.
fn locate(k: &Known) -> Option<PathBuf> {
if cfg!(target_os = "macos") {
let mut dirs = vec![PathBuf::from("/Applications")];
if let Some(home) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(home).join("Applications"));
}
// Safari moved into the cryptex; /Applications keeps a link to it.
dirs.push(PathBuf::from("/System/Volumes/Preboot/Cryptexes/App/System/Applications"));
k.mac.iter().flat_map(|app| dirs.iter().map(move |d| d.join(format!("{app}.app")))).find(|p| p.exists())
} else if cfg!(windows) {
let bases: Vec<PathBuf> = ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
.iter()
.filter_map(std::env::var_os)
.map(PathBuf::from)
.collect();
k.windows.iter().flat_map(|exe| bases.iter().map(move |b| b.join(exe))).find(|p| p.is_file())
} else {
let path = std::env::var_os("PATH")?;
let dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
k.linux.iter().flat_map(|cmd| dirs.iter().map(move |d| d.join(cmd))).find(|p| p.is_file())
}
}
/// The known browsers installed on this machine, in a fixed order.
pub fn installed() -> Vec<Browser> {
KNOWN.iter().filter(|k| locate(k).is_some()).map(|k| Browser { id: k.id.into(), name: k.name.into() }).collect()
}
/// Opens `url` in browser `id`, or in the system default browser.
pub fn open(url: &str, id: Option<&str>) -> IdeResult<()> {
if !(url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://")) {
return Err(IdeError::invalid(format!("not a web URL: {url}")));
}
let result = match id {
None => open::that_detached(url),
Some(id) => {
let known =
KNOWN.iter().find(|k| k.id == id).ok_or_else(|| IdeError::invalid(format!("unknown browser: {id}")))?;
let app = locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?;
open::with_detached(url, app.to_string_lossy().as_ref())
}
};
result.map_err(|e| IdeError::unavailable(format!("cannot open the browser: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_unique() {
let mut ids: Vec<_> = KNOWN.iter().map(|k| k.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), KNOWN.len());
}
#[test]
fn refuses_non_web_urls() {
assert!(open("/etc/passwd", None).is_err());
assert!(open("javascript:alert(1)", None).is_err());
assert!(open("http://127.0.0.1/", Some("netscape")).is_err());
}
}
+14
Переглянути файл
@@ -0,0 +1,14 @@
//! Web browsers, like IDEA's "Open In › Browser" and the editor's browser bar.
//!
//! [`WebServer`] is the built-in server: it serves project files read-only on
//! `127.0.0.1`, so pages opened from the IDE load relative scripts, styles and
//! ES modules the way they would from a real server. Every URL starts with a
//! random per-run token, and requests whose `Host` is not the server itself are
//! refused (DNS rebinding). [`installed`] lists the browsers found on this
//! machine and [`open`] launches one, or the system default.
mod browsers;
mod server;
pub use browsers::{Browser, installed, open};
pub use server::WebServer;
+355
Переглянути файл
@@ -0,0 +1,355 @@
use ide_core::{IdeError, IdeResult};
use parking_lot::RwLock;
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
/// IDEA's built-in server port, tried first so bookmarked URLs keep working.
const PREFERRED_PORT: u16 = 63342;
const MAX_HEAD: usize = 16 * 1024;
const READ_TIMEOUT: Duration = Duration::from_secs(10);
/// Characters escaped in one URL path segment.
const SEGMENT: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'%')
.add(b'/')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'`')
.add(b'{')
.add(b'|')
.add(b'}');
struct Shared {
token: String,
/// URL key (`/<token>/<key>/…`) → served directory.
roots: RwLock<HashMap<String, PathBuf>>,
}
/// The built-in web server; started on the first [`WebServer::url_for`].
pub struct WebServer {
shared: Arc<Shared>,
port: tokio::sync::OnceCell<u16>,
}
impl Default for WebServer {
fn default() -> Self {
Self::new()
}
}
impl WebServer {
pub fn new() -> Self {
Self {
shared: Arc::new(Shared { token: uuid::Uuid::new_v4().simple().to_string(), roots: RwLock::default() }),
port: tokio::sync::OnceCell::new(),
}
}
/// The URL serving `file`: under `root` (the project) when it contains the
/// file, else under the file's directory. Starts the server if needed.
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
let base = match root {
Some(r) if file.starts_with(r) && file != r => r,
_ => file.parent().ok_or_else(|| IdeError::invalid(format!("no directory: {}", file.display())))?,
};
let rel = file.strip_prefix(base).map_err(|e| IdeError::internal(e.to_string()))?;
let port = self.port().await?;
let key = self.register(base);
let mut url = format!("http://127.0.0.1:{port}/{}/{}", self.shared.token, enc(&key));
for c in rel.components() {
url.push('/');
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
}
Ok(url)
}
/// The key `dir` is served under: its name, made unique.
fn register(&self, dir: &Path) -> String {
let mut roots = self.shared.roots.write();
if let Some((k, _)) = roots.iter().find(|(_, d)| d.as_path() == dir) {
return k.clone();
}
let name: String = dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
.chars()
.map(|c| if c.is_alphanumeric() || "._-".contains(c) { c } else { '_' })
.collect();
let name = if name.is_empty() || name == "." || name == ".." { "root".to_string() } else { name };
let key = (1..)
.map(|i| if i == 1 { name.clone() } else { format!("{name}-{i}") })
.find(|k| !roots.contains_key(k))
.expect("unbounded");
roots.insert(key.clone(), dir.to_path_buf());
key
}
async fn port(&self) -> IdeResult<u16> {
self.port
.get_or_try_init(|| async {
let listener = match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)).await {
Ok(l) => l,
Err(_) => TcpListener::bind(("127.0.0.1", 0)).await?,
};
let port = listener.local_addr()?.port();
let shared = self.shared.clone();
tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((sock, _)) => {
let shared = shared.clone();
tokio::spawn(async move {
if let Err(e) = serve(sock, &shared, port).await {
tracing::debug!("web server: {e}");
}
});
}
Err(e) => {
tracing::warn!("web server accept: {e}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
});
tracing::info!("built-in web server on 127.0.0.1:{port}");
Ok::<_, std::io::Error>(port)
})
.await
.copied()
.map_err(|e| IdeError::unavailable(format!("cannot start the built-in web server: {e}")))
}
}
fn enc(s: &str) -> String {
utf8_percent_encode(s, SEGMENT).to_string()
}
struct Request {
method: String,
target: String,
host: Option<String>,
}
async fn read_head(sock: &mut TcpStream) -> std::io::Result<Option<Request>> {
let mut reader = BufReader::new(sock).take(MAX_HEAD as u64);
let mut line = String::new();
if reader.read_line(&mut line).await? == 0 {
return Ok(None);
}
let mut parts = line.split_whitespace();
let (Some(method), Some(target)) = (parts.next(), parts.next()) else { return Ok(None) };
let (method, target) = (method.to_string(), target.to_string());
let mut host = None;
loop {
line.clear();
if reader.read_line(&mut line).await? == 0 {
return Ok(None);
}
let l = line.trim_end();
if l.is_empty() {
break;
}
if let Some((name, value)) = l.split_once(':')
&& name.eq_ignore_ascii_case("host")
{
host = Some(value.trim().to_ascii_lowercase());
}
}
Ok(Some(Request { method, target, host }))
}
enum Response {
File { path: PathBuf, len: u64 },
Redirect(String),
Error(u16, &'static str),
}
async fn serve(mut sock: TcpStream, shared: &Shared, port: u16) -> std::io::Result<()> {
let Ok(head) = tokio::time::timeout(READ_TIMEOUT, read_head(&mut sock)).await else { return Ok(()) };
let Some(req) = head? else { return Ok(()) };
let head_only = req.method == "HEAD";
let response = if !matches!(req.method.as_str(), "GET" | "HEAD") {
Response::Error(405, "Method Not Allowed")
} else if !host_allowed(req.host.as_deref(), port) {
Response::Error(403, "Forbidden")
} else {
resolve(shared, &req.target).await
};
let mut out = String::new();
match &response {
Response::File { path, len } => {
out.push_str("HTTP/1.1 200 OK\r\n");
out.push_str(&format!("Content-Type: {}\r\nContent-Length: {len}\r\n", content_type(path)));
}
Response::Redirect(to) => {
out.push_str(&format!("HTTP/1.1 301 Moved Permanently\r\nLocation: {to}\r\nContent-Length: 0\r\n"));
}
Response::Error(code, reason) => {
out.push_str(&format!(
"HTTP/1.1 {code} {reason}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\n",
reason.len()
));
}
}
out.push_str("Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n");
sock.write_all(out.as_bytes()).await?;
if !head_only {
match response {
Response::File { path, .. } => {
let mut file = tokio::fs::File::open(&path).await?;
tokio::io::copy(&mut file, &mut sock).await?;
}
Response::Error(_, reason) => sock.write_all(reason.as_bytes()).await?,
Response::Redirect(_) => {}
}
}
sock.shutdown().await
}
fn host_allowed(host: Option<&str>, port: u16) -> bool {
host.is_some_and(|h| h == format!("127.0.0.1:{port}") || h == format!("localhost:{port}"))
}
async fn resolve(shared: &Shared, target: &str) -> Response {
const NOT_FOUND: Response = Response::Error(404, "Not Found");
let path = target.split(['?', '#']).next().unwrap_or("");
let Some(rest) = path.strip_prefix('/') else { return NOT_FOUND };
let mut segments = rest.split('/');
if segments.next() != Some(shared.token.as_str()) {
return NOT_FOUND;
}
let Some(key) = segments.next().and_then(dec) else { return NOT_FOUND };
let Some(mut file) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
let mut trailing_slash = true;
for seg in segments {
trailing_slash = seg.is_empty();
if seg.is_empty() {
continue;
}
match dec(seg) {
Some(s) if s != "." && s != ".." && !s.contains(['/', '\\', ':', '\0']) => file.push(s),
_ => return NOT_FOUND,
}
}
let Ok(meta) = tokio::fs::metadata(&file).await else { return NOT_FOUND };
if meta.is_dir() {
// Relative URLs in an index page resolve against the directory.
if !trailing_slash {
return Response::Redirect(format!("{path}/"));
}
file.push("index.html");
return match tokio::fs::metadata(&file).await {
Ok(m) if m.is_file() => Response::File { path: file, len: m.len() },
_ => NOT_FOUND,
};
}
Response::File { path: file, len: meta.len() }
}
fn dec(s: &str) -> Option<String> {
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
}
fn content_type(path: &Path) -> &'static str {
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
"xml" => "application/xml; charset=utf-8",
"txt" | "md" | "csv" => "text/plain; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"ico" => "image/x-icon",
"bmp" => "image/bmp",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ttf" => "font/ttf",
"otf" => "font/otf",
"wasm" => "application/wasm",
"pdf" => "application/pdf",
"mp4" => "video/mp4",
"webm" => "video/webm",
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"ogg" => "audio/ogg",
_ => "application/octet-stream",
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn get(url: &str, host: Option<&str>) -> String {
let rest = url.strip_prefix("http://").unwrap();
let (authority, path) = rest.split_at(rest.find('/').unwrap());
let mut sock = TcpStream::connect(authority).await.unwrap();
let host = host.unwrap_or(authority);
sock.write_all(format!("GET {path} HTTP/1.1\r\nHost: {host}\r\n\r\n").as_bytes()).await.unwrap();
let mut out = String::new();
sock.read_to_string(&mut out).await.unwrap();
out
}
#[tokio::test]
async fn serves_project_files() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("my app");
std::fs::create_dir_all(root.join("web/sub")).unwrap();
std::fs::write(root.join("web/index.html"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("web/sub/a b.js"), "export {}").unwrap();
std::fs::write(dir.path().join("secret.txt"), "no").unwrap();
let server = WebServer::new();
let url = server.url_for(Some(&root), &root.join("web/index.html")).await.unwrap();
assert!(url.ends_with("/my_app/web/index.html"), "{url}");
let page = get(&url, None).await;
assert!(page.starts_with("HTTP/1.1 200"), "{page}");
assert!(page.contains("text/html") && page.ends_with("<h1>hi</h1>"));
let base = url.trim_end_matches("/web/index.html");
assert!(get(&format!("{base}/web/sub/a%20b.js"), None).await.contains("text/javascript"));
assert!(get(&format!("{base}/web"), None).await.contains("Location: /"));
assert!(get(&format!("{base}/web/"), None).await.ends_with("<h1>hi</h1>"));
assert!(get(&format!("{base}/../secret.txt"), None).await.starts_with("HTTP/1.1 404"));
assert!(get(&format!("{base}/%2e%2e/secret.txt"), None).await.starts_with("HTTP/1.1 404"));
assert!(get(&format!("{base}/web/..%2f..%2fsecret.txt"), None).await.starts_with("HTTP/1.1 404"));
// Wrong token, foreign Host (DNS rebinding).
let other = url.replacen(&server.shared.token, "0123", 1);
assert!(get(&other, None).await.starts_with("HTTP/1.1 404"));
assert!(get(&url, Some("evil.example:80")).await.starts_with("HTTP/1.1 403"));
}
#[tokio::test]
async fn files_outside_the_project_get_their_own_root() {
let dir = tempfile::tempdir().unwrap();
let (a, b) = (dir.path().join("x/site"), dir.path().join("y/site"));
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
let server = WebServer::new();
let ua = server.url_for(None, &a.join("p.html")).await.unwrap();
let ub = server.url_for(Some(&a), &b.join("p.html")).await.unwrap();
assert!(ua.ends_with("/site/p.html") && ub.ends_with("/site-2/p.html"), "{ua} {ub}");
assert_eq!(server.url_for(None, &a.join("q.html")).await.unwrap(), ua.replace("p.html", "q.html"));
}
}
+212
Переглянути файл
@@ -0,0 +1,212 @@
//! File references in text (`href="css/a.css"`, `url(../img/x.png)`,
//! `open("data/x.csv")`), resolved like IDEA's file references: relative to the
//! referencing file, `/`-rooted paths against the project root and its resource
//! roots (`public/`, `src/main/resources`), which web servers serve at `/`.
use std::path::{Component, Path, PathBuf};
/// Whether `value` names a local file at all (not a URL, an anchor, a data URI
/// or a template expression), so an unresolved one is worth reporting.
pub fn is_file_reference(value: &str) -> bool {
let v = value.trim();
!(v.is_empty()
|| v.starts_with('#')
|| v.starts_with("//")
|| v.starts_with('~')
|| has_scheme(v)
|| ["{{", "${", "<%", "{%", "<?", "@{"].iter().any(|t| v.contains(t)))
}
/// `http:`, `mailto:`, `data:`, `javascript:`… (a Windows drive `C:` is a path).
fn has_scheme(v: &str) -> bool {
match v.find(':') {
Some(i) if i > 1 => v[..i].chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)),
_ => false,
}
}
/// The path part: no `?query` / `#fragment`, percent-decoded.
pub fn path_part(value: &str) -> String {
let bare = value.trim().split(['?', '#']).next().unwrap_or_default();
percent_decode(bare)
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(b);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8(out).unwrap_or_else(|_| s.to_owned())
}
/// Removes `.` and resolves `..` lexically.
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in path.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other),
}
}
out
}
/// Directories a reference's path is looked up in, most likely first.
pub fn base_dirs(path: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
// A file outside the project is not served from its roots.
let root = root.filter(|r| from.starts_with(r));
let mut dirs: Vec<PathBuf> = Vec::new();
if path.starts_with('/') {
dirs.extend(root.map(Path::to_path_buf));
if root.is_some() {
dirs.extend(resource_roots.iter().cloned());
}
dirs.push(PathBuf::from("/"));
} else {
dirs.extend(from.parent().map(Path::to_path_buf));
// `img/a.png` from a page served at the root; never for `./` or `../`.
if !path.starts_with('.') {
dirs.extend(root.map(Path::to_path_buf));
}
}
let mut seen = Vec::new();
dirs.retain(|d| {
let fresh = !seen.contains(d);
seen.push(d.clone());
fresh
});
dirs
}
/// Paths `value` may point at, most likely first.
pub fn candidates(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathBuf> {
let path = path_part(value);
let rel = path.trim_start_matches('/');
base_dirs(&path, from, root, resource_roots).iter().map(|d| normalize(&d.join(rel))).collect()
}
/// The existing file or directory `value` names, if any.
pub fn resolve(value: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Option<PathBuf> {
if !is_file_reference(value) || path_part(value).is_empty() {
return None;
}
candidates(value, from, root, resource_roots).into_iter().find(|p| p.exists())
}
/// An entry offered when completing a path.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct PathCompletion {
pub name: String,
pub dir: bool,
}
/// Entries of the directories `prefix` (the path typed so far) continues in:
/// the part before its last `/`, looked up like a reference. Dot files only
/// when the last segment starts with `.`.
pub fn complete(prefix: &str, from: &Path, root: Option<&Path>, resource_roots: &[PathBuf]) -> Vec<PathCompletion> {
let prefix = percent_decode(prefix);
let (dir_part, last) = prefix.rsplit_once('/').map_or(("", prefix.as_str()), |(d, l)| (d, l));
let dir_value =
if prefix.starts_with('/') { format!("/{}", dir_part.trim_start_matches('/')) } else { dir_part.to_owned() };
let show_hidden = last.starts_with('.');
let rel = dir_value.trim_start_matches('/');
let mut out: Vec<PathCompletion> = Vec::new();
for base in base_dirs(&dir_value, from, root, resource_roots) {
// The file system root only as a last resort for `/` paths.
if base == Path::new("/") && !out.is_empty() {
continue;
}
let Ok(entries) = std::fs::read_dir(normalize(&base.join(rel))) else { continue };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if (name.starts_with('.') && !show_hidden) || out.iter().any(|c| c.name == name) {
continue;
}
let dir = e.file_type().is_ok_and(|t| t.is_dir()) || e.path().is_dir();
out.push(PathCompletion { name, dir });
}
}
out.sort_by(|a, b| b.dir.cmp(&a.dir).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_counts_as_a_file_reference() {
for v in ["a.css", "./a", "../img/x.png", "/splash.css", "a%20b.png?v=1#x", "C:/x"] {
assert!(is_file_reference(v), "{v}");
}
for v in [
"",
"#top",
"https://x.org",
"//cdn.x/a.js",
"mailto:a@b",
"data:image/png;base64,x",
"{{ url }}",
"${base}/a.js",
"~/x",
] {
assert!(!is_file_reference(v), "{v}");
}
assert_eq!(path_part(" img/a%20b.png?v=2#i "), "img/a b.png");
}
#[cfg(unix)]
#[test]
fn candidates_follow_ideas_rules() {
let from = Path::new("/p/web/pages/index.html");
let root = Some(Path::new("/p"));
let res = [PathBuf::from("/p/public")];
let s = |v| candidates(v, from, root, &res).into_iter().map(|p| p.display().to_string()).collect::<Vec<_>>();
assert_eq!(s("../img/a.png"), ["/p/web/img/a.png"]);
assert_eq!(s("img/a.png"), ["/p/web/pages/img/a.png", "/p/img/a.png"]);
assert_eq!(s("/splash.css"), ["/p/splash.css", "/p/public/splash.css", "/splash.css"]);
}
#[test]
fn resolves_and_completes_against_the_file_system() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
for f in ["web/index.html", "web/css/a.css", "web/css/.hidden", "public/splash.css", "public/img/logo.svg"] {
let p = root.join(f);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
}
let from = root.join("web/index.html");
let res = [root.join("public")];
let r = |v| resolve(v, &from, Some(root), &res);
assert_eq!(r("css/a.css?v=1"), Some(root.join("web/css/a.css")));
assert_eq!(r("/splash.css"), Some(root.join("public/splash.css")));
assert_eq!(r("css/missing.css"), None);
assert_eq!(r("https://x.org/a.css"), None);
let names = |p| complete(p, &from, Some(root), &res).into_iter().map(|c| (c.name, c.dir)).collect::<Vec<_>>();
assert_eq!(names("css/"), [("a.css".into(), false)]);
assert_eq!(names("css/."), [(".hidden".into(), false), ("a.css".into(), false)]);
assert_eq!(
names("/im"),
[("img".into(), true), ("public".into(), true), ("web".into(), true), ("splash.css".into(), false)]
);
assert_eq!(names("/img/"), [("logo.svg".into(), false)]);
}
}
+1
Переглянути файл
@@ -5,6 +5,7 @@ pub mod documents;
pub mod editorconfig;
pub mod file_defaults;
pub mod file_moves;
pub mod file_refs;
pub mod history;
pub mod memory;
pub mod process;
+4
Переглянути файл
@@ -192,6 +192,8 @@ fn module_roots(root: &Path, rel: &str, files: &[String], out: &mut Vec<SourceFo
// A JVM build's `src` holds source sets, not JavaScript.
if !has("pom.xml") && !GRADLE_FILES.iter().any(|f| has(f)) {
add("src", RootKind::Source, "package.json");
// Served at `/` by Vite, Next and Create React App: `href="/logo.svg"` resolves here.
add("public", RootKind::Resources, "package.json");
for t in ["test", "tests", "__tests__"] {
add(t, RootKind::Test, "package.json");
}
@@ -330,6 +332,7 @@ mod tests {
"flat/tests/",
"web/package.json",
"web/src/",
"web/public/",
"web/__tests__/",
"web/node_modules/x/package.json",
"web/dist/",
@@ -351,6 +354,7 @@ mod tests {
"web/__tests__=Test@web/package.json",
"web/dist=Excluded@web/package.json",
"web/node_modules=Excluded@web/package.json",
"web/public=Resources@web/package.json",
"web/src=Source@web/package.json",
]
);
+5
Переглянути файл
@@ -107,6 +107,11 @@ impl ProjectRoots {
}
}
/// Effective resource folders (project-relative): served at `/` for web file references.
pub fn resource_dirs(&self) -> Vec<&str> {
self.roots.iter().filter(|r| r.kind == RootKind::Resources).map(|r| r.path.as_str()).collect()
}
/// Effective excluded folders as anchored globs (`/target`), for the index, watcher and search.
pub fn excluded_globs(&self) -> Vec<String> {
self.roots
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ test("Search Everywhere finds and runs an action", async ({ workbench: page }) =
await expect(option).toBeVisible();
await page.keyboard.press("Enter");
await expect(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
await expect(page.getByRole("table", { name: /language servers/i })).toBeVisible();
await expect(page.getByRole("list", { name: /language servers/i })).toBeVisible();
});
test("Search Everywhere finds a file and opens it", async ({ workbench: page }) => {
+12 -10
Переглянути файл
@@ -17,17 +17,19 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
// The page tree is virtualized; search brings the page into view.
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Language Servers");
await dialog.getByRole("treeitem", { name: "Language Servers", exact: true }).click();
const table = dialog.getByRole("table", { name: /language servers/i });
await expect(table).toBeVisible();
const list = dialog.getByRole("list", { name: /language servers/i });
await expect(list).toBeVisible();
const row = table.locator('tr[data-tool="gopls"]');
await expect(row).toContainText("Missing");
await row.getByRole("button", { name: "Install gopls" }).click();
await expect(table.getByRole("progressbar", { name: "Installing gopls" })).toBeVisible();
await expect(row).toContainText("Installed");
await expect(row).toContainText("1.0.0");
await expect(row.getByRole("button", { name: "Uninstall gopls" })).toBeVisible();
await list.locator('[data-tool="gopls"]').click();
const details = dialog.getByLabel("gopls details");
await expect(details).toContainText("Missing");
await details.getByRole("button", { name: "Install gopls" }).click();
await expect(details.getByRole("progressbar", { name: "Installing gopls" })).toBeVisible();
await expect(details).toContainText("Installed");
await expect(details).toContainText("1.0.0");
await expect(details.getByRole("button", { name: "Uninstall" })).toBeVisible();
// Tools without an installer explain how to get them.
await expect(table).toContainText("gem install solargraph");
await list.locator('[data-tool="solargraph"]').click();
await expect(dialog.getByLabel("solargraph details")).toContainText("gem install solargraph");
});
+2 -2
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.8",
"version": "0.1.13",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -41,12 +41,12 @@
"@tauri-apps/plugin-opener": "^2",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-search": "^0.16.0",
"@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^6.0.0",
"anser": "^2.3.5",
"clsx": "^2.1.1",
"codemirror": "^6.0.2",
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"marked": "^18.1.1",
"react": "^19.1.0",
Створено
+30 -8
Переглянути файл
@@ -65,9 +65,6 @@ importers:
'@xterm/addon-search':
specifier: ^0.16.0
version: 0.16.0
'@xterm/addon-webgl':
specifier: ^0.19.0
version: 0.19.0
'@xterm/xterm':
specifier: ^6.0.0
version: 6.0.0
@@ -83,6 +80,9 @@ importers:
dompurify:
specifier: ^3.4.17
version: 3.4.17
emmet:
specifier: 2.4.11
version: 2.4.11
immer:
specifier: ^11.1.21
version: 11.1.21
@@ -386,6 +386,15 @@ packages:
resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==}
engines: {node: '>=20.19.0'}
'@emmetio/[email protected]':
resolution: {integrity: sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA==}
'@emmetio/[email protected]':
resolution: {integrity: sha512-s9yjhJ6saOO/uk1V74eifykk2CBYi01STTK3WlXWGOepyKa23ymJ053+DNQjpFcy1ingpaO7AxCcwLvHFY9tuw==}
'@emmetio/[email protected]':
resolution: {integrity: sha512-IqRuJtQff7YHHBk4G8YZ45uB9BaAGcwQeVzgj/zj8/UdOhtQpEIupUhSk8dys6spFIWVZVeK20CzGEnqR5SbqA==}
'@eslint-community/[email protected]':
resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
@@ -918,9 +927,6 @@ packages:
'@xterm/[email protected]':
resolution: {integrity: sha512-9OeuBFu0/uZJPu+9AHKY6g/w0Czyb/Ut0A5t79I4ULoU4IfU5BEpPFVGQxP4zTTMdfZEYkVIRYbHBX1xWwjeSA==}
'@xterm/[email protected]':
resolution: {integrity: sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
@@ -1056,6 +1062,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-4SC9HHSFjO/liAhifpdOL5hG9b4BP7/5G3y3UPZVO8trlAXr1CaUEEJL0gWK3kOcYcZrOA5rkwG45Gra/lTIgg==}
[email protected]:
resolution: {integrity: sha512-23QPJB3moh/U9sT4rQzGgeyyGIrcM+GH5uVYg2C6wZIxAIJq7Ng3QLT79tl8FUwDXhyq9SusfknOrofAKqvgyQ==}
[email protected]:
resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==}
engines: {node: '>=20.19.0'}
@@ -2162,6 +2171,16 @@ snapshots:
'@csstools/[email protected]': {}
'@emmetio/[email protected]':
dependencies:
'@emmetio/scanner': 1.0.4
'@emmetio/[email protected]':
dependencies:
'@emmetio/scanner': 1.0.4
'@emmetio/[email protected]': {}
'@eslint-community/[email protected]([email protected])':
dependencies:
eslint: 10.13.0
@@ -2657,8 +2676,6 @@ snapshots:
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
[email protected]([email protected]):
@@ -2780,6 +2797,11 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
'@emmetio/abbreviation': 2.3.3
'@emmetio/css-abbreviation': 2.1.8
[email protected]: {}
[email protected]: {}
+1
Переглянути файл
@@ -53,6 +53,7 @@ ide-coverage.workspace = true
ide-profiler.workspace = true
ide-http.workspace = true
ide-db.workspace = true
ide-web.workspace = true
ide-tools = { path = "../crates/ide-tools" }
ide-plugin = { path = "../crates/ide-plugin" }
ide-docker = { path = "../crates/ide-docker" }
+8
Переглянути файл
@@ -109,6 +109,14 @@ pub fn settings_get(window: Window, state: State<'_, AppState>) -> Settings {
}
}
/// Defaults plus the global layer, without any project's values: what new
/// projects (and projects without their own value) get.
#[tauri::command]
#[specta::specta]
pub fn settings_get_global(state: State<'_, AppState>) -> Settings {
state.global_settings.effective()
}
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
/// re-reads its effective settings.
+26
Переглянути файл
@@ -156,6 +156,21 @@ pub async fn lsp_code_action_query(
result
}
/// Resolves a code action's edit without applying it (intention preview).
#[tauri::command]
#[specta::specta]
pub async fn lsp_resolve_code_action(
window: Window,
state: State<'_, AppState>,
doc: DocId,
action: CodeAction,
) -> IdeResult<CodeAction> {
if action.edit.is_some() {
return Ok(action);
}
project!(window, state).lsp.resolve_code_action(doc, action).await
}
/// Resolves (if needed), applies the edit, then runs the command of a code action.
#[tauri::command]
#[specta::specta]
@@ -243,6 +258,17 @@ pub async fn lsp_code_lens(window: Window, state: State<'_, AppState>, doc: DocI
project!(window, state).lsp.code_lens(doc).await
}
/// Links in a document (`href`s, Markdown links, `#include`s…) from its language servers.
#[tauri::command]
#[specta::specta]
pub async fn lsp_document_links(
window: Window,
state: State<'_, AppState>,
doc: DocId,
) -> IdeResult<Vec<DocumentLink>> {
project!(window, state).lsp.document_links(doc).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_call_hierarchy(
+17
Переглянути файл
@@ -34,6 +34,7 @@ pub mod syntax;
pub mod term;
pub mod tools;
pub mod vcs;
pub mod web;
pub mod window;
use tauri_specta::collect_commands;
@@ -48,6 +49,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::close_project,
app::languages,
app::settings_get,
app::settings_get_global,
app::settings_set,
app::project_roots,
app::cancel_request,
@@ -101,6 +103,11 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
nav::find_symbols,
nav::mark_recent,
nav::recent_files,
nav::remove_recent,
nav::web_goto,
nav::fs_resolve_reference,
nav::path_completions,
nav::web_unresolved_references,
search::search_start,
search::replace_in_files,
search::replace_preview,
@@ -116,6 +123,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_workspace_symbols,
lsp::lsp_code_actions,
lsp::lsp_code_action_query,
lsp::lsp_resolve_code_action,
lsp::lsp_apply_code_action,
lsp::lsp_prepare_rename,
lsp::lsp_rename,
@@ -123,6 +131,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_inlay_hints,
lsp::lsp_semantic_tokens,
lsp::lsp_code_lens,
lsp::lsp_document_links,
lsp::lsp_call_hierarchy,
lsp::lsp_type_hierarchy,
lsp::lsp_servers,
@@ -146,6 +155,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_commit,
vcs::vcs_checkout,
vcs::vcs_delete_branch,
vcs::vcs_restore_branch,
vcs::vcs_create_branch,
vcs::vcs_undo_commit,
vcs::vcs_rename_branch,
@@ -167,6 +177,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_create_tag,
vcs::vcs_tags,
vcs::vcs_diff_with_worktree,
vcs::vcs_diff_revisions,
vcs::vcs_create_patch,
vcs::vcs_patch_preview,
vcs::vcs_apply_patch,
@@ -183,7 +194,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
term::term_write,
term::term_resize,
term::term_kill,
term::term_is_busy,
term::term_default_shell,
term::term_available_shells,
run::run_configs,
run::run_save_configs,
run::run_start,
@@ -238,6 +251,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::app_log_location,
window::app_build_info,
window::app_check_update,
window::app_startup_update_check,
window::app_install_update,
debug::debug_exception_filters,
debug::debug_set_exception_breakpoints,
@@ -254,6 +268,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
debug::debug_redefine_classes,
coverage::coverage_prepare,
coverage::coverage_collect,
web::web_browsers,
web::web_url,
web::web_open,
profiler::profiler_prepare,
profiler::profiler_collect,
plugin::plugin_subscribe,
+136 -2
Переглянути файл
@@ -1,6 +1,11 @@
use crate::state::AppState;
use ide_core::IdeResult;
use super::doc::blocking;
use crate::state::{AppState, Project};
use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
use ide_index::{FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
use tauri::{State, Window};
@@ -35,9 +40,138 @@ pub fn mark_recent(window: Window, state: State<'_, AppState>, path: PathBuf) ->
Ok(())
}
#[tauri::command]
#[specta::specta]
pub fn remove_recent(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<()> {
state.project(window.label())?.index.remove_recent(&path);
Ok(())
}
/// Recently opened files, most recent first (⌘E).
#[tauri::command]
#[specta::specta]
pub fn recent_files(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ide_core::IpcPath>> {
Ok(state.project(window.label())?.index.recent_files().into_iter().map(Into::into).collect())
}
/// A web reference no language server resolves and where it points: `class="card"` →
/// `.card` selectors, `id` → `#id` selectors, `href="#top"` → the element, `var(--x)` →
/// `--x:` declarations.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct WebGoto {
pub reference: WebReference,
pub targets: Vec<Location>,
}
const MAX_WEB_TARGETS: usize = 200;
/// The web reference at `pos` of `doc` and its targets; `None` when there is no reference.
#[tauri::command]
#[specta::specta]
pub async fn web_goto(window: Window, state: State<'_, AppState>, doc: DocId, pos: Pos) -> IdeResult<Option<WebGoto>> {
let project = state.project(window.label())?;
let syntax = state.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large {
return Ok(None);
}
let Some(reference) = syntax.web_reference_at(&snap.language, &snap.text, pos) else { return Ok(None) };
let here = |range| Location { path: snap.path.clone(), range, uri: None };
let targets = match reference.symbol() {
None => syntax.web_anchors(&snap.language, &snap.text, &reference.name).into_iter().map(here).collect(),
Some((name, kind)) => {
// The open document from its (possibly unsaved) text, other files from the index.
let mut targets: Vec<Location> = syntax
.web_definitions(&snap.language, &snap.text)
.into_iter()
.filter(|t| t.name == name && t.kind == kind)
.map(|t| here(t.range))
.collect();
targets.extend(
project
.index
.symbols_named(&name, Some(kind), MAX_WEB_TARGETS)
.into_iter()
.filter(|m| *m.path != *snap.path)
.map(|m| Location { path: m.path, range: m.range, uri: None }),
);
targets
}
};
Ok(Some(WebGoto { reference, targets }))
})
.await
}
/// The project root and its resource roots (served at `/`), for file references.
fn reference_roots(project: &Project) -> (PathBuf, Vec<PathBuf>) {
let resources = project.roots().resource_dirs().iter().map(|d| project.root.join(d)).collect();
(project.root.clone(), resources)
}
/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
#[tauri::command]
#[specta::specta]
pub async fn fs_resolve_reference(
window: Window,
state: State<'_, AppState>,
from: IpcPath,
value: String,
) -> IdeResult<Option<IpcPath>> {
let project = state.project(window.label()).ok();
blocking(move || {
let (root, resources) = project.as_deref().map(reference_roots).unzip();
let resources = resources.unwrap_or_default();
Ok(file_refs::resolve(&value, &from, root.as_deref(), &resources).map(Into::into))
})
.await
}
/// Files and folders that continue `prefix`, a path being typed in `from`.
#[tauri::command]
#[specta::specta]
pub async fn path_completions(
window: Window,
state: State<'_, AppState>,
from: IpcPath,
prefix: String,
) -> IdeResult<Vec<PathCompletion>> {
let project = state.project(window.label()).ok();
blocking(move || {
let (root, resources) = project.as_deref().map(reference_roots).unzip();
let resources = resources.unwrap_or_default();
Ok(file_refs::complete(&prefix, &from, root.as_deref(), &resources))
})
.await
}
/// Paths in an HTML document or stylesheet that name no existing file.
#[tauri::command]
#[specta::specta]
pub async fn web_unresolved_references(
window: Window,
state: State<'_, AppState>,
doc: DocId,
) -> IdeResult<Vec<FileReference>> {
let project = state.project(window.label())?;
let syntax = state.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large {
return Ok(Vec::new());
}
let (root, resources) = reference_roots(&project);
Ok(syntax
.web_file_references(&snap.language, &snap.text)
.into_iter()
.filter(|r| {
file_refs::is_file_reference(&r.value)
&& !file_refs::path_part(&r.value).is_empty()
&& file_refs::resolve(&r.value, &snap.path, Some(&root), &resources).is_none()
})
.collect())
})
.await
}
+27 -3
Переглянути файл
@@ -40,6 +40,8 @@ pub async fn search_start(
let cancel = state.begin_request(request);
let documents = project.documents.clone();
let root = project.root.clone();
let languages = state.languages.clone();
let syntax = state.syntax();
let events = on_event.clone();
let summary = tauri::async_runtime::spawn_blocking(move || {
let filter = |rel: &str| match set {
@@ -47,9 +49,23 @@ pub async fn search_start(
Some(ProjectFileSet::Test) => roots.is_test(rel),
Some(ProjectFileSet::All) | None => true,
};
ide_search::search_filtered(&root, &query, Some(&filter), &|p| documents.text_of(p), &cancel, &|file| {
let _ = events.send(SearchEvent::File { file });
})
// Comments and string literals for the search context filter.
let literals = |path: &Path, text: &str| {
let language = languages.detect(path, text.lines().next());
let found = syntax.literals(&language, text)?;
Some(found.into_iter().map(literal_range).collect())
};
ide_search::search_in_context(
&root,
&query,
Some(&filter),
Some(&literals),
&|p| documents.text_of(p),
&cancel,
&|file| {
let _ = events.send(SearchEvent::File { file });
},
)
})
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
@@ -116,6 +132,14 @@ pub async fn replace_preview(
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
}
fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
let kind = match l.kind {
ide_language::LiteralKind::Comment => ide_search::LiteralKind::Comment,
ide_language::LiteralKind::String => ide_search::LiteralKind::String,
};
ide_search::LiteralRange { start: l.start, end: l.end, kind }
}
struct DocumentsHost<'a>(&'a Documents);
impl ReplaceHost for DocumentsHost<'_> {
+15
Переглянути файл
@@ -48,9 +48,24 @@ pub fn term_kill(state: State<'_, AppState>, id: TerminalId) -> IdeResult<()> {
state.terminals.kill(id)
}
/// Whether the session is running a command (closing its tab asks first). A
/// `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
#[tauri::command]
#[specta::specta]
pub async fn term_is_busy(state: State<'_, AppState>, id: TerminalId) -> IdeResult<bool> {
state.terminals.is_busy(id)
}
/// Shell used when Settings › Terminal › Shell path is empty.
#[tauri::command]
#[specta::specta]
pub fn term_default_shell() -> String {
ide_terminal::default_shell_path()
}
/// Installed shells for the Terminal's "New Predefined Session" menu.
#[tauri::command]
#[specta::specta]
pub fn term_available_shells() -> Vec<String> {
ide_terminal::available_shells()
}
+60 -26
Переглянути файл
@@ -185,10 +185,15 @@ pub async fn vcs_checkout(
repo: Option<PathBuf>,
branch: String,
create: bool,
) -> IdeResult<()> {
options: Option<ide_vcs::CheckoutOptions>,
) -> IdeResult<ide_vcs::CheckoutOutcome> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout(&branch, create)))
.await
let options = options.unwrap_or_default();
blocking(move || {
project
.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| r.checkout_with(&branch, create, &options))
})
.await
}
/// New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out.
@@ -231,10 +236,22 @@ pub async fn vcs_delete_branch(
state: State<'_, AppState>,
repo: Option<PathBuf>,
branch: String,
force: bool,
) -> IdeResult<ide_vcs::DeletedBranch> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch_restorable(&branch))).await
}
/// "Restore" of the branch-deleted notification.
#[tauri::command]
#[specta::specta]
pub async fn vcs_restore_branch(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
deleted: ide_vcs::DeletedBranch,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_branch(&branch, force))).await
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_branch(&deleted))).await
}
#[tauri::command]
@@ -282,11 +299,12 @@ pub async fn vcs_stash_push(
repo: Option<PathBuf>,
message: Option<String>,
include_untracked: bool,
keep_index: bool,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || {
project.with_repo_recorded(repo.as_deref(), Some("Git stash"), |r| {
r.stash_push(message.as_deref(), include_untracked)
r.stash_push(message.as_deref(), include_untracked, keep_index)
})
})
.await
@@ -300,10 +318,17 @@ pub async fn vcs_stash_apply(
repo: Option<PathBuf>,
index: u32,
pop: bool,
reinstate_index: bool,
branch: Option<String>,
) -> IdeResult<()> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| r.stash_apply(index, pop)))
.await
blocking(move || {
project.with_repo_recorded(repo.as_deref(), Some("Git unstash"), |r| match branch.as_deref() {
Some(name) => r.stash_branch(index, name),
None => r.stash_apply(index, pop, reinstate_index),
})
})
.await
}
#[tauri::command]
@@ -336,11 +361,14 @@ pub enum RemoteOp {
DeleteBranch {
branch: String,
},
/// Pushes local `branch` (only up to `revision` when set) to its upstream.
/// Pushes local `branch` (only up to `revision` when set) to its upstream, or to
/// remote branch `target` of the same remote.
PushBranch {
branch: String,
revision: Option<String>,
force_with_lease: bool,
#[serde(default)]
target: Option<String>,
},
/// Fast-forwards local `branch` (not checked out) to its upstream.
UpdateBranch {
@@ -373,9 +401,12 @@ pub async fn vcs_remote(
r.push_with_tags(force_with_lease, set_upstream, tags, &cancel, &out)
}
RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out),
RemoteOp::PushBranch { branch, revision, force_with_lease } => {
r.push_branch(&branch, revision.as_deref(), force_with_lease, &cancel, &out)
}
RemoteOp::PushBranch { branch, revision, force_with_lease, target } => match target {
Some(target) => {
r.push_branch_to(&branch, revision.as_deref(), &target, force_with_lease, &cancel, &out)
}
None => r.push_branch(&branch, revision.as_deref(), force_with_lease, &cancel, &out),
},
RemoteOp::UpdateBranch { branch } => r.update_branch(&branch, &cancel, &out),
})
})
@@ -385,27 +416,16 @@ pub async fn vcs_remote(
result
}
#[derive(Serialize, Deserialize, Type)]
pub struct ConflictVersions {
pub base: Option<String>,
pub ours: Option<String>,
pub theirs: Option<String>,
}
/// The user's side is `ours` (sides swapped during a rebase, as in IDEA).
#[tauri::command]
#[specta::specta]
pub async fn vcs_conflict_versions(
window: Window,
state: State<'_, AppState>,
path: PathBuf,
) -> IdeResult<ConflictVersions> {
) -> IdeResult<ide_vcs::MergeVersions> {
let project = state.project(window.label())?;
blocking(move || {
project.with_repo_of(&path, |r| {
r.conflict_versions(&path).map(|(base, ours, theirs)| ConflictVersions { base, ours, theirs })
})
})
.await
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path))).await
}
#[tauri::command]
@@ -622,6 +642,20 @@ pub async fn vcs_diff_with_worktree(
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_with_worktree(&rev))).await
}
/// Files that differ between two revisions (the "N files updated" of Update Project).
#[tauri::command]
#[specta::specta]
pub async fn vcs_diff_revisions(
window: Window,
state: State<'_, AppState>,
repo: Option<PathBuf>,
from: String,
to: String,
) -> IdeResult<Vec<ChangedFile>> {
let project = state.project(window.label())?;
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
}
/// Runs `f` once per repository with the `paths` that belong to it.
fn per_repo(
project: &Project,
+29
Переглянути файл
@@ -0,0 +1,29 @@
//! Web browsers: the built-in server's URLs and launching browsers.
use super::coverage::blocking;
use crate::state::AppState;
use ide_core::{IdeResult, IpcPath};
use ide_web::Browser;
use tauri::{State, Window};
/// The browsers installed on this machine.
#[tauri::command]
#[specta::specta]
pub async fn web_browsers() -> IdeResult<Vec<Browser>> {
blocking(|| Ok(ide_web::installed())).await
}
/// The built-in server's URL for `path` (started on first use).
#[tauri::command]
#[specta::specta]
pub async fn web_url(window: Window, state: State<'_, AppState>, path: IpcPath) -> IdeResult<String> {
let root = state.project(window.label()).ok().map(|p| p.root.clone());
state.web.url_for(root.as_deref(), &path).await
}
/// Opens `url` in `browser` (an id from `web_browsers`), or the default browser.
#[tauri::command]
#[specta::specta]
pub async fn web_open(url: String, browser: Option<String>) -> IdeResult<()> {
blocking(move || ide_web::open(&url, browser.as_deref())).await
}
+24 -2
Переглянути файл
@@ -24,7 +24,8 @@ pub async fn window_new(app: AppHandle) -> IdeResult<String> {
windows::create_window(&app, None).map(|w| w.label().to_owned())
}
/// Opens this window's Settings window on `page` (or focuses it and navigates).
/// Opens this window's Settings window on `page` (or focuses it and navigates);
/// `new_projects` edits the global layer only ("Settings for New Projects").
/// `background` (`#rrggbb`) paints a new window until its page has loaded.
#[tauri::command]
#[specta::specta]
@@ -32,9 +33,10 @@ pub async fn window_open_settings(
app: AppHandle,
window: WebviewWindow,
page: Option<String>,
new_projects: bool,
background: Option<String>,
) -> IdeResult<()> {
windows::open_settings_window(&app, &window, page, background)
windows::open_settings_window(&app, &window, page, new_projects, background)
}
/// Focuses the next / previous window (⌘` / ⇧⌘`).
@@ -268,6 +270,26 @@ pub async fn app_check_update(app: AppHandle) -> IdeResult<UpdateCheck> {
})
}
/// The background check made once per process when the first window starts;
/// later calls (other windows) and debug builds get `None`. Failures are logged,
/// not reported: the user didn't ask for this check.
#[tauri::command]
#[specta::specta]
pub async fn app_startup_update_check(app: AppHandle) -> Option<UpdateInfo> {
use std::sync::atomic::{AtomicBool, Ordering};
static DONE: AtomicBool = AtomicBool::new(false);
if cfg!(debug_assertions) || DONE.swap(true, Ordering::SeqCst) {
return None;
}
match app_check_update(app).await {
Ok(check) => check.update,
Err(e) => {
tracing::warn!("startup update check failed: {e}");
None
}
}
}
/// Downloads and installs the available update, then quits through every
/// window's unsaved-changes check and relaunches. If a window cancels the quit,
/// the update applies on the next start.
+6 -2
Переглянути файл
@@ -79,7 +79,7 @@ pub fn run() {
if let Ok(cwd) = std::env::current_dir()
&& let Some(path) = windows::cli_path(&std::env::args().collect::<Vec<_>>(), &cwd)
{
windows.set_launch("main", windows::Launch { project: Some(path.into()), settings_page: None });
windows.set_launch("main", windows::Launch { project: Some(path.into()), ..Default::default() });
}
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
@@ -135,7 +135,11 @@ fn on_menu_event(app: &tauri::AppHandle, event: tauri::menu::MenuEvent) {
Some(w) => {
// Settings is modal for its project window: only app-level items get through, to the parent.
let label = match windows::settings_parent(w.label()) {
Some(parent) if matches!(route.action.as_str(), "app.quit" | "file.settings") => parent,
Some(parent)
if matches!(route.action.as_str(), "app.quit" | "file.settings" | "file.newProjectsSettings") =>
{
parent
}
Some(_) => return,
None => w.label(),
};
+6
Переглянути файл
@@ -208,6 +208,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.save", "Save All"),
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
SEP,
sub(
"newProjectsSetup",
"New Projects Setup",
vec![act("file.newProjectsSettings", "Settings for New Projects…")],
),
act("file.invalidateCaches", "Invalidate Caches…"),
];
if !mac {
@@ -972,6 +977,7 @@ mod tests {
"file.closeProject",
"file.save",
"file.settings",
"file.newProjectsSettings",
"window.new",
"window.next",
"window.previous",
+8
Переглянути файл
@@ -37,6 +37,8 @@ pub struct AppState {
pub debugger: Arc<DebugManager>,
/// WASM plugins (`ide-plugin`), shared by all windows.
pub plugins: Arc<ide_plugin::PluginHost>,
/// The built-in web server (Open In › Browser, the editor's browser bar).
pub web: ide_web::WebServer,
/// Broadcasts to every window.
pub sink: SharedSink,
/// One project per window, keyed by window label.
@@ -121,6 +123,7 @@ impl AppState {
debugger: DebugManager::new(languages.clone()),
sink: global_sink,
plugins: crate::commands::plugin::create_host(&app, &data_dir)?,
web: ide_web::WebServer::new(),
syntax,
startup: Startup {
process_to_main,
@@ -259,12 +262,17 @@ impl AppState {
if let Some(problem) = lombok.problem() {
tracing::warn!("{problem}");
}
let server_jdk = ide_sdk::apply::jdtls_jdk(&root, &effective).unwrap_or_else(|e| {
cfg.launch_error = Some(e);
None
});
ide_sdk::java::configure_jdtls(
cfg,
server_root,
&data_dir,
&jdks,
ide_sdk::apply::project_jdk(&root, &effective).as_ref(),
server_jdk.as_ref(),
min_java,
&bundles,
lombok.jar(),
+9 -6
Переглянути файл
@@ -39,6 +39,8 @@ pub struct Launch {
pub project: Option<ide_core::IpcPath>,
/// Settings windows: the page to show.
pub settings_page: Option<String>,
/// Settings windows: edit the global layer only ("Settings for New Projects").
pub new_projects: bool,
}
#[derive(Default)]
@@ -271,7 +273,7 @@ pub fn create_window(app: &AppHandle, project: Option<PathBuf>) -> IdeResult<Web
config.y = Some(pos.y + CASCADE);
config.center = false;
}
app.state::<WindowsState>().set_launch(&label, Launch { project: project.map(Into::into), settings_page: None });
app.state::<WindowsState>().set_launch(&label, Launch { project: project.map(Into::into), ..Default::default() });
let window = build_project_window(app, config)?;
focus(&window);
Ok(window)
@@ -338,7 +340,7 @@ pub fn open_path(app: &AppHandle, path: &Path) {
match free {
Some(w) => {
app.state::<WindowsState>()
.set_launch(w.label(), Launch { project: Some(root.into()), settings_page: None });
.set_launch(w.label(), Launch { project: Some(root.into()), ..Default::default() });
let _ = app.emit_to(w.label(), LAUNCH_EVENT, ());
focus(&w);
}
@@ -375,6 +377,7 @@ pub fn open_settings_window(
app: &AppHandle,
parent: &WebviewWindow,
page: Option<String>,
new_projects: bool,
background: Option<String>,
) -> IdeResult<()> {
// Asked from a settings window itself: navigate it.
@@ -382,8 +385,8 @@ pub fn open_settings_window(
let label = settings_label(&parent_label);
let windows = app.state::<WindowsState>();
if let Some(existing) = app.get_webview_window(&label) {
if page.is_some() {
windows.set_launch(&label, Launch { project: None, settings_page: page });
if page.is_some() || new_projects {
windows.set_launch(&label, Launch { project: None, settings_page: page, new_projects });
let _ = app.emit_to(label.as_str(), LAUNCH_EVENT, ());
}
focus(&existing);
@@ -406,7 +409,7 @@ pub fn open_settings_window(
if let Some(color) = background.and_then(|c| serde_json::from_value(serde_json::Value::String(c)).ok()) {
config.background_color = Some(color);
}
windows.set_launch(&label, Launch { project: None, settings_page: page });
windows.set_launch(&label, Launch { project: None, settings_page: page, new_projects });
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.parent(&parent))
.and_then(|b| b.build())
@@ -485,7 +488,7 @@ mod tests {
#[test]
fn launches_are_taken_once() {
let st = WindowsState::default();
st.set_launch("project-1", Launch { project: Some("/p".into()), settings_page: None });
st.set_launch("project-1", Launch { project: Some("/p".into()), ..Default::default() });
assert_eq!(st.take_launch("project-1").and_then(|l| l.project), Some("/p".into()));
assert_eq!(st.take_launch("project-1"), None);
}
+5 -4
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.8",
"version": "0.1.13",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -30,12 +30,13 @@
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' asset: data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:"
"csp": "default-src 'self'; img-src 'self' asset: data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:*"
}
},
"bundle": {
"active": true,
"targets": "all",
"createUpdaterArtifacts": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
@@ -56,8 +57,8 @@
"mainBinaryName": "openidea",
"plugins": {
"updater": {
"pubkey": "",
"endpoints": []
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFCOUU0MUFFOUY4NzZCNkQKUldSdGE0ZWZya0dlRzNnRFJUR2loUVdNZ1BmamxkNzFoaWNPUTBsRmI0cjhxZFRqQURybkMwakEK",
"endpoints": ["https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json"]
}
}
}
+344 -28
Переглянути файл
@@ -22,6 +22,11 @@ export const commands = {
languages: () => __TAURI_INVOKE<LanguageInfo_Serialize[]>("languages"),
/** Effective settings for the window's project, or global settings without one. */
settingsGet: () => __TAURI_INVOKE<Settings_Serialize>("settings_get"),
/**
* Defaults plus the global layer, without any project's values: what new
* projects (and projects without their own value) get.
*/
settingsGetGlobal: () => __TAURI_INVOKE<Settings_Serialize>("settings_get_global"),
/**
* `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
* value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
@@ -181,6 +186,18 @@ export const commands = {
markRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("mark_recent", { path })),
/** Recently opened files, most recent first (⌘E). */
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
removeRecent: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remove_recent", { path })),
/** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */
webGoto: (doc: DocId, pos: Pos) => typedError<{
reference: WebReference,
targets: Location[],
} | null, IdeError>(__TAURI_INVOKE("web_goto", { doc, pos })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/** Files and folders that continue `prefix`, a path being typed in `from`. */
pathCompletions: (from: IpcPath, prefix: string) => typedError<PathCompletion[], IdeError>(__TAURI_INVOKE("path_completions", { from, prefix })),
/** Paths in an HTML document or stylesheet that name no existing file. */
webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -223,6 +240,8 @@ export const commands = {
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
/** Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability). */
lspCodeActionQuery: (request: RequestId, doc: DocId, range: Range, only: string[]) => typedError<CodeActionQuery, IdeError>(__TAURI_INVOKE("lsp_code_action_query", { request, doc, range, only })),
/** Resolves a code action's edit without applying it (intention preview). */
lspResolveCodeAction: (doc: DocId, action: CodeAction) => typedError<CodeAction, IdeError>(__TAURI_INVOKE("lsp_resolve_code_action", { doc, action })),
/** Resolves (if needed), applies the edit, then runs the command of a code action. */
lspApplyCodeAction: (doc: DocId, action: CodeAction) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_apply_code_action", { doc, action })),
lspPrepareRename: (doc: DocId, pos: Pos) => typedError<{
@@ -243,6 +262,8 @@ export const commands = {
tokenModifiers: string[],
} | null, IdeError>(__TAURI_INVOKE("lsp_semantic_tokens", { doc })),
lspCodeLens: (doc: DocId) => typedError<CodeLens[], IdeError>(__TAURI_INVOKE("lsp_code_lens", { doc })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
lspCallHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_call_hierarchy", { doc, pos, direction })),
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
lspServers: () => typedError<ServerInfo[], IdeError>(__TAURI_INVOKE("lsp_servers")),
@@ -272,8 +293,14 @@ export const commands = {
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
vcsCommit: (repo: string | null, message: string, options: CommitOptions) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_commit", { repo, message, options })),
vcsCheckout: (repo: string | null, branch: string, create: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create })),
vcsDeleteBranch: (repo: string | null, branch: string, force: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch, force })),
vcsCheckout: (repo: string | null, branch: string, create: boolean, options: {
mode?: CheckoutMode,
/** Required when checking out a remote branch whose local namesake is ahead of it. */
diverged?: DivergedLocal | null,
} | null) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })),
vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
/** "Restore" of the branch-deleted notification. */
vcsRestoreBranch: (repo: string | null, deleted: DeletedBranch) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_branch", { repo, deleted })),
/** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */
vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout })),
/**
@@ -284,12 +311,13 @@ export const commands = {
vcsRenameBranch: (repo: string | null, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to })),
vcsMerge: (repo: string | null, branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { repo, branch })),
vcsRebase: (repo: string | null, onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { repo, onto })),
vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked })),
vcsStashApply: (repo: string | null, index: number, pop: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { repo, index, pop })),
vcsStashPush: (repo: string | null, message: string | null, includeUntracked: boolean, keepIndex: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_push", { repo, message, includeUntracked, keepIndex })),
vcsStashApply: (repo: string | null, index: number, pop: boolean, reinstateIndex: boolean, branch: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_apply", { repo, index, pop, reinstateIndex, branch })),
vcsStashDrop: (repo: string | null, index: number) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stash_drop", { repo, index })),
/** Network operation; progress lines stream through `on_output`. Cancellable. */
vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput })),
vcsConflictVersions: (path: string) => typedError<ConflictVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
/** The user's side is `ours` (sides swapped during a rebase, as in IDEA). */
vcsConflictVersions: (path: string) => typedError<MergeVersions, IdeError>(__TAURI_INVOKE("vcs_conflict_versions", { path })),
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
@@ -318,6 +346,8 @@ export const commands = {
vcsTags: (repo: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("vcs_tags", { repo })),
/** Compare with Local: tracked files that differ between `rev` and the working tree. */
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
/** Files that differ between two revisions (the "N files updated" of Update Project). */
vcsDiffRevisions: (repo: string | null, from: string, to: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_revisions", { repo, from, to })),
vcsCreatePatch: (source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { source })),
vcsPatchPreview: (patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { patch })),
vcsApplyPatch: (patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { patch })),
@@ -340,12 +370,19 @@ export const commands = {
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
/**
* Whether the session is running a command (closing its tab asks first). A
* `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
*/
termIsBusy: (id: TerminalId) => typedError<boolean, IdeError>(__TAURI_INVOKE("term_is_busy", { id })),
/** Shell used when Settings › Terminal › Shell path is empty. */
termDefaultShell: () => __TAURI_INVOKE<string>("term_default_shell"),
/** Installed shells for the Terminal's "New Predefined Session" menu. */
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
/** Detected configs followed by user-defined ones (user ids win on conflict). */
runConfigs: () => typedError<RunConfig[], IdeError>(__TAURI_INVOKE("run_configs")),
runSaveConfigs: (configs: RunConfig[]) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs })),
runStart: (config: RunConfig, onOutput: Channel<OutputChunk>) => typedError<RunInfo, IdeError>(__TAURI_INVOKE("run_start", { config, onOutput })),
runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
runSaveConfigs: (configs: RunConfig_Deserialize[]) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs })),
runStart: (config: RunConfig_Deserialize, onOutput: Channel<OutputChunk>) => typedError<RunInfo, IdeError>(__TAURI_INVOKE("run_start", { config, onOutput })),
runStop: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_stop", { id })),
runStdin: (id: RunId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("run_stdin", { id, data })),
runList: () => __TAURI_INVOKE<RunInfo[]>("run_list"),
@@ -427,10 +464,11 @@ export const commands = {
/** Opens an empty (welcome) window; returns its label. */
windowNew: () => typedError<string, IdeError>(__TAURI_INVOKE("window_new")),
/**
* Opens this window's Settings window on `page` (or focuses it and navigates).
* Opens this window's Settings window on `page` (or focuses it and navigates);
* `new_projects` edits the global layer only ("Settings for New Projects").
* `background` (`#rrggbb`) paints a new window until its page has loaded.
*/
windowOpenSettings: (page: string | null, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_settings", { page, background })),
windowOpenSettings: (page: string | null, newProjects: boolean, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_settings", { page, newProjects, background })),
/** Focuses the next / previous window (⌘` / ⇧⌘`). */
windowCycle: (forward: boolean) => __TAURI_INVOKE<void>("window_cycle", { forward }),
windowToggleFullscreen: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_fullscreen")),
@@ -440,6 +478,8 @@ export const commands = {
project: IpcPath | null,
/** Settings windows: the page to show. */
settingsPage: string | null,
/** Settings windows: edit the global layer only ("Settings for New Projects"). */
newProjects: boolean,
} | null>("window_take_launch"),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Projects open in project windows, in window order (title bar project widget). */
@@ -457,6 +497,17 @@ export const commands = {
appLogLocation: () => typedError<LogLocation, IdeError>(__TAURI_INVOKE("app_log_location")),
appBuildInfo: () => __TAURI_INVOKE<BuildInfo>("app_build_info"),
appCheckUpdate: () => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update")),
/**
* The background check made once per process when the first window starts;
* later calls (other windows) and debug builds get `None`. Failures are logged,
* not reported: the user didn't ask for this check.
*/
appStartupUpdateCheck: () => __TAURI_INVOKE<{
version: string,
currentVersion: string,
notes: string | null,
date: string | null,
} | null>("app_startup_update_check"),
/**
* Downloads and installs the available update, then quits through every
* window's unsaved-changes check and relaunches. If a window cancels the quit,
@@ -487,11 +538,17 @@ export const commands = {
* How to run `config` with coverage: the command to launch and where its report will be,
* or which tool is missing.
*/
coveragePrepare: (config: RunConfig) => typedError<CoveragePrepared, IdeError>(__TAURI_INVOKE("coverage_prepare", { config })),
coveragePrepare: (config: RunConfig_Deserialize) => typedError<CoveragePrepared_Serialize, IdeError>(__TAURI_INVOKE("coverage_prepare", { config })),
/** Reads the report a coverage run left behind. */
coverageCollect: (report: CoverageReportSpec) => typedError<CoverageSuite, IdeError>(__TAURI_INVOKE("coverage_collect", { report })),
/** The browsers installed on this machine. */
webBrowsers: () => typedError<Browser[], IdeError>(__TAURI_INVOKE("web_browsers")),
/** The built-in server's URL for `path` (started on first use). */
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
/** Opens `url` in `browser` (an id from `web_browsers`), or the default browser. */
webOpen: (url: string, browser: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("web_open", { url, browser })),
/** How to run `config` under a sampling profiler, or which profiler is missing. */
profilerPrepare: (config: RunConfig) => typedError<ProfilePrepared, IdeError>(__TAURI_INVOKE("profiler_prepare", { config })),
profilerPrepare: (config: RunConfig_Deserialize) => typedError<ProfilePrepared_Serialize, IdeError>(__TAURI_INVOKE("profiler_prepare", { config })),
/** Reads the profile a profiled run left behind. */
profilerCollect: (spec: ProfileSpec) => typedError<Profile, IdeError>(__TAURI_INVOKE("profiler_collect", { spec })),
/** Routes this window's plugin events to `on_event` (replaces an earlier subscription). */
@@ -805,6 +862,13 @@ export type BreakpointState = {
message: string | null,
};
/** An installed browser. */
export type Browser = {
/** `chrome`, `firefox`, `safari`, `edge`, `brave`, `chromium`. */
id: string,
name: string,
};
export type BuildEvent =
/** The build starts: its tree root. */
{ kind: "started"; system: BuildSystem; title: string } |
@@ -928,6 +992,39 @@ export type ChangelistState = {
export type CheckStatus = "pending" | "success" | "failure" | "cancelled" | "skipped" | "neutral";
/**
* How Checkout treats local changes that the switch would overwrite (IDEA's Smart
* Checkout dialog).
*/
export type CheckoutMode =
/** Fail with [`CheckoutOutcome::LocalChanges`] and change nothing. */
"normal" |
/** Stash local changes, switch, and restore them (conflicts are left to resolve). */
"smart" |
/** Discard the local changes in the way (`git switch --discard-changes`). */
"force";
export type CheckoutOptions = {
mode?: CheckoutMode,
/** Required when checking out a remote branch whose local namesake is ahead of it. */
diverged?: DivergedLocal | null,
};
/**
* Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
* left the repository untouched.
*/
export type CheckoutOutcome = { kind: "done" } |
/** These local changes (repository-relative paths) would be overwritten. */
{ kind: "localChanges"; files: string[] } |
/** Local branch `local` has commits that remote branch `remote` does not. */
{ kind: "localBranchAhead"; local: string; remote: string } |
/**
* Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
* on conflicts in these files.
*/
{ kind: "conflicts"; files: string[] };
export type ClearCachesResult = {
/** Syntax trees dropped (they are rebuilt on demand). */
syntaxTrees: number,
@@ -1045,6 +1142,12 @@ export type CommitOptions = {
author: string | null,
/** False skips the pre-commit and commit-msg hooks (`--no-verify`). */
runHooks: boolean,
/**
* Files committed with only some of their changes (IDEA's partial commit). They are
* committed through a temporary index, so neither the working tree nor the other
* entries of the index change; afterwards their index entries match the new commit.
*/
partial?: PartialCommitFile[],
};
/** Version Control › Commit: commit checks and commit-message inspections. */
@@ -1116,12 +1219,6 @@ export type ComposeOp = "start" | "stop" | "restart" |
/** Stops and removes the project's containers and networks. */
"down";
export type ConflictVersions = {
base: string | null,
ours: string | null,
theirs: string | null,
};
/** Build, Execution, Deployment › Console. */
export type ConsoleSettings = {
softWrap?: boolean,
@@ -1135,9 +1232,15 @@ export type ConsoleSettings = {
export type ContainerOp = "start" | "stop" | "restart" | "pause" | "unpause" | "kill";
export type CoveragePrepared = { status: "ready"; runner: string;
export type CoveragePrepared = CoveragePrepared_Serialize | CoveragePrepared_Deserialize;
export type CoveragePrepared_Deserialize = ({ status: "ready"; runner: string;
/** What to launch instead of the configuration. */
launch: RunConfig; report: CoverageReportSpec } | { status: "missingTool"; tool: string; message: string; install: InstallCommand | null } | { status: "unsupported"; reason: string };
launch: RunConfig_Deserialize; report: CoverageReportSpec }) & { install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: InstallCommand | null }) & { launch?: never; reason?: never; report?: never; runner?: never } | ({ status: "unsupported"; reason: string }) & { install?: never; launch?: never; message?: never; report?: never; runner?: never; tool?: never };
export type CoveragePrepared_Serialize = ({ status: "ready"; runner: string;
/** What to launch instead of the configuration. */
launch: RunConfig_Serialize; report: CoverageReportSpec }) & { install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: InstallCommand | null }) & { launch?: never; reason?: never; report?: never; runner?: never } | ({ status: "unsupported"; reason: string }) & { install?: never; launch?: never; message?: never; report?: never; runner?: never; tool?: never };
/** Where the report of a prepared run will be, and how to read it. */
export type CoverageReportSpec =
@@ -1411,6 +1514,17 @@ export type DebuggerSettings = {
python?: PythonDebuggerSettings,
};
/** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */
export type DeletedBranch = {
name: string,
/** The commit the branch pointed at. */
tip: string,
/** Its upstream (`origin/x`), restored with it. */
upstream: string | null,
/** It was not fully merged: its own commits are now unreachable from any branch. */
unmerged: boolean,
};
export type Diagnostic = {
range: Range,
severity: Severity,
@@ -1430,6 +1544,13 @@ export type DirectoryHistory = {
deleted: IpcPath[],
};
/** Checking out remote `origin/x` while local `x` has commits `origin/x` lacks. */
export type DivergedLocal =
/** Rebase local `x` onto `origin/x` (IDEA "Rebase onto Remote"). */
"rebase" |
/** Reset local `x` to `origin/x` (IDEA "Drop Local Commits"). */
"reset";
/** An open document buffer. */
export type DocId = number;
@@ -1541,6 +1662,21 @@ export type DocumentInfo = {
uri?: string | null,
};
/**
* A link in a document (`textDocument/documentLink`): an HTML `href`, a
* Markdown link, an `#include`, a JSON `$schema`…
*/
export type DocumentLink = {
range: Range,
/** A `file:` target. */
path: IpcPath | null,
/** The `#fragment` of a `file:` target (`L12`, `L12,5`, a heading or element id). */
fragment: string | null,
/** Any other target (`https:`, …). */
url: string | null,
tooltip: string | null,
};
export type DuplicateGroup = {
tokens: number,
/** Lines of the first fragment. */
@@ -1813,8 +1949,10 @@ export type FileEntry = {
size: number,
/** Milliseconds since the Unix epoch. */
mtimeMs: number | null,
/** Matched by .gitignore / exclude settings (shown dimmed, like IDEA "excluded"). */
/** Matched by .gitignore or the exclude settings. */
ignored: boolean,
/** Matched by the exclude settings (IDEA's "excluded": dimmed, excluded-folder icon). */
excluded: boolean,
hidden: boolean,
/**
* For symlinks: what the link points to (`None` when dangling); `None`
@@ -1860,6 +1998,12 @@ export type FileProbe = {
tooLarge: boolean,
};
/** A path written in a document: an HTML URL attribute, a CSS `url()` / `@import`. */
export type FileReference = {
range: Range,
value: string,
};
/** Reference updates for a file / folder move (`workspace/willRenameFiles`). */
export type FileRenameEdits = {
/** Edits of every server that took part, in terms of the paths before the move. */
@@ -2159,6 +2303,14 @@ export type HttpResponse = {
export type HunkKind = "added" | "modified" | "deleted";
/** A hunk identified by its line ranges (0-based), see [`LineHunk`]. */
export type HunkRange = {
start: number,
lines: number,
oldStart: number,
oldLines: number,
};
/**
* The single error type that crosses the IPC boundary.
*
@@ -2243,6 +2395,11 @@ export type InlayHint = {
paddingLeft: boolean,
paddingRight: boolean,
tooltip: string | null,
/**
* The label's parts when the server split it (empty for a plain label);
* their values concatenate to `label`.
*/
parts: InlayLabelPart[],
};
/** Editor › Inlay Hints. */
@@ -2258,6 +2415,14 @@ export type InlayHintsSettings = {
export type InlayKind = "type" | "parameter" | "other";
/** One part of an inlay hint label, e.g. a type name that navigates to its declaration. */
export type InlayLabelPart = {
value: string,
tooltip: string | null,
/** Declaration the part stands for (⌘-click navigates there). */
location: Location | null,
};
export type InspectEvent =
/** Files about to be inspected. */
{ type: "started"; total: number } |
@@ -2354,6 +2519,12 @@ export type JavaSettings = {
* Java version it targets.
*/
jdk?: string,
/**
* JDK home the Java language server (jdtls) runs on, apart from the project
* JDK (IDEA's "JDK for importer"); empty = the project JDK when new enough,
* else the first installed one that is.
*/
jdtlsJdk?: string,
/**
* Extra JVM options for the Java language server (jdtls), space-separated
* (VS Code's `java.jdt.ls.vmargs`).
@@ -2372,6 +2543,10 @@ export type LanguageCodeStyle_Deserialize = {
tabSize?: number | null,
indent?: number | null,
hardWrapAt?: number | null,
/** Comment Code › Line comment at first column. */
lineCommentAtFirstColumn?: boolean | null,
/** Comment Code › Add a space at line comment start. */
lineCommentAddSpace?: boolean | null,
};
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
@@ -2380,6 +2555,10 @@ export type LanguageCodeStyle_Serialize = {
tabSize?: number | null,
indent?: number | null,
hardWrapAt?: number | null,
/** Comment Code › Line comment at first column. */
lineCommentAtFirstColumn?: boolean | null,
/** Comment Code › Add a space at line comment start. */
lineCommentAddSpace?: boolean | null,
};
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
@@ -2429,6 +2608,8 @@ export type Launch = {
project: IpcPath | null,
/** Settings windows: the page to show. */
settingsPage: string | null,
/** Settings windows: edit the global layer only ("Settings for New Projects"). */
newProjects: boolean,
};
export type LaunchConfig = {
@@ -2575,6 +2756,10 @@ export type LogQuery = {
textRegex?: boolean,
/** `text` matches case-sensitively (Log filter `Cc`). */
textMatchCase?: boolean,
/** More starting revisions next to `branch` (Log Branch filter with several branches). */
branches?: string[],
/** More author needles next to `author`; a commit matches any of them (Log User filter). */
authors?: string[],
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens";
@@ -2691,6 +2876,45 @@ export type MenuNode = { kind: "submenu"; id: string; label: string; children: M
/** A disabled placeholder such as "No Recent Projects". */
{ kind: "placeholder"; id: string; label: string } | { kind: "separator" };
/**
* Who stands on each side of the conflicts of the operation in progress (merge editor
* titles, as IDEA labels them).
*/
export type MergeSides = {
/** `merge`, `rebase`, `cherry-pick`, `revert`…; `None` outside an operation. */
operation: string | null,
/**
* Git's "ours" is not the user's work: during a rebase stage 2 holds the commits
* rebased onto and stage 3 the user's commit being replayed. [`MergeVersions`] is
* already swapped; conflict markers in the file are not.
*/
reversed: boolean,
/** The current branch (for a rebase: the branch being rebased). */
branch: string | null,
/**
* Short id of the commit being applied (REBASE_HEAD, CHERRY_PICK_HEAD, REVERT_HEAD)
* or merged (MERGE_HEAD).
*/
commit: string | null,
/** The other branch: the one being merged, or the one rebased onto. */
otherBranch: string | null,
};
/** The versions of a conflicted file as the merge editor shows them. */
export type MergeVersions = {
base: string | null,
/** The user's side ("Accept Yours"): git's stage 2, or stage 3 when `sides.reversed`. */
ours: string | null,
theirs: string | null,
sides: MergeSides,
/**
* Three-way merge of the versions above: non-conflicting changes merged, each
* conflict left as a diff3 block (yours / base / theirs). `None` when a side is
* missing (deleted on one side).
*/
merged: string | null,
};
/** Per-function totals (a recursive function's samples count once in `total`). */
export type MethodStat = {
frame: number,
@@ -2778,6 +3002,13 @@ export type OutputChunk = { kind: "stdout"; text: string } | { kind: "stderr"; t
/** System message from the IDE (command line echo, exit code). */
{ kind: "system"; text: string };
/** A file of a partial commit: which of its changes against HEAD to commit. */
export type PartialCommitFile = {
path: IpcPath,
/** The hunks to commit, as [`diff_hunks`] of the HEAD and on-disk texts reports them. */
hunks: HunkRange[],
};
/** One file of a patch (Apply Patch preview). */
export type PatchFile = {
/** Path relative to the repository root (after the change). */
@@ -2797,6 +3028,12 @@ export type PatchSource =
/** Changes made by these commits (oldest first). */
{ from: "commits"; commits: string[]; reverse: boolean };
/** An entry offered when completing a path. */
export type PathCompletion = {
name: string,
dir: boolean,
};
/** Capabilities a plugin must declare to use the gated host functions. */
export type Permission =
/** `workspace-root`, `read-file` (inside the project root only). */
@@ -3010,7 +3247,11 @@ export type ProfileNode = {
children: number[],
};
export type ProfilePrepared = { status: "ready"; profiler: string; launch: RunConfig; spec: ProfileSpec } | { status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null } | { status: "unsupported"; reason: string };
export type ProfilePrepared = ProfilePrepared_Serialize | ProfilePrepared_Deserialize;
export type ProfilePrepared_Deserialize = ({ status: "ready"; profiler: string; launch: RunConfig_Deserialize; spec: ProfileSpec }) & { homepage?: never; install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null }) & { launch?: never; profiler?: never; reason?: never; spec?: never } | ({ status: "unsupported"; reason: string }) & { homepage?: never; install?: never; launch?: never; message?: never; profiler?: never; spec?: never; tool?: never };
export type ProfilePrepared_Serialize = ({ status: "ready"; profiler: string; launch: RunConfig_Serialize; spec: ProfileSpec }) & { homepage?: never; install?: never; message?: never; reason?: never; tool?: never } | ({ status: "missingTool"; tool: string; message: string; install: ProfilerInstall | null; homepage: string | null }) & { launch?: never; profiler?: never; reason?: never; spec?: never } | ({ status: "unsupported"; reason: string }) & { homepage?: never; install?: never; launch?: never; message?: never; profiler?: never; spec?: never; tool?: never };
/** Where a prepared run's profile will be, and how to read it. */
export type ProfileSpec =
@@ -3182,8 +3423,11 @@ export type RemoteOp = { op: "fetch" } | { op: "pull"; rebase: boolean } | { op:
tags?: PushTags | null } |
/** Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`). */
{ op: "deleteBranch"; branch: string } |
/** Pushes local `branch` (only up to `revision` when set) to its upstream. */
{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean } |
/**
* Pushes local `branch` (only up to `revision` when set) to its upstream, or to
* remote branch `target` of the same remote.
*/
{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean; target?: string | null } |
/** Fast-forwards local `branch` (not checked out) to its upstream. */
{ op: "updateBranch"; branch: string };
@@ -3228,7 +3472,9 @@ export type ReviewEvent = "approve" | "requestChanges" | "comment";
export type RootKind = "source" | "test" | "resources" | "testResources" | "excluded";
export type RunConfig = {
export type RunConfig = RunConfig_Serialize | RunConfig_Deserialize;
export type RunConfig_Deserialize = {
/** Stable id, e.g. `npm:dev`, `cargo:run:app`, or a uuid for user-defined. */
id: string,
name: string,
@@ -3244,6 +3490,28 @@ export type RunConfig = {
isTest: boolean,
/** DAP adapter that can debug this config, if any. */
debugAdapter: string | null,
/** "Allow multiple instances": Run on a running config starts another one instead of restarting it. */
allowParallel?: boolean,
};
export type RunConfig_Serialize = {
/** Stable id, e.g. `npm:dev`, `cargo:run:app`, or a uuid for user-defined. */
id: string,
name: string,
/** `npm` | `cargo` | `gradle` | `maven` | `go` | `python` | `pytest` | `make` | `shell` … */
kind: string,
command: string,
args: string[],
cwd: IpcPath | null,
env: { [key in string]: string },
/** Detected configs are regenerated; user configs persist in `.openidea/run.toml`. */
detected: boolean,
/** Test runner configs render results in the test tree. */
isTest: boolean,
/** DAP adapter that can debug this config, if any. */
debugAdapter: string | null,
/** "Allow multiple instances": Run on a running config starts another one instead of restarting it. */
allowParallel?: boolean,
};
/** A process started from a run configuration. */
@@ -3260,6 +3528,8 @@ export type RunInfo = {
/** Run/Debug configuration behaviour. */
export type RunSettings = {
confirmRerun?: boolean,
/** Ask before closing a Run tab whose process is still running. */
confirmTerminate?: boolean,
showOnStart?: boolean,
/** Grace period between interrupt and kill when stopping a process. */
terminationTimeoutMs?: number,
@@ -3314,6 +3584,12 @@ export type SdkKind = "python" | "node" |
/** Maven homes. */
"maven";
/**
* IDEA's search context: matches anywhere, only in, or outside comments and
* string literals. Files whose language has no syntax tree contain neither.
*/
export type SearchContext = "any" | "inComments" | "inStringLiterals" | "exceptComments" | "exceptStringLiterals" | "exceptCommentsAndStringLiterals";
export type SearchEvent = { type: "file"; file: FileMatches } | { type: "done"; summary: SearchSummary };
export type SearchQuery = {
@@ -3330,6 +3606,8 @@ export type SearchQuery = {
scope: SearchScope,
/** Stop after this many matches overall (0 = 10 000). */
maxMatches: number,
/** Where in the code a match may lie (IDEA's search context filter). */
context?: SearchContext,
};
export type SearchScope = { kind: "project" } | { kind: "directory"; path: IpcPath } | { kind: "files"; paths: IpcPath[] } |
@@ -3368,7 +3646,12 @@ export type ServerInfo = {
pid: number | null,
};
export type ServerStatus = "starting" | "ready" | "busy" | "crashed" | "stopped" | "missing";
export type ServerStatus = "starting" | "ready" | "busy" | "crashed" | "stopped" | "missing" |
/**
* Not started: its configuration can't launch it (e.g. no JDK new enough);
* the message says what to change, and a settings change retries.
*/
"misconfigured";
/** Exception filters of one session (see [`DebugManager::exception_filters`]). */
export type SessionExceptionFilters = {
@@ -3506,7 +3789,7 @@ export type SmartKeysSettings = {
/** Reformat on paste: `none` | `indentBlock` | `indentEachLine`. */
reformatOnPaste?: string,
smartIndent?: boolean,
/** Backspace › Unindent: `nearest` indent position | `none`. */
/** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
backspaceUnindent?: string,
};
@@ -3740,7 +4023,7 @@ export type TerminalInfo = {
export type TerminalOptions = {
cwd: IpcPath,
/** Defaults to the user's login shell (`$SHELL`, or `COMSPEC` on Windows). */
/** Defaults to the user's login shell (passwd entry, then `$SHELL`; PowerShell or `COMSPEC` on Windows). */
shell: string | null,
args: string[],
env: { [key in string]: string },
@@ -3767,6 +4050,8 @@ export type TerminalSettings = {
shellIntegration?: boolean,
highlightHyperlinks?: boolean,
optionAsMeta?: boolean,
/** Escape moves focus to the editor instead of reaching the shell. */
escapeToEditor?: boolean,
/** `block` | `underline` | `bar`. */
cursorShape?: string,
cursorBlink?: boolean,
@@ -3775,6 +4060,10 @@ export type TerminalSettings = {
fontSize?: number | null,
/** Multiple of the cell height. */
lineHeight?: number | null,
/** Font tried for glyphs the main font lacks; empty = none. */
fallbackFontFamily?: string,
/** Multiple of the cell width. */
columnWidth?: number | null,
};
export type TestCaseReport = {
@@ -3973,6 +4262,33 @@ export type VirtualDocument = {
decompiled: boolean,
};
/**
* A web reference no language server resolves and where it points: `class="card"` →
* `.card` selectors, `id` → `#id` selectors, `href="#top"` → the element, `var(--x)` →
* `--x:` declarations.
*/
export type WebGoto = {
reference: WebReference,
targets: Location[],
};
export type WebReference = {
kind: WebReferenceKind,
/** Without sigil: `card`, `main`, `--accent`. */
name: string,
range: Range,
};
export type WebReferenceKind =
/** A class in a `class` / `className` attribute: `.name` selectors. */
"class" |
/** An `id` attribute value: `#name` selectors. */
"id" |
/** `href="#name"`: the element with that id in the same document. */
"anchor" |
/** `var(--name)`: the custom property's declarations. */
"cssVariable";
/** Edits to many files, applied atomically from the user's point of view. */
export type WorkspaceEdit = {
files: FileEdit[],
+18
Переглянути файл
@@ -445,3 +445,21 @@ export function registerLanguageMode(desc: LanguageDescription): () => void {
export function _languageMode(name: string): LanguageDescription | undefined {
return languageModes.get(name);
}
// --- read-only code previews ------------------------------------------------------
let codePreviewProvider: ((path: string) => Promise<Extension>) | null = null;
/**
* Extensions for a read-only CodeMirror view showing `path` like an editor tab
* (editor font and colours, line numbers, syntax highlighting): previews
* outside editor tabs such as Find in Files. Empty before editor/core starts.
*/
export function codePreviewExtensions(path: string): Promise<Extension> {
return codePreviewProvider ? codePreviewProvider(path) : Promise.resolve([]);
}
/** @internal editor/core only. */
export function _provideCodePreview(provider: ((path: string) => Promise<Extension>) | null) {
codePreviewProvider = provider;
}
+80 -37
Переглянути файл
@@ -1,20 +1,22 @@
/** Editor actions (ids from keymaps/intellij-macos.ts). */
import { EditorSelection, type EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { deleteLine, moveLineDown, moveLineUp, toggleBlockComment } from "@codemirror/commands";
import { foldAll, syntaxTree, toggleFold, unfoldAll } from "@codemirror/language";
import { addCursorAbove, addCursorBelow, moveLineDown, moveLineUp, toggleBlockComment } from "@codemirror/commands";
import { syntaxTree, toggleFold } from "@codemirror/language";
import { acceptCompletion, completionStatus } from "@codemirror/autocomplete";
import { executeAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { editorController, useGotoLine, useTabs } from "./controller";
import {
addCaretNextOccurrence,
addCaretsToLineEnds,
commentLine,
completeStatement,
deleteLine,
duplicateLineOrSelection,
joinLines,
moveStatementDown,
moveStatementUp,
nextOccurrence,
selectAllOccurrences,
startNewLine,
startNewLineBefore,
@@ -24,8 +26,10 @@ import {
import { emptyStack, extendSelection, shrinkSelection, type SelectionStack, type SimpleRange } from "./model/selectionStack";
import type { EditorSlot } from "./model/slot";
import { findAgain, openFindBar } from "./view/FindBar";
import { foldAtCaret, foldSelection, unfoldAtCaret } from "./cm/folding";
import { collapseAll, collapseRecursively, expandAll, expandRecursively, foldAtCaret, foldSelection, unfoldAtCaret } from "./cm/folding";
import { reverseLines, sortLines } from "./cm/lines";
import { cursorCodeBlockEnd, cursorCodeBlockStart, cursorMatchBrace, scrollToCenter, splitLine } from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
@@ -67,7 +71,8 @@ function withView(run: (view: EditorView, slot: EditorSlot) => unknown) {
// --- extend / shrink selection ---------------------------------------------------
const stacks = new WeakMap<EditorSlot, SelectionStack>();
/** One stack per selection range (by index): ⌥↑ / ⌥↓ work on every caret. */
const stacks = new WeakMap<EditorSlot, SelectionStack[]>();
/** Syntax-tree candidates when the backend has nothing (or the language isn't parsed there). */
export function syntaxCandidates(state: EditorState, sel: SimpleRange): SimpleRange[] {
@@ -115,35 +120,40 @@ export function reusableChain(chain: BackendChain | undefined, counter: number,
const chains = new WeakMap<EditorSlot, BackendChain>();
/** Backend candidates around `current` (the cached chain for repeated extends of one range). */
async function backendCandidates(slot: EditorSlot, current: SimpleRange, cache: boolean): Promise<SimpleRange[]> {
const model = slot.model;
const cached = cache ? reusableChain(chains.get(slot), model.changeCounter, current) : null;
if (cached) return cached;
try {
await model.sync.whenIdle();
const counter = model.changeCounter;
const ranges = await model.manager.backend.selectionRanges(model.doc, current.from);
if (counter !== model.changeCounter || !slot.view) return [];
const candidates = rangesFromBackend(slot.view.state, ranges);
if (cache) chains.set(slot, { counter, pos: current.from, ranges: candidates });
return candidates;
} catch {
return []; // fall back to the syntax tree
}
}
async function extend(slot: EditorSlot) {
const view = slot.view;
if (!view) return;
const main = view.state.selection.main;
const current = { from: main.from, to: main.to };
let candidates: SimpleRange[] = [];
const model = slot.model;
const cached = reusableChain(chains.get(slot), model.changeCounter, current);
if (cached) {
candidates = cached;
} else {
try {
await model.sync.whenIdle();
const counter = model.changeCounter;
const ranges = await model.manager.backend.selectionRanges(model.doc, current.from);
if (counter === model.changeCounter && slot.view) {
candidates = rangesFromBackend(slot.view.state, ranges);
chains.set(slot, { counter, pos: current.from, ranges: candidates });
}
} catch {
// fall back to the syntax tree
}
}
const before = view.state.selection;
const currents = before.ranges.map((r) => ({ from: r.from, to: r.to }));
const candidates = await Promise.all(currents.map((c, i) => backendCandidates(slot, c, i === before.mainIndex)));
const v = slot.view;
if (!v || !v.state.selection.main.eq(main)) return;
const all = [...candidates, ...syntaxCandidates(v.state, current)];
const r = extendSelection(stacks.get(slot) ?? emptyStack(), current, all);
stacks.set(slot, r.state);
if (r.next) v.dispatch({ selection: EditorSelection.single(r.next.from, r.next.to), scrollIntoView: true, userEvent: "select.extend" });
if (!v || !v.state.selection.eq(before)) return;
const prev = stacks.get(slot) ?? [];
const results = currents.map((c, i) =>
extendSelection(prev[i] ?? emptyStack(), c, [...candidates[i]!, ...syntaxCandidates(v.state, c)]),
);
stacks.set(slot, results.map((r) => r.state));
if (!results.some((r) => r.next)) return;
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : before.ranges[i]!));
v.dispatch({ selection: EditorSelection.create(ranges, before.mainIndex), scrollIntoView: true, userEvent: "select.extend" });
}
/** Extend / shrink run in order: a quick ⌥↑⌥↑ extends twice although extending waits for the backend. */
@@ -158,10 +168,13 @@ function queueSelection(slot: EditorSlot, step: (slot: EditorSlot) => void | Pro
function shrink(slot: EditorSlot) {
const view = slot.view;
if (!view) return;
const main = view.state.selection.main;
const r = shrinkSelection(stacks.get(slot) ?? emptyStack(), { from: main.from, to: main.to });
stacks.set(slot, r.state);
if (r.next) view.dispatch({ selection: EditorSelection.single(r.next.from, r.next.to), scrollIntoView: true, userEvent: "select.shrink" });
const sel = view.state.selection;
const prev = stacks.get(slot) ?? [];
const results = sel.ranges.map((r, i) => shrinkSelection(prev[i] ?? emptyStack(), { from: r.from, to: r.to }));
stacks.set(slot, results.map((r) => r.state));
if (!results.some((r) => r.next)) return;
const ranges = results.map((r, i) => (r.next ? EditorSelection.range(r.next.from, r.next.to) : sel.ranges[i]!));
view.dispatch({ selection: EditorSelection.create(ranges, sel.mainIndex), scrollIntoView: true, userEvent: "select.shrink" });
}
// --- structural editing without a Lezer tree ------------------------------------------
@@ -221,8 +234,10 @@ function moveStatement(view: EditorView, slot: EditorSlot, up: boolean) {
* Complete Current Statement: tree-sitter knows what is missing where (and
* which multi-line statement the caret is in) for stream-mode languages, and
* places Java's `;` better than the line heuristics; the heuristics finish the line.
* With the completion lookup open, its selected item is inserted first (IDEA).
*/
function completeCurrentStatement(view: EditorView, slot: EditorSlot) {
if (completionStatus(view.state) === "active") acceptCompletion(view);
const language = slot.model.getMeta().language;
const sel = view.state.selection;
if ((hasLezerTree(view.state) && language !== "java") || sel.ranges.length > 1) return completeStatement(language)(view);
@@ -276,6 +291,11 @@ function copyReference(view: EditorView, slot: EditorSlot) {
void executeAction("editor.showHint", { text: `Copied reference: ${reference}` });
}
/** ⌃G; when nothing more is found, a hint first and the search from the top on the next press (IDEA). */
function addNextOccurrence(view: EditorView) {
if (nextOccurrence(view) === "notFound") void executeAction("editor.showHint", { text: "Not found, press again to search from the top" });
}
// ---------------------------------------------------------------------------------
export function registerEditorActions(): () => void {
@@ -328,13 +348,34 @@ export function registerEditorActions(): () => void {
toggled: () => activeSlot()?.model.softWrapOn() ?? false,
run: () => activeSlot()?.model.toggleSoftWrap(),
},
text("code.foldAll", "Collapse All", (v) => foldAll(v), { category: "Folding", icon: "collapse-all" }),
text("code.unfoldAll", "Expand All", (v) => unfoldAll(v), { category: "Folding", icon: "expand-all" }),
text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addCaretNextOccurrence(v), { category: "Edit" }),
text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }),
text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }),
text("code.collapseRecursively", "Collapse Recursively", (v) => collapseRecursively(v), { category: "Folding", keywords: ["fold"] }),
text("code.expandRecursively", "Expand Recursively", (v) => expandRecursively(v), { category: "Folding", keywords: ["unfold"] }),
text("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", (v) => addNextOccurrence(v), { category: "Edit" }),
text("code.selectAllOccurrences", "Select All Occurrences", (v) => selectAllOccurrences(v), { category: "Edit" }),
text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)),
text("code.startNewLine", "Start New Line", (v) => startNewLine(v)),
text("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)),
text("code.splitLine", "Split Line", (v) => splitLine(v)),
text("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
text("editor.codeBlockStart", "Move Caret to Code Block Start", (v) => cursorCodeBlockStart(v), { category: "Editor Actions" }),
text("editor.codeBlockEnd", "Move Caret to Code Block End", (v) => cursorCodeBlockEnd(v), { category: "Editor Actions" }),
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => addCursorAbove(v), { category: "Editor Actions" }),
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => addCursorBelow(v), { category: "Editor Actions" }),
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
category: "Editor Actions",
// ⌃M is Show Commit Message History in the commit window.
keyWhen: "editorTextFocus",
}),
text("editor.toggleInsertState", "Toggle Insert/Overwrite", (v) => toggleOverwrite(v), {
category: "Editor Actions",
keywords: ["overwrite mode", "overtype"],
toggled: () => {
const view = activeSlot()?.view;
return view ? isOverwrite(view.state) : false;
},
}),
text("code.joinLines", "Join Lines", (v) => joinLines(v)),
text("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
text("code.addCaretsToLineEnds", "Add Carets to Ends of Selected Lines", (v) => addCaretsToLineEnds(v), { category: "Edit" }),
@@ -543,6 +584,8 @@ export function registerEditorActions(): () => void {
category: "Edit",
icon: "copy",
when: "textEditorActive",
// ⇧⌘C / Ctrl+Shift+C stays with the terminal (copy) and other tool windows.
keyWhen: "editorFocus || !toolWindowFocus",
run: () => {
const p = ctrl.activePath();
if (p) void navigator.clipboard?.writeText(p);
+36
Переглянути файл
@@ -0,0 +1,36 @@
/**
* CodeMirror's default keymap minus the bindings that clash with IntelliJ IDEA.
* Those keys belong to IDE actions instead (keymaps in `platform/keymaps/`):
* ⌘/Ctrl+Enter is Split Line, Ctrl+M / ⌃L Scroll to Center, Ctrl+[ / ] code
* block navigation, ⌥⌘↑↓ / Ctrl+Alt+↑↓ Previous / Next Occurrence.
*/
import type { KeyBinding } from "@codemirror/view";
import {
addCursorAbove,
addCursorBelow,
defaultKeymap,
historyKeymap,
indentLess,
indentMore,
insertBlankLine,
redo,
selectLine,
toggleTabFocusMode,
} from "@codemirror/commands";
const DROPPED = new Set<unknown>([
insertBlankLine, // Mod-Enter
toggleTabFocusMode, // Ctrl-m / Shift-Alt-m
selectLine, // Alt-l / Ctrl-l
addCursorAbove, // Mod-Alt-ArrowUp
addCursorBelow, // Mod-Alt-ArrowDown
indentLess, // Mod-[
indentMore, // Mod-]
]);
export const editorBaseKeymap: readonly KeyBinding[] = [
...defaultKeymap.filter((b) => !DROPPED.has(b.run)),
...historyKeymap,
// IDEA's Windows Redo is Ctrl+Shift+Z (Ctrl+Y is Delete Line); CodeMirror only binds it on macOS and Linux.
{ win: "Ctrl-Shift-z", run: redo, preventDefault: true },
];
+103
Переглянути файл
@@ -0,0 +1,103 @@
import { afterEach, beforeAll, describe, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { indentService, type LanguageSupport } from "@codemirror/language";
import { languages } from "@codemirror/language-data";
import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
import { codeBlockEnd, codeBlockStart, splitLine } from "./caretCommands";
import { editorBaseKeymap } from "./baseKeymap";
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
/** One unit deeper after a line ending in `{`. */
const braceIndent = indentService.of((cx, pos) => {
const line = cx.lineAt(pos, -1);
const base = /^ */.exec(line.text)![0].length;
return line.text.slice(0, pos - line.from).trimEnd().endsWith("{") ? base + 2 : base;
});
/** `|` marks carets. */
function make(text: string) {
const carets: number[] = [];
let doc = "";
for (const ch of text) {
if (ch === "|") carets.push(doc.length);
else doc += ch;
}
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.create(carets.map((c) => EditorSelection.cursor(c))),
extensions: [EditorState.allowMultipleSelections.of(true), braceIndent],
}),
});
views.push(view);
return view;
}
function show(view: EditorView) {
const doc = view.state.doc.toString();
const heads = view.state.selection.ranges.map((r) => r.head).sort((a, b) => b - a);
return heads.reduce((s, h) => s.slice(0, h) + "|" + s.slice(h), doc);
}
describe("Split Line", () => {
it("breaks the line at each caret and leaves the caret before the break", () => {
const view = make("if (a) {|return 1; }");
splitLine(view);
expect(show(view)).toBe("if (a) {|\n return 1; }");
const multi = make("a|b\nc|d");
splitLine(multi);
expect(show(multi)).toBe("a|\nb\nc|\nd");
});
});
describe("code block navigation", () => {
let js: LanguageSupport;
beforeAll(async () => {
js = await languages.find((l) => l.name === "JavaScript")!.load();
});
const at = (text: string) => {
const pos = text.indexOf("|");
return { state: EditorState.create({ doc: text.replace("|", ""), extensions: js }), pos };
};
it("goes to just inside the enclosing braces", () => {
const { state, pos } = at("f() { if (x) { a|(); } b(); }");
expect(codeBlockStart(state, pos)).toBe("f() { if (x) {".length);
expect(codeBlockEnd(state, pos)).toBe("f() { if (x) { a(); ".length);
});
it("jumps across a brace at the caret to its match, and outward from inside one", () => {
const text = "f() { if (x) { a(); } b(); }";
const { state } = at(text);
const open = text.indexOf("{", 6);
const close = text.indexOf("}");
expect(codeBlockEnd(state, open)).toBe(close + 1); // |{ … } → { … }|
expect(codeBlockStart(state, close + 1)).toBe(open); // { … }| → |{ … }
expect(codeBlockStart(state, open + 1)).toBe(text.indexOf("{") + 1); // {| → outer block
expect(codeBlockEnd(state, close)).toBe(text.lastIndexOf("}")); // |} → outer block
});
it("skips braces in strings and comments", () => {
const { state, pos } = at('f() { const s = "{"; /* } */ a|(); }');
expect(codeBlockStart(state, pos)).toBe("f() {".length);
expect(codeBlockEnd(state, pos)).toBe('f() { const s = "{"; /* } */ a(); '.length);
});
it("has nowhere to go outside any block", () => {
const { state, pos } = at("a|();");
expect(codeBlockStart(state, pos)).toBeNull();
expect(codeBlockEnd(state, pos)).toBeNull();
});
});
describe("editor base keymap", () => {
it("drops CodeMirror defaults that IDEA uses for other actions", () => {
const runs = editorBaseKeymap.map((b) => b.run);
for (const cmd of [insertBlankLine, toggleTabFocusMode, selectLine, addCursorAbove]) expect(runs).not.toContain(cmd);
expect(editorBaseKeymap.some((b) => b.key === "Mod-Enter" || b.key === "Ctrl-m")).toBe(false);
expect(editorBaseKeymap.some((b) => b.win === "Ctrl-Shift-z")).toBe(true);
});
});
+130
Переглянути файл
@@ -0,0 +1,130 @@
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center, code block and brace navigation. */
import { EditorSelection, type EditorState, type Transaction } from "@codemirror/state";
import { EditorView, type Command } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
import { matchBrackets, syntaxTree } from "@codemirror/language";
/** Split Line: break the line at each caret, indented, leaving the caret before the break. */
export const splitLine: Command = (view) => {
if (view.state.readOnly) return false;
const before = view.state.selection;
let tr: Transaction | null = null;
insertNewlineAndIndent({ state: view.state, dispatch: (t) => (tr = t) });
if (!tr) return false;
const changes = (tr as Transaction).changes;
const selection = EditorSelection.create(
before.ranges.map((r) => EditorSelection.cursor(changes.mapPos(r.from, -1))),
before.mainIndex,
);
view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "input" });
return true;
};
/** Scroll to Center: put the caret line in the middle of the viewport. */
export const scrollToCenter: Command = (view) => {
view.dispatch({ effects: EditorView.scrollIntoView(view.state.selection.main.head, { y: "center" }) });
return true;
};
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
function braceAt(state: EditorState, pos: number): "{" | "}" | null {
const ch = state.sliceDoc(pos, pos + 1);
if (ch !== "{" && ch !== "}") return null;
const tree = syntaxTree(state);
if (tree.length && NOT_CODE.test(tree.resolveInner(pos, 1).name)) return null;
return ch;
}
/**
* Where Move Caret to Code Block Start goes from `pos` (as IDEA):
* just after the enclosing `{`, or before the `{` matching a `}` the caret follows.
*/
export function codeBlockStart(state: EditorState, pos: number): number | null {
const from = pos - 1;
if (from < 0) return null;
const afterClose = braceAt(state, from) === "}";
let depth = afterClose ? -1 : 0;
for (let p = from; p >= 0; p--) {
const b = braceAt(state, p);
if (b === "{" && p !== from) {
if (depth === 0) return afterClose ? p : p + 1;
depth--;
} else if (b === "}") {
depth++;
}
}
return null;
}
/**
* Where Move Caret to Code Block End goes from `pos`: before the enclosing `}`,
* or after the `}` matching a `{` the caret precedes.
*/
export function codeBlockEnd(state: EditorState, pos: number): number | null {
const len = state.doc.length;
const beforeOpen = braceAt(state, pos) === "{";
let depth = beforeOpen ? -1 : 0;
for (let p = pos; p < len; p++) {
const b = braceAt(state, p);
if (b === "}" && p !== pos) {
if (depth === 0) return beforeOpen ? p + 1 : p;
depth--;
} else if (b === "{") {
depth++;
}
}
return null;
}
function moveToBlock(find: (state: EditorState, pos: number) => number | null): Command {
return (view) => {
const { state } = view;
const target = find(state, state.selection.main.head);
if (target == null) return false;
view.dispatch({ selection: EditorSelection.cursor(target), scrollIntoView: true, userEvent: "select.navigate" });
return true;
};
}
export const cursorCodeBlockStart = moveToBlock(codeBlockStart);
export const cursorCodeBlockEnd = moveToBlock(codeBlockEnd);
/**
* Where Go to Matching Brace (⌃M) goes from `pos`: from a brace next to the
* caret to its match; elsewhere to the unclosed opening brace before the caret.
*/
export function matchBraceTarget(state: EditorState, pos: number): number | null {
const found =
matchBrackets(state, pos, -1) ||
matchBrackets(state, pos, 1) ||
(pos > 0 && matchBrackets(state, pos - 1, 1)) ||
(pos < state.doc.length && matchBrackets(state, pos + 1, -1));
if (found && found.end) return found.start.from === pos ? found.end.to : found.end.from;
const tree = syntaxTree(state);
let depth = 0;
for (let p = pos - 1; p >= 0; p--) {
const ch = state.sliceDoc(p, p + 1);
const open = "([{".includes(ch);
if (!open && !")]}".includes(ch)) continue;
if (tree.length && NOT_CODE.test(tree.resolveInner(p, 1).name)) continue;
if (!open) depth++;
else if (depth-- === 0) return p;
}
return null;
}
export const cursorMatchBrace: Command = (view) => {
const { state } = view;
let moved = false;
const ranges = state.selection.ranges.map((r) => {
const target = matchBraceTarget(state, r.head);
if (target == null) return r;
moved = true;
return EditorSelection.cursor(target);
});
if (!moved) return false;
view.dispatch({ selection: EditorSelection.create(ranges, state.selection.mainIndex), scrollIntoView: true, userEvent: "select.navigate" });
return true;
};
+19 -5
Переглянути файл
@@ -2,9 +2,10 @@
* Edit › Column Selection Mode (⇧⌘8): while on, a plain mouse drag and
* ⇧+arrows make rectangular (block) selections, one range per line.
*/
import { EditorSelection, Prec, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { EditorSelection, Prec, StateEffect, StateField, countColumn, findColumn, type EditorState, type Extension } from "@codemirror/state";
import { EditorView, keymap, rectangularSelection } from "@codemirror/view";
/** A block between two visual columns (tabs expanded) of two lines. */
interface Block {
anchorLine: number;
anchorCol: number;
@@ -43,18 +44,30 @@ export function toggleColumnMode(view: EditorView): boolean {
return true;
}
/** One range per line from the anchor column to the head column (clamped to each line). */
/** One range per line from the anchor column to the head column (visual columns, clamped to each line). */
export function blockSelection(state: EditorState, b: Block): EditorSelection {
const ranges = [];
const step = b.headLine >= b.anchorLine ? 1 : -1;
const at = (text: string, col: number) => findColumn(text, col, state.tabSize);
for (let n = b.anchorLine; ; n += step) {
const line = state.doc.line(n);
ranges.push(EditorSelection.range(line.from + Math.min(b.anchorCol, line.length), line.from + Math.min(b.headCol, line.length)));
ranges.push(EditorSelection.range(line.from + at(line.text, b.anchorCol), line.from + at(line.text, b.headCol)));
if (n === b.headLine) break;
}
return EditorSelection.create(ranges, ranges.length - 1);
}
/** The visual column one character left / right of `col` (a tab is one step; past the line end, one column). */
export function stepColumn(text: string, col: number, d: number, tabSize: number): number {
if (!d) return col;
const width = countColumn(text, tabSize);
if (d > 0 ? col >= width : col > width) return Math.max(0, col + d);
const pos = findColumn(text, col, tabSize);
const at = countColumn(text, tabSize, pos);
if (d > 0) return at > col ? at : countColumn(text, tabSize, pos + 1);
return pos === 0 ? 0 : countColumn(text, tabSize, pos - 1);
}
/** ⇧+arrow in column mode: moves the block's head by a line / column. */
export function extendBlock(view: EditorView, dLine: number, dCol: number): boolean {
const state = view.state;
@@ -65,10 +78,11 @@ export function extendBlock(view: EditorView, dLine: number, dCol: number): bool
const main = state.selection.main;
const a = state.doc.lineAt(main.anchor);
const h = state.doc.lineAt(main.head);
b = { anchorLine: a.number, anchorCol: main.anchor - a.from, headLine: h.number, headCol: main.head - h.from };
const col = (text: string, offset: number) => countColumn(text, state.tabSize, offset);
b = { anchorLine: a.number, anchorCol: col(a.text, main.anchor - a.from), headLine: h.number, headCol: col(h.text, main.head - h.from) };
}
const headLine = Math.max(1, Math.min(state.doc.lines, b.headLine + dLine));
const next = { ...b, headLine, headCol: Math.max(0, b.headCol + dCol) };
const next = { ...b, headLine, headCol: stepColumn(state.doc.line(b.headLine).text, b.headCol, dCol, state.tabSize) };
view.dispatch({
selection: blockSelection(state, next),
effects: setBlock.of(next),
Loaded 100 of 495 files, more files were not shown because too many files have changed in this diff. Show more