Fix clippy::needless_borrow lint violations (#36444)

Release Notes:

- N/A
This commit is contained in:
Piotr Osiewicz 2025-08-18 23:54:35 +02:00 committed by GitHub
parent eecf142f06
commit 9e0e233319
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
242 changed files with 801 additions and 821 deletions

View file

@ -824,6 +824,7 @@ module_inception = { level = "deny" }
question_mark = { level = "deny" } question_mark = { level = "deny" }
redundant_closure = { level = "deny" } redundant_closure = { level = "deny" }
declare_interior_mutable_const = { level = "deny" } declare_interior_mutable_const = { level = "deny" }
needless_borrow = { level = "warn"}
# Individual rules that have violations in the codebase: # Individual rules that have violations in the codebase:
type_complexity = "allow" type_complexity = "allow"
# We often return trait objects from `new` functions. # We often return trait objects from `new` functions.

View file

@ -485,7 +485,7 @@ impl ContentBlock {
} }
fn resource_link_md(uri: &str) -> String { fn resource_link_md(uri: &str) -> String {
if let Some(uri) = MentionUri::parse(&uri).log_err() { if let Some(uri) = MentionUri::parse(uri).log_err() {
uri.as_link().to_string() uri.as_link().to_string()
} else { } else {
uri.to_string() uri.to_string()
@ -1416,7 +1416,7 @@ impl AcpThread {
fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> { fn user_message(&self, id: &UserMessageId) -> Option<&UserMessage> {
self.entries.iter().find_map(|entry| { self.entries.iter().find_map(|entry| {
if let AgentThreadEntry::UserMessage(message) = entry { if let AgentThreadEntry::UserMessage(message) = entry {
if message.id.as_ref() == Some(&id) { if message.id.as_ref() == Some(id) {
Some(message) Some(message)
} else { } else {
None None
@ -1430,7 +1430,7 @@ impl AcpThread {
fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> { fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
self.entries.iter_mut().enumerate().find_map(|(ix, entry)| { self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
if let AgentThreadEntry::UserMessage(message) = entry { if let AgentThreadEntry::UserMessage(message) = entry {
if message.id.as_ref() == Some(&id) { if message.id.as_ref() == Some(id) {
Some((ix, message)) Some((ix, message))
} else { } else {
None None
@ -2356,7 +2356,7 @@ mod tests {
fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) { fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
let sessions = self.sessions.lock(); let sessions = self.sessions.lock();
let thread = sessions.get(&session_id).unwrap().clone(); let thread = sessions.get(session_id).unwrap().clone();
cx.spawn(async move |cx| { cx.spawn(async move |cx| {
thread thread

View file

@ -71,8 +71,8 @@ impl Diff {
let hunk_ranges = { let hunk_ranges = {
let buffer = new_buffer.read(cx); let buffer = new_buffer.read(cx);
let diff = buffer_diff.read(cx); let diff = buffer_diff.read(cx);
diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, cx) diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer, cx)
.map(|diff_hunk| diff_hunk.buffer_range.to_point(&buffer)) .map(|diff_hunk| diff_hunk.buffer_range.to_point(buffer))
.collect::<Vec<_>>() .collect::<Vec<_>>()
}; };
@ -306,13 +306,13 @@ impl PendingDiff {
let buffer = self.buffer.read(cx); let buffer = self.buffer.read(cx);
let diff = self.diff.read(cx); let diff = self.diff.read(cx);
let mut ranges = diff let mut ranges = diff
.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, cx) .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer, cx)
.map(|diff_hunk| diff_hunk.buffer_range.to_point(&buffer)) .map(|diff_hunk| diff_hunk.buffer_range.to_point(buffer))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
ranges.extend( ranges.extend(
self.revealed_ranges self.revealed_ranges
.iter() .iter()
.map(|range| range.to_point(&buffer)), .map(|range| range.to_point(buffer)),
); );
ranges.sort_unstable_by_key(|range| (range.start, Reverse(range.end))); ranges.sort_unstable_by_key(|range| (range.start, Reverse(range.end)));

View file

@ -146,7 +146,7 @@ impl MentionUri {
FileIcons::get_folder_icon(false, cx) FileIcons::get_folder_icon(false, cx)
.unwrap_or_else(|| IconName::Folder.path().into()) .unwrap_or_else(|| IconName::Folder.path().into())
} else { } else {
FileIcons::get_icon(&abs_path, cx) FileIcons::get_icon(abs_path, cx)
.unwrap_or_else(|| IconName::File.path().into()) .unwrap_or_else(|| IconName::File.path().into())
} }
} }

View file

@ -290,7 +290,7 @@ impl ActionLog {
} }
_ = git_diff_updates_rx.changed().fuse() => { _ = git_diff_updates_rx.changed().fuse() => {
if let Some(git_diff) = git_diff.as_ref() { if let Some(git_diff) = git_diff.as_ref() {
Self::keep_committed_edits(&this, &buffer, &git_diff, cx).await?; Self::keep_committed_edits(&this, &buffer, git_diff, cx).await?;
} }
} }
} }
@ -498,7 +498,7 @@ impl ActionLog {
new: new_range, new: new_range,
}, },
&new_diff_base, &new_diff_base,
&buffer_snapshot.as_rope(), buffer_snapshot.as_rope(),
)); ));
} }
unreviewed_edits unreviewed_edits
@ -964,7 +964,7 @@ impl TrackedBuffer {
fn has_edits(&self, cx: &App) -> bool { fn has_edits(&self, cx: &App) -> bool {
self.diff self.diff
.read(cx) .read(cx)
.hunks(&self.buffer.read(cx), cx) .hunks(self.buffer.read(cx), cx)
.next() .next()
.is_some() .is_some()
} }
@ -2268,7 +2268,7 @@ mod tests {
log::info!("quiescing..."); log::info!("quiescing...");
cx.run_until_parked(); cx.run_until_parked();
action_log.update(cx, |log, cx| { action_log.update(cx, |log, cx| {
let tracked_buffer = log.tracked_buffers.get(&buffer).unwrap(); let tracked_buffer = log.tracked_buffers.get(buffer).unwrap();
let mut old_text = tracked_buffer.diff_base.clone(); let mut old_text = tracked_buffer.diff_base.clone();
let new_text = buffer.read(cx).as_rope(); let new_text = buffer.read(cx).as_rope();
for edit in tracked_buffer.unreviewed_edits.edits() { for edit in tracked_buffer.unreviewed_edits.edits() {

View file

@ -702,7 +702,7 @@ impl ActivityIndicator {
on_click: Some(Arc::new(|this, window, cx| { on_click: Some(Arc::new(|this, window, cx| {
this.dismiss_error_message(&DismissErrorMessage, window, cx) this.dismiss_error_message(&DismissErrorMessage, window, cx)
})), })),
tooltip_message: Some(Self::version_tooltip_message(&version)), tooltip_message: Some(Self::version_tooltip_message(version)),
}), }),
AutoUpdateStatus::Installing { version } => Some(Content { AutoUpdateStatus::Installing { version } => Some(Content {
icon: Some( icon: Some(
@ -714,13 +714,13 @@ impl ActivityIndicator {
on_click: Some(Arc::new(|this, window, cx| { on_click: Some(Arc::new(|this, window, cx| {
this.dismiss_error_message(&DismissErrorMessage, window, cx) this.dismiss_error_message(&DismissErrorMessage, window, cx)
})), })),
tooltip_message: Some(Self::version_tooltip_message(&version)), tooltip_message: Some(Self::version_tooltip_message(version)),
}), }),
AutoUpdateStatus::Updated { version } => Some(Content { AutoUpdateStatus::Updated { version } => Some(Content {
icon: None, icon: None,
message: "Click to restart and update Zed".to_string(), message: "Click to restart and update Zed".to_string(),
on_click: Some(Arc::new(move |_, _, cx| workspace::reload(cx))), on_click: Some(Arc::new(move |_, _, cx| workspace::reload(cx))),
tooltip_message: Some(Self::version_tooltip_message(&version)), tooltip_message: Some(Self::version_tooltip_message(version)),
}), }),
AutoUpdateStatus::Errored => Some(Content { AutoUpdateStatus::Errored => Some(Content {
icon: Some( icon: Some(

View file

@ -1692,7 +1692,7 @@ impl Thread {
self.last_received_chunk_at = Some(Instant::now()); self.last_received_chunk_at = Some(Instant::now());
let task = cx.spawn(async move |thread, cx| { let task = cx.spawn(async move |thread, cx| {
let stream_completion_future = model.stream_completion(request, &cx); let stream_completion_future = model.stream_completion(request, cx);
let initial_token_usage = let initial_token_usage =
thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage); thread.read_with(cx, |thread, _cx| thread.cumulative_token_usage);
let stream_completion = async { let stream_completion = async {
@ -1824,7 +1824,7 @@ impl Thread {
let streamed_input = if tool_use.is_input_complete { let streamed_input = if tool_use.is_input_complete {
None None
} else { } else {
Some((&tool_use.input).clone()) Some(tool_use.input.clone())
}; };
let ui_text = thread.tool_use.request_tool_use( let ui_text = thread.tool_use.request_tool_use(
@ -2051,7 +2051,7 @@ impl Thread {
retry_scheduled = thread retry_scheduled = thread
.handle_retryable_error_with_delay( .handle_retryable_error_with_delay(
&completion_error, completion_error,
Some(retry_strategy), Some(retry_strategy),
model.clone(), model.clone(),
intent, intent,
@ -2130,7 +2130,7 @@ impl Thread {
self.pending_summary = cx.spawn(async move |this, cx| { self.pending_summary = cx.spawn(async move |this, cx| {
let result = async { let result = async {
let mut messages = model.model.stream_completion(request, &cx).await?; let mut messages = model.model.stream_completion(request, cx).await?;
let mut new_summary = String::new(); let mut new_summary = String::new();
while let Some(event) = messages.next().await { while let Some(event) = messages.next().await {
@ -2456,7 +2456,7 @@ impl Thread {
// which result to prefer (the old task could complete after the new one, resulting in a // which result to prefer (the old task could complete after the new one, resulting in a
// stale summary). // stale summary).
self.detailed_summary_task = cx.spawn(async move |thread, cx| { self.detailed_summary_task = cx.spawn(async move |thread, cx| {
let stream = model.stream_completion_text(request, &cx); let stream = model.stream_completion_text(request, cx);
let Some(mut messages) = stream.await.log_err() else { let Some(mut messages) = stream.await.log_err() else {
thread thread
.update(cx, |thread, _cx| { .update(cx, |thread, _cx| {
@ -4043,7 +4043,7 @@ fn main() {{
}); });
let fake_model = model.as_fake(); let fake_model = model.as_fake();
simulate_successful_response(&fake_model, cx); simulate_successful_response(fake_model, cx);
// Should start generating summary when there are >= 2 messages // Should start generating summary when there are >= 2 messages
thread.read_with(cx, |thread, _| { thread.read_with(cx, |thread, _| {
@ -4138,7 +4138,7 @@ fn main() {{
}); });
let fake_model = model.as_fake(); let fake_model = model.as_fake();
simulate_successful_response(&fake_model, cx); simulate_successful_response(fake_model, cx);
thread.read_with(cx, |thread, _| { thread.read_with(cx, |thread, _| {
// State is still Error, not Generating // State is still Error, not Generating
@ -5420,7 +5420,7 @@ fn main() {{
}); });
let fake_model = model.as_fake(); let fake_model = model.as_fake();
simulate_successful_response(&fake_model, cx); simulate_successful_response(fake_model, cx);
thread.read_with(cx, |thread, _| { thread.read_with(cx, |thread, _| {
assert!(matches!(thread.summary(), ThreadSummary::Generating)); assert!(matches!(thread.summary(), ThreadSummary::Generating));

View file

@ -91,7 +91,7 @@ impl LanguageModels {
for provider in &providers { for provider in &providers {
for model in provider.recommended_models(cx) { for model in provider.recommended_models(cx) {
recommended_models.insert(model.id()); recommended_models.insert(model.id());
recommended.push(Self::map_language_model_to_info(&model, &provider)); recommended.push(Self::map_language_model_to_info(&model, provider));
} }
} }
if !recommended.is_empty() { if !recommended.is_empty() {

View file

@ -62,7 +62,7 @@ fn contains(
handlebars::RenderError::new("contains: missing or invalid query parameter") handlebars::RenderError::new("contains: missing or invalid query parameter")
})?; })?;
if list.contains(&query) { if list.contains(query) {
out.write("true")?; out.write("true")?;
} }

View file

@ -173,7 +173,7 @@ impl UserMessage {
&mut symbol_context, &mut symbol_context,
"\n{}", "\n{}",
MarkdownCodeBlock { MarkdownCodeBlock {
tag: &codeblock_tag(&abs_path, None), tag: &codeblock_tag(abs_path, None),
text: &content.to_string(), text: &content.to_string(),
} }
) )
@ -189,8 +189,8 @@ impl UserMessage {
&mut rules_context, &mut rules_context,
"\n{}", "\n{}",
MarkdownCodeBlock { MarkdownCodeBlock {
tag: &codeblock_tag(&path, Some(line_range)), tag: &codeblock_tag(path, Some(line_range)),
text: &content text: content
} }
) )
.ok(); .ok();
@ -207,7 +207,7 @@ impl UserMessage {
"\n{}", "\n{}",
MarkdownCodeBlock { MarkdownCodeBlock {
tag: "", tag: "",
text: &content text: content
} }
) )
.ok(); .ok();
@ -1048,7 +1048,7 @@ impl Thread {
tools, tools,
tool_choice: None, tool_choice: None,
stop: Vec::new(), stop: Vec::new(),
temperature: AgentSettings::temperature_for_model(&model, cx), temperature: AgentSettings::temperature_for_model(model, cx),
thinking_allowed: true, thinking_allowed: true,
}; };

View file

@ -103,7 +103,7 @@ impl ContextServerRegistry {
self.reload_tools_for_server(server_id.clone(), cx); self.reload_tools_for_server(server_id.clone(), cx);
} }
ContextServerStatus::Stopped | ContextServerStatus::Error(_) => { ContextServerStatus::Stopped | ContextServerStatus::Error(_) => {
self.registered_servers.remove(&server_id); self.registered_servers.remove(server_id);
cx.notify(); cx.notify();
} }
} }

View file

@ -471,7 +471,7 @@ fn resolve_path(
let parent_entry = parent_project_path let parent_entry = parent_project_path
.as_ref() .as_ref()
.and_then(|path| project.entry_for_path(&path, cx)) .and_then(|path| project.entry_for_path(path, cx))
.context("Can't create file: parent directory doesn't exist")?; .context("Can't create file: parent directory doesn't exist")?;
anyhow::ensure!( anyhow::ensure!(

View file

@ -80,7 +80,7 @@ impl AgentTool for TerminalTool {
let first_line = lines.next().unwrap_or_default(); let first_line = lines.next().unwrap_or_default();
let remaining_line_count = lines.count(); let remaining_line_count = lines.count();
match remaining_line_count { match remaining_line_count {
0 => MarkdownInlineCode(&first_line).to_string().into(), 0 => MarkdownInlineCode(first_line).to_string().into(),
1 => MarkdownInlineCode(&format!( 1 => MarkdownInlineCode(&format!(
"{} - {} more line", "{} - {} more line",
first_line, remaining_line_count first_line, remaining_line_count

View file

@ -19,14 +19,14 @@ pub async fn connect(
root_dir: &Path, root_dir: &Path,
cx: &mut AsyncApp, cx: &mut AsyncApp,
) -> Result<Rc<dyn AgentConnection>> { ) -> Result<Rc<dyn AgentConnection>> {
let conn = v1::AcpConnection::stdio(server_name, command.clone(), &root_dir, cx).await; let conn = v1::AcpConnection::stdio(server_name, command.clone(), root_dir, cx).await;
match conn { match conn {
Ok(conn) => Ok(Rc::new(conn) as _), Ok(conn) => Ok(Rc::new(conn) as _),
Err(err) if err.is::<UnsupportedVersion>() => { Err(err) if err.is::<UnsupportedVersion>() => {
// Consider re-using initialize response and subprocess when adding another version here // Consider re-using initialize response and subprocess when adding another version here
let conn: Rc<dyn AgentConnection> = let conn: Rc<dyn AgentConnection> =
Rc::new(v0::AcpConnection::stdio(server_name, command, &root_dir, cx).await?); Rc::new(v0::AcpConnection::stdio(server_name, command, root_dir, cx).await?);
Ok(conn) Ok(conn)
} }
Err(err) => Err(err), Err(err) => Err(err),

View file

@ -291,7 +291,7 @@ impl AgentConnection for ClaudeAgentConnection {
fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) { fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
let sessions = self.sessions.borrow(); let sessions = self.sessions.borrow();
let Some(session) = sessions.get(&session_id) else { let Some(session) = sessions.get(session_id) else {
log::warn!("Attempted to cancel nonexistent session {}", session_id); log::warn!("Attempted to cancel nonexistent session {}", session_id);
return; return;
}; };

View file

@ -552,11 +552,11 @@ fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx:
let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId); let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
let mut label = CodeLabel::default(); let mut label = CodeLabel::default();
label.push_str(&file_name, None); label.push_str(file_name, None);
label.push_str(" ", None); label.push_str(" ", None);
if let Some(directory) = directory { if let Some(directory) = directory {
label.push_str(&directory, comment_id); label.push_str(directory, comment_id);
} }
label.filter_range = 0..label.text().len(); label.filter_range = 0..label.text().len();

View file

@ -1191,7 +1191,7 @@ impl MentionSet {
}) })
} }
MentionUri::Fetch { url } => { MentionUri::Fetch { url } => {
let Some(content) = self.fetch_results.get(&url).cloned() else { let Some(content) = self.fetch_results.get(url).cloned() else {
return Task::ready(Err(anyhow!("missing fetch result"))); return Task::ready(Err(anyhow!("missing fetch result")));
}; };
let uri = uri.clone(); let uri = uri.clone();

View file

@ -330,7 +330,7 @@ async fn fuzzy_search(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut matches = match_strings( let mut matches = match_strings(
&candidates, &candidates,
&query, query,
false, false,
true, true,
100, 100,

View file

@ -696,7 +696,7 @@ impl AcpThreadView {
}; };
diff.update(cx, |diff, cx| { diff.update(cx, |diff, cx| {
diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx) diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
}) })
} }
@ -722,13 +722,13 @@ impl AcpThreadView {
let len = thread.read(cx).entries().len(); let len = thread.read(cx).entries().len();
let index = len - 1; let index = len - 1;
self.entry_view_state.update(cx, |view_state, cx| { self.entry_view_state.update(cx, |view_state, cx| {
view_state.sync_entry(index, &thread, window, cx) view_state.sync_entry(index, thread, window, cx)
}); });
self.list_state.splice(index..index, 1); self.list_state.splice(index..index, 1);
} }
AcpThreadEvent::EntryUpdated(index) => { AcpThreadEvent::EntryUpdated(index) => {
self.entry_view_state.update(cx, |view_state, cx| { self.entry_view_state.update(cx, |view_state, cx| {
view_state.sync_entry(*index, &thread, window, cx) view_state.sync_entry(*index, thread, window, cx)
}); });
self.list_state.splice(*index..index + 1, 1); self.list_state.splice(*index..index + 1, 1);
} }
@ -1427,7 +1427,7 @@ impl AcpThreadView {
Empty.into_any_element() Empty.into_any_element()
} }
} }
ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, &diff, cx), ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, cx),
ToolCallContent::Terminal(terminal) => { ToolCallContent::Terminal(terminal) => {
self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx) self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
} }
@ -1583,7 +1583,7 @@ impl AcpThreadView {
.border_color(self.tool_card_border_color(cx)) .border_color(self.tool_card_border_color(cx))
.child( .child(
if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix) if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
&& let Some(editor) = entry.editor_for_diff(&diff) && let Some(editor) = entry.editor_for_diff(diff)
{ {
editor.clone().into_any_element() editor.clone().into_any_element()
} else { } else {
@ -1783,7 +1783,7 @@ impl AcpThreadView {
.entry_view_state .entry_view_state
.read(cx) .read(cx)
.entry(entry_ix) .entry(entry_ix)
.and_then(|entry| entry.terminal(&terminal)); .and_then(|entry| entry.terminal(terminal));
let show_output = self.terminal_expanded && terminal_view.is_some(); let show_output = self.terminal_expanded && terminal_view.is_some();
v_flex() v_flex()
@ -2420,7 +2420,7 @@ impl AcpThreadView {
.buffer_font(cx) .buffer_font(cx)
}); });
let file_icon = FileIcons::get_icon(&path, cx) let file_icon = FileIcons::get_icon(path, cx)
.map(Icon::from_path) .map(Icon::from_path)
.map(|icon| icon.color(Color::Muted).size(IconSize::Small)) .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
.unwrap_or_else(|| { .unwrap_or_else(|| {
@ -3453,7 +3453,7 @@ impl Render for AcpThreadView {
configuration_view, configuration_view,
.. ..
} => self.render_auth_required_state( } => self.render_auth_required_state(
&connection, connection,
description.as_ref(), description.as_ref(),
configuration_view.as_ref(), configuration_view.as_ref(),
window, window,

View file

@ -1044,12 +1044,12 @@ impl ActiveThread {
); );
} }
ThreadEvent::StreamedAssistantText(message_id, text) => { ThreadEvent::StreamedAssistantText(message_id, text) => {
if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) { if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(message_id) {
rendered_message.append_text(text, cx); rendered_message.append_text(text, cx);
} }
} }
ThreadEvent::StreamedAssistantThinking(message_id, text) => { ThreadEvent::StreamedAssistantThinking(message_id, text) => {
if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) { if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(message_id) {
rendered_message.append_thinking(text, cx); rendered_message.append_thinking(text, cx);
} }
} }
@ -2473,7 +2473,7 @@ impl ActiveThread {
message_id, message_id,
index, index,
content.clone(), content.clone(),
&scroll_handle, scroll_handle,
Some(index) == pending_thinking_segment_index, Some(index) == pending_thinking_segment_index,
window, window,
cx, cx,

View file

@ -207,7 +207,7 @@ impl AgentDiffPane {
), ),
match &thread { match &thread {
AgentDiffThread::Native(thread) => { AgentDiffThread::Native(thread) => {
Some(cx.subscribe(&thread, |this, _thread, event, cx| { Some(cx.subscribe(thread, |this, _thread, event, cx| {
this.handle_thread_event(event, cx) this.handle_thread_event(event, cx)
})) }))
} }
@ -398,7 +398,7 @@ fn keep_edits_in_selection(
.disjoint_anchor_ranges() .disjoint_anchor_ranges()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
keep_edits_in_ranges(editor, buffer_snapshot, &thread, ranges, window, cx) keep_edits_in_ranges(editor, buffer_snapshot, thread, ranges, window, cx)
} }
fn reject_edits_in_selection( fn reject_edits_in_selection(
@ -412,7 +412,7 @@ fn reject_edits_in_selection(
.selections .selections
.disjoint_anchor_ranges() .disjoint_anchor_ranges()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
reject_edits_in_ranges(editor, buffer_snapshot, &thread, ranges, window, cx) reject_edits_in_ranges(editor, buffer_snapshot, thread, ranges, window, cx)
} }
fn keep_edits_in_ranges( fn keep_edits_in_ranges(
@ -1001,7 +1001,7 @@ impl AgentDiffToolbar {
return; return;
}; };
*state = agent_diff.read(cx).editor_state(&editor); *state = agent_diff.read(cx).editor_state(editor);
self.update_location(cx); self.update_location(cx);
cx.notify(); cx.notify();
} }
@ -1343,13 +1343,13 @@ impl AgentDiff {
}); });
let thread_subscription = match &thread { let thread_subscription = match &thread {
AgentDiffThread::Native(thread) => cx.subscribe_in(&thread, window, { AgentDiffThread::Native(thread) => cx.subscribe_in(thread, window, {
let workspace = workspace.clone(); let workspace = workspace.clone();
move |this, _thread, event, window, cx| { move |this, _thread, event, window, cx| {
this.handle_native_thread_event(&workspace, event, window, cx) this.handle_native_thread_event(&workspace, event, window, cx)
} }
}), }),
AgentDiffThread::AcpThread(thread) => cx.subscribe_in(&thread, window, { AgentDiffThread::AcpThread(thread) => cx.subscribe_in(thread, window, {
let workspace = workspace.clone(); let workspace = workspace.clone();
move |this, thread, event, window, cx| { move |this, thread, event, window, cx| {
this.handle_acp_thread_event(&workspace, thread, event, window, cx) this.handle_acp_thread_event(&workspace, thread, event, window, cx)
@ -1357,11 +1357,11 @@ impl AgentDiff {
}), }),
}; };
if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) { if let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) {
// replace thread and action log subscription, but keep editors // replace thread and action log subscription, but keep editors
workspace_thread.thread = thread.downgrade(); workspace_thread.thread = thread.downgrade();
workspace_thread._thread_subscriptions = (action_log_subscription, thread_subscription); workspace_thread._thread_subscriptions = (action_log_subscription, thread_subscription);
self.update_reviewing_editors(&workspace, window, cx); self.update_reviewing_editors(workspace, window, cx);
return; return;
} }
@ -1677,7 +1677,7 @@ impl AgentDiff {
editor.register_addon(EditorAgentDiffAddon); editor.register_addon(EditorAgentDiffAddon);
}); });
} else { } else {
unaffected.remove(&weak_editor); unaffected.remove(weak_editor);
} }
if new_state == EditorState::Reviewing && previous_state != Some(new_state) { if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
@ -1730,7 +1730,7 @@ impl AgentDiff {
fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState { fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
self.reviewing_editors self.reviewing_editors
.get(&editor) .get(editor)
.cloned() .cloned()
.unwrap_or(EditorState::Idle) .unwrap_or(EditorState::Idle)
} }

View file

@ -2923,7 +2923,7 @@ impl AgentPanel {
.style(ButtonStyle::Tinted(ui::TintColor::Warning)) .style(ButtonStyle::Tinted(ui::TintColor::Warning))
.label_size(LabelSize::Small) .label_size(LabelSize::Small)
.key_binding( .key_binding(
KeyBinding::for_action_in(&OpenSettings, &focus_handle, window, cx) KeyBinding::for_action_in(&OpenSettings, focus_handle, window, cx)
.map(|kb| kb.size(rems_from_px(12.))), .map(|kb| kb.size(rems_from_px(12.))),
) )
.on_click(|_event, window, cx| { .on_click(|_event, window, cx| {
@ -3329,7 +3329,7 @@ impl AgentPanel {
.paths() .paths()
.into_iter() .into_iter()
.map(|path| { .map(|path| {
Workspace::project_path_for_path(this.project.clone(), &path, false, cx) Workspace::project_path_for_path(this.project.clone(), path, false, cx)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
cx.spawn_in(window, async move |this, cx| { cx.spawn_in(window, async move |this, cx| {
@ -3599,7 +3599,7 @@ impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
let text_thread_store = None; let text_thread_store = None;
let context_store = cx.new(|_| ContextStore::new(project.clone(), None)); let context_store = cx.new(|_| ContextStore::new(project.clone(), None));
assistant.assist( assistant.assist(
&prompt_editor, prompt_editor,
self.workspace.clone(), self.workspace.clone(),
context_store, context_store,
project, project,

View file

@ -388,7 +388,7 @@ impl CodegenAlternative {
} else { } else {
let request = self.build_request(&model, user_prompt, cx)?; let request = self.build_request(&model, user_prompt, cx)?;
cx.spawn(async move |_, cx| { cx.spawn(async move |_, cx| {
Ok(model.stream_completion_text(request.await, &cx).await?) Ok(model.stream_completion_text(request.await, cx).await?)
}) })
.boxed_local() .boxed_local()
}; };
@ -447,7 +447,7 @@ impl CodegenAlternative {
} }
}); });
let temperature = AgentSettings::temperature_for_model(&model, cx); let temperature = AgentSettings::temperature_for_model(model, cx);
Ok(cx.spawn(async move |_cx| { Ok(cx.spawn(async move |_cx| {
let mut request_message = LanguageModelRequestMessage { let mut request_message = LanguageModelRequestMessage {
@ -1028,7 +1028,7 @@ where
chunk.push('\n'); chunk.push('\n');
} }
chunk.push_str(&line); chunk.push_str(line);
} }
consumed += line.len(); consumed += line.len();

View file

@ -728,11 +728,11 @@ fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx:
let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId); let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
let mut label = CodeLabel::default(); let mut label = CodeLabel::default();
label.push_str(&file_name, None); label.push_str(file_name, None);
label.push_str(" ", None); label.push_str(" ", None);
if let Some(directory) = directory { if let Some(directory) = directory {
label.push_str(&directory, comment_id); label.push_str(directory, comment_id);
} }
label.filter_range = 0..label.text().len(); label.filter_range = 0..label.text().len();

View file

@ -315,7 +315,7 @@ pub fn render_file_context_entry(
context_store: WeakEntity<ContextStore>, context_store: WeakEntity<ContextStore>,
cx: &App, cx: &App,
) -> Stateful<Div> { ) -> Stateful<Div> {
let (file_name, directory) = extract_file_name_and_directory(&path, path_prefix); let (file_name, directory) = extract_file_name_and_directory(path, path_prefix);
let added = context_store.upgrade().and_then(|context_store| { let added = context_store.upgrade().and_then(|context_store| {
let project_path = ProjectPath { let project_path = ProjectPath {
@ -334,7 +334,7 @@ pub fn render_file_context_entry(
let file_icon = if is_directory { let file_icon = if is_directory {
FileIcons::get_folder_icon(false, cx) FileIcons::get_folder_icon(false, cx)
} else { } else {
FileIcons::get_icon(&path, cx) FileIcons::get_icon(path, cx)
} }
.map(Icon::from_path) .map(Icon::from_path)
.unwrap_or_else(|| Icon::new(IconName::File)); .unwrap_or_else(|| Icon::new(IconName::File));

View file

@ -289,7 +289,7 @@ pub(crate) fn search_symbols(
.iter() .iter()
.enumerate() .enumerate()
.map(|(id, symbol)| { .map(|(id, symbol)| {
StringMatchCandidate::new(id, &symbol.label.filter_text()) StringMatchCandidate::new(id, symbol.label.filter_text())
}) })
.partition(|candidate| { .partition(|candidate| {
project project

View file

@ -167,7 +167,7 @@ impl PickerDelegate for ThreadContextPickerDelegate {
return; return;
}; };
let open_thread_task = let open_thread_task =
thread_store.update(cx, |this, cx| this.open_thread(&id, window, cx)); thread_store.update(cx, |this, cx| this.open_thread(id, window, cx));
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let thread = open_thread_task.await?; let thread = open_thread_task.await?;
@ -236,7 +236,7 @@ pub fn render_thread_context_entry(
let is_added = match entry { let is_added = match entry {
ThreadContextEntry::Thread { id, .. } => context_store ThreadContextEntry::Thread { id, .. } => context_store
.upgrade() .upgrade()
.map_or(false, |ctx_store| ctx_store.read(cx).includes_thread(&id)), .map_or(false, |ctx_store| ctx_store.read(cx).includes_thread(id)),
ThreadContextEntry::Context { path, .. } => { ThreadContextEntry::Context { path, .. } => {
context_store.upgrade().map_or(false, |ctx_store| { context_store.upgrade().map_or(false, |ctx_store| {
ctx_store.read(cx).includes_text_thread(path) ctx_store.read(cx).includes_text_thread(path)
@ -338,7 +338,7 @@ pub(crate) fn search_threads(
let candidates = threads let candidates = threads
.iter() .iter()
.enumerate() .enumerate()
.map(|(id, (_, thread))| StringMatchCandidate::new(id, &thread.title())) .map(|(id, (_, thread))| StringMatchCandidate::new(id, thread.title()))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let matches = fuzzy::match_strings( let matches = fuzzy::match_strings(
&candidates, &candidates,

View file

@ -145,7 +145,7 @@ impl ContextStrip {
} }
let file_name = active_buffer.file()?.file_name(cx); let file_name = active_buffer.file()?.file_name(cx);
let icon_path = FileIcons::get_icon(&Path::new(&file_name), cx); let icon_path = FileIcons::get_icon(Path::new(&file_name), cx);
Some(SuggestedContext::File { Some(SuggestedContext::File {
name: file_name.to_string_lossy().into_owned().into(), name: file_name.to_string_lossy().into_owned().into(),
buffer: active_buffer_entity.downgrade(), buffer: active_buffer_entity.downgrade(),
@ -377,7 +377,7 @@ impl ContextStrip {
fn add_suggested_context(&mut self, suggested: &SuggestedContext, cx: &mut Context<Self>) { fn add_suggested_context(&mut self, suggested: &SuggestedContext, cx: &mut Context<Self>) {
self.context_store.update(cx, |context_store, cx| { self.context_store.update(cx, |context_store, cx| {
context_store.add_suggested_context(&suggested, cx) context_store.add_suggested_context(suggested, cx)
}); });
cx.notify(); cx.notify();
} }

View file

@ -526,9 +526,9 @@ impl InlineAssistant {
if assist_to_focus.is_none() { if assist_to_focus.is_none() {
let focus_assist = if newest_selection.reversed { let focus_assist = if newest_selection.reversed {
range.start.to_point(&snapshot) == newest_selection.start range.start.to_point(snapshot) == newest_selection.start
} else { } else {
range.end.to_point(&snapshot) == newest_selection.end range.end.to_point(snapshot) == newest_selection.end
}; };
if focus_assist { if focus_assist {
assist_to_focus = Some(assist_id); assist_to_focus = Some(assist_id);
@ -550,7 +550,7 @@ impl InlineAssistant {
let editor_assists = self let editor_assists = self
.assists_by_editor .assists_by_editor
.entry(editor.downgrade()) .entry(editor.downgrade())
.or_insert_with(|| EditorInlineAssists::new(&editor, window, cx)); .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
let mut assist_group = InlineAssistGroup::new(); let mut assist_group = InlineAssistGroup::new();
for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists { for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
let codegen = prompt_editor.read(cx).codegen().clone(); let codegen = prompt_editor.read(cx).codegen().clone();
@ -649,7 +649,7 @@ impl InlineAssistant {
let editor_assists = self let editor_assists = self
.assists_by_editor .assists_by_editor
.entry(editor.downgrade()) .entry(editor.downgrade())
.or_insert_with(|| EditorInlineAssists::new(&editor, window, cx)); .or_insert_with(|| EditorInlineAssists::new(editor, window, cx));
let mut assist_group = InlineAssistGroup::new(); let mut assist_group = InlineAssistGroup::new();
self.assists.insert( self.assists.insert(

View file

@ -75,7 +75,7 @@ impl<T: 'static> Render for PromptEditor<T> {
let codegen = codegen.read(cx); let codegen = codegen.read(cx);
if codegen.alternative_count(cx) > 1 { if codegen.alternative_count(cx) > 1 {
buttons.push(self.render_cycle_controls(&codegen, cx)); buttons.push(self.render_cycle_controls(codegen, cx));
} }
let editor_margins = editor_margins.lock(); let editor_margins = editor_margins.lock();

View file

@ -296,7 +296,7 @@ impl ModelMatcher {
pub fn fuzzy_search(&self, query: &str) -> Vec<ModelInfo> { pub fn fuzzy_search(&self, query: &str) -> Vec<ModelInfo> {
let mut matches = self.bg_executor.block(match_strings( let mut matches = self.bg_executor.block(match_strings(
&self.candidates, &self.candidates,
&query, query,
false, false,
true, true,
100, 100,

View file

@ -1166,7 +1166,7 @@ impl MessageEditor {
.buffer_font(cx) .buffer_font(cx)
}); });
let file_icon = FileIcons::get_icon(&path, cx) let file_icon = FileIcons::get_icon(path, cx)
.map(Icon::from_path) .map(Icon::from_path)
.map(|icon| icon.color(Color::Muted).size(IconSize::Small)) .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
.unwrap_or_else(|| { .unwrap_or_else(|| {
@ -1559,9 +1559,8 @@ impl ContextCreasesAddon {
cx: &mut Context<Editor>, cx: &mut Context<Editor>,
) { ) {
self.creases.entry(key).or_default().extend(creases); self.creases.entry(key).or_default().extend(creases);
self._subscription = Some(cx.subscribe( self._subscription = Some(
&context_store, cx.subscribe(context_store, |editor, _, event, cx| match event {
|editor, _, event, cx| match event {
ContextStoreEvent::ContextRemoved(key) => { ContextStoreEvent::ContextRemoved(key) => {
let Some(this) = editor.addon_mut::<Self>() else { let Some(this) = editor.addon_mut::<Self>() else {
return; return;
@ -1581,8 +1580,8 @@ impl ContextCreasesAddon {
editor.edit(ranges.into_iter().zip(replacement_texts), cx); editor.edit(ranges.into_iter().zip(replacement_texts), cx);
cx.notify(); cx.notify();
} }
}, }),
)) )
} }
pub fn into_inner(self) -> HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>> { pub fn into_inner(self) -> HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>> {

View file

@ -214,7 +214,7 @@ impl PickerDelegate for SlashCommandDelegate {
let mut label = format!("{}", info.name); let mut label = format!("{}", info.name);
if let Some(args) = info.args.as_ref().filter(|_| selected) if let Some(args) = info.args.as_ref().filter(|_| selected)
{ {
label.push_str(&args); label.push_str(args);
} }
Label::new(label) Label::new(label)
.single_line() .single_line()

View file

@ -48,7 +48,7 @@ impl TerminalCodegen {
let prompt = prompt_task.await; let prompt = prompt_task.await;
let model_telemetry_id = model.telemetry_id(); let model_telemetry_id = model.telemetry_id();
let model_provider_id = model.provider_id(); let model_provider_id = model.provider_id();
let response = model.stream_completion_text(prompt, &cx).await; let response = model.stream_completion_text(prompt, cx).await;
let generate = async { let generate = async {
let message_id = response let message_id = response
.as_ref() .as_ref()

View file

@ -353,7 +353,7 @@ impl AddedContext {
name, name,
parent, parent,
tooltip: Some(full_path_string), tooltip: Some(full_path_string),
icon_path: FileIcons::get_icon(&full_path, cx), icon_path: FileIcons::get_icon(full_path, cx),
status: ContextStatus::Ready, status: ContextStatus::Ready,
render_hover: None, render_hover: None,
handle: AgentContextHandle::File(handle), handle: AgentContextHandle::File(handle),
@ -615,7 +615,7 @@ impl AddedContext {
let full_path_string: SharedString = full_path.to_string_lossy().into_owned().into(); let full_path_string: SharedString = full_path.to_string_lossy().into_owned().into();
let (name, parent) = let (name, parent) =
extract_file_name_and_directory_from_full_path(full_path, &full_path_string); extract_file_name_and_directory_from_full_path(full_path, &full_path_string);
let icon_path = FileIcons::get_icon(&full_path, cx); let icon_path = FileIcons::get_icon(full_path, cx);
(name, parent, icon_path) (name, parent, icon_path)
} else { } else {
("Image".into(), None, None) ("Image".into(), None, None)
@ -706,7 +706,7 @@ impl ContextFileExcerpt {
.and_then(|p| p.file_name()) .and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned().into()); .map(|n| n.to_string_lossy().into_owned().into());
let icon_path = FileIcons::get_icon(&full_path, cx); let icon_path = FileIcons::get_icon(full_path, cx);
ContextFileExcerpt { ContextFileExcerpt {
file_name_and_range: file_name_and_range.into(), file_name_and_range: file_name_and_range.into(),

View file

@ -592,7 +592,7 @@ impl MessageMetadata {
pub fn is_cache_valid(&self, buffer: &BufferSnapshot, range: &Range<usize>) -> bool { pub fn is_cache_valid(&self, buffer: &BufferSnapshot, range: &Range<usize>) -> bool {
let result = match &self.cache { let result = match &self.cache {
Some(MessageCacheMetadata { cached_at, .. }) => !buffer.has_edits_since_in_range( Some(MessageCacheMetadata { cached_at, .. }) => !buffer.has_edits_since_in_range(
&cached_at, cached_at,
Range { Range {
start: buffer.anchor_at(range.start, Bias::Right), start: buffer.anchor_at(range.start, Bias::Right),
end: buffer.anchor_at(range.end, Bias::Left), end: buffer.anchor_at(range.end, Bias::Left),
@ -1413,7 +1413,7 @@ impl AssistantContext {
} }
let request = { let request = {
let mut req = self.to_completion_request(Some(&model), cx); let mut req = self.to_completion_request(Some(model), cx);
// Skip the last message because it's likely to change and // Skip the last message because it's likely to change and
// therefore would be a waste to cache. // therefore would be a waste to cache.
req.messages.pop(); req.messages.pop();
@ -1428,7 +1428,7 @@ impl AssistantContext {
let model = Arc::clone(model); let model = Arc::clone(model);
self.pending_cache_warming_task = cx.spawn(async move |this, cx| { self.pending_cache_warming_task = cx.spawn(async move |this, cx| {
async move { async move {
match model.stream_completion(request, &cx).await { match model.stream_completion(request, cx).await {
Ok(mut stream) => { Ok(mut stream) => {
stream.next().await; stream.next().await;
log::info!("Cache warming completed successfully"); log::info!("Cache warming completed successfully");
@ -1661,12 +1661,12 @@ impl AssistantContext {
) -> Range<usize> { ) -> Range<usize> {
let buffer = self.buffer.read(cx); let buffer = self.buffer.read(cx);
let start_ix = match all_annotations let start_ix = match all_annotations
.binary_search_by(|probe| probe.range().end.cmp(&range.start, &buffer)) .binary_search_by(|probe| probe.range().end.cmp(&range.start, buffer))
{ {
Ok(ix) | Err(ix) => ix, Ok(ix) | Err(ix) => ix,
}; };
let end_ix = match all_annotations let end_ix = match all_annotations
.binary_search_by(|probe| probe.range().start.cmp(&range.end, &buffer)) .binary_search_by(|probe| probe.range().start.cmp(&range.end, buffer))
{ {
Ok(ix) => ix + 1, Ok(ix) => ix + 1,
Err(ix) => ix, Err(ix) => ix,
@ -2045,7 +2045,7 @@ impl AssistantContext {
let task = cx.spawn({ let task = cx.spawn({
async move |this, cx| { async move |this, cx| {
let stream = model.stream_completion(request, &cx); let stream = model.stream_completion(request, cx);
let assistant_message_id = assistant_message.id; let assistant_message_id = assistant_message.id;
let mut response_latency = None; let mut response_latency = None;
let stream_completion = async { let stream_completion = async {
@ -2708,7 +2708,7 @@ impl AssistantContext {
self.summary_task = cx.spawn(async move |this, cx| { self.summary_task = cx.spawn(async move |this, cx| {
let result = async { let result = async {
let stream = model.model.stream_completion_text(request, &cx); let stream = model.model.stream_completion_text(request, cx);
let mut messages = stream.await?; let mut messages = stream.await?;
let mut replaced = !replace_old; let mut replaced = !replace_old;
@ -2927,7 +2927,7 @@ impl AssistantContext {
if let Some(old_path) = old_path.as_ref() { if let Some(old_path) = old_path.as_ref() {
if new_path.as_path() != old_path.as_ref() { if new_path.as_path() != old_path.as_ref() {
fs.rename( fs.rename(
&old_path, old_path,
&new_path, &new_path,
RenameOptions { RenameOptions {
overwrite: true, overwrite: true,

View file

@ -1300,7 +1300,7 @@ fn test_summarize_error(
context.assist(cx); context.assist(cx);
}); });
simulate_successful_response(&model, cx); simulate_successful_response(model, cx);
context.read_with(cx, |context, _| { context.read_with(cx, |context, _| {
assert!(!context.summary().content().unwrap().done); assert!(!context.summary().content().unwrap().done);

View file

@ -44,7 +44,7 @@ impl SlashCommand for ContextServerSlashCommand {
parts.push(arg.name.as_str()); parts.push(arg.name.as_str());
} }
} }
create_label_for_command(&parts[0], &parts[1..], cx) create_label_for_command(parts[0], &parts[1..], cx)
} }
fn description(&self) -> String { fn description(&self) -> String {

View file

@ -249,7 +249,7 @@ fn collect_diagnostics(
let worktree = worktree.read(cx); let worktree = worktree.read(cx);
let worktree_root_path = Path::new(worktree.root_name()); let worktree_root_path = Path::new(worktree.root_name());
let relative_path = path.strip_prefix(worktree_root_path).ok()?; let relative_path = path.strip_prefix(worktree_root_path).ok()?;
worktree.absolutize(&relative_path).ok() worktree.absolutize(relative_path).ok()
}) })
}) })
.is_some() .is_some()
@ -365,7 +365,7 @@ pub fn collect_buffer_diagnostics(
) { ) {
for (_, group) in snapshot.diagnostic_groups(None) { for (_, group) in snapshot.diagnostic_groups(None) {
let entry = &group.entries[group.primary_ix]; let entry = &group.entries[group.primary_ix];
collect_diagnostic(output, entry, &snapshot, include_warnings) collect_diagnostic(output, entry, snapshot, include_warnings)
} }
} }
@ -396,7 +396,7 @@ fn collect_diagnostic(
let start_row = range.start.row.saturating_sub(EXCERPT_EXPANSION_SIZE); let start_row = range.start.row.saturating_sub(EXCERPT_EXPANSION_SIZE);
let end_row = (range.end.row + EXCERPT_EXPANSION_SIZE).min(snapshot.max_point().row) + 1; let end_row = (range.end.row + EXCERPT_EXPANSION_SIZE).min(snapshot.max_point().row) + 1;
let excerpt_range = let excerpt_range =
Point::new(start_row, 0).to_offset(&snapshot)..Point::new(end_row, 0).to_offset(&snapshot); Point::new(start_row, 0).to_offset(snapshot)..Point::new(end_row, 0).to_offset(snapshot);
output.text.push_str("```"); output.text.push_str("```");
if let Some(language_name) = snapshot.language().map(|l| l.code_fence_block_name()) { if let Some(language_name) = snapshot.language().map(|l| l.code_fence_block_name()) {

View file

@ -536,7 +536,7 @@ fn resolve_path(
let parent_entry = parent_project_path let parent_entry = parent_project_path
.as_ref() .as_ref()
.and_then(|path| project.entry_for_path(&path, cx)) .and_then(|path| project.entry_for_path(path, cx))
.context("Can't create file: parent directory doesn't exist")?; .context("Can't create file: parent directory doesn't exist")?;
anyhow::ensure!( anyhow::ensure!(
@ -723,13 +723,13 @@ impl EditFileToolCard {
let buffer = buffer.read(cx); let buffer = buffer.read(cx);
let diff = diff.read(cx); let diff = diff.read(cx);
let mut ranges = diff let mut ranges = diff
.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &buffer, cx) .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, buffer, cx)
.map(|diff_hunk| diff_hunk.buffer_range.to_point(&buffer)) .map(|diff_hunk| diff_hunk.buffer_range.to_point(buffer))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
ranges.extend( ranges.extend(
self.revealed_ranges self.revealed_ranges
.iter() .iter()
.map(|range| range.to_point(&buffer)), .map(|range| range.to_point(buffer)),
); );
ranges.sort_unstable_by_key(|range| (range.start, Reverse(range.end))); ranges.sort_unstable_by_key(|range| (range.start, Reverse(range.end)));

View file

@ -894,7 +894,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not find files outside the project worktree" "grep_tool should not find files outside the project worktree"
@ -920,7 +920,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.iter().any(|p| p.contains("allowed_file.rs")), paths.iter().any(|p| p.contains("allowed_file.rs")),
"grep_tool should be able to search files inside worktrees" "grep_tool should be able to search files inside worktrees"
@ -946,7 +946,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not search files in .secretdir (file_scan_exclusions)" "grep_tool should not search files in .secretdir (file_scan_exclusions)"
@ -971,7 +971,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not search .mymetadata files (file_scan_exclusions)" "grep_tool should not search .mymetadata files (file_scan_exclusions)"
@ -997,7 +997,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not search .mysecrets (private_files)" "grep_tool should not search .mysecrets (private_files)"
@ -1022,7 +1022,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not search .privatekey files (private_files)" "grep_tool should not search .privatekey files (private_files)"
@ -1047,7 +1047,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not search .mysensitive files (private_files)" "grep_tool should not search .mysensitive files (private_files)"
@ -1073,7 +1073,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.iter().any(|p| p.contains("normal_file.rs")), paths.iter().any(|p| p.contains("normal_file.rs")),
"Should be able to search normal files" "Should be able to search normal files"
@ -1100,7 +1100,7 @@ mod tests {
}) })
.await; .await;
let results = result.unwrap(); let results = result.unwrap();
let paths = extract_paths_from_results(&results.content.as_str().unwrap()); let paths = extract_paths_from_results(results.content.as_str().unwrap());
assert!( assert!(
paths.is_empty(), paths.is_empty(),
"grep_tool should not allow escaping project boundaries with relative paths" "grep_tool should not allow escaping project boundaries with relative paths"
@ -1206,7 +1206,7 @@ mod tests {
.unwrap(); .unwrap();
let content = result.content.as_str().unwrap(); let content = result.content.as_str().unwrap();
let paths = extract_paths_from_results(&content); let paths = extract_paths_from_results(content);
// Should find matches in non-private files // Should find matches in non-private files
assert!( assert!(
@ -1271,7 +1271,7 @@ mod tests {
.unwrap(); .unwrap();
let content = result.content.as_str().unwrap(); let content = result.content.as_str().unwrap();
let paths = extract_paths_from_results(&content); let paths = extract_paths_from_results(content);
// Should only find matches in worktree1 *.rs files (excluding private ones) // Should only find matches in worktree1 *.rs files (excluding private ones)
assert!( assert!(

View file

@ -81,7 +81,7 @@ fn fit_patch_to_size(patch: &str, max_size: usize) -> String {
// Compression level 1: remove context lines in diff bodies, but // Compression level 1: remove context lines in diff bodies, but
// leave the counts and positions of inserted/deleted lines // leave the counts and positions of inserted/deleted lines
let mut current_size = patch.len(); let mut current_size = patch.len();
let mut file_patches = split_patch(&patch); let mut file_patches = split_patch(patch);
file_patches.sort_by_key(|patch| patch.len()); file_patches.sort_by_key(|patch| patch.len());
let compressed_patches = file_patches let compressed_patches = file_patches
.iter() .iter()

View file

@ -105,7 +105,7 @@ impl Tool for TerminalTool {
let first_line = lines.next().unwrap_or_default(); let first_line = lines.next().unwrap_or_default();
let remaining_line_count = lines.count(); let remaining_line_count = lines.count();
match remaining_line_count { match remaining_line_count {
0 => MarkdownInlineCode(&first_line).to_string(), 0 => MarkdownInlineCode(first_line).to_string(),
1 => MarkdownInlineCode(&format!( 1 => MarkdownInlineCode(&format!(
"{} - {} more line", "{} - {} more line",
first_line, remaining_line_count first_line, remaining_line_count

View file

@ -231,7 +231,7 @@ fn apply_dirty_filename_style(
let highlight = vec![(filename_position..text.len(), highlight_style)]; let highlight = vec![(filename_position..text.len(), highlight_style)];
Some( Some(
StyledText::new(text) StyledText::new(text)
.with_default_highlights(&text_style, highlight) .with_default_highlights(text_style, highlight)
.into_any(), .into_any(),
) )
} }

View file

@ -928,7 +928,7 @@ impl BufferDiff {
let new_index_text = self.inner.stage_or_unstage_hunks_impl( let new_index_text = self.inner.stage_or_unstage_hunks_impl(
&self.secondary_diff.as_ref()?.read(cx).inner, &self.secondary_diff.as_ref()?.read(cx).inner,
stage, stage,
&hunks, hunks,
buffer, buffer,
file_exists, file_exists,
); );
@ -952,12 +952,12 @@ impl BufferDiff {
cx: &App, cx: &App,
) -> Option<Range<Anchor>> { ) -> Option<Range<Anchor>> {
let start = self let start = self
.hunks_intersecting_range(range.clone(), &buffer, cx) .hunks_intersecting_range(range.clone(), buffer, cx)
.next()? .next()?
.buffer_range .buffer_range
.start; .start;
let end = self let end = self
.hunks_intersecting_range_rev(range.clone(), &buffer) .hunks_intersecting_range_rev(range.clone(), buffer)
.next()? .next()?
.buffer_range .buffer_range
.end; .end;
@ -1031,18 +1031,18 @@ impl BufferDiff {
&& state.base_text.syntax_update_count() && state.base_text.syntax_update_count()
== new_state.base_text.syntax_update_count() => == new_state.base_text.syntax_update_count() =>
{ {
(false, new_state.compare(&state, buffer)) (false, new_state.compare(state, buffer))
} }
_ => (true, Some(text::Anchor::MIN..text::Anchor::MAX)), _ => (true, Some(text::Anchor::MIN..text::Anchor::MAX)),
}; };
if let Some(secondary_changed_range) = secondary_diff_change { if let Some(secondary_changed_range) = secondary_diff_change {
if let Some(secondary_hunk_range) = if let Some(secondary_hunk_range) =
self.range_to_hunk_range(secondary_changed_range, &buffer, cx) self.range_to_hunk_range(secondary_changed_range, buffer, cx)
{ {
if let Some(range) = &mut changed_range { if let Some(range) = &mut changed_range {
range.start = secondary_hunk_range.start.min(&range.start, &buffer); range.start = secondary_hunk_range.start.min(&range.start, buffer);
range.end = secondary_hunk_range.end.max(&range.end, &buffer); range.end = secondary_hunk_range.end.max(&range.end, buffer);
} else { } else {
changed_range = Some(secondary_hunk_range); changed_range = Some(secondary_hunk_range);
} }
@ -1057,8 +1057,8 @@ impl BufferDiff {
if let Some((first, last)) = state.pending_hunks.first().zip(state.pending_hunks.last()) if let Some((first, last)) = state.pending_hunks.first().zip(state.pending_hunks.last())
{ {
if let Some(range) = &mut changed_range { if let Some(range) = &mut changed_range {
range.start = range.start.min(&first.buffer_range.start, &buffer); range.start = range.start.min(&first.buffer_range.start, buffer);
range.end = range.end.max(&last.buffer_range.end, &buffer); range.end = range.end.max(&last.buffer_range.end, buffer);
} else { } else {
changed_range = Some(first.buffer_range.start..last.buffer_range.end); changed_range = Some(first.buffer_range.start..last.buffer_range.end);
} }
@ -1797,7 +1797,7 @@ mod tests {
uncommitted_diff.update(cx, |diff, cx| { uncommitted_diff.update(cx, |diff, cx| {
let hunks = diff let hunks = diff
.hunks_intersecting_range(hunk_range.clone(), &buffer, &cx) .hunks_intersecting_range(hunk_range.clone(), &buffer, cx)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for hunk in &hunks { for hunk in &hunks {
assert_ne!( assert_ne!(
@ -1812,7 +1812,7 @@ mod tests {
.to_string(); .to_string();
let hunks = diff let hunks = diff
.hunks_intersecting_range(hunk_range.clone(), &buffer, &cx) .hunks_intersecting_range(hunk_range.clone(), &buffer, cx)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for hunk in &hunks { for hunk in &hunks {
assert_eq!( assert_eq!(
@ -1870,7 +1870,7 @@ mod tests {
.to_string(); .to_string();
assert_eq!(new_index_text, buffer_text); assert_eq!(new_index_text, buffer_text);
let hunk = diff.hunks(&buffer, &cx).next().unwrap(); let hunk = diff.hunks(&buffer, cx).next().unwrap();
assert_eq!( assert_eq!(
hunk.secondary_status, hunk.secondary_status,
DiffHunkSecondaryStatus::SecondaryHunkRemovalPending DiffHunkSecondaryStatus::SecondaryHunkRemovalPending
@ -1882,7 +1882,7 @@ mod tests {
.to_string(); .to_string();
assert_eq!(index_text, head_text); assert_eq!(index_text, head_text);
let hunk = diff.hunks(&buffer, &cx).next().unwrap(); let hunk = diff.hunks(&buffer, cx).next().unwrap();
// optimistically unstaged (fine, could also be HasSecondaryHunk) // optimistically unstaged (fine, could also be HasSecondaryHunk)
assert_eq!( assert_eq!(
hunk.secondary_status, hunk.secondary_status,

View file

@ -518,11 +518,11 @@ mod linux {
) -> Result<(), std::io::Error> { ) -> Result<(), std::io::Error> {
for _ in 0..100 { for _ in 0..100 {
thread::sleep(Duration::from_millis(10)); thread::sleep(Duration::from_millis(10));
if sock.connect_addr(&sock_addr).is_ok() { if sock.connect_addr(sock_addr).is_ok() {
return Ok(()); return Ok(());
} }
} }
sock.connect_addr(&sock_addr) sock.connect_addr(sock_addr)
} }
} }
} }

View file

@ -162,7 +162,7 @@ pub fn init(client: &Arc<Client>, cx: &mut App) {
let client = client.clone(); let client = client.clone();
move |_: &SignIn, cx| { move |_: &SignIn, cx| {
if let Some(client) = client.upgrade() { if let Some(client) = client.upgrade() {
cx.spawn(async move |cx| client.sign_in_with_optional_connect(true, &cx).await) cx.spawn(async move |cx| client.sign_in_with_optional_connect(true, cx).await)
.detach_and_log_err(cx); .detach_and_log_err(cx);
} }
} }
@ -173,7 +173,7 @@ pub fn init(client: &Arc<Client>, cx: &mut App) {
move |_: &SignOut, cx| { move |_: &SignOut, cx| {
if let Some(client) = client.upgrade() { if let Some(client) = client.upgrade() {
cx.spawn(async move |cx| { cx.spawn(async move |cx| {
client.sign_out(&cx).await; client.sign_out(cx).await;
}) })
.detach(); .detach();
} }
@ -185,7 +185,7 @@ pub fn init(client: &Arc<Client>, cx: &mut App) {
move |_: &Reconnect, cx| { move |_: &Reconnect, cx| {
if let Some(client) = client.upgrade() { if let Some(client) = client.upgrade() {
cx.spawn(async move |cx| { cx.spawn(async move |cx| {
client.reconnect(&cx); client.reconnect(cx);
}) })
.detach(); .detach();
} }
@ -677,7 +677,7 @@ impl Client {
let mut delay = INITIAL_RECONNECTION_DELAY; let mut delay = INITIAL_RECONNECTION_DELAY;
loop { loop {
match client.connect(true, &cx).await { match client.connect(true, cx).await {
ConnectionResult::Timeout => { ConnectionResult::Timeout => {
log::error!("client connect attempt timed out") log::error!("client connect attempt timed out")
} }
@ -701,7 +701,7 @@ impl Client {
Status::ReconnectionError { Status::ReconnectionError {
next_reconnection: Instant::now() + delay, next_reconnection: Instant::now() + delay,
}, },
&cx, cx,
); );
let jitter = let jitter =
Duration::from_millis(rng.gen_range(0..delay.as_millis() as u64)); Duration::from_millis(rng.gen_range(0..delay.as_millis() as u64));
@ -1151,7 +1151,7 @@ impl Client {
let this = self.clone(); let this = self.clone();
async move |cx| { async move |cx| {
while let Some(message) = incoming.next().await { while let Some(message) = incoming.next().await {
this.handle_message(message, &cx); this.handle_message(message, cx);
// Don't starve the main thread when receiving lots of messages at once. // Don't starve the main thread when receiving lots of messages at once.
smol::future::yield_now().await; smol::future::yield_now().await;
} }
@ -1169,12 +1169,12 @@ impl Client {
peer_id, peer_id,
}) })
{ {
this.set_status(Status::SignedOut, &cx); this.set_status(Status::SignedOut, cx);
} }
} }
Err(err) => { Err(err) => {
log::error!("connection error: {:?}", err); log::error!("connection error: {:?}", err);
this.set_status(Status::ConnectionLost, &cx); this.set_status(Status::ConnectionLost, cx);
} }
} }
}) })

View file

@ -943,21 +943,21 @@ impl Database {
let current_merge_conflicts = db_repository_entry let current_merge_conflicts = db_repository_entry
.current_merge_conflicts .current_merge_conflicts
.as_ref() .as_ref()
.map(|conflicts| serde_json::from_str(&conflicts)) .map(|conflicts| serde_json::from_str(conflicts))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let branch_summary = db_repository_entry let branch_summary = db_repository_entry
.branch_summary .branch_summary
.as_ref() .as_ref()
.map(|branch_summary| serde_json::from_str(&branch_summary)) .map(|branch_summary| serde_json::from_str(branch_summary))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let head_commit_details = db_repository_entry let head_commit_details = db_repository_entry
.head_commit_details .head_commit_details
.as_ref() .as_ref()
.map(|head_commit_details| serde_json::from_str(&head_commit_details)) .map(|head_commit_details| serde_json::from_str(head_commit_details))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();

View file

@ -746,21 +746,21 @@ impl Database {
let current_merge_conflicts = db_repository let current_merge_conflicts = db_repository
.current_merge_conflicts .current_merge_conflicts
.as_ref() .as_ref()
.map(|conflicts| serde_json::from_str(&conflicts)) .map(|conflicts| serde_json::from_str(conflicts))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let branch_summary = db_repository let branch_summary = db_repository
.branch_summary .branch_summary
.as_ref() .as_ref()
.map(|branch_summary| serde_json::from_str(&branch_summary)) .map(|branch_summary| serde_json::from_str(branch_summary))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let head_commit_details = db_repository let head_commit_details = db_repository
.head_commit_details .head_commit_details
.as_ref() .as_ref()
.map(|head_commit_details| serde_json::from_str(&head_commit_details)) .map(|head_commit_details| serde_json::from_str(head_commit_details))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();

View file

@ -245,7 +245,7 @@ impl MessageEditor {
if !candidates.is_empty() { if !candidates.is_empty() {
return cx.spawn(async move |_, cx| { return cx.spawn(async move |_, cx| {
let completion_response = Self::completions_for_candidates( let completion_response = Self::completions_for_candidates(
&cx, cx,
query.as_str(), query.as_str(),
&candidates, &candidates,
start_anchor..end_anchor, start_anchor..end_anchor,
@ -263,7 +263,7 @@ impl MessageEditor {
if !candidates.is_empty() { if !candidates.is_empty() {
return cx.spawn(async move |_, cx| { return cx.spawn(async move |_, cx| {
let completion_response = Self::completions_for_candidates( let completion_response = Self::completions_for_candidates(
&cx, cx,
query.as_str(), query.as_str(),
candidates, candidates,
start_anchor..end_anchor, start_anchor..end_anchor,

View file

@ -2317,7 +2317,7 @@ impl CollabPanel {
let client = this.client.clone(); let client = this.client.clone();
cx.spawn_in(window, async move |_, cx| { cx.spawn_in(window, async move |_, cx| {
client client
.connect(true, &cx) .connect(true, cx)
.await .await
.into_response() .into_response()
.notify_async_err(cx); .notify_async_err(cx);

View file

@ -643,7 +643,7 @@ impl Render for NotificationPanel {
let client = client.clone(); let client = client.clone();
window window
.spawn(cx, async move |cx| { .spawn(cx, async move |cx| {
match client.connect(true, &cx).await { match client.connect(true, cx).await {
util::ConnectionResult::Timeout => { util::ConnectionResult::Timeout => {
log::error!("Connection timeout"); log::error!("Connection timeout");
} }

View file

@ -315,12 +315,12 @@ impl McpServer {
Self::send_err( Self::send_err(
request_id, request_id,
format!("Tool not found: {}", params.name), format!("Tool not found: {}", params.name),
&outgoing_tx, outgoing_tx,
); );
} }
} }
Err(err) => { Err(err) => {
Self::send_err(request_id, err.to_string(), &outgoing_tx); Self::send_err(request_id, err.to_string(), outgoing_tx);
} }
} }
} }

View file

@ -691,7 +691,7 @@ impl CallToolResponse {
let mut text = String::new(); let mut text = String::new();
for chunk in &self.content { for chunk in &self.content {
if let ToolResponseContent::Text { text: chunk } = chunk { if let ToolResponseContent::Text { text: chunk } = chunk {
text.push_str(&chunk) text.push_str(chunk)
}; };
} }
text text

View file

@ -484,7 +484,7 @@ impl CopilotChat {
}; };
if this.oauth_token.is_some() { if this.oauth_token.is_some() {
cx.spawn(async move |this, mut cx| Self::update_models(&this, &mut cx).await) cx.spawn(async move |this, cx| Self::update_models(&this, cx).await)
.detach_and_log_err(cx); .detach_and_log_err(cx);
} }
@ -863,7 +863,7 @@ mod tests {
"object": "list" "object": "list"
}"#; }"#;
let schema: ModelSchema = serde_json::from_str(&json).unwrap(); let schema: ModelSchema = serde_json::from_str(json).unwrap();
assert_eq!(schema.data.len(), 2); assert_eq!(schema.data.len(), 2);
assert_eq!(schema.data[0].id, "gpt-4"); assert_eq!(schema.data[0].id, "gpt-4");

View file

@ -285,7 +285,7 @@ pub async fn download_adapter_from_github(
} }
if !adapter_path.exists() { if !adapter_path.exists() {
fs.create_dir(&adapter_path.as_path()) fs.create_dir(adapter_path.as_path())
.await .await
.context("Failed creating adapter path")?; .context("Failed creating adapter path")?;
} }

View file

@ -36,7 +36,7 @@ impl GoDebugAdapter {
delegate: &Arc<dyn DapDelegate>, delegate: &Arc<dyn DapDelegate>,
) -> Result<AdapterVersion> { ) -> Result<AdapterVersion> {
let release = latest_github_release( let release = latest_github_release(
&"zed-industries/delve-shim-dap", "zed-industries/delve-shim-dap",
true, true,
false, false,
delegate.http_client(), delegate.http_client(),

View file

@ -514,7 +514,7 @@ impl DebugAdapter for JsDebugAdapter {
} }
} }
self.get_installed_binary(delegate, &config, user_installed_path, user_args, cx) self.get_installed_binary(delegate, config, user_installed_path, user_args, cx)
.await .await
} }

View file

@ -717,7 +717,7 @@ impl DebugAdapter for PythonDebugAdapter {
local_path.display() local_path.display()
); );
return self return self
.get_installed_binary(delegate, &config, Some(local_path.clone()), user_args, None) .get_installed_binary(delegate, config, Some(local_path.clone()), user_args, None)
.await; .await;
} }
@ -754,7 +754,7 @@ impl DebugAdapter for PythonDebugAdapter {
return self return self
.get_installed_binary( .get_installed_binary(
delegate, delegate,
&config, config,
None, None,
user_args, user_args,
Some(toolchain.path.to_string()), Some(toolchain.path.to_string()),
@ -762,7 +762,7 @@ impl DebugAdapter for PythonDebugAdapter {
.await; .await;
} }
self.get_installed_binary(delegate, &config, None, user_args, None) self.get_installed_binary(delegate, config, None, user_args, None)
.await .await
} }

View file

@ -238,7 +238,7 @@ mod tests {
.unwrap(); .unwrap();
let _bad_db = open_db::<BadDB>( let _bad_db = open_db::<BadDB>(
tempdir.path(), tempdir.path(),
&release_channel::ReleaseChannel::Dev.dev_name(), release_channel::ReleaseChannel::Dev.dev_name(),
) )
.await; .await;
} }
@ -279,7 +279,7 @@ mod tests {
{ {
let corrupt_db = open_db::<CorruptedDB>( let corrupt_db = open_db::<CorruptedDB>(
tempdir.path(), tempdir.path(),
&release_channel::ReleaseChannel::Dev.dev_name(), release_channel::ReleaseChannel::Dev.dev_name(),
) )
.await; .await;
assert!(corrupt_db.persistent()); assert!(corrupt_db.persistent());
@ -287,7 +287,7 @@ mod tests {
let good_db = open_db::<GoodDB>( let good_db = open_db::<GoodDB>(
tempdir.path(), tempdir.path(),
&release_channel::ReleaseChannel::Dev.dev_name(), release_channel::ReleaseChannel::Dev.dev_name(),
) )
.await; .await;
assert!( assert!(
@ -334,7 +334,7 @@ mod tests {
// Setup the bad database // Setup the bad database
let corrupt_db = open_db::<CorruptedDB>( let corrupt_db = open_db::<CorruptedDB>(
tempdir.path(), tempdir.path(),
&release_channel::ReleaseChannel::Dev.dev_name(), release_channel::ReleaseChannel::Dev.dev_name(),
) )
.await; .await;
assert!(corrupt_db.persistent()); assert!(corrupt_db.persistent());
@ -347,7 +347,7 @@ mod tests {
let guard = thread::spawn(move || { let guard = thread::spawn(move || {
let good_db = smol::block_on(open_db::<GoodDB>( let good_db = smol::block_on(open_db::<GoodDB>(
tmp_path.as_path(), tmp_path.as_path(),
&release_channel::ReleaseChannel::Dev.dev_name(), release_channel::ReleaseChannel::Dev.dev_name(),
)); ));
assert!( assert!(
good_db.select_row::<usize>("SELECT * FROM test2").unwrap()() good_db.select_row::<usize>("SELECT * FROM test2").unwrap()()

View file

@ -485,7 +485,7 @@ impl LogStore {
&mut self, &mut self,
id: &LogStoreEntryIdentifier<'_>, id: &LogStoreEntryIdentifier<'_>,
) -> Option<&Vec<SharedString>> { ) -> Option<&Vec<SharedString>> {
self.get_debug_adapter_state(&id) self.get_debug_adapter_state(id)
.map(|state| &state.rpc_messages.initialization_sequence) .map(|state| &state.rpc_messages.initialization_sequence)
} }
} }
@ -536,11 +536,11 @@ impl Render for DapLogToolbarItemView {
}) })
.unwrap_or_else(|| "No adapter selected".into()), .unwrap_or_else(|| "No adapter selected".into()),
)) ))
.menu(move |mut window, cx| { .menu(move |window, cx| {
let log_view = log_view.clone(); let log_view = log_view.clone();
let menu_rows = menu_rows.clone(); let menu_rows = menu_rows.clone();
let project = project.clone(); let project = project.clone();
ContextMenu::build(&mut window, cx, move |mut menu, window, _cx| { ContextMenu::build(window, cx, move |mut menu, window, _cx| {
for row in menu_rows.into_iter() { for row in menu_rows.into_iter() {
menu = menu.custom_row(move |_window, _cx| { menu = menu.custom_row(move |_window, _cx| {
div() div()
@ -1131,7 +1131,7 @@ impl LogStore {
project: &WeakEntity<Project>, project: &WeakEntity<Project>,
session_id: SessionId, session_id: SessionId,
) -> Vec<SharedString> { ) -> Vec<SharedString> {
self.projects.get(&project).map_or(vec![], |state| { self.projects.get(project).map_or(vec![], |state| {
state state
.debug_sessions .debug_sessions
.get(&session_id) .get(&session_id)

View file

@ -693,7 +693,7 @@ impl DebugPanel {
) )
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| { |this, _, _window, cx| {
this.pause_thread(cx); this.pause_thread(cx);
}, },
@ -719,7 +719,7 @@ impl DebugPanel {
) )
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| this.continue_thread(cx), |this, _, _window, cx| this.continue_thread(cx),
)) ))
.disabled(thread_status != ThreadStatus::Stopped) .disabled(thread_status != ThreadStatus::Stopped)
@ -742,7 +742,7 @@ impl DebugPanel {
IconButton::new("debug-step-over", IconName::ArrowRight) IconButton::new("debug-step-over", IconName::ArrowRight)
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| { |this, _, _window, cx| {
this.step_over(cx); this.step_over(cx);
}, },
@ -768,7 +768,7 @@ impl DebugPanel {
) )
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| { |this, _, _window, cx| {
this.step_in(cx); this.step_in(cx);
}, },
@ -791,7 +791,7 @@ impl DebugPanel {
IconButton::new("debug-step-out", IconName::ArrowUpRight) IconButton::new("debug-step-out", IconName::ArrowUpRight)
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| { |this, _, _window, cx| {
this.step_out(cx); this.step_out(cx);
}, },
@ -815,7 +815,7 @@ impl DebugPanel {
IconButton::new("debug-restart", IconName::RotateCcw) IconButton::new("debug-restart", IconName::RotateCcw)
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, window, cx| { |this, _, window, cx| {
this.rerun_session(window, cx); this.rerun_session(window, cx);
}, },
@ -837,7 +837,7 @@ impl DebugPanel {
IconButton::new("debug-stop", IconName::Power) IconButton::new("debug-stop", IconName::Power)
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _window, cx| { |this, _, _window, cx| {
if this.session().read(cx).is_building() { if this.session().read(cx).is_building() {
this.session().update(cx, |session, cx| { this.session().update(cx, |session, cx| {
@ -892,7 +892,7 @@ impl DebugPanel {
) )
.icon_size(IconSize::Small) .icon_size(IconSize::Small)
.on_click(window.listener_for( .on_click(window.listener_for(
&running_state, running_state,
|this, _, _, cx| { |this, _, _, cx| {
this.detach_client(cx); this.detach_client(cx);
}, },
@ -1160,7 +1160,7 @@ impl DebugPanel {
workspace workspace
.project() .project()
.read(cx) .read(cx)
.project_path_for_absolute_path(&path, cx) .project_path_for_absolute_path(path, cx)
.context( .context(
"Couldn't get project path for .zed/debug.json in active worktree", "Couldn't get project path for .zed/debug.json in active worktree",
) )

View file

@ -413,7 +413,7 @@ impl NewProcessModal {
let Some(adapter) = self.debugger.as_ref() else { let Some(adapter) = self.debugger.as_ref() else {
return; return;
}; };
let scenario = self.debug_scenario(&adapter, cx); let scenario = self.debug_scenario(adapter, cx);
cx.spawn_in(window, async move |this, cx| { cx.spawn_in(window, async move |this, cx| {
let scenario = scenario.await.context("no scenario to save")?; let scenario = scenario.await.context("no scenario to save")?;
let worktree_id = task_contexts let worktree_id = task_contexts
@ -659,12 +659,7 @@ impl Render for NewProcessModal {
this.mode = NewProcessMode::Attach; this.mode = NewProcessMode::Attach;
if let Some(debugger) = this.debugger.as_ref() { if let Some(debugger) = this.debugger.as_ref() {
Self::update_attach_picker( Self::update_attach_picker(&this.attach_mode, debugger, window, cx);
&this.attach_mode,
&debugger,
window,
cx,
);
} }
this.mode_focus_handle(cx).focus(window); this.mode_focus_handle(cx).focus(window);
cx.notify(); cx.notify();
@ -1083,7 +1078,7 @@ impl DebugDelegate {
.into_iter() .into_iter()
.map(|(scenario, context)| { .map(|(scenario, context)| {
let (kind, scenario) = let (kind, scenario) =
Self::get_scenario_kind(&languages, &dap_registry, scenario); Self::get_scenario_kind(&languages, dap_registry, scenario);
(kind, scenario, Some(context)) (kind, scenario, Some(context))
}) })
.chain( .chain(
@ -1100,7 +1095,7 @@ impl DebugDelegate {
.filter(|(_, scenario)| valid_adapters.contains(&scenario.adapter)) .filter(|(_, scenario)| valid_adapters.contains(&scenario.adapter))
.map(|(kind, scenario)| { .map(|(kind, scenario)| {
let (language, scenario) = let (language, scenario) =
Self::get_scenario_kind(&languages, &dap_registry, scenario); Self::get_scenario_kind(&languages, dap_registry, scenario);
(language.or(Some(kind)), scenario, None) (language.or(Some(kind)), scenario, None)
}), }),
) )

View file

@ -341,7 +341,7 @@ impl SerializedPaneLayout {
pub(crate) fn in_order(&self) -> Vec<SerializedPaneLayout> { pub(crate) fn in_order(&self) -> Vec<SerializedPaneLayout> {
let mut panes = vec![]; let mut panes = vec![];
Self::inner_in_order(&self, &mut panes); Self::inner_in_order(self, &mut panes);
panes panes
} }

View file

@ -102,7 +102,7 @@ impl Render for RunningState {
.find(|pane| pane.read(cx).is_zoomed()); .find(|pane| pane.read(cx).is_zoomed());
let active = self.panes.panes().into_iter().next(); let active = self.panes.panes().into_iter().next();
let pane = if let Some(ref zoomed_pane) = zoomed_pane { let pane = if let Some(zoomed_pane) = zoomed_pane {
zoomed_pane.update(cx, |pane, cx| pane.render(window, cx).into_any_element()) zoomed_pane.update(cx, |pane, cx| pane.render(window, cx).into_any_element())
} else if let Some(active) = active { } else if let Some(active) = active {
self.panes self.panes
@ -627,7 +627,7 @@ impl RunningState {
if s.starts_with("\"$ZED_") && s.ends_with('"') { if s.starts_with("\"$ZED_") && s.ends_with('"') {
*s = s[1..s.len() - 1].to_string(); *s = s[1..s.len() - 1].to_string();
} }
if let Some(substituted) = substitute_variables_in_str(&s, context) { if let Some(substituted) = substitute_variables_in_str(s, context) {
*s = substituted; *s = substituted;
} }
} }
@ -657,7 +657,7 @@ impl RunningState {
} }
resolve_path(s); resolve_path(s);
if let Some(substituted) = substitute_variables_in_str(&s, context) { if let Some(substituted) = substitute_variables_in_str(s, context) {
*s = substituted; *s = substituted;
} }
} }
@ -954,7 +954,7 @@ impl RunningState {
inventory.read(cx).task_template_by_label( inventory.read(cx).task_template_by_label(
buffer, buffer,
worktree_id, worktree_id,
&label, label,
cx, cx,
) )
}) })
@ -1310,7 +1310,7 @@ impl RunningState {
let mut pane_item_status = IndexMap::from_iter( let mut pane_item_status = IndexMap::from_iter(
DebuggerPaneItem::all() DebuggerPaneItem::all()
.iter() .iter()
.filter(|kind| kind.is_supported(&caps)) .filter(|kind| kind.is_supported(caps))
.map(|kind| (*kind, false)), .map(|kind| (*kind, false)),
); );
self.panes.panes().iter().for_each(|pane| { self.panes.panes().iter().for_each(|pane| {
@ -1371,7 +1371,7 @@ impl RunningState {
this.serialize_layout(window, cx); this.serialize_layout(window, cx);
match event { match event {
Event::Remove { .. } => { Event::Remove { .. } => {
let _did_find_pane = this.panes.remove(&source_pane).is_ok(); let _did_find_pane = this.panes.remove(source_pane).is_ok();
debug_assert!(_did_find_pane); debug_assert!(_did_find_pane);
cx.notify(); cx.notify();
} }

View file

@ -494,7 +494,7 @@ impl BreakpointList {
fn toggle_data_breakpoint(&mut self, id: &str, cx: &mut Context<Self>) { fn toggle_data_breakpoint(&mut self, id: &str, cx: &mut Context<Self>) {
if let Some(session) = &self.session { if let Some(session) = &self.session {
session.update(cx, |this, cx| { session.update(cx, |this, cx| {
this.toggle_data_breakpoint(&id, cx); this.toggle_data_breakpoint(id, cx);
}); });
} }
} }
@ -502,7 +502,7 @@ impl BreakpointList {
fn toggle_exception_breakpoint(&mut self, id: &str, cx: &mut Context<Self>) { fn toggle_exception_breakpoint(&mut self, id: &str, cx: &mut Context<Self>) {
if let Some(session) = &self.session { if let Some(session) = &self.session {
session.update(cx, |this, cx| { session.update(cx, |this, cx| {
this.toggle_exception_breakpoint(&id, cx); this.toggle_exception_breakpoint(id, cx);
}); });
cx.notify(); cx.notify();
const EXCEPTION_SERIALIZATION_INTERVAL: Duration = Duration::from_secs(1); const EXCEPTION_SERIALIZATION_INTERVAL: Duration = Duration::from_secs(1);

View file

@ -697,7 +697,7 @@ impl ConsoleQueryBarCompletionProvider {
new_bytes: &[u8], new_bytes: &[u8],
snapshot: &TextBufferSnapshot, snapshot: &TextBufferSnapshot,
) -> Range<Anchor> { ) -> Range<Anchor> {
let buffer_offset = buffer_position.to_offset(&snapshot); let buffer_offset = buffer_position.to_offset(snapshot);
let buffer_bytes = &buffer_text.as_bytes()[0..buffer_offset]; let buffer_bytes = &buffer_text.as_bytes()[0..buffer_offset];
let mut prefix_len = 0; let mut prefix_len = 0;
@ -977,7 +977,7 @@ mod tests {
&cx.buffer_text(), &cx.buffer_text(),
snapshot.anchor_before(buffer_position), snapshot.anchor_before(buffer_position),
replacement.as_bytes(), replacement.as_bytes(),
&snapshot, snapshot,
); );
cx.update_editor(|editor, _, cx| { cx.update_editor(|editor, _, cx| {

View file

@ -262,7 +262,7 @@ impl MemoryView {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
use parse_int::parse; use parse_int::parse;
let Ok(as_address) = parse::<u64>(&memory_reference) else { let Ok(as_address) = parse::<u64>(memory_reference) else {
return; return;
}; };
let access_size = evaluate_name let access_size = evaluate_name
@ -931,7 +931,7 @@ impl Render for MemoryView {
v_flex() v_flex()
.size_full() .size_full()
.on_drag_move(cx.listener(|this, evt, _, _| { .on_drag_move(cx.listener(|this, evt, _, _| {
this.handle_memory_drag(&evt); this.handle_memory_drag(evt);
})) }))
.child(self.render_memory(cx).size_full()) .child(self.render_memory(cx).size_full())
.children(self.open_context_menu.as_ref().map(|(menu, position, _)| { .children(self.open_context_menu.as_ref().map(|(menu, position, _)| {

View file

@ -1289,7 +1289,7 @@ impl VariableList {
}), }),
) )
.child(self.render_variable_value( .child(self.render_variable_value(
&entry, entry,
&variable_color, &variable_color,
watcher.value.to_string(), watcher.value.to_string(),
cx, cx,
@ -1494,7 +1494,7 @@ impl VariableList {
}), }),
) )
.child(self.render_variable_value( .child(self.render_variable_value(
&variable, variable,
&variable_color, &variable_color,
dap.value.clone(), dap.value.clone(),
cx, cx,

View file

@ -139,7 +139,7 @@ async fn test_show_attach_modal_and_select_process(
workspace workspace
.update(cx, |_, window, cx| { .update(cx, |_, window, cx| {
let names = let names =
attach_modal.update(cx, |modal, cx| attach_modal::_process_names(&modal, cx)); attach_modal.update(cx, |modal, cx| attach_modal::_process_names(modal, cx));
// Initially all processes are visible. // Initially all processes are visible.
assert_eq!(3, names.len()); assert_eq!(3, names.len());
attach_modal.update(cx, |this, cx| { attach_modal.update(cx, |this, cx| {
@ -154,7 +154,7 @@ async fn test_show_attach_modal_and_select_process(
workspace workspace
.update(cx, |_, _, cx| { .update(cx, |_, _, cx| {
let names = let names =
attach_modal.update(cx, |modal, cx| attach_modal::_process_names(&modal, cx)); attach_modal.update(cx, |modal, cx| attach_modal::_process_names(modal, cx));
// Initially all processes are visible. // Initially all processes are visible.
assert_eq!(2, names.len()); assert_eq!(2, names.len());
}) })

View file

@ -107,7 +107,7 @@ async fn test_debug_session_substitutes_variables_and_relativizes_paths(
let expected_other_field = if input_path.contains("$ZED_WORKTREE_ROOT") { let expected_other_field = if input_path.contains("$ZED_WORKTREE_ROOT") {
input_path input_path
.replace("$ZED_WORKTREE_ROOT", &path!("/test/worktree/path")) .replace("$ZED_WORKTREE_ROOT", path!("/test/worktree/path"))
.to_owned() .to_owned()
} else { } else {
input_path.to_string() input_path.to_string()

View file

@ -46,7 +46,7 @@ impl DiagnosticRenderer {
markdown.push_str(" ("); markdown.push_str(" (");
} }
if let Some(source) = diagnostic.source.as_ref() { if let Some(source) = diagnostic.source.as_ref() {
markdown.push_str(&Markdown::escape(&source)); markdown.push_str(&Markdown::escape(source));
} }
if diagnostic.source.is_some() && diagnostic.code.is_some() { if diagnostic.source.is_some() && diagnostic.code.is_some() {
markdown.push(' '); markdown.push(' ');
@ -306,7 +306,7 @@ impl DiagnosticBlock {
cx: &mut Context<Editor>, cx: &mut Context<Editor>,
) { ) {
let snapshot = &editor.buffer().read(cx).snapshot(cx); let snapshot = &editor.buffer().read(cx).snapshot(cx);
let range = range.start.to_offset(&snapshot)..range.end.to_offset(&snapshot); let range = range.start.to_offset(snapshot)..range.end.to_offset(snapshot);
editor.unfold_ranges(&[range.start..range.end], true, false, cx); editor.unfold_ranges(&[range.start..range.end], true, false, cx);
editor.change_selections(Default::default(), window, cx, |s| { editor.change_selections(Default::default(), window, cx, |s| {

View file

@ -528,7 +528,7 @@ impl ProjectDiagnosticsEditor {
lsp::DiagnosticSeverity::ERROR lsp::DiagnosticSeverity::ERROR
}; };
cx.spawn_in(window, async move |this, mut cx| { cx.spawn_in(window, async move |this, cx| {
let diagnostics = buffer_snapshot let diagnostics = buffer_snapshot
.diagnostics_in_range::<_, text::Anchor>( .diagnostics_in_range::<_, text::Anchor>(
Point::zero()..buffer_snapshot.max_point(), Point::zero()..buffer_snapshot.max_point(),
@ -595,7 +595,7 @@ impl ProjectDiagnosticsEditor {
b.initial_range.clone(), b.initial_range.clone(),
DEFAULT_MULTIBUFFER_CONTEXT, DEFAULT_MULTIBUFFER_CONTEXT,
buffer_snapshot.clone(), buffer_snapshot.clone(),
&mut cx, cx,
) )
.await; .await;
let i = excerpt_ranges let i = excerpt_ranges

View file

@ -129,7 +129,7 @@ fn handle_frontmatter(book: &mut Book, errors: &mut HashSet<PreprocessorError>)
let Some((name, value)) = line.split_once(':') else { let Some((name, value)) = line.split_once(':') else {
errors.insert(PreprocessorError::InvalidFrontmatterLine(format!( errors.insert(PreprocessorError::InvalidFrontmatterLine(format!(
"{}: {}", "{}: {}",
chapter_breadcrumbs(&chapter), chapter_breadcrumbs(chapter),
line line
))); )));
continue; continue;
@ -402,11 +402,11 @@ fn handle_postprocessing() -> Result<()> {
path: &'a std::path::PathBuf, path: &'a std::path::PathBuf,
root: &'a std::path::PathBuf, root: &'a std::path::PathBuf,
) -> &'a std::path::Path { ) -> &'a std::path::Path {
&path.strip_prefix(&root).unwrap_or(&path) path.strip_prefix(&root).unwrap_or(path)
} }
fn extract_title_from_page(contents: &str, pretty_path: &std::path::Path) -> String { fn extract_title_from_page(contents: &str, pretty_path: &std::path::Path) -> String {
let title_tag_contents = &title_regex() let title_tag_contents = &title_regex()
.captures(&contents) .captures(contents)
.with_context(|| format!("Failed to find title in {:?}", pretty_path)) .with_context(|| format!("Failed to find title in {:?}", pretty_path))
.expect("Page has <title> element")[1]; .expect("Page has <title> element")[1];
let title = title_tag_contents let title = title_tag_contents

View file

@ -104,6 +104,6 @@ pub fn apply_related_actions(editor: &Entity<Editor>, window: &mut Window, cx: &
.filter_map(|buffer| buffer.read(cx).language()) .filter_map(|buffer| buffer.read(cx).language())
.any(|language| is_c_language(language)) .any(|language| is_c_language(language))
{ {
register_action(&editor, window, switch_source_header); register_action(editor, window, switch_source_header);
} }
} }

View file

@ -317,7 +317,7 @@ async fn filter_and_sort_matches(
let candidates: Arc<[StringMatchCandidate]> = completions let candidates: Arc<[StringMatchCandidate]> = completions
.iter() .iter()
.enumerate() .enumerate()
.map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text())) .map(|(id, completion)| StringMatchCandidate::new(id, completion.label.filter_text()))
.collect(); .collect();
let cancel_flag = Arc::new(AtomicBool::new(false)); let cancel_flag = Arc::new(AtomicBool::new(false));
let background_executor = cx.executor(); let background_executor = cx.executor();
@ -331,5 +331,5 @@ async fn filter_and_sort_matches(
background_executor, background_executor,
) )
.await; .await;
CompletionsMenu::sort_string_matches(matches, Some(query), snippet_sort_order, &completions) CompletionsMenu::sort_string_matches(matches, Some(query), snippet_sort_order, completions)
} }

View file

@ -321,7 +321,7 @@ impl CompletionsMenu {
let match_candidates = choices let match_candidates = choices
.iter() .iter()
.enumerate() .enumerate()
.map(|(id, completion)| StringMatchCandidate::new(id, &completion)) .map(|(id, completion)| StringMatchCandidate::new(id, completion))
.collect(); .collect();
let entries = choices let entries = choices
.iter() .iter()

View file

@ -77,7 +77,7 @@ fn create_highlight_endpoints(
let ranges = &text_highlights.1; let ranges = &text_highlights.1;
let start_ix = match ranges.binary_search_by(|probe| { let start_ix = match ranges.binary_search_by(|probe| {
let cmp = probe.end.cmp(&start, &buffer); let cmp = probe.end.cmp(&start, buffer);
if cmp.is_gt() { if cmp.is_gt() {
cmp::Ordering::Greater cmp::Ordering::Greater
} else { } else {
@ -88,18 +88,18 @@ fn create_highlight_endpoints(
}; };
for range in &ranges[start_ix..] { for range in &ranges[start_ix..] {
if range.start.cmp(&end, &buffer).is_ge() { if range.start.cmp(&end, buffer).is_ge() {
break; break;
} }
highlight_endpoints.push(HighlightEndpoint { highlight_endpoints.push(HighlightEndpoint {
offset: range.start.to_offset(&buffer), offset: range.start.to_offset(buffer),
is_start: true, is_start: true,
tag, tag,
style, style,
}); });
highlight_endpoints.push(HighlightEndpoint { highlight_endpoints.push(HighlightEndpoint {
offset: range.end.to_offset(&buffer), offset: range.end.to_offset(buffer),
is_start: false, is_start: false,
tag, tag,
style, style,

View file

@ -36,8 +36,8 @@ pub fn is_invisible(c: char) -> bool {
} else if c >= '\u{7f}' { } else if c >= '\u{7f}' {
c <= '\u{9f}' c <= '\u{9f}'
|| (c.is_whitespace() && c != IDEOGRAPHIC_SPACE) || (c.is_whitespace() && c != IDEOGRAPHIC_SPACE)
|| contains(c, &FORMAT) || contains(c, FORMAT)
|| contains(c, &OTHER) || contains(c, OTHER)
} else { } else {
false false
} }
@ -50,7 +50,7 @@ pub fn replacement(c: char) -> Option<&'static str> {
Some(C0_SYMBOLS[c as usize]) Some(C0_SYMBOLS[c as usize])
} else if c == '\x7f' { } else if c == '\x7f' {
Some(DEL) Some(DEL)
} else if contains(c, &PRESERVE) { } else if contains(c, PRESERVE) {
None None
} else { } else {
Some("\u{2007}") // fixed width space Some("\u{2007}") // fixed width space

View file

@ -1461,7 +1461,7 @@ mod tests {
} }
let mut prev_ix = 0; let mut prev_ix = 0;
for boundary in line_wrapper.wrap_line(&[LineFragment::text(&line)], wrap_width) { for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
wrapped_text.push_str(&line[prev_ix..boundary.ix]); wrapped_text.push_str(&line[prev_ix..boundary.ix]);
wrapped_text.push('\n'); wrapped_text.push('\n');
wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize)); wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));

View file

@ -2379,7 +2379,7 @@ impl Editor {
pending_selection pending_selection
.selection .selection
.range() .range()
.includes(&range, &snapshot) .includes(range, &snapshot)
}) })
{ {
return true; return true;
@ -3342,9 +3342,9 @@ impl Editor {
let old_cursor_position = &state.old_cursor_position; let old_cursor_position = &state.old_cursor_position;
self.selections_did_change(true, &old_cursor_position, state.effects, window, cx); self.selections_did_change(true, old_cursor_position, state.effects, window, cx);
if self.should_open_signature_help_automatically(&old_cursor_position, cx) { if self.should_open_signature_help_automatically(old_cursor_position, cx) {
self.show_signature_help(&ShowSignatureHelp, window, cx); self.show_signature_help(&ShowSignatureHelp, window, cx);
} }
} }
@ -3764,9 +3764,9 @@ impl Editor {
ColumnarSelectionState::FromMouse { ColumnarSelectionState::FromMouse {
selection_tail, selection_tail,
display_point, display_point,
} => display_point.unwrap_or_else(|| selection_tail.to_display_point(&display_map)), } => display_point.unwrap_or_else(|| selection_tail.to_display_point(display_map)),
ColumnarSelectionState::FromSelection { selection_tail } => { ColumnarSelectionState::FromSelection { selection_tail } => {
selection_tail.to_display_point(&display_map) selection_tail.to_display_point(display_map)
} }
}; };
@ -6082,7 +6082,7 @@ impl Editor {
if let Some(tasks) = &tasks { if let Some(tasks) = &tasks {
if let Some(project) = project { if let Some(project) = project {
task_context_task = task_context_task =
Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx); Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx);
} }
} }
@ -6864,7 +6864,7 @@ impl Editor {
for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges { for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
match_ranges.extend( match_ranges.extend(
regex regex
.search(&buffer_snapshot, Some(search_range.clone())) .search(buffer_snapshot, Some(search_range.clone()))
.await .await
.into_iter() .into_iter()
.filter_map(|match_range| { .filter_map(|match_range| {
@ -7206,7 +7206,7 @@ impl Editor {
return Some(false); return Some(false);
} }
let provider = self.edit_prediction_provider()?; let provider = self.edit_prediction_provider()?;
if !provider.is_enabled(&buffer, buffer_position, cx) { if !provider.is_enabled(buffer, buffer_position, cx) {
return Some(false); return Some(false);
} }
let buffer = buffer.read(cx); let buffer = buffer.read(cx);
@ -7966,7 +7966,7 @@ impl Editor {
let multi_buffer_anchor = let multi_buffer_anchor =
Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), breakpoint.position); Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), breakpoint.position);
let position = multi_buffer_anchor let position = multi_buffer_anchor
.to_point(&multi_buffer_snapshot) .to_point(multi_buffer_snapshot)
.to_display_point(&snapshot); .to_display_point(&snapshot);
breakpoint_display_points.insert( breakpoint_display_points.insert(
@ -8859,7 +8859,7 @@ impl Editor {
} }
let highlighted_edits = if let Some(edit_preview) = edit_preview.as_ref() { let highlighted_edits = if let Some(edit_preview) = edit_preview.as_ref() {
crate::edit_prediction_edit_text(&snapshot, edits, edit_preview, false, cx) crate::edit_prediction_edit_text(snapshot, edits, edit_preview, false, cx)
} else { } else {
// Fallback for providers without edit_preview // Fallback for providers without edit_preview
crate::edit_prediction_fallback_text(edits, cx) crate::edit_prediction_fallback_text(edits, cx)
@ -9222,7 +9222,7 @@ impl Editor {
.child(div().px_1p5().child(match &prediction.completion { .child(div().px_1p5().child(match &prediction.completion {
EditPrediction::Move { target, snapshot } => { EditPrediction::Move { target, snapshot } => {
use text::ToPoint as _; use text::ToPoint as _;
if target.text_anchor.to_point(&snapshot).row > cursor_point.row if target.text_anchor.to_point(snapshot).row > cursor_point.row
{ {
Icon::new(IconName::ZedPredictDown) Icon::new(IconName::ZedPredictDown)
} else { } else {
@ -9424,7 +9424,7 @@ impl Editor {
.gap_2() .gap_2()
.flex_1() .flex_1()
.child( .child(
if target.text_anchor.to_point(&snapshot).row > cursor_point.row { if target.text_anchor.to_point(snapshot).row > cursor_point.row {
Icon::new(IconName::ZedPredictDown) Icon::new(IconName::ZedPredictDown)
} else { } else {
Icon::new(IconName::ZedPredictUp) Icon::new(IconName::ZedPredictUp)
@ -9440,14 +9440,14 @@ impl Editor {
snapshot, snapshot,
display_mode: _, display_mode: _,
} => { } => {
let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row; let first_edit_row = edits.first()?.0.start.text_anchor.to_point(snapshot).row;
let (highlighted_edits, has_more_lines) = let (highlighted_edits, has_more_lines) =
if let Some(edit_preview) = edit_preview.as_ref() { if let Some(edit_preview) = edit_preview.as_ref() {
crate::edit_prediction_edit_text(&snapshot, &edits, edit_preview, true, cx) crate::edit_prediction_edit_text(snapshot, edits, edit_preview, true, cx)
.first_line_preview() .first_line_preview()
} else { } else {
crate::edit_prediction_fallback_text(&edits, cx).first_line_preview() crate::edit_prediction_fallback_text(edits, cx).first_line_preview()
}; };
let styled_text = gpui::StyledText::new(highlighted_edits.text) let styled_text = gpui::StyledText::new(highlighted_edits.text)
@ -9770,7 +9770,7 @@ impl Editor {
if let Some(choices) = &snippet.choices[snippet.active_index] { if let Some(choices) = &snippet.choices[snippet.active_index] {
if let Some(selection) = current_ranges.first() { if let Some(selection) = current_ranges.first() {
self.show_snippet_choices(&choices, selection.clone(), cx); self.show_snippet_choices(choices, selection.clone(), cx);
} }
} }
@ -12284,7 +12284,7 @@ impl Editor {
let trigger_in_words = let trigger_in_words =
this.show_edit_predictions_in_menu() || !had_active_edit_prediction; this.show_edit_predictions_in_menu() || !had_active_edit_prediction;
this.trigger_completion_on_input(&text, trigger_in_words, window, cx); this.trigger_completion_on_input(text, trigger_in_words, window, cx);
}); });
} }
@ -17896,7 +17896,7 @@ impl Editor {
ranges: &[Range<Anchor>], ranges: &[Range<Anchor>],
snapshot: &MultiBufferSnapshot, snapshot: &MultiBufferSnapshot,
) -> bool { ) -> bool {
let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot); let mut hunks = self.diff_hunks_in_ranges(ranges, snapshot);
hunks.any(|hunk| hunk.status().has_secondary_hunk()) hunks.any(|hunk| hunk.status().has_secondary_hunk())
} }
@ -19042,8 +19042,8 @@ impl Editor {
buffer_ranges.last() buffer_ranges.last()
}?; }?;
let selection = text::ToPoint::to_point(&range.start, &buffer).row let selection = text::ToPoint::to_point(&range.start, buffer).row
..text::ToPoint::to_point(&range.end, &buffer).row; ..text::ToPoint::to_point(&range.end, buffer).row;
Some(( Some((
multi_buffer.buffer(buffer.remote_id()).unwrap().clone(), multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
selection, selection,
@ -20055,8 +20055,7 @@ impl Editor {
self.registered_buffers self.registered_buffers
.entry(edited_buffer.read(cx).remote_id()) .entry(edited_buffer.read(cx).remote_id())
.or_insert_with(|| { .or_insert_with(|| {
project project.register_buffer_with_language_servers(edited_buffer, cx)
.register_buffer_with_language_servers(&edited_buffer, cx)
}); });
}); });
} }
@ -21079,7 +21078,7 @@ impl Editor {
}; };
if let Some((workspace, path)) = workspace.as_ref().zip(path) { if let Some((workspace, path)) = workspace.as_ref().zip(path) {
let Some(task) = cx let Some(task) = cx
.update_window_entity(&workspace, |workspace, window, cx| { .update_window_entity(workspace, |workspace, window, cx| {
workspace workspace
.open_path_preview(path, None, false, false, false, window, cx) .open_path_preview(path, None, false, false, false, window, cx)
}) })
@ -21303,14 +21302,14 @@ fn process_completion_for_edit(
debug_assert!( debug_assert!(
insert_range insert_range
.start .start
.cmp(&cursor_position, &buffer_snapshot) .cmp(cursor_position, &buffer_snapshot)
.is_le(), .is_le(),
"insert_range should start before or at cursor position" "insert_range should start before or at cursor position"
); );
debug_assert!( debug_assert!(
replace_range replace_range
.start .start
.cmp(&cursor_position, &buffer_snapshot) .cmp(cursor_position, &buffer_snapshot)
.is_le(), .is_le(),
"replace_range should start before or at cursor position" "replace_range should start before or at cursor position"
); );
@ -21344,7 +21343,7 @@ fn process_completion_for_edit(
LspInsertMode::ReplaceSuffix => { LspInsertMode::ReplaceSuffix => {
if replace_range if replace_range
.end .end
.cmp(&cursor_position, &buffer_snapshot) .cmp(cursor_position, &buffer_snapshot)
.is_gt() .is_gt()
{ {
let range_after_cursor = *cursor_position..replace_range.end; let range_after_cursor = *cursor_position..replace_range.end;
@ -21380,7 +21379,7 @@ fn process_completion_for_edit(
if range_to_replace if range_to_replace
.end .end
.cmp(&cursor_position, &buffer_snapshot) .cmp(cursor_position, &buffer_snapshot)
.is_lt() .is_lt()
{ {
range_to_replace.end = *cursor_position; range_to_replace.end = *cursor_position;
@ -21388,7 +21387,7 @@ fn process_completion_for_edit(
CompletionEdit { CompletionEdit {
new_text, new_text,
replace_range: range_to_replace.to_offset(&buffer), replace_range: range_to_replace.to_offset(buffer),
snippet, snippet,
} }
} }
@ -22137,7 +22136,7 @@ fn snippet_completions(
snippet snippet
.prefix .prefix
.iter() .iter()
.map(move |prefix| StringMatchCandidate::new(ix, &prefix)) .map(move |prefix| StringMatchCandidate::new(ix, prefix))
}) })
.collect::<Vec<StringMatchCandidate>>(); .collect::<Vec<StringMatchCandidate>>();
@ -22366,10 +22365,10 @@ impl SemanticsProvider for Entity<Project> {
cx: &mut App, cx: &mut App,
) -> Option<Task<Result<Vec<LocationLink>>>> { ) -> Option<Task<Result<Vec<LocationLink>>>> {
Some(self.update(cx, |project, cx| match kind { Some(self.update(cx, |project, cx| match kind {
GotoDefinitionKind::Symbol => project.definitions(&buffer, position, cx), GotoDefinitionKind::Symbol => project.definitions(buffer, position, cx),
GotoDefinitionKind::Declaration => project.declarations(&buffer, position, cx), GotoDefinitionKind::Declaration => project.declarations(buffer, position, cx),
GotoDefinitionKind::Type => project.type_definitions(&buffer, position, cx), GotoDefinitionKind::Type => project.type_definitions(buffer, position, cx),
GotoDefinitionKind::Implementation => project.implementations(&buffer, position, cx), GotoDefinitionKind::Implementation => project.implementations(buffer, position, cx),
})) }))
} }
@ -23778,7 +23777,7 @@ fn all_edits_insertions_or_deletions(
let mut all_deletions = true; let mut all_deletions = true;
for (range, new_text) in edits.iter() { for (range, new_text) in edits.iter() {
let range_is_empty = range.to_offset(&snapshot).is_empty(); let range_is_empty = range.to_offset(snapshot).is_empty();
let text_is_empty = new_text.is_empty(); let text_is_empty = new_text.is_empty();
if range_is_empty != text_is_empty { if range_is_empty != text_is_empty {

View file

@ -8393,7 +8393,7 @@ async fn test_autoindent_disabled_with_nested_language(cx: &mut TestAppContext)
buffer.set_language(Some(language), cx); buffer.set_language(Some(language), cx);
}); });
cx.set_state(&r#"struct A {ˇ}"#); cx.set_state(r#"struct A {ˇ}"#);
cx.update_editor(|editor, window, cx| { cx.update_editor(|editor, window, cx| {
editor.newline(&Default::default(), window, cx); editor.newline(&Default::default(), window, cx);
@ -8405,7 +8405,7 @@ async fn test_autoindent_disabled_with_nested_language(cx: &mut TestAppContext)
}" }"
)); ));
cx.set_state(&r#"select_biased!(ˇ)"#); cx.set_state(r#"select_biased!(ˇ)"#);
cx.update_editor(|editor, window, cx| { cx.update_editor(|editor, window, cx| {
editor.newline(&Default::default(), window, cx); editor.newline(&Default::default(), window, cx);
@ -12319,7 +12319,7 @@ async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext)
let counter = Arc::new(AtomicUsize::new(0)); let counter = Arc::new(AtomicUsize::new(0));
handle_completion_request_with_insert_and_replace( handle_completion_request_with_insert_and_replace(
&mut cx, &mut cx,
&buffer_marked_text, buffer_marked_text,
vec![(completion_text, completion_text)], vec![(completion_text, completion_text)],
counter.clone(), counter.clone(),
) )
@ -12333,7 +12333,7 @@ async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext)
.confirm_completion_replace(&ConfirmCompletionReplace, window, cx) .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
.unwrap() .unwrap()
}); });
cx.assert_editor_state(&expected_with_replace_mode); cx.assert_editor_state(expected_with_replace_mode);
handle_resolve_completion_request(&mut cx, None).await; handle_resolve_completion_request(&mut cx, None).await;
apply_additional_edits.await.unwrap(); apply_additional_edits.await.unwrap();
@ -12353,7 +12353,7 @@ async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext)
}); });
handle_completion_request_with_insert_and_replace( handle_completion_request_with_insert_and_replace(
&mut cx, &mut cx,
&buffer_marked_text, buffer_marked_text,
vec![(completion_text, completion_text)], vec![(completion_text, completion_text)],
counter.clone(), counter.clone(),
) )
@ -12367,7 +12367,7 @@ async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext)
.confirm_completion_insert(&ConfirmCompletionInsert, window, cx) .confirm_completion_insert(&ConfirmCompletionInsert, window, cx)
.unwrap() .unwrap()
}); });
cx.assert_editor_state(&expected_with_insert_mode); cx.assert_editor_state(expected_with_insert_mode);
handle_resolve_completion_request(&mut cx, None).await; handle_resolve_completion_request(&mut cx, None).await;
apply_additional_edits.await.unwrap(); apply_additional_edits.await.unwrap();
} }
@ -13141,7 +13141,7 @@ async fn test_word_completion(cx: &mut TestAppContext) {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["first", "last"], &["first", "last"],
"When LSP server is fast to reply, no fallback word completions are used" "When LSP server is fast to reply, no fallback word completions are used"
); );
@ -13164,7 +13164,7 @@ async fn test_word_completion(cx: &mut TestAppContext) {
cx.update_editor(|editor, _, _| { cx.update_editor(|editor, _, _| {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!(completion_menu_entries(&menu), &["one", "three", "two"], assert_eq!(completion_menu_entries(menu), &["one", "three", "two"],
"When LSP server is slow, document words can be shown instead, if configured accordingly"); "When LSP server is slow, document words can be shown instead, if configured accordingly");
} else { } else {
panic!("expected completion menu to be open"); panic!("expected completion menu to be open");
@ -13225,7 +13225,7 @@ async fn test_word_completions_do_not_duplicate_lsp_ones(cx: &mut TestAppContext
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["first", "last", "second"], &["first", "last", "second"],
"Word completions that has the same edit as the any of the LSP ones, should not be proposed" "Word completions that has the same edit as the any of the LSP ones, should not be proposed"
); );
@ -13281,7 +13281,7 @@ async fn test_word_completions_continue_on_typing(cx: &mut TestAppContext) {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["first", "last", "second"], &["first", "last", "second"],
"`ShowWordCompletions` action should show word completions" "`ShowWordCompletions` action should show word completions"
); );
@ -13298,7 +13298,7 @@ async fn test_word_completions_continue_on_typing(cx: &mut TestAppContext) {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["last"], &["last"],
"After showing word completions, further editing should filter them and not query the LSP" "After showing word completions, further editing should filter them and not query the LSP"
); );
@ -13337,7 +13337,7 @@ async fn test_word_completions_usually_skip_digits(cx: &mut TestAppContext) {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["let"], &["let"],
"With no digits in the completion query, no digits should be in the word completions" "With no digits in the completion query, no digits should be in the word completions"
); );
@ -13362,7 +13362,7 @@ async fn test_word_completions_usually_skip_digits(cx: &mut TestAppContext) {
cx.update_editor(|editor, _, _| { cx.update_editor(|editor, _, _| {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!(completion_menu_entries(&menu), &["33", "35f32"], "The digit is in the completion query, \ assert_eq!(completion_menu_entries(menu), &["33", "35f32"], "The digit is in the completion query, \
return matching words with digits (`33`, `35f32`) but exclude query duplicates (`3`)"); return matching words with digits (`33`, `35f32`) but exclude query duplicates (`3`)");
} else { } else {
panic!("expected completion menu to be open"); panic!("expected completion menu to be open");
@ -13599,7 +13599,7 @@ async fn test_completion_page_up_down_keys(cx: &mut TestAppContext) {
cx.update_editor(|editor, _, _| { cx.update_editor(|editor, _, _| {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!(completion_menu_entries(&menu), &["first", "last"]); assert_eq!(completion_menu_entries(menu), &["first", "last"]);
} else { } else {
panic!("expected completion menu to be open"); panic!("expected completion menu to be open");
} }
@ -16702,7 +16702,7 @@ async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestA
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!( assert_eq!(
completion_menu_entries(&menu), completion_menu_entries(menu),
&["bg-blue", "bg-red", "bg-yellow"] &["bg-blue", "bg-red", "bg-yellow"]
); );
} else { } else {
@ -16715,7 +16715,7 @@ async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestA
cx.update_editor(|editor, _, _| { cx.update_editor(|editor, _, _| {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!(completion_menu_entries(&menu), &["bg-blue", "bg-yellow"]); assert_eq!(completion_menu_entries(menu), &["bg-blue", "bg-yellow"]);
} else { } else {
panic!("expected completion menu to be open"); panic!("expected completion menu to be open");
} }
@ -16729,7 +16729,7 @@ async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestA
cx.update_editor(|editor, _, _| { cx.update_editor(|editor, _, _| {
if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref() if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
{ {
assert_eq!(completion_menu_entries(&menu), &["bg-yellow"]); assert_eq!(completion_menu_entries(menu), &["bg-yellow"]);
} else { } else {
panic!("expected completion menu to be open"); panic!("expected completion menu to be open");
} }
@ -17298,7 +17298,7 @@ async fn test_multibuffer_reverts(cx: &mut TestAppContext) {
(buffer_2.clone(), base_text_2), (buffer_2.clone(), base_text_2),
(buffer_3.clone(), base_text_3), (buffer_3.clone(), base_text_3),
] { ] {
let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx)); let diff = cx.new(|cx| BufferDiff::new_with_base_text(diff_base, &buffer, cx));
editor editor
.buffer .buffer
.update(cx, |buffer, cx| buffer.add_diff(diff, cx)); .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
@ -17919,7 +17919,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut TestAppContext) {
(buffer_2.clone(), file_2_old), (buffer_2.clone(), file_2_old),
(buffer_3.clone(), file_3_old), (buffer_3.clone(), file_3_old),
] { ] {
let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx)); let diff = cx.new(|cx| BufferDiff::new_with_base_text(diff_base, &buffer, cx));
editor editor
.buffer .buffer
.update(cx, |buffer, cx| buffer.add_diff(diff, cx)); .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
@ -21024,7 +21024,7 @@ async fn assert_highlighted_edits(
cx.update(|_window, cx| { cx.update(|_window, cx| {
let highlighted_edits = edit_prediction_edit_text( let highlighted_edits = edit_prediction_edit_text(
&snapshot.as_singleton().unwrap().2, snapshot.as_singleton().unwrap().2,
&edits, &edits,
&edit_preview, &edit_preview,
include_deletions, include_deletions,
@ -21091,7 +21091,7 @@ fn add_log_breakpoint_at_cursor(
.buffer_snapshot .buffer_snapshot
.anchor_before(Point::new(cursor_position.row, 0)); .anchor_before(Point::new(cursor_position.row, 0));
(breakpoint_position, Breakpoint::new_log(&log_message)) (breakpoint_position, Breakpoint::new_log(log_message))
}); });
editor.edit_breakpoint_at_anchor( editor.edit_breakpoint_at_anchor(

View file

@ -1162,7 +1162,7 @@ impl EditorElement {
.map_or(false, |state| state.keyboard_grace); .map_or(false, |state| state.keyboard_grace);
if mouse_over_inline_blame || mouse_over_popover { if mouse_over_inline_blame || mouse_over_popover {
editor.show_blame_popover(&blame_entry, event.position, false, cx); editor.show_blame_popover(blame_entry, event.position, false, cx);
} else if !keyboard_grace { } else if !keyboard_grace {
editor.hide_blame_popover(cx); editor.hide_blame_popover(cx);
} }
@ -2818,7 +2818,7 @@ impl EditorElement {
} }
let row = let row =
MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(&snapshot).row); MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
if snapshot.is_line_folded(row) { if snapshot.is_line_folded(row) {
return None; return None;
} }
@ -3312,7 +3312,7 @@ impl EditorElement {
let chunks = snapshot.highlighted_chunks(rows.clone(), true, style); let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
LineWithInvisibles::from_chunks( LineWithInvisibles::from_chunks(
chunks, chunks,
&style, style,
MAX_LINE_LEN, MAX_LINE_LEN,
rows.len(), rows.len(),
&snapshot.mode, &snapshot.mode,
@ -3393,7 +3393,7 @@ impl EditorElement {
let line_ix = align_to.row().0.checked_sub(rows.start.0); let line_ix = align_to.row().0.checked_sub(rows.start.0);
x_position = x_position =
if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) { if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
x_and_width(&layout) x_and_width(layout)
} else { } else {
x_and_width(&layout_line( x_and_width(&layout_line(
align_to.row(), align_to.row(),
@ -5549,9 +5549,9 @@ impl EditorElement {
// In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor. // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
// In multi buffers, we open file at the line number clicked, so use a pointing hand cursor. // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
if is_singleton { if is_singleton {
window.set_cursor_style(CursorStyle::IBeam, &hitbox); window.set_cursor_style(CursorStyle::IBeam, hitbox);
} else { } else {
window.set_cursor_style(CursorStyle::PointingHand, &hitbox); window.set_cursor_style(CursorStyle::PointingHand, hitbox);
} }
} }
} }
@ -5570,7 +5570,7 @@ impl EditorElement {
&layout.position_map.snapshot, &layout.position_map.snapshot,
line_height, line_height,
layout.gutter_hitbox.bounds, layout.gutter_hitbox.bounds,
&hunk, hunk,
); );
Some(( Some((
hunk_bounds, hunk_bounds,
@ -6092,10 +6092,10 @@ impl EditorElement {
if axis == ScrollbarAxis::Vertical { if axis == ScrollbarAxis::Vertical {
let fast_markers = let fast_markers =
self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx); self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
// Refresh slow scrollbar markers in the background. Below, we // Refresh slow scrollbar markers in the background. Below, we
// paint whatever markers have already been computed. // paint whatever markers have already been computed.
self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx); self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone(); let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
for marker in markers.iter().chain(&fast_markers) { for marker in markers.iter().chain(&fast_markers) {
@ -6129,7 +6129,7 @@ impl EditorElement {
if any_scrollbar_dragged { if any_scrollbar_dragged {
window.set_window_cursor_style(CursorStyle::Arrow); window.set_window_cursor_style(CursorStyle::Arrow);
} else { } else {
window.set_cursor_style(CursorStyle::Arrow, &hitbox); window.set_cursor_style(CursorStyle::Arrow, hitbox);
} }
} }
}) })
@ -9782,7 +9782,7 @@ pub fn layout_line(
let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style); let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
LineWithInvisibles::from_chunks( LineWithInvisibles::from_chunks(
chunks, chunks,
&style, style,
MAX_LINE_LEN, MAX_LINE_LEN,
1, 1,
&snapshot.mode, &snapshot.mode,

View file

@ -794,7 +794,7 @@ pub(crate) async fn find_file(
) -> Option<ResolvedPath> { ) -> Option<ResolvedPath> {
project project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.resolve_path_in_buffer(&candidate_file_path, buffer, cx) project.resolve_path_in_buffer(candidate_file_path, buffer, cx)
}) })
.ok()? .ok()?
.await .await

View file

@ -524,8 +524,8 @@ fn serialize_selection(
) -> proto::Selection { ) -> proto::Selection {
proto::Selection { proto::Selection {
id: selection.id as u64, id: selection.id as u64,
start: Some(serialize_anchor(&selection.start, &buffer)), start: Some(serialize_anchor(&selection.start, buffer)),
end: Some(serialize_anchor(&selection.end, &buffer)), end: Some(serialize_anchor(&selection.end, buffer)),
reversed: selection.reversed, reversed: selection.reversed,
} }
} }
@ -1010,7 +1010,7 @@ impl Item for Editor {
self.workspace = Some((workspace.weak_handle(), workspace.database_id())); self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
if let Some(workspace) = &workspace.weak_handle().upgrade() { if let Some(workspace) = &workspace.weak_handle().upgrade() {
cx.subscribe( cx.subscribe(
&workspace, workspace,
|editor, _, event: &workspace::Event, _cx| match event { |editor, _, event: &workspace::Event, _cx| match event {
workspace::Event::ModalOpened => { workspace::Event::ModalOpened => {
editor.mouse_context_menu.take(); editor.mouse_context_menu.take();
@ -1296,7 +1296,7 @@ impl SerializableItem for Editor {
project project
.read(cx) .read(cx)
.worktree_for_id(worktree_id, cx) .worktree_for_id(worktree_id, cx)
.and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok()) .and_then(|worktree| worktree.read(cx).absolutize(file.path()).ok())
.or_else(|| { .or_else(|| {
let full_path = file.full_path(cx); let full_path = file.full_path(cx);
let project_path = project.read(cx).find_project_path(&full_path, cx)?; let project_path = project.read(cx).find_project_path(&full_path, cx)?;
@ -1385,14 +1385,14 @@ impl ProjectItem for Editor {
}) })
{ {
editor.fold_ranges( editor.fold_ranges(
clip_ranges(&restoration_data.folds, &snapshot), clip_ranges(&restoration_data.folds, snapshot),
false, false,
window, window,
cx, cx,
); );
if !restoration_data.selections.is_empty() { if !restoration_data.selections.is_empty() {
editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| { editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
s.select_ranges(clip_ranges(&restoration_data.selections, &snapshot)); s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
}); });
} }
let (top_row, offset) = restoration_data.scroll_position; let (top_row, offset) = restoration_data.scroll_position;

View file

@ -37,7 +37,7 @@ pub(crate) fn should_auto_close(
let text = buffer let text = buffer
.text_for_range(edited_range.clone()) .text_for_range(edited_range.clone())
.collect::<String>(); .collect::<String>();
let edited_range = edited_range.to_offset(&buffer); let edited_range = edited_range.to_offset(buffer);
if !text.ends_with(">") { if !text.ends_with(">") {
continue; continue;
} }

View file

@ -207,7 +207,7 @@ impl Editor {
.entry(buffer_snapshot.remote_id()) .entry(buffer_snapshot.remote_id())
.or_insert_with(Vec::new); .or_insert_with(Vec::new);
let excerpt_point_range = let excerpt_point_range =
excerpt_range.context.to_point_utf16(&buffer_snapshot); excerpt_range.context.to_point_utf16(buffer_snapshot);
excerpt_data.push(( excerpt_data.push((
excerpt_id, excerpt_id,
buffer_snapshot.clone(), buffer_snapshot.clone(),

View file

@ -76,7 +76,7 @@ async fn lsp_task_context(
let project_env = project let project_env = project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.buffer_environment(&buffer, &worktree_store, cx) project.buffer_environment(buffer, &worktree_store, cx)
}) })
.ok()? .ok()?
.await; .await;

View file

@ -102,11 +102,11 @@ impl MouseContextMenu {
let display_snapshot = &editor let display_snapshot = &editor
.display_map .display_map
.update(cx, |display_map, cx| display_map.snapshot(cx)); .update(cx, |display_map, cx| display_map.snapshot(cx));
let selection_init_range = selection_init.display_range(&display_snapshot); let selection_init_range = selection_init.display_range(display_snapshot);
let selection_now_range = editor let selection_now_range = editor
.selections .selections
.newest_anchor() .newest_anchor()
.display_range(&display_snapshot); .display_range(display_snapshot);
if selection_now_range == selection_init_range { if selection_now_range == selection_init_range {
return; return;
} }

View file

@ -439,17 +439,17 @@ pub fn start_of_excerpt(
}; };
match direction { match direction {
Direction::Prev => { Direction::Prev => {
let mut start = excerpt.start_anchor().to_display_point(&map); let mut start = excerpt.start_anchor().to_display_point(map);
if start >= display_point && start.row() > DisplayRow(0) { if start >= display_point && start.row() > DisplayRow(0) {
let Some(excerpt) = map.buffer_snapshot.excerpt_before(excerpt.id()) else { let Some(excerpt) = map.buffer_snapshot.excerpt_before(excerpt.id()) else {
return display_point; return display_point;
}; };
start = excerpt.start_anchor().to_display_point(&map); start = excerpt.start_anchor().to_display_point(map);
} }
start start
} }
Direction::Next => { Direction::Next => {
let mut end = excerpt.end_anchor().to_display_point(&map); let mut end = excerpt.end_anchor().to_display_point(map);
*end.row_mut() += 1; *end.row_mut() += 1;
map.clip_point(end, Bias::Right) map.clip_point(end, Bias::Right)
} }
@ -467,7 +467,7 @@ pub fn end_of_excerpt(
}; };
match direction { match direction {
Direction::Prev => { Direction::Prev => {
let mut start = excerpt.start_anchor().to_display_point(&map); let mut start = excerpt.start_anchor().to_display_point(map);
if start.row() > DisplayRow(0) { if start.row() > DisplayRow(0) {
*start.row_mut() -= 1; *start.row_mut() -= 1;
} }
@ -476,7 +476,7 @@ pub fn end_of_excerpt(
start start
} }
Direction::Next => { Direction::Next => {
let mut end = excerpt.end_anchor().to_display_point(&map); let mut end = excerpt.end_anchor().to_display_point(map);
*end.column_mut() = 0; *end.column_mut() = 0;
if end <= display_point { if end <= display_point {
*end.row_mut() += 1; *end.row_mut() += 1;
@ -485,7 +485,7 @@ pub fn end_of_excerpt(
else { else {
return display_point; return display_point;
}; };
end = excerpt.end_anchor().to_display_point(&map); end = excerpt.end_anchor().to_display_point(map);
*end.column_mut() = 0; *end.column_mut() = 0;
} }
end end

View file

@ -478,7 +478,7 @@ impl SemanticsProvider for BranchBufferSemanticsProvider {
} }
fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool { fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
if let Some(buffer) = self.to_base(&buffer, &[], cx) { if let Some(buffer) = self.to_base(buffer, &[], cx) {
self.0.supports_inlay_hints(&buffer, cx) self.0.supports_inlay_hints(&buffer, cx)
} else { } else {
false false
@ -491,7 +491,7 @@ impl SemanticsProvider for BranchBufferSemanticsProvider {
position: text::Anchor, position: text::Anchor,
cx: &mut App, cx: &mut App,
) -> Option<Task<anyhow::Result<Vec<project::DocumentHighlight>>>> { ) -> Option<Task<anyhow::Result<Vec<project::DocumentHighlight>>>> {
let buffer = self.to_base(&buffer, &[position], cx)?; let buffer = self.to_base(buffer, &[position], cx)?;
self.0.document_highlights(&buffer, position, cx) self.0.document_highlights(&buffer, position, cx)
} }
@ -502,7 +502,7 @@ impl SemanticsProvider for BranchBufferSemanticsProvider {
kind: crate::GotoDefinitionKind, kind: crate::GotoDefinitionKind,
cx: &mut App, cx: &mut App,
) -> Option<Task<anyhow::Result<Vec<project::LocationLink>>>> { ) -> Option<Task<anyhow::Result<Vec<project::LocationLink>>>> {
let buffer = self.to_base(&buffer, &[position], cx)?; let buffer = self.to_base(buffer, &[position], cx)?;
self.0.definitions(&buffer, position, kind, cx) self.0.definitions(&buffer, position, kind, cx)
} }

View file

@ -35,12 +35,12 @@ pub fn apply_related_actions(editor: &Entity<Editor>, window: &mut Window, cx: &
.filter_map(|buffer| buffer.read(cx).language()) .filter_map(|buffer| buffer.read(cx).language())
.any(|language| is_rust_language(language)) .any(|language| is_rust_language(language))
{ {
register_action(&editor, window, go_to_parent_module); register_action(editor, window, go_to_parent_module);
register_action(&editor, window, expand_macro_recursively); register_action(editor, window, expand_macro_recursively);
register_action(&editor, window, open_docs); register_action(editor, window, open_docs);
register_action(&editor, window, cancel_flycheck_action); register_action(editor, window, cancel_flycheck_action);
register_action(&editor, window, run_flycheck_action); register_action(editor, window, run_flycheck_action);
register_action(&editor, window, clear_flycheck_action); register_action(editor, window, clear_flycheck_action);
} }
} }

View file

@ -196,7 +196,7 @@ impl Editor {
.highlight_text(&text, 0..signature.label.len()) .highlight_text(&text, 0..signature.label.len())
.into_iter() .into_iter()
.flat_map(|(range, highlight_id)| { .flat_map(|(range, highlight_id)| {
Some((range, highlight_id.style(&cx.theme().syntax())?)) Some((range, highlight_id.style(cx.theme().syntax())?))
}); });
signature.highlights = signature.highlights =
combine_highlights(signature.highlights.clone(), highlights) combine_highlights(signature.highlights.clone(), highlights)

View file

@ -189,7 +189,7 @@ pub fn editor_content_with_blocks(editor: &Entity<Editor>, cx: &mut VisualTestCo
continue; continue;
} }
}; };
let content = block_content_for_tests(&editor, custom_block.id, cx) let content = block_content_for_tests(editor, custom_block.id, cx)
.expect("block content not found"); .expect("block content not found");
// 2: "related info 1 for diagnostic 0" // 2: "related info 1 for diagnostic 0"
if let Some(height) = custom_block.height { if let Some(height) = custom_block.height {

View file

@ -520,7 +520,7 @@ async fn judge_example(
enable_telemetry: bool, enable_telemetry: bool,
cx: &AsyncApp, cx: &AsyncApp,
) -> JudgeOutput { ) -> JudgeOutput {
let judge_output = example.judge(model.clone(), &run_output, cx).await; let judge_output = example.judge(model.clone(), run_output, cx).await;
if enable_telemetry { if enable_telemetry {
telemetry::event!( telemetry::event!(

View file

@ -64,7 +64,7 @@ impl ExampleMetadata {
self.url self.url
.split('/') .split('/')
.next_back() .next_back()
.unwrap_or(&"") .unwrap_or("")
.trim_end_matches(".git") .trim_end_matches(".git")
.into() .into()
} }
@ -255,7 +255,7 @@ impl ExampleContext {
thread.update(cx, |thread, _cx| { thread.update(cx, |thread, _cx| {
if let Some(tool_use) = pending_tool_use { if let Some(tool_use) = pending_tool_use {
let mut tool_metrics = tool_metrics.lock().unwrap(); let mut tool_metrics = tool_metrics.lock().unwrap();
if let Some(tool_result) = thread.tool_result(&tool_use_id) { if let Some(tool_result) = thread.tool_result(tool_use_id) {
let message = if tool_result.is_error { let message = if tool_result.is_error {
format!("✖︎ {}", tool_use.name) format!("✖︎ {}", tool_use.name)
} else { } else {

View file

@ -459,8 +459,8 @@ impl ExampleInstance {
let mut output_file = let mut output_file =
File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md"); File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
let diff_task = self.judge_diff(model.clone(), &run_output, cx); let diff_task = self.judge_diff(model.clone(), run_output, cx);
let thread_task = self.judge_thread(model.clone(), &run_output, cx); let thread_task = self.judge_thread(model.clone(), run_output, cx);
let (diff_result, thread_result) = futures::join!(diff_task, thread_task); let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
@ -661,7 +661,7 @@ pub fn wait_for_lang_server(
.update(cx, |buffer, cx| { .update(cx, |buffer, cx| {
lsp_store.update(cx, |lsp_store, cx| { lsp_store.update(cx, |lsp_store, cx| {
lsp_store lsp_store
.language_servers_for_local_buffer(&buffer, cx) .language_servers_for_local_buffer(buffer, cx)
.next() .next()
.is_some() .is_some()
}) })
@ -693,7 +693,7 @@ pub fn wait_for_lang_server(
_ => {} _ => {}
} }
}), }),
cx.subscribe(&project, { cx.subscribe(project, {
let buffer = buffer.clone(); let buffer = buffer.clone();
move |project, event, cx| match event { move |project, event, cx| match event {
project::Event::LanguageServerAdded(_, _, _) => { project::Event::LanguageServerAdded(_, _, _) => {
@ -838,7 +838,7 @@ fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>)
for segment in &message.segments { for segment in &message.segments {
match segment { match segment {
MessageSegment::Text(text) => { MessageSegment::Text(text) => {
messages.push_str(&text); messages.push_str(text);
messages.push_str("\n\n"); messages.push_str("\n\n");
} }
MessageSegment::Thinking { text, signature } => { MessageSegment::Thinking { text, signature } => {
@ -846,7 +846,7 @@ fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>)
if let Some(sig) = signature { if let Some(sig) = signature {
messages.push_str(&format!("Signature: {}\n\n", sig)); messages.push_str(&format!("Signature: {}\n\n", sig));
} }
messages.push_str(&text); messages.push_str(text);
messages.push_str("\n"); messages.push_str("\n");
} }
MessageSegment::RedactedThinking(items) => { MessageSegment::RedactedThinking(items) => {
@ -878,7 +878,7 @@ pub async fn send_language_model_request(
request: LanguageModelRequest, request: LanguageModelRequest,
cx: &AsyncApp, cx: &AsyncApp,
) -> anyhow::Result<String> { ) -> anyhow::Result<String> {
match model.stream_completion_text(request, &cx).await { match model.stream_completion_text(request, cx).await {
Ok(mut stream) => { Ok(mut stream) => {
let mut full_response = String::new(); let mut full_response = String::new();
while let Some(chunk_result) = stream.stream.next().await { while let Some(chunk_result) = stream.stream.next().await {

View file

@ -452,7 +452,7 @@ impl ExtensionBuilder {
let mut output = Vec::new(); let mut output = Vec::new();
let mut stack = Vec::new(); let mut stack = Vec::new();
for payload in Parser::new(0).parse_all(&input) { for payload in Parser::new(0).parse_all(input) {
let payload = payload?; let payload = payload?;
// Track nesting depth, so that we don't mess with inner producer sections: // Track nesting depth, so that we don't mess with inner producer sections:

View file

@ -1341,7 +1341,7 @@ impl ExtensionStore {
&extension_path, &extension_path,
&extension.manifest, &extension.manifest,
wasm_host.clone(), wasm_host.clone(),
&cx, cx,
) )
.await .await
.with_context(|| format!("Loading extension from {extension_path:?}")); .with_context(|| format!("Loading extension from {extension_path:?}"));
@ -1776,7 +1776,7 @@ impl ExtensionStore {
})?; })?;
for client in clients { for client in clients {
Self::sync_extensions_over_ssh(&this, client, cx) Self::sync_extensions_over_ssh(this, client, cx)
.await .await
.log_err(); .log_err();
} }

View file

@ -175,7 +175,7 @@ impl HeadlessExtensionStore {
} }
let wasm_extension: Arc<dyn Extension> = let wasm_extension: Arc<dyn Extension> =
Arc::new(WasmExtension::load(&extension_dir, &manifest, wasm_host.clone(), &cx).await?); Arc::new(WasmExtension::load(&extension_dir, &manifest, wasm_host.clone(), cx).await?);
for (language_server_id, language_server_config) in &manifest.language_servers { for (language_server_id, language_server_config) in &manifest.language_servers {
for language in language_server_config.languages() { for language in language_server_config.languages() {

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