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

...
Автор SHA1 Повідомлення Дата
Deng Liu 14e13220d7 fix(agents): pick Linux Copilot archive from host dynamic linker
openidea-server on Linux is compiled as a static musl binary (*-unknown-linux-musl) so it runs across distributions, while GitHub Copilot CLI's Linux release archives dynamically link either glibc (copilot-linux-*.tar.gz) or musl (copilot-linuxmusl-*.tar.gz). Checking compile-time cfg!(target_env = "musl") caused remote servers on glibc hosts (such as Ubuntu) to install the musl Copilot binary, which failed to spawn with ENOENT (os error 2) when /lib/ld-musl-*.so.1 was absent.

Inspect the host's runtime ELF dynamic linker paths per architecture instead, using copilot-linuxmusl-* only when /lib/ld-musl-{x86_64,aarch64}.so.1 exists and glibc's loader (/lib64/ld-linux-x86-64.so.2 or /lib/ld-linux-aarch64.so.1) does not.
2026-11-26 23:50:52 -08:00
Deng Liuтаdengliu 7ecccb3b75 feat(agents): preview Copilot subscription models immediately on account switch (#6346)
Switching Sign In > GitHub account for GitHub Copilot used to hide New Tasks models behind an Apply step. A new trusted command, agent_preview_copilot_models, probes Copilot's model catalog for the staged account in memory without touching copilot.toml, models.json or active sessions, so the account and default model can be chosen together and saved with one Apply / OK, and Cancel discards both. Account logins are validated before they reach gh, and applying the account refreshes the stored catalog.

Co-authored-by: dengliu <[email protected]>
2026-11-27 15:45:27 +08:00
Muuтаmuutot 7cbf17b10e feat(vcs): drag the Unversioned Files group and multi-selections onto a changelist (#6299)
In the Commit tool window the Unversioned Files group header is now a drag source whose files are the payload, and a selection of unversioned files drags together. The drag gate in ChangesTree excluded every group row without a changelist id; it now also allows the unversioned group. Dropping reuses addToChangelist, which adds the files to Git and assigns the list; ignored rows stay non-draggable.

Co-authored-by: muutot <[email protected]>
2026-11-27 15:41:46 +08:00
LU XIANGRUIтаwildcatDownstairs cb0d02620d feat(python): run unittest tests without pytest (#6385)
Adds a Python unittest run configuration and Settings > Python > Testing > Default test runner (Autodetect / pytest / unittest). Autodetect keeps pytest for projects that use it; projects whose test modules import unittest and not pytest get a detected python -m unittest configuration, and gutter / context runs of such modules use unittest. Runs go through a stdlib-only reporter that wraps unittest's main() and prints one record per test and subtest, so the tree shows passed, failed, error, skipped, expected failure and unexpected success, subtests as children, captured output, failure locations, import and setUpClass failures; project, folder (discover), module, class and method targets and Rerun Failed (-k) are supported. PyCharm Unittests configurations import as this type. Jump to Source and MCP run / select-tests also handle unittest configurations (file and dotted-name narrowing) instead of falling back to pytest.

Closes #6361

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:40:08 +08:00
LU XIANGRUIтаwildcatDownstairs d6ca43cba4 feat(mdx): add MDX language support through @mdx-js/language-server (#6355)
Adds an mdx language backed by @mdx-js/language-server and moves .mdx out of markdown.toml; the prose keeps Markdown highlighting, outline and folding. The server needs typescript.tsdk, which the launcher fills with the TypeScript vtsls uses (selected version, else vtsls' bundled one, else the one installed with the server, else the project's); an explicit tsdk setting wins, and the managed install adds typescript@6. Places keyed on markdown (live rendering, large-file outline, spell checking as prose, auto-indent, Surround With, colour preview) now include mdx. Formatting follows the Markdown entry of the Prettier / oxfmt language lists so saved lists keep formatting .mdx, and Prettier gets --parser mdx from mdx.toml instead of an extension special case.

Closes #6340

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:33:09 +08:00
l0ng-ai 165d4f7d76 test(plugins): record the plain HTTP request before replying (#6396)
The local server in net_http_setting_grants_reach_plain_http_per_transport recorded a served request only after writing the response, so the client could read it and assert seen.len() == 2 before the second push (1 != 2 on ubuntu CI). The request is now recorded before the reply.
2026-11-27 15:29:03 +08:00
LU XIANGRUIтаwildcatDownstairs 5785ebadd8 feat(typescript): import style code style settings, sent to tsserver (#6342)
Editor > Code Style > JavaScript and TypeScript get an Imports tab: import paths (shortest / relative / non-relative / relative within the project), import path ending (automatic / minimal / index / .js), and glob and regex lists of what not to auto-import. They are stored with the code style, added to the servers' typescript/javascript preferences under both vtsls and typescript-language-server key names, and sent to running servers with didChangeConfiguration; a server's own Language Servers settings still win. The two exclusion lists are always sent (as [] when unset) so clearing one takes effect without a restart. Adds the typescript_import_style language smoke test.

Closes #6072

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:26:29 +08:00
LU XIANGRUIтаwildcatDownstairs 0c67a4eea2 feat(typescript): load the tsserver plugins a project's tsconfig declares (#6353)
tsserver only looks for tsconfig plugins next to the TypeScript it runs from, so with vtsls' bundled TypeScript plugins such as Next.js' were never found. When a tsconfig.json / jsconfig.json under the server root declares compilerOptions.plugins (directly or through extends), vtsls now gets one extra tsserver pluginPaths entry: a folder under the IDE data dir with a small re-exporting package per declared plugin. Plugins the IDE registers globally are left out so they keep resolving to the IDE's copies; missing plugins are logged and skipped; only valid npm package names are used. Changes to tsconfig/jsconfig files trigger a reconfigure, and the probe folder is keyed by the declaring configurations' text, so vtsls restarts instead of stacking plugin instances. Untrusted projects start no language servers, so no project plugin loads there.

Closes #6336

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:23:33 +08:00
LU XIANGRUIтаwildcatDownstairs 5e2deed81e feat(new-project): add Expo, Electron and create-vue generators (#6351)
New Project gains three JavaScript generators that run the official packages through the chosen package manager: Vue (create-vue) with TypeScript, Vue Router, Pinia, Vitest and ESLint options; Expo (React Native) with blank, blank TypeScript and tabs templates; and Electron (Electron Forge) with Vite, Vite + TypeScript and webpack + TypeScript. create-vue gets a kebab-case folder renamed to the project name and a no-op flag when every option is off so it never prompts. Electron always installs, since Forge writes the dependencies by installing them. Static Website moves to the end of the group. Brand icons and en/zh strings added.

Closes #6338

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:21:11 +08:00
LU XIANGRUIтаwildcatDownstairs cae7c05fb1 feat(sass): language server for indented Sass files (#6348)
Indented .sass files now run some-sass-language-server (MIT, installed through npm from the Tools list): completion for variables and mixins across @use, Go to Declaration, hover with SassDoc comments and syntax diagnostics. vscode-css-language-server does not parse the indented syntax; SCSS, CSS and Less stay on it. The server throws on a null somesass configuration, so the definition passes an empty settings table to keep its defaults.

Closes #6339

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:18:58 +08:00
LU XIANGRUIтаwildcatDownstairs be83458161 feat(run): choose the Python interpreter of a run configuration from a list (#6382)
Python and Django test run configurations get an Interpreter dropdown: Project default, each detected interpreter (minus those removed on All Interpreters), or Custom command, which shows the Command field for runners such as uv or poetry. The chosen interpreter's path is stored as the command, so command lines, the backend and .run.xml import are unchanged; existing configurations open with the choice their command stands for, and a missing interpreter is shown as not found. With a run-target project interpreter only Project default and Custom command are offered. RunConfigTypeField gains an optional set(value, params) so a select can stand for other params.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:17:30 +08:00
LU XIANGRUIтаwildcatDownstairs 661124d0d4 fix(run): group pytest parametrized cases under their test (#6384)
Parametrized pytest cases now appear as children of their test, with the combined status on the parent, and Run / Rerun Failed on either runs exactly that node id. The parser split node ids at every :: and failure titles at every dot and only matched ids without spaces, so cases were flat siblings, cases with spaces were missing, and a failing [v1.2 ...] case became a bogus chain under the run root. The [id] part is now kept whole. Tests without a failure line, and the grouping node, now navigate to the test's def.

Closes #6360

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:15:04 +08:00
LU XIANGRUIтаwildcatDownstairs 0dae111b2d feat(navigation): Related Symbol for JS/TS components, templates, styles, tests and stories (#6347)
Navigate > Related Symbol now switches between a JS/TS component and the same-named files beside it: an Angular component, directive, pipe or service and its template, styles and spec (also following templateUrl / styleUrl / styleUrls), and Button.tsx with Button.module.css, Button.test.tsx and Button.stories.tsx. Targets are grouped as Source File, Template, Styles, Test and Stories. It reads only the folder listing and the open file's text; two same-named sources (Button.ts and a compiled Button.js) are not offered for each other.

Closes #6337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:13:19 +08:00
Mansur Akhmadiтаmansur-akhmadi 61d269045b feat(vcs): Compare File with Editor action (#6364)
Adds Compare File with Editor: the file selected in the Project view (or passed as the argument) is diffed against the active editor's file, opened at the editor's caret line, with swappable sides. The Project view context menu offers it right after Compare With… for a single file other than the editor's; virtual documents, folders, multiple files and the editor's own file get an explanatory notification instead. It is unbound in the presets and mapped from imported keymaps via CompareFileWithEditor.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:12:02 +08:00
Mansur Akhmadiтаmansur-akhmadi 266d85fa1a feat(run): Search with Google in the console context menu (#6358)
Adds Search with Google to the Run console context menu: it opens a web search for the trimmed, URL-encoded selected output in the browser, and is disabled when nothing (or only whitespace) is selected.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:08:59 +08:00
Mansur Akhmadiтаmansur-akhmadi f964d79e10 feat(terminal): Close All Tabs in the session tab menu (#6344)
Adds Close All Tabs to the terminal tab context menu. Close Tab / Close Other Tabs / Close All Tabs now share requestCloseTabs, which closes the tabs in order, confirms each running command like Close Tab, stops at a tab the user keeps open, and skips tabs whose shell already exited.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:07:43 +08:00
Mansur Akhmadiтаmansur-akhmadi 4a3eacff62 feat(code-insight): Export to Text File in the Find Usages tool window (#6292)
Adds Export to Text File… to the Find Usages toolbar and Find Action. It writes the active search as shown (access filter applied, excluded usages left out) as an indented text report to a file picked in the save dialog, and reports write errors as a notification.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:06:50 +08:00
Mansur Akhmadiтаmansur-akhmadi aebc2fe02d feat(templates): Save as Live Template from the editor selection (#6305)
Adds Tools > Save as Live Template…: with a selection in a text editor it adds a User live template whose text is the selection (dedented like $SELECTION$, with $ escaped as $$), in the file's language, and opens Settings > Live Templates on it. The page now accepts a focus target and selects that template.

The action is unbound in the presets and is reachable from imported keymaps and IdeaVim via SaveAsTemplate.

Closes #6304

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:05:34 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b63aa9526 feat(editor): Increase / Decrease Font Size in All Editors actions (#6350)
Adds Increase / Decrease Font Size in All Editors actions that change the editor font size setting for every open editor, next to the existing single-editor zoom actions.

The default keymaps bind Alt+Shift+. / Alt+Shift+, (Ctrl+Shift+. / Ctrl+Shift+, on macOS) to the All Editors actions; the single-editor actions stay available from Find Action and can be bound in Keymap settings. Docs and keymap tests updated.

Closes #6349

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:00:39 +08:00
Mansur Akhmadiтаmansur-akhmadi df07073886 feat(editor): Delete Duplicate Lines action (#6323)
IDEA's Edit > Delete Duplicate Lines (EditorUniqueLines): in the selected lines, or the whole file without a selection, keeps the first of each repeated line and deletes the later ones.

Closes #6322

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:55:06 +08:00
Mansur Akhmadiтаmansur-akhmadi 3433ee951b feat(editor): Scroll Left / Scroll Right actions (#6303)
IDEA's Scroll Left / Scroll Right: move the editor viewport by one column without moving the caret, counted in whole columns. Unbound by default, as in IDEA.

Closes #6302

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:53:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 8f5b281486 feat(editor): Kill to Word Start / Kill to Word End actions (#6294)
IDEA's Kill to Word Start / Kill to Word End: cut from each caret back to the previous word start or on to the next word end, across blank lines, by hump with CamelHumps on. Repeated kills at the same caret collect into one clipboard entry like Cut up to Line End, backward kills before the collected text. Unbound by default, as in IDEA's default keymaps.

Closes #6293

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:52:04 +08:00
Mansur Akhmadiтаmansur-akhmadi 43aee8058c feat(editor): Toggle Sticky Selection action (#6325)
IDEA's Toggle Sticky Selection: while on, every caret move (keys, IDE actions, clicks, Find) extends the selection from its anchor. Turning it off, Esc, an edit of the document or a copy end it and remove the selection, as in IDEA. Swap Selection Boundaries keeps it going from the other end. No default shortcut, as in IDEA's default keymaps.

Closes #6324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:49:18 +08:00
audichuang 4016c3c905 fix(vcs): show the merge result in a background tab of the file (#6378)
After Apply in the merge editor, a tab of the file behind the merge editor kept showing the conflict markers although disk and index held the result. Without an editor view, writeFileText edited a transient doc_open/doc_edit/doc_save reference; doc_edit is not echoed to the document's other references, so the background tab never got the change. The write now goes through the file's document (attachDocument), so every tab of the file follows; the file is still saved as is. Get from Revision in the log uses the same helper.

Closes #5567

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:40:00 +08:00
audichuang e6cb7df653 fix(run): count every test when JUnit runs them in parallel (#6377)
With JUnit's parallel concurrent mode, OpenIDEA's JUnit runner could report fewer tests than finished: the listener is called from several worker threads, Reporter's counters were plain ints incremented without a lock and PlatformRunner's start times a HashMap. The counting methods are synchronized now and the start times a ConcurrentHashMap. build.py --test runs a 4000-invocation parallel sample and expects the exact summary.

Closes #6334

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:37:21 +08:00
Muuтаmuutot 2a26c82357 fix(vcs): the Git Log branch filter follows a branch rename (#6341)
Renaming a branch left the Git Log filtering the old name: the Branch chip kept it and the query failed with unknown revision. renameBranchInLogFilters now rewrites the shown view's branch filter, parked log views, the per-repository remembered choice and Log: <branch> tab targets, and reloads the log when the shown view filtered by the old name. A batch rename follows only when every repository was renamed.

Co-authored-by: muutot <[email protected]>
2026-11-27 14:27:05 +08:00
eclix-del 66f0bce92f fix(editor): keep a re-dropped file saveable (#6328)
A file from outside the project, dropped into the editor again, stopped saving after the first save, silently. Three paths led there:
- onLocal set the dirty flag after updating the touched ranges, so an exception there left the buffer clean and every save a no-op. Dirty is now set first, and a failure to map the ranges falls back to treating the whole document as touched.
- A reused model kept the touched ranges of the previous tab; they are cleared when a clean model is reacquired.
- A file opened under its native Windows spelling (E:\code\a.sql) and the editor's E:/code/a.sql got two models sharing one backend document, and dirty/patch/language events reached only one. Events now go to every model of the document, and dropped paths are normalized with ipcPath (extended-length paths too).
save() also writes when the dirty flag lags but edits are still pending.

Refs #5528

Co-authored-by: eclix-del <[email protected]>
2026-11-27 14:24:00 +08:00
Mollo-i dfbd13e2af fix(run): keep console soft wrap across run tabs (#6331)
The Run/Services and Debug console toolbars kept soft wrap in component state, so switching run tabs reset it to the Settings default. The toolbar toggle now writes Settings > Console > Use soft wraps in console (console.softWrap) and every console reads it, so one toggle applies to all consoles and survives a restart. The e2e settings-write stub moves into the shared fixtures.

Co-authored-by: Greenker <[email protected]>
2026-11-27 14:19:24 +08:00
aconeshanaтаaconeshana 944b57dead fix(run): open a stack frame's file from the run module's scope (#6366)
Clicking a stack frame in the Run console opened another module's copy of a class when several modules of a multi-module Maven build declare the same package and class: the lookup went by file name, and the package check cannot tell same-package copies apart.

Candidates are now narrowed to the run configuration's module and the modules it depends on (transitively, all scopes) before the name and package checks. The module reaches the Run console links, the test tree's Jump to Source and the Debug console links. Without a Maven model, for an unlisted module, or when the scope matches no candidate, the lookup behaves as before.

Closes #6313

Co-authored-by: aconeshana <[email protected]>
2026-11-27 14:16:59 +08:00
LU XIANGRUIтаwildcatDownstairs 5bcb37492f fix(run): print each line of a JUnit test's output once (#6333)
With Run tests using: OpenIDEA, every line a JUnit Platform test printed showed twice: the runner enabled JUnit's output capture, whose StreamInterceptor also writes each line to the original System.out, and then reported the captured text again as testStdOut.

The runner now captures System.out / System.err per thread itself, as Junit4Runner does: a thread's lines while it runs a test or a class's set-up go only into that test's or class's testStdOut / testStdErr, other output passes through, and JUnit's capture is turned off explicitly. The console now shows testStdErr as stderr, and "Show console when a message is printed to stderr" fires for it (also for Junit4Runner and the Gradle test init script).

Fixes #6332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 14:14:49 +08:00
Yann d5bde9af67 fix(agents): preserve Codex failure diagnostics (#6354)
Codex turns blocked under cyberPolicy were turned into a successful ACP refusal, dropping the server's explanation and showing only "The agent declined to continue." They now fail like other turns, and a failed turn's message carries Codex's additional details, its diagnostic code and any reported HTTP status. Authentication and usage-limit classification are unchanged.

Co-authored-by: YannABC <[email protected]>
2026-11-27 14:13:03 +08:00
Deng Liuтаdengliu 5b3e2b7a3d fix(editor): skip whitespace-only selections in selection match highlighting (#6318)
Selecting indentation (spaces or tabs) flooded the editor with occurrence highlights, because CodeMirror's highlightSelectionMatches matches whitespace-only selections verbatim. heavyExtension now uses a selectionMatches view plugin with the same bounds (min length 2, max length 200, at most 500 visible matches) that skips whitespace-only selections, as the terminal and Markdown preview already do.

Co-authored-by: dengliu <[email protected]>
2026-11-27 14:11:22 +08:00
薛纪克таxuejike dbb6fa51c3 fix(database): start new query consoles in the selected schema (#6375)
New Query Console and Query Console opened from a schema, folder or table node started in the connection's default schema: the commands passed only the node's data source id, and bindConsole clears the console schema when the binding changes. The commands now pass the invoking node's schema (else the selected tree node's on the same connection) and the console switches to it after binding.

Closes #6329

Co-authored-by: xuejike <[email protected]>
2026-11-27 14:09:04 +08:00
l0ng-ai 3d1769ef00 chore(plugins): rebuild the net-setting test fixture from its sources 2026-11-27 12:28:25 +08:00
l0ng-ai c966429f92 chore: v0.1.54 2026-11-27 11:40:15 +08:00
l0ng-ai dfcc05dd41 fix(vcs): keep the combined diff's stuck file header flush with the top (#6326)
A stuck file header left a gap the size of the list's top padding and showed
the diff scrolling by through it and outside its rounded corners. It now sticks
past the padding, draws its own top border, and covers the area behind it.
2026-11-27 10:53:31 +08:00
Fabio Nunes d41feefc07 feat(editor): remember the encoding chosen for a file or folder (#5510)
The encoding chosen for a file from the status bar (Reload or Convert) is remembered for that file across reopening and restarts, and a folder can have an encoding its files inherit (project settings). A converted file keeps its new encoding once saved. Precedence: a file's own choice, then the .editorconfig charset, then the folder mapping.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 10:43:43 +08:00
l0ng-ai f0fe910017 fix(agents): use a declared radius token for the sign-in terminal (#6320) 2026-11-27 10:37:24 +08:00
l0ng-ai b932220b41 fix(plugins): color Java annotations from a theme plugin's annotation key (#6317)
Java annotations are drawn with --syn-decorator, but a theme plugin's
ANNOTATION_NAME_ATTRIBUTES only set --syn-annotation, so they kept the
DEFAULT_METADATA color. The annotation key now sets both, and
DEFAULT_METADATA applies only when neither the file nor its bundled parent
(Default, Darcula) defines the annotation key, as for imported schemes.
2026-11-27 10:35:42 +08:00
l0ng-ai bcad8f61cb fix(debugger): don't sync the closed project's breakpoint files (#6315)
Closing a project reloads the breakpoints with no project, which rescheduled
every file the project had breakpoints in with an empty list. Each sync then
failed in the backend (no project in the window) and logged
debugSetBreakpoints failed. Per-file syncs now wait for a project as well.
2026-11-27 10:35:32 +08:00
l0ng-ai 2cdcb888cf fix(viewers): update the SVG preview's size when the typed source changes it (#6314)
WebKit keeps the natural size of an <img> that has a CSS size when its src
changes to another SVG, so editing the root's width or height left the live
preview and its dimension readout at the old size. The preview now measures
each typed source with a detached image.
2026-11-27 10:35:22 +08:00
l0ng-ai 9ed0fd9fa7 fix(ci): format the API 1.18 run output test and fit the commit chooser's macOS Close button (#6319)
The Plugins job's rustfmt check failed on `sdk/rust/openidea-plugin/tests/api18_run_output_mode.rs`. Since dialogs on macOS show as sheets (#6208), a dialog without footer buttons gets a Close button and a taller title, so the Git Log commit chooser is taller than `e2e/gitLogCommitChooser.spec.ts` allowed.
2026-11-27 10:35:14 +08:00
Vladislav Kuzmin fe76dc4573 test(viewers): select SVG source with the fixture keymap (#6297)
The browser fixture uses macOS shortcuts on every host. Playwright resolves `ControlOrMeta+A` to Ctrl+A on Linux, so the test inserts the new SVG without replacing the existing source. Use `Meta+A` to match the fixture's keymap.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:55 +08:00
Vladislav Kuzmin 45a75f782a fix(ci): scope the managed gh test helper to Unix (#6287)
Windows Clippy fails because the managed GitHub CLI accessor is compiled on every test target and its only caller is Unix-only. Give the accessor the same test and Unix conditions as its caller.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:47 +08:00
Vladislav Kuzmin bd1fd011e4 test(editor): include File Color in tab menu groups (#6280)
The editor tab menu gained a File Color group in #6105. The layout test still expected Copy Path/Reference in that position and compared four groups, so it failed before it could check splitting and pinning. Include File Color and compare all five original and new groups in order.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:38 +08:00
Vladislav Kuzmin b44015b2ce fix(frontend): remove unused VCS and Markdown exports (#6279)
Remove the unused VCS date wrapper and the Markdown layout-mode alias left behind after their callers moved to the shared formatting and viewer code. The VCS model also drops its unused import. The author-hint comment now describes the shared formatting behavior without pointing to a removed function.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:30 +08:00
l0ng-ai 0cce0a9840 fix(problems): start TypeScript Project Errors when the option is turned on (#6316)
The desktop app's settings_set has its own copy of the side effects of a
changed setting, and the tsc --watch watcher was only started from the host
command's copy, so turning on Problems › TypeScript Project Errors did
nothing until the project was reopened. Both commands now share
apply_setting, which also applies the terminal frame rate on desktop.
2026-11-27 10:28:13 +08:00
l0ng-ai db8224f74e perf(agents): stop a running task's Changes tab from reloading every diff on each update (#6298)
While a task runs, it is published again with every token count. The Changes tab rebuilt its
diff items from the whole task object, so each update re-read the base text of every changed
file over IPC, hashed all of them, and handed the view a new array that rendered every mounted
diff block and every row of the file tree again. The diffs now depend only on the task fields
they use (id, base, isolation, branch, cwd), an unchanged list keeps its array, and the file
tree is memoized. The all-in-one diff also works out each diff's key once per list instead of
hashing every file's text on every scroll frame (autosave off).
2026-11-27 10:03:35 +08:00
Fabio Nunes b075f5de2a feat(editorconfig): apply charset to existing files and accept the listed encodings (#5509)
An .editorconfig charset now applies to existing files when they are opened and decoded, not only to new ones, and every charset EditorConfig lists is accepted (latin1, utf-8, utf-8-bom, utf-16be, utf-16le). Find in Files decodes closed files with that charset too, so a Latin-1 file is found by its accented text.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 09:51:49 +08:00
318 змінених файлів з 9006 додано та 824 видалено

No files matched your search

Створено
+49 -48
Переглянути файл
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4182,7 +4182,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4205,7 +4205,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4223,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4259,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4294,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4323,7 +4323,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4362,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4389,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4409,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4420,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4444,7 +4444,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4463,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4544,7 +4544,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"hyper-util",
"ide-core",
@@ -4563,7 +4563,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4586,7 +4586,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4598,7 +4598,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4614,7 +4614,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"libc",
"tempfile",
@@ -4623,7 +4623,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"futures",
"serde",
@@ -4634,7 +4634,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4693,7 +4693,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"dunce",
@@ -4704,6 +4704,7 @@ dependencies = [
"ide-jsonrpc",
"ide-jvm-inspect",
"ide-language",
"ide-sdk",
"ide-text",
"ide-vfs",
"ignore",
@@ -4722,7 +4723,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"bytes",
"dunce",
@@ -4741,7 +4742,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4762,7 +4763,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -4784,7 +4785,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4798,7 +4799,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"futures",
@@ -4818,7 +4819,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"encoding_rs",
@@ -4843,7 +4844,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-tools",
@@ -4859,7 +4860,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4885,7 +4886,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"encoding_rs",
@@ -4906,7 +4907,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4919,7 +4920,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4944,7 +4945,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4957,7 +4958,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4972,7 +4973,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"libc",
@@ -4986,7 +4987,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -4999,7 +5000,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"flate2",
"hex",
@@ -5022,7 +5023,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -5044,7 +5045,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"chardetng",
"dunce",
@@ -5071,7 +5072,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5087,7 +5088,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -6726,7 +6727,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.53"
version = "0.1.54"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+34
Переглянути файл
@@ -627,6 +627,40 @@ impl crate::AgentManager {
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
let account = account.trim();
if !account.is_empty() {
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
}
match discover(&self.shared, spec, model).await {
Ok(found) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: self.shared.config_for_new_task(found.config, "copilot"),
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
refreshing: false,
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
retry_at_ms: None,
error: None,
}),
Err(error) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: Vec::new(),
thought_levels: BTreeMap::new(),
refreshing: false,
refreshed_at_ms: None,
retry_at_ms: None,
error: Some(error),
}),
}
}
}
async fn discover(
+1 -2
Переглянути файл
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
let message = translate::error_message(&e);
return match translate::classify(&e, rate_limits) {
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
Failure::UsageLimit(resets) => Err(ResponseError {
code: codes::INTERNAL_ERROR,
message,
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
}),
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
+84
Переглянути файл
@@ -455,6 +455,90 @@ fn failures_are_classified() {
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
}
#[test]
fn failed_turns_preserve_codex_error_diagnostics() {
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
assert_eq!(failure.code, codes::INTERNAL_ERROR);
assert_eq!(failure.message, expected);
}
// A completed turn's own error wins over an older error notification.
let failure = stop_reason(
&json!({ "status": "failed", "error": policy }),
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
None,
)
.unwrap_err();
assert_eq!(failure.message, expected);
}
#[test]
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
for (value, expected) in [
(
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
"Context is full.\nCodex error: contextWindowExceeded",
),
(
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
),
(
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
"Failed\nbecause",
),
(
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
"Codex failed\nDetails\nCodex error: cyberPolicy",
),
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
(json!({}), "Codex failed"),
] {
assert_eq!(error_message(&value), expected);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
for notification_only in [false, true] {
let mut transcript = load(Scenario::UsageLimit.file());
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
match frame["method"].as_str() {
Some("error") => frame["params"]["error"] = policy.clone(),
Some("turn/completed") => {
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
}
_ => {}
}
}
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
match result(&results, "prompt") {
Err(RpcError::Server { code, message, .. }) => {
assert_eq!(*code, codes::INTERNAL_ERROR);
assert_eq!(
message,
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
);
}
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
}
}
}
#[test]
fn approvals_offer_what_codex_offers_and_always_a_decline() {
let params = json!({"availableDecisions": ["accept",
+20 -6
Переглянути файл
@@ -740,7 +740,7 @@ pub(super) enum Failure {
UsageLimit(Option<f64>),
/// Signed out or refused.
Auth,
/// The model declined.
/// The server blocked the turn under a safety policy.
Refusal,
Other,
}
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
exhausted.map(|s| s * 1000.0)
}
/// The text a failed turn reports: codex's message, with its details.
/// The text a failed turn reports: Codex's message, details and diagnostic code.
pub(super) fn error_message(error: &Value) -> String {
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
_ => message.to_owned(),
let original =
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
let mut message = original.to_owned();
if let Some(details) =
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
&& !original.contains(details)
{
message.push('\n');
message.push_str(details);
}
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
message.push_str(&format!("\nCodex error: {code}"));
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
message.push_str(&format!(" (HTTP {status})"));
}
}
message
}
/// One choice of an approval: what ACP shows and what codex gets back.
+11
Переглянути файл
@@ -289,7 +289,18 @@ fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn is_valid_github_login(account: &str) -> bool {
let bytes = account.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn github_token_for_account(account: &str) -> Result<String, String> {
if !is_valid_github_login(account) {
return Err(format!("Invalid GitHub account login: {account}"));
}
let program = find_gh_executable()
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
+119 -3
Переглянути файл
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
}
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
let tag = format!("v{}", entry.version.trim_start_matches('v'));
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
let sha256_url = format!("{base}/SHA256SUMS.txt");
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
let linux_arm = format!(
"copilot-{}-arm64.tar.gz",
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
);
let linux_x64 =
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
let targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
}
}
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
let (glibc_rel, musl_rel) = match arch {
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
};
let glibc = root.join(glibc_rel);
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
let points_to_musl =
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
let has_glibc = glibc.exists() && !points_to_musl;
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
}
fn safe_segment(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
@@ -1304,4 +1328,96 @@ esac
assert!(npm_bin.is_file());
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
}
#[test]
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let archives_for = |root: &Path| -> (String, String) {
let mut entry = parse(index).unwrap().remove(0);
entry.distribution.binary.clear();
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
(
entry.distribution.binary["linux-x86_64"].archive.clone(),
entry.distribution.binary["linux-aarch64"].archive.clone(),
)
};
let touch = |path: PathBuf| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"").unwrap();
};
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
let empty = tempfile::tempdir().unwrap();
assert_eq!(
archives_for(empty.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
let glibc = tempfile::tempdir().unwrap();
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
let musl = tempfile::tempdir().unwrap();
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
#[cfg(unix)]
{
fs::create_dir_all(musl.path().join("lib64")).unwrap();
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
.unwrap();
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
}
#[cfg(target_os = "linux")]
{
let parsed = parse(index).unwrap().remove(0);
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
assert!(
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
"unexpected linux-x86_64 archive: {}",
parsed.distribution.binary["linux-x86_64"].archive
);
}
}
}
+52
Переглянути файл
@@ -505,6 +505,19 @@ pub struct LanguageCodeStyle {
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub spaces: BTreeMap<String, bool>,
/// JavaScript / TypeScript › Imports › Import paths:
/// `shortest` | `relative` | `non-relative` | `project-relative`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier: Option<String>,
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier_ending: Option<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_file_exclude_patterns: Vec<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_specifier_exclude_regexes: Vec<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -562,6 +575,25 @@ pub struct EncodingSettings {
pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
/// relative to the project with `/` separators. The status bar's choice is kept here.
#[serde(deserialize_with = "labels")]
#[specta(type = BTreeMap<String, String>)]
pub mappings: BTreeMap<String, String>,
}
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
return Ok(BTreeMap::new());
};
Ok(entries
.into_iter()
.filter_map(|(path, label)| match label {
serde_json::Value::String(label) => Some((path, label)),
_ => None,
})
.collect())
}
impl Default for EncodingSettings {
@@ -572,10 +604,30 @@ impl Default for EncodingSettings {
properties: "iso-8859-1".into(),
native_to_ascii: false,
utf8_bom: "never".into(),
mappings: BTreeMap::new(),
}
}
}
#[cfg(test)]
mod encoding_mappings_tests {
use super::EncodingSettings;
#[test]
fn encoding_mappings_keep_the_entries_that_are_labels() {
let json = serde_json::json!({
"project": "gbk",
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
});
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
assert_eq!(settings.project, "gbk");
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
assert!(not_a_table.mappings.is_empty());
assert!(EncodingSettings::default().mappings.is_empty());
}
}
#[cfg(test)]
mod auto_import_tests {
use super::{AutoImportSettings, ImportsOnPaste};
+4
Переглянути файл
@@ -1426,6 +1426,9 @@ pub struct PythonSettings {
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
/// it, else unittest), `pytest` or `unittest`.
pub test_runner: String,
}
impl Default for PythonSettings {
@@ -1438,6 +1441,7 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
}
}
}
+26 -1
Переглянути файл
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
}
}
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
/// and follows its entry, so lists saved before it had its own language keep formatting it.
fn formatter_language(language: &str) -> &str {
if language == "mdx" { "markdown" } else { language }
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
@@ -295,7 +301,8 @@ fn external_tool(
)))
};
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
let id = formatter_language(language.id.as_str());
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
@@ -897,6 +904,24 @@ mod tests {
external_tool(forced, language.as_ref(), file, settings)
}
#[test]
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
let old: ide_core::settings::Settings = serde_json::from_str(
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
)
.unwrap();
let file = Path::new("/project/docs/intro.mdx");
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
let mut no_markdown = old.languages.clone();
no_markdown.prettier.languages.retain(|l| l != "markdown");
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
let mut oxfmt = old.languages.clone();
oxfmt.oxfmt.languages.push("markdown".into());
oxfmt.oxfmt.prefer = true;
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
}
#[test]
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
let settings = LanguagesSettings::default();
+35 -1
Переглянути файл
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
if JS_FILE.is_match(rel) {
&["npm", "deno", "bun"]
} else if rel.ends_with(".py") {
&["pytest", "python"]
&["pytest", "unittest", "python"]
} else if rel.ends_with(".go") {
&["go"]
} else if rel.ends_with(".rs") {
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
// `python -m unittest <file>`; a `discover` selection gives way to the file.
"unittest" => {
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
}
"go" => {
let dir = dir_of(&file);
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
@@ -790,6 +795,11 @@ pub fn target_config(
"pytest" | "python" => {
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
}
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
format!("{module}.{}", target.path.join("."))
}))),
"go" => {
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
@@ -921,6 +931,30 @@ mod tests {
);
}
#[test]
fn narrows_unittest_configs_to_files_and_dotted_tests() {
let root = Path::new("/p");
let mut unittest =
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
unittest.is_test = true;
let mut discover = unittest.clone();
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
let rel = "tests/test_calc.py";
for configs in [vec![unittest], vec![discover]] {
let c = context_config(root, rel, &configs, src).unwrap();
assert_eq!(
(c.kind.as_str(), c.args.as_slice()),
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
);
let ts = detect(src, rel);
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
}
}
#[test]
fn narrows_cargo_test_configs() {
let root = Path::new("/p");
+2
Переглянути файл
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
));
let mut tools = vec![
act("code.saveAsLiveTemplate", "Save as Live Template…"),
SEP,
act("http.newRequest", "New HTTP Request"),
act("http.showToolWindow", "HTTP Client"),
SEP,
+14
Переглянути файл
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
}
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
#[command(trust = trusted)]
pub async fn agent_preview_copilot_models(
host: &Host,
window: &str,
account: String,
model: Option<String>,
) -> IdeResult<AgentModelCatalog> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
agents.preview_copilot_models(&account, model.as_deref()).await
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
#[command(trust = trusted)]
@@ -1584,6 +1597,7 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_preview_copilot_models,
agent_probe,
agent_prompt,
agent_providers,
+19 -3
Переглянути файл
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
#[command(trust = always)]
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save(doc)).await?;
host.blocking(move || {
project.documents.save(doc)?;
remember_saved_encodings(&project);
Ok(())
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
let saved = host
.blocking(move || {
let saved = project.documents.autosave(doc)?;
remember_saved_encodings(&project);
Ok(saved)
})
.await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save_all()).await?;
host.blocking(move || {
let saved = project.documents.save_all();
remember_saved_encodings(&project);
saved
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
+50 -4
Переглянути файл
@@ -1,11 +1,13 @@
use crate::Host;
use crate::ops::blocking;
use crate::project::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
/// Keeps the encoding the user chose for a project file in the project's File Encodings
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
/// until then its file is still in the old encoding. Nothing is kept for a document without
/// a file in the project.
#[command(trust = always)]
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let info = project.documents.snapshot(doc)?;
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
return Ok(());
}
remember_encoding(&project, &info.path, &info.encoding)
})
.await
}
/// Keeps the encodings of the converted documents a save has just written.
pub(super) fn remember_saved_encodings(project: &Project) {
for (path, encoding) in project.documents.take_saved_encodings() {
if let Err(e) = remember_encoding(project, &path, &encoding) {
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
}
}
}
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
const MAPPINGS: &str = "editor.encodings.mappings";
if project.light {
return Ok(());
}
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
return Ok(());
};
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
return Ok(());
}
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
Ok(())
}
#[command(trust = always)]
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
}
items
}
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
})
})
@@ -263,6 +308,7 @@ ide_command::domain!(
doc_outline,
doc_python_facts,
doc_rearrange,
doc_remember_encoding,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+95
Переглянути файл
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
impl Fixture {
fn project_settings(&self) -> PathBuf {
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
}
fn mappings_changed(&self) -> usize {
let events = self.events.lock();
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
assert_eq!(doc.encoding, "utf-8");
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
assert!(!settings.exists());
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
let written = std::fs::read_to_string(&settings).unwrap();
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
assert_eq!(f.mappings_changed(), 1);
// The same choice again leaves the file alone.
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
// A file outside the project has no place in the project's settings.
let outside = f.open(&f.outside).await;
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
assert!(!settings.exists());
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
assert_eq!(
std::fs::read_to_string(&settings).unwrap(),
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
);
assert_eq!(f.mappings_changed(), 1);
// Later saves keep nothing more.
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", reopened.id).await.unwrap();
let again = f.open(&f.path).await;
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
std::fs::write(&settings, "[editor\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
assert_eq!(f.mappings_changed(), 0);
}
+17 -11
Переглянути файл
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
}
}
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
/// crate's and the desktop's) call it after writing the value.
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
if "languages.typescript.watchProblems".starts_with(key)
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
{
watch.apply(&host.runtime);
}
}
/// `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.
@@ -122,17 +138,7 @@ pub fn settings_set(
value: String,
) -> IdeResult<Settings> {
let applied = set_settings(host, window, scope, &key, &value)?;
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
if "languages.typescript.watchProblems".starts_with(&key)
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
{
watch.apply(&host.runtime);
}
apply_setting(host, window, &key);
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
+1 -1
Переглянути файл
@@ -493,7 +493,7 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
+2 -2
Переглянути файл
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
_ => true,
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
// Search's UTF-8 fast path does not need to resolve the configured encoding.
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+1 -1
Переглянути файл
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
use std::path::{Path, PathBuf};
/// Languages checked as prose (all text but code spans).
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
+32 -5
Переглянути файл
@@ -211,6 +211,8 @@ impl Host {
crate::ts_code_style::configure(cfg, server_root, &effective);
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
// After the global plugins: they keep the IDE's copies.
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
let container_python = effective.languages.python.run_target().is_some();
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
// Attached dependency projects are source, so basedpyright/Pyright should
@@ -452,7 +454,9 @@ impl Host {
phpstan.files_removed(batch.removed.iter());
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
// Not while loading: a first `use flake` may write `flake.lock` itself.
@@ -1530,8 +1534,7 @@ impl Project {
}
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
let defaults = self.documents.file_defaults();
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
let charset = self.documents.detect_encoding(path, bytes);
self.vcs_text_encoding(path, charset)
}
@@ -1890,7 +1893,9 @@ fn content_root_watcher(
index.ignore_rules_changed(&batch.ignore_rules);
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
// A workspace member's PHP language level follows its own composer.json.
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
if let Some(bridge) = &kotlin_bridge {
@@ -1912,6 +1917,17 @@ fn content_root_watcher(
.ok()
}
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
/// plugins it declares are part of vtsls' configuration.
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
paths.any(|p| {
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
!p.components().any(|c| c.as_os_str() == "node_modules")
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
&& name.ends_with(".json")
})
}
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
/// (`ide_sdk::php`).
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
@@ -2737,9 +2753,20 @@ mod agent_worktree_tests {
#[cfg(test)]
mod composer_tests {
use super::composer_changed;
use super::{composer_changed, ts_config_changed};
use std::path::{Path, PathBuf};
#[test]
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
assert!(changed(yes), "{yes}");
}
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
assert!(!changed(no), "{no}");
}
}
#[test]
fn only_the_roots_own_composer_json_counts() {
let root = Path::new("/work/app");
+81 -13
Переглянути файл
@@ -1,4 +1,4 @@
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
//! quick fixes, auto-imports, refactorings and organize imports.
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
.unwrap_or_default();
let section = section(language, code_style.languages.get(language), &pairs);
if !section.is_empty() {
layer.insert(language.into(), Value::Object(section));
}
}
if layer.is_empty() {
return;
layer.insert(language.into(), Value::Object(section));
}
let mut merged = Value::Object(layer);
if let Some(own) = cfg.settings.take() {
@@ -96,10 +91,30 @@ fn section(
if !format.is_empty() {
section.insert("format".into(), Value::Object(format));
}
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
let mut preferences = Map::new();
if let Some(quotes) = quotes {
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
preferences.insert("quoteStyle".into(), json!(quotes));
preferences.insert("quotePreference".into(), json!(quotes));
}
let paths = ["shortest", "relative", "non-relative", "project-relative"];
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
preferences.insert("importModuleSpecifier".into(), json!(paths));
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
}
let endings = ["auto", "minimal", "index", "js"];
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
}
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
let none = Vec::new();
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
section.insert("preferences".into(), Value::Object(preferences));
section
}
@@ -133,9 +148,17 @@ mod tests {
"typescript": {
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
// The server's own settings win.
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
"preferences": {
"quoteStyle": "double",
"quotePreference": "single",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
},
},
"javascript": {
"format": { "semicolons": "insert" },
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
},
"javascript": { "format": { "semicolons": "insert" } },
})
);
@@ -144,7 +167,52 @@ mod tests {
assert_eq!(eslint.settings, None);
let mut untouched = server("vtsls");
configure(&mut untouched, dir.path(), &Settings::default());
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
// a running server.
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
assert_eq!(untouched.settings, Some(empty));
}
#[test]
fn import_style_reaches_the_preferences_of_each_language() {
let mut settings = Settings::default();
let ts = LanguageCodeStyle {
import_module_specifier: Some("relative".into()),
import_module_specifier_ending: Some("index".into()),
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
..Default::default()
};
settings.editor.code_style.languages.insert("typescript".into(), ts);
let js = LanguageCodeStyle {
import_module_specifier: Some("non-relative".into()),
// Not a tsserver value: left out.
import_module_specifier_ending: Some("ts".into()),
..Default::default()
};
settings.editor.code_style.languages.insert("javascript".into(), js);
let dir = tempfile::tempdir().unwrap();
let mut cfg = server("vtsls");
configure(&mut cfg, dir.path(), &settings);
assert_eq!(
cfg.settings.unwrap(),
json!({
"typescript": { "preferences": {
"importModuleSpecifier": "relative",
"importModuleSpecifierPreference": "relative",
"importModuleSpecifierEnding": "index",
"autoImportFileExcludePatterns": ["**/index.ts"],
"autoImportSpecifierExcludeRegexes": ["^node:"],
} },
"javascript": { "preferences": {
"importModuleSpecifier": "non-relative",
"importModuleSpecifierPreference": "non-relative",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
} },
})
);
}
#[test]
@@ -178,6 +246,6 @@ mod tests {
configure(&mut cfg, dir.path(), &settings);
let s = cfg.settings.unwrap();
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
assert_eq!(s.get("javascript"), None);
assert_eq!(s["javascript"].get("format"), None);
}
}
+82
Переглянути файл
@@ -542,6 +542,23 @@ impl Smoke {
self.restore(doc, &before).await;
}
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
/// none labelled `label`.
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
let (doc, pos, before) = self.type_line(typed).await;
self.retry("completion without the item", self.warm_up, || async {
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
let labels: Vec<String> = match list {
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
Err(e) => vec![e.to_string()],
};
let has = |name: &str| labels.iter().any(|l| l == name);
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
})
.await;
self.restore(doc, &before).await;
}
async fn organize_imports(&self, import: Typed, expect: Imports) {
let (doc, _, before) = self.type_line(import).await;
let typed = import.text.trim();
@@ -696,6 +713,71 @@ async fn typescript() {
smoke("typescript", TYPESCRIPT).await;
}
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
/// specifiers left out.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs vtsls"]
async fn typescript_import_style() {
let checks = Checks {
files: &[
(
"tsconfig.json",
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
"include": ["src"]}"#,
),
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
// Never excluded, and matching what is typed (tsserver offers only those): the
// auto-import candidates are in the completion list.
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
("src/app/main.ts", "export const ready = true;\n"),
("src/app/other.ts", "export const other = true;\n"),
("src/app/third.ts", "export const third = true;\n"),
("src/app/fourth.ts", "export const fourth = true;\n"),
("src/app/fifth.ts", "export const fifth = true;\n"),
],
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let set = |key: &str, value: &str| {
let scope = ide_workspace::settings::SettingsScope::Project;
let key = format!("editor.codeStyle.languages.typescript.{key}");
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
};
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
let beta = typed("src/app/main.ts", "export const ready", "betaW");
let import = |typed, label, result| AutoImport { typed, label, result };
set("importModuleSpecifier", r#""relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
set("importModuleSpecifier", r#""non-relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifierEnding", r#""index""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
set("importModuleSpecifierEnding", r#""minimal""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
// tsserver keeps the auto-import candidates of the file it last completed in until the
// program changes; other files see an exclusion at once.
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
// Emptied lists reach the server too: the symbols are offered again.
set("autoImportFileExcludePatterns", "[]");
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
set("autoImportSpecifierExcludeRegexes", "[]");
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
}
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
#[cfg(unix)]
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
+2 -1
Переглянути файл
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
let mut req = vec![0; len];
let _ = reader.read_exact(&mut req);
let body = "plain ok";
// Recorded before the reply: the client may assert as soon as it reads it.
seen.lock().push("served".into());
let _ = writer.write_all(
format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
)
.as_bytes(),
);
seen.lock().push("served".into());
}
});
}
+22
Переглянути файл
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
project.documents.set_file_defaults(defaults);
assert!(find(&host, "中文搜索验证").await.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "gbk".into();
project.documents.set_file_defaults(defaults);
let files = find(&host, "ação €").await;
assert_eq!(files.len(), 1);
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
}
+18
Переглянути файл
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
("lua", include_str!("../../../languages/lua.toml")),
("makefile", include_str!("../../../languages/makefile.toml")),
("markdown", include_str!("../../../languages/markdown.toml")),
("mdx", include_str!("../../../languages/mdx.toml")),
("nix", include_str!("../../../languages/nix.toml")),
("objective-c", include_str!("../../../languages/objective-c.toml")),
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
@@ -1281,6 +1282,7 @@ mod tests {
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Intro.mdx", "mdx"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
("Makefile", "makefile"),
@@ -1362,6 +1364,22 @@ mod tests {
);
}
#[test]
fn indented_sass_has_its_own_server() {
let reg = reg();
let names = |lang: &str| -> Vec<String> {
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
};
assert_eq!(names("sass"), ["some-sass-language-server"]);
let sass = &reg.get(&LanguageId::new("sass")).unwrap().language_servers[0];
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
for lang in ["scss", "css", "less"] {
let names = names(lang);
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
}
}
#[test]
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
let reg = reg();
+1
Переглянути файл
@@ -28,6 +28,7 @@ percent-encoding = "2"
zip.workspace = true
[dev-dependencies]
ide-sdk.workspace = true
tempfile.workspace = true
encoding_rs.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
+217
Переглянути файл
@@ -969,6 +969,145 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
const MDX_BUTTON: &str =
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
/// The MDX Language Server with the `typescript.tsdk` the launcher adds. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @mdx-js/language-server
/// typescript@6 @types/react`; the project is created inside it, so that it
/// resolves the React types.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @mdx-js/language-server, typescript and @types/react (OPENIDEA_TEST_NPM_TOOLS)"]
async fn mdx_language_server_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir_in(&tools).unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(
root.join("tsconfig.json"),
"{\"compilerOptions\":{\"strict\":true,\"jsx\":\"react-jsx\",\"moduleResolution\":\"bundler\",\"module\":\"esnext\"},\"mdx\":{\"checkMdx\":true}}",
)
.unwrap();
let (button, file) = (root.join("Button.tsx"), root.join("doc.mdx"));
std::fs::write(&button, MDX_BUTTON).unwrap();
std::fs::write(&file, MDX_DOC).unwrap();
let mut mdx = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("mdx")).unwrap();
let server = &mut mdx.language_servers[0];
server.command = tools.join("node_modules/.bin/mdx-language-server").to_string_lossy().into_owned();
let tsdk = tools.join("node_modules/typescript/lib").to_string_lossy().into_owned();
server.initialization_options.as_mut().unwrap()["typescript"]
.as_table_mut()
.unwrap()
.insert("tsdk".into(), toml::Value::String(tsdk));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![mdx]));
let doc = DocId::next();
mgr.did_open(doc, &file, &LanguageId::new("mdx"), 1, MDX_DOC);
// `Button` in `<Button label="hi" />`.
let hover = retry("hover", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.hover(doc, Pos::new(6, 3), Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.contains("label: string"), "{}", hover.contents.value);
let defs = mgr.goto(doc, Pos::new(6, 3), GotoKind::Definition).await.unwrap();
assert!(defs.iter().any(|d| d.path == button), "{defs:?}");
// Members of `count` inside `{…}`, and the imported component in JSX.
for (pos, label) in [(Pos::new(10, 7), "toFixed"), (Pos::new(6, 3), "Button")] {
retry(label, Duration::from_secs(30), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
list.items.iter().any(|i| i.label == label).then_some(())
}
})
.await;
}
// Markdown headings come from the server too (marksman skips `.mdx` by default).
let symbols = mgr.document_symbols(doc).await.unwrap().unwrap();
assert!(symbols.iter().any(|s| s.name.contains("Hello")), "{symbols:?}");
// `label={count}`: number is not assignable to string.
retry("prop type error", Duration::from_secs(60), || {
let found = events.lock().iter().any(|e| {
matches!(e, IdeEvent::Diagnostics { path, items, .. }
if path == &file && items.iter().any(|d| d.range.start.line == 8 && d.message.contains("string")))
});
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// A tsserver plugin reporting `from <name>` at the start of every file.
const DIAGNOSTIC_PLUGIN: &str = "module.exports = () => ({ create(info) {\n const ls = info.languageService;\n const proxy = Object.create(null);\n for (const k of Object.keys(ls)) proxy[k] = (...a) => ls[k](...a);\n proxy.getSemanticDiagnostics = (f) => [...ls.getSemanticDiagnostics(f), { file: ls.getProgram().getSourceFile(f), start: 0, length: 1, messageText: 'from ' + NAME, category: 1, code: 99001 }];\n return proxy;\n} });\n";
/// tsconfig `compilerOptions.plugins` load from the project's `node_modules` with vtsls' own
/// TypeScript through the probe location `configure_tsconfig_plugins` writes (#6336); one that
/// isn't installed is skipped, and the IDE's global plugins keep loading their own copies,
/// also when the project has a package of the same name. Set `OPENIDEA_TEST_NPM_TOOLS` to a
/// dir with `npm i @vtsls/language-server typescript@5`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
async fn tsconfig_plugins_load_from_the_project_with_the_bundled_typescript() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
// Outside the project: a probe location resolves plugins from its ancestors' node_modules too.
let ide = tempfile::tempdir().unwrap();
let ide = dunce::canonicalize(ide.path()).unwrap();
let plugin = |dir: &Path, name: &str, says: &str| {
let dir = dir.join("node_modules").join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", &format!("'{says}'"))).unwrap();
};
plugin(&root, "project-plugin", "project-plugin");
plugin(&root, "global-plugin", "the project's global-plugin");
plugin(&ide, "global-plugin", "global-plugin");
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
let plugins = r#"[{"name":"not-installed"},{"name":"project-plugin"}]"#;
std::fs::write(root.join("tsconfig.json"), format!("{{\"compilerOptions\":{{\"plugins\":{plugins}}}}}")).unwrap();
let main = root.join("main.ts");
let text = "export const n: number = 1;\n";
std::fs::write(&main, text).unwrap();
let global = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
"name": "global-plugin",
"location": ide.to_string_lossy(),
"enableForWorkspaceTypeScriptVersions": true,
}] } } });
for configured in [false, true] {
let mut server = npm_server(&tools, "vtsls", "vtsls", Some(global.clone()));
server.tsserver_project = true;
if configured {
assert!(ide_sdk::apply::configure_tsconfig_plugins(&mut server, &root, &ide.join("data")));
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
let doc = DocId::next();
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
let mut messages = retry("the plugins' diagnostics", Duration::from_secs(90), || {
let found = events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => {
Some(items.iter().map(|d| d.message.clone()).collect::<Vec<_>>())
}
_ => None,
});
async move { found }
})
.await;
messages.sort();
let expected: &[&str] =
if configured { &["from global-plugin", "from project-plugin"] } else { &["from global-plugin"] };
assert_eq!(messages, expected);
let crashed = matches!(last_status(&events, "vtsls"), Some((ServerStatus::Crashed, _)));
assert!(!crashed, "{:?}", last_status(&events, "vtsls"));
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
@@ -1425,3 +1564,81 @@ async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// Indented Sass through the built-in `sass` definition: completion, Go to
/// Declaration and hover across `@use`, and syntax errors as diagnostics.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires some-sass-language-server on PATH"]
async fn some_sass_indented_end_to_end() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let theme = root.join("_theme.sass");
std::fs::write(
&theme,
"/// Brand colour\n$brand: #336699\n\n/// Rounded corners\n@mixin rounded($r: 4px)\n border-radius: $r\n",
)
.unwrap();
let main = root.join("main.sass");
let source = "@use \"theme\"\n\n.button\n color: theme.$brand\n +theme.rounded(2px)\n";
std::fs::write(&main, source).unwrap();
let sass = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("sass")).unwrap();
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![sass]));
let doc = DocId::next();
mgr.did_open(doc, &main, &LanguageId::new("sass"), 1, source);
let name = "some-sass-language-server";
retry("some-sass ready", Duration::from_secs(30), || {
let status = last_status(&events, name);
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("some-sass failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
// `theme.$brand` and the `+theme.rounded` mixin, both in `_theme.sass`.
for (pos, line) in [(Pos::new(3, 17), 1), (Pos::new(4, 10), 4)] {
let defs = retry("definition", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move { mgr.goto(doc, pos, GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
})
.await;
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (theme.clone(), line), "{pos:?}");
}
// The `@use` path is a document link, which Go to Declaration follows.
let links = mgr.document_links(doc).await.unwrap();
assert!(
links
.iter()
.any(|l| l.range.start.line == 0 && l.path.as_ref().map(|p| p.to_path_buf()) == Some(theme.clone())),
"{links:?}"
);
let hover = mgr.hover(doc, Pos::new(3, 17), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("#336699") && hover.contents.value.contains("Brand colour"));
let hover = mgr.hover(doc, Pos::new(4, 10), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("Rounded corners"), "{}", hover.contents.value);
// `$` lists the module's variables, `+` its mixins.
let edited = format!("{source} margin: theme.$\n +theme.\n");
mgr.did_change(
doc,
2,
&[AppliedChange { range: Range::point(Pos::new(5, 0)), text: edited[source.len()..].into() }],
&|| unreachable!(),
);
let labels = |list: ide_lsp::types::CompletionList| list.items.into_iter().map(|i| i.label).collect::<Vec<_>>();
let vars = labels(mgr.completion(doc, Pos::new(5, 16), Some("$".into()), Default::default()).await.unwrap());
assert!(vars.iter().any(|l| l.contains("$brand")), "{vars:?}");
let mixins = labels(mgr.completion(doc, Pos::new(6, 9), Some(".".into()), Default::default()).await.unwrap());
assert!(mixins.iter().any(|l| l.contains("rounded")), "{mixins:?}");
let errors = retry("diagnostics", Duration::from_secs(30), || {
let found = events.lock().iter().rev().find_map(|event| match event {
IdeEvent::Diagnostics { source, items, .. } if source == name && !items.is_empty() => Some(items.clone()),
_ => None,
});
async move { found }
})
.await;
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
db06d81fb37a51711e2b76ab0192eb23293ef498e8ff6e5e46e0b5099d6ba038
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
// Variables go by name (`-e NAME`) so their values stay out of the command line
// echoed in the console; the docker CLI reads them from its own environment.
let mut env: BTreeMap<String, String> = run.file_env.clone();
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
&& !command.env.contains_key("PYTHONUNBUFFERED")
{
env.insert("PYTHONUNBUFFERED".into(), "1".into());
+37 -1
Переглянути файл
@@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool {
if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) {
return true;
}
if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) {
// A `tests` folder alone means pytest unless its tests are the standard library's unittest.
if read(&root.join("pyproject.toml"))
.is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root)))
{
return true;
}
["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"]
@@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool {
.any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest")))
}
/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the
/// standard library's unittest and none of them pytest.
fn uses_unittest(root: &Path) -> bool {
let mut found = false;
for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] {
let Ok(entries) = fs::read_dir(&dir) else { continue };
// ponytail: the first 50 modules of each folder decide; enough to tell a project's style.
for entry in entries.flatten().take(50) {
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with("test") || !name.ends_with(".py") {
continue;
}
let Some(text) = read(&entry.path()) else { continue };
if text
.lines()
.any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest"))
{
return false;
}
found |= text.lines().any(|l| {
let l = l.trim_start();
l.starts_with("import unittest") || l.starts_with("from unittest")
});
}
}
found
}
/// Python configurations of the project at `root`, a folder of the opened project `top`.
fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
@@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest");
if uses_pytest(root) || own_pytest {
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
} else if !root.join("manage.py").is_file() && uses_unittest(root) {
out.push(
py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"])
.test(),
);
}
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
if root.join("manage.py").is_file() {
+33
Переглянути файл
@@ -341,6 +341,7 @@ impl Cx<'_> {
DJANGO_SERVER => self.django_server(name, c, &mut ignored)?,
DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?,
PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?,
PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?,
NPM => self.npm(name, c, &mut ignored)?,
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
NODE => self.node(name, c, &mut ignored)?,
@@ -667,6 +668,38 @@ impl Cx<'_> {
Ok(rc)
}
/// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a
/// file as its path, a folder discovered (`discover -s`, with the configuration's pattern).
fn unittest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
args.extend(["-m".to_owned(), "unittest".to_owned()]);
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
if let Some(target) = field("_new_target") {
let target = self.expand(&target)?;
match field("_new_targetType").as_deref() {
Some("PYTHON") => args.push(target),
Some("CUSTOM") => {}
_ => {
let path = path_from(self.root, file_url_path(&target), &dir);
if path.ends_with(".py") {
args.push(path);
} else {
args.extend(["discover".to_owned(), "-s".to_owned(), path]);
if let Some(pattern) = field("_new_pattern") {
args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]);
}
}
}
}
}
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
let mut rc = config(name, "unittest", exe, args, Some("debugpy"));
rc.cwd = cwd.map(Into::into);
rc.is_test = true;
self.python_env(c, &mut rc, ignored)?;
Ok(rc)
}
/// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm
/// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`):
/// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working
+2 -2
Переглянути файл
@@ -426,7 +426,7 @@ impl ProcessManager {
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
}
let mut env = launch_env(root, config)?;
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") {
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
}
if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) {
@@ -1087,7 +1087,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
};
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
&& !config.env.contains_key("PYTHONUNBUFFERED")
&& !vars.contains_key("PYTHONUNBUFFERED")
{
+28
Переглянути файл
@@ -676,6 +676,34 @@ fn python_projects() {
assert_eq!(ids(&c), ["python:module:app"]);
}
#[test]
fn python_unittest_projects() {
const UNITTEST: &str = "import unittest\n\nclass T(unittest.TestCase):\n pass\n";
// The standard library's unittest and no pytest: `python -m unittest`.
let dir = project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", UNITTEST)]);
let c = detect(dir.path());
assert_eq!(ids(&c), ["unittest"]);
let unittest = find(&c, "unittest");
let python = if cfg!(windows) { "python" } else { "python3" };
assert_eq!(cmdline(unittest), format!("{python} -m unittest"));
assert!(unittest.is_test);
assert_eq!(unittest.debug_adapter.as_deref(), Some("debugpy"));
let dir = project(&[("requirements.txt", ""), ("test_app.py", UNITTEST)]);
assert_eq!(ids(&detect(dir.path())), ["unittest"]);
// A module that imports pytest, a `tests` folder of pytest-style tests, or Django: as before.
let dir = project(&[
("pyproject.toml", "[project]\nname = 'x'\n"),
("tests/test_x.py", UNITTEST),
("tests/test_y.py", "import pytest\n"),
]);
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
let dir =
project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", "def test_x():\n assert 1\n")]);
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
let dir = project(&[("manage.py", ""), ("shop/tests.py", UNITTEST), ("test_x.py", UNITTEST)]);
assert_eq!(ids(&detect(dir.path())), ["django:runserver", "django:test"]);
}
#[cfg(unix)]
#[test]
fn python_virtualenv() {
+17 -4
Переглянути файл
@@ -299,7 +299,16 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
</configuration>
<configuration name="Unittests in tests" type="tests" factoryName="Unittests">
{PY_COMMON}
<option name="_new_target" value="&quot;tests&quot;" />
<option name="_new_pattern" value="&quot;check_*.py&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/tests&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<configuration name="Unittest case" type="tests" factoryName="Unittests">
{PY_COMMON}
<option name="_new_additionalArguments" value="&quot;-f&quot;" />
<option name="_new_target" value="&quot;tests.test_money.RoundTests&quot;" />
<option name="_new_targetType" value="&quot;PYTHON&quot;" />
<method v="2" />
</configuration>
<configuration name="dev" type="js.build_tools.npm">
@@ -319,7 +328,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
);
let r = import_from(dir.path(), &[]);
let names: Vec<&str> = r.imported.iter().map(|c| c.config.name.as_str()).collect();
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "dev"]);
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "Unittests in tests", "Unittest case", "dev"]);
let app = get(&r, "App");
// `$USER_HOME$` is this machine's: the configuration goes to run.local.toml.
@@ -343,7 +352,11 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
assert_eq!(get(&r, "Path params").args, s(&["-m", "pytest", "tests/test_money.py", "-k", "slow or fast"]));
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
let unittests = get(&r, "Unittests in tests");
assert_eq!(unittests.kind, "unittest");
assert!(unittests.is_test);
assert_eq!(unittests.args, s(&["-m", "unittest", "discover", "-s", "tests", "-p", "check_*.py"]));
assert_eq!(get(&r, "Unittest case").args, s(&["-m", "unittest", "tests.test_money.RoundTests", "-f"]));
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
let dev = get(&r, "dev");
@@ -366,7 +379,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
);
assert_eq!(ignored(&r, "dev"), ["scripts"]);
// Neither the template nor the temporary `build` is listed as skipped.
assert_eq!(r.skipped.len(), 2);
assert_eq!(r.skipped.len(), 1);
}
#[test]
+3
Переглянути файл
@@ -35,6 +35,9 @@ pub(crate) const SOURCES: &[(&str, &str)] = generators![
"astro",
"nestjs",
"express",
"vue",
"expo",
"electron",
// Systems
"go",
"rust",
+8
Переглянути файл
@@ -20,8 +20,13 @@ dotnet:
- "dotnet new console --name my-app --output my-app --language C#"
- dotnet sln add my-app
- dotnet new gitignore
electron:
- npx --yes create-electron-app@latest init my-app --skip-git --package-manager npm --template vite --typescript
elixir:
- mix new . --app my_app
expo:
- npx --yes create-expo-app@latest my-app --template blank-typescript --no-install --yes
- npm install
express:
- npm install
fastapi:
@@ -77,5 +82,8 @@ symfony:
vite:
- npx --yes create-vite@latest my-app --template react-ts --no-interactive
- npm install
vue:
- npx --yes create-vue@latest my-app --ts
- npm install
zig:
- zig init
+14
Переглянути файл
@@ -130,6 +130,20 @@ fn package_steps_use_the_chosen_runner() {
assert_eq!(argv(step, &values)[..2], ["bunx", "create-vite@latest"]);
}
#[test]
fn create_vue_runs_without_prompting() {
let def = def("vue").unwrap();
let mut values = with_defaults(def, "My App", &Values::new());
// A valid package name, or create-vue asks for one.
assert_eq!(argv(&def.steps[0], &values)[2..], ["create-vue@latest", "my-app", "--ts"]);
values.insert("ts".into(), "false".into());
assert!(argv(&def.steps[0], &values).ends_with(&["--oxlint".to_owned()]));
for flag in ["router", "pinia", "vitest", "eslint"] {
values.insert(flag.into(), "true".into());
}
assert!(argv(&def.steps[0], &values).ends_with(&["--router", "--pinia", "--vitest", "--eslint"].map(String::from)));
}
#[test]
fn conditional_arguments() {
let def = def("python").unwrap();
+4
Переглянути файл
@@ -72,6 +72,10 @@ smoke! {
astro: "astro", [], ["npm", "run", "build"];
nestjs: "nestjs", [], ["npm", "run", "build"];
express: "express", [], ["node", "--check", "index.js"];
vue: "vue", [("router", "true"), ("pinia", "true"), ("vitest", "true"), ("eslint", "true")], ["npm", "run", "build"];
expo: "expo", [], ["npx", "tsc", "--noEmit"];
electron: "electron", [], ["npx", "tsc", "--noEmit"];
electron_pnpm: "electron", [("pm", "pnpm")], ["pnpm", "exec", "tsc", "--noEmit"];
html: "html", [], [];
go: "go", [], ["go", "build", "./..."];
rust: "rust", [], ["cargo", "build", "-q"];
+73 -3
Переглянути файл
@@ -1574,6 +1574,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
{
cfg.command = bin.to_string_lossy().into_owned();
}
if name == crate::mdx::SERVER {
crate::mdx::configure(cfg, root, server_root, s);
}
if name == crate::arduino::SERVER {
crate::arduino::configure(cfg, root, server_root, s);
}
@@ -1649,6 +1652,32 @@ pub fn configure_path_aliases(cfg: &mut LanguageServerConfig, server_root: &Path
true
}
/// Lets vtsls load the tsserver plugins that the project's tsconfig.json / jsconfig.json
/// declare (Next.js) with any TypeScript version, from a plugin probe location under
/// `data_dir` that loads the project's packages (#6336). A plugin the IDE registers globally
/// keeps the IDE's copy, also when a tsconfig names it, so call this after those are
/// registered. No-op without declared plugins, and for TypeScript 7's native server.
pub fn configure_tsconfig_plugins(cfg: &mut LanguageServerConfig, server_root: &Path, data_dir: &Path) -> bool {
if cfg.name != "vtsls" || !cfg.tsserver_project {
return false;
}
let options = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok());
let global: Vec<String> = options
.as_ref()
.and_then(|v| v.pointer("/vtsls/tsserver/globalPlugins")?.as_array().cloned())
.unwrap_or_default()
.iter()
.filter_map(|p| p.get("name")?.as_str().map(str::to_owned))
.collect();
let mut declared = crate::tsconfig_plugins::declared(server_root);
declared.packages.retain(|name, _| !global.contains(name));
let Some(location) = crate::tsconfig_plugins::probe_location(data_dir, server_root, &declared) else {
return false;
};
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "pluginPaths": [location] } } }));
true
}
/// The servers `language` uses after Settings › Language Servers: the
/// definition's ones that aren't disabled, then the ones defined in settings for it.
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
@@ -1925,7 +1954,7 @@ pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a
}
fn is_python_config(config: &RunConfig, program: &str) -> bool {
matches!(config.kind.as_str(), "python" | "pytest" | "django-test") || is_python_command(program)
matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") || is_python_command(program)
}
/// Whether the configuration's `JAVA_HOME` is the one Settings choose (the Maven runner JRE,
@@ -2038,7 +2067,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
"python" | "pytest" | "django-test" => {
"python" | "pytest" | "unittest" | "django-test" => {
let command = Path::new(&c.command);
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
let python = if own {
@@ -2056,7 +2085,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
let runner_options = runner
&& c.args.first().map(String::as_str) == Some("run")
&& c.args.get(1).is_some_and(|a| a.starts_with('-'));
if (c.kind == "python" || c.kind == "django-test")
if matches!(c.kind.as_str(), "python" | "unittest" | "django-test")
&& !runner_options
&& (runner || is_python_command(&c.command))
{
@@ -2689,6 +2718,47 @@ mod maven_linkage_tests {
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
}
#[test]
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
let tmp = tempfile::tempdir().unwrap();
let (root, data) = (tmp.path().join("app"), tmp.path().join("data"));
std::fs::create_dir_all(root.join("node_modules/next")).unwrap();
std::fs::create_dir_all(root.join("node_modules/@vue/typescript-plugin")).unwrap();
let vtsls = || {
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
cfg.tsserver_project = true;
merge_init_options(
&mut cfg,
json!({ "vtsls": { "tsserver": { "globalPlugins": [{ "name": vue::PLUGIN }] } } }),
);
cfg
};
let probed = |cfg: &LanguageServerConfig| {
serde_json::to_value(&cfg.initialization_options)
.unwrap()
.pointer("/typescript/tsserver/pluginPaths")
.cloned()
};
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions":{"strict":true}}"#).unwrap();
let mut cfg = vtsls();
assert!(!configure_tsconfig_plugins(&mut cfg, &root, &data));
assert_eq!(probed(&cfg), None);
let plugins = format!(r#"[{{"name":"next"}},{{"name":"{}"}}]"#, vue::PLUGIN);
std::fs::write(root.join("tsconfig.json"), format!(r#"{{"compilerOptions":{{"plugins":{plugins}}}}}"#))
.unwrap();
let mut cfg = vtsls();
assert!(configure_tsconfig_plugins(&mut cfg, &root, &data));
let location = PathBuf::from(probed(&cfg).unwrap()[0].as_str().unwrap());
assert!(location.starts_with(&data) && location.join("node_modules/next/index.js").is_file());
// The IDE's Vue plugin is not replaced by the project's.
assert!(!location.join("node_modules").join(vue::PLUGIN).exists());
// TypeScript 7's native server hosts no plugins.
let mut native = vtsls();
native.tsserver_project = false;
assert!(!configure_tsconfig_plugins(&mut native, &root, &data));
}
#[test]
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -22,12 +22,14 @@ pub mod libraries;
pub mod locate;
pub mod lombok;
pub mod maven_profiles;
mod mdx;
mod npm;
mod path_aliases;
pub mod php;
pub mod pinned;
pub mod python;
pub mod ruby;
mod tsconfig_plugins;
mod vue;
mod zig;
+120
Переглянути файл
@@ -0,0 +1,120 @@
//! The MDX language server (Volar) refuses to start without `typescript.tsdk`.
use crate::apply::{merge_init_options, setting_path, tsdk};
use crate::discover::workspace_tsdk;
use crate::npm::{own_typescript, package_dir};
use ide_core::settings::Settings;
use ide_core::tool_path::{find_command, search_path};
use ide_language::LanguageServerConfig;
use serde_json::json;
use std::ffi::OsString;
use std::path::Path;
pub(crate) const SERVER: &str = "mdx-language-server";
/// The TypeScript vtsls runs with: the selected version, else vtsls' bundled one.
/// Without vtsls, the one installed with the server, then the project's.
pub(crate) fn configure(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
let explicit = |o: Option<&toml::Value>| o.and_then(|o| o.get("typescript")?.get("tsdk")).is_some();
let overridden = s.language_servers.get(SERVER).and_then(|ls| ls.initialization_options.as_ref());
if explicit(cfg.initialization_options.as_ref())
|| overridden.is_some_and(|o| o.pointer("/typescript/tsdk").is_some())
{
return;
}
let search = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
// Missing servers keep the normal install hint.
let Some(bin) = find_command(&cfg.command, &search, server_root) else { return };
let bundled = |command: &Path, package: &str| own_typescript(&package_dir(command, package)?);
let vtsls = s
.tool_path("vtsls")
.and_then(|p| setting_path(root, p))
.or_else(|| find_command("vtsls", &search, server_root));
let lib = tsdk(server_root, s)
.or_else(|| tsdk(root, s))
.or_else(|| bundled(vtsls.as_deref()?, "@vtsls/language-server"))
.or_else(|| bundled(&bin, "@mdx-js/language-server"))
.or_else(|| workspace_tsdk(server_root))
.or_else(|| workspace_tsdk(root));
match lib {
Some(lib) => merge_init_options(cfg, json!({ "typescript": { "tsdk": lib.to_string_lossy() } })),
None => {
cfg.launch_error = Some(
"MDX Language Server needs TypeScript. Install typescript@6 in the project or select a TypeScript lib directory in Settings."
.into(),
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
use std::path::PathBuf;
fn touch(path: &Path) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "{}").unwrap();
#[cfg(unix)]
std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
}
fn bin(dir: &Path, name: &str) {
touch(&dir.join("node_modules/.bin").join(if cfg!(windows) { format!("{name}.cmd") } else { name.into() }));
}
/// An npm install of `package` with command `bin` under `dir`, and its TypeScript lib.
fn install(dir: &Path, package: &str, bin: &str, typescript: &Path) -> PathBuf {
self::bin(dir, bin);
touch(&dir.join("node_modules").join(package).join("package.json"));
let lib = typescript.join("node_modules/typescript/lib");
touch(&lib.join("typescript.js"));
touch(&lib.join("tsserver.js"));
lib
}
fn sdk(root: &Path, path: &[&Path], settings: &Settings) -> LanguageServerConfig {
let reg = LanguageRegistry::load(None).unwrap();
let mut cfg = reg.get(&LanguageId::new("mdx")).unwrap().language_servers.remove(0);
let bins: Vec<PathBuf> = path.iter().map(|p| p.join("node_modules/.bin")).collect();
cfg.env.insert("PATH".into(), std::env::join_paths(bins).unwrap().to_string_lossy().into_owned());
configure(&mut cfg, root, root, settings);
cfg
}
fn tsdk_of(cfg: &LanguageServerConfig) -> Option<PathBuf> {
let options = cfg.initialization_options.as_ref()?;
assert_eq!(options.get("typescript")?.get("enabled")?.as_bool(), Some(true));
Some(PathBuf::from(options.get("typescript")?.get("tsdk")?.as_str()?))
}
#[test]
fn uses_the_typescript_of_vtsls_then_its_own_then_the_project() {
let tmp = tempfile::tempdir().unwrap();
let t = dunce::canonicalize(tmp.path()).unwrap();
let (mdx, vtsls, project) = (t.join("mdx"), t.join("vtsls"), t.join("project"));
let own = install(&mdx, "@mdx-js/language-server", SERVER, &mdx);
let vtsls_lib =
install(&vtsls, "@vtsls/language-server", "vtsls", &vtsls.join("node_modules/@vtsls/language-server"));
let workspace = project.join("node_modules/typescript/lib");
touch(&workspace.join("tsserver.js"));
let mut settings = Settings::default();
assert_eq!(tsdk_of(&sdk(&project, &[&mdx], &settings)), Some(own));
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(vtsls_lib));
settings.languages.typescript.version = "workspace".into();
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(workspace));
// Missing server: the usual install hint, nothing derived.
let missing = sdk(&project, &[&vtsls], &settings);
assert_eq!((tsdk_of(&missing), missing.launch_error), (None, None));
// No TypeScript anywhere.
let bare = t.join("bare");
bin(&bare, SERVER);
let none = sdk(&t.join("empty"), &[&bare], &Settings::default());
assert_eq!(tsdk_of(&none), None);
assert!(none.launch_error.unwrap().contains("TypeScript"));
}
}
+4 -1
Переглянути файл
@@ -564,6 +564,7 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
run("django-test", "uv", &["run", "python", "manage.py", "test"]),
run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]),
run("python", "uv", &["run", "--with", "rich", "--no-sync", "main.py"]),
run("unittest", "uv", &["run", "python", "-m", "unittest", "tests"]),
];
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].command, python);
@@ -581,6 +582,8 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
// uv's own options stay with uv (#5874).
assert_eq!(configs[7].command, "uv");
assert_eq!(configs[7].args, ["run", "--with", "rich", "--no-sync", "main.py"]);
assert_eq!(configs[8].command, python);
assert_eq!(configs[8].args, ["-m", "unittest", "tests"]);
}
#[test]
@@ -594,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
for command in [&override_python, relative_python] {
for kind in ["python", "pytest", "django-test"] {
for kind in ["python", "pytest", "unittest", "django-test"] {
let command = command.to_string_lossy();
let mut config = run(kind, &command, &["main.py"]);
config.detected = false;
+234
Переглянути файл
@@ -0,0 +1,234 @@
//! The tsserver plugins a project's tsconfig.json / jsconfig.json declares
//! (`compilerOptions.plugins`, e.g. Next.js' `{ "name": "next" }`). tsserver looks for them
//! next to the TypeScript it runs from and in its plugin probe locations only, so with the
//! bundled TypeScript they are never found unless the project's folder is a probe location.
//! Language servers run in trusted projects only, so untrusted ones never load them.
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const CONFIGS: [&str; 2] = ["tsconfig.json", "jsconfig.json"];
/// The plugins that the tsconfig.json / jsconfig.json files under a server root declare.
#[derive(Debug, Default)]
pub(crate) struct Declared {
/// The plugins' packages by name, resolved as tsserver resolves a plugin from a probe
/// location: `node_modules` in the configuration's folder or above.
pub packages: BTreeMap<String, PathBuf>,
/// The text of the configurations declaring them, with what they extend. When one changes,
/// tsserver applies its plugins again on top of the loaded ones (each diagnostic of the
/// Next.js plugin shows once more), so the probe location changes and vtsls restarts.
pub sources: String,
}
/// The plugins that the configurations under `server_root` declare. Logs the ones that are
/// not installed; tsserver skips them.
pub(crate) fn declared(server_root: &Path) -> Declared {
// ponytail: bounded walk, as the path aliases'; deeper workspace members keep the old behaviour.
const MAX_DEPTH: usize = 4;
const MAX_ENTRIES: usize = 50_000;
let mut walker = ignore::WalkBuilder::new(server_root);
walker
.max_depth(Some(MAX_DEPTH))
.require_git(ide_core::ignored::inside_git_repo(server_root))
.follow_links(false)
.filter_entry(|e| e.file_name() != "node_modules");
let mut configs: Vec<PathBuf> = walker
.build()
.take(MAX_ENTRIES)
.flatten()
.filter(|e| CONFIGS.iter().any(|c| e.file_name() == *c))
.map(|e| e.into_path())
.collect();
configs.sort();
// ponytail: one package per name; a monorepo with two versions of a plugin gets the first one's.
let mut declared = Declared::default();
for config in configs {
let Some(dir) = config.parent() else { continue };
let mut sources = String::new();
let names = plugins(&config, 0, &mut sources);
if !names.is_empty() {
declared.sources.push_str(&sources);
}
for name in names.into_iter().filter(|n| package_name(n)) {
match dir.ancestors().map(|d| d.join("node_modules").join(&name)).find(|p| p.is_dir()) {
Some(package) => {
declared.packages.entry(name).or_insert(package);
}
None => tracing::warn!("vtsls: tsserver plugin `{name}` from {} is not installed", config.display()),
}
}
}
declared
}
/// A plugin probe location under `data_dir` holding a package for each of the `declared`
/// plugins that loads the project's one, and nothing else: packages the project has under the
/// names of the IDE's global plugins never shadow those, as the project folder itself would
/// (vtsls puts `pluginPaths` before the global plugins' locations). Named after its contents
/// and the declaring configurations, so a change is a new location (and a configuration change
/// that restarts vtsls). `None` without plugins or when it cannot be written.
pub(crate) fn probe_location(data_dir: &Path, server_root: &Path, declared: &Declared) -> Option<PathBuf> {
let plugins = &declared.packages;
if plugins.is_empty() {
return None;
}
let parent = data_dir.join("tsplugins").join("project").join(key(&server_root.to_string_lossy()));
let location = parent.join(key(&format!("{}{}", serde_json::to_string(plugins).ok()?, declared.sources)));
for (name, package) in plugins {
let dir = location.join("node_modules").join(name);
std::fs::create_dir_all(&dir).ok()?;
let index = format!("module.exports = require({});\n", Value::from(package.to_string_lossy()));
let manifest = serde_json::json!({ "name": name, "main": "index.js" }).to_string();
for (file, content) in [("index.js", index), ("package.json", manifest)] {
if std::fs::read(dir.join(file)).ok().as_deref() != Some(content.as_bytes()) {
std::fs::write(dir.join(file), content).ok()?;
}
}
}
// The previous contents: a running tsserver loaded its plugins already.
for old in std::fs::read_dir(&parent).into_iter().flatten().flatten() {
if old.path() != location {
let _ = std::fs::remove_dir_all(old.path());
}
}
Some(location)
}
fn key(text: &str) -> String {
Sha256::digest(text.as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect()
}
/// An npm package name (`next`, `@scope/name`): it becomes a path under the data dir.
fn package_name(name: &str) -> bool {
let parts: Vec<&str> = name.split('/').collect();
let part = |p: &str| {
!p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c))
};
match parts.as_slice() {
[name] => part(name),
[scope, name] => scope.strip_prefix('@').is_some_and(part) && part(name),
_ => false,
}
}
/// `compilerOptions.plugins` names of `config`, else of the configurations it `extends`
/// (the last of an `extends` array that has some wins, as tsc merges them). Appends the text
/// of each file read, the whole `extends` chain, to `read`.
fn plugins(config: &Path, depth: usize, read: &mut String) -> Vec<String> {
let Ok(text) = std::fs::read_to_string(config) else { return Vec::new() };
read.push_str(&text);
let Ok(json) = serde_json::from_str::<Value>(&ide_core::jsonc::strip(&text)) else { return Vec::new() };
let dir = config.parent().unwrap_or(Path::new(""));
let extends = match json.get("extends") {
Some(Value::String(s)) => vec![s.as_str()],
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
_ => Vec::new(),
};
let inherited: Vec<Vec<String>> = if depth > 8 {
Vec::new()
} else {
extends.into_iter().filter_map(|spec| extended(dir, spec)).map(|base| plugins(&base, depth + 1, read)).collect()
};
match json.pointer("/compilerOptions/plugins").and_then(Value::as_array) {
Some(own) => own.iter().filter_map(|p| p.get("name")?.as_str().map(str::to_owned)).collect(),
None => inherited.into_iter().rev().find(|p| !p.is_empty()).unwrap_or_default(),
}
}
/// The file an `extends` entry names: a path relative to `dir`, or a package's file
/// (`@tsconfig/next/tsconfig.json`, or a package's own `tsconfig.json`) in `node_modules`.
fn extended(dir: &Path, spec: &str) -> Option<PathBuf> {
let candidates = |base: PathBuf| [base.clone(), base.with_extension("json"), base.join("tsconfig.json")];
if spec.starts_with('.') || Path::new(spec).is_absolute() {
return candidates(dir.join(spec)).into_iter().find(|p| p.is_file());
}
dir.ancestors().flat_map(|d| candidates(d.join("node_modules").join(spec))).find(|p| p.is_file())
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, file: &str, text: &str) {
let path = root.join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
#[test]
fn declared_plugins_resolve_to_the_project_packages() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "package.json", "{}");
// A monorepo: the root tsconfig has no plugins, the Next.js app (comments, trailing commas) has.
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": true } }"#);
write(
root,
"apps/web/tsconfig.json",
"{\n // Next.js\n \"compilerOptions\": { \"plugins\": [{ \"name\": \"next\" },] } }",
);
write(root, "apps/web/node_modules/next/package.json", "{}");
// Inherited from a shared configuration, in a package and in a relative file; resolved upwards.
write(root, "apps/docs/tsconfig.json", r#"{ "extends": ["../../tsconfig.json", "@acme/tsconfig/next.json"] }"#);
write(
root,
"node_modules/@acme/tsconfig/next.json",
r#"{ "compilerOptions": { "plugins": [{ "name": "@acme/plugin" }] } }"#,
);
write(root, "node_modules/@acme/plugin/package.json", "{}");
write(root, "apps/api/jsconfig.json", r#"{ "extends": "./base" }"#);
write(
root,
"apps/api/base.json",
r#"{ "compilerOptions": { "plugins": [{ "name": "missing-plugin" }, { "name": "../../escape" }] } }"#,
);
// An empty list overrides the inherited one; node_modules is never searched for configurations.
write(
root,
"apps/plain/tsconfig.json",
r#"{ "extends": "../api/base.json", "compilerOptions": { "plugins": [] } }"#,
);
write(root, "node_modules/x/tsconfig.json", r#"{ "compilerOptions": { "plugins": [{ "name": "x" }] } }"#);
let found = declared(root);
let expected = [("@acme/plugin", "node_modules/@acme/plugin"), ("next", "apps/web/node_modules/next")];
assert_eq!(found.packages, expected.map(|(n, p)| (n.to_owned(), root.join(p))).into_iter().collect());
// Forwarding packages, replaced when the plugins change.
let data = tempfile::tempdir().unwrap();
let location = probe_location(data.path(), root, &found).unwrap();
let index = std::fs::read_to_string(location.join("node_modules/@acme/plugin/index.js")).unwrap();
assert!(index.contains(&serde_json::to_string(&root.join("node_modules/@acme/plugin")).unwrap()), "{index}");
let next_only =
Declared { packages: found.packages.clone().into_iter().filter(|(n, _)| n == "next").collect(), ..found };
let changed = probe_location(data.path(), root, &next_only).unwrap();
assert_ne!(changed, location);
assert!(!location.exists() && changed.join("node_modules/next/index.js").is_file());
// Any edit of a declaring configuration (or one it extends) makes a new location.
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": false } }"#);
let edited =
probe_location(data.path(), root, &Declared { sources: declared(root).sources, ..next_only }).unwrap();
assert_ne!(edited, changed);
assert_eq!(probe_location(data.path(), root, &Declared::default()), None);
}
#[test]
fn plugin_names_are_package_names() {
for ok in ["next", "@scope/name", "gql.tada", "@styled/typescript-styled-plugin"] {
assert!(package_name(ok), "{ok}");
}
for bad in ["", "..", "../x", "a/b", "@scope", "@/x", "@scope/..", "a\\b", "/abs"] {
assert!(!package_name(bad), "{bad}");
}
}
#[test]
fn projects_without_plugins_declare_none() {
let tmp = tempfile::tempdir().unwrap();
write(tmp.path(), "tsconfig.json", r#"{ "extends": "./missing.json", "compilerOptions": {} }"#);
assert!(declared(tmp.path()).packages.is_empty());
}
}
+1 -6
Переглянути файл
@@ -183,15 +183,10 @@ pub fn arguments(
return vec!["format".into(), path];
}
if tool == "prettier" {
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
"mdx"
} else {
&config.parser
};
args.extend(
[
"--parser",
parser,
config.parser.as_str(),
"--config-precedence",
"file-override",
"--tab-width",
+1 -1
Переглянути файл
@@ -447,7 +447,7 @@ impl Http {
self
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) fn gh_path(&self) -> Option<&Path> {
self.gh.as_deref()
}
+22
Переглянути файл
@@ -446,6 +446,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
needs: &[],
},
ToolSpec {
name: "some-sass-language-server",
display: "Some Sass Language Server",
kind: LanguageServer,
commands: &["some-sass-language-server"],
method: Method::Npm { packages: &["some-sass-language-server"] },
fallback: None,
version: V,
homepage: "https://github.com/wkillerud/some-sass",
needs: &[],
},
ToolSpec {
name: "vscode-html-language-server",
display: "HTML Language Server",
@@ -479,6 +490,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/withastro/astro/tree/main/packages/language-tools",
needs: NODE,
},
ToolSpec {
name: "mdx-language-server",
display: "MDX Language Server",
kind: LanguageServer,
commands: &["mdx-language-server"],
method: Method::Npm { packages: &["@mdx-js/language-server", TYPESCRIPT] },
fallback: None,
version: V,
homepage: "https://github.com/mdx-js/mdx-analyzer",
needs: NODE,
},
ToolSpec {
name: "svelte-language-server",
display: "Svelte Language Server",
+6 -1
Переглянути файл
@@ -181,6 +181,9 @@ fn everything_missing_on_an_empty_system() {
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
// Shared npm package: each server is its own row.
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
let sass = find(&list, "some-sass-language-server");
assert_eq!(sass.install_method.as_deref(), Some("npm"));
assert_eq!(sass.languages, ["Sass"]);
assert!(find(&list, "delve").kind == ToolKind::Debugger);
}
@@ -652,6 +655,7 @@ for a in "$@"; do case "$a" in
typescript-language-server@latest) n=typescript-language-server;;
@vue/language-server@latest) n=vue-language-server; d=@vue/language-server;;
@astrojs/language-server@latest) n=astro-ls; d=@astrojs/language-server;;
@mdx-js/language-server@latest) n=mdx-language-server; d=@mdx-js/language-server;;
*) continue;;
esac
d="${{d:-$n}}"; /bin/mkdir -p "$prefix/node_modules/$d"
@@ -662,7 +666,7 @@ done"#,
),
);
let tools = env.tools();
for name in ["vue-language-server", "typescript-language-server", "astro-ls"] {
for name in ["vue-language-server", "typescript-language-server", "astro-ls", "mdx-language-server"] {
assert_eq!(
tools.install(name, &langs(), &CancellationToken::new(), &|_| {}).unwrap().status,
ToolStatus::Installed
@@ -674,6 +678,7 @@ done"#,
}
assert!(installs.contains("@vue/language-server@latest"), "{installs}");
assert!(installs.contains("@astrojs/language-server@latest"), "{installs}");
assert!(installs.contains("@mdx-js/language-server@latest"), "{installs}");
fs::write(&log, "").unwrap();
tools.uninstall("vue-language-server", &langs()).unwrap();
+102 -30
Переглянути файл
@@ -1,5 +1,5 @@
use crate::editorconfig::{EditorConfig, EditorConfigProps};
use crate::file_defaults::FileDefaults;
use crate::file_defaults::{EncodingSource, FileDefaults};
use ide_core::error::ErrorKind;
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
@@ -168,6 +168,8 @@ struct DocState {
can_reload_encoding: bool,
/// The user picked `encoding`; reloads keep it instead of detecting again.
encoding_chosen: bool,
/// The user converted the text to `encoding`; it is theirs to keep once a save writes it.
encoding_unsaved: bool,
/// Disk state we last loaded or wrote; changes matching it are our own.
disk_mtime: f64,
disk_len: u64,
@@ -247,19 +249,25 @@ fn disk_len(path: &Path) -> u64 {
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}
fn editorconfig_label(editorconfig: Option<&EditorConfigProps>, detected: &str, ascii: bool) -> Option<&'static str> {
let (charset, _) = editorconfig?.encoding()?;
let compatible = encoding_rs::Encoding::for_label(detected.as_bytes()).is_some_and(|e| e.is_ascii_compatible());
(ascii && compatible && !charset.starts_with("utf-16")).then_some(charset)
}
fn apply_editorconfig_charset(loaded: &mut ide_vfs::LoadedText, editorconfig: Option<&EditorConfigProps>) {
if loaded.binary {
return;
}
if let Some(charset) = editorconfig_label(editorconfig, &loaded.encoding, !loaded.has_bom && loaded.text.is_ascii())
{
loaded.encoding = charset.to_owned();
/// EditorConfig takes precedence over File Encodings for legacy text and ASCII labels.
/// UTF-16 is detected, not assumed; invalid UTF-8 still uses the File Encodings fallback.
fn configured_fallback<'a>(
defaults: &'a FileDefaults,
path: &Path,
editorconfig: Option<&EditorConfigProps>,
) -> Option<ide_vfs::Fallback<'a>> {
let path = absolute(path);
let charset = editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding);
let inherited = defaults.inherited_encoding_for(&path);
let fallback = if inherited.source == EncodingSource::Folder && charset.is_some() {
defaults.project_encoding_for(&path).fallback()
} else {
inherited.fallback()
};
match charset {
Some(("utf-8", _)) => fallback.map(|f| ide_vfs::Fallback { ascii: false, ..f }),
Some((encoding, _)) if !encoding.starts_with("utf-16") => Some(ide_vfs::Fallback { encoding, ascii: true }),
_ => fallback,
}
}
@@ -365,17 +373,21 @@ impl Documents {
/// Closed-file readers use the same decoding as document opening.
pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
let defaults = self.file_defaults();
Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())
Ok(Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())?.0)
}
/// Encoding of `bytes`, a revision of `path`, with the same rules as opening the file.
pub fn detect_encoding(&self, path: &Path, bytes: &[u8]) -> &'static encoding_rs::Encoding {
let defaults = self.file_defaults();
let detected = ide_vfs::detect_encoding(bytes, defaults.fallback_for(&absolute(path)));
let editorconfig = self.editorconfig_for(path, &defaults);
editorconfig_label(editorconfig.as_ref(), detected.name(), bytes.is_ascii())
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
.unwrap_or(detected)
let configured = defaults.configured_encoding_for(&absolute(path));
if configured.source == EncodingSource::File
&& let Some(enc) = encoding_rs::Encoding::for_label(configured.label.as_bytes())
&& !enc.decode_with_bom_removal(bytes).0.contains(char::REPLACEMENT_CHARACTER)
{
return enc;
}
ide_vfs::detect_encoding(bytes, configured_fallback(&defaults, path, editorconfig.as_ref()))
}
fn editorconfig_for(&self, path: &Path, defaults: &FileDefaults) -> Option<EditorConfigProps> {
@@ -385,11 +397,23 @@ impl Documents {
self.editorconfig.resolve(&absolute(path))
}
/// Fallback encoding for closed-file search; ASCII relabelling does not affect its text.
pub fn configured_encoding_for(&self, path: &Path) -> Option<String> {
let defaults = self.file_defaults();
let editorconfig = self.editorconfig_for(path, &defaults);
let configured = defaults.configured_encoding_for(&absolute(path));
if configured.source == EncodingSource::File {
return Some(configured.label.to_owned());
}
configured_fallback(&defaults, path, editorconfig.as_ref()).map(|f| f.encoding.to_owned())
}
/// Bounded closed-file snapshots use the same project defaults as open documents.
pub fn load_file_bounded(&self, path: &Path, max_bytes: usize) -> IdeResult<ide_vfs::LoadedText> {
let defaults = self.file_defaults();
let mut loaded = ide_vfs::load_text_bounded(path, defaults.fallback_for(&absolute(path)), max_bytes)?;
apply_editorconfig_charset(&mut loaded, self.editorconfig_for(path, &defaults).as_ref());
let editorconfig = self.editorconfig_for(path, &defaults);
let mut loaded =
ide_vfs::load_text_bounded(path, configured_fallback(&defaults, path, editorconfig.as_ref()), max_bytes)?;
if !loaded.binary && defaults.native_to_ascii_for(path) {
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
}
@@ -400,17 +424,30 @@ impl Documents {
Self::load_as(path, encoding, self.native_to_ascii_for(path))
}
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
/// very file, as "Reload with Encoding" does, instead of detecting it.
fn load_with_defaults(
path: &Path,
defaults: &FileDefaults,
editorconfig: Option<&EditorConfigProps>,
) -> IdeResult<ide_vfs::LoadedText> {
let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
apply_editorconfig_charset(&mut loaded, editorconfig);
) -> IdeResult<(ide_vfs::LoadedText, bool)> {
let path_abs = absolute(path);
let configured = defaults.configured_encoding_for(&path_abs);
if configured.source == EncodingSource::File {
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
// The bytes are not text in that encoding (the file changed outside the IDE):
// open it as if nothing was chosen, rather than show and save broken characters.
// A single-byte encoding decodes any bytes, so this only catches the others.
if !loaded.text.contains(char::REPLACEMENT_CHARACTER) {
return Ok((loaded, true));
}
}
let fallback = configured_fallback(defaults, path, editorconfig);
let mut loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
if !loaded.binary && defaults.native_to_ascii_for(path) {
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
}
Ok(loaded)
Ok((loaded, false))
}
pub fn file_defaults(&self) -> FileDefaults {
@@ -492,7 +529,7 @@ impl Documents {
}
let defaults = self.file_defaults();
let editorconfig = self.editorconfig_for(path, &defaults);
let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
let (loaded, encoding_chosen) = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
let editorconfig = editorconfig.filter(|_| !loaded.binary);
let language = (self.detect_language)(path, loaded.text.lines().next());
let ui_mode = (self.detect_ui_mode)(path, &language);
@@ -508,8 +545,14 @@ impl Documents {
// An empty file has nothing to detect: Code Style / File Encodings defaults apply.
if empty_file && !loaded.binary {
doc.set_line_ending(defaults.line_ending);
encoding = defaults.encoding.clone();
has_bom = defaults.encoding == "utf-8" && defaults.utf8_bom;
if !encoding_chosen {
let configured = defaults.configured_encoding_for(&absolute(path));
encoding = match configured.source {
EncodingSource::Folder => configured.label.to_owned(),
_ => defaults.encoding.clone(),
};
has_bom = encoding == "utf-8" && defaults.utf8_bom;
}
}
if let Some(ec) = &editorconfig {
if let Some(le) = ec.end_of_line {
@@ -517,6 +560,7 @@ impl Documents {
}
if let Some((enc, bom)) = ec.encoding()
&& empty_file
&& !encoding_chosen
{
(encoding, has_bom) = (enc.to_owned(), bom);
}
@@ -539,7 +583,8 @@ impl Documents {
binary: loaded.binary,
dirty: false,
can_reload_encoding: true,
encoding_chosen: false,
encoding_chosen,
encoding_unsaved: false,
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
@@ -617,6 +662,7 @@ impl Documents {
dirty: false,
can_reload_encoding,
encoding_chosen: false,
encoding_unsaved: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
@@ -678,6 +724,7 @@ impl Documents {
dirty: false,
can_reload_encoding: false,
encoding_chosen: false,
encoding_unsaved: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
@@ -1291,6 +1338,30 @@ impl Documents {
})
}
/// Whether the encoding the user chose for `doc` is still to reach its file: the text was
/// converted and not saved. It is then reported by [`Documents::take_saved_encodings`]
/// once a save has written it.
pub fn keep_encoding_when_saved(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
st.encoding_unsaved = st.dirty;
Ok(st.dirty)
})
}
/// The files saved in the encoding their text was converted to since
/// [`Documents::keep_encoding_when_saved`], with that encoding. Each is reported once.
pub fn take_saved_encodings(&self) -> Vec<(PathBuf, String)> {
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
let saved = |id| {
self.with_doc(id, |st| {
let saved = st.encoding_unsaved && !st.dirty;
st.encoding_unsaved &= st.dirty;
Ok(saved.then(|| (st.path.clone(), st.encoding.clone())))
})
};
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
}
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
@@ -1300,6 +1371,7 @@ impl Documents {
}
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
st.has_bom = loaded.has_bom;
st.encoding_unsaved = false;
self.replace_locked(doc, st, &loaded.text)?;
st.synced(loaded.mtime_ms);
self.set_dirty(doc, st, false);
@@ -1470,7 +1542,7 @@ impl Documents {
let loaded = if st.encoding_chosen {
Self::load_as(&st.path, &st.encoding, native_to_ascii)?
} else {
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?.0
};
st.native_to_ascii = native_to_ascii;
loaded
+1 -1
Переглянути файл
@@ -850,7 +850,7 @@ impl Documents {
let loaded = if state.encoding_chosen {
Self::load_as(path, &state.encoding, native_to_ascii)?
} else {
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?.0
};
state.native_to_ascii = native_to_ascii;
self.replace_locked(id, state, &loaded.text)?;
+55 -11
Переглянути файл
@@ -34,7 +34,8 @@ pub struct EditorConfigProps {
pub indent_size: Option<u32>,
pub tab_width: Option<u32>,
pub end_of_line: Option<LineEnding>,
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be` or `latin1`.
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be`, `latin1` or an encoding
/// Settings › Editor › File Encodings lists (`iso-8859-15`, `windows-1252`, `gbk`, …).
pub charset: Option<String>,
pub trim_trailing_whitespace: Option<bool>,
pub insert_final_newline: Option<bool>,
@@ -48,17 +49,31 @@ impl EditorConfigProps {
/// WHATWG encoding label and BOM flag for `charset`.
pub fn encoding(&self) -> Option<(&'static str, bool)> {
Some(match self.charset.as_deref()? {
"utf-8" => ("utf-8", false),
"utf-8-bom" => ("utf-8", true),
"utf-16le" => ("utf-16le", true),
"utf-16be" => ("utf-16be", true),
"latin1" => ("windows-1252", false),
_ => return None,
})
charset_encoding(self.charset.as_deref()?)
}
}
/// WHATWG label and BOM flag of a lower-cased `charset` value: the five the spec
/// defines and the other encodings Settings › Editor › File Encodings lists.
fn charset_encoding(charset: &str) -> Option<(&'static str, bool)> {
Some(match charset {
"utf-8" => ("utf-8", false),
"utf-8-bom" => ("utf-8", true),
"utf-16le" => ("utf-16le", true),
"utf-16be" => ("utf-16be", true),
// WHATWG decodes ISO-8859-1 as windows-1252.
"latin1" | "iso-8859-1" | "windows-1252" => ("windows-1252", false),
"iso-8859-15" => ("iso-8859-15", false),
"gbk" => ("gbk", false),
"gb18030" => ("gb18030", false),
"big5" => ("big5", false),
"shift_jis" => ("shift_jis", false),
"euc-kr" => ("euc-kr", false),
"koi8-r" => ("koi8-r", false),
_ => return None,
})
}
/// Raw `key = value` pairs (keys lower-cased) in application order.
type Pairs = Vec<(String, String)>;
@@ -200,8 +215,7 @@ fn props_from(map: &HashMap<String, String>) -> EditorConfigProps {
Some("cr") => Some(LineEnding::Cr),
_ => None,
};
let charset =
get("charset").filter(|c| matches!(c.as_str(), "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be" | "latin1"));
let charset = get("charset").filter(|c| charset_encoding(c).is_some());
let max_line_length = get("max_line_length").and_then(|v| v.parse::<u32>().ok());
EditorConfigProps {
indent_style,
@@ -406,4 +420,34 @@ mod tests {
assert!(std::fs::read(r.join("new.l1")).unwrap().is_empty());
assert!(create_file(&ec, &r.join("new.txt")).is_err(), "never truncates");
}
/// The labels of `ENCODING_CHOICES` in `src/platform/editorSettings.ts`, copied by hand.
#[test]
fn charset_maps_the_listed_encodings() {
let tmp = tempfile::tempdir().unwrap();
let r = tmp.path().canonicalize().unwrap();
let listed = [
("utf-8", "utf-8"),
("utf-16le", "utf-16le"),
("utf-16be", "utf-16be"),
("gbk", "gbk"),
("gb18030", "gb18030"),
("big5", "big5"),
("shift_jis", "shift_jis"),
("euc-kr", "euc-kr"),
("windows-1252", "windows-1252"),
("iso-8859-1", "windows-1252"),
("ISO-8859-15", "iso-8859-15"),
("koi8-r", "koi8-r"),
];
let sections: String =
listed.iter().enumerate().map(|(i, (c, _))| format!("[*.e{i}]\ncharset = {c}\n")).collect();
write(&r.join(".editorconfig"), &format!("root = true\n{sections}"));
let ec = EditorConfig::new();
for (i, (charset, label)) in listed.iter().enumerate() {
let encoding = ec.resolve(&r.join(format!("a.e{i}"))).and_then(|p| p.encoding());
assert_eq!(encoding.map(|(label, _)| label), Some(*label), "charset = {charset}");
assert!(encoding_rs::Encoding::for_label(label.as_bytes()).is_some(), "{label} is a WHATWG label");
}
}
}
+212 -11
Переглянути файл
@@ -4,7 +4,8 @@
use ide_core::settings::Settings;
use ide_text::LineEnding;
use std::path::{Path, PathBuf};
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub struct FileDefaults {
@@ -21,6 +22,34 @@ pub struct FileDefaults {
pub native_to_ascii: bool,
pub editorconfig: bool,
pub root: Option<PathBuf>,
/// File Encodings mappings: a file's or a folder's path with its encoding. An entry
/// naming the file itself is the user's choice for it; one naming a folder above it
/// covers the files inside.
pub mappings: Vec<(PathBuf, String)>,
}
/// Where the encoding configured for a file comes from, strongest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EncodingSource {
File,
Properties,
Folder,
Project,
Global,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConfiguredEncoding<'a> {
pub label: &'a str,
pub source: EncodingSource,
}
impl<'a> ConfiguredEncoding<'a> {
/// The label for files that are not valid UTF-8 or are plain ASCII (`None`: detect).
pub fn fallback(self) -> Option<ide_vfs::Fallback<'a>> {
(self.label != "utf-8")
.then_some(ide_vfs::Fallback { encoding: self.label, ascii: self.source != EncodingSource::Properties })
}
}
impl Default for FileDefaults {
@@ -51,20 +80,47 @@ impl FileDefaults {
native_to_ascii: enc.native_to_ascii,
editorconfig: style.editorconfig,
root: root.map(Path::to_path_buf),
mappings: root.map(|root| mappings(root, &enc.mappings)).unwrap_or_default(),
}
}
/// Encoding for `path` when it is not valid UTF-8 (`None`: detect). The project and
/// global encodings also label plain ASCII; the properties encoding only decodes.
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
let (label, ascii) = if path.extension().is_some_and(|e| e == "properties") {
(&self.properties_fallback, false)
} else if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
(&self.project_fallback, true)
} else {
(&self.global_fallback, true)
/// The encoding the settings give `path`: the one chosen for the file itself, else the
/// one it [inherits](Self::inherited_encoding_for).
pub fn configured_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
match self.mappings.iter().find(|(mapped, _)| path == mapped) {
Some((_, label)) => ConfiguredEncoding { label, source: EncodingSource::File },
None => self.inherited_encoding_for(path),
}
}
/// The encoding of `path` without a choice for the file itself: the `.properties`
/// default, the nearest mapped folder above it, then the project's or the global one.
pub fn inherited_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
let folder = || {
let above = self.mappings.iter().filter(|(mapped, _)| path != mapped && path.starts_with(mapped));
above.max_by_key(|(mapped, _)| mapped.components().count())
};
(label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii })
if path.extension().is_some_and(|e| e == "properties") {
ConfiguredEncoding { label: &self.properties_fallback, source: EncodingSource::Properties }
} else if let Some((_, label)) = folder() {
ConfiguredEncoding { label, source: EncodingSource::Folder }
} else {
self.project_encoding_for(path)
}
}
/// The project's encoding for a file inside it, the global one for any other.
pub fn project_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
ConfiguredEncoding { label: &self.project_fallback, source: EncodingSource::Project }
} else {
ConfiguredEncoding { label: &self.global_fallback, source: EncodingSource::Global }
}
}
/// Encoding for `path` when it is not valid UTF-8 or is plain ASCII (`None`: detect).
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
self.configured_encoding_for(path).fallback()
}
pub fn native_to_ascii_for(&self, path: &Path) -> bool {
@@ -81,6 +137,49 @@ impl FileDefaults {
}
}
/// The `[editor.encodings.mappings]` key of `path`: its path inside the project `root`,
/// with `/` separators. `None` for anything else.
pub fn mapping_key(root: &Path, path: &Path) -> Option<String> {
let segments: Option<Vec<&str>> = path
.strip_prefix(root)
.ok()?
.components()
.map(|c| match c {
Component::Normal(name) => name.to_str(),
_ => None,
})
.collect();
segments.filter(|s| !s.is_empty()).map(|s| s.join("/"))
}
/// The mapped paths under `root`. An entry whose key is not such a path, or whose value is
/// not an encoding label, is left out.
fn mappings(root: &Path, entries: &BTreeMap<String, String>) -> Vec<(PathBuf, String)> {
let path_of = |key: &str| {
let mut path = root.to_path_buf();
for segment in key.strip_suffix('/').unwrap_or(key).split('/') {
let mut components = Path::new(segment).components();
let plain = matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
if !plain || segment.contains('\\') {
return None;
}
path.push(segment);
}
Some(path)
};
let mapping = |(key, label): (&String, &String)| {
let label = normalize(label);
match (path_of(key), ide_vfs::encode("", &label, false)) {
(Some(path), Ok(_)) => Some((path, label)),
_ => {
tracing::warn!("ignoring the encoding mapping {key:?} = {label:?}");
None
}
}
};
entries.iter().filter_map(mapping).collect()
}
fn normalize(label: &str) -> String {
let l = label.trim().to_ascii_lowercase();
match l.as_str() {
@@ -108,4 +207,106 @@ mod tests {
assert_eq!(d.fallback_for(Path::new("/p/a.properties")), fallback("iso-8859-1", false));
assert!(d.new_file_bytes().is_empty(), "BOM only for UTF-8 new files");
}
fn mapped(entries: &[(&str, &str)], root: &Path) -> FileDefaults {
let mut s = Settings::default();
s.editor.encodings.project = "gbk".into();
s.editor.encodings.mappings = entries.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
FileDefaults::from_settings(&s, Some(root))
}
#[test]
fn encoding_mappings_resolve_a_file_before_its_folders_and_the_project() {
let root = Path::new("/p");
let d = mapped(
&[
("src", "ISO-8859-15"),
("src/legacy", "koi8-r"),
("src/legacy/A.java", "windows-1252"),
("src/utf", "utf-8"),
("src/app.properties", "big5"),
],
root,
);
let fallback = |rel: &str| d.fallback_for(&root.join(rel));
assert_eq!(fallback("src/legacy/A.java"), Some(ide_vfs::Fallback { encoding: "windows-1252", ascii: true }));
assert_eq!(
fallback("src/legacy/B.java"),
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true }),
"the longest folder wins"
);
assert_eq!(fallback("src/main/C.java"), Some(ide_vfs::Fallback { encoding: "iso-8859-15", ascii: true }));
assert_eq!(
fallback("srcs/C.java"),
Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }),
"a folder is matched by whole path segments"
);
assert_eq!(fallback("other/C.java"), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
assert_eq!(fallback("src/utf/D.java"), None, "a UTF-8 mapping does not fall through to the project");
// `.properties` keep their own default inside a mapped folder; only their own entry overrides it.
assert_eq!(
fallback("src/legacy/b.properties"),
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
);
assert_eq!(fallback("src/app.properties"), Some(ide_vfs::Fallback { encoding: "big5", ascii: true }));
assert_eq!(d.fallback_for(Path::new("/elsewhere/src/C.java")), None);
let source = |rel: &str| d.configured_encoding_for(&root.join(rel)).source;
assert_eq!(source("src/legacy/A.java"), EncodingSource::File);
assert_eq!(source("src/legacy/B.java"), EncodingSource::Folder);
assert_eq!(source("src/legacy/b.properties"), EncodingSource::Properties);
assert_eq!(source("other/C.java"), EncodingSource::Project);
assert_eq!(d.configured_encoding_for(Path::new("/elsewhere/C.java")).source, EncodingSource::Global);
}
#[test]
fn invalid_encoding_mappings_are_dropped() {
let root = Path::new("/p");
let d = mapped(
&[
("ok", "iso-8859-15"),
("unknown", "klingon-1"),
("", "koi8-r"),
("/abs", "koi8-r"),
("../up", "koi8-r"),
("a/./b", "koi8-r"),
("a//b", "koi8-r"),
("back\\slash", "koi8-r"),
],
root,
);
assert_eq!(d.mappings, [(root.join("ok"), "iso-8859-15".to_owned())]);
assert_eq!(d.fallback_for(&root.join("up/A.java")), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
assert!(mapped(&[("ok", "iso-8859-15")], root).mappings.len() == 1);
// Without a project there is nothing the paths are relative to.
let mut s = Settings::default();
s.editor.encodings.mappings.insert("ok".into(), "gbk".into());
assert!(FileDefaults::from_settings(&s, None).mappings.is_empty());
}
#[test]
fn mapping_key_is_the_path_inside_the_project_with_slashes() {
let root = Path::new("/p");
assert_eq!(mapping_key(root, &root.join("src").join("a.b").join("A.java")).as_deref(), Some("src/a.b/A.java"));
assert_eq!(mapping_key(root, Path::new("/elsewhere/A.java")), None);
assert_eq!(mapping_key(root, root), None);
assert_eq!(mapping_key(root, Path::new("untitled:Untitled-1")), None);
let d = mapped(&[("src/a.b/A.java", "koi8-r")], root);
assert_eq!(
d.fallback_for(&root.join("src/a.b/A.java")),
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true })
);
}
#[test]
fn nothing_mapped_resolves_as_before() {
let d = FileDefaults::from_settings(&Settings::default(), Some(Path::new("/p")));
assert!(d.mappings.is_empty());
assert_eq!(d.fallback_for(Path::new("/p/src/A.java")), None);
assert_eq!(
d.fallback_for(Path::new("/p/a.properties")),
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
);
assert_eq!(d.configured_encoding_for(Path::new("/p/src/A.java")).label, "utf-8");
}
}
+75 -2
Переглянути файл
@@ -392,8 +392,35 @@ impl SettingsStore {
{
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
}
self.set_segments(scope, key, &key.split('.').collect::<Vec<_>>(), value)
}
/// Sets (`null`: removes) the `entry` of the map setting `map`, e.g. `editor.encodings.mappings`.
/// Unlike a dotted key of [`set`](Self::set), `entry` may hold dots: a file path.
pub fn set_map_entry(
&self,
scope: SettingsScope,
map: &str,
entry: &str,
value: serde_json::Value,
) -> IdeResult<Settings> {
if scope == SettingsScope::Project
&& let Some(setting) = user_only_setting(map, &serde_json::json!({ entry: value }))
{
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
}
let segments: Vec<&str> = map.split('.').chain([entry]).collect();
self.set_segments(scope, &format!("{map}.{entry}"), &segments, value)
}
fn set_segments(
&self,
scope: SettingsScope,
key: &str,
segments: &[&str],
value: serde_json::Value,
) -> IdeResult<Settings> {
let file = self.file(scope).ok_or_else(|| IdeError::invalid("no project is open"))?.to_path_buf();
let segments: Vec<&str> = key.split('.').collect();
if segments.iter().any(|s| s.is_empty()) {
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
}
@@ -421,7 +448,7 @@ impl SettingsStore {
.parse()
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
set_in_document(&mut doc, &segments, new_value, map_entry);
set_in_document(&mut doc, segments, new_value, map_entry);
let new_text = doc.to_string();
// Validate the resulting stack before touching the disk.
@@ -792,6 +819,52 @@ mod tests {
);
}
#[test]
fn map_entry_named_by_a_path_is_written_under_its_table() {
let tmp = tempfile::tempdir().unwrap();
let cfg = tmp.path().join("cfg");
let proj = tmp.path().join("proj");
let file = proj.join(".openidea/settings.toml");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, "[editor]\ntabSize = 8 # wide\n").unwrap();
let store = SettingsStore::load(&cfg, Some(&proj));
let key = "editor.encodings.mappings";
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
assert_eq!(s.editor.encodings.mappings.get("src/a.b/A.java").map(String::as_str), Some("iso-8859-15"));
assert_eq!(s.editor.tab_size, 8);
let written =
"[editor]\ntabSize = 8 # wide\n\n[editor.encodings.mappings]\n\"src/a.b/A.java\" = \"iso-8859-15\"\n";
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
// Setting it again changes nothing; another entry joins the table; `null` removes one.
store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
store.set_map_entry(SettingsScope::Project, key, "web", json!("gbk")).unwrap();
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", Json::Null).unwrap();
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("web".into(), "gbk".into())]);
for (map, entry) in [("editor.encodings.nope", "a"), (key, "")] {
let err = store.set_map_entry(SettingsScope::Project, map, entry, json!("gbk")).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
}
}
#[test]
fn an_encoding_mapping_that_is_not_a_label_does_not_drop_the_project_settings() {
let tmp = tempfile::tempdir().unwrap();
let proj = tmp.path().join("proj");
std::fs::create_dir_all(proj.join(".openidea")).unwrap();
std::fs::write(
proj.join(".openidea/settings.toml"),
"[editor]\ntabSize = 8\n[editor.encodings.mappings]\nsrc = \"gbk\"\ncount = 5\n",
)
.unwrap();
let s = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective();
assert_eq!(s.editor.tab_size, 8);
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("src".into(), "gbk".into())]);
}
#[test]
fn set_console_log_colors() {
let tmp = tempfile::tempdir().unwrap();
+295
Переглянути файл
@@ -1567,3 +1567,298 @@ fn undo_back_to_the_disk_text_reloads_on_checkout() {
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(id).unwrap().text, "checked out\n");
}
fn project_encoding(f: &Fixture, label: &str) {
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = label.into();
f.docs.set_file_defaults(defaults);
}
fn latin9_editorconfig(f: &Fixture) {
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
}
#[test]
fn editorconfig_charset_applies_to_an_existing_ascii_file_over_the_project_encoding() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "iso-8859-15");
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
}
#[test]
fn editorconfig_charset_decodes_a_legacy_file_over_the_project_encoding() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
let bytes = b"// a\xe7\xe3o \xa4\n";
fs::write(&path, bytes).unwrap();
assert_eq!(f.docs.detect_encoding(&path, bytes), encoding_rs::ISO_8859_15);
for loaded in [f.docs.load_file(&path).unwrap(), f.docs.load_file_bounded(&path, 1024).unwrap()] {
assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
#[test]
fn editorconfig_charset_survives_a_reload_from_disk() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "iso-8859-15"));
}
#[test]
fn editorconfig_without_a_usable_charset_leaves_the_encoding_alone() {
let open = |project: Option<&str>, editorconfig: &str, enabled: bool| {
let f = fixture();
let mut defaults = f.docs.file_defaults();
if let Some(project) = project {
defaults.project_fallback = project.into();
}
defaults.editorconfig = enabled;
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), format!("root = true\n[*.java]\n{editorconfig}\n")).unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
f.docs.open(&path).unwrap().encoding
};
assert_eq!(open(None, "indent_size = 2", true), "utf-8", "nothing configured");
assert_eq!(open(None, "charset = ebcdic", true), "utf-8", "unknown charset");
assert_eq!(open(Some("iso-8859-15"), "indent_size = 2", true), "iso-8859-15", "no charset: the project's");
assert_eq!(open(Some("iso-8859-15"), "charset = ebcdic", true), "iso-8859-15", "unknown charset: the project's");
assert_eq!(open(Some("iso-8859-15"), "charset = gbk", false), "iso-8859-15", "EditorConfig support is off");
assert_eq!(open(Some("iso-8859-15"), "charset = utf-16le", true), "iso-8859-15", "UTF-16 is detected, not assumed");
}
#[test]
fn utf16_text_without_a_bom_keeps_utf16_under_a_utf8_charset() {
let f = fixture();
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, ide_vfs::encode("class A {}\n", "utf-16le", false).unwrap()).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("class A {}\n", "utf-16le"));
}
#[test]
fn valid_utf8_text_keeps_utf8_under_a_legacy_charset() {
let f = fixture();
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
}
#[test]
fn editorconfig_utf8_charset_survives_a_reload_from_disk() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "utf-8"));
}
#[test]
fn editorconfig_charset_wins_over_the_properties_encoding() {
let f = fixture();
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = iso-8859-15\n").unwrap();
let path = f.root.join("messages.properties");
fs::write(&path, b"price=10 \xa4\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("price=10 €\n", "iso-8859-15"));
assert_eq!(f.docs.detect_encoding(&path, b"price=10\n"), encoding_rs::ISO_8859_15);
assert_eq!(f.docs.detect_encoding(&f.root.join("unmatched.txt"), b"price=10\n"), encoding_rs::UTF_8);
}
#[test]
fn switching_editorconfig_support_off_stops_the_charset_on_reload() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.editorconfig = false;
f.docs.set_file_defaults(defaults);
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
assert_eq!(f.docs.snapshot(doc.id).unwrap().encoding, "gbk");
}
#[test]
fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
let mut defaults = f.docs.file_defaults();
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
f.docs.set_file_defaults(defaults);
}
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
}
#[test]
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
let f = fixture();
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
let chosen = f.docs.snapshot(doc.id).unwrap();
assert_eq!(chosen.text, "// ação\n");
f.docs.close(doc.id);
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
let reopened = f.docs.open(&path).unwrap();
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
// A later change on disk is read in the remembered encoding too.
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(reopened.id).unwrap();
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
}
#[test]
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
}
#[test]
fn encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
}
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
let file = open("src/A.java");
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
assert_eq!(open("other.txt").encoding, "gbk");
let latin = open("src/latin.txt");
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
}
#[test]
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
let path = in_root(&f, "src/B.java");
fs::write(&path, b"// \xd6\xd0\n").unwrap();
let unmapped = f.docs.open(&path).unwrap();
f.docs.close(unmapped.id);
encoding_mappings(&f, &[("src", "koi8-r")]);
let mapped = f.docs.open(&path).unwrap();
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
}
#[test]
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
}
#[test]
fn without_encoding_mappings_files_open_as_before() {
let f = fixture();
let settings = ide_core::settings::Settings::default();
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
assert!(f.docs.file_defaults().mappings.is_empty());
for (name, bytes) in [
("ascii.java", &b"class A {}\n"[..]),
("utf8.java", "// ação\n".as_bytes()),
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
("empty.java", &b""[..]),
] {
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let detected = ide_vfs::load_text(&path).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
}
}
+15
Переглянути файл
@@ -241,6 +241,21 @@ fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abcé", "windows-1252"));
}
#[test]
fn undo_keeps_the_editorconfig_charset_of_a_file_opened_after_the_edit() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join(".editorconfig"), "root = true\n[*.txt]\ncharset = iso-8859-15\n").unwrap();
let path = tmp.path().join("legacy.txt");
std::fs::write(&path, b"abc\xA4").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
let info = docs.open(&path).unwrap();
assert_eq!((info.text.as_str(), info.encoding.as_str()), ("new€", "iso-8859-15"));
docs.undo_workspace_edit(undo_id(&events)).unwrap();
let snapshot = docs.snapshot(info.id).unwrap();
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abc€", "iso-8859-15"));
}
#[test]
fn stale_document_version_rejects_the_whole_edit() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -132,7 +132,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone.
For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). **New Tasks** model options are loaded for the authenticated account after sign-in or **Apply**.
For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). **New Tasks** model options load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions.
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
+2 -2
Переглянути файл
@@ -61,7 +61,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations, and a JavaScript or TypeScript component and the files beside it with the same name (an Angular component's template, styles and spec, or its `templateUrl` / `styleUrls`; `Button.tsx` and `Button.module.css`, `Button.test.tsx`, `Button.stories.tsx`). With several targets it shows a chooser.
- In Rails, **Go to Declaration** also follows method symbols in callbacks (`before_action :load_user`, `if: :admin?`) to their `def`, and controller actions in `config/routes.rb` (`to: "users#index"`, `resources :users`) to the controller.
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
@@ -75,7 +75,7 @@ Going to files, classes and symbols by name is covered in [Search and navigation
| **Highlight Usages in File** | `⇧⌘F7` | `Ctrl+Shift+F7` |
| **Next Highlighted Usage** / **Previous** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. The occurrences of the symbol under the caret are highlighted in the editor as you move.
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. **Export to Text File** in the tool window's toolbar saves the results as shown (with the access filter applied, without excluded usages) to a text file. The occurrences of the symbol under the caret are highlighted in the editor as you move.
Above declarations, a **N usages** hint and the last author of the code (from Git blame) are shown, with the date of that last change. Turn them off under **Code Vision** in **Settings › Editor › Inlay Hints**.
+10 -5
Переглянути файл
@@ -25,6 +25,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
- Drag with `⌥` / `Alt` held (or with the middle mouse button on macOS and Windows) to make a rectangular selection without switching modes.
- **Extend Selection** grows the selection to the enclosing word, expression, statement and block, using the syntax tree.
- **Swap Selection Boundaries** moves the caret of each selection to its other end and keeps the text selected, so `⇧` / `Shift` with the arrow keys then extends or shrink it from that side. It has no default shortcut.
- **Toggle Sticky Selection** starts a selection at each caret: arrow keys and other caret moves then extend it as if `⇧` / `Shift` were held. Run it again or press `Esc` to turn it off, which also removes the selection. Copying or editing the text turns it off too. It has no default shortcut.
- **Select Line at Caret** selects the whole line at each caret together with its line break; a selection grows to the whole lines it touches. It has no default shortcut.
## Editing lines and code
@@ -57,10 +58,12 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut.
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones. **Delete Duplicate Lines** works on the same lines and keeps only the first of each repeated line (the text must match exactly, whitespace included); run it from **Find Action** or assign a shortcut in **Settings › Keymap**.
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
**Kill to Word Start** and **Kill to Word End** cut from each caret back to the start of the previous word or on to the end of the next one, together with the whitespace and line breaks in between; with **Settings › Editor › General › Smart Keys › Use "CamelHumps" words** on they stop at humps (`parse|HTML|Document`). A selection is ignored. Repeated cuts at the same caret, and Cut up to Line End there, collect into one clipboard entry, the ones to the word start in front. They have no default shortcut.
**Hungry Backspace** deletes all the spaces, tabs and line breaks before each caret in one go, up to the previous non-whitespace character; after anything else, or with a selection, it works like `⌫` / `Backspace`. It has no default shortcut.
**Duplicate Entire Lines** copies every line touched by a caret or selection below itself, even when only part of a line is selected, and keeps the selection on the copy. It has no default shortcut; run it from **Find Action** or assign one in **Settings › Keymap**.
@@ -149,11 +152,13 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
| Action | macOS | Windows / Linux |
| ------------------------------------- | ----- | --------------- |
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
| **Increase Font Size in All Editors** | `⌃⇧.` | `Alt+Shift+.` |
| **Decrease Font Size in All Editors** | `⌃⇧,` | `Alt+Shift+,` |
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
| **Scroll Up** | — | `Ctrl+Up` |
| **Scroll Down** | — | `Ctrl+Down` |
| **Scroll Left** | — | — |
| **Scroll Right** | — | — |
| **Scroll Up and Move if Necessary** | — | — |
| **Scroll Down and Move if Necessary** | — | — |
| **Move Up and Scroll** | — | — |
@@ -161,10 +166,10 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
| **Scroll to Top** | — | — |
| **Scroll to Bottom** | — | — |
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight; **Scroll Left** and **Scroll Right** do the same sideways, by one column. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). **Increase Font Size in All Editors** and **Decrease Font Size in All Editors** resize every open editor together, starting from the active one, and have no default shortcut. Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
- **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave.
- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off.
- **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**.
+1
Переглянути файл
@@ -163,6 +163,7 @@ Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **R
- File paths and stack trace frames in the output are links. **Up the Stack Trace** / **Down the Stack Trace** in the toolbar (or **Previous / Next Occurrence**, `⌥⌘↑` / `⌥⌘↓`, `Ctrl+Alt+↑` / `Ctrl+Alt+↓` on Windows and Linux) select the previous / next one and open it; links in collapsed folds are skipped. In a test run these keys go through the failed tests instead.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
- **Search with Google** in the console's context menu searches the web for the selected output, such as an error message, in the browser.
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
+2
Переглянути файл
@@ -42,6 +42,8 @@ In HTML, Vue, Svelte, JSX and TSX files, and in CSS, SCSS, Less and Sass, `⇥`
Templates are edited in **Settings › Editor › Live Templates**.
To start from existing code, select it and choose **Tools › Save as Live Template…**: a template in the **User** group gets the selection as its text (with `$` written as `$$`) and the file's language as its context, and Settings opens on it.
<Steps>
<Step title="Add a template">
Click **Add Template** and enter the **Abbreviation**, **Description** and **Group**.
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ Showing an empty Terminal window opens a tab in the start directory (the project
- **+** (**New Tab**) opens a tab with the default shell.
- The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**.
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close All Tabs**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A terminal moved to the editor can return via **Move to Terminal** or by dragging its editor tab onto a Terminal tab strip, pane edge, or the **Terminal** stripe button.
A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends.
+1 -1
Переглянути файл
@@ -64,7 +64,7 @@ To create a theme or icon theme, see [Themes](/en/plugins/guides/themes) and [Ic
- **Enable ligatures** for fonts with programming ligatures.
- **Typography Settings**: **Main font weight**, **Bold font weight**, and a **Fallback font** for characters the main font lacks.
To change the size temporarily in the active editor, use **Increase Font Size** (`⌥⇧.` / `Alt+Shift+.`) and **Decrease Font Size** (`⌥⇧,` / `Alt+Shift+,`); **View › Reset Font Size** (or **View › Reset Font Size in All Editors**) goes back. In **Settings › Editor › General**, **Change font size with Ctrl/Command+Mouse Wheel** enables wheel zoom for the **Active editor** (default) or **All editors**.
To change the size temporarily, use **Increase Font Size in All Editors** (`⌃⇧.` / `Alt+Shift+.`) and **Decrease Font Size in All Editors** (`⌃⇧,` / `Alt+Shift+,`), or **Increase Font Size** / **Decrease Font Size** from Find Action for the active editor only; **View › Reset Font Size** (or **View › Reset Font Size in All Editors**) goes back. In **Settings › Editor › General**, **Change font size with Ctrl/Command+Mouse Wheel** enables wheel zoom for the **Active editor** (default) or **All editors**.
### UI font and zoom
+1 -1
Переглянути файл
@@ -138,7 +138,7 @@ The toolbar switches between **Side-by-side Viewer** and **Unified Viewer**, and
Other ways to compare:
- **Compare with Branch or Revision…** and **Compare with Revision…** for the current file, or for folders (a list of changed files).
- **Compare With…** (`⌘D` / `Ctrl+D` in the Project view), **Compare Files**, **Compare Directories** (with copy left/right) and **View › Compare with Clipboard**.
- **Compare With…** (`⌘D` / `Ctrl+D` in the Project view), **Compare Files**, **Compare File with Editor** (the selected file against the active editor's, at its caret), **Compare Directories** (with copy left/right) and **View › Compare with Clipboard**.
## Branches
+3 -2
Переглянути файл
@@ -59,7 +59,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
| Method | Used for |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| npm | Node-based servers such as vtsls, Pyright, Intelephense, the Vue, Svelte, Astro, Angular, CSS, HTML, JSON, YAML, Bash and Dockerfile servers. Needs Node.js. |
| npm | Node-based servers such as vtsls, Pyright, Intelephense, the Vue, Svelte, Astro, MDX, Angular, CSS, Sass, HTML, JSON, YAML, Bash and Dockerfile servers. Needs Node.js. |
| pip into a private virtualenv | basedpyright, ty, pyrefly, Ruff (uses `uv` when available). |
| pip into a private folder | debugpy. |
| `go install` | gopls, Delve, sqls. Needs Go. |
@@ -143,6 +143,7 @@ The table lists every built-in language definition. Server and debugger names in
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
| MDX | `mdx` | `.mdx` | Yes | Yes | **mdx-language-server** | — |
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
@@ -160,7 +161,7 @@ The table lists every built-in language definition. Server and debugger names in
| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | Yes | — | — | — |
| Sass | `sass` | `.sass` | Yes | — | **some-sass-language-server** | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — |
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** + **stylelint** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** |
+2
Переглянути файл
@@ -89,6 +89,8 @@ With **Automatic**, a JavaScript or TypeScript file below the tool's own configu
**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written.
The **Imports** tab sets how the TypeScript server writes the imports it adds (auto-import, quick fixes, moving files): **Import paths** (shortest, relative, non-relative through `paths` / `baseUrl`, or relative within the project), **Import path ending** (automatic, `./components`, `./components/index` or `./components/index.js`), **Do not auto-import from** (globs such as `**/index.ts` to keep barrel files out) and **Do not auto-import specifiers matching** (regular expressions for the import path, such as `^node:`). Like the other tabs, they are saved per project, separately for JavaScript and TypeScript, and apply to a running server without a restart.
### Biome lint
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
+10
Переглянути файл
@@ -140,6 +140,16 @@ Settings › Appearance & Behavior › Appearance, unless noted.
Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completion]`, `[editor.tabs]`, `[editor.codeStyle]` and `[editor.encodings]` hold the options of the matching Editor pages.
`[editor.encodings.mappings]` in a project's `.openidea/settings.toml` gives a file or a folder its own encoding. Keys are paths relative to the project, with `/` separators. Choosing an encoding in the status bar adds the file here; after **Convert**, once the file is saved.
```toml
[editor.encodings.mappings]
"src/main/java" = "iso-8859-15" # every file in the folder
"web/legacy/index.jsp" = "windows-1252"
```
A file's own entry wins over `.editorconfig`. A folder's entry applies where `.editorconfig` sets no `charset`, and wins over the project encoding; the nearest folder wins. An entry with an unknown encoding or a path outside the project is ignored.
### `[files]`
| Key | Default | Description |
+16 -16
Переглянути файл
@@ -188,19 +188,19 @@ Some shortcuts depend on where the focus is. For example `⌘N` / `Alt+Insert` i
## Files, tabs and view
| Action | macOS | Windows / Linux |
| -------------------- | ------------ | ----------------------- |
| Settings… | `⌘,` | `Ctrl+Alt+S` |
| Project Structure… | `⌘;` | `Ctrl+Alt+Shift+S` |
| Save All | `⌘S` | `Ctrl+S` |
| New Scratch File… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
| Close Tab | `⌘W` | `Ctrl+F4` |
| Select Next Tab | `⌃→` / `⇧⌘]` | `Alt+Right` |
| Select Previous Tab | `⌃←` / `⇧⌘[` | `Alt+Left` |
| Quick Switch Scheme… | `` ⌃` `` | `` Ctrl+` `` |
| Zoom In IDE | `⌃⌥=` | `Alt+Shift+=` |
| Zoom Out IDE | `⌃⌥-` | `Alt+Shift+-` |
| Reset IDE Zoom | `⌃⌥0` | `Alt+Shift+0` |
| Increase Font Size | `⌥⇧.` | `Alt+Shift+.` |
| Decrease Font Size | `⌥⇧,` | `Alt+Shift+,` |
| Toggle Full Screen | `⌃⌘F` | — |
| Action | macOS | Windows / Linux |
| --------------------------------- | ------------ | ----------------------- |
| Settings… | `⌘,` | `Ctrl+Alt+S` |
| Project Structure… | `⌘;` | `Ctrl+Alt+Shift+S` |
| Save All | `⌘S` | `Ctrl+S` |
| New Scratch File… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
| Close Tab | `⌘W` | `Ctrl+F4` |
| Select Next Tab | `⌃→` / `⇧⌘]` | `Alt+Right` |
| Select Previous Tab | `⌃←` / `⇧⌘[` | `Alt+Left` |
| Quick Switch Scheme… | `` ⌃` `` | `` Ctrl+` `` |
| Zoom In IDE | `⌃⌥=` | `Alt+Shift+=` |
| Zoom Out IDE | `⌃⌥-` | `Alt+Shift+-` |
| Reset IDE Zoom | `⌃⌥0` | `Alt+Shift+0` |
| Increase Font Size in All Editors | `⌃⇧.` | `Alt+Shift+.` |
| Decrease Font Size in All Editors | `⌃⇧,` | `Alt+Shift+,` |
| Toggle Full Screen | `⌃⌘F` | — |
+1 -1
Переглянути файл
@@ -132,7 +132,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。选择已验证的账号后,**新任务**会自动加载该账号对应的可用模型列表,点击**应用**或**确定**保存以供新会话使用。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
+2 -2
Переглянути файл
@@ -61,7 +61,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移。有多个目标时显示选择列表。
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移,以及 JavaScript / TypeScript 组件与同一文件夹中同名的文件(Angular 组件的模板、样式和 spec,或其 `templateUrl` / `styleUrls`;`Button.tsx` 与 `Button.module.css`、`Button.test.tsx`、`Button.stories.tsx`)。有多个目标时显示选择列表。
- 在 Rails 中,**转到声明** 还能从回调里的方法符号(`before_action :load_user`、`if: :admin?`)跳到对应的 `def`,从 `config/routes.rb` 里的控制器动作(`to: "users#index"`、`resources :users`)跳到控制器。
按名称跳转到文件、类和符号,见 [搜索与导航](/zh/guide/search)。
@@ -75,7 +75,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
| **高亮文件中的用法** | `⇧⌘F7` | `Ctrl+Shift+F7` |
| **下一个高亮的用法** / **上一个** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。工具窗口工具栏中的 **导出到文本文件** 把当前显示的结果(应用访问过滤,不含已排除的用法)保存为文本文件。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
声明上方会显示用法数量(如 `3 usages`)和这段代码最后的作者(来自 Git blame),并标注最近一次修改的日期。可以在 **设置 › 编辑器 › 嵌入提示** 的 **Code Vision** 一节中关闭。
+10 -5
Переглянути файл
@@ -25,6 +25,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
- 按住 `⌥` / `Alt` 拖动鼠标(macOS 和 Windows 上也可以用鼠标中键拖动)可以直接做矩形选区,不用切换模式。
- **扩展选区** 依据语法树逐级扩大到所在的单词、表达式、语句和代码块。
- **交换选区边界** 把每个选区的光标移到选区的另一端并保持选中,之后用 `⇧` / `Shift`+方向键即可从这一端扩大或缩小选区。它默认没有快捷键。
- **切换粘滞选区** 从每个光标处开始一个选区:之后方向键等光标移动会像按住 `⇧` / `Shift` 一样扩大选区。再执行一次或按 `Esc` 即可关闭,同时取消选区。复制或编辑文本也会关闭它。它默认没有快捷键。
- **选择光标所在行** 选中每个光标所在的整行及其换行符;有选区时扩大到选区涉及的所有整行。它默认没有快捷键。
## 编辑行与代码
@@ -59,9 +60,11 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
**剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。
**剪切到词首** 和 **剪切到词尾** 从每个光标向前剪切到上一个单词的开头,或向后剪切到下一个单词的结尾,连同其间的空白和换行符;开启 **设置 › 编辑器 › 常规 › 智能键 › 使用“驼峰”单词** 时按驼峰片段(`parse|HTML|Document`)停下。选区会被忽略。在同一光标处连续剪切(包括剪切到行尾)会合并为剪贴板中的一条内容,剪切到词首的部分排在前面。它们默认没有快捷键。
**贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。**删除重复行** 作用于同样的行,每组重复行只保留第一行(文本须完全相同,包括空白);可在查找操作中运行,或在 **设置 › 按键映射** 中分配快捷键。
**复制整行** 把光标或选区涉及的每一行完整复制到其下方(即使只选中了行的一部分),并让选区落在副本上。它默认没有快捷键,可在查找操作中运行,或在 **设置 › 按键映射** 中分配快捷键。
@@ -147,11 +150,13 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| 操作 | macOS | Windows / Linux |
| ------------------------------ | ----- | --------------- |
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
| **增大所有编辑器中的字体** | `⌃⇧.` | `Alt+Shift+.` |
| **减小所有编辑器中的字体** | `⌃⇧,` | `Alt+Shift+,` |
| **滚动到中央** | `⌃L` | `Ctrl+M` |
| **向上滚动** | — | `Ctrl+Up` |
| **向下滚动** | — | `Ctrl+Down` |
| **向左滚动** | — | — |
| **向右滚动** | — | — |
| **向上滚动并在必要时移动光标** | — | — |
| **向下滚动并在必要时移动光标** | — | — |
| **向上移动并滚动** | — | — |
@@ -159,10 +164,10 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域;**向左滚动** 和 **向右滚动** 以同样方式横向移动一列。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。**增大所有编辑器中的字体** 和 **减小所有编辑器中的字体** 以当前编辑器为起点同时调整所有打开的编辑器,默认没有快捷键。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
- **视图 › 外观 › 进入无干扰模式** 隐藏工具窗口、标签页、状态栏和装订区域,并让正文居中。再执行一次即可退出。
- **视图 › 外观 › 进入 Zen 模式** 同时开启无干扰模式和全屏;**退出 Zen 模式** 同时关闭两者。
- **显示行号**、**显示缩进参考线**、**显示粘滞行** 和 **显示空白** 在所有编辑器中打开或关闭对应显示。可从查找操作运行,或右键单击装订区域并打开 **外观**。
+1
Переглянути файл
@@ -159,6 +159,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
- 输出里的文件路径和堆栈帧都可以点击跳转。工具栏的 **沿堆栈跟踪向上** / **沿堆栈跟踪向下**(或 **上一个 / 下一个匹配项**,`⌥⌘↑` / `⌥⌘↓`,Windows 和 Linux 上为 `Ctrl+Alt+↑` / `Ctrl+Alt+↓`)选中上一个 / 下一个链接并打开它;折叠起来的行里的链接会跳过。测试运行时这两个快捷键改为在失败的测试之间跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 控制台右键菜单中的 **使用 Google 搜索** 会在浏览器中搜索选中的输出(例如一条错误信息)。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+2
Переглянути файл
@@ -42,6 +42,8 @@ items.for → for (var item : items) { … }
模板在 **设置 › 编辑器 › 实时模板** 中编辑。
要从已有代码开始,选中代码后选择 **工具 › 另存为实时模板…**:会在 **User** 组中新建一个模板,以选中内容为模板文本(`$` 写成 `$$`),以当前文件的语言为上下文,并在设置中打开它。
<Steps>
<Step title="添加模板">单击 **添加模板**,填写 **缩写**、**描述** 和 **组**。</Step>
<Step title="编写模板正文">
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
- **+**(**新建标签页**)用默认 Shell 打开一个标签页。
- **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭所有标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。移到编辑器的终端可通过 **移至终端**,或将编辑器标签拖回终端标签栏、面板边缘或 **终端** 边栏按钮来归位。
标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。
+1 -1
Переглянути файл
@@ -64,7 +64,7 @@ OpenIDEA 会把主题(以及其中附带的编辑器配色方案)转换为
- **启用连字**:用于带编程连字的字体。
- **排版设置**:**主字重**、**粗体字重**,以及主字体缺少字符时使用的 **备用字体**。
在当前编辑器中临时调整字号可以用 **增大字体**(`⌥⇧.` / `Alt+Shift+.`)和 **减小字体**(`⌥⇧,` / `Alt+Shift+,`),用 **视图 › 重置字体大小**(或 **视图 › 重置所有编辑器中的字体大小**)恢复。在 **设置 › 编辑器 › 常规** 中开启 **使用 Ctrl/Command+鼠标滚轮更改字体大小** 后可以用滚轮缩放,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
临时调整字号可以用 **增大所有编辑器中的字体**(`⌃⇧.` / `Alt+Shift+.`)和 **减小所有编辑器中的字体**(`⌃⇧,` / `Alt+Shift+,`),只调当前编辑器可在查找操作中运行 **增大字体** / **减小字体**;用 **视图 › 重置字体大小**(或 **视图 › 重置所有编辑器中的字体大小**)恢复。在 **设置 › 编辑器 › 常规** 中开启 **使用 Ctrl/Command+鼠标滚轮更改字体大小** 后可以用滚轮缩放,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
### 界面字体与缩放
+1 -1
Переглянути файл
@@ -136,7 +136,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
其他比较方式:
- 对当前文件或文件夹使用 **与分支或修订比较…** 和 **与修订版比较…**(文件夹会显示变更文件列表)。
- **比较对象…**(在项目视图中按 `⌘D` / `Ctrl+D`)、**比较文件**、**比较目录**(可向左/向右复制)和 **视图 › 与剪贴板比较**。
- **比较对象…**(在项目视图中按 `⌘D` / `Ctrl+D`)、**比较文件**、**将文件与编辑器比较**(所选文件与活动编辑器中的文件比较,定位到其光标所在行)、**比较目录**(可向左/向右复制)和 **视图 › 与剪贴板比较**。
## 分支
+3 -2
Переглянути файл
@@ -55,7 +55,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| 方式 | 适用于 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| npm | 基于 Node 的服务器,如 vtsls、Pyright、Intelephense,以及 Vue、Svelte、Astro、Angular、CSS、HTML、JSON、YAML、Bash、Dockerfile 的服务器。需要 Node.js。 |
| npm | 基于 Node 的服务器,如 vtsls、Pyright、Intelephense,以及 Vue、Svelte、Astro、MDX、Angular、CSS、Sass、HTML、JSON、YAML、Bash、Dockerfile 的服务器。需要 Node.js。 |
| pip 安装到私有虚拟环境 | basedpyright、ty、pyrefly、Ruff(有 `uv` 时用 `uv`)。 |
| pip 安装到私有目录 | debugpy。 |
| `go install` | gopls、Delve、sqls。需要 Go。 |
@@ -138,6 +138,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — |
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — |
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
| MDX | `mdx` | `.mdx` | 是 | 是 | **mdx-language-server** | — |
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
@@ -155,7 +156,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — |
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg |
| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** |
| Sass | `sass` | `.sass` | 是 | — | — | — |
| Sass | `sass` | `.sass` | 是 | — | **some-sass-language-server** | — |
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — |
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** + **stylelint** | — |
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** |
+2
Переглянути файл
@@ -90,6 +90,8 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
**设置 › 编辑器 › 代码样式 › JavaScript** 和 **TypeScript** 有 **空格**(逗号后、运算符两侧、花括号内等)和 **标点**(分号:保持原样、使用或不使用;引号:与文件一致、单引号或双引号)两个标签页。它们和其他代码样式设置一起按项目保存,并发送给 TypeScript 服务器:服务器将其用于 **重新格式化代码**,以及它添加的代码,包括快速修复、自动导入、重构和 **优化导入**。JSX 文件跟随 JavaScript,TSX 文件跟随 TypeScript。启用 EditorConfig 支持时,项目 `.editorconfig` 中设置的 `quote_type` 或 IntelliJ 属性 `ij_typescript_use_semicolon_after_statement`、`ij_typescript_use_double_quotes`、`ij_typescript_space_after_comma`、`ij_typescript_spaces_within_object_literal_braces` 等(JavaScript 用 `ij_javascript_*`)优先。tsserver 没有尾随逗号选项,尾随逗号保持原样。
**导入** 标签页决定 TypeScript 服务器添加导入(自动导入、快速修复、移动文件)时的写法:**导入路径**(最短、相对路径、通过 `paths` / `baseUrl` 的非相对路径,或项目内使用相对路径)、**导入路径结尾**(自动、`./components`、`./components/index` 或 `./components/index.js`)、**不从以下位置自动导入**(glob,例如用 `**/index.ts` 排除 barrel 文件)和 **不自动导入匹配以下表达式的路径**(匹配导入路径的正则表达式,例如 `^node:`)。和其他标签页一样,它们按项目保存,JavaScript 和 TypeScript 分开设置,修改后无需重启服务器即可生效。
### Biome 检查
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
+10
Переглянути файл
@@ -140,6 +140,16 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
`[editor.general]`、`[editor.appearance]`、`[editor.completion]`、`[editor.tabs]`、`[editor.codeStyle]`、`[editor.encodings]` 等子表保存对应编辑器页面的选项。
项目 `.openidea/settings.toml` 中的 `[editor.encodings.mappings]` 为单个文件或文件夹指定编码。键是相对于项目的路径,使用 `/` 分隔。在状态栏中选择编码时,该文件会被添加到这里;使用 **Convert** 时,在保存文件之后添加。
```toml
[editor.encodings.mappings]
"src/main/java" = "iso-8859-15" # 文件夹中的所有文件
"web/legacy/index.jsp" = "windows-1252"
```
文件自身的条目优先于 `.editorconfig`。文件夹的条目在 `.editorconfig` 未设置 `charset` 时生效,并优先于项目编码;最近的文件夹优先。编码未知或路径在项目之外的条目会被忽略。
### `[files]`
| 键 | 默认值 | 说明 |
+16 -16
Переглянути файл
@@ -188,19 +188,19 @@ macOS 符号:`⌘` Command、`⌥` Option、`⌃` Control、`⇧` Shift、`↵
## 文件、标签页与视图
| 操作 | macOS | Windows / Linux |
| ---------------- | ------------ | ----------------------- |
| 设置… | `⌘,` | `Ctrl+Alt+S` |
| 项目结构… | `⌘;` | `Ctrl+Alt+Shift+S` |
| 全部保存 | `⌘S` | `Ctrl+S` |
| 新建临时文件… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
| 关闭标签页 | `⌘W` | `Ctrl+F4` |
| 选择下一个标签页 | `⌃→` / `⇧⌘]` | `Alt+Right` |
| 选择上一个标签页 | `⌃←` / `⇧⌘[` | `Alt+Left` |
| 快速切换方案… | `` ⌃` `` | `` Ctrl+` `` |
| 放大 IDE | `⌃⌥=` | `Alt+Shift+=` |
| 缩小 IDE | `⌃⌥-` | `Alt+Shift+-` |
| 重置 IDE 缩放 | `⌃⌥0` | `Alt+Shift+0` |
| 增大字体 | `⌥⇧.` | `Alt+Shift+.` |
| 减小字体 | `⌥⇧,` | `Alt+Shift+,` |
| 切换全屏 | `⌃⌘F` | — |
| 操作 | macOS | Windows / Linux |
| ---------------------- | ------------ | ----------------------- |
| 设置… | `⌘,` | `Ctrl+Alt+S` |
| 项目结构… | `⌘;` | `Ctrl+Alt+Shift+S` |
| 全部保存 | `⌘S` | `Ctrl+S` |
| 新建临时文件… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
| 关闭标签页 | `⌘W` | `Ctrl+F4` |
| 选择下一个标签页 | `⌃→` / `⇧⌘]` | `Alt+Right` |
| 选择上一个标签页 | `⌃←` / `⇧⌘[` | `Alt+Left` |
| 快速切换方案… | `` ⌃` `` | `` Ctrl+` `` |
| 放大 IDE | `⌃⌥=` | `Alt+Shift+=` |
| 缩小 IDE | `⌃⌥-` | `Alt+Shift+-` |
| 重置 IDE 缩放 | `⌃⌥0` | `Alt+Shift+0` |
| 增大所有编辑器中的字体 | `⌃⇧.` | `Alt+Shift+.` |
| 减小所有编辑器中的字体 | `⌃⇧,` | `Alt+Shift+,` |
| 切换全屏 | `⌃⌘F` | — |
+13 -4
Переглянути файл
@@ -91,6 +91,15 @@ test("unifies Copilot sign-in, gates per-account models on auth, and supports in
retryAtMs: null,
error: null,
}),
agent_preview_copilot_models: ({ account }: { account: string }) => ({
provider: "copilot",
config: [account === "alice-work" ? workModel : personalModel],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
}),
agent_set_env: ({ env }: { env: Record<string, string> }) => {
savedAccount = env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? "";
return null;
@@ -142,14 +151,14 @@ test("unifies Copilot sign-in, gates per-account models on auth, and supports in
await expect(accountSelect).toContainText("Copilot CLI default (alice)");
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
// Add account runs gh auth login in-IDE, auto-selects alice-work, and gates models on Apply.
// Add account runs gh auth login in-IDE, auto-selects alice-work, and immediately previews its models before Apply.
await signIn.getByRole("button", { name: "Add account…" }).click();
await expect(page.getByRole("dialog", { name: "Sign In to GitHub CLI" })).toHaveCount(0);
await expect(accountSelect).toContainText("alice-work");
await expect(newTasks.getByText("Click Apply to load the models available for the selected account.")).toBeVisible();
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)");
expect(await ipcCalls(page, "agent_set_env")).toEqual([]);
// Applying loads the new account's subscription models.
// Applying saves the staged account selection.
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)");
expect(await ipcCalls(page, "agent_set_env")).toEqual([
+81
Переглянути файл
@@ -0,0 +1,81 @@
import type { Page } from "@playwright/test";
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, openFromTree, test } from "./fixtures";
const policyMessage = "This content was flagged for possible cybersecurity risk.";
const policyDetails = "Contact support if this is unexpected.";
const diagnostics = `${policyMessage}\n${policyDetails}\nCodex error: cyberPolicy`;
const now = Date.now();
const task: AgentTask = {
id: "sample-policy-failure",
title: "Investigate sample editor crash",
provider: "codex",
model: null,
status: "failed",
isolation: "local",
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: diagnostics,
createdMs: now - 2000,
updatedMs: now,
config: [],
commands: [],
usage: null,
queue: [],
};
const entries: AgentEntry[] = [
{
type: "user",
text: "Investigate and fix the sample editor shutdown crash.",
attachments: [],
sentMs: now - 2000,
doneMs: now - 1000,
},
{ type: "agent", text: "I will check the shutdown sequence and run the regression tests." },
{ type: "error", message: diagnostics },
];
async function showFailure(page: Page) {
await page.evaluate(
async ({ task, entries }) => {
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
commands.agentEntries = async () => ({ status: "ok", data: entries });
commands.agentChanges = async () => ({ status: "ok", data: [] });
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, task]]),
entries: new Map(),
unread: new Set(),
});
await store.openTaskInEditorLocation(task.id);
},
{ task, entries },
);
}
for (const width of [1400, 700]) {
test(`preserves saved Codex error details and code at width ${width}`, async ({ workbench: page }) => {
await page.setViewportSize({ width, height: 900 });
await showFailure(page);
const error = page.getByRole("alert").filter({ hasText: policyMessage });
await expect(error).toBeVisible();
await expect(error).toContainText(policyDetails);
await expect(error).toContainText("Codex error: cyberPolicy");
await expect(error).toHaveCSS("white-space", "pre-wrap");
await expect(page.getByText("The agent declined to continue.", { exact: true })).toHaveCount(0);
await expect(error.getByRole("button", { name: "Sign In…" })).toHaveCount(0);
expect(await error.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
// A different editor must not replace the saved failure with a generic task status.
await openFromTree(page, "README.md");
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("tree", { name: "Agent tasks", exact: true }).getByText(task.title, { exact: true }).click();
await expect(error).toContainText(diagnostics);
});
}
+2 -27
Переглянути файл
@@ -3,7 +3,7 @@
* menu, the modal Commit dialog and the non-modal Commit window defaults. Git is stubbed at the IPC layer.
*/
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, openFromTree, stubDesktop, stubSettingsWrites, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const FILE = "build.gradle.kts";
@@ -43,33 +43,8 @@ async function stubRepository(page: Page) {
}
/**
* Settings writes land in the project store the way the backend answers `settings_set`: the dotted
* key is set, `null` removes it, and the store takes the returned settings.
* Sets a commit setting in the store directly, before the window that reads it opens.
*/
async function stubSettingsWrites(page: Page) {
await page.evaluate(async () => {
const storeModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ storeModule);
window.__ipc.handlers.settings_set = (args) => {
const { key, value } = args as { key: string; value: string };
const next = structuredClone(useProject.getState().settings ?? {}) as Record<string, unknown>;
const path = key.split(".");
let node = next;
for (const seg of path.slice(0, -1)) {
node[seg] ??= {};
node = node[seg] as Record<string, unknown>;
}
const last = path[path.length - 1]!;
const parsed: unknown = JSON.parse(value);
if (parsed === null) delete node[last];
else node[last] = parsed;
useProject.setState({ settings: next as never });
return next;
};
});
}
/** Sets a commit setting in the store directly, before the window that reads it opens. */
async function setCommitSetting(page: Page, key: "nonModal" | "doubleClickOpensDiff", value: boolean | null) {
await page.evaluate(
async ({ key, value }) => {
+111
Переглянути файл
@@ -149,3 +149,114 @@ test("dragging one changelist onto another moves all of its files (PyCharm style
)
.toEqual({ "build.gradle.kts": "dd", "settings.gradle.kts": "dd" });
});
/** A repository with two untracked files; staging flips both to `added`. */
async function stubUnversionedRepository(page: Page) {
await stubDesktop(page);
await page.evaluate(async (root) => {
const staged = new Set<string>();
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [
{
path: `${root}/build.gradle.kts`,
relPath: "build.gradle.kts",
staged: null,
unstaged: "modified",
renamedFrom: null,
},
...["notes.txt", "todo.txt"].map((rel) => ({
path: `${root}/${rel}`,
relPath: rel,
staged: staged.has(rel) ? "added" : null,
unstaged: staged.has(rel) ? null : "untracked",
renamedFrom: null,
})),
];
h.vcs_stage = (args: Record<string, unknown>) => {
const paths = (args.paths as string[] | undefined) ?? [];
for (const p of paths) staged.add(p.slice(root.length + 1));
return null;
};
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
}, ROOT);
}
async function changelistFiles(page: Page) {
return page.evaluate(async () => {
const listsPath = "/src/features/vcs/changelists.ts";
const { useChangelists } = await import(/* @vite-ignore */ listsPath);
return useChangelists.getState().state.files;
});
}
async function dragTree(page: Page, from: { x: number; y: number; width: number; height: number }, to: typeof from) {
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 });
await page.mouse.up();
}
test("dragging the Unversioned Files header onto a changelist adds all of them", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubUnversionedRepository(page);
await page.keyboard.press("Meta+k");
const changes = page.getByRole("region", { name: "Commit", exact: true }).getByRole("tree", { name: "Changes" });
const source = changes.getByRole("treeitem", { name: /Unversioned Files/ });
const target = changes.getByRole("treeitem", { name: /Changes/ }).first();
await expect(source).toBeVisible();
await dragTree(page, (await source.boundingBox())!, (await target.boundingBox())!);
// Every unversioned file is added to Git and joins the list.
await expect
.poll(() => ipcCalls(page, "vcs_stage").then((calls) => calls.flat()))
.toEqual([{ paths: [`${ROOT}/notes.txt`, `${ROOT}/todo.txt`] }]);
await expect.poll(() => changelistFiles(page)).toEqual({ "notes.txt": "default", "todo.txt": "default" });
await expect(changes.getByRole("treeitem", { name: /Unversioned Files/ })).toHaveCount(0);
});
test("dragging selected unversioned files onto a changelist adds exactly them", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubUnversionedRepository(page);
await page.keyboard.press("Meta+k");
const changes = page.getByRole("region", { name: "Commit", exact: true }).getByRole("tree", { name: "Changes" });
// Unversioned Files starts collapsed.
await changes
.getByRole("treeitem", { name: /Unversioned Files/ })
.locator("[data-tree-toggle]")
.click();
const notes = changes.getByText("notes.txt", { exact: true });
const todo = changes.getByText("todo.txt", { exact: true });
const target = changes.getByRole("treeitem", { name: /Changes/ }).first();
await expect(notes).toBeVisible();
await expect(todo).toBeVisible();
const notesBox = (await notes.boundingBox())!;
// Select notes, then shift-click todo for a range selection (a press-drag
// between the two would start a file drag instead of selecting).
await page.mouse.click(notesBox.x + 10, notesBox.y + notesBox.height / 2);
await todo.click({ modifiers: ["Shift"] });
const selected = (await todo.boundingBox())!;
await dragTree(page, selected, (await target.boundingBox())!);
// Only the two selected files are added; the drag payload names both.
await expect
.poll(() => ipcCalls(page, "vcs_stage").then((calls) => calls.flat()))
.toEqual([{ paths: [`${ROOT}/notes.txt`, `${ROOT}/todo.txt`] }]);
await expect.poll(() => changelistFiles(page)).toEqual({ "notes.txt": "default", "todo.txt": "default" });
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Related Symbol lists an Angular component's template, styles and spec", async ({ workbench: page }, testInfo) => {
await stubDesktop(page);
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const files: Map<string, string> = (await import(backend)).docBackend().files;
const dir = "/dev/acme-api/src/app/user";
files.set(
`${dir}/user.component.ts`,
'@Component({\n selector: "app-user",\n templateUrl: "./user.component.html",\n styleUrl: "./user.component.scss",\n})\nexport class UserComponent {}\n',
);
files.set(`${dir}/user.component.html`, "<p>{{ name }}</p>\n");
files.set(`${dir}/user.component.scss`, "p { margin: 0; }\n");
files.set(`${dir}/user.component.spec.ts`, 'describe("UserComponent", () => {});\n');
window.__ipc.handlers.fs_read_dir = ({ path }) =>
[...files.keys()]
.filter((p) => p.startsWith(`${path}/`) && !p.slice(String(path).length + 1).includes("/"))
.map((p) => ({
path: p,
name: p.slice(String(path).length + 1),
kind: "file",
size: 0,
mtimeMs: 0,
ignored: false,
excluded: false,
hidden: false,
}));
const contributions = "/src/workbench/contributions.ts";
await (await import(contributions)).editorService().openFile(`${dir}/user.component.ts`);
});
await expect(page.locator(".cm-content").last()).toContainText("templateUrl");
const related = async () =>
page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(actions)).executeAction("navigate.relatedSymbol");
});
await related();
const chooser = page.getByRole("dialog", { name: "Choose Target" });
const options = chooser.getByRole("option");
await expect(options).toHaveCount(3);
await expect(options.nth(0)).toContainText("Template");
await expect(options.nth(1)).toContainText("Styles");
await expect(options.nth(2)).toContainText("Test");
await page.screenshot({ path: testInfo.outputPath("component-related.png"), animations: "disabled" });
await options.nth(2).click();
await expect(page.locator(".cm-content").last()).toContainText("describe");
await related();
await expect(options).toHaveCount(3);
await expect(options.nth(0)).toContainText("user.component.ts");
await expect(options.nth(0)).toContainText("Source File");
await page.screenshot({ path: testInfo.outputPath("spec-related.png"), animations: "disabled" });
});
+2 -1
Переглянути файл
@@ -23,7 +23,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
}
return groups;
});
expect(groups.slice(0, 4)).toEqual([
expect(groups.slice(0, 5)).toEqual([
[
"Close",
"Close Other Tabs",
@@ -32,6 +32,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
"Close Tabs to the Left",
"Close Tabs to the Right",
],
["File Color"],
["Copy Path/Reference…"],
["Split Right", "Split and Move Right", "Split Down", "Split and Move Down"],
["Pin Tab", "Open in New Window", "Configure Editor Tabs…"],
+27
Переглянути файл
@@ -118,6 +118,33 @@ export async function stubDesktop(page: Page) {
});
}
/**
* Makes `settings_set` answer like the backend: the dotted key lands in the project store (and
* `null` removes it), so toolbar toggles that write a setting behave as they do in the app.
*/
export async function stubSettingsWrites(page: Page) {
await page.evaluate(async () => {
const storeModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ storeModule);
window.__ipc.handlers.settings_set = (args) => {
const { key, value } = args as { key: string; value: string };
const next = structuredClone(useProject.getState().settings ?? {}) as Record<string, unknown>;
const path = key.split(".");
let node = next;
for (const seg of path.slice(0, -1)) {
node[seg] ??= {};
node = node[seg] as Record<string, unknown>;
}
const last = path[path.length - 1]!;
const parsed: unknown = JSON.parse(value);
if (parsed === null) delete node[last];
else node[last] = parsed;
useProject.setState({ settings: next as never });
return next;
};
});
}
/** The commands the page has invoked so far under `stubDesktop`, by name. */
export async function ipcCalls(page: Page, cmd: string): Promise<Record<string, unknown>[]> {
return page.evaluate((cmd) => window.__ipc.calls.filter((c) => c.cmd === cmd).map((c) => c.args), cmd);
+2 -1
Переглянути файл
@@ -65,7 +65,8 @@ test("Git Log commit choices fit their rows and navigate by keyboard after filte
await expect(filter).toBeFocused();
await expect(options).toHaveCount(2);
const before = (await chooser.boundingBox())!;
expect(before.height).toBeLessThan(200);
// Two rows under the title, and the Close button a macOS sheet without buttons gets.
expect(before.height).toBeLessThan(260);
const first = options.filter({ hasText: firstSubject });
const subject = first.getByText(firstSubject, { exact: true });
const author = first.getByText("Priya Kapoor", { exact: true });
+1 -1
Переглянути файл
@@ -56,7 +56,7 @@ test("an SVG file opens as its source with the image beside it", async ({ workbe
// Not an SVG yet: the preview says so, and draws the source once it is typed.
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
await page.locator(".cm-content").click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("Meta+A");
await page.keyboard.insertText(
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
);
+148
Переглянути файл
@@ -0,0 +1,148 @@
/**
* Renaming a branch follows in the Git Log: the Branch filter chip keeps naming
* the branch under its new name (and the remembered choice follows), instead of
* filtering an unknown revision. Git is stubbed at the IPC layer.
*/
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
interface StubBranch {
name: string;
current: boolean;
remote: boolean;
upstream: string | null;
ahead: number;
behind: number;
lastCommitMs: number | null;
commit: string;
}
/** Installs a two-branch repository (`sd` checked out) and opens the Git Log on `HEAD`. */
async function openLogOnSd(page: Page) {
await stubDesktop(page);
await page.evaluate(async (root) => {
const h = window.__ipc.handlers;
const commits = Array.from({ length: 6 }, (_, i) => ({
id: i.toString(16).padStart(40, "0"),
shortId: i.toString(16).padStart(8, "0"),
parents: i + 1 < 6 ? [(i + 1).toString(16).padStart(40, "0")] : [],
refs: i === 0 ? ["HEAD", "sd"] : [],
author: "Author",
email: "[email protected]",
timeMs: 20 - i,
summary: `Commit ${i}`,
message: `Commit ${i}`,
}));
let head = "sd";
let branches: StubBranch[] = [
{
name: "sd",
current: true,
remote: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 20,
commit: commits[0]!.id,
},
{
name: "main",
current: false,
remote: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 20,
commit: commits[5]!.id,
},
];
h.vcs_log = ({ query }) => {
const { skip, limit } = query as { skip: number; limit: number };
return commits.slice(skip, limit ? skip + limit : undefined);
};
h.vcs_log_refs = () => ({});
h.vcs_log_users = () => ["Author <[email protected]>"];
h.vcs_roots = () => [{ root, operation: null, head, headCommit: commits[0]!.id, hasRemotes: false }];
h.vcs_branch_info = () => ({
head,
headCommit: commits[0]!.id,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_branches = () => branches;
h.vcs_stashes = () => [];
h.vcs_tags = () => [];
h.vcs_config_get = () => null;
h.vcs_rename_branch = (args) => {
const { from, to } = args as { from: string; to: string };
if (!branches.some((b) => !b.remote && b.name === from))
throw { kind: "failed", message: "no such branch", detail: null };
head = to;
branches = branches.map((b) => (b.name === from ? { ...b, name: to } : b));
return null;
};
h.vcs_commit_files = () => [];
h.vcs_log_details_batch = ({ revisions }) =>
(revisions as string[]).map(() => ({
message: "",
containingBranches: [],
signature: "N",
signer: "",
key: "",
fingerprint: "",
}));
const storeModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: false, stashesLoaded: false });
await refreshNow();
await loadBranches();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showLog");
}, ROOT);
await expect(page.getByRole("listbox", { name: "Commits" }).getByRole("option").first()).toBeVisible();
}
test("the log branch filter follows a branch rename from the log's own toolbar", async ({ workbench: page }) => {
await openLogOnSd(page);
const toolbar = page.getByRole("toolbar", { name: "Log filters", exact: true });
// First open settles the filter on HEAD; the chip names it.
await expect(toolbar.getByRole("button", { name: "Branch: HEAD", exact: true })).toBeVisible();
// Choose the branch `sd` in the filter popup, as the user would.
await toolbar.getByRole("button", { name: "Branch: HEAD", exact: true }).click();
const popup = page.getByRole("dialog", { name: "Filter by Branch" });
await expect(popup).toBeVisible();
await popup.getByRole("option", { name: "Local", exact: true }).click();
await popup.getByRole("option", { name: "sd", exact: true }).click();
await expect(toolbar.getByRole("button", { name: "Branch: sd", exact: true })).toBeVisible();
// Rename the branch from its Branches pane context menu, as the user would.
await page.getByRole("tree", { name: "Branches" }).getByRole("treeitem", { name: "sd current" }).click({
button: "right",
});
await page.getByRole("menuitem", { name: "Rename…", exact: true }).click();
// The prompt dialog: type the new name and confirm.
const dialog = page.getByRole("dialog", { name: "Rename Branch sd" });
await expect(dialog).toBeVisible();
const field = dialog.getByRole("textbox");
await field.fill("feature");
await dialog.getByRole("button", { name: "Rename", exact: true }).click();
// No error balloon (the old filter would produce "unknown revision sd").
await expect(page.getByText(/unknown revision/)).toHaveCount(0);
await expect
.poll(() => ipcCalls(page, "vcs_rename_branch"))
.toMatchObject([{ repo: ROOT, from: "sd", to: "feature" }]);
// The chip follows the rename; the log reloads without an error row.
await expect(toolbar.getByRole("button", { name: "Branch: feature", exact: true })).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Branch: sd", exact: true })).toHaveCount(0);
await expect(page.getByText(/unknown revision/)).toHaveCount(0);
await expect(page.getByRole("listbox", { name: "Commits" }).getByRole("option").first()).toBeVisible();
});
+21 -8
Переглянути файл
@@ -103,16 +103,20 @@ test("merge controls and pane titles fit while resizing the result", async ({ pa
await expect.poll(() => text(result(page))).toContain("\nmine\n");
});
/** Capture the save boundary, keeping real editor state, dialogs and Apply behavior. */
/**
* Capture the Git boundary, keeping real editor state, dialogs and Apply behavior. Apply writes
* the file through its document, which the page keeps in memory.
*/
async function captureWrites(page: Page) {
await page.evaluate(async () => {
const ipcPath = "/src/platform/ipc.ts";
const backendPath = "/src/editor/core/backend.ts";
const { commands } = await import(ipcPath);
const { docBackend } = await import(backendPath);
docBackend().files.set("/project/demo.ts", "working copy\n");
const calls: { command: string; args: unknown[] }[] = [];
Object.assign(window, { mergeWrites: calls });
commands.fsReadText = async () => ({ status: "ok", data: "working copy\n" });
commands.docOpen = async () => ({ status: "ok", data: { id: 777, version: 1 } });
for (const command of ["docEdit", "docSave", "docClose", "vcsAcceptConflictSide", "vcsStage"])
for (const command of ["vcsAcceptConflictSide", "vcsStage"])
commands[command] = async (...args: unknown[]) => {
calls.push({ command, args });
return { status: "ok", data: null };
@@ -120,6 +124,14 @@ async function captureWrites(page: Page) {
});
}
/** The text Apply saved to the file. */
const saved = (page: Page) =>
page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const { docBackend } = await import(backendPath);
return docBackend().files.get("/project/demo.ts") as string;
});
const writes = (page: Page) =>
page.evaluate(
() =>
@@ -130,7 +142,7 @@ const writes = (page: Page) =>
).mergeWrites,
);
test("CRLF resolutions use UTF-16 editor positions and preserve line endings on Apply", async ({ page }) => {
test("Apply saves a CRLF resolution with UTF-16 text as resolved", async ({ page }) => {
const base = "标题😀\r\nunchanged\r\nbase\r\ntail";
const ours = base.replace("base", "左侧🚀");
await mountMerge(page, [base, ours, base.replace("base", "右侧🧪")]);
@@ -144,8 +156,9 @@ test("CRLF resolutions use UTF-16 editor positions and preserve line endings on
await page.locator("#merge-host").getByRole("button", { name: "Apply", exact: true }).click();
await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true);
const calls = await writes(page);
expect(calls.map((call) => call.command)).toEqual(["docEdit", "docSave", "docClose", "vcsStage"]);
expect(calls[0]!.args[2]).toEqual({ changes: [{ from: 0, to: 13, insert: ours }] });
expect(calls.map((call) => call.command)).toEqual(["vcsStage"]);
// Documents keep `\n`; saving writes the file's own line ending.
expect(await saved(page)).toBe(ours.replace(/\r\n/g, "\n"));
});
test("Apply writes and stages unresolved text only after confirmation", async ({ page }) => {
@@ -159,7 +172,7 @@ test("Apply writes and stages unresolved text only after confirmation", async ({
await apply.click();
await page.getByRole("button", { name: "Mark Resolved", exact: true }).click();
await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true);
expect((await writes(page))[0]!.args[2]).toEqual({ changes: [{ from: 0, to: 13, insert: BASE }] });
expect(await saved(page)).toBe(BASE);
});
test("footer buttons work when a click doesn't focus them, as in WebKit", async ({ page }) => {
+2 -1
Переглянути файл
@@ -4,7 +4,7 @@
*/
import type { Page } from "@playwright/test";
import type { RunConfig } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, ipcCalls, stubDesktop, stubSettingsWrites, test } from "./fixtures";
const RUN_ID = 7;
@@ -16,6 +16,7 @@ async function stubRun(
overrides: Partial<RunConfig> = {},
) {
await stubDesktop(page);
await stubSettingsWrites(page);
await page.evaluate(
async ({ output, exit, runId, overrides }) => {
const config = {
+1
Переглянути файл
@@ -20,6 +20,7 @@ something to show.
| `java-app/` | JDK 21, Maven 3.9 | `mvn compile exec:java` | `mvn test` | `mvn test -DopenideaFail=true` | unused variable in `App.java` |
| `c-app/` | gcc / g++ 12+, make, GDB 14+ | `make all` | — | — | — |
| `php-app/` | PHP 8.5, Composer | `composer quote` | `vendor/bin/pest` | `OPENIDEA_FAIL=1 vendor/bin/pest` | unused variable in `ThresholdCustoms.php` |
| `unittest-app/` | Python 3.10+ (standard library only) | — | `python -m unittest` | `OPENIDEA_FAIL=1 python -m unittest` | unused import in `inventory/stock.py` |
| `django-app/` | Python 3.10+, Django 5.2+ | `python manage.py runserver` | `python manage.py test` | `OPENIDEA_FAIL=1 python manage.py test` | unused import in `shop/views.py` |
| `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` |
| `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — |
+8
Переглянути файл
@@ -21,6 +21,14 @@ def test_complete_and_overdue():
assert tasks.overdue(date(2024, 1, 1)) == []
@pytest.mark.parametrize(
("title", "expected"),
[("write docs", "write docs"), (" padded ", "padded"), ("v1.2 notes", "v1.2 notes")],
)
def test_add_strips_titles(title, expected):
assert TaskList().add(title).title == expected
def test_rejects_empty_titles():
with pytest.raises(ValueError):
TaskList().add(" ")
+1
Переглянути файл
@@ -0,0 +1 @@
"""A tiny stock keeper: the OpenIDEA unittest fixture."""
+31
Переглянути файл
@@ -0,0 +1,31 @@
"""Items in stock and their quantities."""
import os # intentional warning: unused import
class OutOfStock(Exception):
"""Raised when taking more than is in stock."""
class Stock:
def __init__(self):
self._items: dict[str, int] = {}
def add(self, name: str, quantity: int = 1) -> None:
if quantity <= 0:
raise ValueError("quantity must be positive")
self._items[name] = self._items.get(name, 0) + quantity
def take(self, name: str, quantity: int = 1) -> int:
have = self._items.get(name, 0)
if quantity > have:
raise OutOfStock(f"{name}: {have} in stock, {quantity} asked")
self._items[name] = have - quantity
return self._items[name]
def count(self, name: str) -> int:
return self._items.get(name, 0)
# TODO: report the items running low
def total(self) -> int:
return sum(self._items.values())
+1
Переглянути файл
@@ -0,0 +1 @@
# Standard library only: the tests run with `python -m unittest`.
Переглянути файл
Whitespace-only changes.
+40
Переглянути файл
@@ -0,0 +1,40 @@
import os
import unittest
from inventory.stock import OutOfStock, Stock
class StockTests(unittest.TestCase):
def setUp(self):
self.stock = Stock()
self.stock.add("apple", 3)
def test_add(self):
self.stock.add("apple", 2)
self.assertEqual(self.stock.count("apple"), 5)
def test_take(self):
print("taking one apple")
self.assertEqual(self.stock.take("apple"), 2)
def test_take_too_many(self):
with self.assertRaises(OutOfStock):
self.stock.take("apple", 4)
def test_rejects_bad_quantities(self):
for quantity in (0, -1, -5):
with self.subTest(quantity=quantity):
with self.assertRaises(ValueError):
self.stock.add("pear", quantity)
@unittest.skip("FIXME: low-stock report not written yet")
def test_low_stock_report(self):
pass
@unittest.expectedFailure
def test_negative_total(self):
self.assertLess(self.stock.total(), 0)
@unittest.skipUnless(os.environ.get("OPENIDEA_FAIL"), "set OPENIDEA_FAIL=1 to run")
def test_failing(self):
self.assertEqual(self.stock.count("apple"), 4)
Loaded 100 of 318 files, more files were not shown because too many files have changed in this diff. Show more