Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into multi-server-completions-tailwind
Juliaff3865a4adcb
diff --cc Cargo.lockindex e27b5756aa9,91a8a12eacc..f4bf4506e45--- a/Cargo.lock+++ b/Cargo.lock@@@ -1249,10 -1199,39 +1198,39 @@@ source = "registry+https://github.com/rchecksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"[[package]]- name = "cfg_aliases"- version = "0.1.1"- source = "registry+https://github.com/rust-lang/crates.io-index"- checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"+ name = "channel"+ version = "0.1.0"+ dependencies = [+ "anyhow",+ "client",+ "collections",+ "db",+ "feature_flags",+ "futures 0.3.28",+ "gpui",+ "image",+ "language",+ "lazy_static",+ "log",+ "parking_lot 0.11.2",+ "postage",+ "rand 0.8.5",+ "rpc",+ "schemars",+ "serde",+ "serde_derive",+ "settings",+ "smol",+ "sum_tree",+ "tempfile",+ "text",+ "thiserror",- "time 0.3.27",++ "time 0.3.24",+ "tiny_http",+ "url",+ "util",+ "uuid 1.4.1",+ ][[package]]name = "chrono"@@@ -1421,11 -1395,11 +1394,11 @@@ dependencies ="serde_derive","settings","smol",- "staff_mode","sum_tree","tempfile",+ "text","thiserror",- "time 0.3.27",+ "time 0.3.24","tiny_http","url","util",@@@ -1526,8 -1504,9 +1503,9 @@@ dependencies ="settings","sha-1 0.9.8","sqlx",+ "text","theme",- "time 0.3.27",+ "time 0.3.24","tokio","tokio-tungstenite","toml 0.5.11",@@@ -2070,20 -2067,11 +2066,11 @@@ dependencies ="winapi 0.3.9",]- [[package]]- name = "cursor-icon"- version = "1.0.0"- source = "registry+https://github.com/rust-lang/crates.io-index"- checksum = "740bb192a8e2d1350119916954f4409ee7f62f149b536911eeb78ba5a20526bf"- dependencies = [- "serde",- ]-[[package]]name = "dashmap"-version = "5.5.1"+version = "5.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "edd72493923899c6f10c641bdbdeddc7183d6396641d99c1a0d1597f37f92e28"+checksum = "6943ae99c34386c84a470c499d3414f66502a41340aa895406e0d2e4a207b91d"dependencies = ["cfg-if 1.0.0","hashbrown 0.14.0",@@@ -2769,7 -2768,8 +2767,8 @@@ dependencies ="smol","sum_tree","tempfile",+ "text",- "time 0.3.27",+ "time 0.3.24","util",]@@@ -3160,7 -3161,8 +3160,8 @@@ dependencies ="smol","sqlez","sum_tree",+ "taffy",- "time 0.3.27",+ "time 0.3.24","tiny-skia","usvg","util",@@@ -3178,11 -3180,17 +3179,17 @@@ dependencies ="syn 1.0.109",]+ [[package]]+ name = "grid"+ version = "0.10.0"+ source = "registry+https://github.com/rust-lang/crates.io-index"+ checksum = "eec1c01eb1de97451ee0d60de7d81cf1e72aabefb021616027f3d1c3ec1c723c"+[[package]]name = "h2"-version = "0.3.21"+version = "0.3.20"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833"+checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049"dependencies = ["bytes 1.4.0","fnv",@@@ -5711,11 -5652,23 +5656,23 @@@ dependencies ="memchr",]+ [[package]]+ name = "quick_action_bar"+ version = "0.1.0"+ dependencies = [+ "ai",+ "editor",+ "gpui",+ "search",+ "theme",+ "workspace",+ ]+[[package]]name = "quote"-version = "1.0.33"+version = "1.0.32"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"+checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965"dependencies = ["proc-macro2",]@@@ -9632,51 -9527,15 +9523,15 @@@ checksum = "9aec5da331524158c6d1a4ac0ab[[package]]name = "windows_x86_64_msvc"-version = "0.48.5"+version = "0.48.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"+checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"- [[package]]- name = "winit"- version = "0.29.0-beta.0"- source = "registry+https://github.com/rust-lang/crates.io-index"- checksum = "2f1afaf8490cc3f1309520ebb53a4cd3fc3642c7df8064a4b074bb9867998d44"- dependencies = [- "android-activity",- "atomic-waker",- "bitflags 2.3.3",- "calloop",- "cfg_aliases",- "core-foundation",- "core-graphics",- "cursor-icon",- "dispatch",- "js-sys",- "libc",- "log",- "ndk",- "ndk-sys",- "objc2",- "once_cell",- "orbclient",- "raw-window-handle",- "redox_syscall 0.3.5",- "serde",- "smol_str",- "unicode-segmentation",- "wasm-bindgen",- "wasm-bindgen-futures",- "web-sys",- "web-time",- "windows-sys",- "xkbcommon-dl",- ]-[[package]]name = "winnow"-version = "0.5.14"+version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d09770118a7eb1ccaf4a594a221334119a44a814fcb0d31c5b85e83e97227a97"+checksum = "8bd122eb777186e60c3fdf765a58ac76e41c582f1f535fbf3314434c6b58f3f7"dependencies = ["memchr",]diff --cc crates/project/src/lsp_command.rsindex c1bb890d496,6b10ed26c1d..8beaea5031c--- a/crates/project/src/lsp_command.rs+++ b/crates/project/src/lsp_command.rs@@@ -12,14 -12,13 +12,16 @@@ use language::language_settings::{language_settings, InlayHintKind},point_from_lsp, point_to_lsp,proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},- range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CharKind, CodeAction,- Completion, OffsetRangeExt, PointUtf16, ToOffset, ToPointUtf16, Transaction, Unclipped,+ range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, BufferSnapshot, CachedLspAdapter, CharKind,+ CodeAction, Completion, OffsetRangeExt, PointUtf16, ToOffset, ToPointUtf16, Transaction,+ Unclipped,};-use lsp::{DocumentHighlightKind, LanguageServer, LanguageServerId, OneOf, ServerCapabilities};+use lsp::{+ CompletionListItemDefaultsEditRange, DocumentHighlightKind, LanguageServer, LanguageServerId,- ServerCapabilities,++ OneOf, ServerCapabilities,+};use std::{cmp::Reverse, ops::Range, path::Path, sync::Arc};+ use text::LineEnding;pub fn lsp_formatting_options(tab_size: u32) -> lsp::FormattingOptions {lsp::FormattingOptions {diff --cc crates/project/src/project.rsindex 597deacd1a1,f839c8d5c50..edada5c6307--- a/crates/project/src/project.rs+++ b/crates/project/src/project.rs@@@ -5265,24 -5156,292 +5198,309 @@@ impl Project}}+ pub fn search_local(+ &self,+ query: SearchQuery,+ cx: &mut ModelContext<Self>,+ ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {+ // Local search is split into several phases.+ // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match+ // and the second phase that finds positions of all the matches found in the candidate files.+ // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.+ //+ // It gets a bit hairy though, because we must account for files that do not have a persistent representation+ // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.+ //+ // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).+ // Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan+ // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.+ // 2. At this point, we have a list of all potentially matching buffers/files.+ // We sort that list by buffer path - this list is retained for later use.+ // We ensure that all buffers are now opened and available in project.+ // 3. We run a scan over all the candidate buffers on multiple background threads.+ // We cannot assume that there will even be a match - while at least one match+ // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.+ // There is also an auxilliary background thread responsible for result gathering.+ // This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),+ // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.+ // As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next+ // entry - which might already be available thanks to out-of-order processing.+ //+ // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.+ // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.+ // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index+ // in face of constantly updating list of sorted matches.+ // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.+ let snapshots = self+ .visible_worktrees(cx)+ .filter_map(|tree| {+ let tree = tree.read(cx).as_local()?;+ Some(tree.snapshot())+ })+ .collect::<Vec<_>>();++ let background = cx.background().clone();+ let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();+ if path_count == 0 {+ let (_, rx) = smol::channel::bounded(1024);+ return rx;+ }+ let workers = background.num_cpus().min(path_count);+ let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);+ let mut unnamed_files = vec![];+ let opened_buffers = self+ .opened_buffers+ .iter()+ .filter_map(|(_, b)| {+ let buffer = b.upgrade(cx)?;+ let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());+ if let Some(path) = snapshot.file().map(|file| file.path()) {+ Some((path.clone(), (buffer, snapshot)))+ } else {+ unnamed_files.push(buffer);+ None+ }+ })+ .collect();+ cx.background()+ .spawn(Self::background_search(+ unnamed_files,+ opened_buffers,+ cx.background().clone(),+ self.fs.clone(),+ workers,+ query.clone(),+ path_count,+ snapshots,+ matching_paths_tx,+ ))+ .detach();++ let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);+ let background = cx.background().clone();+ let (result_tx, result_rx) = smol::channel::bounded(1024);+ cx.background()+ .spawn(async move {+ let Ok(buffers) = buffers.await else {+ return;+ };++ let buffers_len = buffers.len();+ if buffers_len == 0 {+ return;+ }+ let query = &query;+ let (finished_tx, mut finished_rx) = smol::channel::unbounded();+ background+ .scoped(|scope| {+ #[derive(Clone)]+ struct FinishedStatus {+ entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,+ buffer_index: SearchMatchCandidateIndex,+ }++ for _ in 0..workers {+ let finished_tx = finished_tx.clone();+ let mut buffers_rx = buffers_rx.clone();+ scope.spawn(async move {+ while let Some((entry, buffer_index)) = buffers_rx.next().await {+ let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()+ {+ if query.file_matches(+ snapshot.file().map(|file| file.path().as_ref()),+ ) {+ query+ .search(&snapshot, None)+ .await+ .iter()+ .map(|range| {+ snapshot.anchor_before(range.start)+ ..snapshot.anchor_after(range.end)+ })+ .collect()+ } else {+ Vec::new()+ }+ } else {+ Vec::new()+ };++ let status = if !buffer_matches.is_empty() {+ let entry = if let Some((buffer, _)) = entry.as_ref() {+ Some((buffer.clone(), buffer_matches))+ } else {+ None+ };+ FinishedStatus {+ entry,+ buffer_index,+ }+ } else {+ FinishedStatus {+ entry: None,+ buffer_index,+ }+ };+ if finished_tx.send(status).await.is_err() {+ break;+ }+ }+ });+ }+ // Report sorted matches+ scope.spawn(async move {+ let mut current_index = 0;+ let mut scratch = vec![None; buffers_len];+ while let Some(status) = finished_rx.next().await {+ debug_assert!(+ scratch[status.buffer_index].is_none(),+ "Got match status of position {} twice",+ status.buffer_index+ );+ let index = status.buffer_index;+ scratch[index] = Some(status);+ while current_index < buffers_len {+ let Some(current_entry) = scratch[current_index].take() else {+ // We intentionally **do not** increment `current_index` here. When next element arrives+ // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)+ // this time.+ break;+ };+ if let Some(entry) = current_entry.entry {+ result_tx.send(entry).await.log_err();+ }+ current_index += 1;+ }+ if current_index == buffers_len {+ break;+ }+ }+ });+ })+ .await;+ })+ .detach();+ result_rx+ }+ /// Pick paths that might potentially contain a match of a given search query.+ async fn background_search(+ unnamed_buffers: Vec<ModelHandle<Buffer>>,+ opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,+ background: Arc<Background>,+ fs: Arc<dyn Fs>,+ workers: usize,+ query: SearchQuery,+ path_count: usize,+ snapshots: Vec<LocalSnapshot>,+ matching_paths_tx: Sender<SearchMatchCandidate>,+ ) {+ let fs = &fs;+ let query = &query;+ let matching_paths_tx = &matching_paths_tx;+ let snapshots = &snapshots;+ let paths_per_worker = (path_count + workers - 1) / workers;+ for buffer in unnamed_buffers {+ matching_paths_tx+ .send(SearchMatchCandidate::OpenBuffer {+ buffer: buffer.clone(),+ path: None,+ })+ .await+ .log_err();+ }+ for (path, (buffer, _)) in opened_buffers.iter() {+ matching_paths_tx+ .send(SearchMatchCandidate::OpenBuffer {+ buffer: buffer.clone(),+ path: Some(path.clone()),+ })+ .await+ .log_err();+ }+ background+ .scoped(|scope| {+ for worker_ix in 0..workers {+ let worker_start_ix = worker_ix * paths_per_worker;+ let worker_end_ix = worker_start_ix + paths_per_worker;+ let unnamed_buffers = opened_buffers.clone();+ scope.spawn(async move {+ let mut snapshot_start_ix = 0;+ let mut abs_path = PathBuf::new();+ for snapshot in snapshots {+ let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();+ if worker_end_ix <= snapshot_start_ix {+ break;+ } else if worker_start_ix > snapshot_end_ix {+ snapshot_start_ix = snapshot_end_ix;+ continue;+ } else {+ let start_in_snapshot =+ worker_start_ix.saturating_sub(snapshot_start_ix);+ let end_in_snapshot =+ cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;++ for entry in snapshot+ .files(false, start_in_snapshot)+ .take(end_in_snapshot - start_in_snapshot)+ {+ if matching_paths_tx.is_closed() {+ break;+ }+ if unnamed_buffers.contains_key(&entry.path) {+ continue;+ }+ let matches = if query.file_matches(Some(&entry.path)) {+ abs_path.clear();+ abs_path.push(&snapshot.abs_path());+ abs_path.push(&entry.path);+ if let Some(file) = fs.open_sync(&abs_path).await.log_err()+ {+ query.detect(file).unwrap_or(false)+ } else {+ false+ }+ } else {+ false+ };++ if matches {+ let project_path = SearchMatchCandidate::Path {+ worktree_id: snapshot.id(),+ path: entry.path.clone(),+ };+ if matching_paths_tx.send(project_path).await.is_err() {+ break;+ }+ }+ }++ snapshot_start_ix = snapshot_end_ix;+ }+ }+ });+ }+ })+ .await;+ }+- // TODO: Wire this up to allow selecting a server?+ fn request_primary_lsp<R: LspCommand>(+ &self,+ buffer_handle: ModelHandle<Buffer>,+ request: R,+ cx: &mut ModelContext<Self>,+ ) -> Task<Result<R::Response>>+ where+ <R::LspRequest as lsp::request::Request>::Result: Send,+ {+ let buffer = buffer_handle.read(cx);+ let server_id = match self.primary_language_server_for_buffer(buffer, cx) {+ Some((_, server)) => server.server_id(),+ None => return Task::ready(Ok(Default::default())),+ };++ self.request_lsp(buffer_handle, server_id, request, cx)+ }+fn request_lsp<R: LspCommand>(&self,buffer_handle: ModelHandle<Buffer>,diff --cc crates/vim/src/motion.rsindex 243653680b1,0d3fb700eff..4c8560a5973--- a/crates/vim/src/motion.rs+++ b/crates/vim/src/motion.rs@@@ -509,9 -659,13 +659,13 @@@ fn previous_word_startpoint}- fn first_non_whitespace(map: &DisplaySnapshot, from: DisplayPoint) -> DisplayPoint {- let mut last_point = DisplayPoint::new(from.row(), 0);+ fn first_non_whitespace(+ map: &DisplaySnapshot,+ display_lines: bool,+ from: DisplayPoint,+ ) -> DisplayPoint {+ let mut last_point = start_of_line(map, display_lines, from);- let language = map.buffer_snapshot.language_at(from.to_point(map));+ let scope = map.buffer_snapshot.language_scope_at(from.to_point(map));for (ch, point) in map.chars_at(last_point) {if ch == '\n' {return from;diff --cc crates/zed/src/languages/javascript/config.tomlindex 6f7ce49d3da,0435f96c921..2394c575392--- a/crates/zed/src/languages/javascript/config.toml+++ b/crates/zed/src/languages/javascript/config.toml@@@ -13,7 -13,7 +13,8 @@@ brackets ={ start = "`", end = "`", close = true, newline = false, not_in = ["comment", "string"] },{ start = "/*", end = " */", close = true, newline = false, not_in = ["comment", "string"] },]+ word_characters = ["$", "#"]+scope_opt_in_language_servers = ["tailwindcss-language-server"][overrides.element]line_comment = { remove = true }diff --cc crates/zed/src/languages/json.rsindex f7e8f874925,61d19ce5b65..049549ac5d6--- a/crates/zed/src/languages/json.rs+++ b/crates/zed/src/languages/json.rs@@@ -106,9 -102,9 +106,9 @@@ impl LspAdapter for JsonLspAdapterfn workspace_configuration(&self,cx: &mut AppContext,- ) -> Option<BoxFuture<'static, serde_json::Value>> {+ ) -> BoxFuture<'static, serde_json::Value> {let action_names = cx.all_action_names().collect::<Vec<_>>();- let staff_mode = cx.default_global::<StaffMode>().0;+ let staff_mode = cx.is_staff();let language_names = &self.languages.language_names();let settings_schema = cx.global::<SettingsStore>().json_schema(&SettingsJsonSchemaParams {diff --cc crates/zed/src/languages/tsx/config.tomlindex 3bdc638f731,63d1f85e643..a7f99bef5eb--- a/crates/zed/src/languages/tsx/config.toml+++ b/crates/zed/src/languages/tsx/config.toml@@@ -12,7 -12,7 +12,8 @@@ brackets ={ start = "`", end = "`", close = true, newline = false, not_in = ["string"] },{ start = "/*", end = " */", close = true, newline = false, not_in = ["string", "comment"] },]+ word_characters = ["#", "$"]+scope_opt_in_language_servers = ["tailwindcss-language-server"][overrides.element]line_comment = { remove = true }