Compare commits

..

39 Commits

Author SHA1 Message Date
Marshall Bowers
c822188a53 Replace license with symlink 2024-09-14 15:53:02 -04:00
Marshall Bowers
32fe23a182 Remove blank line 2024-09-14 15:52:22 -04:00
Marshall Bowers
b337f419d3 Merge branch 'main' into buffer-extensions 2024-09-14 15:51:33 -04:00
Marshall Bowers
4d8c3855c2 theme: Clamp font sizes between 6px and 100px (#17829)
This PR clamps the `ui_font_size` and `buffer_font_size` settings
between 6px and 100px.

Release Notes:

- Changed `ui_font_size` and `buffer_font_size` to require values to be
between 6px and 100px (inclusive).
2024-09-14 15:44:54 -04:00
Nate Butler
e8a2dd92c8 Derive icon paths (#17816)
This PR improves adding and working with icons by using the new
`DerivePathStr` to derive icon paths.

This means paths no longer need to be manually specified, and the
`IconName` and file name will always be consistent between icons.

This PR does not do any work to standardize icons visually, remove
unused icons, or any other such cleanup.

Release Notes:

- N/A
2024-09-13 21:12:29 -04:00
Nate Butler
ce848375fe add ui::Vector and separate images from icons (#17815)
This PR pulls non-icon assets out of `ui::components::icon` in
preparation for icon standardization.

In the future icons will have standard names and sizes, and these image
assets won't conform to those constraints.

We can also add a `ui::components::image::Image` wrapper around the
`gpui::img` element in the future for any Zed-specific image styling we
want to enforce.

Of note:

```rust
#[derive(Debug, PartialEq, Eq, Copy, Clone, EnumIter, EnumString, IntoStaticStr, Serialize, Deserialize, DerivePathStr)]
#[strum(serialize_all = "snake_case")]
#[path_str(prefix = "images", suffix = ".svg")]
pub enum VectorName {
    ZedLogo,
    ZedXCopilot,
}
```

You can see in the above code we no longer need to manually specify
paths for image/icon enums like we currently do in
`ui::components::icon`.

The icon component will get this same treatment in the future, once we:

- do the design work needed to standardize the icons
- remove unused icons
- update icon names

Release Notes:

- N/A
2024-09-13 17:44:16 -04:00
Nate Butler
fac9ee5f86 Add ui_macros crate & DerivePathStr derive macro (#17811)
This PR adds the `ui_macros` crate to allow building supporting macros
for the `ui` crate.

Additionally, it implements the `DerivePathStr` derive macro and the
`path_str` attribute macro. These macros work together to generate a
`path` method for enum variants, which is useful for creating
standardized string representations of enum variants.

The `DerivePathStr` macro provides the following functionality:
- Generates a `path` method for each enum variant.
- Allows specifying a prefix (required) and suffix (optional) for all
paths.
- Supports `strum` attributes for case conversion (e.g., snake_case,
lowercase).

Usage example:

```rust
#[derive(DerivePathStr)]
#[path_str(prefix = "my_prefix", suffix = ".txt")]
#[strum(serialize_all = "snake_case")]
enum MyEnum {
    VariantOne,
    VariantTwo,
}

// Generated paths:
// MyEnum::VariantOne.path() -> "my_prefix/variant_one.txt"
// MyEnum::VariantTwo.path() -> "my_prefix/variant_two.txt"
```

In a later PR this will be used to automate the creation of icon & image
paths in the `ui` crate.

This gives the following benefits:

1. Ensures standard naming of assets as paths are not manually
specified.
2. Makes adding new enum variants less tedious and error-prone.
3. Quickly catches missing or incorrect paths during compilation.
3. Adds a building block towards being able to lint for unused assets in
the future.

Release Notes:

- N/A
2024-09-13 16:45:16 -04:00
Peter Tripp
d245f5e75c OpenAI o1-preview and o1-mini support (#17796)
Release Notes:

- Added support for OpenAI o1-mini and o1-preview models.

---------

Co-authored-by: Jason Mancuso <7891333+jvmncs@users.noreply.github.com>
Co-authored-by: Bennet <bennet@zed.dev>
2024-09-13 16:23:55 -04:00
Danilo Leal
e145c13f73 Add stray UI polish to the SSH flow (#17798)
Some super subtle refinement opportunities I spotted while playing
around with this flow. There are mostly copywriting tweaks and some UI
tweaks here and there (including editing the modal horizontal padding).

--- 

Release Notes:

- N/A
2024-09-13 17:05:34 -03:00
Conrad Irwin
548878d8a0 Add support for extensions that edit buffers
Co-Authored-by: Zach <zachary.tc.@gmail.com>
Co-Authored-by: Marshall <marshall@zed.dev>
2024-09-13 15:55:57 -04:00
jvmncs
c71f052276 Add ability to use o1-preview and o1-mini as custom models (#17804)
This is a barebones modification of the OpenAI provider code to
accommodate non-streaming completions. This is specifically for the o1
models, which do not support streaming. Tested that this is working by
running a `/workflow` with the following (arbitrarily chosen) settings:

```json
{
  "language_models": {
    "openai": {
      "version": "1",
      "available_models": [
        {
          "name": "o1-preview",
          "display_name": "o1-preview",
          "max_tokens": 128000,
          "max_completion_tokens": 30000
        },
        {
          "name": "o1-mini",
          "display_name": "o1-mini",
          "max_tokens": 128000,
          "max_completion_tokens": 20000
        }
      ]
    }
  },
}
```

Release Notes:

- Changed  `low_speed_timeout_in_seconds` option to `600` for OpenAI
provider to accommodate recent o1 model release.

---------

Co-authored-by: Peter <peter@zed.dev>
Co-authored-by: Bennet <bennet@zed.dev>
Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-09-13 15:42:15 -04:00
tepek2
1b36c62188 Add keybinding to swap pane items (#15583)
- Rearrange tabs (left: `ctrl-shift-pageup`, right: `ctrl-shift-pagedown`) like Chrome

Co-authored-by: Peter Tripp <peter@zed.dev>
2024-09-13 15:17:01 -04:00
Thorsten Ball
adbe973f02 editor: In OpenFile check if file with path_suffix exists (#17805)
Demo:


https://github.com/user-attachments/assets/6acb6c1e-bb15-4205-9dcb-2aa4bb99dcf9



Release Notes:

- When using `OpenFile` (`gf` in Vim mode) and the word under the cursor
is not an existing file path, we now fall back and additionally check
whether a file called
`<word-under-cursor>.<language-specific-path-suffixes>` exists. That's
similar to Vim's `suffixesadd` option.

---------

Co-authored-by: Abdelhakim Qbaich <abdelhakim@qbaich.com>
Co-authored-by: Pete LeVasseur <plevasseur@gmail.com>
2024-09-13 15:11:10 -04:00
Barry Penner
8f833ea029 Fix missing on-mouseup when dragging the window on Linux (#17801)
Zed Hackathon entry :D

Release Notes:

- Fixed a bug where Zed would initiate a window move and then refuse to
release the mouse.

Co-authored-by: Mikayla <mikayla@zed.dev>
2024-09-13 11:51:14 -07:00
Marshall Bowers
de344c833b zed_extension_api: Use v0.2.0 WIT types (#17802)
This PR makes `zed_extension_api` use the WIT types from v0.2.0 of
extension API.

A follow-up from #17795, since I had forgotten to do it there.

Release Notes:

- N/A
2024-09-13 14:49:50 -04:00
Conrad Irwin
cdb88f52b7 temp 2024-09-13 13:44:58 -04:00
Richard Feldman
91ffa02e2c /auto (#16696)
Add `/auto` behind a feature flag that's disabled for now, even for
staff.

We've decided on a different design for context inference, but there are
parts of /auto that will be useful for that, so we want them in the code
base even if they're unused for now.

Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-09-13 13:17:49 -04:00
Conrad Irwin
14b4dc9a3a it compiles 2024-09-13 13:15:32 -04:00
Marshall Bowers
93a3e8bc94 zed_extension_api: Fork new version of extension API (#17795)
This PR forks a new version of the `zed_extension_api` in preparation
for new changes.

Release Notes:

- N/A

---------

Co-authored-by: Max <max@zed.dev>
2024-09-13 10:54:23 -04:00
Albert Marashi
3aeea93847 typescript: Highlight is predicate keyword & ... spread pattern (#17787)
Release Notes:

- Fixed the `is` and `...` highlights for TypeScript
2024-09-13 08:11:27 -04:00
CharlesChen0823
3613ebd93c editor: Fix an error when cut with vim visual line select (#17591)
Becuause in vim visual mode, we will always select next char, hit
[here](66ef318823/crates/vim/src/visual.rs (L174)),
when using editor method
for `cut` this selection, will hit this error.

Closes #17585 

Release Notes:

- N/A

---------

Co-authored-by: Conrad Irwin <conrad.irwin@gmail.com>
2024-09-12 16:55:59 -04:00
Junkui Zhang
461812d7b6 windows: Use the existing open_target function for platform::open_with_system (#17705)
Release Notes:

- N/A
2024-09-12 16:15:20 -04:00
Junkui Zhang
af819bf661 windows: Implement fs::trash_file and fs::trash_dir (#17711)
https://github.com/user-attachments/assets/43370cee-26a5-4d27-b86f-656127e03b4a



Release Notes:

- N/A
2024-09-12 16:14:53 -04:00
Jason Lee
ee96d69e37 gpui: Fix CJK line wrap for GPUI text render (#17737)
Release Notes:

- N/A

This changes is going to let GPUI render correct text wrapping for CJK
characters. We was done this in PR #11296 for Editor, but this is also
need support for other text renders.

| Before | After |
| --- | --- |
| <img width="488" alt="SCR-20240912-jtvo"
src="https://github.com/user-attachments/assets/d061669c-62ab-4a7e-a724-2df84815d1ed">
| <img width="438" alt="image"
src="https://github.com/user-attachments/assets/ec27fd80-69db-48b6-8ade-694cd65d1843">
|
2024-09-12 15:55:03 -04:00
Piotr Osiewicz
b9b62842f8 lsp: Treat unrooted paths as relative to the worktree root (#17769)
gopls would send us watch patterns like `**/*.mod` and we'd fall back to
watching `/`.

Release Notes:
- Fix file watching for go projects resorting to watching the fs root.

Co-authored-by: Thorsten <thorsten@zed.dev>
2024-09-12 15:23:27 -04:00
Conrad Irwin
4d26f83d23 Revert "settings: Remove auxiliary Content types where possible (#16744)" (#17768)
This breaks setting `{"scrollbar": {"show":"never"}}`
Release Notes:

- N/A
2024-09-12 14:46:08 -04:00
Danilo Leal
3b37db4140 Improve button copy on database load error toast (#17767)
Minimal copywriting improvement as that just happened to me while
working on Zed during ReactConf.

Release Notes:

- N/A
2024-09-12 15:17:59 -03:00
Danilo Leal
bba380e41a docs: Add copywriting tweaks to the Vim page (#17766)
Quick writing refinements as we displayed this docs over at RustConf.
Namely:

- Removal of "here" links
- Making link anchors generally bigger
- Adding commas where suitable
- Capitalizing "Vim" (although "vim mode" is still lowercased)

---

Release Notes:

- N/A
2024-09-12 15:06:38 -03:00
renovate[bot]
6841f7b9d7 Update Python to v3.12.6 (#17728)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [python](https://redirect.github.com/containerbase/python-prebuild) |
dependencies | patch | `3.12.5` -> `3.12.6` |

---

### Release Notes

<details>
<summary>containerbase/python-prebuild (python)</summary>

###
[`v3.12.6`](https://redirect.github.com/containerbase/python-prebuild/releases/tag/3.12.6)

[Compare
Source](https://redirect.github.com/containerbase/python-prebuild/compare/3.12.5...3.12.6)

##### Bug Fixes

-   **deps:** update dependency python to v3.12.6

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC43NC4xIiwidXBkYXRlZEluVmVyIjoiMzguNzQuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-12 11:53:31 -04:00
renovate[bot]
f39c175bd3 Update Rust crate serde_json_lenient to 0.2 (#17732)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
|
[serde_json_lenient](https://redirect.github.com/google/serde_json_lenient)
| workspace.dependencies | minor | `0.1` -> `0.2` |

---

### Release Notes

<details>
<summary>google/serde_json_lenient (serde_json_lenient)</summary>

###
[`v0.2.1`](https://redirect.github.com/google/serde_json_lenient/releases/tag/v0.2.1)

[Compare
Source](https://redirect.github.com/google/serde_json_lenient/compare/v0.2.0...v0.2.1)

- Fixed newline handling
([#&#8203;20](https://redirect.github.com/google/serde_json_lenient/issues/20))

###
[`v0.2.0`](https://redirect.github.com/google/serde_json_lenient/releases/tag/v0.2.0)

[Compare
Source](https://redirect.github.com/google/serde_json_lenient/compare/v0.1.8...v0.2.0)

-   Merged from upstream `serde_json`
- Introduce cfg!(parse_negative_zero_as_int) to create a build-time
option to parse -0 the same as other JSON parsers.
([#&#8203;16](https://redirect.github.com/google/serde_json_lenient/issues/16))
- Add an option to control escaped newlines separately from other
control
([#&#8203;18](https://redirect.github.com/google/serde_json_lenient/issues/18))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC43NC4xIiwidXBkYXRlZEluVmVyIjoiMzguNzQuMSIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-12 11:52:59 -04:00
Marshall Bowers
0043b0d957 editor: Render documentation popovers using UI font (#17761)
This PR updates the documentation popovers to render non-code using the
UI font:

<img width="603" alt="Screenshot 2024-09-12 at 11 10 46 AM"
src="https://github.com/user-attachments/assets/c5be0676-0f0f-4ff6-8a96-76b44684e1cf">

<img width="347" alt="Screenshot 2024-09-12 at 11 21 12 AM"
src="https://github.com/user-attachments/assets/842ba922-9837-45c1-9cf2-846fe8362f99">

Requested by @davidbarsky.

Release Notes:

- Changed documentation popovers to render Markdown prose using the UI
font instead of the buffer font. Code blocks still using the buffer
font.
2024-09-12 11:32:24 -04:00
Conrad Irwin
b341079d8a Fix maxTsServerMemory (#17758)
Release Notes:

- N/A

---------

Co-authored-by: Thorsten Ball <mrnugget@gmail.com>
2024-09-12 11:23:37 -04:00
Thorsten Ball
02d5f320ad lsp: Fix initialization_options being used as workspace configuration (#17757)
Release Notes:

- Fixed user-configured `initialization_options` being passed as
`workspace/Configuration` for the vtsls, TypeScript, and YAML language
servers.

Co-authored-by: Bennet <bennet@zed.dev>
2024-09-12 10:02:45 -04:00
Thorsten Ball
9db68ee6ae lsp: Use project-local settings if available (#17753)
Release Notes:

- Changed built-in language support (Rust, Go, C, YAML, ...) to lookup
language-server specific settings locally in project directory first
before falling back to global value.

---------

Co-authored-by: Bennet <bennet@zed.dev>
2024-09-12 09:47:25 -04:00
Conrad Irwin
092f29d394 Use a bigger prefix for numeric sorting (#17752)
Release Notes:

- Fixed sorting of files with YYYYmmddHHMMSS prefix
2024-09-12 09:11:19 -04:00
Conrad Irwin
25b6e43b0f bump eslint memory usage (#17724)
Release Notes:

- Increased memory limit for eslint to reduce crashes
2024-09-11 16:22:10 -04:00
Thorsten Ball
3a6a29f117 vim: Fix inline completions showing up in normal mode (#17727)
Booleans are hard.

Release Notes:

- Fixed inline completions showing up in Vim normal mode.
2024-09-11 16:13:17 -04:00
Thorsten Ball
9407d86ce6 project: Use login shell to get environment per project (#17717)
This is a follow-up to #17075 to spawn a login shell when getting the
environment for projects.

The reason why we didn't do it before is that we only used the
environment for certain language servers and not a lot of other things,
like tasks.

But with #17075 we now use the project more often and use it as the
_base_ environment for tasks/terminals.

Before the change, terminals and tasks would inherit the Zed process'
environment, including PATH and so on. After the change, we would set
the environment, overwriting the PATH instead of merging. But the
non-login shell environment is a subset of the login-shell environment.


Release Notes:

- Fixed environment variables used per project in terminals/tasks
overwriting the base environment and not making use of a login-shell
environment.
2024-09-11 13:33:42 -04:00
Thorsten Ball
b5c42edf1e lsp: Fix noisy logs when starting language servers (#17713)
We would log every time we'd lookup a language server for a file and
we'd also log "starting language server" even though we were about to
only download it and not start it.


Release Notes:

- N/A
2024-09-11 12:56:39 -04:00
226 changed files with 6404 additions and 2710 deletions

131
Cargo.lock generated
View File

@@ -304,6 +304,9 @@ name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
dependencies = [
"serde",
]
[[package]]
name = "as-raw-xcb-connection"
@@ -1709,6 +1712,19 @@ dependencies = [
"profiling",
]
[[package]]
name = "blake3"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d82033247fd8e890df8f740e407ad4d038debb9eb1f40533fffb32e7d17dc6f7"
dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
]
[[package]]
name = "block"
version = "0.1.6"
@@ -2752,6 +2768,12 @@ dependencies = [
"tiny-keccak",
]
[[package]]
name = "constant_time_eq"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
[[package]]
name = "context_servers"
version = "0.1.0"
@@ -4038,6 +4060,7 @@ dependencies = [
"client",
"collections",
"ctor",
"editor",
"env_logger",
"fs",
"futures 0.3.30",
@@ -4048,6 +4071,7 @@ dependencies = [
"language",
"log",
"lsp",
"multi_buffer",
"node_runtime",
"parking_lot",
"paths",
@@ -4187,6 +4211,7 @@ dependencies = [
name = "feature_flags"
version = "0.1.0"
dependencies = [
"futures 0.3.30",
"gpui",
]
@@ -7873,7 +7898,7 @@ name = "perplexity"
version = "0.1.0"
dependencies = [
"serde",
"zed_extension_api 0.1.0",
"zed_extension_api 0.2.0",
]
[[package]]
@@ -9814,10 +9839,13 @@ name = "semantic_index"
version = "0.1.0"
dependencies = [
"anyhow",
"arrayvec",
"blake3",
"client",
"clock",
"collections",
"env_logger",
"feature_flags",
"fs",
"futures 0.3.30",
"futures-batch",
@@ -9825,6 +9853,7 @@ dependencies = [
"heed",
"http_client",
"language",
"language_model",
"languages",
"log",
"open_ai",
@@ -9928,9 +9957,9 @@ dependencies = [
[[package]]
name = "serde_json_lenient"
version = "0.1.8"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc61c66b53a4035fcce237ef38043f4b2f0ebf918fd0e69541a5166104065581"
checksum = "a5d0bae483150302560d7cb52e7932f39b69a6fbdd099e48d33ef060a8c9c078"
dependencies = [
"indexmap 2.4.0",
"itoa",
@@ -10254,7 +10283,7 @@ dependencies = [
name = "slash_commands_example"
version = "0.1.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
@@ -11155,7 +11184,6 @@ dependencies = [
"futures 0.3.30",
"gpui",
"hex",
"log",
"parking_lot",
"schemars",
"serde",
@@ -12247,6 +12275,7 @@ dependencies = [
"story",
"strum 0.25.0",
"theme",
"ui_macros",
"windows 0.58.0",
]
@@ -12261,6 +12290,16 @@ dependencies = [
"ui",
]
[[package]]
name = "ui_macros"
version = "0.1.0"
dependencies = [
"convert_case 0.6.0",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "unicase"
version = "2.7.0"
@@ -14318,72 +14357,63 @@ name = "zed_astro"
version = "0.1.0"
dependencies = [
"serde",
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_clojure"
version = "0.0.3"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_csharp"
version = "0.0.2"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_dart"
version = "0.0.3"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_deno"
version = "0.0.2"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_elixir"
version = "0.0.9"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_elm"
version = "0.0.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_emmet"
version = "0.0.3"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_erlang"
version = "0.1.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "zed_extension_api"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"wit-bindgen",
"zed_extension_api 0.1.0",
]
[[package]]
@@ -14397,82 +14427,91 @@ dependencies = [
"wit-bindgen",
]
[[package]]
name = "zed_extension_api"
version = "0.2.0"
dependencies = [
"serde",
"serde_json",
"wit-bindgen",
]
[[package]]
name = "zed_gleam"
version = "0.2.0"
dependencies = [
"html_to_markdown 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_glsl"
version = "0.1.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_haskell"
version = "0.1.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_html"
version = "0.1.2"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_lua"
version = "0.0.3"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_ocaml"
version = "0.0.2"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_php"
version = "0.2.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_prisma"
version = "0.0.3"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_purescript"
version = "0.0.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_ruby"
version = "0.2.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_ruff"
version = "0.0.2"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
@@ -14480,42 +14519,50 @@ name = "zed_snippets"
version = "0.0.5"
dependencies = [
"serde_json",
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_svelte"
version = "0.1.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_terraform"
version = "0.1.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_test_extension"
version = "0.1.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.2.0",
]
[[package]]
name = "zed_toml"
version = "0.1.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_uiua"
version = "0.0.1"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_uppercase"
version = "0.0.5"
dependencies = [
"serde_json",
"zed_extension_api 0.2.0",
]
[[package]]
@@ -14523,14 +14570,14 @@ name = "zed_vue"
version = "0.1.0"
dependencies = [
"serde",
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]
name = "zed_zig"
version = "0.3.0"
dependencies = [
"zed_extension_api 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"zed_extension_api 0.1.0",
]
[[package]]

View File

@@ -118,6 +118,7 @@ members = [
"crates/title_bar",
"crates/ui",
"crates/ui_input",
"crates/ui_macros",
"crates/util",
"crates/vcs_menu",
"crates/vim",
@@ -158,6 +159,7 @@ members = [
"extensions/terraform",
"extensions/test-extension",
"extensions/toml",
"extensions/uppercase",
"extensions/uiua",
"extensions/vue",
"extensions/zig",
@@ -292,6 +294,7 @@ time_format = { path = "crates/time_format" }
title_bar = { path = "crates/title_bar" }
ui = { path = "crates/ui" }
ui_input = { path = "crates/ui_input" }
ui_macros = { path = "crates/ui_macros" }
util = { path = "crates/util" }
vcs_menu = { path = "crates/vcs_menu" }
vim = { path = "crates/vim" }
@@ -309,6 +312,7 @@ aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/alacritty/alacritty", rev = "91d034ff8b53867143c005acfaa14609147c9a2c" }
any_vec = "0.14"
anyhow = "1.0.86"
arrayvec = { version = "0.7.4", features = ["serde"] }
ashpd = "0.9.1"
async-compression = { version = "0.4", features = ["gzip", "futures-io"] }
async-dispatcher = "0.1"
@@ -325,12 +329,14 @@ bitflags = "2.6.0"
blade-graphics = { git = "https://github.com/kvark/blade", rev = "e142a3a5e678eb6a13e642ad8401b1f3aa38e969" }
blade-macros = { git = "https://github.com/kvark/blade", rev = "e142a3a5e678eb6a13e642ad8401b1f3aa38e969" }
blade-util = { git = "https://github.com/kvark/blade", rev = "e142a3a5e678eb6a13e642ad8401b1f3aa38e969" }
blake3 = "1.5.3"
cargo_metadata = "0.18"
cargo_toml = "0.20"
chrono = { version = "0.4", features = ["serde"] }
clap = { version = "4.4", features = ["derive"] }
clickhouse = "0.11.6"
cocoa = "0.26"
convert_case = "0.6.0"
core-foundation = "0.9.3"
core-foundation-sys = "0.8.6"
ctor = "0.2.6"
@@ -393,7 +399,7 @@ semver = "1.0"
serde = { version = "1.0", features = ["derive", "rc"] }
serde_derive = { version = "1.0", features = ["deserialize_in_place"] }
serde_json = { version = "1.0", features = ["preserve_order", "raw_value"] }
serde_json_lenient = { version = "0.1", features = [
serde_json_lenient = { version = "0.2", features = [
"preserve_order",
"raw_value",
] }
@@ -483,6 +489,7 @@ version = "0.58"
features = [
"implement",
"Foundation_Numerics",
"Storage",
"System",
"System_Threading",
"UI_ViewManagement",

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-volume-off"><path d="M16 9a5 5 0 0 1 .95 2.293"/><path d="M19.364 5.636a9 9 0 0 1 1.889 9.96"/><path d="m2 2 20 20"/><path d="m7 7-.587.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298V11"/><path d="M9.828 4.172A.686.686 0 0 1 11 4.657v.686"/></svg>

After

Width:  |  Height:  |  Size: 527 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-volume-2"><path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/></svg>

After

Width:  |  Height:  |  Size: 475 B

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

Before

Width:  |  Height:  |  Size: 238 B

After

Width:  |  Height:  |  Size: 238 B

View File

Before

Width:  |  Height:  |  Size: 610 B

After

Width:  |  Height:  |  Size: 610 B

View File

Before

Width:  |  Height:  |  Size: 345 B

After

Width:  |  Height:  |  Size: 345 B

View File

Before

Width:  |  Height:  |  Size: 443 B

After

Width:  |  Height:  |  Size: 443 B

View File

@@ -0,0 +1,6 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13 11V11.8374C13 11.9431 12.9665 12.046 12.9044 12.1315L12.1498 13.1691C12.0557 13.2985 11.9054 13.375 11.7454 13.375H4.25461C4.09464 13.375 3.94433 13.2985 3.85024 13.1691L3.09563 12.1315C3.03348 12.046 3 11.9431 3 11.8374V3" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M3 13V11L8 12H13V13H3Z" fill="black"/>
<path d="M6.63246 3.04418C7.44914 3.31641 8 4.08069 8 4.94155V11.7306C8 12.0924 7.62757 12.3345 7.29693 12.1875L3.79693 10.632C3.61637 10.5518 3.5 10.3727 3.5 10.1751V2.69374C3.5 2.35246 3.83435 2.11148 4.15811 2.2194L6.63246 3.04418Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.5 3C8.67157 3 8 3.67157 8 4.5V13C8 12.1954 11.2366 12.0382 12.5017 12.0075C12.7778 12.0008 13 11.7761 13 11.5V3.5C13 3.22386 12.7761 3 12.5 3H9.5Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 1009 B

View File

@@ -0,0 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 5H11" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M3 8H13" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M3 11H9" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 334 B

View File

@@ -0,0 +1,6 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 13C6.10457 13 7 12.1046 7 11C7 9.89543 6.10457 9 5 9C3.89543 9 3 9.89543 3 11C3 12.1046 3.89543 13 5 13Z" stroke="black" stroke-width="1.5"/>
<path d="M11 7C12.1046 7 13 6.10457 13 5C13 3.89543 12.1046 3 11 3C9.89543 3 9 3.89543 9 5C9 6.10457 9.89543 7 11 7Z" fill="black" stroke="black" stroke-width="1.5"/>
<path d="M4.625 3.625V8.375" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M11 7C11 9.20914 9.20914 11 7 11" stroke="black" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 591 B

View File

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 5C5 3.89543 5.89543 3 7 3H9C10.1046 3 11 3.89543 11 5V6H5V5Z" stroke="black" stroke-width="1.5"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.25 6.5C3.25 5.80964 3.80964 5.25 4.5 5.25H11.5C12.1904 5.25 12.75 5.80964 12.75 6.5V12.5C12.75 13.1904 12.1904 13.75 11.5 13.75H4.5C3.80964 13.75 3.25 13.1904 3.25 12.5V6.5ZM8.75 9.66146C8.90559 9.48517 9 9.25361 9 9C9 8.44772 8.55228 8 8 8C7.44772 8 7 8.44772 7 9C7 9.25361 7.09441 9.48517 7.25 9.66146V11C7.25 11.4142 7.58579 11.75 8 11.75C8.41421 11.75 8.75 11.4142 8.75 11V9.66146Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 667 B

View File

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.27935 10.9821C5.32063 10.4038 4.9204 9.89049 4.35998 9.80276L3.60081 9.68387C3.37979 9.64945 3.20167 9.48001 3.15225 9.25614L3.01378 8.63511C2.96382 8.41235 3.05233 8.1807 3.23696 8.05125L3.8631 7.61242C4.33337 7.28297 4.47456 6.6369 4.18621 6.13364L3.79467 5.45092C3.68118 5.25261 3.69801 5.00374 3.83757 4.82321L4.22314 4.32436C4.3627 4.14438 4.59621 4.06994 4.81071 4.13772L5.57531 4.37769C6.11944 4.54879 6.70048 4.26159 6.90683 3.71886L7.1811 2.99782C7.26255 2.78395 7.46345 2.64285 7.68772 2.6423L8.31007 2.64063C8.53434 2.64007 8.73579 2.78006 8.81834 2.99337L9.09965 3.72275C9.30821 4.26214 9.88655 4.54712 10.429 4.37714L11.1632 4.14716C11.3772 4.07994 11.6096 4.15382 11.7492 4.3327L12.1374 4.83099" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.76988 11.5933C8.76988 11.6595 8.8236 11.7133 8.88988 11.7133H8.97588C9.32602 11.7133 9.60988 11.9971 9.60988 12.3472C9.60988 12.6974 9.32602 12.9812 8.97588 12.9812H7.05587C6.70573 12.9812 6.42188 12.6974 6.42188 12.3472C6.42188 11.9971 6.70573 11.7133 7.05587 11.7133H7.14188C7.20815 11.7133 7.26188 11.6595 7.26188 11.5933V7.66925C7.26188 7.60298 7.20815 7.54925 7.14188 7.54925H7.05588C6.70573 7.54925 6.42188 7.2654 6.42188 6.91525C6.42188 6.5651 6.70573 6.28125 7.05588 6.28125H9.89988C11.0518 6.28125 12.8619 6.71487 12.8619 8.15185C12.8619 8.67078 12.7284 9.10362 12.4642 9.45348C12.1981 9.79765 11.8458 10.0564 11.4056 10.2293C11.3782 10.2401 11.3673 10.273 11.3829 10.298L12.2163 11.6342C12.247 11.6834 12.3008 11.7133 12.3588 11.7133H12.7319C13.082 11.7133 13.3659 11.9971 13.3659 12.3472C13.3659 12.6974 13.082 12.9812 12.7319 12.9812H11.5637C11.4955 12.9812 11.432 12.9465 11.3952 12.889L9.96523 10.6541C9.92847 10.5966 9.86495 10.5618 9.79675 10.5618H8.96988C8.85942 10.5618 8.76988 10.6514 8.76988 10.7619V11.5933ZM9.61188 7.54925C10.0296 7.54925 11.125 7.54925 11.2339 8.18785C11.2975 8.56123 11.1181 8.86557 10.8812 9.07715C10.6423 9.29046 10.2053 9.38985 9.58788 9.38985H8.86988C8.81465 9.38985 8.76988 9.34508 8.76988 9.28985V7.64925C8.76988 7.59402 8.81465 7.54925 8.86988 7.54925H9.61188Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -0,0 +1,5 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6 6H10" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M8 6V11" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
<path d="M5 3H3.5C3.22386 3 3 3.22386 3 3.5V12.5C3 12.7761 3.22386 13 3.5 13H5M11 3H12.5C12.7761 3 13 3.22386 13 3.5V12.5C13 12.7761 12.7761 13 12.5 13H11" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 472 B

View File

Before

Width:  |  Height:  |  Size: 462 B

After

Width:  |  Height:  |  Size: 462 B

3
assets/icons/folder.svg Normal file
View File

@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8.26046 3.97337C8.3527 4.17617 8.4795 4.47151 8.57375 4.69341C8.65258 4.87898 8.83437 4.99999 9.03599 4.99999H12.5C12.7761 4.99999 13 5.22385 13 5.49999V12.125C13 12.4011 12.7761 12.625 12.5 12.625H3.5C3.22386 12.625 3 12.4011 3 12.125V3.86932C3 3.59318 3.22386 3.36932 3.5 3.36932H7.34219C7.74141 3.36932 8.09483 3.60924 8.26046 3.97337Z" stroke="black" stroke-width="1.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 512 B

View File

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.42782 7.2487C4.43495 6.97194 4.65009 6.75 4.91441 6.75H13.5293C13.7935 6.75 14.007 6.97194 13.9998 7.2487C13.9628 8.6885 13.7533 12.75 12.5721 12.75H3.375C4.55631 12.75 4.3907 8.6885 4.42782 7.2487Z" fill="black" stroke="black" stroke-width="1.5" stroke-linejoin="round"/>
<path d="M5.19598 12.625H3.66515C3.42618 12.625 3.22289 12.4453 3.18626 12.2017L1.94333 3.93602C1.89776 3.63295 2.12496 3.35938 2.42223 3.35938H5.78585C6.11241 3.35938 6.41702 3.52903 6.59618 3.81071L6.94517 4.35938H9.92811C10.4007 4.35938 10.8044 4.71102 10.8836 5.1917L11.1251 6.65624" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 759 B

View File

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 8.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 677 B

After

Width:  |  Height:  |  Size: 677 B

View File

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.16089 10.2476L3.99598 10.3784C4.61244 10.4749 5.05269 11.0395 5.00728 11.6755L4.94576 12.5377C4.92784 12.789 5.06165 13.0255 5.28326 13.1348L5.90091 13.4391C6.12253 13.5485 6.38717 13.5075 6.56817 13.3371L7.1888 12.7505C7.64641 12.3178 8.35245 12.3178 8.81059 12.7505L9.43121 13.3371C9.61222 13.5081 9.87629 13.5485 10.0985 13.4391L10.7173 13.1341C10.9384 13.0255 11.0716 12.7895 11.0537 12.539L10.9921 11.6755C10.9467 11.0395 11.3869 10.4749 12.0033 10.3784L12.8385 10.2476C13.0817 10.2097 13.2776 10.0233 13.3325 9.77768L13.4848 9.09455C13.5398 8.8489 13.4425 8.59408 13.2393 8.45229L12.5422 7.96404C12.0279 7.60355 11.8708 6.89963 12.1814 6.34659L12.6025 5.59745C12.7249 5.3793 12.7047 5.10616 12.5511 4.9094L12.1241 4.36128C11.9706 4.16451 11.7149 4.08325 11.4795 4.15719L10.6719 4.41016C10.0752 4.59714 9.43903 4.28367 9.20962 3.69035L8.90017 2.88803C8.80937 2.65339 8.58777 2.4994 8.34108 2.5L7.65649 2.50184C7.40979 2.50244 7.1888 2.65766 7.09921 2.89291L6.79751 3.68607C6.57053 4.28307 5.93138 4.59898 5.33284 4.41077L4.49178 4.1468C4.25583 4.07225 3.99897 4.15413 3.84545 4.35212L3.42133 4.90084C3.26781 5.09943 3.2493 5.37319 3.37414 5.59133L3.80483 6.34232C4.12201 6.89591 3.96671 7.60659 3.44941 7.96897L2.76065 8.45169C2.55756 8.59408 2.4602 8.84891 2.51516 9.09393L2.66747 9.77708C2.72184 10.0233 2.91777 10.2097 3.16089 10.2476Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.41432 6.83576C8.63332 6.05481 7.36676 6.05476 6.58575 6.83571C5.8048 7.61672 5.80476 8.88327 6.58571 9.66427C7.36671 10.4452 8.63326 10.4452 9.41426 9.66432C10.1952 8.88332 10.1952 7.61676 9.41432 6.83576Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 450 B

After

Width:  |  Height:  |  Size: 450 B

View File

@@ -1,8 +0,0 @@
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.72361 1.05279C7.893 1.13749 8 1.31062 8 1.5V13.5C8 13.6894 7.893 13.8625 7.72361 13.9472C7.55421 14.0319 7.35151 14.0136 7.2 13.9L3.33333 11H1.5C0.671573 11 0 10.3284 0 9.5V5.5C0 4.67158 0.671573 4 1.5 4H3.33333L7.2 1.1C7.35151 0.986371 7.55421 0.968093 7.72361 1.05279ZM7 2.5L3.8 4.9C3.71345 4.96491 3.60819 5 3.5 5H1.5C1.22386 5 1 5.22386 1 5.5V9.5C1 9.77614 1.22386 10 1.5 10H3.5C3.60819 10 3.71345 10.0351 3.8 10.1L7 12.5V2.5ZM14.8536 5.14645C15.0488 5.34171 15.0488 5.65829 14.8536 5.85355L13.2071 7.5L14.8536 9.14645C15.0488 9.34171 15.0488 9.65829 14.8536 9.85355C14.6583 10.0488 14.3417 10.0488 14.1464 9.85355L12.5 8.20711L10.8536 9.85355C10.6583 10.0488 10.3417 10.0488 10.1464 9.85355C9.95118 9.65829 9.95118 9.34171 10.1464 9.14645L11.7929 7.5L10.1464 5.85355C9.95118 5.65829 9.95118 5.34171 10.1464 5.14645C10.3417 4.95118 10.6583 4.95118 10.8536 5.14645L12.5 6.79289L14.1464 5.14645C14.3417 4.95118 14.6583 4.95118 14.8536 5.14645Z"
fill="currentColor"
/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 947 B

After

Width:  |  Height:  |  Size: 947 B

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 785 B

After

Width:  |  Height:  |  Size: 785 B

View File

@@ -0,0 +1,10 @@
<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_1957_1318)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 6C7.34315 6 6 7.34315 6 9V75H0V9C0 4.02944 4.02944 0 9 0H89.3787C93.3878 0 95.3955 4.84715 92.5607 7.68198L43.0551 57.1875H57V51H63V58.6875C63 61.1728 60.9853 63.1875 58.5 63.1875H37.0551L26.7426 73.5H73.5V36H79.5V73.5C79.5 76.8137 76.8137 79.5 73.5 79.5H20.7426L10.2426 90H87C88.6569 90 90 88.6569 90 87V21H96V87C96 91.9706 91.9706 96 87 96H6.62132C2.61224 96 0.604504 91.1529 3.43934 88.318L52.7574 39H39V45H33V37.5C33 35.0147 35.0147 33 37.5 33H58.7574L69.2574 22.5H22.5V60H16.5V22.5C16.5 19.1863 19.1863 16.5 22.5 16.5H75.2574L85.7574 6H9Z" fill="black"/>
</g>
<defs>
<clipPath id="clip0_1957_1318">
<rect width="96" height="96" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 861 B

View File

@@ -0,0 +1,14 @@
<svg width="93" height="32" viewBox="0 0 93 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.03994 7.04962C8.00934 7.67635 7.30394 8.63219 7.30394 10.0149C7.30394 11.6908 7.72423 12.5893 8.20468 13.0744C8.68379 13.5581 9.40524 13.8149 10.4054 13.8149C11.815 13.8149 13.0291 13.5336 13.8802 12.9464C14.6756 12.3977 15.2708 11.5042 15.3438 9.96182C15.3991 8.79382 15.3678 8.01341 15.0568 7.45711C14.8094 7.01449 14.2326 6.47436 12.4901 6.27416C11.4684 6.15678 10.1114 6.39804 9.03994 7.04962ZM7.8731 5.13084C9.39145 4.2075 11.2531 3.87155 12.7464 4.04312C14.8843 4.28874 16.2844 5.05049 17.0171 6.36142C17.6863 7.55867 17.6384 8.98348 17.587 10.068C17.484 12.2439 16.5804 13.8118 15.1554 14.7949C13.7861 15.7396 12.0582 16.0606 10.4054 16.0606C9.04199 16.0606 7.65126 15.7069 6.60911 14.6547C5.5683 13.6038 5.05823 12.0408 5.05823 10.0149C5.05823 7.6958 6.31388 6.07903 7.8731 5.13084Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.983 18.2811C14.6595 18.2811 15.2079 18.8295 15.2079 19.506V22.16C15.2079 22.8365 14.6595 23.385 13.983 23.385C13.3065 23.385 12.758 22.8365 12.758 22.16V19.506C12.758 18.8295 13.3065 18.2811 13.983 18.2811Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M5.25567 14.8903C5.48362 14.039 5.99219 12.9059 7.20735 12.5361L7.92069 14.8798L7.92376 14.8785C7.92375 14.8785 7.92323 14.8778 7.92069 14.8798C7.91365 14.8852 7.89134 14.9052 7.85879 14.951C7.78817 15.0505 7.70058 15.2311 7.62217 15.524C7.46355 16.1164 7.40615 16.9168 7.40617 17.7813V22.1675C7.43457 22.3571 7.45083 22.438 7.48149 22.5189C7.50698 22.5862 7.55955 22.695 7.72277 22.8617C8.0938 23.2406 8.94056 23.8264 10.9275 24.7081C12.5399 25.4236 13.2749 25.7456 13.9586 25.9166C14.6053 26.0784 15.2382 26.1115 16.6666 26.1115V28.5613C15.2536 28.5613 14.3395 28.5372 13.3641 28.2932C12.452 28.0651 11.5174 27.6502 10.0614 27.004C10.0193 26.9853 9.9768 26.9664 9.93383 26.9474C7.89761 26.0438 6.6867 25.3053 5.97233 24.5757C5.59285 24.1882 5.34579 23.7967 5.19056 23.387C5.05419 23.0271 5.00551 22.6875 4.9751 22.4754C4.97301 22.4608 4.971 22.4468 4.96906 22.4335L4.9563 22.3458V17.7814C4.95628 16.8606 5.01201 15.8003 5.25567 14.8903Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.98306 15.3589C4.62844 14.6695 5.39976 13.9884 5.99652 13.6348L7.24552 15.7424C6.93706 15.9252 6.34938 16.4159 5.77155 17.0332C5.21994 17.6224 4.85695 18.1377 4.73071 18.4254C4.70277 18.6674 4.71195 19.116 4.78977 19.648C4.87834 20.2536 5.01731 20.7033 5.10492 20.8628L5.19261 21.0224L5.23006 21.2007C5.28661 21.4698 5.55952 21.8651 6.30146 22.3907C6.88143 22.8015 7.56502 23.1703 8.29605 23.5648C8.45794 23.6521 8.62215 23.7407 8.78809 23.8313C9.5952 24.2156 10.848 24.7773 12.0191 25.2425C12.613 25.4784 13.1698 25.6831 13.6288 25.8268C13.8584 25.8987 14.0505 25.9512 14.2021 25.9847C14.3503 26.0175 14.4185 26.0227 14.4277 26.0234C14.4288 26.0234 14.4281 26.0234 14.4277 26.0234L14.4287 28.4733C13.9646 28.4733 13.3889 28.3188 12.8968 28.1648C12.3562 27.9955 11.7367 27.7664 11.1147 27.5193C9.86871 27.0244 8.54832 26.4314 7.70298 26.028L7.67249 26.0135L7.64284 25.9973C7.49779 25.918 7.34502 25.8357 7.18702 25.7506C6.4505 25.354 5.60004 24.896 4.88539 24.3898C4.08363 23.8219 3.18153 23.0135 2.87437 21.8785C2.61828 21.3365 2.4557 20.618 2.3657 20.0026C2.26537 19.3167 2.2169 18.4951 2.33888 17.8727L2.35434 17.7938L2.37996 17.7176C2.6522 16.9085 3.36219 16.0221 3.98306 15.3589Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.48529 21.264V17.1402H5.93516V21.264H3.48529Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.2932 7.04962C25.3238 7.67635 26.0292 8.63219 26.0292 10.0149C26.0292 11.6908 25.609 12.5893 25.1285 13.0744C24.6494 13.5581 23.9279 13.8149 22.9278 13.8149C21.5182 13.8149 20.3041 13.5336 19.453 12.9464C18.6576 12.3977 18.0624 11.5042 17.9894 9.96182C17.9341 8.79382 17.9654 8.01341 18.2764 7.45711C18.5238 7.01449 19.1006 6.47436 20.8431 6.27416C21.8648 6.15678 23.2218 6.39804 24.2932 7.04962ZM25.4601 5.13084C23.9417 4.2075 22.0801 3.87155 20.5868 4.04312C18.4489 4.28874 17.0488 5.05049 16.3161 6.36142C15.6469 7.55867 15.6948 8.98348 15.7462 10.068C15.8492 12.2439 16.7528 13.8118 18.1778 14.7949C19.5471 15.7396 21.275 16.0606 22.9278 16.0606C24.2912 16.0606 25.6819 15.7069 26.7241 14.6547C27.7649 13.6038 28.275 12.0408 28.275 10.0149C28.275 7.6958 27.0193 6.07903 25.4601 5.13084Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.3502 18.2811C18.6737 18.2811 18.1253 18.8295 18.1253 19.506V22.16C18.1253 22.8365 18.6737 23.385 19.3502 23.385C20.0267 23.385 20.5752 22.8365 20.5752 22.16V19.506C20.5752 18.8295 20.0267 18.2811 19.3502 18.2811Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M28.0775 14.8903C27.8496 14.039 27.341 12.9059 26.1259 12.5361L25.4125 14.8798L25.4095 14.8785C25.4095 14.8785 25.41 14.8778 25.4125 14.8798C25.4196 14.8852 25.4419 14.9052 25.4744 14.951C25.545 15.0505 25.6326 15.2311 25.711 15.524C25.8697 16.1164 25.9271 16.9168 25.927 17.7813V22.1675C25.8986 22.3571 25.8824 22.438 25.8517 22.5189C25.8262 22.5862 25.7737 22.695 25.6104 22.8617C25.2394 23.2406 24.3927 23.8264 22.4057 24.7081C20.7933 25.4236 20.0583 25.7456 19.3746 25.9166C18.7279 26.0784 18.0949 26.1115 16.6666 26.1115V28.5613C18.0796 28.5613 18.9937 28.5372 19.9691 28.2932C20.8812 28.0651 21.8158 27.6502 23.2718 27.004C23.3139 26.9853 23.3564 26.9664 23.3994 26.9474C25.4356 26.0438 26.6465 25.3053 27.3609 24.5757C27.7404 24.1882 27.9874 23.7967 28.1427 23.387C28.279 23.0271 28.3277 22.6875 28.3581 22.4754C28.3602 22.4608 28.3622 22.4468 28.3642 22.4335L28.3769 22.3458V17.7814C28.3769 16.8606 28.3212 15.8003 28.0775 14.8903Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M29.3501 15.3589C28.7048 14.6695 27.9334 13.9884 27.3367 13.6348L26.0877 15.7424C26.3961 15.9252 26.9838 16.4159 27.5616 17.0332C28.1133 17.6224 28.4763 18.1377 28.6025 18.4254C28.6304 18.6674 28.6213 19.116 28.5434 19.648C28.4549 20.2536 28.3159 20.7033 28.2283 20.8628L28.1406 21.0224L28.1031 21.2007C28.0466 21.4698 27.7737 21.8651 27.0317 22.3907C26.4518 22.8015 25.7682 23.1703 25.0372 23.5648C24.8753 23.6521 24.711 23.7407 24.5451 23.8313C23.738 24.2156 22.4852 24.7773 21.3141 25.2425C20.7202 25.4784 20.1634 25.6831 19.7044 25.8268C19.4748 25.8987 19.2827 25.9512 19.1311 25.9847C18.9829 26.0175 18.9147 26.0227 18.9055 26.0234C18.9051 26.0234 18.9044 26.0234 18.9055 26.0234L18.9045 28.4733C19.3686 28.4733 19.9443 28.3188 20.4364 28.1648C20.977 27.9955 21.5965 27.7664 22.2185 27.5193C23.4645 27.0244 24.7849 26.4314 25.6302 26.028L25.6607 26.0135L25.6904 25.9973C25.8354 25.918 25.9882 25.8357 26.1462 25.7506C26.8827 25.354 27.7332 24.896 28.4478 24.3898C29.2496 23.8219 30.1517 23.0135 30.4588 21.8785C30.7149 21.3365 30.8775 20.618 30.9675 20.0026C31.0678 19.3167 31.1163 18.4951 30.9943 17.8727L30.9789 17.7938L30.9532 17.7176C30.681 16.9085 29.971 16.0221 29.3501 15.3589Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M29.8479 21.264V17.1402H27.398V21.264H29.8479Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M48.6666 11C49.2189 11 49.6666 11.4477 49.6666 12V15H52.6666C53.2189 15 53.6666 15.4477 53.6666 16C53.6666 16.5523 53.2189 17 52.6666 17H49.6666V20C49.6666 20.5523 49.2189 21 48.6666 21C48.1143 21 47.6666 20.5523 47.6666 20V17H44.6666C44.1143 17 43.6666 16.5523 43.6666 16C43.6666 15.4477 44.1143 15 44.6666 15H47.6666V12C47.6666 11.4477 48.1143 11 48.6666 11Z" fill="black" fill-opacity="0.5"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M67.1666 4.33329C66.7064 4.33329 66.3333 4.70639 66.3333 5.16663V23.5H64.6666V5.16663C64.6666 3.78591 65.7859 2.66663 67.1666 2.66663H89.494C90.6077 2.66663 91.1654 4.01306 90.3779 4.80051L76.6264 18.552H80.5V16.8333H82.1666V18.9687C82.1666 19.6591 81.607 20.2187 80.9166 20.2187H74.9597L72.0951 23.0833H85.0833V12.6666H86.75V23.0833C86.75 24.0038 86.0038 24.75 85.0833 24.75H70.4285L67.5118 27.6666H88.8333C89.2935 27.6666 89.6666 27.2935 89.6666 26.8333V8.49996H91.3333V26.8333C91.3333 28.214 90.214 29.3333 88.8333 29.3333H66.5059C65.3922 29.3333 64.8345 27.9869 65.622 27.1994L79.3214 13.5H75.5V15.1666H73.8333V13.0833C73.8333 12.3929 74.3929 11.8333 75.0833 11.8333H80.9881L83.9048 8.91663H70.9166V19.3333H69.25V8.91663C69.25 7.99615 69.9962 7.24996 70.9166 7.24996H85.5714L88.4881 4.33329H67.1666Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 8.2 KiB

View File

@@ -245,6 +245,8 @@
"bindings": {
"ctrl-pageup": "pane::ActivatePrevItem",
"ctrl-pagedown": "pane::ActivateNextItem",
"ctrl-shift-pageup": "pane::SwapItemLeft",
"ctrl-shift-pagedown": "pane::SwapItemRight",
"ctrl-w": "pane::CloseActiveItem",
"ctrl-f4": "pane::CloseActiveItem",
"alt-ctrl-t": "pane::CloseInactiveItems",

View File

@@ -285,6 +285,8 @@
"cmd-}": "pane::ActivateNextItem",
"alt-cmd-left": "pane::ActivatePrevItem",
"alt-cmd-right": "pane::ActivateNextItem",
"ctrl-shift-pageup": "pane::SwapItemLeft",
"ctrl-shift-pagedown": "pane::SwapItemRight",
"cmd-w": "pane::CloseActiveItem",
"alt-cmd-t": "pane::CloseInactiveItems",
"ctrl-alt-cmd-w": "workspace::CloseInactiveTabsAndPanes",

View File

@@ -916,7 +916,8 @@
},
"openai": {
"version": "1",
"api_url": "https://api.openai.com/v1"
"api_url": "https://api.openai.com/v1",
"low_speed_timeout_in_seconds": 600
}
},
// Zed's Prettier integration settings.

View File

@@ -262,7 +262,7 @@ impl ActivityIndicator {
if !failed.is_empty() {
return Some(Content {
icon: Some(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.into_any_element(),
),
@@ -280,7 +280,7 @@ impl ActivityIndicator {
if let Some(failure) = self.project.read(cx).last_formatting_failure() {
return Some(Content {
icon: Some(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.into_any_element(),
),
@@ -333,7 +333,7 @@ impl ActivityIndicator {
}),
AutoUpdateStatus::Errored => Some(Content {
icon: Some(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.into_any_element(),
),

View File

@@ -8,6 +8,7 @@ use rust_embed::RustEmbed;
#[folder = "../../assets"]
#[include = "fonts/**/*"]
#[include = "icons/**/*"]
#[include = "images/**/*"]
#[include = "themes/**/*"]
#[exclude = "themes/src/*"]
#[include = "sounds/**/*"]

View File

@@ -37,13 +37,13 @@ use language_model::{
pub(crate) use model_selector::*;
pub use prompts::PromptBuilder;
use prompts::PromptLoadingParams;
use semantic_index::{CloudEmbeddingProvider, SemanticIndex};
use semantic_index::{CloudEmbeddingProvider, SemanticDb};
use serde::{Deserialize, Serialize};
use settings::{update_settings_file, Settings, SettingsStore};
use slash_command::{
context_server_command, default_command, diagnostics_command, docs_command, fetch_command,
file_command, now_command, project_command, prompt_command, search_command, symbols_command,
tab_command, terminal_command, workflow_command,
auto_command, context_server_command, default_command, diagnostics_command, docs_command,
fetch_command, file_command, now_command, project_command, prompt_command, search_command,
symbols_command, tab_command, terminal_command, workflow_command,
};
use std::path::PathBuf;
use std::sync::Arc;
@@ -210,12 +210,13 @@ pub fn init(
let client = client.clone();
async move {
let embedding_provider = CloudEmbeddingProvider::new(client.clone());
let semantic_index = SemanticIndex::new(
let semantic_index = SemanticDb::new(
paths::embeddings_dir().join("semantic-index-db.0.mdb"),
Arc::new(embedding_provider),
&mut cx,
)
.await?;
cx.update(|cx| cx.set_global(semantic_index))
}
})
@@ -364,6 +365,7 @@ fn update_active_language_model_from_settings(cx: &mut AppContext) {
fn register_slash_commands(prompt_builder: Option<Arc<PromptBuilder>>, cx: &mut AppContext) {
let slash_command_registry = SlashCommandRegistry::global(cx);
slash_command_registry.register_command(file_command::FileSlashCommand, true);
slash_command_registry.register_command(symbols_command::OutlineSlashCommand, true);
slash_command_registry.register_command(tab_command::TabSlashCommand, true);
@@ -382,6 +384,17 @@ fn register_slash_commands(prompt_builder: Option<Arc<PromptBuilder>>, cx: &mut
}
slash_command_registry.register_command(fetch_command::FetchSlashCommand, false);
cx.observe_flag::<auto_command::AutoSlashCommandFeatureFlag, _>({
let slash_command_registry = slash_command_registry.clone();
move |is_enabled, _cx| {
if is_enabled {
// [#auto-staff-ship] TODO remove this when /auto is no longer staff-shipped
slash_command_registry.register_command(auto_command::AutoCommand, true);
}
}
})
.detach();
update_slash_commands_from_settings(cx);
cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
.detach();

View File

@@ -4110,7 +4110,7 @@ impl ContextEditor {
h_flex()
.gap_3()
.child(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.color(Color::Warning),
)
@@ -4723,6 +4723,20 @@ impl Render for ContextEditorToolbarItem {
let weak_self = cx.view().downgrade();
let right_side = h_flex()
.gap_2()
// TODO display this in a nicer way, once we have a design for it.
// .children({
// let project = self
// .workspace
// .upgrade()
// .map(|workspace| workspace.read(cx).project().downgrade());
//
// let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
// project.and_then(|project| db.remaining_summaries(&project, cx))
// });
// scan_items_remaining
// .map(|remaining_items| format!("Files to scan: {}", remaining_items))
// })
.child(
ModelSelector::new(
self.fs.clone(),
@@ -5221,7 +5235,7 @@ fn quote_selection_fold_placeholder(title: String, editor: WeakView<Editor>) ->
ButtonLike::new(fold_id)
.style(ButtonStyle::Filled)
.layer(ElevationIndex::ElevatedSurface)
.child(Icon::new(IconName::TextSelect))
.child(Icon::new(IconName::CursorIBeam))
.child(Label::new(title.clone()).single_line())
.on_click(move |_, cx| {
editor
@@ -5325,7 +5339,7 @@ fn render_docs_slash_command_trailer(
div()
.id(("latest-error", row.0))
.child(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.color(Color::Warning),
)

View File

@@ -163,11 +163,13 @@ impl AssistantSettingsContent {
display_name,
max_tokens,
max_output_tokens,
max_completion_tokens: None,
} => Some(open_ai::AvailableModel {
name,
display_name,
max_tokens,
max_output_tokens,
max_completion_tokens: None,
}),
_ => None,
})
@@ -519,6 +521,7 @@ impl Settings for AssistantSettings {
&mut settings.default_model,
value.default_model.map(Into::into),
);
// merge(&mut settings.infer_context, value.infer_context); TODO re-enable this once we ship context inference
}
Ok(settings)

View File

@@ -1478,7 +1478,7 @@ impl Render for PromptEditor {
.child(
ModelSelector::new(
self.fs.clone(),
IconButton::new("context", IconName::SlidersAlt)
IconButton::new("context", IconName::SettingsAlt)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.icon_color(Color::Muted)
@@ -2407,7 +2407,7 @@ impl Codegen {
Ok(LanguageModelRequest {
messages,
tools: Vec::new(),
stop: vec!["|END|>".to_string()],
stop: Vec::new(),
temperature: 1.,
})
}

View File

@@ -19,6 +19,7 @@ use std::{
use ui::ActiveTheme;
use workspace::Workspace;
pub mod auto_command;
pub mod context_server_command;
pub mod default_command;
pub mod diagnostics_command;

View File

@@ -0,0 +1,360 @@
use super::create_label_for_command;
use super::{SlashCommand, SlashCommandOutput};
use anyhow::{anyhow, Result};
use assistant_slash_command::ArgumentCompletion;
use feature_flags::FeatureFlag;
use futures::StreamExt;
use gpui::{AppContext, AsyncAppContext, Task, WeakView};
use language::{CodeLabel, LspAdapterDelegate};
use language_model::{
LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
LanguageModelRequestMessage, Role,
};
use semantic_index::{FileSummary, SemanticDb};
use smol::channel;
use std::sync::{atomic::AtomicBool, Arc};
use ui::{BorrowAppContext, WindowContext};
use util::ResultExt;
use workspace::Workspace;
pub struct AutoSlashCommandFeatureFlag;
impl FeatureFlag for AutoSlashCommandFeatureFlag {
const NAME: &'static str = "auto-slash-command";
}
pub(crate) struct AutoCommand;
impl SlashCommand for AutoCommand {
fn name(&self) -> String {
"auto".into()
}
fn description(&self) -> String {
"Automatically infer what context to add, based on your prompt".into()
}
fn menu_text(&self) -> String {
"Automatically Infer Context".into()
}
fn label(&self, cx: &AppContext) -> CodeLabel {
create_label_for_command("auto", &["--prompt"], cx)
}
fn complete_argument(
self: Arc<Self>,
_arguments: &[String],
_cancel: Arc<AtomicBool>,
workspace: Option<WeakView<Workspace>>,
cx: &mut WindowContext,
) -> Task<Result<Vec<ArgumentCompletion>>> {
// There's no autocomplete for a prompt, since it's arbitrary text.
// However, we can use this opportunity to kick off a drain of the backlog.
// That way, it can hopefully be done resummarizing by the time we've actually
// typed out our prompt. This re-runs on every keystroke during autocomplete,
// but in the future, we could instead do it only once, when /auto is first entered.
let Some(workspace) = workspace.and_then(|ws| ws.upgrade()) else {
log::warn!("workspace was dropped or unavailable during /auto autocomplete");
return Task::ready(Ok(Vec::new()));
};
let project = workspace.read(cx).project().clone();
let Some(project_index) =
cx.update_global(|index: &mut SemanticDb, cx| index.project_index(project, cx))
else {
return Task::ready(Err(anyhow!("No project indexer, cannot use /auto")));
};
let cx: &mut AppContext = cx;
cx.spawn(|cx: gpui::AsyncAppContext| async move {
let task = project_index.read_with(&cx, |project_index, cx| {
project_index.flush_summary_backlogs(cx)
})?;
cx.background_executor().spawn(task).await;
anyhow::Ok(Vec::new())
})
}
fn requires_argument(&self) -> bool {
true
}
fn run(
self: Arc<Self>,
arguments: &[String],
workspace: WeakView<Workspace>,
_delegate: Option<Arc<dyn LspAdapterDelegate>>,
cx: &mut WindowContext,
) -> Task<Result<SlashCommandOutput>> {
let Some(workspace) = workspace.upgrade() else {
return Task::ready(Err(anyhow::anyhow!("workspace was dropped")));
};
if arguments.is_empty() {
return Task::ready(Err(anyhow!("missing prompt")));
};
let argument = arguments.join(" ");
let original_prompt = argument.to_string();
let project = workspace.read(cx).project().clone();
let Some(project_index) =
cx.update_global(|index: &mut SemanticDb, cx| index.project_index(project, cx))
else {
return Task::ready(Err(anyhow!("no project indexer")));
};
let task = cx.spawn(|cx: gpui::AsyncWindowContext| async move {
let summaries = project_index
.read_with(&cx, |project_index, cx| project_index.all_summaries(cx))?
.await?;
commands_for_summaries(&summaries, &original_prompt, &cx).await
});
// As a convenience, append /auto's argument to the end of the prompt
// so you don't have to write it again.
let original_prompt = argument.to_string();
cx.background_executor().spawn(async move {
let commands = task.await?;
let mut prompt = String::new();
log::info!(
"Translating this response into slash-commands: {:?}",
commands
);
for command in commands {
prompt.push('/');
prompt.push_str(&command.name);
prompt.push(' ');
prompt.push_str(&command.arg);
prompt.push('\n');
}
prompt.push('\n');
prompt.push_str(&original_prompt);
Ok(SlashCommandOutput {
text: prompt,
sections: Vec::new(),
run_commands_in_text: true,
})
})
}
}
const PROMPT_INSTRUCTIONS_BEFORE_SUMMARY: &str = include_str!("prompt_before_summary.txt");
const PROMPT_INSTRUCTIONS_AFTER_SUMMARY: &str = include_str!("prompt_after_summary.txt");
fn summaries_prompt(summaries: &[FileSummary], original_prompt: &str) -> String {
let json_summaries = serde_json::to_string(summaries).unwrap();
format!("{PROMPT_INSTRUCTIONS_BEFORE_SUMMARY}\n{json_summaries}\n{PROMPT_INSTRUCTIONS_AFTER_SUMMARY}\n{original_prompt}")
}
/// The slash commands that the model is told about, and which we look for in the inference response.
const SUPPORTED_SLASH_COMMANDS: &[&str] = &["search", "file"];
#[derive(Debug, Clone)]
struct CommandToRun {
name: String,
arg: String,
}
/// Given the pre-indexed file summaries for this project, as well as the original prompt
/// string passed to `/auto`, get a list of slash commands to run, along with their arguments.
///
/// The prompt's output does not include the slashes (to reduce the chance that it makes a mistake),
/// so taking one of these returned Strings and turning it into a real slash-command-with-argument
/// involves prepending a slash to it.
///
/// This function will validate that each of the returned lines begins with one of SUPPORTED_SLASH_COMMANDS.
/// Any other lines it encounters will be discarded, with a warning logged.
async fn commands_for_summaries(
summaries: &[FileSummary],
original_prompt: &str,
cx: &AsyncAppContext,
) -> Result<Vec<CommandToRun>> {
if summaries.is_empty() {
log::warn!("Inferring no context because there were no summaries available.");
return Ok(Vec::new());
}
// Use the globally configured model to translate the summaries into slash-commands,
// because Qwen2-7B-Instruct has not done a good job at that task.
let Some(model) = cx.update(|cx| LanguageModelRegistry::read_global(cx).active_model())? else {
log::warn!("Can't infer context because there's no active model.");
return Ok(Vec::new());
};
// Only go up to 90% of the actual max token count, to reduce chances of
// exceeding the token count due to inaccuracies in the token counting heuristic.
let max_token_count = (model.max_token_count() * 9) / 10;
// Rather than recursing (which would require this async function use a pinned box),
// we use an explicit stack of arguments and answers for when we need to "recurse."
let mut stack = vec![summaries];
let mut final_response = Vec::new();
let mut prompts = Vec::new();
// TODO We only need to create multiple Requests because we currently
// don't have the ability to tell if a CompletionProvider::complete response
// was a "too many tokens in this request" error. If we had that, then
// we could try the request once, instead of having to make separate requests
// to check the token count and then afterwards to run the actual prompt.
let make_request = |prompt: String| LanguageModelRequest {
messages: vec![LanguageModelRequestMessage {
role: Role::User,
content: vec![prompt.into()],
// Nothing in here will benefit from caching
cache: false,
}],
tools: Vec::new(),
stop: Vec::new(),
temperature: 1.0,
};
while let Some(current_summaries) = stack.pop() {
// The split can result in one slice being empty and the other having one element.
// Whenever that happens, skip the empty one.
if current_summaries.is_empty() {
continue;
}
log::info!(
"Inferring prompt context using {} file summaries",
current_summaries.len()
);
let prompt = summaries_prompt(&current_summaries, original_prompt);
let start = std::time::Instant::now();
// Per OpenAI, 1 token ~= 4 chars in English (we go with 4.5 to overestimate a bit, because failed API requests cost a lot of perf)
// Verifying this against an actual model.count_tokens() confirms that it's usually within ~5% of the correct answer, whereas
// getting the correct answer from tiktoken takes hundreds of milliseconds (compared to this arithmetic being ~free).
// source: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
let token_estimate = prompt.len() * 2 / 9;
let duration = start.elapsed();
log::info!(
"Time taken to count tokens for prompt of length {:?}B: {:?}",
prompt.len(),
duration
);
if token_estimate < max_token_count {
prompts.push(prompt);
} else if current_summaries.len() == 1 {
log::warn!("Inferring context for a single file's summary failed because the prompt's token length exceeded the model's token limit.");
} else {
log::info!(
"Context inference using file summaries resulted in a prompt containing {token_estimate} tokens, which exceeded the model's max of {max_token_count}. Retrying as two separate prompts, each including half the number of summaries.",
);
let (left, right) = current_summaries.split_at(current_summaries.len() / 2);
stack.push(right);
stack.push(left);
}
}
let all_start = std::time::Instant::now();
let (tx, rx) = channel::bounded(1024);
let completion_streams = prompts
.into_iter()
.map(|prompt| {
let request = make_request(prompt.clone());
let model = model.clone();
let tx = tx.clone();
let stream = model.stream_completion(request, &cx);
(stream, tx)
})
.collect::<Vec<_>>();
cx.background_executor()
.spawn(async move {
let futures = completion_streams
.into_iter()
.enumerate()
.map(|(ix, (stream, tx))| async move {
let start = std::time::Instant::now();
let events = stream.await?;
log::info!("Time taken for awaiting /await chunk stream #{ix}: {:?}", start.elapsed());
let completion: String = events
.filter_map(|event| async {
if let Ok(LanguageModelCompletionEvent::Text(text)) = event {
Some(text)
} else {
None
}
})
.collect()
.await;
log::info!("Time taken for all /auto chunks to come back for #{ix}: {:?}", start.elapsed());
for line in completion.split('\n') {
if let Some(first_space) = line.find(' ') {
let command = &line[..first_space].trim();
let arg = &line[first_space..].trim();
tx.send(CommandToRun {
name: command.to_string(),
arg: arg.to_string(),
})
.await?;
} else if !line.trim().is_empty() {
// All slash-commands currently supported in context inference need a space for the argument.
log::warn!(
"Context inference returned a non-blank line that contained no spaces (meaning no argument for the slash command): {:?}",
line
);
}
}
anyhow::Ok(())
})
.collect::<Vec<_>>();
let _ = futures::future::try_join_all(futures).await.log_err();
let duration = all_start.elapsed();
eprintln!("All futures completed in {:?}", duration);
})
.await;
drop(tx); // Close the channel so that rx.collect() won't hang. This is safe because all futures have completed.
let results = rx.collect::<Vec<_>>().await;
eprintln!(
"Finished collecting from the channel with {} results",
results.len()
);
for command in results {
// Don't return empty or duplicate commands
if !command.name.is_empty()
&& !final_response
.iter()
.any(|cmd: &CommandToRun| cmd.name == command.name && cmd.arg == command.arg)
{
if SUPPORTED_SLASH_COMMANDS
.iter()
.any(|supported| &command.name == supported)
{
final_response.push(command);
} else {
log::warn!(
"Context inference returned an unrecognized slash command: {:?}",
command
);
}
}
}
// Sort the commands by name (reversed just so that /search appears before /file)
final_response.sort_by(|cmd1, cmd2| cmd1.name.cmp(&cmd2.name).reverse());
Ok(final_response)
}

View File

@@ -193,11 +193,11 @@ impl SlashCommand for DiagnosticsSlashCommand {
.map(|(range, placeholder_type)| SlashCommandOutputSection {
range,
icon: match placeholder_type {
PlaceholderType::Root(_, _) => IconName::ExclamationTriangle,
PlaceholderType::Root(_, _) => IconName::Warning,
PlaceholderType::File(_) => IconName::File,
PlaceholderType::Diagnostic(DiagnosticType::Error, _) => IconName::XCircle,
PlaceholderType::Diagnostic(DiagnosticType::Warning, _) => {
IconName::ExclamationTriangle
IconName::Warning
}
},
label: match placeholder_type {

View File

@@ -0,0 +1,24 @@
Actions have a cost, so only include actions that you think
will be helpful to you in doing a great job answering the
prompt in the future.
You must respond ONLY with a list of actions you would like to
perform. Each action should be on its own line, and followed by a space and then its parameter.
Actions can be performed more than once with different parameters.
Here is an example valid response:
```
file path/to/my/file.txt
file path/to/another/file.txt
search something to search for
search something else to search for
```
Once again, do not forget: you must respond ONLY in the format of
one action per line, and the action name should be followed by
its parameter. Your response must not include anything other
than a list of actions, with one action per line, in this format.
It is extremely important that you do not deviate from this format even slightly!
This is the end of my instructions for how to respond. The rest is the prompt:

View File

@@ -0,0 +1,31 @@
I'm going to give you a prompt. I don't want you to respond
to the prompt itself. I want you to figure out which of the following
actions on my project, if any, would help you answer the prompt.
Here are the actions:
## file
This action's parameter is a file path to one of the files
in the project. If you ask for this action, I will tell you
the full contents of the file, so you can learn all the
details of the file.
## search
This action's parameter is a string to do a semantic search for
across the files in the project. (You will have a JSON summary
of all the files in the project.) It will tell you which files this string
(or similar strings; it is a semantic search) appear in,
as well as some context of the lines surrounding each result.
It's very important that you only use this action when you think
that searching across the specific files in this project for the query
in question will be useful. For example, don't use this command to search
for queries you might put into a general Web search engine, because those
will be too general to give useful results in this project-specific search.
---
That was the end of the list of actions.
Here is a JSON summary of each of the files in my project:

View File

@@ -8,7 +8,7 @@ use assistant_slash_command::{ArgumentCompletion, SlashCommandOutputSection};
use feature_flags::FeatureFlag;
use gpui::{AppContext, Task, WeakView};
use language::{CodeLabel, LineEnding, LspAdapterDelegate};
use semantic_index::SemanticIndex;
use semantic_index::SemanticDb;
use std::{
fmt::Write,
path::PathBuf,
@@ -92,8 +92,11 @@ impl SlashCommand for SearchSlashCommand {
let project = workspace.read(cx).project().clone();
let fs = project.read(cx).fs().clone();
let project_index =
cx.update_global(|index: &mut SemanticIndex, cx| index.project_index(project, cx));
let Some(project_index) =
cx.update_global(|index: &mut SemanticDb, cx| index.project_index(project, cx))
else {
return Task::ready(Err(anyhow::anyhow!("no project indexer")));
};
cx.spawn(|cx| async move {
let results = project_index

View File

@@ -585,7 +585,7 @@ impl Render for PromptEditor {
.gap_2()
.child(ModelSelector::new(
self.fs.clone(),
IconButton::new("context", IconName::SlidersAlt)
IconButton::new("context", IconName::SettingsAlt)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.icon_color(Color::Muted)

View File

@@ -116,30 +116,27 @@ impl Drop for MacOsUnmounter {
}
}
/// Whether or not to automatically check for updates.
#[derive(Clone, Copy, JsonSchema, Deserialize, Serialize)]
#[serde(default)]
#[serde(transparent)]
struct AutoUpdateSetting(bool);
impl Default for AutoUpdateSetting {
fn default() -> Self {
Self(true)
}
}
/// Whether or not to automatically check for updates.
///
/// Default: true
#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
#[serde(transparent)]
struct AutoUpdateSettingContent(bool);
impl Settings for AutoUpdateSetting {
const KEY: Option<&'static str> = Some("auto_update");
type FileContent = Self;
type FileContent = Option<AutoUpdateSettingContent>;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
let auto_update = [sources.release_channel, sources.user]
.into_iter()
.find_map(|value| value.copied())
.unwrap_or(*sources.default);
.find_map(|value| value.copied().flatten())
.unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
Ok(auto_update)
Ok(Self(auto_update.0))
}
}

View File

@@ -4,20 +4,30 @@ use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
/// Configuration of voice calls in Zed.
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
#[serde(default)]
#[derive(Deserialize, Debug)]
pub struct CallSettings {
/// Whether the microphone should be muted when joining a channel or a call.
pub mute_on_join: bool,
/// Whether your current project should be shared when joining an empty channel.
pub share_on_join: bool,
}
/// Configuration of voice calls in Zed.
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct CallSettingsContent {
/// Whether the microphone should be muted when joining a channel or a call.
///
/// Default: false
pub mute_on_join: Option<bool>,
/// Whether your current project should be shared when joining an empty channel.
///
/// Default: true
pub share_on_join: Option<bool>,
}
impl Settings for CallSettings {
const KEY: Option<&'static str> = Some("calls");
type FileContent = Self;
type FileContent = CallSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
sources.json_merge()

View File

@@ -99,26 +99,20 @@ pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(20);
actions!(client, [SignIn, SignOut, Reconnect]);
#[derive(Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct ClientSettings {
/// The server to connect to. If the environment variable
/// ZED_SERVER_URL is set, it will override this setting.
pub server_url: String,
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ClientSettingsContent {
server_url: Option<String>,
}
impl Default for ClientSettings {
fn default() -> Self {
Self {
server_url: "https://zed.dev".to_owned(),
}
}
#[derive(Deserialize)]
pub struct ClientSettings {
pub server_url: String,
}
impl Settings for ClientSettings {
const KEY: Option<&'static str> = None;
type FileContent = Self;
type FileContent = ClientSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
let mut result = sources.json_merge::<Self>()?;
@@ -130,37 +124,19 @@ impl Settings for ClientSettings {
}
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct ProxySettings {
/// Set a proxy to use. The proxy protocol is specified by the URI scheme.
///
/// Supported URI scheme: `http`, `https`, `socks4`, `socks4a`, `socks5`,
/// `socks5h`. `http` will be used when no scheme is specified.
///
/// By default no proxy will be used, or Zed will try get proxy settings from
/// environment variables.
///
/// Examples:
/// - "proxy": "socks5://localhost:10808"
/// - "proxy": "http://127.0.0.1:10809"
#[schemars(example = "Self::example_1")]
#[schemars(example = "Self::example_2")]
pub proxy: Option<String>,
pub struct ProxySettingsContent {
proxy: Option<String>,
}
impl ProxySettings {
fn example_1() -> String {
"http://127.0.0.1:10809".to_owned()
}
fn example_2() -> String {
"socks5://localhost:10808".to_owned()
}
#[derive(Deserialize, Default)]
pub struct ProxySettings {
pub proxy: Option<String>,
}
impl Settings for ProxySettings {
const KEY: Option<&'static str> = None;
type FileContent = Self;
type FileContent = ProxySettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
Ok(Self {

View File

@@ -149,16 +149,16 @@ spec:
secretKeyRef:
name: google-ai
key: api_key
- name: QWEN2_7B_API_KEY
- name: RUNPOD_API_KEY
valueFrom:
secretKeyRef:
name: hugging-face
name: runpod
key: api_key
- name: QWEN2_7B_API_URL
- name: RUNPOD_API_SUMMARY_URL
valueFrom:
secretKeyRef:
name: hugging-face
key: qwen2_api_url
name: runpod
key: summary
- name: BLOB_STORE_ACCESS_KEY
valueFrom:
secretKeyRef:

View File

@@ -728,6 +728,11 @@ impl Database {
is_ignored: db_entry.is_ignored,
is_external: db_entry.is_external,
git_status: db_entry.git_status.map(|status| status as i32),
// This is only used in the summarization backlog, so if it's None,
// that just means we won't be able to detect when to resummarize
// based on total number of backlogged bytes - instead, we'd go
// on number of files only. That shouldn't be a huge deal in practice.
size: None,
is_fifo: db_entry.is_fifo,
});
}

View File

@@ -663,6 +663,11 @@ impl Database {
is_ignored: db_entry.is_ignored,
is_external: db_entry.is_external,
git_status: db_entry.git_status.map(|status| status as i32),
// This is only used in the summarization backlog, so if it's None,
// that just means we won't be able to detect when to resummarize
// based on total number of backlogged bytes - instead, we'd go
// on number of files only. That shouldn't be a huge deal in practice.
size: None,
is_fifo: db_entry.is_fifo,
});
}

View File

@@ -170,8 +170,8 @@ pub struct Config {
pub anthropic_api_key: Option<Arc<str>>,
pub anthropic_staff_api_key: Option<Arc<str>>,
pub llm_closed_beta_model_name: Option<Arc<str>>,
pub qwen2_7b_api_key: Option<Arc<str>>,
pub qwen2_7b_api_url: Option<Arc<str>>,
pub runpod_api_key: Option<Arc<str>>,
pub runpod_api_summary_url: Option<Arc<str>>,
pub zed_client_checksum_seed: Option<String>,
pub slack_panics_webhook: Option<String>,
pub auto_join_channel_id: Option<ChannelId>,
@@ -235,8 +235,8 @@ impl Config {
stripe_api_key: None,
stripe_price_id: None,
supermaven_admin_api_key: None,
qwen2_7b_api_key: None,
qwen2_7b_api_url: None,
runpod_api_key: None,
runpod_api_summary_url: None,
user_backfiller_github_access_token: None,
}
}

View File

@@ -402,12 +402,12 @@ async fn perform_completion(
LanguageModelProvider::Zed => {
let api_key = state
.config
.qwen2_7b_api_key
.runpod_api_key
.as_ref()
.context("no Qwen2-7B API key configured on the server")?;
let api_url = state
.config
.qwen2_7b_api_url
.runpod_api_summary_url
.as_ref()
.context("no Qwen2-7B URL configured on the server")?;
let chunks = open_ai::stream_completion(

View File

@@ -1,5 +1,5 @@
use super::*;
use sea_orm::QueryOrder;
use sea_orm::{sea_query::OnConflict, QueryOrder};
use std::str::FromStr;
use strum::IntoEnumIterator as _;
@@ -99,6 +99,17 @@ impl LlmDatabase {
..Default::default()
}
}))
.on_conflict(
OnConflict::columns([model::Column::ProviderId, model::Column::Name])
.update_columns([
model::Column::MaxRequestsPerMinute,
model::Column::MaxTokensPerMinute,
model::Column::MaxTokensPerDay,
model::Column::PricePerMillionInputTokens,
model::Column::PricePerMillionOutputTokens,
])
.to_owned(),
)
.exec_without_returning(&*tx)
.await?;
Ok(())

View File

@@ -40,6 +40,15 @@ pub async fn seed_database(_config: &Config, db: &mut LlmDatabase, _force: bool)
price_per_million_input_tokens: 25, // $0.25/MTok
price_per_million_output_tokens: 125, // $1.25/MTok
},
ModelParams {
provider: LanguageModelProvider::Zed,
name: "Qwen/Qwen2-7B-Instruct".into(),
max_requests_per_minute: 5,
max_tokens_per_minute: 25_000, // These are arbitrary limits we've set to cap costs; we control this number
max_tokens_per_day: 300_000,
price_per_million_input_tokens: 25,
price_per_million_output_tokens: 125,
},
])
.await
}

View File

@@ -2261,11 +2261,11 @@ async fn test_git_blame_is_forwarded(cx_a: &mut TestAppContext, cx_b: &mut TestA
cx_a.update(editor::init);
cx_b.update(editor::init);
// Turn inline-blame-off by default so no state is transferred without us explicitly doing so
let inline_blame_off_settings = InlineBlameSettings {
let inline_blame_off_settings = Some(InlineBlameSettings {
enabled: false,
delay_ms: 0,
min_column: 0,
};
delay_ms: None,
min_column: None,
});
cx_a.update(|cx| {
SettingsStore::update_global(cx, |store, cx| {
store.update_user_settings::<ProjectSettings>(cx, |settings| {

View File

@@ -1649,7 +1649,7 @@ async fn test_following_into_excluded_file(
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|store, cx| {
store.update_user_settings::<WorktreeSettings>(cx, |settings| {
settings.file_scan_exclusions = vec!["**/.git".to_string()];
settings.file_scan_exclusions = Some(vec!["**/.git".to_string()]);
});
});
});

View File

@@ -679,8 +679,8 @@ impl TestServer {
stripe_api_key: None,
stripe_price_id: None,
supermaven_admin_api_key: None,
qwen2_7b_api_key: None,
qwen2_7b_api_url: None,
runpod_api_key: None,
runpod_api_summary_url: None,
user_backfiller_github_access_token: None,
},
})

View File

@@ -1108,7 +1108,7 @@ impl Panel for ChatPanel {
settings::update_settings_file::<ChatPanelSettings>(
self.fs.clone(),
cx,
move |settings, _| settings.dock = position,
move |settings, _| settings.dock = Some(position),
);
}

View File

@@ -113,7 +113,9 @@ impl MessageEditor {
editor.set_show_indent_guides(false, cx);
editor.set_completion_provider(Box::new(MessageEditorCompletionProvider(this)));
editor.set_auto_replace_emoji_shortcode(
MessageEditorSettings::get_global(cx).auto_replace_emoji_shortcode,
MessageEditorSettings::get_global(cx)
.auto_replace_emoji_shortcode
.unwrap_or_default(),
);
});
@@ -128,7 +130,9 @@ impl MessageEditor {
cx.observe_global::<settings::SettingsStore>(|view, cx| {
view.editor.update(cx, |editor, cx| {
editor.set_auto_replace_emoji_shortcode(
MessageEditorSettings::get_global(cx).auto_replace_emoji_shortcode,
MessageEditorSettings::get_global(cx)
.auto_replace_emoji_shortcode
.unwrap_or_default(),
)
})
})

View File

@@ -2813,7 +2813,7 @@ impl Panel for CollabPanel {
settings::update_settings_file::<CollaborationPanelSettings>(
self.fs.clone(),
cx,
move |settings, _| settings.dock = position,
move |settings, _| settings.dock = Some(position),
);
}
@@ -2831,7 +2831,7 @@ impl Panel for CollabPanel {
fn icon(&self, cx: &gpui::WindowContext) -> Option<ui::IconName> {
CollaborationPanelSettings::get_global(cx)
.button
.then_some(ui::IconName::Collab)
.then_some(ui::IconName::UserGroup)
}
fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {

View File

@@ -672,7 +672,7 @@ impl Panel for NotificationPanel {
settings::update_settings_file::<NotificationPanelSettings>(
self.fs.clone(),
cx,
move |settings, _| settings.dock = position,
move |settings, _| settings.dock = Some(position),
);
}

View File

@@ -2,84 +2,58 @@ use gpui::Pixels;
use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
use ui::px;
use workspace::dock::DockPosition;
#[derive(Clone, Deserialize, Debug, JsonSchema, Serialize)]
#[serde(default)]
#[derive(Deserialize, Debug)]
pub struct CollaborationPanelSettings {
/// Whether to show the panel button in the status bar.
pub button: bool,
/// Where to dock the panel.
pub dock: DockPosition,
/// Default width of the panel in pixels.
pub default_width: Pixels,
}
impl Default for CollaborationPanelSettings {
fn default() -> Self {
Self {
button: true,
dock: DockPosition::Left,
default_width: px(240.),
}
}
}
#[derive(Clone, Deserialize, Debug, JsonSchema, Serialize)]
#[serde(default)]
#[derive(Deserialize, Debug)]
pub struct ChatPanelSettings {
/// Whether to show the panel button in the status bar.
pub button: bool,
/// Where to dock the panel.
pub dock: DockPosition,
/// Default width of the panel in pixels.
pub default_width: Pixels,
}
impl Default for ChatPanelSettings {
fn default() -> Self {
Self {
button: true,
dock: DockPosition::Right,
default_width: px(240.),
}
}
}
#[derive(Clone, Deserialize, Debug, JsonSchema, Serialize)]
#[serde(default)]
#[derive(Deserialize, Debug)]
pub struct NotificationPanelSettings {
/// Whether to show the panel button in the status bar.
pub button: bool,
/// Where to dock the panel.
pub dock: DockPosition,
/// Default width of the panel in pixels.
pub default_width: Pixels,
}
impl Default for NotificationPanelSettings {
fn default() -> Self {
Self {
button: true,
dock: DockPosition::Right,
default_width: px(380.),
}
}
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
#[serde(default)]
pub struct PanelSettingsContent {
/// Whether to show the panel button in the status bar.
///
/// Default: true
pub button: Option<bool>,
/// Where to dock the panel.
///
/// Default: left
pub dock: Option<DockPosition>,
/// Default width of the panel in pixels.
///
/// Default: 240
pub default_width: Option<f32>,
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct MessageEditorSettings {
/// Whether to automatically replace emoji shortcodes with emoji characters.
/// For example: typing `:wave:` gets replaced with `👋`.
pub auto_replace_emoji_shortcode: bool,
///
/// Default: false
pub auto_replace_emoji_shortcode: Option<bool>,
}
impl Settings for CollaborationPanelSettings {
const KEY: Option<&'static str> = Some("collaboration_panel");
type FileContent = Self;
type FileContent = PanelSettingsContent;
fn load(
sources: SettingsSources<Self::FileContent>,
@@ -92,7 +66,7 @@ impl Settings for CollaborationPanelSettings {
impl Settings for ChatPanelSettings {
const KEY: Option<&'static str> = Some("chat_panel");
type FileContent = Self;
type FileContent = PanelSettingsContent;
fn load(
sources: SettingsSources<Self::FileContent>,
@@ -105,7 +79,7 @@ impl Settings for ChatPanelSettings {
impl Settings for NotificationPanelSettings {
const KEY: Option<&'static str> = Some("notification_panel");
type FileContent = Self;
type FileContent = PanelSettingsContent;
fn load(
sources: SettingsSources<Self::FileContent>,
@@ -118,7 +92,7 @@ impl Settings for NotificationPanelSettings {
impl Settings for MessageEditorSettings {
const KEY: Option<&'static str> = Some("message_editor");
type FileContent = Self;
type FileContent = MessageEditorSettings;
fn load(
sources: SettingsSources<Self::FileContent>,

View File

@@ -210,10 +210,9 @@ impl CommandPaletteDelegate {
positions,
}) = intercept_result
{
if let Some(idx) = matches
.iter()
.position(|m| commands[m.candidate_id].action.type_id() == action.type_id())
{
if let Some(idx) = matches.iter().position(|m| {
commands[m.candidate_id].action.action_type_id() == action.action_type_id()
}) {
matches.remove(idx);
}
commands.push(Command {

View File

@@ -2,11 +2,9 @@
#![deny(missing_docs)]
use std::any::TypeId;
use collections::HashSet;
use derive_more::{Deref, DerefMut};
use gpui::{Action, AppContext, BorrowAppContext, Global};
use gpui::{Action, ActionTypeId, AppContext, BorrowAppContext, Global};
/// Initializes the command palette hooks.
pub fn init(cx: &mut AppContext) {
@@ -18,7 +16,7 @@ pub fn init(cx: &mut AppContext) {
#[derive(Default)]
pub struct CommandPaletteFilter {
hidden_namespaces: HashSet<&'static str>,
hidden_action_types: HashSet<TypeId>,
hidden_action_types: HashSet<ActionTypeId>,
}
#[derive(Deref, DerefMut, Default)]
@@ -52,7 +50,7 @@ impl CommandPaletteFilter {
let namespace = name.split("::").next().unwrap_or("malformed action name");
self.hidden_namespaces.contains(namespace)
|| self.hidden_action_types.contains(&action.type_id())
|| self.hidden_action_types.contains(&action.action_type_id())
}
/// Hides all actions in the given namespace.
@@ -66,12 +64,13 @@ impl CommandPaletteFilter {
}
/// Hides all actions with the given types.
pub fn hide_action_types(&mut self, action_types: &[TypeId]) {
self.hidden_action_types.extend(action_types);
pub fn hide_action_types(&mut self, action_types: &[ActionTypeId]) {
self.hidden_action_types
.extend(action_types.iter().cloned());
}
/// Shows all actions with the given types.
pub fn show_action_types<'a>(&mut self, action_types: impl Iterator<Item = &'a TypeId>) {
pub fn show_action_types<'a>(&mut self, action_types: impl Iterator<Item = &'a ActionTypeId>) {
for action_type in action_types {
self.hidden_action_types.remove(action_type);
}

View File

@@ -11,8 +11,8 @@ use collections::{HashMap, HashSet};
use command_palette_hooks::CommandPaletteFilter;
use futures::{channel::oneshot, future::Shared, Future, FutureExt, TryFutureExt};
use gpui::{
actions, AppContext, AsyncAppContext, Context, Entity, EntityId, EventEmitter, Global, Model,
ModelContext, Task, WeakModel,
actions, ActionTypeId, AppContext, AsyncAppContext, Context, Entity, EntityId, EventEmitter,
Global, Model, ModelContext, Task, WeakModel,
};
use http_client::github::latest_github_release;
use http_client::HttpClient;
@@ -69,13 +69,13 @@ pub fn init(
Copilot::set_global(copilot.clone(), cx);
cx.observe(&copilot, |handle, cx| {
let copilot_action_types = [
TypeId::of::<Suggest>(),
TypeId::of::<NextSuggestion>(),
TypeId::of::<PreviousSuggestion>(),
TypeId::of::<Reinstall>(),
ActionTypeId::of::<Suggest>(),
ActionTypeId::of::<NextSuggestion>(),
ActionTypeId::of::<PreviousSuggestion>(),
ActionTypeId::of::<Reinstall>(),
];
let copilot_auth_action_types = [TypeId::of::<SignOut>()];
let copilot_no_auth_action_types = [TypeId::of::<SignIn>()];
let copilot_auth_action_types = [ActionTypeId::of::<SignOut>()];
let copilot_no_auth_action_types = [ActionTypeId::of::<SignIn>()];
let status = handle.read(cx).status();
let filter = CommandPaletteFilter::global_mut(cx);

View File

@@ -1,10 +1,10 @@
use crate::{request::PromptUserDeviceFlow, Copilot, Status};
use gpui::{
div, svg, AppContext, ClipboardItem, DismissEvent, Element, EventEmitter, FocusHandle,
div, AppContext, ClipboardItem, DismissEvent, Element, EventEmitter, FocusHandle,
FocusableView, InteractiveElement, IntoElement, Model, MouseDownEvent, ParentElement, Render,
Styled, Subscription, ViewContext,
};
use ui::{prelude::*, Button, IconName, Label};
use ui::{prelude::*, Button, Label, Vector, VectorName};
use workspace::ModalView;
const COPILOT_SIGN_UP_URL: &str = "https://github.com/features/copilot";
@@ -198,12 +198,8 @@ impl Render for CopilotCodeVerification {
cx.focus(&this.focus_handle);
}))
.child(
svg()
.w_32()
.h_16()
.flex_none()
.path(IconName::ZedXCopilot.path())
.text_color(cx.theme().colors().icon),
Vector::new(VectorName::ZedXCopilot, rems(8.), rems(4.))
.color(Color::Custom(cx.theme().colors().icon)),
)
.child(prompt)
}

View File

@@ -667,7 +667,7 @@ impl Item for ProjectDiagnosticsEditor {
then.child(
h_flex()
.gap_1()
.child(Icon::new(IconName::ExclamationTriangle).color(Color::Warning))
.child(Icon::new(IconName::Warning).color(Color::Warning))
.child(
Label::new(self.summary.warning_count.to_string())
.color(params.text_color()),
@@ -804,7 +804,7 @@ fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
icon.path(IconName::XCircle.path())
.text_color(Color::Error.color(cx))
} else {
icon.path(IconName::ExclamationTriangle.path())
icon.path(IconName::Warning.path())
.text_color(Color::Warning.color(cx))
}
}),

View File

@@ -30,7 +30,7 @@ impl Render for DiagnosticIndicator {
(0, warning_count) => h_flex()
.gap_1()
.child(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.color(Color::Warning),
)
@@ -52,7 +52,7 @@ impl Render for DiagnosticIndicator {
)
.child(Label::new(error_count.to_string()).size(LabelSize::Small))
.child(
Icon::new(IconName::ExclamationTriangle)
Icon::new(IconName::Warning)
.size(IconSize::Small)
.color(Color::Warning),
)

View File

@@ -4,25 +4,23 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
#[derive(Clone, Serialize, Deserialize, JsonSchema, Debug)]
#[serde(default)]
/// Diagnostics configuration.
#[derive(Deserialize, Debug)]
pub struct ProjectDiagnosticsSettings {
/// Whether to show warnings or not by default.
pub include_warnings: bool,
}
impl Default for ProjectDiagnosticsSettings {
fn default() -> Self {
Self {
include_warnings: true,
}
}
/// Diagnostics configuration.
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct ProjectDiagnosticsSettingsContent {
/// Whether to show warnings or not by default.
///
/// Default: true
include_warnings: Option<bool>,
}
impl Settings for ProjectDiagnosticsSettings {
const KEY: Option<&'static str> = Some("diagnostics");
type FileContent = Self;
type FileContent = ProjectDiagnosticsSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
sources.json_merge()

View File

@@ -50,7 +50,7 @@ impl Render for ToolbarControls {
)
})
.child(
IconButton::new("toggle-warnings", IconName::ExclamationTriangle)
IconButton::new("toggle-warnings", IconName::Warning)
.tooltip(move |cx| Tooltip::text(tooltip, cx))
.on_click(cx.listener(|this, _, cx| {
if let Some(editor) = this.editor() {

View File

@@ -35,7 +35,7 @@ chrono.workspace = true
client.workspace = true
clock.workspace = true
collections.workspace = true
convert_case = "0.6.0"
convert_case.workspace = true
db.workspace = true
emojis.workspace = true
file_icons.workspace = true

View File

@@ -72,14 +72,14 @@ use fuzzy::{StringMatch, StringMatchCandidate};
use git::blame::GitBlame;
use git::diff_hunk_to_display;
use gpui::{
div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
VisualContext, WeakFocusHandle, WeakView, WindowContext,
div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, ActionTypeId,
AnyElement, AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds,
ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter,
FocusHandle, FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla,
InteractiveText, KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement,
Pixels, Render, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
TextStyle, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext,
ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
};
use highlight_matching_bracket::refresh_matching_bracket_highlights;
use hover_popover::{hide_hover, HoverState};
@@ -128,6 +128,7 @@ use serde::{Deserialize, Serialize};
use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
use smallvec::SmallVec;
use snippet::Snippet;
use std::any::Any;
use std::{
any::TypeId,
borrow::Cow,
@@ -4975,9 +4976,10 @@ impl Editor {
let cursor = self.selections.newest_anchor().head();
let (buffer, cursor_buffer_position) =
self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
if !user_requested
&& self.enable_inline_completions
&& !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
&& (!self.enable_inline_completions
|| !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
{
self.discard_inline_completion(false, cx);
return None;
@@ -6670,7 +6672,11 @@ impl Editor {
let is_entire_line = selection.is_empty() || self.selections.line_mode;
if is_entire_line {
selection.start = Point::new(selection.start.row, 0);
selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
if !selection.is_empty() && selection.end.column == 0 {
selection.end = cmp::min(max_point, selection.end);
} else {
selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
}
selection.goal = SelectionGoal::None;
}
if is_first {
@@ -10639,7 +10645,7 @@ impl Editor {
let fs = workspace.read(cx).app_state().fs.clone();
let current_show = TabBarSettings::get_global(cx).show;
update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
setting.show = !current_show;
setting.show = Some(!current_show);
});
}
@@ -12046,10 +12052,12 @@ impl Editor {
cx.notify();
}
pub fn register_action<A: Action>(
pub fn register_runtime_action(
&mut self,
listener: impl Fn(&A, &mut WindowContext) + 'static,
action_type_id: ActionTypeId,
listener: impl Fn(&dyn Any, &mut WindowContext) + 'static,
) -> Subscription {
dbg!("register runtime action", action_type_id.clone());
let id = self.next_editor_action_id.post_inc();
let listener = Arc::new(listener);
self.editor_actions.borrow_mut().insert(
@@ -12057,8 +12065,8 @@ impl Editor {
Box::new(move |cx| {
let cx = cx.window_context();
let listener = listener.clone();
cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
let action = action.downcast_ref().unwrap();
cx.on_action(action_type_id.clone(), move |action, phase, cx| {
eprintln!("Action fired; phase is {phase:?}");
if phase == DispatchPhase::Bubble {
listener(action, cx)
}
@@ -12072,6 +12080,16 @@ impl Editor {
})
}
pub fn register_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut WindowContext) + 'static,
) -> Subscription {
self.register_runtime_action(ActionTypeId::of::<A>(), move |action, cx| {
let action = action.downcast_ref().unwrap();
listener(action, cx)
})
}
pub fn file_header_size(&self) -> u32 {
self.file_header_size
}
@@ -12562,7 +12580,7 @@ impl EditorSnapshot {
let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
matches!(
ProjectSettings::get_global(cx).git.git_gutter,
GitGutterSetting::TrackedFiles
Some(GitGutterSetting::TrackedFiles)
)
});
let gutter_settings = EditorSettings::get_global(cx).gutter;

View File

@@ -3,105 +3,38 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
#[derive(Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
#[derive(Deserialize, Clone)]
pub struct EditorSettings {
/// Whether the cursor blinks in the editor.
pub cursor_blink: bool,
/// How to highlight the current line in the editor.
pub current_line_highlight: CurrentLineHighlight,
/// Whether to show the informational hover box when moving the mouse
/// over symbols in the editor.
pub hover_popover_enabled: bool,
/// Whether to pop the completions menu while typing in an editor without
/// explicitly requesting it.
pub show_completions_on_input: bool,
/// Whether to display inline and alongside documentation for items in the
/// completions menu.
pub show_completion_documentation: bool,
/// The debounce delay before re-querying the language server for completion
/// documentation when not included in original completion list.
pub completion_documentation_secondary_query_debounce: u64,
/// Whether to use additional LSP queries to format (and amend) the code after
/// every "trigger" symbol input, defined by LSP server capabilities.
pub use_on_type_format: bool,
/// Toolbar related settings
pub toolbar: Toolbar,
/// Scrollbar related settings
pub scrollbar: Scrollbar,
/// Gutter related settings
pub gutter: Gutter,
/// Whether the editor will scroll beyond the last line.
pub scroll_beyond_last_line: ScrollBeyondLastLine,
/// The number of lines to keep above/below the cursor when auto-scrolling.
pub vertical_scroll_margin: f32,
/// Scroll sensitivity multiplier. This multiplier is applied
/// to both the horizontal and vertical delta values while scrolling.
pub scroll_sensitivity: f32,
/// Whether the line numbers on editors gutter are relative or not.
pub relative_line_numbers: bool,
/// When to populate a new search's query based on the text under the cursor.
pub seed_search_query_from_cursor: SeedQuerySetting,
pub use_smartcase_search: bool,
/// The key to use for adding multiple cursors
pub multi_cursor_modifier: MultiCursorModifier,
/// Hide the values of variables in `private` files, as defined by the
/// private_files setting. This only changes the visual representation,
/// the values are still present in the file and can be selected / copied / pasted
pub redact_private_values: bool,
/// How many lines to expand the multibuffer excerpts by default
pub expand_excerpt_lines: u32,
pub middle_click_paste: bool,
/// What to do when multibuffer is double clicked in some of its excerpts
/// (parts of singleton buffers).
#[serde(default)]
pub double_click_in_multibuffer: DoubleClickInMultibuffer,
/// Whether the editor search results will loop
pub search_wrap: bool,
#[serde(default)]
pub search: SearchSettings,
/// Show method signatures in the editor, when inside parentheses.
pub auto_signature_help: bool,
/// Whether to show the signature help after completion or a bracket pair inserted.
/// If `auto_signature_help` is enabled, this setting will be treated as enabled also.
pub show_signature_help_after_edits: bool,
/// Jupyter REPL settings.
pub jupyter: Jupyter,
}
impl Default for EditorSettings {
fn default() -> Self {
Self {
cursor_blink: true,
current_line_highlight: CurrentLineHighlight::All,
hover_popover_enabled: true,
show_completions_on_input: true,
show_completion_documentation: true,
completion_documentation_secondary_query_debounce: 300,
use_on_type_format: true,
toolbar: Default::default(),
scrollbar: Default::default(),
gutter: Default::default(),
scroll_beyond_last_line: ScrollBeyondLastLine::OnePage,
vertical_scroll_margin: 3.,
scroll_sensitivity: 1.0,
relative_line_numbers: false,
seed_search_query_from_cursor: SeedQuerySetting::Always,
multi_cursor_modifier: MultiCursorModifier::Alt,
redact_private_values: false,
expand_excerpt_lines: 3,
double_click_in_multibuffer: DoubleClickInMultibuffer::Select,
search_wrap: true,
auto_signature_help: false,
show_signature_help_after_edits: true,
jupyter: Default::default(),
use_smartcase_search: false,
middle_click_paste: true,
search: SearchSettings::default(),
}
}
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CurrentLineHighlight {
@@ -139,93 +72,48 @@ pub enum DoubleClickInMultibuffer {
Open,
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[derive(Debug, Clone, Deserialize)]
pub struct Jupyter {
/// Whether the Jupyter feature is enabled.
///
/// Default: true
pub enabled: bool,
}
impl Default for Jupyter {
fn default() -> Self {
Self { enabled: true }
}
#[derive(Default, Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct JupyterContent {
/// Whether the Jupyter feature is enabled.
///
/// Default: true
pub enabled: Option<bool>,
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(default)]
pub struct Toolbar {
/// Whether to display breadcrumbs in the editor toolbar.
pub breadcrumbs: bool,
/// Whether to display quick action buttons in the editor toolbar.
pub quick_actions: bool,
/// Whether to show the selections menu in the editor toolbar
pub selections_menu: bool,
}
impl Default for Toolbar {
fn default() -> Self {
Self {
breadcrumbs: true,
quick_actions: true,
selections_menu: true,
}
}
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct Scrollbar {
/// When to show the scrollbar in the editor.
pub show: ShowScrollbar,
/// Whether to show git diff indicators in the scrollbar.
pub git_diff: bool,
/// Whether to show buffer search result indicators in the scrollbar.
pub selected_symbol: bool,
/// Whether to show selected symbol occurrences in the scrollbar.
pub search_results: bool,
/// Whether to show diagnostic indicators in the scrollbar.
pub diagnostics: bool,
/// Whether to show cursor positions in the scrollbar.
pub cursors: bool,
}
impl Default for Scrollbar {
fn default() -> Self {
Self {
show: ShowScrollbar::Auto,
git_diff: true,
selected_symbol: true,
search_results: true,
diagnostics: true,
cursors: true,
}
}
}
/// Gutter-related settings.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(default)]
pub struct Gutter {
/// Whether to show line numbers in the gutter.
pub line_numbers: bool,
/// Whether to show code action buttons in the gutter.
pub code_actions: bool,
/// Whether to show runnable buttons in the gutter.
pub runnables: bool,
/// Whether to show fold buttons in the gutter.
pub folds: bool,
}
impl Default for Gutter {
fn default() -> Self {
Self {
line_numbers: true,
code_actions: true,
runnables: true,
folds: true,
}
}
}
/// When to show the scrollbar in the editor.
///
/// Default: auto
@@ -283,6 +171,188 @@ pub struct SearchSettings {
pub regex: bool,
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct EditorSettingsContent {
/// Whether the cursor blinks in the editor.
///
/// Default: true
pub cursor_blink: Option<bool>,
/// How to highlight the current line in the editor.
///
/// Default: all
pub current_line_highlight: Option<CurrentLineHighlight>,
/// Whether to show the informational hover box when moving the mouse
/// over symbols in the editor.
///
/// Default: true
pub hover_popover_enabled: Option<bool>,
/// Whether to pop the completions menu while typing in an editor without
/// explicitly requesting it.
///
/// Default: true
pub show_completions_on_input: Option<bool>,
/// Whether to display inline and alongside documentation for items in the
/// completions menu.
///
/// Default: true
pub show_completion_documentation: Option<bool>,
/// The debounce delay before re-querying the language server for completion
/// documentation when not included in original completion list.
///
/// Default: 300 ms
pub completion_documentation_secondary_query_debounce: Option<u64>,
/// Whether to use additional LSP queries to format (and amend) the code after
/// every "trigger" symbol input, defined by LSP server capabilities.
///
/// Default: true
pub use_on_type_format: Option<bool>,
/// Toolbar related settings
pub toolbar: Option<ToolbarContent>,
/// Scrollbar related settings
pub scrollbar: Option<ScrollbarContent>,
/// Gutter related settings
pub gutter: Option<GutterContent>,
/// Whether the editor will scroll beyond the last line.
///
/// Default: one_page
pub scroll_beyond_last_line: Option<ScrollBeyondLastLine>,
/// The number of lines to keep above/below the cursor when auto-scrolling.
///
/// Default: 3.
pub vertical_scroll_margin: Option<f32>,
/// Scroll sensitivity multiplier. This multiplier is applied
/// to both the horizontal and vertical delta values while scrolling.
///
/// Default: 1.0
pub scroll_sensitivity: Option<f32>,
/// Whether the line numbers on editors gutter are relative or not.
///
/// Default: false
pub relative_line_numbers: Option<bool>,
/// When to populate a new search's query based on the text under the cursor.
///
/// Default: always
pub seed_search_query_from_cursor: Option<SeedQuerySetting>,
pub use_smartcase_search: Option<bool>,
/// The key to use for adding multiple cursors
///
/// Default: alt
pub multi_cursor_modifier: Option<MultiCursorModifier>,
/// Hide the values of variables in `private` files, as defined by the
/// private_files setting. This only changes the visual representation,
/// the values are still present in the file and can be selected / copied / pasted
///
/// Default: false
pub redact_private_values: Option<bool>,
/// How many lines to expand the multibuffer excerpts by default
///
/// Default: 3
pub expand_excerpt_lines: Option<u32>,
/// Whether to enable middle-click paste on Linux
///
/// Default: true
pub middle_click_paste: Option<bool>,
/// What to do when multibuffer is double clicked in some of its excerpts
/// (parts of singleton buffers).
///
/// Default: select
pub double_click_in_multibuffer: Option<DoubleClickInMultibuffer>,
/// Whether the editor search results will loop
///
/// Default: true
pub search_wrap: Option<bool>,
/// Defaults to use when opening a new buffer and project search items.
///
/// Default: nothing is enabled
pub search: Option<SearchSettings>,
/// Whether to automatically show a signature help pop-up or not.
///
/// Default: false
pub auto_signature_help: Option<bool>,
/// Whether to show the signature help pop-up after completions or bracket pairs inserted.
///
/// Default: true
pub show_signature_help_after_edits: Option<bool>,
/// Jupyter REPL settings.
pub jupyter: Option<JupyterContent>,
}
// Toolbar related settings
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ToolbarContent {
/// Whether to display breadcrumbs in the editor toolbar.
///
/// Default: true
pub breadcrumbs: Option<bool>,
/// Whether to display quick action buttons in the editor toolbar.
///
/// Default: true
pub quick_actions: Option<bool>,
/// Whether to show the selections menu in the editor toolbar
///
/// Default: true
pub selections_menu: Option<bool>,
}
/// Scrollbar related settings
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct ScrollbarContent {
/// When to show the scrollbar in the editor.
///
/// Default: auto
pub show: Option<ShowScrollbar>,
/// Whether to show git diff indicators in the scrollbar.
///
/// Default: true
pub git_diff: Option<bool>,
/// Whether to show buffer search result indicators in the scrollbar.
///
/// Default: true
pub search_results: Option<bool>,
/// Whether to show selected symbol occurrences in the scrollbar.
///
/// Default: true
pub selected_symbol: Option<bool>,
/// Whether to show diagnostic indicators in the scrollbar.
///
/// Default: true
pub diagnostics: Option<bool>,
/// Whether to show cursor positions in the scrollbar.
///
/// Default: true
pub cursors: Option<bool>,
}
/// Gutter related settings
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct GutterContent {
/// Whether to show line numbers in the gutter.
///
/// Default: true
pub line_numbers: Option<bool>,
/// Whether to show code action buttons in the gutter.
///
/// Default: true
pub code_actions: Option<bool>,
/// Whether to show runnable buttons in the gutter.
///
/// Default: true
pub runnables: Option<bool>,
/// Whether to show fold buttons in the gutter.
///
/// Default: true
pub folds: Option<bool>,
}
impl EditorSettings {
pub fn jupyter_enabled(cx: &AppContext) -> bool {
EditorSettings::get_global(cx).jupyter.enabled
@@ -292,7 +362,7 @@ impl EditorSettings {
impl Settings for EditorSettings {
const KEY: Option<&'static str> = None;
type FileContent = Self;
type FileContent = EditorSettingsContent;
fn load(
sources: SettingsSources<Self::FileContent>,

View File

@@ -1,7 +1,7 @@
use std::sync::Arc;
use gpui::{AppContext, FontFeatures, FontWeight};
use project::project_settings::ProjectSettings;
use project::project_settings::{InlineBlameSettings, ProjectSettings};
use settings::{EditableSettingControl, Settings};
use theme::{FontFamilyCache, ThemeSettings};
use ui::{
@@ -296,7 +296,14 @@ impl EditableSettingControl for InlineGitBlameControl {
value: Self::Value,
_cx: &AppContext,
) {
settings.git.inline_blame.enabled = value;
if let Some(inline_blame) = settings.git.inline_blame.as_mut() {
inline_blame.enabled = value;
} else {
settings.git.inline_blame = Some(InlineBlameSettings {
enabled: false,
..Default::default()
});
}
}
}
@@ -342,7 +349,14 @@ impl EditableSettingControl for LineNumbersControl {
value: Self::Value,
_cx: &AppContext,
) {
settings.gutter.line_numbers = value;
if let Some(gutter) = settings.gutter.as_mut() {
gutter.line_numbers = Some(value);
} else {
settings.gutter = Some(crate::editor_settings::GutterContent {
line_numbers: Some(value),
..Default::default()
});
}
}
}
@@ -388,7 +402,7 @@ impl EditableSettingControl for RelativeLineNumbersControl {
value: Self::Value,
_cx: &AppContext,
) {
settings.relative_line_numbers = value;
settings.relative_line_numbers = Some(value);
}
}

View File

@@ -6964,7 +6964,7 @@ async fn test_handle_input_for_show_signature_help_auto_signature_help_true(
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.auto_signature_help = true;
settings.auto_signature_help = Some(true);
});
});
});
@@ -7105,8 +7105,8 @@ async fn test_handle_input_with_different_show_signature_settings(cx: &mut gpui:
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.auto_signature_help = false;
settings.show_signature_help_after_edits = false;
settings.auto_signature_help = Some(false);
settings.show_signature_help_after_edits = Some(false);
});
});
});
@@ -7232,8 +7232,8 @@ async fn test_handle_input_with_different_show_signature_settings(cx: &mut gpui:
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.auto_signature_help = false;
settings.show_signature_help_after_edits = true;
settings.auto_signature_help = Some(false);
settings.show_signature_help_after_edits = Some(true);
});
});
});
@@ -7274,8 +7274,8 @@ async fn test_handle_input_with_different_show_signature_settings(cx: &mut gpui:
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.auto_signature_help = true;
settings.show_signature_help_after_edits = false;
settings.auto_signature_help = Some(true);
settings.show_signature_help_after_edits = Some(false);
});
});
});
@@ -7318,7 +7318,7 @@ async fn test_signature_help(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.auto_signature_help = true;
settings.auto_signature_help = Some(true);
});
});
});
@@ -7759,7 +7759,7 @@ async fn test_completion(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.show_completions_on_input = false;
settings.show_completions_on_input = Some(false);
});
})
});

View File

@@ -29,7 +29,6 @@ use crate::{
use client::ParticipantIndex;
use collections::{BTreeMap, HashMap};
use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
use gpui::Subscription;
use gpui::{
anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
@@ -40,6 +39,7 @@ use gpui::{
StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
ViewContext, WeakView, WindowContext,
};
use gpui::{ActionTypeId, Subscription};
use itertools::Itertools;
use language::{
language_settings::{
@@ -1283,7 +1283,10 @@ impl EditorElement {
.row,
);
let git_gutter_setting = ProjectSettings::get_global(cx).git.git_gutter;
let git_gutter_setting = ProjectSettings::get_global(cx)
.git
.git_gutter
.unwrap_or_default();
let display_hunks = buffer_snapshot
.git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
.map(|hunk| diff_hunk_to_display(&hunk, snapshot))
@@ -1363,10 +1366,12 @@ impl EditorElement {
};
let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
let min_column_in_pixels = self.column_pixels(
ProjectSettings::get_global(cx).git.inline_blame.min_column as usize,
cx,
);
let min_column_in_pixels = ProjectSettings::get_global(cx)
.git
.inline_blame
.and_then(|settings| settings.min_column)
.map(|col| self.column_pixels(col as usize, cx))
.unwrap_or(px(0.));
let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
cmp::max(padded_line_end, min_start)
@@ -3326,7 +3331,7 @@ impl EditorElement {
.unwrap_or_else(|| {
matches!(
ProjectSettings::get_global(cx).git.git_gutter,
GitGutterSetting::TrackedFiles
Some(GitGutterSetting::TrackedFiles)
)
});
if show_git_gutter {
@@ -6253,7 +6258,7 @@ pub fn register_action<T: Action>(
listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
) {
let view = view.clone();
cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
cx.on_action(ActionTypeId::of::<T>(), move |action, phase, cx| {
let action = action.downcast_ref().unwrap();
if phase == DispatchPhase::Bubble {
view.update(cx, |editor, cx| {

View File

@@ -713,17 +713,42 @@ pub(crate) async fn find_file(
cx: &mut AsyncWindowContext,
) -> Option<(Range<text::Anchor>, ResolvedPath)> {
let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot()).ok()?;
let scope = snapshot.language_scope_at(position);
let (range, candidate_file_path) = surrounding_filename(snapshot, position)?;
let existing_path = project
.update(cx, |project, cx| {
project.resolve_existing_file_path(&candidate_file_path, buffer, cx)
})
.ok()?
.await?;
async fn check_path(
candidate_file_path: &str,
project: &Model<Project>,
buffer: &Model<language::Buffer>,
cx: &mut AsyncWindowContext,
) -> Option<ResolvedPath> {
project
.update(cx, |project, cx| {
project.resolve_existing_file_path(&candidate_file_path, buffer, cx)
})
.ok()?
.await
}
Some((range, existing_path))
if let Some(existing_path) = check_path(&candidate_file_path, &project, buffer, cx).await {
return Some((range, existing_path));
}
if let Some(scope) = scope {
for suffix in scope.path_suffixes() {
if candidate_file_path.ends_with(format!(".{suffix}").as_str()) {
continue;
}
let suffixed_candidate = format!("{candidate_file_path}.{suffix}");
if let Some(existing_path) = check_path(&suffixed_candidate, &project, buffer, cx).await
{
return Some((range, existing_path));
}
}
}
None
}
fn surrounding_filename(
@@ -1490,7 +1515,8 @@ mod tests {
You can't go to a file that does_not_exist.txt.
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.ˇ
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.ˇ
"});
// File does not exist
@@ -1499,6 +1525,7 @@ mod tests {
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
// No highlight
@@ -1517,6 +1544,7 @@ mod tests {
Go to fˇile2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
@@ -1525,6 +1553,7 @@ mod tests {
Go to «file2.rsˇ» if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
// Moving the mouse over a relative path that does exist should highlight it
@@ -1533,6 +1562,7 @@ mod tests {
Go to file2.rs if you want.
Or go to ../dir/fˇile2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
@@ -1541,6 +1571,7 @@ mod tests {
Go to file2.rs if you want.
Or go to «../dir/file2.rsˇ» if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
// Moving the mouse over an absolute path that does exist should highlight it
@@ -1549,6 +1580,7 @@ mod tests {
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/diˇr/file2.rs if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
@@ -1557,6 +1589,25 @@ mod tests {
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to «/root/dir/file2.rsˇ» if project is local.
Or go to /root/dir/file2 if this is a Rust file.
"});
// Moving the mouse over a path that exists, if we add the language-specific suffix, it should highlight it
let screen_coord = cx.pixel_position(indoc! {"
You can't go to a file that does_not_exist.txt.
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to /root/diˇr/file2 if this is a Rust file.
"});
cx.simulate_mouse_move(screen_coord, None, Modifiers::secondary_key());
cx.assert_editor_text_highlights::<HoveredLinkState>(indoc! {"
You can't go to a file that does_not_exist.txt.
Go to file2.rs if you want.
Or go to ../dir/file2.rs if you want.
Or go to /root/dir/file2.rs if project is local.
Or go to «/root/dir/file2ˇ» if this is a Rust file.
"});
cx.simulate_click(screen_coord, Modifiers::secondary_key());

View File

@@ -518,19 +518,22 @@ async fn parse_blocks(
let rendered_block = cx
.new_view(|cx| {
let settings = ThemeSettings::get_global(cx);
let ui_font_family = settings.ui_font.family.clone();
let buffer_font_family = settings.buffer_font.family.clone();
let mut base_style = cx.text_style();
base_style.refine(&TextStyleRefinement {
font_family: Some(buffer_font_family.clone()),
let mut base_text_style = cx.text_style();
base_text_style.refine(&TextStyleRefinement {
font_family: Some(ui_font_family.clone()),
color: Some(cx.theme().colors().editor_foreground),
..Default::default()
});
let markdown_style = MarkdownStyle {
base_text_style: base_style,
code_block: StyleRefinement::default().mt(rems(1.)).mb(rems(1.)),
base_text_style,
code_block: StyleRefinement::default().my(rems(1.)).font_buffer(cx),
inline_code: TextStyleRefinement {
background_color: Some(cx.theme().colors().background),
font_family: Some(buffer_font_family),
..Default::default()
},
rule_color: Color::Muted.color(cx),

View File

@@ -24,6 +24,7 @@ async-trait.workspace = true
client.workspace = true
collections.workspace = true
fs.workspace = true
editor.workspace = true
futures.workspace = true
gpui.workspace = true
http_client.workspace = true
@@ -32,7 +33,9 @@ isahc.workspace = true
language.workspace = true
log.workspace = true
lsp.workspace = true
multi_buffer.workspace = true
node_runtime.workspace = true
parking_lot.workspace = true
paths.workspace = true
project.workspace = true
release_channel.workspace = true

View File

@@ -6,17 +6,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
copy_extension_api_rust_files()
}
// rust-analyzer doesn't support include! for files from outside the crate.
// Copy them to the OUT_DIR, so we can include them from there, which is supported.
/// rust-analyzer doesn't support include! for files from outside the crate.
/// Copy them to the OUT_DIR, so we can include them from there, which is supported.
fn copy_extension_api_rust_files() -> Result<(), Box<dyn std::error::Error>> {
let out_dir = env::var("OUT_DIR")?;
let input_dir = PathBuf::from("../extension_api/wit");
let output_dir = PathBuf::from(out_dir);
println!("cargo:rerun-if-changed={}", input_dir.display());
for entry in fs::read_dir(&input_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
println!("cargo:rerun-if-changed={}", path.display());
for subentry in fs::read_dir(&path)? {
let subentry = subentry?;
let subpath = subentry.path();
@@ -26,7 +30,6 @@ fn copy_extension_api_rust_files() -> Result<(), Box<dyn std::error::Error>> {
fs::create_dir_all(destination.parent().unwrap())?;
fs::copy(&subpath, &destination)?;
println!("cargo:rerun-if-changed={}", subpath.display());
}
}
} else if path.extension() == Some(std::ffi::OsStr::new("rs")) {

View File

@@ -80,6 +80,8 @@ pub struct ExtensionManifest {
pub indexed_docs_providers: BTreeMap<Arc<str>, IndexedDocsProviderEntry>,
#[serde(default)]
pub snippets: Option<PathBuf>,
#[serde(default)]
pub editor_actions: BTreeMap<Arc<str>, EditorActionManifestEntry>,
}
#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
@@ -116,6 +118,9 @@ pub struct LanguageServerManifestEntry {
pub code_action_kinds: Option<Vec<lsp::CodeActionKind>>,
}
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
pub struct ActionManifestEntry {}
impl LanguageServerManifestEntry {
/// Returns the list of languages for the language server.
///
@@ -140,6 +145,11 @@ pub struct SlashCommandManifestEntry {
pub requires_argument: bool,
}
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
pub struct EditorActionManifestEntry {
pub name: String, // <extension_id>:: "Name"
}
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
pub struct IndexedDocsProviderEntry {}
@@ -187,6 +197,7 @@ fn manifest_from_old_manifest(
authors: manifest_json.authors,
schema_version: SchemaVersion::ZERO,
lib: Default::default(),
editor_actions: Default::default(),
themes: {
let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
themes.sort();

View File

@@ -6,25 +6,18 @@ use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
use std::sync::Arc;
#[derive(Deserialize, Serialize, Debug, Clone, JsonSchema)]
#[serde(default)]
#[derive(Deserialize, Serialize, Debug, Default, Clone, JsonSchema)]
pub struct ExtensionSettings {
/// The extensions that should be automatically installed by Zed.
///
/// This is used to make functionality provided by extensions (e.g., language support)
/// available out-of-the-box.
#[serde(default)]
pub auto_install_extensions: HashMap<Arc<str>, bool>,
#[serde(default)]
pub auto_update_extensions: HashMap<Arc<str>, bool>,
}
impl Default for ExtensionSettings {
fn default() -> Self {
Self {
auto_install_extensions: HashMap::from_iter([("html".into(), true)]),
auto_update_extensions: Default::default(),
}
}
}
impl ExtensionSettings {
/// Returns whether the given extension should be auto-installed.
pub fn should_auto_install(&self, extension_id: &str) -> bool {

View File

@@ -18,7 +18,8 @@ use assistant_slash_command::SlashCommandRegistry;
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use client::{telemetry::Telemetry, Client, ExtensionMetadata, GetExtensionsResponse};
use collections::{btree_map, BTreeMap, HashSet};
use collections::{btree_map, BTreeMap, HashMap, HashSet};
use editor::Editor;
use extension_builder::{CompileExtensionOptions, ExtensionBuilder};
use fs::{Fs, RemoveOptions};
use futures::{
@@ -30,8 +31,9 @@ use futures::{
select_biased, AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
};
use gpui::{
actions, AppContext, AsyncAppContext, Context, EventEmitter, Global, Model, ModelContext, Task,
WeakModel,
actions, Action, ActionTypeId, AnyWindowHandle, AppContext, AsyncAppContext,
BackgroundExecutor, Context, EventEmitter, Global, Model, ModelContext, Subscription, Task,
WeakModel, WeakView, WindowHandle,
};
use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
use indexed_docs::{IndexedDocsRegistry, ProviderId};
@@ -48,6 +50,7 @@ use settings::Settings;
use snippet_provider::SnippetRegistry;
use std::ops::RangeInclusive;
use std::str::FromStr;
use std::sync::LazyLock;
use std::{
cmp::Ordering,
path::{self, Path, PathBuf},
@@ -55,6 +58,7 @@ use std::{
time::{Duration, Instant},
};
use theme::{ThemeRegistry, ThemeSettings};
use ui::SharedString;
use url::Url;
use util::{maybe, ResultExt};
use wasm_host::{
@@ -102,6 +106,143 @@ pub fn is_version_compatible(
true
}
#[derive(Clone, PartialEq, Eq)]
pub struct ExtensionAction {
name: Arc<str>,
action_type_id: ActionTypeId,
}
static NAME_TO_TYPE_ID: LazyLock<Arc<parking_lot::Mutex<HashMap<String, ActionTypeId>>>> =
LazyLock::new(|| Default::default());
impl gpui::Action for ExtensionAction {
fn boxed_clone(&self) -> Box<dyn gpui::Action> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn std::any::Any {
self as _
}
fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
let Some(other) = action.as_any().downcast_ref::<ExtensionAction>() else {
return false;
};
other == self
}
fn name(&self) -> &str {
&self.name
}
fn debug_name() -> &'static str
where
Self: Sized,
{
"extension::ActionDebugName"
}
fn action_type_id(&self) -> gpui::ActionTypeId {
self.action_type_id.clone()
}
fn build(name: &str, value: serde_json::Value) -> Result<Box<dyn gpui::Action>>
where
Self: Sized,
{
let Some(action_type_id) = NAME_TO_TYPE_ID.lock().get(name).cloned() else {
anyhow::bail!("lol")
};
Ok(Box::new(Self {
name: name.into(),
action_type_id,
}))
}
}
pub struct EditorActionRegistry {
executor: BackgroundExecutor,
wasm_host: Arc<WasmHost>,
editors: Vec<(AnyWindowHandle, WeakView<Editor>)>,
actions: Vec<String>,
}
impl EditorActionRegistry {
fn new(wasm_host: Arc<WasmHost>, cx: &mut AppContext) -> Self {
EditorActionRegistry {
executor: cx.background_executor().clone(),
wasm_host: wasm_host.clone(),
editors: Default::default(),
actions: Default::default(),
}
}
fn add_editor(
&mut self,
editor: &mut Editor,
handle: WeakView<Editor>,
window: AnyWindowHandle,
cx: &mut AppContext,
) {
self.editors.push((window, handle));
dbg!(&self.actions);
for action in self.actions.iter() {
let Some(type_id) = NAME_TO_TYPE_ID.lock().get(action).cloned() else {
panic!("yikes");
};
dbg!("Registering runtime action");
editor
.register_runtime_action(type_id.clone(), |any, cx| {
dbg!("oh wow!");
})
.detach();
}
}
fn add_actions(&mut self, actions: Vec<String>) {
self.actions.extend(actions.clone());
for action in actions.into_iter() {
let editors = self.editors.clone();
let task = self.wasm_host.on_main_thread(|cx| {
{
async move {
cx.update(|cx| {
let type_id = NAME_TO_TYPE_ID
.lock()
.entry(action.clone())
.or_insert_with(|| {
cx.register_action_type(action.into(), ExtensionAction::build)
})
.clone();
dbg!(&type_id, &editors.len());
for (window, editor) in editors {
window
.update(cx, |_, cx| {
editor.update(cx, |editor, cx| {
editor
.register_runtime_action(
type_id.clone(),
|any, cx| {
dbg!("oh wow!");
},
)
.detach()
})
})
.log_err();
}
})
.log_err()
}
}
.boxed_local()
});
self.executor.spawn(task).detach();
}
}
}
pub struct ExtensionStore {
builder: Arc<ExtensionBuilder>,
extension_index: ExtensionIndex,
@@ -114,6 +255,7 @@ pub struct ExtensionStore {
outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
index_path: PathBuf,
language_registry: Arc<LanguageRegistry>,
editor_actions_registry: EditorActionRegistry,
theme_registry: Arc<ThemeRegistry>,
slash_command_registry: Arc<SlashCommandRegistry>,
indexed_docs_registry: Arc<IndexedDocsRegistry>,
@@ -239,11 +381,37 @@ impl ExtensionStore {
let installed_dir = extensions_dir.join("installed");
let index_path = extensions_dir.join("index.json");
let handle = cx.handle();
cx.observe_new_views(move |editor: &mut Editor, cx| {
let editor_handle = cx.view().downgrade();
let window = cx.window_handle();
handle.update(cx, |extension_store, cx| {
dbg!("registering!");
extension_store.editor_actions_registry.add_editor(
editor,
editor_handle,
window,
cx,
)
})
})
.detach();
let wasm_host = WasmHost::new(
fs.clone(),
http_client.clone(),
node_runtime,
language_registry.clone(),
work_dir,
cx,
);
let (reload_tx, mut reload_rx) = unbounded();
let mut this = Self {
extension_index: Default::default(),
installed_dir,
index_path,
editor_actions_registry: EditorActionRegistry::new(wasm_host.clone(), cx),
builder: Arc::new(ExtensionBuilder::new(
// Construct a real HTTP client for the extension builder, as we
// don't want to use a fake one in the tests.
@@ -253,15 +421,8 @@ impl ExtensionStore {
outstanding_operations: Default::default(),
modified_extensions: Default::default(),
reload_complete_senders: Vec::new(),
wasm_host: WasmHost::new(
fs.clone(),
http_client.clone(),
node_runtime,
language_registry.clone(),
work_dir,
cx,
),
wasm_extensions: Vec::new(),
wasm_host,
fs,
http_client,
telemetry,
@@ -939,7 +1100,7 @@ impl ExtensionStore {
///
/// First, this unloads any themes, languages, or grammars that are
/// no longer in the manifest, or whose files have changed on disk.
/// Then it loads any themes, languages, or grammars that are newly
/// Then it loads any themes, languages, edits, or grammars that are newly
/// added to the manifest, or whose files have changed on disk.
fn extensions_updated(
&mut self,
@@ -1064,6 +1225,7 @@ impl ExtensionStore {
let mut grammars_to_add = Vec::new();
let mut themes_to_add = Vec::new();
let mut snippets_to_add = Vec::new();
let mut actions_to_add = Vec::new();
for extension_id in &extensions_to_load {
let Some(extension) = new_index.extensions.get(extension_id) else {
continue;
@@ -1086,8 +1248,25 @@ impl ExtensionStore {
path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
path
}));
actions_to_add.extend(
extension
.manifest
.editor_actions
.iter()
.map(|(k, v)| dbg!(format!("{}::{}", extension_id, v.name))),
);
actions_to_add.extend(
extension
.manifest
.editor_actions
.iter()
.map(|(k, v)| dbg!(format!("editor::{}", v.name))),
);
}
dbg!("hello!", &actions_to_add);
self.editor_actions_registry.add_actions(actions_to_add);
self.language_registry
.register_wasm_grammars(grammars_to_add);

View File

@@ -145,6 +145,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
id: "zed-ruby".into(),
name: "Zed Ruby".into(),
version: "1.0.0".into(),
editor_actions: Default::default(),
schema_version: SchemaVersion::ZERO,
description: None,
authors: Vec::new(),
@@ -170,6 +171,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
"zed-monokai".into(),
ExtensionIndexEntry {
manifest: Arc::new(ExtensionManifest {
editor_actions: Default::default(),
id: "zed-monokai".into(),
name: "Zed Monokai".into(),
version: "2.0.0".into(),
@@ -336,6 +338,7 @@ async fn test_extension_store(cx: &mut TestAppContext) {
"zed-gruvbox".into(),
ExtensionIndexEntry {
manifest: Arc::new(ExtensionManifest {
editor_actions: Default::default(),
id: "zed-gruvbox".into(),
name: "Zed Gruvbox".into(),
version: "1.0.0".into(),

View File

@@ -104,6 +104,25 @@ impl WasmHost {
})
}
pub fn on_main_thread<T, Fn>(&self, f: Fn) -> impl 'static + Future<Output = T>
where
T: 'static + Send,
Fn: 'static + Send + for<'a> FnOnce(&'a mut AsyncAppContext) -> LocalBoxFuture<'a, T>,
{
let (return_tx, return_rx) = oneshot::channel();
self.main_thread_message_tx
.clone()
.unbounded_send(Box::new(move |cx| {
async {
let result = f(cx).await;
return_tx.send(result).ok();
}
.boxed_local()
}))
.expect("main thread message channel should not be closed yet");
async move { return_rx.await.expect("main thread message channel") }
}
pub fn load_extension(
self: &Arc<Self>,
wasm_bytes: Vec<u8>,
@@ -270,19 +289,7 @@ impl WasmState {
T: 'static + Send,
Fn: 'static + Send + for<'a> FnOnce(&'a mut AsyncAppContext) -> LocalBoxFuture<'a, T>,
{
let (return_tx, return_rx) = oneshot::channel();
self.host
.main_thread_message_tx
.clone()
.unbounded_send(Box::new(move |cx| {
async {
let result = f(cx).await;
return_tx.send(result).ok();
}
.boxed_local()
}))
.expect("main thread message channel should not be closed yet");
async move { return_rx.await.expect("main thread message channel") }
self.host.on_main_thread(f)
}
fn work_dir(&self) -> PathBuf {

View File

@@ -2,9 +2,10 @@ mod since_v0_0_1;
mod since_v0_0_4;
mod since_v0_0_6;
mod since_v0_1_0;
mod since_v0_2_0;
use indexed_docs::IndexedDocsDatabase;
use release_channel::ReleaseChannel;
use since_v0_1_0 as latest;
use since_v0_2_0::{self as latest, ExtensionBuffer};
use super::{wasm_engine, WasmState};
use anyhow::{anyhow, Context, Result};
@@ -52,10 +53,16 @@ pub fn wasm_api_version_range(release_channel: ReleaseChannel) -> RangeInclusive
// Note: The release channel can be used to stage a new version of the extension API.
let _ = release_channel;
since_v0_0_1::MIN_VERSION..=latest::MAX_VERSION
let max_version = match release_channel {
ReleaseChannel::Dev | ReleaseChannel::Nightly => latest::MAX_VERSION,
ReleaseChannel::Stable | ReleaseChannel::Preview => since_v0_1_0::MAX_VERSION,
};
since_v0_0_1::MIN_VERSION..=max_version
}
pub enum Extension {
V020(since_v0_2_0::Extension),
V010(since_v0_1_0::Extension),
V006(since_v0_0_6::Extension),
V004(since_v0_0_4::Extension),
@@ -72,11 +79,25 @@ impl Extension {
// Note: The release channel can be used to stage a new version of the extension API.
let _ = release_channel;
if version >= latest::MIN_VERSION {
let allow_latest_version = match release_channel {
ReleaseChannel::Dev | ReleaseChannel::Nightly => true,
ReleaseChannel::Stable | ReleaseChannel::Preview => false,
};
if allow_latest_version && version >= latest::MIN_VERSION {
let (extension, instance) =
latest::Extension::instantiate_async(store, component, latest::linker())
.await
.context("failed to instantiate wasm extension")?;
Ok((Self::V020(extension), instance))
} else if version >= since_v0_1_0::MIN_VERSION {
let (extension, instance) = since_v0_1_0::Extension::instantiate_async(
store,
component,
since_v0_1_0::linker(),
)
.await
.context("failed to instantiate wasm extension")?;
Ok((Self::V010(extension), instance))
} else if version >= since_v0_0_6::MIN_VERSION {
let (extension, instance) = since_v0_0_6::Extension::instantiate_async(
@@ -110,6 +131,7 @@ impl Extension {
pub async fn call_init_extension(&self, store: &mut Store<WasmState>) -> Result<()> {
match self {
Extension::V020(ext) => ext.call_init_extension(store).await,
Extension::V010(ext) => ext.call_init_extension(store).await,
Extension::V006(ext) => ext.call_init_extension(store).await,
Extension::V004(ext) => ext.call_init_extension(store).await,
@@ -117,6 +139,21 @@ impl Extension {
}
}
pub async fn call_run_editor_action(
&self,
store: &mut Store<WasmState>,
action_name: &str,
resource: Resource<ExtensionBuffer>,
) -> Result<()> {
match self {
Extension::V020(ext) => {
ext.call_run_editor_action(store, action_name, resource)
.await
}
_ => anyhow::bail!("not implemented"),
}
}
pub async fn call_language_server_command(
&self,
store: &mut Store<WasmState>,
@@ -125,10 +162,14 @@ impl Extension {
resource: Resource<Arc<dyn LspAdapterDelegate>>,
) -> Result<Result<Command, String>> {
match self {
Extension::V010(ext) => {
Extension::V020(ext) => {
ext.call_language_server_command(store, &language_server_id.0, resource)
.await
}
Extension::V010(ext) => Ok(ext
.call_language_server_command(store, &language_server_id.0, resource)
.await?
.map(|command| command.into())),
Extension::V006(ext) => Ok(ext
.call_language_server_command(store, &language_server_id.0, resource)
.await?
@@ -152,6 +193,14 @@ impl Extension {
resource: Resource<Arc<dyn LspAdapterDelegate>>,
) -> Result<Result<Option<String>, String>> {
match self {
Extension::V020(ext) => {
ext.call_language_server_initialization_options(
store,
&language_server_id.0,
resource,
)
.await
}
Extension::V010(ext) => {
ext.call_language_server_initialization_options(
store,
@@ -190,6 +239,14 @@ impl Extension {
resource: Resource<Arc<dyn LspAdapterDelegate>>,
) -> Result<Result<Option<String>, String>> {
match self {
Extension::V020(ext) => {
ext.call_language_server_workspace_configuration(
store,
&language_server_id.0,
resource,
)
.await
}
Extension::V010(ext) => {
ext.call_language_server_workspace_configuration(
store,
@@ -217,10 +274,19 @@ impl Extension {
completions: Vec<latest::Completion>,
) -> Result<Result<Vec<Option<CodeLabel>>, String>> {
match self {
Extension::V010(ext) => {
Extension::V020(ext) => {
ext.call_labels_for_completions(store, &language_server_id.0, &completions)
.await
}
Extension::V010(ext) => Ok(ext
.call_labels_for_completions(store, &language_server_id.0, &completions)
.await?
.map(|labels| {
labels
.into_iter()
.map(|label| label.map(Into::into))
.collect()
})),
Extension::V006(ext) => Ok(ext
.call_labels_for_completions(store, &language_server_id.0, &completions)
.await?
@@ -241,10 +307,19 @@ impl Extension {
symbols: Vec<latest::Symbol>,
) -> Result<Result<Vec<Option<CodeLabel>>, String>> {
match self {
Extension::V010(ext) => {
Extension::V020(ext) => {
ext.call_labels_for_symbols(store, &language_server_id.0, &symbols)
.await
}
Extension::V010(ext) => Ok(ext
.call_labels_for_symbols(store, &language_server_id.0, &symbols)
.await?
.map(|labels| {
labels
.into_iter()
.map(|label| label.map(Into::into))
.collect()
})),
Extension::V006(ext) => Ok(ext
.call_labels_for_symbols(store, &language_server_id.0, &symbols)
.await?
@@ -265,6 +340,10 @@ impl Extension {
arguments: &[String],
) -> Result<Result<Vec<SlashCommandArgumentCompletion>, String>> {
match self {
Extension::V020(ext) => {
ext.call_complete_slash_command_argument(store, command, arguments)
.await
}
Extension::V010(ext) => {
ext.call_complete_slash_command_argument(store, command, arguments)
.await
@@ -281,6 +360,10 @@ impl Extension {
resource: Option<Resource<Arc<dyn LspAdapterDelegate>>>,
) -> Result<Result<SlashCommandOutput, String>> {
match self {
Extension::V020(ext) => {
ext.call_run_slash_command(store, command, arguments, resource)
.await
}
Extension::V010(ext) => {
ext.call_run_slash_command(store, command, arguments, resource)
.await
@@ -297,6 +380,7 @@ impl Extension {
provider: &str,
) -> Result<Result<Vec<String>, String>> {
match self {
Extension::V020(ext) => ext.call_suggest_docs_packages(store, provider).await,
Extension::V010(ext) => ext.call_suggest_docs_packages(store, provider).await,
Extension::V001(_) | Extension::V004(_) | Extension::V006(_) => Err(anyhow!(
"`suggest_docs_packages` not available prior to v0.1.0"
@@ -312,6 +396,10 @@ impl Extension {
database: Resource<Arc<IndexedDocsDatabase>>,
) -> Result<Result<(), String>> {
match self {
Extension::V020(ext) => {
ext.call_index_docs(store, provider, package_name, database)
.await
}
Extension::V010(ext) => {
ext.call_index_docs(store, provider, package_name, database)
.await

View File

@@ -16,13 +16,14 @@ use language::{
use project::project_settings::ProjectSettings;
use semantic_version::SemanticVersion;
use std::{
env,
path::{Path, PathBuf},
sync::{Arc, OnceLock},
};
use util::maybe;
use wasmtime::component::{Linker, Resource};
use super::latest;
pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 1, 0);
@@ -33,7 +34,12 @@ wasmtime::component::bindgen!({
with: {
"worktree": ExtensionWorktree,
"key-value-store": ExtensionKeyValueStore,
"zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
"zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream,
"zed:extension/github": latest::zed::extension::github,
"zed:extension/lsp": latest::zed::extension::lsp,
"zed:extension/nodejs": latest::zed::extension::nodejs,
"zed:extension/platform": latest::zed::extension::platform,
"zed:extension/slash-command": latest::zed::extension::slash_command,
},
});
@@ -49,7 +55,94 @@ pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBo
pub fn linker() -> &'static Linker<WasmState> {
static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
LINKER.get_or_init(|| {
super::new_linker(|linker, f| {
Extension::add_to_linker(linker, f)?;
latest::zed::extension::github::add_to_linker(linker, f)?;
latest::zed::extension::nodejs::add_to_linker(linker, f)?;
latest::zed::extension::platform::add_to_linker(linker, f)?;
latest::zed::extension::slash_command::add_to_linker(linker, f)?;
Ok(())
})
})
}
impl From<Command> for latest::Command {
fn from(value: Command) -> Self {
Self {
command: value.command,
args: value.args,
env: value.env,
}
}
}
impl From<SettingsLocation> for latest::SettingsLocation {
fn from(value: SettingsLocation) -> Self {
Self {
worktree_id: value.worktree_id,
path: value.path,
}
}
}
impl From<LanguageServerInstallationStatus> for latest::LanguageServerInstallationStatus {
fn from(value: LanguageServerInstallationStatus) -> Self {
match value {
LanguageServerInstallationStatus::None => Self::None,
LanguageServerInstallationStatus::Downloading => Self::Downloading,
LanguageServerInstallationStatus::CheckingForUpdate => Self::CheckingForUpdate,
LanguageServerInstallationStatus::Failed(message) => Self::Failed(message),
}
}
}
impl From<DownloadedFileType> for latest::DownloadedFileType {
fn from(value: DownloadedFileType) -> Self {
match value {
DownloadedFileType::Gzip => Self::Gzip,
DownloadedFileType::GzipTar => Self::GzipTar,
DownloadedFileType::Zip => Self::Zip,
DownloadedFileType::Uncompressed => Self::Uncompressed,
}
}
}
impl From<Range> for latest::Range {
fn from(value: Range) -> Self {
Self {
start: value.start,
end: value.end,
}
}
}
impl From<CodeLabelSpan> for latest::CodeLabelSpan {
fn from(value: CodeLabelSpan) -> Self {
match value {
CodeLabelSpan::CodeRange(range) => Self::CodeRange(range.into()),
CodeLabelSpan::Literal(literal) => Self::Literal(literal.into()),
}
}
}
impl From<CodeLabelSpanLiteral> for latest::CodeLabelSpanLiteral {
fn from(value: CodeLabelSpanLiteral) -> Self {
Self {
text: value.text,
highlight_name: value.highlight_name,
}
}
}
impl From<CodeLabel> for latest::CodeLabel {
fn from(value: CodeLabel) -> Self {
Self {
code: value.code,
spans: value.spans.into_iter().map(Into::into).collect(),
filter_range: value.filter_range.into(),
}
}
}
#[async_trait]
@@ -251,136 +344,6 @@ async fn convert_response(
Ok(extension_response)
}
#[async_trait]
impl nodejs::Host for WasmState {
async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
self.host
.node_runtime
.binary_path()
.await
.map(|path| path.to_string_lossy().to_string())
.to_wasmtime_result()
}
async fn npm_package_latest_version(
&mut self,
package_name: String,
) -> wasmtime::Result<Result<String, String>> {
self.host
.node_runtime
.npm_package_latest_version(&package_name)
.await
.to_wasmtime_result()
}
async fn npm_package_installed_version(
&mut self,
package_name: String,
) -> wasmtime::Result<Result<Option<String>, String>> {
self.host
.node_runtime
.npm_package_installed_version(&self.work_dir(), &package_name)
.await
.to_wasmtime_result()
}
async fn npm_install_package(
&mut self,
package_name: String,
version: String,
) -> wasmtime::Result<Result<(), String>> {
self.host
.node_runtime
.npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
.await
.to_wasmtime_result()
}
}
#[async_trait]
impl lsp::Host for WasmState {}
impl From<::http_client::github::GithubRelease> for github::GithubRelease {
fn from(value: ::http_client::github::GithubRelease) -> Self {
Self {
version: value.tag_name,
assets: value.assets.into_iter().map(Into::into).collect(),
}
}
}
impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
Self {
name: value.name,
download_url: value.browser_download_url,
}
}
}
#[async_trait]
impl github::Host for WasmState {
async fn latest_github_release(
&mut self,
repo: String,
options: github::GithubReleaseOptions,
) -> wasmtime::Result<Result<github::GithubRelease, String>> {
maybe!(async {
let release = ::http_client::github::latest_github_release(
&repo,
options.require_assets,
options.pre_release,
self.host.http_client.clone(),
)
.await?;
Ok(release.into())
})
.await
.to_wasmtime_result()
}
async fn github_release_by_tag_name(
&mut self,
repo: String,
tag: String,
) -> wasmtime::Result<Result<github::GithubRelease, String>> {
maybe!(async {
let release = ::http_client::github::get_release_by_tag_name(
&repo,
&tag,
self.host.http_client.clone(),
)
.await?;
Ok(release.into())
})
.await
.to_wasmtime_result()
}
}
#[async_trait]
impl platform::Host for WasmState {
async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
Ok((
match env::consts::OS {
"macos" => platform::Os::Mac,
"linux" => platform::Os::Linux,
"windows" => platform::Os::Windows,
_ => panic!("unsupported os"),
},
match env::consts::ARCH {
"aarch64" => platform::Architecture::Aarch64,
"x86" => platform::Architecture::X86,
"x86_64" => platform::Architecture::X8664,
_ => panic!("unsupported architecture"),
},
))
}
}
#[async_trait]
impl slash_command::Host for WasmState {}
#[async_trait]
impl ExtensionImports for WasmState {
async fn get_settings(

View File

@@ -0,0 +1,632 @@
use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
use ::http_client::AsyncBody;
use ::settings::{Settings, WorktreeId};
use anyhow::{anyhow, bail, Context, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use async_trait::async_trait;
use editor::MultiBufferSnapshot;
use futures::{io::BufReader, FutureExt as _};
use futures::{lock::Mutex, AsyncReadExt};
use indexed_docs::IndexedDocsDatabase;
use isahc::config::{Configurable, RedirectPolicy};
use language::LanguageName;
use language::{
language_settings::AllLanguageSettings, LanguageServerBinaryStatus, LspAdapterDelegate,
};
use project::project_settings::ProjectSettings;
use semantic_version::SemanticVersion;
use std::{
env,
path::{Path, PathBuf},
sync::{Arc, OnceLock},
};
use util::maybe;
use wasmtime::component::{Linker, Resource};
pub const MIN_VERSION: SemanticVersion = SemanticVersion::new(0, 2, 0);
pub const MAX_VERSION: SemanticVersion = SemanticVersion::new(0, 2, 0);
wasmtime::component::bindgen!({
async: true,
trappable_imports: true,
path: "../extension_api/wit/since_v0.2.0",
with: {
"worktree": ExtensionWorktree,
"buffer": ExtensionBuffer,
"char-iterator": ExtensionCharIterator,
"key-value-store": ExtensionKeyValueStore,
"zed:extension/http-client/http-response-stream": ExtensionHttpResponseStream
},
});
pub struct BoopCharIterator {
snapshot: multi_buffer::MultiBufferSnapshot,
offset: usize,
}
impl Iterator for BoopCharIterator {
type Item = (char, u64);
fn next(&mut self) -> Option<Self::Item> {
let offset = self.offset;
let char = self.snapshot.chars_at(self.offset).next()?;
self.offset = offset + char.len_utf8();
Some((char, offset as u64))
}
}
pub use self::zed::extension::*;
mod settings {
include!(concat!(env!("OUT_DIR"), "/since_v0.2.0/settings.rs"));
}
pub struct ExtensionBuffer {
snapshot: MultiBufferSnapshot,
selections: Vec<Selection>,
}
impl ExtensionBuffer {
fn selections(&self) -> Vec<Selection> {
self.selections.clone()
}
}
pub type ExtensionCharIterator = Arc<Mutex<BoopCharIterator>>;
pub type ExtensionWorktree = Arc<dyn LspAdapterDelegate>;
pub type ExtensionKeyValueStore = Arc<IndexedDocsDatabase>;
pub type ExtensionHttpResponseStream = Arc<Mutex<::http_client::Response<AsyncBody>>>;
pub fn linker() -> &'static Linker<WasmState> {
static LINKER: OnceLock<Linker<WasmState>> = OnceLock::new();
LINKER.get_or_init(|| super::new_linker(Extension::add_to_linker))
}
#[async_trait]
impl HostKeyValueStore for WasmState {
async fn insert(
&mut self,
kv_store: Resource<ExtensionKeyValueStore>,
key: String,
value: String,
) -> wasmtime::Result<Result<(), String>> {
let kv_store = self.table.get(&kv_store)?;
kv_store.insert(key, value).await.to_wasmtime_result()
}
fn drop(&mut self, _worktree: Resource<ExtensionKeyValueStore>) -> Result<()> {
// We only ever hand out borrows of key-value stores.
Ok(())
}
}
#[async_trait]
impl HostWorktree for WasmState {
async fn id(
&mut self,
delegate: Resource<Arc<dyn LspAdapterDelegate>>,
) -> wasmtime::Result<u64> {
let delegate = self.table.get(&delegate)?;
Ok(delegate.worktree_id().to_proto())
}
async fn root_path(
&mut self,
delegate: Resource<Arc<dyn LspAdapterDelegate>>,
) -> wasmtime::Result<String> {
let delegate = self.table.get(&delegate)?;
Ok(delegate.worktree_root_path().to_string_lossy().to_string())
}
async fn read_text_file(
&mut self,
delegate: Resource<Arc<dyn LspAdapterDelegate>>,
path: String,
) -> wasmtime::Result<Result<String, String>> {
let delegate = self.table.get(&delegate)?;
Ok(delegate
.read_text_file(path.into())
.await
.map_err(|error| error.to_string()))
}
async fn shell_env(
&mut self,
delegate: Resource<Arc<dyn LspAdapterDelegate>>,
) -> wasmtime::Result<EnvVars> {
let delegate = self.table.get(&delegate)?;
Ok(delegate.shell_env().await.into_iter().collect())
}
async fn which(
&mut self,
delegate: Resource<Arc<dyn LspAdapterDelegate>>,
binary_name: String,
) -> wasmtime::Result<Option<String>> {
let delegate = self.table.get(&delegate)?;
Ok(delegate
.which(binary_name.as_ref())
.await
.map(|path| path.to_string_lossy().to_string()))
}
fn drop(&mut self, _worktree: Resource<Worktree>) -> Result<()> {
// We only ever hand out borrows of worktrees.
Ok(())
}
}
#[async_trait]
impl common::Host for WasmState {}
#[async_trait]
impl http_client::Host for WasmState {
async fn fetch(
&mut self,
request: http_client::HttpRequest,
) -> wasmtime::Result<Result<http_client::HttpResponse, String>> {
maybe!(async {
let url = &request.url;
let request = convert_request(&request)?;
let mut response = self.host.http_client.send(request).await?;
if response.status().is_client_error() || response.status().is_server_error() {
bail!("failed to fetch '{url}': status code {}", response.status())
}
convert_response(&mut response).await
})
.await
.to_wasmtime_result()
}
async fn fetch_stream(
&mut self,
request: http_client::HttpRequest,
) -> wasmtime::Result<Result<Resource<ExtensionHttpResponseStream>, String>> {
let request = convert_request(&request)?;
let response = self.host.http_client.send(request);
maybe!(async {
let response = response.await?;
let stream = Arc::new(Mutex::new(response));
let resource = self.table.push(stream)?;
Ok(resource)
})
.await
.to_wasmtime_result()
}
}
#[async_trait]
impl http_client::HostHttpResponseStream for WasmState {
async fn next_chunk(
&mut self,
resource: Resource<ExtensionHttpResponseStream>,
) -> wasmtime::Result<Result<Option<Vec<u8>>, String>> {
let stream = self.table.get(&resource)?.clone();
maybe!(async move {
let mut response = stream.lock().await;
let mut buffer = vec![0; 8192]; // 8KB buffer
let bytes_read = response.body_mut().read(&mut buffer).await?;
if bytes_read == 0 {
Ok(None)
} else {
buffer.truncate(bytes_read);
Ok(Some(buffer))
}
})
.await
.to_wasmtime_result()
}
fn drop(&mut self, _resource: Resource<ExtensionHttpResponseStream>) -> Result<()> {
Ok(())
}
}
impl From<http_client::HttpMethod> for ::http_client::Method {
fn from(value: http_client::HttpMethod) -> Self {
match value {
http_client::HttpMethod::Get => Self::GET,
http_client::HttpMethod::Post => Self::POST,
http_client::HttpMethod::Put => Self::PUT,
http_client::HttpMethod::Delete => Self::DELETE,
http_client::HttpMethod::Head => Self::HEAD,
http_client::HttpMethod::Options => Self::OPTIONS,
http_client::HttpMethod::Patch => Self::PATCH,
}
}
}
fn convert_request(
extension_request: &http_client::HttpRequest,
) -> Result<::http_client::Request<AsyncBody>, anyhow::Error> {
let mut request = ::http_client::Request::builder()
.method(::http_client::Method::from(extension_request.method))
.uri(&extension_request.url)
.redirect_policy(match extension_request.redirect_policy {
http_client::RedirectPolicy::NoFollow => RedirectPolicy::None,
http_client::RedirectPolicy::FollowLimit(limit) => RedirectPolicy::Limit(limit),
http_client::RedirectPolicy::FollowAll => RedirectPolicy::Follow,
});
for (key, value) in &extension_request.headers {
request = request.header(key, value);
}
let body = extension_request
.body
.clone()
.map(AsyncBody::from)
.unwrap_or_default();
request.body(body).map_err(anyhow::Error::from)
}
async fn convert_response(
response: &mut ::http_client::Response<AsyncBody>,
) -> Result<http_client::HttpResponse, anyhow::Error> {
let mut extension_response = http_client::HttpResponse {
body: Vec::new(),
headers: Vec::new(),
};
for (key, value) in response.headers() {
extension_response
.headers
.push((key.to_string(), value.to_str().unwrap_or("").to_string()));
}
response
.body_mut()
.read_to_end(&mut extension_response.body)
.await?;
Ok(extension_response)
}
#[async_trait]
impl nodejs::Host for WasmState {
async fn node_binary_path(&mut self) -> wasmtime::Result<Result<String, String>> {
self.host
.node_runtime
.binary_path()
.await
.map(|path| path.to_string_lossy().to_string())
.to_wasmtime_result()
}
async fn npm_package_latest_version(
&mut self,
package_name: String,
) -> wasmtime::Result<Result<String, String>> {
self.host
.node_runtime
.npm_package_latest_version(&package_name)
.await
.to_wasmtime_result()
}
async fn npm_package_installed_version(
&mut self,
package_name: String,
) -> wasmtime::Result<Result<Option<String>, String>> {
self.host
.node_runtime
.npm_package_installed_version(&self.work_dir(), &package_name)
.await
.to_wasmtime_result()
}
async fn npm_install_package(
&mut self,
package_name: String,
version: String,
) -> wasmtime::Result<Result<(), String>> {
self.host
.node_runtime
.npm_install_packages(&self.work_dir(), &[(&package_name, &version)])
.await
.to_wasmtime_result()
}
}
#[async_trait]
impl lsp::Host for WasmState {}
impl From<::http_client::github::GithubRelease> for github::GithubRelease {
fn from(value: ::http_client::github::GithubRelease) -> Self {
Self {
version: value.tag_name,
assets: value.assets.into_iter().map(Into::into).collect(),
}
}
}
impl From<::http_client::github::GithubReleaseAsset> for github::GithubReleaseAsset {
fn from(value: ::http_client::github::GithubReleaseAsset) -> Self {
Self {
name: value.name,
download_url: value.browser_download_url,
}
}
}
#[async_trait]
impl github::Host for WasmState {
async fn latest_github_release(
&mut self,
repo: String,
options: github::GithubReleaseOptions,
) -> wasmtime::Result<Result<github::GithubRelease, String>> {
maybe!(async {
let release = ::http_client::github::latest_github_release(
&repo,
options.require_assets,
options.pre_release,
self.host.http_client.clone(),
)
.await?;
Ok(release.into())
})
.await
.to_wasmtime_result()
}
async fn github_release_by_tag_name(
&mut self,
repo: String,
tag: String,
) -> wasmtime::Result<Result<github::GithubRelease, String>> {
maybe!(async {
let release = ::http_client::github::get_release_by_tag_name(
&repo,
&tag,
self.host.http_client.clone(),
)
.await?;
Ok(release.into())
})
.await
.to_wasmtime_result()
}
}
#[async_trait]
impl platform::Host for WasmState {
async fn current_platform(&mut self) -> Result<(platform::Os, platform::Architecture)> {
Ok((
match env::consts::OS {
"macos" => platform::Os::Mac,
"linux" => platform::Os::Linux,
"windows" => platform::Os::Windows,
_ => panic!("unsupported os"),
},
match env::consts::ARCH {
"aarch64" => platform::Architecture::Aarch64,
"x86" => platform::Architecture::X86,
"x86_64" => platform::Architecture::X8664,
_ => panic!("unsupported architecture"),
},
))
}
}
#[async_trait]
impl slash_command::Host for WasmState {}
#[async_trait]
impl ExtensionImports for WasmState {
async fn get_settings(
&mut self,
location: Option<self::SettingsLocation>,
category: String,
key: Option<String>,
) -> wasmtime::Result<Result<String, String>> {
self.on_main_thread(|cx| {
async move {
let location = location
.as_ref()
.map(|location| ::settings::SettingsLocation {
worktree_id: WorktreeId::from_proto(location.worktree_id),
path: Path::new(&location.path),
});
cx.update(|cx| match category.as_str() {
"language" => {
let key = key.map(|k| LanguageName::new(&k));
let settings =
AllLanguageSettings::get(location, cx).language(key.as_ref());
Ok(serde_json::to_string(&settings::LanguageSettings {
tab_size: settings.tab_size,
})?)
}
"lsp" => {
let settings = key
.and_then(|key| {
ProjectSettings::get(location, cx)
.lsp
.get(&Arc::<str>::from(key))
})
.cloned()
.unwrap_or_default();
Ok(serde_json::to_string(&settings::LspSettings {
binary: settings.binary.map(|binary| settings::BinarySettings {
path: binary.path,
arguments: binary.arguments,
}),
settings: settings.settings,
initialization_options: settings.initialization_options,
})?)
}
_ => {
bail!("Unknown settings category: {}", category);
}
})
}
.boxed_local()
})
.await?
.to_wasmtime_result()
}
async fn set_language_server_installation_status(
&mut self,
server_name: String,
status: LanguageServerInstallationStatus,
) -> wasmtime::Result<()> {
let status = match status {
LanguageServerInstallationStatus::CheckingForUpdate => {
LanguageServerBinaryStatus::CheckingForUpdate
}
LanguageServerInstallationStatus::Downloading => {
LanguageServerBinaryStatus::Downloading
}
LanguageServerInstallationStatus::None => LanguageServerBinaryStatus::None,
LanguageServerInstallationStatus::Failed(error) => {
LanguageServerBinaryStatus::Failed { error }
}
};
self.host
.language_registry
.update_lsp_status(language::LanguageServerName(server_name.into()), status);
Ok(())
}
async fn download_file(
&mut self,
url: String,
path: String,
file_type: DownloadedFileType,
) -> wasmtime::Result<Result<(), String>> {
maybe!(async {
let path = PathBuf::from(path);
let extension_work_dir = self.host.work_dir.join(self.manifest.id.as_ref());
self.host.fs.create_dir(&extension_work_dir).await?;
let destination_path = self
.host
.writeable_path_from_extension(&self.manifest.id, &path)?;
let mut response = self
.host
.http_client
.get(&url, Default::default(), true)
.await
.map_err(|err| anyhow!("error downloading release: {}", err))?;
if !response.status().is_success() {
Err(anyhow!(
"download failed with status {}",
response.status().to_string()
))?;
}
let body = BufReader::new(response.body_mut());
match file_type {
DownloadedFileType::Uncompressed => {
futures::pin_mut!(body);
self.host
.fs
.create_file_with(&destination_path, body)
.await?;
}
DownloadedFileType::Gzip => {
let body = GzipDecoder::new(body);
futures::pin_mut!(body);
self.host
.fs
.create_file_with(&destination_path, body)
.await?;
}
DownloadedFileType::GzipTar => {
let body = GzipDecoder::new(body);
futures::pin_mut!(body);
self.host
.fs
.extract_tar_file(&destination_path, Archive::new(body))
.await?;
}
DownloadedFileType::Zip => {
futures::pin_mut!(body);
node_runtime::extract_zip(&destination_path, body)
.await
.with_context(|| format!("failed to unzip {} archive", path.display()))?;
}
}
Ok(())
})
.await
.to_wasmtime_result()
}
async fn make_file_executable(&mut self, path: String) -> wasmtime::Result<Result<(), String>> {
#[allow(unused)]
let path = self
.host
.writeable_path_from_extension(&self.manifest.id, Path::new(&path))?;
#[cfg(unix)]
{
use std::fs::{self, Permissions};
use std::os::unix::fs::PermissionsExt;
return fs::set_permissions(&path, Permissions::from_mode(0o755))
.map_err(|error| anyhow!("failed to set permissions for path {path:?}: {error}"))
.to_wasmtime_result();
}
#[cfg(not(unix))]
Ok(Ok(()))
}
}
#[async_trait]
impl HostBuffer for WasmState {
async fn selections(&mut self, buffer: Resource<Buffer>) -> wasmtime::Result<Vec<Selection>> {
let buffer = self.table.get(&buffer)?;
// Assuming Buffer has a selections() method that returns Vec<Selection>
Ok(buffer.selections())
}
async fn chars_at(
&mut self,
buffer: Resource<Buffer>,
offset: u64,
) -> wasmtime::Result<Resource<CharIterator>> {
todo!("Implement chars_at")
}
async fn chars_before(
&mut self,
buffer: Resource<Buffer>,
offset: u64,
) -> wasmtime::Result<Resource<CharIterator>> {
todo!("Implement chars_before")
}
async fn edits(&mut self, buffer: Resource<Buffer>) -> wasmtime::Result<Vec<Edit>> {
todo!("Implement edits")
}
fn drop(&mut self, buffer: Resource<Buffer>) -> wasmtime::Result<()> {
todo!("Implement drop for Buffer")
}
}
#[async_trait]
impl HostCharIterator for WasmState {
async fn next(
&mut self,
iterator: Resource<CharIterator>,
) -> wasmtime::Result<Option<(char, u64)>> {
let char_iterator = self.table.get(&iterator)?;
let mut state = char_iterator.lock().await;
Ok(state.next())
}
fn drop(&mut self, _: Resource<CharIterator>) -> wasmtime::Result<()> {
Ok(())
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "zed_extension_api"
version = "0.1.0"
version = "0.2.0"
description = "APIs for creating Zed extensions in Rust"
repository = "https://github.com/zed-industries/zed"
documentation = "https://docs.rs/zed_extension_api"
@@ -8,6 +8,9 @@ keywords = ["zed", "extension"]
edition = "2021"
license = "Apache-2.0"
# Remove when we're ready to publish v0.2.0.
publish = false
[lints]
workspace = true

View File

@@ -27,7 +27,7 @@ pub use wit::{
zed::extension::slash_command::{
SlashCommand, SlashCommandArgumentCompletion, SlashCommandOutput, SlashCommandOutputSection,
},
CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
Buffer, CodeLabel, CodeLabelSpan, CodeLabelSpanLiteral, Command, DownloadedFileType, EnvVars,
KeyValueStore, LanguageServerInstallationStatus, Range, Worktree,
};
@@ -57,6 +57,9 @@ pub fn set_language_server_installation_status(
wit::set_language_server_installation_status(&language_server_id.0, status)
}
// regsister editor action
// handle action (editor)
/// A Zed extension.
pub trait Extension: Send + Sync {
/// Returns a new instance of the extension.
@@ -147,6 +150,9 @@ pub trait Extension: Send + Sync {
) -> Result<(), String> {
Err("`index_docs` not implemented".to_string())
}
/// Returns the output from running the provided slash command.
fn run_editor_action(&self, _name: String, buffer: Buffer) {}
}
/// Registers the provided type as a Zed extension.
@@ -186,7 +192,7 @@ mod wit {
wit_bindgen::generate!({
skip: ["init-extension"],
path: "./wit/since_v0.1.0",
path: "./wit/since_v0.2.0",
});
}
@@ -281,6 +287,10 @@ impl wit::Guest for Component {
) -> Result<(), String> {
extension().index_docs(provider, package, database)
}
fn run_editor_action(
name: String,buffer: Buffe extension().run_editor_action(name, buffer)
}
}
/// The ID of a language server.

View File

@@ -0,0 +1,9 @@
interface common {
/// A (half-open) range (`[start, end)`).
record range {
/// The start of the range (inclusive).
start: u32,
/// The end of the range (exclusive).
end: u32,
}
}

View File

@@ -0,0 +1,171 @@
package zed:extension;
world extension {
import github;
import http-client;
import platform;
import nodejs;
use common.{range};
use lsp.{completion, symbol};
use slash-command.{slash-command, slash-command-argument-completion, slash-command-output};
/// Initializes the extension.
export init-extension: func();
/// The type of a downloaded file.
enum downloaded-file-type {
/// A gzipped file (`.gz`).
gzip,
/// A gzipped tar archive (`.tar.gz`).
gzip-tar,
/// A ZIP file (`.zip`).
zip,
/// An uncompressed file.
uncompressed,
}
/// The installation status for a language server.
variant language-server-installation-status {
/// The language server has no installation status.
none,
/// The language server is being downloaded.
downloading,
/// The language server is checking for updates.
checking-for-update,
/// The language server installation failed for specified reason.
failed(string),
}
record settings-location {
worktree-id: u64,
path: string,
}
import get-settings: func(path: option<settings-location>, category: string, key: option<string>) -> result<string, string>;
/// Downloads a file from the given URL and saves it to the given path within the extension's
/// working directory.
///
/// The file will be extracted according to the given file type.
import download-file: func(url: string, file-path: string, file-type: downloaded-file-type) -> result<_, string>;
/// Makes the file at the given path executable.
import make-file-executable: func(filepath: string) -> result<_, string>;
/// Updates the installation status for the given language server.
import set-language-server-installation-status: func(language-server-name: string, status: language-server-installation-status);
/// A list of environment variables.
type env-vars = list<tuple<string, string>>;
/// A command.
record command {
/// The command to execute.
command: string,
/// The arguments to pass to the command.
args: list<string>,
/// The environment variables to set for the command.
env: env-vars,
}
/// A Zed worktree.
resource worktree {
/// Returns the ID of the worktree.
id: func() -> u64;
/// Returns the root path of the worktree.
root-path: func() -> string;
/// Returns the textual contents of the specified file in the worktree.
read-text-file: func(path: string) -> result<string, string>;
/// Returns the path to the given binary name, if one is present on the `$PATH`.
which: func(binary-name: string) -> option<string>;
/// Returns the current shell environment.
shell-env: func() -> env-vars;
}
resource buffer {
selections: func() -> list<selection>;
chars-at: func(offset: u64) -> char-iterator;
chars-before: func(offset: u64) -> char-iterator;
edits: func() -> list<edit>;
}
record edit {
range: range,
text: string,
}
resource char-iterator {
next: func() -> option<tuple<char, u64>>;
}
record selection {
range: range,
reversed: bool,
}
/// A key-value store.
resource key-value-store {
/// Inserts an entry under the specified key.
insert: func(key: string, value: string) -> result<_, string>;
}
/// Runs the editor action
export run-editor-action: func(name: string, buffer: buffer);
/// Returns the command used to start up the language server.
export language-server-command: func(language-server-id: string, worktree: borrow<worktree>) -> result<command, string>;
/// Returns the initialization options to pass to the language server on startup.
///
/// The initialization options are represented as a JSON string.
export language-server-initialization-options: func(language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
/// Returns the workspace configuration options to pass to the language server.
export language-server-workspace-configuration: func(language-server-id: string, worktree: borrow<worktree>) -> result<option<string>, string>;
/// A label containing some code.
record code-label {
/// The source code to parse with Tree-sitter.
code: string,
/// The spans to display in the label.
spans: list<code-label-span>,
/// The range of the displayed label to include when filtering.
filter-range: range,
}
/// A span within a code label.
variant code-label-span {
/// A range into the parsed code.
code-range(range),
/// A span containing a code literal.
literal(code-label-span-literal),
}
/// A span containing a code literal.
record code-label-span-literal {
/// The literal text.
text: string,
/// The name of the highlight to use for this literal.
highlight-name: option<string>,
}
export labels-for-completions: func(language-server-id: string, completions: list<completion>) -> result<list<option<code-label>>, string>;
export labels-for-symbols: func(language-server-id: string, symbols: list<symbol>) -> result<list<option<code-label>>, string>;
/// Returns the completions that should be shown when completing the provided slash command with the given query.
export complete-slash-command-argument: func(command: slash-command, args: list<string>) -> result<list<slash-command-argument-completion>, string>;
/// Returns the output from running the provided slash command.
export run-slash-command: func(command: slash-command, args: list<string>, worktree: option<borrow<worktree>>) -> result<slash-command-output, string>;
/// Returns a list of packages as suggestions to be included in the `/docs`
/// search results.
///
/// This can be used to provide completions for known packages (e.g., from the
/// local project or a registry) before a package has been indexed.
export suggest-docs-packages: func(provider-name: string) -> result<list<string>, string>;
/// Indexes the docs for the specified package.
export index-docs: func(provider-name: string, package-name: string, database: borrow<key-value-store>) -> result<_, string>;
}

View File

@@ -0,0 +1,33 @@
interface github {
/// A GitHub release.
record github-release {
/// The version of the release.
version: string,
/// The list of assets attached to the release.
assets: list<github-release-asset>,
}
/// An asset from a GitHub release.
record github-release-asset {
/// The name of the asset.
name: string,
/// The download URL for the asset.
download-url: string,
}
/// The options used to filter down GitHub releases.
record github-release-options {
/// Whether releases without assets should be included.
require-assets: bool,
/// Whether pre-releases should be included.
pre-release: bool,
}
/// Returns the latest release for the given GitHub repository.
latest-github-release: func(repo: string, options: github-release-options) -> result<github-release, string>;
/// Returns the GitHub release with the specified tag name for the given GitHub repository.
///
/// Returns an error if a release with the given tag name does not exist.
github-release-by-tag-name: func(repo: string, tag: string) -> result<github-release, string>;
}

View File

@@ -0,0 +1,67 @@
interface http-client {
/// An HTTP request.
record http-request {
/// The HTTP method for the request.
method: http-method,
/// The URL to which the request should be made.
url: string,
/// The headers for the request.
headers: list<tuple<string, string>>,
/// The request body.
body: option<list<u8>>,
/// The policy to use for redirects.
redirect-policy: redirect-policy,
}
/// HTTP methods.
enum http-method {
/// `GET`
get,
/// `HEAD`
head,
/// `POST`
post,
/// `PUT`
put,
/// `DELETE`
delete,
/// `OPTIONS`
options,
/// `PATCH`
patch,
}
/// The policy for dealing with redirects received from the server.
variant redirect-policy {
/// Redirects from the server will not be followed.
///
/// This is the default behavior.
no-follow,
/// Redirects from the server will be followed up to the specified limit.
follow-limit(u32),
/// All redirects from the server will be followed.
follow-all,
}
/// An HTTP response.
record http-response {
/// The response headers.
headers: list<tuple<string, string>>,
/// The response body.
body: list<u8>,
}
/// Performs an HTTP request and returns the response.
fetch: func(req: http-request) -> result<http-response, string>;
/// An HTTP response stream.
resource http-response-stream {
/// Retrieves the next chunk of data from the response stream.
///
/// Returns `Ok(None)` if the stream has ended.
next-chunk: func() -> result<option<list<u8>>, string>;
}
/// Performs an HTTP request and returns a response stream.
fetch-stream: func(req: http-request) -> result<http-response-stream, string>;
}

View File

@@ -0,0 +1,83 @@
interface lsp {
/// An LSP completion.
record completion {
label: string,
detail: option<string>,
kind: option<completion-kind>,
insert-text-format: option<insert-text-format>,
}
/// The kind of an LSP completion.
variant completion-kind {
text,
method,
function,
%constructor,
field,
variable,
class,
%interface,
module,
property,
unit,
value,
%enum,
keyword,
snippet,
color,
file,
reference,
folder,
enum-member,
constant,
struct,
event,
operator,
type-parameter,
other(s32),
}
/// Defines how to interpret the insert text in a completion item.
variant insert-text-format {
plain-text,
snippet,
other(s32),
}
/// An LSP symbol.
record symbol {
kind: symbol-kind,
name: string,
}
/// The kind of an LSP symbol.
variant symbol-kind {
file,
module,
namespace,
%package,
class,
method,
property,
field,
%constructor,
%enum,
%interface,
function,
variable,
constant,
%string,
number,
boolean,
array,
object,
key,
null,
enum-member,
struct,
event,
operator,
type-parameter,
other(s32),
}
}

View File

@@ -0,0 +1,13 @@
interface nodejs {
/// Returns the path to the Node binary used by Zed.
node-binary-path: func() -> result<string, string>;
/// Returns the latest version of the given NPM package.
npm-package-latest-version: func(package-name: string) -> result<string, string>;
/// Returns the installed version of the given NPM package, if it exists.
npm-package-installed-version: func(package-name: string) -> result<option<string>, string>;
/// Installs the specified NPM package.
npm-install-package: func(package-name: string, version: string) -> result<_, string>;
}

View File

@@ -0,0 +1,24 @@
interface platform {
/// An operating system.
enum os {
/// macOS.
mac,
/// Linux.
linux,
/// Windows.
windows,
}
/// A platform architecture.
enum architecture {
/// AArch64 (e.g., Apple Silicon).
aarch64,
/// x86.
x86,
/// x86-64.
x8664,
}
/// Gets the current operating system and architecture.
current-platform: func() -> tuple<os, architecture>;
}

View File

@@ -0,0 +1,29 @@
use serde::{Deserialize, Serialize};
use std::num::NonZeroU32;
/// The settings for a particular language.
#[derive(Debug, Serialize, Deserialize)]
pub struct LanguageSettings {
/// How many columns a tab should occupy.
pub tab_size: NonZeroU32,
}
/// The settings for a particular language server.
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct LspSettings {
/// The settings for the language server binary.
pub binary: Option<BinarySettings>,
/// The initialization options to pass to the language server.
pub initialization_options: Option<serde_json::Value>,
/// The settings to pass to language server.
pub settings: Option<serde_json::Value>,
}
/// The settings for a language server binary.
#[derive(Debug, Serialize, Deserialize)]
pub struct BinarySettings {
/// The path to the binary.
pub path: Option<String>,
/// The arguments to pass to the binary.
pub arguments: Option<Vec<String>>,
}

View File

@@ -0,0 +1,41 @@
interface slash-command {
use common.{range};
/// A slash command for use in the Assistant.
record slash-command {
/// The name of the slash command.
name: string,
/// The description of the slash command.
description: string,
/// The tooltip text to display for the run button.
tooltip-text: string,
/// Whether this slash command requires an argument.
requires-argument: bool,
}
/// The output of a slash command.
record slash-command-output {
/// The text produced by the slash command.
text: string,
/// The list of sections to show in the slash command placeholder.
sections: list<slash-command-output-section>,
}
/// A section in the slash command output.
record slash-command-output-section {
/// The range this section occupies.
range: range,
/// The label to display in the placeholder for this section.
label: string,
}
/// A completion for a slash command argument.
record slash-command-argument-completion {
/// The label to display for this completion.
label: string,
/// The new text that should be inserted into the command when this completion is accepted.
new-text: string,
/// Whether the command should be run when accepting this completion.
run-command: bool,
}
}

Some files were not shown because too many files have changed in this diff Show More