Detailed changes
@@ -821,6 +821,7 @@ single_range_in_vec_init = "allow"
style = { level = "allow", priority = -1 }
# Temporary list of style lints that we've fixed so far.
+comparison_to_empty = "warn"
iter_cloned_collect = "warn"
iter_next_slice = "warn"
iter_nth = "warn"
@@ -831,8 +832,13 @@ question_mark = { level = "deny" }
redundant_closure = { level = "deny" }
declare_interior_mutable_const = { level = "deny" }
collapsible_if = { level = "warn"}
+collapsible_else_if = { level = "warn" }
needless_borrow = { level = "warn"}
+needless_return = { level = "warn" }
unnecessary_mut_passed = {level = "warn"}
+unnecessary_map_or = { level = "warn" }
+unused_unit = "warn"
+
# Individual rules that have violations in the codebase:
type_complexity = "allow"
# We often return trait objects from `new` functions.
@@ -49,7 +49,7 @@ impl UserMessage {
if self
.checkpoint
.as_ref()
- .map_or(false, |checkpoint| checkpoint.show)
+ .is_some_and(|checkpoint| checkpoint.show)
{
writeln!(markdown, "## User (checkpoint)").unwrap();
} else {
@@ -79,12 +79,10 @@ impl MentionUri {
} else {
Ok(Self::Selection { path, line_range })
}
+ } else if input.ends_with("/") {
+ Ok(Self::Directory { abs_path: path })
} else {
- if input.ends_with("/") {
- Ok(Self::Directory { abs_path: path })
- } else {
- Ok(Self::File { abs_path: path })
- }
+ Ok(Self::File { abs_path: path })
}
}
"zed" => {
@@ -116,7 +116,7 @@ impl ActionLog {
} else if buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state().exists())
+ .is_some_and(|file| file.disk_state().exists())
{
TrackedBufferStatus::Created {
existing_file_content: Some(buffer.read(cx).as_rope().clone()),
@@ -215,7 +215,7 @@ impl ActionLog {
if buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state() == DiskState::Deleted)
+ .is_some_and(|file| file.disk_state() == DiskState::Deleted)
{
// If the buffer had been edited by a tool, but it got
// deleted externally, we want to stop tracking it.
@@ -227,7 +227,7 @@ impl ActionLog {
if buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state() != DiskState::Deleted)
+ .is_some_and(|file| file.disk_state() != DiskState::Deleted)
{
// If the buffer had been deleted by a tool, but it got
// resurrected externally, we want to clear the edits we
@@ -811,7 +811,7 @@ impl ActionLog {
tracked.version != buffer.version
&& buffer
.file()
- .map_or(false, |file| file.disk_state() != DiskState::Deleted)
+ .is_some_and(|file| file.disk_state() != DiskState::Deleted)
})
.map(|(buffer, _)| buffer)
}
@@ -847,7 +847,7 @@ fn apply_non_conflicting_edits(
conflict = true;
if new_edits
.peek()
- .map_or(false, |next_edit| next_edit.old.overlaps(&old_edit.new))
+ .is_some_and(|next_edit| next_edit.old.overlaps(&old_edit.new))
{
new_edit = new_edits.next().unwrap();
} else {
@@ -90,7 +90,7 @@ impl AgentProfile {
return false;
};
- return Self::is_enabled(settings, source, tool_name);
+ Self::is_enabled(settings, source, tool_name)
}
fn is_enabled(settings: &AgentProfileSettings, source: ToolSource, name: String) -> bool {
@@ -42,7 +42,7 @@ use std::{
use util::ResultExt as _;
pub static ZED_STATELESS: std::sync::LazyLock<bool> =
- std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").map_or(false, |v| !v.is_empty()));
+ std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataType {
@@ -275,7 +275,7 @@ impl ToolUseState {
pub fn message_has_tool_results(&self, assistant_message_id: MessageId) -> bool {
self.tool_uses_by_assistant_message
.get(&assistant_message_id)
- .map_or(false, |results| !results.is_empty())
+ .is_some_and(|results| !results.is_empty())
}
pub fn tool_result(
@@ -184,7 +184,7 @@ impl DbThread {
}
pub static ZED_STATELESS: std::sync::LazyLock<bool> =
- std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").map_or(false, |v| !v.is_empty()));
+ std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataType {
@@ -742,7 +742,7 @@ async fn expect_tool_call(events: &mut UnboundedReceiver<Result<ThreadEvent>>) -
.expect("no tool call authorization event received")
.unwrap();
match event {
- ThreadEvent::ToolCall(tool_call) => return tool_call,
+ ThreadEvent::ToolCall(tool_call) => tool_call,
event => {
panic!("Unexpected event {event:?}");
}
@@ -758,9 +758,7 @@ async fn expect_tool_call_update_fields(
.expect("no tool call authorization event received")
.unwrap();
match event {
- ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) => {
- return update;
- }
+ ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) => update,
event => {
panic!("Unexpected event {event:?}");
}
@@ -1356,7 +1356,7 @@ impl Thread {
// Ensure the last message ends in the current tool use
let last_message = self.pending_message();
- let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
+ let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
if let AgentMessageContent::ToolUse(last_tool_use) = content {
if last_tool_use.id == tool_use.id {
*last_tool_use = tool_use.clone();
@@ -1408,7 +1408,7 @@ impl Thread {
status: Some(acp::ToolCallStatus::InProgress),
..Default::default()
});
- let supports_images = self.model().map_or(false, |model| model.supports_images());
+ let supports_images = self.model().is_some_and(|model| model.supports_images());
let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
log::info!("Running tool {}", tool_use.name);
Some(cx.foreground_executor().spawn(async move {
@@ -175,7 +175,7 @@ impl AgentTool for ReadFileTool {
buffer
.file()
.as_ref()
- .map_or(true, |file| !file.disk_state().exists())
+ .is_none_or(|file| !file.disk_state().exists())
})? {
anyhow::bail!("{file_path} not found");
}
@@ -271,7 +271,7 @@ fn working_dir(
let project = project.read(cx);
let cd = &input.cd;
- if cd == "." || cd == "" {
+ if cd == "." || cd.is_empty() {
// Accept "." or "" as meaning "the one worktree" if we only have one worktree.
let mut worktrees = project.worktrees(cx);
@@ -296,10 +296,8 @@ fn working_dir(
{
return Ok(Some(input_path.into()));
}
- } else {
- if let Some(worktree) = project.worktree_for_root_name(cd, cx) {
- return Ok(Some(worktree.read(cx).abs_path().to_path_buf()));
- }
+ } else if let Some(worktree) = project.worktree_for_root_name(cd, cx) {
+ return Ok(Some(worktree.read(cx).abs_path().to_path_buf()));
}
anyhow::bail!("`cd` directory {cd:?} was not in any of the project's worktrees.");
@@ -104,7 +104,7 @@ impl AgentServerCommand {
cx: &mut AsyncApp,
) -> Option<Self> {
if let Some(agent_settings) = settings {
- return Some(Self {
+ Some(Self {
path: agent_settings.command.path,
args: agent_settings
.command
@@ -113,7 +113,7 @@ impl AgentServerCommand {
.chain(extra_args.iter().map(|arg| arg.to_string()))
.collect(),
env: agent_settings.command.env,
- });
+ })
} else {
match find_bin_in_path(path_bin_name, project, cx).await {
Some(path) => Some(Self {
@@ -471,7 +471,7 @@ pub fn get_zed_path() -> PathBuf {
while zed_path
.file_name()
- .map_or(true, |name| name.to_string_lossy() != "debug")
+ .is_none_or(|name| name.to_string_lossy() != "debug")
{
if !zed_path.pop() {
panic!("Could not find target directory");
@@ -58,7 +58,7 @@ impl AgentProfileSettings {
|| self
.context_servers
.get(server_id)
- .map_or(false, |preset| preset.tools.get(tool_name) == Some(&true))
+ .is_some_and(|preset| preset.tools.get(tool_name) == Some(&true))
}
}
@@ -797,7 +797,7 @@ impl MentionCompletion {
&& line
.chars()
.nth(last_mention_start - 1)
- .map_or(false, |c| !c.is_whitespace())
+ .is_some_and(|c| !c.is_whitespace())
{
return None;
}
@@ -1552,14 +1552,14 @@ impl SemanticsProvider for SlashCommandSemanticsProvider {
return None;
}
let range = snapshot.anchor_after(start)..snapshot.anchor_after(end);
- return Some(Task::ready(vec![project::Hover {
+ Some(Task::ready(vec![project::Hover {
contents: vec![project::HoverBlock {
text: "Slash commands are not supported".into(),
kind: project::HoverBlockKind::PlainText,
}],
range: Some(range),
language: None,
- }]));
+ }]))
}
fn inline_values(
@@ -102,7 +102,7 @@ impl ProfileProvider for Entity<agent2::Thread> {
fn profiles_supported(&self, cx: &App) -> bool {
self.read(cx)
.model()
- .map_or(false, |model| model.supports_tools())
+ .is_some_and(|model| model.supports_tools())
}
}
@@ -2843,7 +2843,7 @@ impl AcpThreadView {
if thread
.model()
- .map_or(true, |model| !model.supports_burn_mode())
+ .is_none_or(|model| !model.supports_burn_mode())
{
return None;
}
@@ -2875,9 +2875,9 @@ impl AcpThreadView {
fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
- let is_generating = self.thread().map_or(false, |thread| {
- thread.read(cx).status() != ThreadStatus::Idle
- });
+ let is_generating = self
+ .thread()
+ .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
if is_generating && is_editor_empty {
IconButton::new("stop-generation", IconName::Stop)
@@ -3455,18 +3455,16 @@ impl AcpThreadView {
} else {
format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
}
+ } else if next_attempt_in_secs == 1 {
+ format!(
+ "Retrying. Next attempt in 1 second (Attempt {} of {}).",
+ state.attempt, state.max_attempts,
+ )
} else {
- if next_attempt_in_secs == 1 {
- format!(
- "Retrying. Next attempt in 1 second (Attempt {} of {}).",
- state.attempt, state.max_attempts,
- )
- } else {
- format!(
- "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
- state.attempt, state.max_attempts,
- )
- }
+ format!(
+ "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
+ state.attempt, state.max_attempts,
+ )
};
Some(
@@ -3552,7 +3550,7 @@ impl AcpThreadView {
let supports_burn_mode = thread
.read(cx)
.model()
- .map_or(false, |model| model.supports_burn_mode());
+ .is_some_and(|model| model.supports_burn_mode());
let focus_handle = self.focus_handle(cx);
@@ -2246,9 +2246,7 @@ impl ActiveThread {
let after_editing_message = self
.editing_message
.as_ref()
- .map_or(false, |(editing_message_id, _)| {
- message_id > *editing_message_id
- });
+ .is_some_and(|(editing_message_id, _)| message_id > *editing_message_id);
let backdrop = div()
.id(("backdrop", ix))
@@ -96,7 +96,7 @@ impl AgentConfiguration {
let mut expanded_provider_configurations = HashMap::default();
if LanguageModelRegistry::read_global(cx)
.provider(&ZED_CLOUD_PROVIDER_ID)
- .map_or(false, |cloud_provider| cloud_provider.must_accept_terms(cx))
+ .is_some_and(|cloud_provider| cloud_provider.must_accept_terms(cx))
{
expanded_provider_configurations.insert(ZED_CLOUD_PROVIDER_ID, true);
}
@@ -285,7 +285,7 @@ impl AgentDiffPane {
&& buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state() == DiskState::Deleted)
+ .is_some_and(|file| file.disk_state() == DiskState::Deleted)
{
editor.fold_buffer(snapshot.text.remote_id(), cx)
}
@@ -1063,7 +1063,7 @@ impl ToolbarItemView for AgentDiffToolbar {
}
self.active_item = None;
- return self.location(cx);
+ self.location(cx)
}
fn pane_focus_update(
@@ -1509,7 +1509,7 @@ impl AgentDiff {
.read(cx)
.entries()
.last()
- .map_or(false, |entry| entry.diffs().next().is_some())
+ .is_some_and(|entry| entry.diffs().next().is_some())
{
self.update_reviewing_editors(workspace, window, cx);
}
@@ -1519,7 +1519,7 @@ impl AgentDiff {
.read(cx)
.entries()
.get(*ix)
- .map_or(false, |entry| entry.diffs().next().is_some())
+ .is_some_and(|entry| entry.diffs().next().is_some())
{
self.update_reviewing_editors(workspace, window, cx);
}
@@ -1709,7 +1709,7 @@ impl AgentDiff {
.read_with(cx, |editor, _cx| editor.workspace())
.ok()
.flatten()
- .map_or(false, |editor_workspace| {
+ .is_some_and(|editor_workspace| {
editor_workspace.entity_id() == workspace.entity_id()
});
@@ -1868,7 +1868,7 @@ impl AgentDiff {
}
}
- return Some(Task::ready(Ok(())));
+ Some(Task::ready(Ok(())))
}
}
@@ -1463,7 +1463,7 @@ impl AgentPanel {
AssistantConfigurationEvent::NewThread(provider) => {
if LanguageModelRegistry::read_global(cx)
.default_model()
- .map_or(true, |model| model.provider.id() != provider.id())
+ .is_none_or(|model| model.provider.id() != provider.id())
&& let Some(model) = provider.default_model(cx)
{
update_settings_file::<AgentSettings>(
@@ -2708,9 +2708,7 @@ impl AgentPanel {
}
ActiveView::ExternalAgentThread { .. }
| ActiveView::History
- | ActiveView::Configuration => {
- return None;
- }
+ | ActiveView::Configuration => None,
}
}
@@ -2726,7 +2724,7 @@ impl AgentPanel {
.thread()
.read(cx)
.configured_model()
- .map_or(false, |model| {
+ .is_some_and(|model| {
model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
})
{
@@ -2737,7 +2735,7 @@ impl AgentPanel {
if LanguageModelRegistry::global(cx)
.read(cx)
.default_model()
- .map_or(false, |model| {
+ .is_some_and(|model| {
model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
})
{
@@ -3051,9 +3049,7 @@ impl AgentPanel {
let zed_provider_configured = AgentSettings::get_global(cx)
.default_model
.as_ref()
- .map_or(false, |selection| {
- selection.provider.0.as_str() == "zed.dev"
- });
+ .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
let callout = if zed_provider_configured {
Callout::new()
@@ -610,9 +610,7 @@ pub(crate) fn available_context_picker_entries(
.read(cx)
.active_item(cx)
.and_then(|item| item.downcast::<Editor>())
- .map_or(false, |editor| {
- editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
- });
+ .is_some_and(|editor| editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx)));
if has_selection {
entries.push(ContextPickerEntry::Action(
ContextPickerAction::AddSelections,
@@ -680,7 +678,7 @@ pub(crate) fn recent_context_picker_entries(
.filter(|(_, abs_path)| {
abs_path
.as_ref()
- .map_or(true, |path| !exclude_paths.contains(path.as_path()))
+ .is_none_or(|path| !exclude_paths.contains(path.as_path()))
})
.take(4)
.filter_map(|(project_path, _)| {
@@ -1020,7 +1020,7 @@ impl MentionCompletion {
&& line
.chars()
.nth(last_mention_start - 1)
- .map_or(false, |c| !c.is_whitespace())
+ .is_some_and(|c| !c.is_whitespace())
{
return None;
}
@@ -226,9 +226,10 @@ impl PickerDelegate for FetchContextPickerDelegate {
_window: &mut Window,
cx: &mut Context<Picker<Self>>,
) -> Option<Self::ListItem> {
- let added = self.context_store.upgrade().map_or(false, |context_store| {
- context_store.read(cx).includes_url(&self.url)
- });
+ let added = self
+ .context_store
+ .upgrade()
+ .is_some_and(|context_store| context_store.read(cx).includes_url(&self.url));
Some(
ListItem::new(ix)
@@ -239,9 +239,7 @@ pub(crate) fn search_files(
PathMatchCandidateSet {
snapshot: worktree.snapshot(),
- include_ignored: worktree
- .root_entry()
- .map_or(false, |entry| entry.is_ignored),
+ include_ignored: worktree.root_entry().is_some_and(|entry| entry.is_ignored),
include_root_name: true,
candidates: project::Candidates::Entries,
}
@@ -159,7 +159,7 @@ pub fn render_thread_context_entry(
context_store: WeakEntity<ContextStore>,
cx: &mut App,
) -> Div {
- let added = context_store.upgrade().map_or(false, |context_store| {
+ let added = context_store.upgrade().is_some_and(|context_store| {
context_store
.read(cx)
.includes_user_rules(user_rules.prompt_id)
@@ -294,7 +294,7 @@ pub(crate) fn search_symbols(
.partition(|candidate| {
project
.entry_for_path(&symbols[candidate.id].path, cx)
- .map_or(false, |e| !e.is_ignored)
+ .is_some_and(|e| !e.is_ignored)
})
})
.log_err()
@@ -236,12 +236,10 @@ pub fn render_thread_context_entry(
let is_added = match entry {
ThreadContextEntry::Thread { id, .. } => context_store
.upgrade()
- .map_or(false, |ctx_store| ctx_store.read(cx).includes_thread(id)),
- ThreadContextEntry::Context { path, .. } => {
- context_store.upgrade().map_or(false, |ctx_store| {
- ctx_store.read(cx).includes_text_thread(path)
- })
- }
+ .is_some_and(|ctx_store| ctx_store.read(cx).includes_thread(id)),
+ ThreadContextEntry::Context { path, .. } => context_store
+ .upgrade()
+ .is_some_and(|ctx_store| ctx_store.read(cx).includes_text_thread(path)),
};
h_flex()
@@ -1120,7 +1120,7 @@ impl InlineAssistant {
if editor_assists
.scroll_lock
.as_ref()
- .map_or(false, |lock| lock.assist_id == assist_id)
+ .is_some_and(|lock| lock.assist_id == assist_id)
{
editor_assists.scroll_lock = None;
}
@@ -345,7 +345,7 @@ impl<T: 'static> PromptEditor<T> {
let prompt = self.editor.read(cx).text(cx);
if self
.prompt_history_ix
- .map_or(true, |ix| self.prompt_history[ix] != prompt)
+ .is_none_or(|ix| self.prompt_history[ix] != prompt)
{
self.prompt_history_ix.take();
self.pending_prompt = prompt;
@@ -156,7 +156,7 @@ impl ProfileProvider for Entity<Thread> {
fn profiles_supported(&self, cx: &App) -> bool {
self.read(cx)
.configured_model()
- .map_or(false, |model| model.model.supports_tools())
+ .is_some_and(|model| model.model.supports_tools())
}
fn profile_id(&self, cx: &App) -> AgentProfileId {
@@ -1289,7 +1289,7 @@ impl MessageEditor {
self.thread
.read(cx)
.configured_model()
- .map_or(false, |model| model.provider.id() == ZED_CLOUD_PROVIDER_ID)
+ .is_some_and(|model| model.provider.id() == ZED_CLOUD_PROVIDER_ID)
}
fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
@@ -1442,7 +1442,7 @@ impl MessageEditor {
let message_text = editor.read(cx).text(cx);
if message_text.is_empty()
- && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
+ && loaded_context.is_none_or(|loaded_context| loaded_context.is_empty())
{
return None;
}
@@ -140,12 +140,10 @@ impl PickerDelegate for SlashCommandDelegate {
);
ret.push(index - 1);
}
- } else {
- if let SlashCommandEntry::Advert { .. } = command {
- previous_is_advert = true;
- if index != 0 {
- ret.push(index - 1);
- }
+ } else if let SlashCommandEntry::Advert { .. } = command {
+ previous_is_advert = true;
+ if index != 0 {
+ ret.push(index - 1);
}
}
}
@@ -373,7 +373,7 @@ impl TextThreadEditor {
.map(|default| default.provider);
if provider
.as_ref()
- .map_or(false, |provider| provider.must_accept_terms(cx))
+ .is_some_and(|provider| provider.must_accept_terms(cx))
{
self.show_accept_terms = true;
cx.notify();
@@ -457,7 +457,7 @@ impl TextThreadEditor {
|| snapshot
.chars_at(newest_cursor)
.next()
- .map_or(false, |ch| ch != '\n')
+ .is_some_and(|ch| ch != '\n')
{
editor.move_to_end_of_line(
&MoveToEndOfLine {
@@ -177,11 +177,11 @@ impl AskPassSession {
_ = askpass_opened_rx.fuse() => {
// Note: this await can only resolve after we are dropped.
askpass_kill_master_rx.await.ok();
- return AskPassResult::CancelledByUser
+ AskPassResult::CancelledByUser
}
_ = futures::FutureExt::fuse(smol::Timer::after(connection_timeout)) => {
- return AskPassResult::Timedout
+ AskPassResult::Timedout
}
}
}
@@ -215,7 +215,7 @@ pub fn main(socket: &str) {
}
#[cfg(target_os = "windows")]
- while buffer.last().map_or(false, |&b| b == b'\n' || b == b'\r') {
+ while buffer.last().is_some_and(|&b| b == b'\n' || b == b'\r') {
buffer.pop();
}
if buffer.last() != Some(&b'\0') {
@@ -1023,9 +1023,11 @@ impl AssistantContext {
summary: new_summary,
..
} => {
- if self.summary.timestamp().map_or(true, |current_timestamp| {
- new_summary.timestamp > current_timestamp
- }) {
+ if self
+ .summary
+ .timestamp()
+ .is_none_or(|current_timestamp| new_summary.timestamp > current_timestamp)
+ {
self.summary = ContextSummary::Content(new_summary);
summary_generated = true;
}
@@ -1339,7 +1341,7 @@ impl AssistantContext {
let is_invalid = self
.messages_metadata
.get(&message_id)
- .map_or(true, |metadata| {
+ .is_none_or(|metadata| {
!metadata.is_cache_valid(&buffer, &message.offset_range)
|| *encountered_invalid
});
@@ -1860,7 +1862,7 @@ impl AssistantContext {
{
let newline_offset = insert_position.saturating_sub(1);
if buffer.contains_str_at(newline_offset, "\n")
- && last_section_range.map_or(true, |last_section_range| {
+ && last_section_range.is_none_or(|last_section_range| {
!last_section_range
.to_offset(buffer)
.contains(&newline_offset)
@@ -2313,10 +2315,7 @@ impl AssistantContext {
let mut request_message = LanguageModelRequestMessage {
role: message.role,
content: Vec::new(),
- cache: message
- .cache
- .as_ref()
- .map_or(false, |cache| cache.is_anchor),
+ cache: message.cache.as_ref().is_some_and(|cache| cache.is_anchor),
};
while let Some(content) = contents.peek() {
@@ -2797,7 +2796,7 @@ impl AssistantContext {
let mut current_message = messages.next();
while let Some(offset) = offsets.next() {
// Locate the message that contains the offset.
- while current_message.as_ref().map_or(false, |message| {
+ while current_message.as_ref().is_some_and(|message| {
!message.offset_range.contains(&offset) && messages.peek().is_some()
}) {
current_message = messages.next();
@@ -2807,7 +2806,7 @@ impl AssistantContext {
};
// Skip offsets that are in the same message.
- while offsets.peek().map_or(false, |offset| {
+ while offsets.peek().is_some_and(|offset| {
message.offset_range.contains(offset) || messages.peek().is_none()
}) {
offsets.next();
@@ -1055,7 +1055,7 @@ fn test_mark_cache_anchors(cx: &mut App) {
assert_eq!(
messages_cache(&context, cx)
.iter()
- .filter(|(_, cache)| cache.as_ref().map_or(false, |cache| cache.is_anchor))
+ .filter(|(_, cache)| cache.as_ref().is_some_and(|cache| cache.is_anchor))
.count(),
0,
"Empty messages should not have any cache anchors."
@@ -1083,7 +1083,7 @@ fn test_mark_cache_anchors(cx: &mut App) {
assert_eq!(
messages_cache(&context, cx)
.iter()
- .filter(|(_, cache)| cache.as_ref().map_or(false, |cache| cache.is_anchor))
+ .filter(|(_, cache)| cache.as_ref().is_some_and(|cache| cache.is_anchor))
.count(),
0,
"Messages should not be marked for cache before going over the token minimum."
@@ -1098,7 +1098,7 @@ fn test_mark_cache_anchors(cx: &mut App) {
assert_eq!(
messages_cache(&context, cx)
.iter()
- .map(|(_, cache)| cache.as_ref().map_or(false, |cache| cache.is_anchor))
+ .map(|(_, cache)| cache.as_ref().is_some_and(|cache| cache.is_anchor))
.collect::<Vec<bool>>(),
vec![true, true, false],
"Last message should not be an anchor on speculative request."
@@ -1116,7 +1116,7 @@ fn test_mark_cache_anchors(cx: &mut App) {
assert_eq!(
messages_cache(&context, cx)
.iter()
- .map(|(_, cache)| cache.as_ref().map_or(false, |cache| cache.is_anchor))
+ .map(|(_, cache)| cache.as_ref().is_some_and(|cache| cache.is_anchor))
.collect::<Vec<bool>>(),
vec![false, true, true, false],
"Most recent message should also be cached if not a speculative request."
@@ -789,7 +789,7 @@ impl ContextStore {
let fs = self.fs.clone();
cx.spawn(async move |this, cx| {
pub static ZED_STATELESS: LazyLock<bool> =
- LazyLock::new(|| std::env::var("ZED_STATELESS").map_or(false, |v| !v.is_empty()));
+ LazyLock::new(|| std::env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
if *ZED_STATELESS {
return Ok(());
}
@@ -62,9 +62,10 @@ impl SlashCommand for ContextServerSlashCommand {
}
fn requires_argument(&self) -> bool {
- self.prompt.arguments.as_ref().map_or(false, |args| {
- args.iter().any(|arg| arg.required == Some(true))
- })
+ self.prompt
+ .arguments
+ .as_ref()
+ .is_some_and(|args| args.iter().any(|arg| arg.required == Some(true)))
}
fn complete_argument(
@@ -61,7 +61,7 @@ impl DiagnosticsSlashCommand {
snapshot: worktree.snapshot(),
include_ignored: worktree
.root_entry()
- .map_or(false, |entry| entry.is_ignored),
+ .is_some_and(|entry| entry.is_ignored),
include_root_name: true,
candidates: project::Candidates::Entries,
}
@@ -92,7 +92,7 @@ impl FileSlashCommand {
snapshot: worktree.snapshot(),
include_ignored: worktree
.root_entry()
- .map_or(false, |entry| entry.is_ignored),
+ .is_some_and(|entry| entry.is_ignored),
include_root_name: true,
candidates: project::Candidates::Entries,
}
@@ -536,7 +536,7 @@ mod custom_path_matcher {
let path_str = path.to_string_lossy();
let separator = std::path::MAIN_SEPARATOR_STR;
if path_str.ends_with(separator) {
- return false;
+ false
} else {
self.glob.is_match(path_str.to_string() + separator)
}
@@ -86,7 +86,7 @@ fn register_web_search_tool(registry: &Entity<LanguageModelRegistry>, cx: &mut A
let using_zed_provider = registry
.read(cx)
.default_model()
- .map_or(false, |default| default.is_provided_by_zed());
+ .is_some_and(|default| default.is_provided_by_zed());
if using_zed_provider {
ToolRegistry::global(cx).register_tool(WebSearchTool);
} else {
@@ -1586,7 +1586,7 @@ impl EditAgentTest {
let has_system_prompt = eval
.conversation
.first()
- .map_or(false, |msg| msg.role == Role::System);
+ .is_some_and(|msg| msg.role == Role::System);
let messages = if has_system_prompt {
eval.conversation
} else {
@@ -201,7 +201,7 @@ impl Tool for ReadFileTool {
buffer
.file()
.as_ref()
- .map_or(true, |file| !file.disk_state().exists())
+ .is_none_or(|file| !file.disk_state().exists())
})? {
anyhow::bail!("{file_path} not found");
}
@@ -387,7 +387,7 @@ fn working_dir(
let project = project.read(cx);
let cd = &input.cd;
- if cd == "." || cd == "" {
+ if cd == "." || cd.is_empty() {
// Accept "." or "" as meaning "the one worktree" if we only have one worktree.
let mut worktrees = project.worktrees(cx);
@@ -412,10 +412,8 @@ fn working_dir(
{
return Ok(Some(input_path.into()));
}
- } else {
- if let Some(worktree) = project.worktree_for_root_name(cd, cx) {
- return Ok(Some(worktree.read(cx).abs_path().to_path_buf()));
- }
+ } else if let Some(worktree) = project.worktree_for_root_name(cd, cx) {
+ return Ok(Some(worktree.read(cx).abs_path().to_path_buf()));
}
anyhow::bail!("`cd` directory {cd:?} was not in any of the project's worktrees.");
@@ -54,11 +54,7 @@ pub async fn stream_completion(
)])));
}
- if request
- .tools
- .as_ref()
- .map_or(false, |t| !t.tools.is_empty())
- {
+ if request.tools.as_ref().is_some_and(|t| !t.tools.is_empty()) {
response = response.set_tool_config(request.tools);
}
@@ -147,7 +147,7 @@ impl ActiveCall {
let mut incoming_call = this.incoming_call.0.borrow_mut();
if incoming_call
.as_ref()
- .map_or(false, |call| call.room_id == envelope.payload.room_id)
+ .is_some_and(|call| call.room_id == envelope.payload.room_id)
{
incoming_call.take();
}
@@ -64,7 +64,7 @@ pub struct RemoteParticipant {
impl RemoteParticipant {
pub fn has_video_tracks(&self) -> bool {
- return !self.video_tracks.is_empty();
+ !self.video_tracks.is_empty()
}
pub fn can_write(&self) -> bool {
@@ -939,8 +939,7 @@ impl Room {
self.client.user_id()
)
})?;
- if self.live_kit.as_ref().map_or(true, |kit| kit.deafened) && publication.is_audio()
- {
+ if self.live_kit.as_ref().is_none_or(|kit| kit.deafened) && publication.is_audio() {
publication.set_enabled(false, cx);
}
match track {
@@ -1174,7 +1173,7 @@ impl Room {
this.update(cx, |this, cx| {
this.shared_projects.insert(project.downgrade());
let active_project = this.local_participant.active_project.as_ref();
- if active_project.map_or(false, |location| *location == project) {
+ if active_project.is_some_and(|location| *location == project) {
this.set_location(Some(&project), cx)
} else {
Task::ready(Ok(()))
@@ -1247,9 +1246,9 @@ impl Room {
}
pub fn is_sharing_screen(&self) -> bool {
- self.live_kit.as_ref().map_or(false, |live_kit| {
- !matches!(live_kit.screen_track, LocalTrack::None)
- })
+ self.live_kit
+ .as_ref()
+ .is_some_and(|live_kit| !matches!(live_kit.screen_track, LocalTrack::None))
}
pub fn shared_screen_id(&self) -> Option<u64> {
@@ -1262,13 +1261,13 @@ impl Room {
}
pub fn is_sharing_mic(&self) -> bool {
- self.live_kit.as_ref().map_or(false, |live_kit| {
- !matches!(live_kit.microphone_track, LocalTrack::None)
- })
+ self.live_kit
+ .as_ref()
+ .is_some_and(|live_kit| !matches!(live_kit.microphone_track, LocalTrack::None))
}
pub fn is_muted(&self) -> bool {
- self.live_kit.as_ref().map_or(false, |live_kit| {
+ self.live_kit.as_ref().is_some_and(|live_kit| {
matches!(live_kit.microphone_track, LocalTrack::None)
|| live_kit.muted_by_user
|| live_kit.deafened
@@ -1278,13 +1277,13 @@ impl Room {
pub fn muted_by_user(&self) -> bool {
self.live_kit
.as_ref()
- .map_or(false, |live_kit| live_kit.muted_by_user)
+ .is_some_and(|live_kit| live_kit.muted_by_user)
}
pub fn is_speaking(&self) -> bool {
self.live_kit
.as_ref()
- .map_or(false, |live_kit| live_kit.speaking)
+ .is_some_and(|live_kit| live_kit.speaking)
}
pub fn is_deafened(&self) -> Option<bool> {
@@ -340,7 +340,7 @@ impl ChannelChat {
return ControlFlow::Break(
if cursor
.item()
- .map_or(false, |message| message.id == message_id)
+ .is_some_and(|message| message.id == message_id)
{
Some(cursor.start().1.0)
} else {
@@ -362,7 +362,7 @@ impl ChannelChat {
if let ChannelMessageId::Saved(latest_message_id) = self.messages.summary().max_id
&& self
.last_acknowledged_id
- .map_or(true, |acknowledged_id| acknowledged_id < latest_message_id)
+ .is_none_or(|acknowledged_id| acknowledged_id < latest_message_id)
{
self.rpc
.send(proto::AckChannelMessage {
@@ -612,7 +612,7 @@ impl ChannelChat {
while let Some(message) = old_cursor.item() {
let message_ix = old_cursor.start().1.0;
if nonces.contains(&message.nonce) {
- if ranges.last().map_or(false, |r| r.end == message_ix) {
+ if ranges.last().is_some_and(|r| r.end == message_ix) {
ranges.last_mut().unwrap().end += 1;
} else {
ranges.push(message_ix..message_ix + 1);
@@ -568,16 +568,14 @@ impl ChannelStore {
self.channel_index
.by_id()
.get(&channel_id)
- .map_or(false, |channel| channel.is_root_channel())
+ .is_some_and(|channel| channel.is_root_channel())
}
pub fn is_public_channel(&self, channel_id: ChannelId) -> bool {
self.channel_index
.by_id()
.get(&channel_id)
- .map_or(false, |channel| {
- channel.visibility == ChannelVisibility::Public
- })
+ .is_some_and(|channel| channel.visibility == ChannelVisibility::Public)
}
pub fn channel_capability(&self, channel_id: ChannelId) -> Capability {
@@ -363,7 +363,7 @@ fn anonymous_fd(path: &str) -> Option<fs::File> {
let fd: fd::RawFd = fd_str.parse().ok()?;
let file = unsafe { fs::File::from_raw_fd(fd) };
- return Some(file);
+ Some(file)
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
{
@@ -381,13 +381,13 @@ fn anonymous_fd(path: &str) -> Option<fs::File> {
}
let fd: fd::RawFd = fd_str.parse().ok()?;
let file = unsafe { fs::File::from_raw_fd(fd) };
- return Some(file);
+ Some(file)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
{
_ = path;
// not implemented for bsd, windows. Could be, but isn't yet
- return None;
+ None
}
}
@@ -586,7 +586,7 @@ mod flatpak {
pub fn set_bin_if_no_escape(mut args: super::Args) -> super::Args {
if env::var(NO_ESCAPE_ENV_NAME).is_ok()
- && env::var("FLATPAK_ID").map_or(false, |id| id.starts_with("dev.zed.Zed"))
+ && env::var("FLATPAK_ID").is_ok_and(|id| id.starts_with("dev.zed.Zed"))
&& args.zed.is_none()
{
args.zed = Some("/app/libexec/zed-editor".into());
@@ -76,7 +76,7 @@ pub static ZED_APP_PATH: LazyLock<Option<PathBuf>> =
LazyLock::new(|| std::env::var("ZED_APP_PATH").ok().map(PathBuf::from));
pub static ZED_ALWAYS_ACTIVE: LazyLock<bool> =
- LazyLock::new(|| std::env::var("ZED_ALWAYS_ACTIVE").map_or(false, |e| !e.is_empty()));
+ LazyLock::new(|| std::env::var("ZED_ALWAYS_ACTIVE").is_ok_and(|e| !e.is_empty()));
pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(500);
pub const MAX_RECONNECTION_DELAY: Duration = Duration::from_secs(30);
@@ -848,7 +848,7 @@ impl UserStore {
pub fn has_accepted_terms_of_service(&self) -> bool {
self.accepted_tos_at
- .map_or(false, |accepted_tos_at| accepted_tos_at.is_some())
+ .is_some_and(|accepted_tos_at| accepted_tos_at.is_some())
}
pub fn accept_terms_of_service(&self, cx: &Context<Self>) -> Task<Result<()>> {
@@ -205,12 +205,12 @@ impl CloudApiClient {
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
if response.status() == StatusCode::UNAUTHORIZED {
- return Ok(false);
+ Ok(false)
} else {
- return Err(anyhow!(
+ Err(anyhow!(
"Failed to get authenticated user.\nStatus: {:?}\nBody: {body}",
response.status()
- ));
+ ))
}
}
}
@@ -304,7 +304,7 @@ impl RandomizedTest for ProjectCollaborationTest {
let worktree = worktree.read(cx);
worktree.is_visible()
&& worktree.entries(false, 0).any(|e| e.is_file())
- && worktree.root_entry().map_or(false, |e| e.is_dir())
+ && worktree.root_entry().is_some_and(|e| e.is_dir())
})
.choose(rng)
});
@@ -890,7 +890,7 @@ impl ChatPanel {
this.highlighted_message = Some((highlight_message_id, task));
}
- if this.active_chat.as_ref().map_or(false, |(c, _)| *c == chat) {
+ if this.active_chat.as_ref().is_some_and(|(c, _)| *c == chat) {
this.message_list.scroll_to(ListOffset {
item_ix,
offset_in_item: px(0.0),
@@ -1186,7 +1186,7 @@ impl Panel for ChatPanel {
let is_in_call = ActiveCall::global(cx)
.read(cx)
.room()
- .map_or(false, |room| room.read(cx).contains_guests());
+ .is_some_and(|room| room.read(cx).contains_guests());
self.active || is_in_call
}
@@ -664,9 +664,7 @@ impl CollabPanel {
let has_children = channel_store
.channel_at_index(mat.candidate_id + 1)
- .map_or(false, |next_channel| {
- next_channel.parent_path.ends_with(&[channel.id])
- });
+ .is_some_and(|next_channel| next_channel.parent_path.ends_with(&[channel.id]));
match &self.channel_editing_state {
Some(ChannelEditingState::Create {
@@ -1125,7 +1123,7 @@ impl CollabPanel {
}
fn has_subchannels(&self, ix: usize) -> bool {
- self.entries.get(ix).map_or(false, |entry| {
+ self.entries.get(ix).is_some_and(|entry| {
if let ListEntry::Channel { has_children, .. } = entry {
*has_children
} else {
@@ -497,7 +497,7 @@ impl NotificationPanel {
panel.is_scrolled_to_bottom()
&& panel
.active_chat()
- .map_or(false, |chat| chat.read(cx).channel_id.0 == *channel_id)
+ .is_some_and(|chat| chat.read(cx).channel_id.0 == *channel_id)
} else {
false
};
@@ -19,7 +19,7 @@ use release_channel::ReleaseChannel;
/// Only works in development. Setting this environment variable in other
/// release channels is a no-op.
static ZED_DEVELOPMENT_USE_KEYCHAIN: LazyLock<bool> = LazyLock::new(|| {
- std::env::var("ZED_DEVELOPMENT_USE_KEYCHAIN").map_or(false, |value| !value.is_empty())
+ std::env::var("ZED_DEVELOPMENT_USE_KEYCHAIN").is_ok_and(|value| !value.is_empty())
});
/// A provider for credentials.
@@ -385,7 +385,7 @@ impl DebugAdapter for CodeLldbDebugAdapter {
&& let Some(source_languages) = config.get("sourceLanguages").filter(|value| {
value
.as_array()
- .map_or(false, |array| array.iter().all(Value::is_string))
+ .is_some_and(|array| array.iter().all(Value::is_string))
})
{
let ret = vec![
@@ -37,7 +37,7 @@ const FALLBACK_DB_NAME: &str = "FALLBACK_MEMORY_DB";
const DB_FILE_NAME: &str = "db.sqlite";
pub static ZED_STATELESS: LazyLock<bool> =
- LazyLock::new(|| env::var("ZED_STATELESS").map_or(false, |v| !v.is_empty()));
+ LazyLock::new(|| env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
pub static ALL_FILE_DB_FAILED: LazyLock<AtomicBool> = LazyLock::new(|| AtomicBool::new(false));
@@ -20,7 +20,7 @@ pub trait Dismissable {
KEY_VALUE_STORE
.read_kvp(Self::KEY)
.log_err()
- .map_or(false, |s| s.is_some())
+ .is_some_and(|s| s.is_some())
}
fn set_dismissed(is_dismissed: bool, cx: &mut App) {
@@ -392,7 +392,7 @@ impl LogStore {
session.label(),
session
.adapter_client()
- .map_or(false, |client| client.has_adapter_logs()),
+ .is_some_and(|client| client.has_adapter_logs()),
)
});
@@ -414,7 +414,7 @@ pub(crate) fn new_debugger_pane(
.and_then(|item| item.downcast::<SubView>());
let is_hovered = as_subview
.as_ref()
- .map_or(false, |item| item.read(cx).hovered);
+ .is_some_and(|item| item.read(cx).hovered);
h_flex()
.track_focus(&focus_handle)
@@ -427,7 +427,6 @@ pub(crate) fn new_debugger_pane(
.bg(cx.theme().colors().tab_bar_background)
.on_action(|_: &menu::Cancel, window, cx| {
if cx.stop_active_drag(window) {
- return;
} else {
cx.propagate();
}
@@ -449,7 +448,7 @@ pub(crate) fn new_debugger_pane(
.children(pane.items().enumerate().map(|(ix, item)| {
let selected = active_pane_item
.as_ref()
- .map_or(false, |active| active.item_id() == item.item_id());
+ .is_some_and(|active| active.item_id() == item.item_id());
let deemphasized = !pane.has_focus(window, cx);
let item_ = item.boxed_clone();
div()
@@ -528,7 +528,7 @@ impl BreakpointList {
cx.background_executor()
.spawn(async move { KEY_VALUE_STORE.write_kvp(key, value?).await })
} else {
- return Task::ready(Result::Ok(()));
+ Task::ready(Result::Ok(()))
}
}
@@ -287,15 +287,13 @@ impl DiagnosticBlock {
}
}
}
- } else {
- if let Some(diagnostic) = editor
- .snapshot(window, cx)
- .buffer_snapshot
- .diagnostic_group(buffer_id, group_id)
- .nth(ix)
- {
- Self::jump_to(editor, diagnostic.range, window, cx)
- }
+ } else if let Some(diagnostic) = editor
+ .snapshot(window, cx)
+ .buffer_snapshot
+ .diagnostic_group(buffer_id, group_id)
+ .nth(ix)
+ {
+ Self::jump_to(editor, diagnostic.range, window, cx)
};
}
@@ -383,12 +383,10 @@ impl ProjectDiagnosticsEditor {
} else {
self.update_all_diagnostics(false, window, cx);
}
+ } else if self.update_excerpts_task.is_some() {
+ self.update_excerpts_task = None;
} else {
- if self.update_excerpts_task.is_some() {
- self.update_excerpts_task = None;
- } else {
- self.update_all_diagnostics(false, window, cx);
- }
+ self.update_all_diagnostics(false, window, cx);
}
cx.notify();
}
@@ -542,7 +540,7 @@ impl ProjectDiagnosticsEditor {
return true;
}
this.diagnostics.insert(buffer_id, diagnostics.clone());
- return false;
+ false
})?;
if unchanged {
return Ok(());
@@ -295,7 +295,7 @@ fn dump_all_gpui_actions() -> Vec<ActionDef> {
actions.sort_by_key(|a| a.name);
- return actions;
+ actions
}
fn handle_postprocessing() -> Result<()> {
@@ -185,7 +185,7 @@ impl Render for EditPredictionButton {
let this = cx.entity();
let fs = self.fs.clone();
- return div().child(
+ div().child(
PopoverMenu::new("supermaven")
.menu(move |window, cx| match &status {
SupermavenButtonStatus::NeedsActivation(activate_url) => {
@@ -230,7 +230,7 @@ impl Render for EditPredictionButton {
},
)
.with_handle(self.popover_menu_handle.clone()),
- );
+ )
}
EditPredictionProvider::Zed => {
@@ -343,7 +343,7 @@ impl Render for EditPredictionButton {
let is_refreshing = self
.edit_prediction_provider
.as_ref()
- .map_or(false, |provider| provider.is_refreshing(cx));
+ .is_some_and(|provider| provider.is_refreshing(cx));
if is_refreshing {
popover_menu = popover_menu.trigger(
@@ -13,7 +13,7 @@ use crate::{Editor, SwitchSourceHeader, element::register_action};
use project::lsp_store::clangd_ext::CLANGD_SERVER_NAME;
fn is_c_language(language: &Language) -> bool {
- return language.name() == "C++".into() || language.name() == "C".into();
+ language.name() == "C++".into() || language.name() == "C".into()
}
pub fn switch_source_header(
@@ -1111,10 +1111,8 @@ impl CompletionsMenu {
let query_start_doesnt_match_split_words = query_start_lower
.map(|query_char| {
!split_words(&string_match.string).any(|word| {
- word.chars()
- .next()
- .and_then(|c| c.to_lowercase().next())
- .map_or(false, |word_char| word_char == query_char)
+ word.chars().next().and_then(|c| c.to_lowercase().next())
+ == Some(query_char)
})
})
.unwrap_or(false);
@@ -991,7 +991,7 @@ impl DisplaySnapshot {
if let Some(severity) = chunk.diagnostic_severity.filter(|severity| {
self.diagnostics_max_severity
.into_lsp()
- .map_or(false, |max_severity| severity <= &max_severity)
+ .is_some_and(|max_severity| severity <= &max_severity)
}) {
if chunk.is_unnecessary {
diagnostic_highlight.fade_out = Some(editor_style.unnecessary_code_fade);
@@ -528,10 +528,7 @@ impl BlockMap {
if let Some(transform) = cursor.item()
&& transform.summary.input_rows > 0
&& cursor.end() == old_start
- && transform
- .block
- .as_ref()
- .map_or(true, |b| !b.is_replacement())
+ && transform.block.as_ref().is_none_or(|b| !b.is_replacement())
{
// Preserve the transform (push and next)
new_transforms.push(transform.clone(), &());
@@ -539,7 +536,7 @@ impl BlockMap {
// Preserve below blocks at end of edit
while let Some(transform) = cursor.item() {
- if transform.block.as_ref().map_or(false, |b| b.place_below()) {
+ if transform.block.as_ref().is_some_and(|b| b.place_below()) {
new_transforms.push(transform.clone(), &());
cursor.next();
} else {
@@ -606,7 +603,7 @@ impl BlockMap {
// Discard below blocks at the end of the edit. They'll be reconstructed.
while let Some(transform) = cursor.item() {
- if transform.block.as_ref().map_or(false, |b| b.place_below()) {
+ if transform.block.as_ref().is_some_and(|b| b.place_below()) {
cursor.next();
} else {
break;
@@ -1328,7 +1325,7 @@ impl BlockSnapshot {
let Dimensions(output_start, input_start, _) = cursor.start();
let overshoot = if cursor
.item()
- .map_or(false, |transform| transform.block.is_none())
+ .is_some_and(|transform| transform.block.is_none())
{
start_row.0 - output_start.0
} else {
@@ -1358,7 +1355,7 @@ impl BlockSnapshot {
&& transform
.block
.as_ref()
- .map_or(false, |block| block.height() > 0))
+ .is_some_and(|block| block.height() > 0))
{
break;
}
@@ -1511,7 +1508,7 @@ impl BlockSnapshot {
pub(super) fn is_block_line(&self, row: BlockRow) -> bool {
let mut cursor = self.transforms.cursor::<Dimensions<BlockRow, WrapRow>>(&());
cursor.seek(&row, Bias::Right);
- cursor.item().map_or(false, |t| t.block.is_some())
+ cursor.item().is_some_and(|t| t.block.is_some())
}
pub(super) fn is_folded_buffer_header(&self, row: BlockRow) -> bool {
@@ -1529,11 +1526,11 @@ impl BlockSnapshot {
.make_wrap_point(Point::new(row.0, 0), Bias::Left);
let mut cursor = self.transforms.cursor::<Dimensions<WrapRow, BlockRow>>(&());
cursor.seek(&WrapRow(wrap_point.row()), Bias::Right);
- cursor.item().map_or(false, |transform| {
+ cursor.item().is_some_and(|transform| {
transform
.block
.as_ref()
- .map_or(false, |block| block.is_replacement())
+ .is_some_and(|block| block.is_replacement())
})
}
@@ -1653,7 +1650,7 @@ impl BlockChunks<'_> {
if transform
.block
.as_ref()
- .map_or(false, |block| block.height() == 0)
+ .is_some_and(|block| block.height() == 0)
{
self.transforms.next();
} else {
@@ -1664,7 +1661,7 @@ impl BlockChunks<'_> {
if self
.transforms
.item()
- .map_or(false, |transform| transform.block.is_none())
+ .is_some_and(|transform| transform.block.is_none())
{
let start_input_row = self.transforms.start().1.0;
let start_output_row = self.transforms.start().0.0;
@@ -1774,7 +1771,7 @@ impl Iterator for BlockRows<'_> {
if transform
.block
.as_ref()
- .map_or(false, |block| block.height() == 0)
+ .is_some_and(|block| block.height() == 0)
{
self.transforms.next();
} else {
@@ -1786,7 +1783,7 @@ impl Iterator for BlockRows<'_> {
if transform
.block
.as_ref()
- .map_or(true, |block| block.is_replacement())
+ .is_none_or(|block| block.is_replacement())
{
self.input_rows.seek(self.transforms.start().1.0);
}
@@ -491,14 +491,14 @@ impl FoldMap {
while folds
.peek()
- .map_or(false, |(_, fold_range)| fold_range.start < edit.new.end)
+ .is_some_and(|(_, fold_range)| fold_range.start < edit.new.end)
{
let (fold, mut fold_range) = folds.next().unwrap();
let sum = new_transforms.summary();
assert!(fold_range.start.0 >= sum.input.len);
- while folds.peek().map_or(false, |(next_fold, next_fold_range)| {
+ while folds.peek().is_some_and(|(next_fold, next_fold_range)| {
next_fold_range.start < fold_range.end
|| (next_fold_range.start == fold_range.end
&& fold.placeholder.merge_adjacent
@@ -575,14 +575,14 @@ impl FoldMap {
for mut edit in inlay_edits {
old_transforms.seek(&edit.old.start, Bias::Left);
- if old_transforms.item().map_or(false, |t| t.is_fold()) {
+ if old_transforms.item().is_some_and(|t| t.is_fold()) {
edit.old.start = old_transforms.start().0;
}
let old_start =
old_transforms.start().1.0 + (edit.old.start - old_transforms.start().0).0;
old_transforms.seek_forward(&edit.old.end, Bias::Right);
- if old_transforms.item().map_or(false, |t| t.is_fold()) {
+ if old_transforms.item().is_some_and(|t| t.is_fold()) {
old_transforms.next();
edit.old.end = old_transforms.start().0;
}
@@ -590,14 +590,14 @@ impl FoldMap {
old_transforms.start().1.0 + (edit.old.end - old_transforms.start().0).0;
new_transforms.seek(&edit.new.start, Bias::Left);
- if new_transforms.item().map_or(false, |t| t.is_fold()) {
+ if new_transforms.item().is_some_and(|t| t.is_fold()) {
edit.new.start = new_transforms.start().0;
}
let new_start =
new_transforms.start().1.0 + (edit.new.start - new_transforms.start().0).0;
new_transforms.seek_forward(&edit.new.end, Bias::Right);
- if new_transforms.item().map_or(false, |t| t.is_fold()) {
+ if new_transforms.item().is_some_and(|t| t.is_fold()) {
new_transforms.next();
edit.new.end = new_transforms.start().0;
}
@@ -709,7 +709,7 @@ impl FoldSnapshot {
.transforms
.cursor::<Dimensions<InlayPoint, FoldPoint>>(&());
cursor.seek(&point, Bias::Right);
- if cursor.item().map_or(false, |t| t.is_fold()) {
+ if cursor.item().is_some_and(|t| t.is_fold()) {
if bias == Bias::Left || point == cursor.start().0 {
cursor.start().1
} else {
@@ -788,7 +788,7 @@ impl FoldSnapshot {
let inlay_offset = self.inlay_snapshot.to_inlay_offset(buffer_offset);
let mut cursor = self.transforms.cursor::<InlayOffset>(&());
cursor.seek(&inlay_offset, Bias::Right);
- cursor.item().map_or(false, |t| t.placeholder.is_some())
+ cursor.item().is_some_and(|t| t.placeholder.is_some())
}
pub fn is_line_folded(&self, buffer_row: MultiBufferRow) -> bool {
@@ -839,7 +839,7 @@ impl FoldSnapshot {
let inlay_end = if transform_cursor
.item()
- .map_or(true, |transform| transform.is_fold())
+ .is_none_or(|transform| transform.is_fold())
{
inlay_start
} else if range.end < transform_end.0 {
@@ -1348,7 +1348,7 @@ impl FoldChunks<'_> {
let inlay_end = if self
.transform_cursor
.item()
- .map_or(true, |transform| transform.is_fold())
+ .is_none_or(|transform| transform.is_fold())
{
inlay_start
} else if range.end < transform_end.0 {
@@ -1463,7 +1463,7 @@ impl FoldOffset {
.transforms
.cursor::<Dimensions<FoldOffset, TransformSummary>>(&());
cursor.seek(&self, Bias::Right);
- let overshoot = if cursor.item().map_or(true, |t| t.is_fold()) {
+ let overshoot = if cursor.item().is_none_or(|t| t.is_fold()) {
Point::new(0, (self.0 - cursor.start().0.0) as u32)
} else {
let inlay_offset = cursor.start().1.input.len + self.0 - cursor.start().0.0;
@@ -625,7 +625,7 @@ impl InlayMap {
// we can push its remainder.
if buffer_edits_iter
.peek()
- .map_or(true, |edit| edit.old.start >= cursor.end().0)
+ .is_none_or(|edit| edit.old.start >= cursor.end().0)
{
let transform_start = new_transforms.summary().input.len;
let transform_end =
@@ -74,10 +74,10 @@ impl WrapRows<'_> {
self.transforms
.seek(&WrapPoint::new(start_row, 0), Bias::Left);
let mut input_row = self.transforms.start().1.row();
- if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
+ if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
input_row += start_row - self.transforms.start().0.row();
}
- self.soft_wrapped = self.transforms.item().map_or(false, |t| !t.is_isomorphic());
+ self.soft_wrapped = self.transforms.item().is_some_and(|t| !t.is_isomorphic());
self.input_buffer_rows.seek(input_row);
self.input_buffer_row = self.input_buffer_rows.next().unwrap();
self.output_row = start_row;
@@ -603,7 +603,7 @@ impl WrapSnapshot {
.cursor::<Dimensions<WrapPoint, TabPoint>>(&());
transforms.seek(&output_start, Bias::Right);
let mut input_start = TabPoint(transforms.start().1.0);
- if transforms.item().map_or(false, |t| t.is_isomorphic()) {
+ if transforms.item().is_some_and(|t| t.is_isomorphic()) {
input_start.0 += output_start.0 - transforms.start().0.0;
}
let input_end = self
@@ -634,7 +634,7 @@ impl WrapSnapshot {
cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Left);
if cursor
.item()
- .map_or(false, |transform| transform.is_isomorphic())
+ .is_some_and(|transform| transform.is_isomorphic())
{
let overshoot = row - cursor.start().0.row();
let tab_row = cursor.start().1.row() + overshoot;
@@ -732,10 +732,10 @@ impl WrapSnapshot {
.cursor::<Dimensions<WrapPoint, TabPoint>>(&());
transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left);
let mut input_row = transforms.start().1.row();
- if transforms.item().map_or(false, |t| t.is_isomorphic()) {
+ if transforms.item().is_some_and(|t| t.is_isomorphic()) {
input_row += start_row - transforms.start().0.row();
}
- let soft_wrapped = transforms.item().map_or(false, |t| !t.is_isomorphic());
+ let soft_wrapped = transforms.item().is_some_and(|t| !t.is_isomorphic());
let mut input_buffer_rows = self.tab_snapshot.rows(input_row);
let input_buffer_row = input_buffer_rows.next().unwrap();
WrapRows {
@@ -754,7 +754,7 @@ impl WrapSnapshot {
.cursor::<Dimensions<WrapPoint, TabPoint>>(&());
cursor.seek(&point, Bias::Right);
let mut tab_point = cursor.start().1.0;
- if cursor.item().map_or(false, |t| t.is_isomorphic()) {
+ if cursor.item().is_some_and(|t| t.is_isomorphic()) {
tab_point += point.0 - cursor.start().0.0;
}
TabPoint(tab_point)
@@ -780,7 +780,7 @@ impl WrapSnapshot {
if bias == Bias::Left {
let mut cursor = self.transforms.cursor::<WrapPoint>(&());
cursor.seek(&point, Bias::Right);
- if cursor.item().map_or(false, |t| !t.is_isomorphic()) {
+ if cursor.item().is_some_and(|t| !t.is_isomorphic()) {
point = *cursor.start();
*point.column_mut() -= 1;
}
@@ -901,7 +901,7 @@ impl WrapChunks<'_> {
let output_end = WrapPoint::new(rows.end, 0);
self.transforms.seek(&output_start, Bias::Right);
let mut input_start = TabPoint(self.transforms.start().1.0);
- if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
+ if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
input_start.0 += output_start.0 - self.transforms.start().0.0;
}
let input_end = self
@@ -993,7 +993,7 @@ impl Iterator for WrapRows<'_> {
self.output_row += 1;
self.transforms
.seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left);
- if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
+ if self.transforms.item().is_some_and(|t| t.is_isomorphic()) {
self.input_buffer_row = self.input_buffer_rows.next().unwrap();
self.soft_wrapped = false;
} else {
@@ -1429,7 +1429,7 @@ impl SelectionHistory {
if self
.undo_stack
.back()
- .map_or(true, |e| e.selections != entry.selections)
+ .is_none_or(|e| e.selections != entry.selections)
{
self.undo_stack.push_back(entry);
if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
@@ -1442,7 +1442,7 @@ impl SelectionHistory {
if self
.redo_stack
.back()
- .map_or(true, |e| e.selections != entry.selections)
+ .is_none_or(|e| e.selections != entry.selections)
{
self.redo_stack.push_back(entry);
if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
@@ -2512,9 +2512,7 @@ impl Editor {
.context_menu
.borrow()
.as_ref()
- .map_or(false, |context| {
- matches!(context, CodeContextMenu::Completions(_))
- });
+ .is_some_and(|context| matches!(context, CodeContextMenu::Completions(_)));
showing_completions
|| self.edit_prediction_requires_modifier()
@@ -2545,7 +2543,7 @@ impl Editor {
|| binding
.keystrokes()
.first()
- .map_or(false, |keystroke| keystroke.modifiers.modified())
+ .is_some_and(|keystroke| keystroke.modifiers.modified())
}))
}
@@ -2941,7 +2939,7 @@ impl Editor {
return false;
};
- scope.override_name().map_or(false, |scope_name| {
+ scope.override_name().is_some_and(|scope_name| {
settings
.edit_predictions_disabled_in
.iter()
@@ -4033,18 +4031,18 @@ impl Editor {
let following_text_allows_autoclose = snapshot
.chars_at(selection.start)
.next()
- .map_or(true, |c| scope.should_autoclose_before(c));
+ .is_none_or(|c| scope.should_autoclose_before(c));
let preceding_text_allows_autoclose = selection.start.column == 0
- || snapshot.reversed_chars_at(selection.start).next().map_or(
- true,
- |c| {
+ || snapshot
+ .reversed_chars_at(selection.start)
+ .next()
+ .is_none_or(|c| {
bracket_pair.start != bracket_pair.end
|| !snapshot
.char_classifier_at(selection.start)
.is_word(c)
- },
- );
+ });
let is_closing_quote = if bracket_pair.end == bracket_pair.start
&& bracket_pair.start.len() == 1
@@ -4185,7 +4183,7 @@ impl Editor {
if !self.linked_edit_ranges.is_empty() {
let start_anchor = snapshot.anchor_before(selection.start);
- let is_word_char = text.chars().next().map_or(true, |char| {
+ let is_word_char = text.chars().next().is_none_or(|char| {
let classifier = snapshot
.char_classifier_at(start_anchor.to_offset(&snapshot))
.ignore_punctuation(true);
@@ -5427,11 +5425,11 @@ impl Editor {
let sort_completions = provider
.as_ref()
- .map_or(false, |provider| provider.sort_completions());
+ .is_some_and(|provider| provider.sort_completions());
let filter_completions = provider
.as_ref()
- .map_or(true, |provider| provider.filter_completions());
+ .is_none_or(|provider| provider.filter_completions());
let trigger_kind = match trigger {
Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
@@ -5537,7 +5535,7 @@ impl Editor {
let skip_digits = query
.as_ref()
- .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
+ .is_none_or(|query| !query.chars().any(|c| c.is_digit(10)));
let (mut words, provider_responses) = match &provider {
Some(provider) => {
@@ -5971,7 +5969,7 @@ impl Editor {
let show_new_completions_on_confirm = completion
.confirm
.as_ref()
- .map_or(false, |confirm| confirm(intent, window, cx));
+ .is_some_and(|confirm| confirm(intent, window, cx));
if show_new_completions_on_confirm {
self.show_completions(&ShowCompletions { trigger: None }, window, cx);
}
@@ -6103,10 +6101,10 @@ impl Editor {
let spawn_straight_away = quick_launch
&& resolved_tasks
.as_ref()
- .map_or(false, |tasks| tasks.templates.len() == 1)
+ .is_some_and(|tasks| tasks.templates.len() == 1)
&& code_actions
.as_ref()
- .map_or(true, |actions| actions.is_empty())
+ .is_none_or(|actions| actions.is_empty())
&& debug_scenarios.is_empty();
editor.update_in(cx, |editor, window, cx| {
@@ -6720,9 +6718,9 @@ impl Editor {
let buffer_id = cursor_position.buffer_id;
let buffer = this.buffer.read(cx);
- if !buffer
+ if buffer
.text_anchor_for_position(cursor_position, cx)
- .map_or(false, |(buffer, _)| buffer == cursor_buffer)
+ .is_none_or(|(buffer, _)| buffer != cursor_buffer)
{
return;
}
@@ -6972,9 +6970,7 @@ impl Editor {
|| self
.quick_selection_highlight_task
.as_ref()
- .map_or(true, |(prev_anchor_range, _)| {
- prev_anchor_range != &query_range
- })
+ .is_none_or(|(prev_anchor_range, _)| prev_anchor_range != &query_range)
{
let multi_buffer_visible_start = self
.scroll_manager
@@ -7003,9 +6999,7 @@ impl Editor {
|| self
.debounced_selection_highlight_task
.as_ref()
- .map_or(true, |(prev_anchor_range, _)| {
- prev_anchor_range != &query_range
- })
+ .is_none_or(|(prev_anchor_range, _)| prev_anchor_range != &query_range)
{
let multi_buffer_start = multi_buffer_snapshot
.anchor_before(0)
@@ -7140,9 +7134,7 @@ impl Editor {
&& self
.edit_prediction_provider
.as_ref()
- .map_or(false, |provider| {
- provider.provider.show_completions_in_menu()
- });
+ .is_some_and(|provider| provider.provider.show_completions_in_menu());
let preview_requires_modifier =
all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
@@ -7726,7 +7718,7 @@ impl Editor {
|| self
.active_edit_prediction
.as_ref()
- .map_or(false, |completion| {
+ .is_some_and(|completion| {
let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
let invalidation_range = invalidation_range.start..=invalidation_range.end;
!invalidation_range.contains(&offset_selection.head())
@@ -8427,7 +8419,7 @@ impl Editor {
.context_menu
.borrow()
.as_ref()
- .map_or(false, |menu| menu.visible())
+ .is_some_and(|menu| menu.visible())
}
pub fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
@@ -8973,9 +8965,8 @@ impl Editor {
let end_row = start_row + line_count as u32;
visible_row_range.contains(&start_row)
&& visible_row_range.contains(&end_row)
- && cursor_row.map_or(true, |cursor_row| {
- !((start_row..end_row).contains(&cursor_row))
- })
+ && cursor_row
+ .is_none_or(|cursor_row| !((start_row..end_row).contains(&cursor_row)))
})?;
content_origin
@@ -9585,7 +9576,7 @@ impl Editor {
.tabstops
.iter()
.map(|tabstop| {
- let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
+ let is_end_tabstop = tabstop.ranges.first().is_some_and(|tabstop| {
tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
});
let mut tabstop_ranges = tabstop
@@ -11716,7 +11707,7 @@ impl Editor {
let transpose_start = display_map
.buffer_snapshot
.clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
- if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
+ if edits.last().is_none_or(|e| e.0.end <= transpose_start) {
let transpose_end = display_map
.buffer_snapshot
.clip_offset(transpose_offset + 1, Bias::Right);
@@ -16229,23 +16220,21 @@ impl Editor {
if split {
workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
- } else {
- if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
- let (preview_item_id, preview_item_idx) =
- workspace.active_pane().read_with(cx, |pane, _| {
- (pane.preview_item_id(), pane.preview_item_idx())
- });
+ } else if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
+ let (preview_item_id, preview_item_idx) =
+ workspace.active_pane().read_with(cx, |pane, _| {
+ (pane.preview_item_id(), pane.preview_item_idx())
+ });
- workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
+ workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
- if let Some(preview_item_id) = preview_item_id {
- workspace.active_pane().update(cx, |pane, cx| {
- pane.remove_item(preview_item_id, false, false, window, cx);
- });
- }
- } else {
- workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
+ if let Some(preview_item_id) = preview_item_id {
+ workspace.active_pane().update(cx, |pane, cx| {
+ pane.remove_item(preview_item_id, false, false, window, cx);
+ });
}
+ } else {
+ workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
}
workspace.active_pane().update(cx, |pane, cx| {
pane.set_preview_item_id(Some(item_id), cx);
@@ -19010,7 +18999,7 @@ impl Editor {
fn has_blame_entries(&self, cx: &App) -> bool {
self.blame()
- .map_or(false, |blame| blame.read(cx).has_generated_entries())
+ .is_some_and(|blame| blame.read(cx).has_generated_entries())
}
fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
@@ -19660,7 +19649,7 @@ impl Editor {
pub fn has_background_highlights<T: 'static>(&self) -> bool {
self.background_highlights
.get(&HighlightKey::Type(TypeId::of::<T>()))
- .map_or(false, |(_, highlights)| !highlights.is_empty())
+ .is_some_and(|(_, highlights)| !highlights.is_empty())
}
pub fn background_highlights_in_range(
@@ -20582,7 +20571,7 @@ impl Editor {
// For now, don't allow opening excerpts in buffers that aren't backed by
// regular project files.
fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
- file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
+ file.is_none_or(|file| project::File::from_dyn(Some(file)).is_some())
}
fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
@@ -21125,7 +21114,7 @@ impl Editor {
pub fn has_visible_completions_menu(&self) -> bool {
!self.edit_prediction_preview_is_active()
- && self.context_menu.borrow().as_ref().map_or(false, |menu| {
+ && self.context_menu.borrow().as_ref().is_some_and(|menu| {
menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
})
}
@@ -21548,9 +21537,9 @@ fn is_grapheme_whitespace(text: &str) -> bool {
}
fn should_stay_with_preceding_ideograph(text: &str) -> bool {
- text.chars().next().map_or(false, |ch| {
- matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
- })
+ text.chars()
+ .next()
+ .is_some_and(|ch| matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…'))
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
@@ -21589,11 +21578,11 @@ impl<'a> Iterator for WordBreakingTokenizer<'a> {
} else {
let mut words = self.input[offset..].split_word_bound_indices().peekable();
let mut next_word_bound = words.peek().copied();
- if next_word_bound.map_or(false, |(i, _)| i == 0) {
+ if next_word_bound.is_some_and(|(i, _)| i == 0) {
next_word_bound = words.next();
}
while let Some(grapheme) = iter.peek().copied() {
- if next_word_bound.map_or(false, |(i, _)| i == offset) {
+ if next_word_bound.is_some_and(|(i, _)| i == offset) {
break;
};
if is_grapheme_whitespace(grapheme) != is_whitespace
@@ -810,10 +810,8 @@ impl Settings for EditorSettings {
if gutter.line_numbers.is_some() {
old_gutter.line_numbers = gutter.line_numbers
}
- } else {
- if gutter != GutterContent::default() {
- current.gutter = Some(gutter)
- }
+ } else if gutter != GutterContent::default() {
+ current.gutter = Some(gutter)
}
if let Some(b) = vscode.read_bool("editor.scrollBeyondLastLine") {
current.scroll_beyond_last_line = Some(if b {
@@ -919,6 +919,7 @@ impl EditorElement {
{
#[allow(
clippy::collapsible_if,
+ clippy::needless_return,
reason = "The cfg-block below makes this a false positive"
)]
if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
@@ -1126,26 +1127,24 @@ impl EditorElement {
let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
Some(control_row)
- } else {
- if text_hovered {
- let current_row = valid_point.row();
- position_map.display_hunks.iter().find_map(|(hunk, _)| {
- if let DisplayDiffHunk::Unfolded {
- display_row_range, ..
- } = hunk
- {
- if display_row_range.contains(¤t_row) {
- Some(display_row_range.start)
- } else {
- None
- }
+ } else if text_hovered {
+ let current_row = valid_point.row();
+ position_map.display_hunks.iter().find_map(|(hunk, _)| {
+ if let DisplayDiffHunk::Unfolded {
+ display_row_range, ..
+ } = hunk
+ {
+ if display_row_range.contains(¤t_row) {
+ Some(display_row_range.start)
} else {
None
}
- })
- } else {
- None
- }
+ } else {
+ None
+ }
+ })
+ } else {
+ None
};
if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
@@ -1159,11 +1158,11 @@ impl EditorElement {
.inline_blame_popover
.as_ref()
.and_then(|state| state.popover_bounds)
- .map_or(false, |bounds| bounds.contains(&event.position));
+ .is_some_and(|bounds| bounds.contains(&event.position));
let keyboard_grace = editor
.inline_blame_popover
.as_ref()
- .map_or(false, |state| state.keyboard_grace);
+ .is_some_and(|state| state.keyboard_grace);
if mouse_over_inline_blame || mouse_over_popover {
editor.show_blame_popover(blame_entry, event.position, false, cx);
@@ -1190,10 +1189,10 @@ impl EditorElement {
let is_visible = editor
.gutter_breakpoint_indicator
.0
- .map_or(false, |indicator| indicator.is_active);
+ .is_some_and(|indicator| indicator.is_active);
let has_existing_breakpoint =
- editor.breakpoint_store.as_ref().map_or(false, |store| {
+ editor.breakpoint_store.as_ref().is_some_and(|store| {
let Some(project) = &editor.project else {
return false;
};
@@ -2220,12 +2219,11 @@ impl EditorElement {
cmp::max(padded_line, min_start)
};
- let behind_edit_prediction_popover = edit_prediction_popover_origin.as_ref().map_or(
- false,
- |edit_prediction_popover_origin| {
+ let behind_edit_prediction_popover = edit_prediction_popover_origin
+ .as_ref()
+ .is_some_and(|edit_prediction_popover_origin| {
(pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
- },
- );
+ });
let opacity = if behind_edit_prediction_popover {
0.5
} else {
@@ -2291,9 +2289,7 @@ impl EditorElement {
None
}
})
- .map_or(false, |source| {
- matches!(source, CodeActionSource::Indicator(..))
- });
+ .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
})?;
@@ -2909,7 +2905,7 @@ impl EditorElement {
if multibuffer_row
.0
.checked_sub(1)
- .map_or(false, |previous_row| {
+ .is_some_and(|previous_row| {
snapshot.is_line_folded(MultiBufferRow(previous_row))
})
{
@@ -3900,7 +3896,7 @@ impl EditorElement {
for (row, block) in fixed_blocks {
let block_id = block.id();
- if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
+ if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
focused_block = None;
}
@@ -3957,7 +3953,7 @@ impl EditorElement {
};
let block_id = block.id();
- if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
+ if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
focused_block = None;
}
@@ -4736,7 +4732,7 @@ impl EditorElement {
}
};
- let source_included = source_display_point.map_or(true, |source_display_point| {
+ let source_included = source_display_point.is_none_or(|source_display_point| {
visible_range
.to_inclusive()
.contains(&source_display_point.row())
@@ -4916,7 +4912,7 @@ impl EditorElement {
let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
context_menu_layout
.as_ref()
- .map_or(false, |menu| bounds.intersects(&menu.bounds))
+ .is_some_and(|menu| bounds.intersects(&menu.bounds))
};
let can_place_above = {
@@ -5101,7 +5097,7 @@ impl EditorElement {
if active_positions
.iter()
- .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
+ .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
{
let y = display_row_range.start.as_f32() * line_height
+ text_hitbox.bounds.top()
@@ -5214,7 +5210,7 @@ impl EditorElement {
let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
context_menu_layout
.as_ref()
- .map_or(false, |menu| bounds.intersects(&menu.bounds))
+ .is_some_and(|menu| bounds.intersects(&menu.bounds))
};
let final_origin = if popover_bounds_above.is_contained_within(hitbox)
@@ -5299,7 +5295,7 @@ impl EditorElement {
let mut end_row = start_row.0;
while active_rows
.peek()
- .map_or(false, |(active_row, has_selection)| {
+ .is_some_and(|(active_row, has_selection)| {
active_row.0 == end_row + 1
&& has_selection.selection == contains_non_empty_selection.selection
})
@@ -6687,25 +6683,23 @@ impl EditorElement {
editor.set_scroll_position(position, window, cx);
}
cx.stop_propagation();
- } else {
- if minimap_hitbox.is_hovered(window) {
- editor.scroll_manager.set_is_hovering_minimap_thumb(
- !event.dragging()
- && layout
- .thumb_layout
- .thumb_bounds
- .is_some_and(|bounds| bounds.contains(&event.position)),
- cx,
- );
+ } else if minimap_hitbox.is_hovered(window) {
+ editor.scroll_manager.set_is_hovering_minimap_thumb(
+ !event.dragging()
+ && layout
+ .thumb_layout
+ .thumb_bounds
+ .is_some_and(|bounds| bounds.contains(&event.position)),
+ cx,
+ );
- // Stop hover events from propagating to the
- // underlying editor if the minimap hitbox is hovered
- if !event.dragging() {
- cx.stop_propagation();
- }
- } else {
- editor.scroll_manager.hide_minimap_thumb(cx);
+ // Stop hover events from propagating to the
+ // underlying editor if the minimap hitbox is hovered
+ if !event.dragging() {
+ cx.stop_propagation();
}
+ } else {
+ editor.scroll_manager.hide_minimap_thumb(cx);
}
mouse_position = event.position;
});
@@ -7084,9 +7078,7 @@ impl EditorElement {
let unstaged_hollow = ProjectSettings::get_global(cx)
.git
.hunk_style
- .map_or(false, |style| {
- matches!(style, GitHunkStyleSetting::UnstagedHollow)
- });
+ .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
unstaged == unstaged_hollow
}
@@ -8183,7 +8175,7 @@ impl Element for EditorElement {
let is_row_soft_wrapped = |row: usize| {
row_infos
.get(row)
- .map_or(true, |info| info.buffer_row.is_none())
+ .is_none_or(|info| info.buffer_row.is_none())
};
let start_anchor = if start_row == Default::default() {
@@ -9718,14 +9710,12 @@ impl PointForPosition {
false
} else if start_row == end_row {
candidate_col >= start_col && candidate_col < end_col
+ } else if candidate_row == start_row {
+ candidate_col >= start_col
+ } else if candidate_row == end_row {
+ candidate_col < end_col
} else {
- if candidate_row == start_row {
- candidate_col >= start_col
- } else if candidate_row == end_row {
- candidate_col < end_col
- } else {
- true
- }
+ true
}
}
}
@@ -415,7 +415,7 @@ impl GitBlame {
let old_end = cursor.end();
if row_edits
.peek()
- .map_or(true, |next_edit| next_edit.old.start >= old_end)
+ .is_none_or(|next_edit| next_edit.old.start >= old_end)
&& let Some(entry) = cursor.item()
{
if old_end > edit.old.end {
@@ -271,7 +271,7 @@ impl Editor {
Task::ready(Ok(Navigated::No))
};
self.select(SelectPhase::End, window, cx);
- return navigate_task;
+ navigate_task
}
}
@@ -871,7 +871,7 @@ fn surrounding_filename(
.peekable();
while let Some(ch) = forwards.next() {
// Skip escaped whitespace
- if ch == '\\' && forwards.peek().map_or(false, |ch| ch.is_whitespace()) {
+ if ch == '\\' && forwards.peek().is_some_and(|ch| ch.is_whitespace()) {
token_end += ch.len_utf8();
let whitespace = forwards.next().unwrap();
token_end += whitespace.len_utf8();
@@ -201,7 +201,7 @@ impl FollowableItem for Editor {
if buffer
.as_singleton()
.and_then(|buffer| buffer.read(cx).file())
- .map_or(false, |file| file.is_private())
+ .is_some_and(|file| file.is_private())
{
return None;
}
@@ -715,7 +715,7 @@ impl Item for Editor {
.read(cx)
.as_singleton()
.and_then(|buffer| buffer.read(cx).file())
- .map_or(false, |file| file.disk_state() == DiskState::Deleted);
+ .is_some_and(|file| file.disk_state() == DiskState::Deleted);
h_flex()
.gap_2()
@@ -86,9 +86,9 @@ pub(crate) fn should_auto_close(
});
}
if to_auto_edit.is_empty() {
- return None;
+ None
} else {
- return Some(to_auto_edit);
+ Some(to_auto_edit)
}
}
@@ -186,7 +186,7 @@ pub(crate) fn generate_auto_close_edits(
let range = node_name.byte_range();
return buffer.text_for_range(range).equals_str(name);
}
- return is_empty;
+ is_empty
};
let tree_root_node = {
@@ -227,7 +227,7 @@ pub(crate) fn generate_auto_close_edits(
let has_open_tag_with_same_tag_name = ancestor
.named_child(0)
.filter(|n| n.kind() == config.open_tag_node_name)
- .map_or(false, |element_open_tag_node| {
+ .is_some_and(|element_open_tag_node| {
tag_node_name_equals(&element_open_tag_node, &tag_name)
});
if has_open_tag_with_same_tag_name {
@@ -263,8 +263,7 @@ pub(crate) fn generate_auto_close_edits(
}
let is_after_open_tag = |node: &Node| {
- return node.start_byte() < open_tag.start_byte()
- && node.end_byte() < open_tag.start_byte();
+ node.start_byte() < open_tag.start_byte() && node.end_byte() < open_tag.start_byte()
};
// perf: use cursor for more efficient traversal
@@ -301,7 +300,7 @@ pub(crate) fn generate_auto_close_edits(
let edit_range = edit_anchor..edit_anchor;
edits.push((edit_range, format!("</{}>", tag_name)));
}
- return Ok(edits);
+ Ok(edits)
}
pub(crate) fn refresh_enabled_in_any_buffer(
@@ -367,7 +366,7 @@ pub(crate) fn construct_initial_buffer_versions_map<
initial_buffer_versions.insert(buffer_id, buffer_version);
}
}
- return initial_buffer_versions;
+ initial_buffer_versions
}
pub(crate) fn handle_from(
@@ -455,12 +454,9 @@ pub(crate) fn handle_from(
let ensure_no_edits_since_start = || -> Option<()> {
let has_edits_since_start = this
.read_with(cx, |this, cx| {
- this.buffer
- .read(cx)
- .buffer(buffer_id)
- .map_or(true, |buffer| {
- buffer.read(cx).has_edits_since(&buffer_version_initial)
- })
+ this.buffer.read(cx).buffer(buffer_id).is_none_or(|buffer| {
+ buffer.read(cx).has_edits_since(&buffer_version_initial)
+ })
})
.ok()?;
@@ -61,13 +61,13 @@ impl MouseContextMenu {
source,
offset: position - (source_position + content_origin),
};
- return Some(MouseContextMenu::new(
+ Some(MouseContextMenu::new(
editor,
menu_position,
context_menu,
window,
cx,
- ));
+ ))
}
pub(crate) fn new(
@@ -89,7 +89,7 @@ impl Editor {
.lsp_task_source()?;
if lsp_settings
.get(&lsp_tasks_source)
- .map_or(true, |s| s.enable_lsp_tasks)
+ .is_none_or(|s| s.enable_lsp_tasks)
{
let buffer_id = buffer.read(cx).remote_id();
Some((lsp_tasks_source, buffer_id))
@@ -54,7 +54,7 @@ impl AssertionsReport {
pub fn passed_count(&self) -> usize {
self.ran
.iter()
- .filter(|a| a.result.as_ref().map_or(false, |result| result.passed))
+ .filter(|a| a.result.as_ref().is_ok_and(|result| result.passed))
.count()
}
@@ -112,7 +112,7 @@ fn main() {
let telemetry = app_state.client.telemetry();
telemetry.start(system_id, installation_id, session_id, cx);
- let enable_telemetry = env::var("ZED_EVAL_TELEMETRY").map_or(false, |value| value == "1")
+ let enable_telemetry = env::var("ZED_EVAL_TELEMETRY").is_ok_and(|value| value == "1")
&& telemetry.has_checksum_seed();
if enable_telemetry {
println!("Telemetry enabled");
@@ -70,10 +70,10 @@ impl Example for AddArgToTraitMethod {
let path_str = format!("crates/assistant_tools/src/{}.rs", tool_name);
let edits = edits.get(Path::new(&path_str));
- let ignored = edits.map_or(false, |edits| {
+ let ignored = edits.is_some_and(|edits| {
edits.has_added_line(" _window: Option<gpui::AnyWindowHandle>,\n")
});
- let uningored = edits.map_or(false, |edits| {
+ let uningored = edits.is_some_and(|edits| {
edits.has_added_line(" window: Option<gpui::AnyWindowHandle>,\n")
});
@@ -89,7 +89,7 @@ impl Example for AddArgToTraitMethod {
let batch_tool_edits = edits.get(Path::new("crates/assistant_tools/src/batch_tool.rs"));
cx.assert(
- batch_tool_edits.map_or(false, |edits| {
+ batch_tool_edits.is_some_and(|edits| {
edits.has_added_line(" window: Option<gpui::AnyWindowHandle>,\n")
}),
"Argument: batch_tool",
@@ -401,7 +401,7 @@ impl ExtensionBuilder {
let mut clang_path = wasi_sdk_dir.clone();
clang_path.extend(["bin", &format!("clang{}", env::consts::EXE_SUFFIX)]);
- if fs::metadata(&clang_path).map_or(false, |metadata| metadata.is_file()) {
+ if fs::metadata(&clang_path).is_ok_and(|metadata| metadata.is_file()) {
return Ok(clang_path);
}
@@ -19,9 +19,8 @@ pub struct ExtensionEvents;
impl ExtensionEvents {
/// Returns the global [`ExtensionEvents`].
pub fn try_global(cx: &App) -> Option<Entity<Self>> {
- return cx
- .try_global::<GlobalExtensionEvents>()
- .map(|g| g.0.clone());
+ cx.try_global::<GlobalExtensionEvents>()
+ .map(|g| g.0.clone())
}
fn new(_cx: &mut Context<Self>) -> Self {
@@ -562,12 +562,12 @@ impl ExtensionStore {
extensions
.into_iter()
.filter(|extension| {
- this.extension_index.extensions.get(&extension.id).map_or(
- true,
- |installed_extension| {
+ this.extension_index
+ .extensions
+ .get(&extension.id)
+ .is_none_or(|installed_extension| {
installed_extension.manifest.version != extension.manifest.version
- },
- )
+ })
})
.collect()
})
@@ -1451,7 +1451,7 @@ impl ExtensionStore {
if extension_dir
.file_name()
- .map_or(false, |file_name| file_name == ".DS_Store")
+ .is_some_and(|file_name| file_name == ".DS_Store")
{
continue;
}
@@ -14,7 +14,7 @@ struct FeatureFlags {
}
pub static ZED_DISABLE_STAFF: LazyLock<bool> = LazyLock::new(|| {
- std::env::var("ZED_DISABLE_STAFF").map_or(false, |value| !value.is_empty() && value != "0")
+ std::env::var("ZED_DISABLE_STAFF").is_ok_and(|value| !value.is_empty() && value != "0")
});
impl FeatureFlags {
@@ -135,7 +135,7 @@ impl Display for SystemSpecs {
fn try_determine_available_gpus() -> Option<String> {
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
- return std::process::Command::new("vulkaninfo")
+ std::process::Command::new("vulkaninfo")
.args(&["--summary"])
.output()
.ok()
@@ -150,11 +150,11 @@ fn try_determine_available_gpus() -> Option<String> {
]
.join("\n")
})
- .or(Some("Failed to run `vulkaninfo --summary`".to_string()));
+ .or(Some("Failed to run `vulkaninfo --summary`".to_string()))
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
{
- return None;
+ None
}
}
@@ -878,9 +878,7 @@ impl FileFinderDelegate {
PathMatchCandidateSet {
snapshot: worktree.snapshot(),
include_ignored: self.include_ignored.unwrap_or_else(|| {
- worktree
- .root_entry()
- .map_or(false, |entry| entry.is_ignored)
+ worktree.root_entry().is_some_and(|entry| entry.is_ignored)
}),
include_root_name,
candidates: project::Candidates::Files,
@@ -728,7 +728,7 @@ impl PickerDelegate for OpenPathDelegate {
.child(LabelLike::new().child(label_with_highlights)),
)
}
- DirectoryState::None { .. } => return None,
+ DirectoryState::None { .. } => None,
}
}
@@ -72,7 +72,7 @@ impl FileIcons {
return maybe_path;
}
}
- return this.get_icon_for_type("default", cx);
+ this.get_icon_for_type("default", cx)
}
fn default_icon_theme(cx: &App) -> Option<Arc<IconTheme>> {
@@ -625,13 +625,13 @@ impl Fs for RealFs {
async fn is_file(&self, path: &Path) -> bool {
smol::fs::metadata(path)
.await
- .map_or(false, |metadata| metadata.is_file())
+ .is_ok_and(|metadata| metadata.is_file())
}
async fn is_dir(&self, path: &Path) -> bool {
smol::fs::metadata(path)
.await
- .map_or(false, |metadata| metadata.is_dir())
+ .is_ok_and(|metadata| metadata.is_dir())
}
async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
@@ -269,10 +269,8 @@ impl GitExcludeOverride {
pub async fn restore_original(&mut self) -> Result<()> {
if let Some(ref original) = self.original_excludes {
smol::fs::write(&self.git_exclude_path, original).await?;
- } else {
- if self.git_exclude_path.exists() {
- smol::fs::remove_file(&self.git_exclude_path).await?;
- }
+ } else if self.git_exclude_path.exists() {
+ smol::fs::remove_file(&self.git_exclude_path).await?;
}
self.added_excludes = None;
@@ -2052,7 +2050,7 @@ fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
}
fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
- if upstream_track == "" {
+ if upstream_track.is_empty() {
return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
ahead: 0,
behind: 0,
@@ -88,11 +88,10 @@ impl CommitView {
let ix = pane.items().position(|item| {
let commit_view = item.downcast::<CommitView>();
commit_view
- .map_or(false, |view| view.read(cx).commit.sha == commit.sha)
+ .is_some_and(|view| view.read(cx).commit.sha == commit.sha)
});
if let Some(ix) = ix {
pane.activate_item(ix, true, true, window, cx);
- return;
} else {
pane.add_item(Box::new(commit_view), true, true, None, window, cx);
}
@@ -775,7 +775,7 @@ impl GitPanel {
if window
.focused(cx)
- .map_or(false, |focused| self.focus_handle == focused)
+ .is_some_and(|focused| self.focus_handle == focused)
{
dispatch_context.add("menu");
dispatch_context.add("ChangesList");
@@ -894,9 +894,7 @@ impl GitPanel {
let have_entries = self
.active_repository
.as_ref()
- .map_or(false, |active_repository| {
- active_repository.read(cx).status_summary().count > 0
- });
+ .is_some_and(|active_repository| active_repository.read(cx).status_summary().count > 0);
if have_entries && self.selected_entry.is_none() {
self.selected_entry = Some(1);
self.scroll_to_selected_entry(cx);
@@ -1207,9 +1205,7 @@ impl GitPanel {
})
.ok();
}
- _ => {
- return;
- }
+ _ => {}
})
.detach();
}
@@ -1640,13 +1636,12 @@ impl GitPanel {
fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
let text = self.commit_editor.read(cx).text(cx);
if !text.trim().is_empty() {
- return true;
+ true
} else if text.is_empty() {
- return self
- .suggest_commit_message(cx)
- .is_some_and(|text| !text.trim().is_empty());
+ self.suggest_commit_message(cx)
+ .is_some_and(|text| !text.trim().is_empty())
} else {
- return false;
+ false
}
}
@@ -2938,8 +2933,7 @@ impl GitPanel {
.matches(git::repository::REMOTE_CANCELLED_BY_USER)
.next()
.is_some()
- {
- return; // Hide the cancelled by user message
+ { // Hide the cancelled by user message
} else {
workspace.update(cx, |workspace, cx| {
let workspace_weak = cx.weak_entity();
@@ -3272,12 +3266,10 @@ impl GitPanel {
} else {
"Amend Tracked"
}
+ } else if self.has_staged_changes() {
+ "Commit"
} else {
- if self.has_staged_changes() {
- "Commit"
- } else {
- "Commit Tracked"
- }
+ "Commit Tracked"
}
}
@@ -4498,7 +4490,7 @@ impl Render for GitPanel {
let has_write_access = self.has_write_access(cx);
- let has_co_authors = room.map_or(false, |room| {
+ let has_co_authors = room.is_some_and(|room| {
self.load_local_committer(cx);
let room = room.read(cx);
room.remote_participants()
@@ -4814,12 +4806,10 @@ impl RenderOnce for PanelRepoFooter {
// ideally, show the whole branch and repo names but
// when we can't, use a budget to allocate space between the two
- let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
- <= LABEL_CHARACTER_BUDGET
- {
- (repo_actual_len, branch_actual_len)
- } else {
- if branch_actual_len <= MAX_BRANCH_LEN {
+ let (repo_display_len, branch_display_len) =
+ if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
+ (repo_actual_len, branch_actual_len)
+ } else if branch_actual_len <= MAX_BRANCH_LEN {
let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
(repo_space, branch_actual_len)
} else if repo_actual_len <= MAX_REPO_LEN {
@@ -4827,8 +4817,7 @@ impl RenderOnce for PanelRepoFooter {
(repo_actual_len, branch_space)
} else {
(MAX_REPO_LEN, MAX_BRANCH_LEN)
- }
- };
+ };
let truncated_repo_name = if repo_actual_len <= repo_display_len {
active_repo_name.to_string()
@@ -329,14 +329,14 @@ impl ProjectDiff {
})
.ok();
- return ButtonStates {
+ ButtonStates {
stage: has_unstaged_hunks,
unstage: has_staged_hunks,
prev_next,
selection,
stage_all,
unstage_all,
- };
+ }
}
fn handle_editor_event(
@@ -129,7 +129,7 @@ impl CursorPosition {
cursor_position.selected_count.lines += 1;
}
}
- if last_selection.as_ref().map_or(true, |last_selection| {
+ if last_selection.as_ref().is_none_or(|last_selection| {
selection.id > last_selection.id
}) {
last_selection = Some(selection);
@@ -477,10 +477,10 @@ impl<'de> Deserialize<'de> for ModelName {
model_id: id.to_string(),
})
} else {
- return Err(serde::de::Error::custom(format!(
+ Err(serde::de::Error::custom(format!(
"Expected model name to begin with {}, got: {}",
MODEL_NAME_PREFIX, string
- )));
+ )))
}
}
}
@@ -786,7 +786,7 @@ impl<T: 'static> PartialOrd for WeakEntity<T> {
#[cfg(any(test, feature = "leak-detection"))]
static LEAK_BACKTRACE: std::sync::LazyLock<bool> =
- std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));
+ std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").is_ok_and(|b| !b.is_empty()));
#[cfg(any(test, feature = "leak-detection"))]
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
@@ -2274,7 +2274,7 @@ impl Interactivity {
window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
if phase == DispatchPhase::Bubble && !window.default_prevented() {
let group_hovered = active_group_hitbox
- .map_or(false, |group_hitbox_id| group_hitbox_id.is_hovered(window));
+ .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
let element_hovered = hitbox.is_hovered(window);
if group_hovered || element_hovered {
*active_state.borrow_mut() = ElementClickedState {
@@ -2614,7 +2614,7 @@ pub(crate) fn register_tooltip_mouse_handlers(
window.on_mouse_event({
let active_tooltip = active_tooltip.clone();
move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
- if !tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(window)) {
+ if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
}
}
@@ -2623,7 +2623,7 @@ pub(crate) fn register_tooltip_mouse_handlers(
window.on_mouse_event({
let active_tooltip = active_tooltip.clone();
move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
- if !tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(window)) {
+ if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
}
}
@@ -64,7 +64,7 @@ mod any_image_cache {
cx: &mut App,
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
let image_cache = image_cache.clone().downcast::<I>().unwrap();
- return image_cache.update(cx, |image_cache, cx| image_cache.load(resource, window, cx));
+ image_cache.update(cx, |image_cache, cx| image_cache.load(resource, window, cx))
}
}
@@ -938,9 +938,10 @@ impl Element for List {
let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
// If the width of the list has changed, invalidate all cached item heights
- if state.last_layout_bounds.map_or(true, |last_bounds| {
- last_bounds.size.width != bounds.size.width
- }) {
+ if state
+ .last_layout_bounds
+ .is_none_or(|last_bounds| last_bounds.size.width != bounds.size.width)
+ {
let new_items = SumTree::from_iter(
state.items.iter().map(|item| ListItem::Unmeasured {
focus_handle: item.focus_handle(),
@@ -458,7 +458,7 @@ impl DispatchTree {
.keymap
.borrow()
.bindings_for_input(input, &context_stack);
- return (bindings, partial, context_stack);
+ (bindings, partial, context_stack)
}
/// dispatch_key processes the keystroke
@@ -639,10 +639,7 @@ mod tests {
}
fn partial_eq(&self, action: &dyn Action) -> bool {
- action
- .as_any()
- .downcast_ref::<Self>()
- .map_or(false, |a| self == a)
+ action.as_any().downcast_ref::<Self>() == Some(self)
}
fn boxed_clone(&self) -> std::boxed::Box<dyn Action> {
@@ -287,7 +287,7 @@ impl KeyBindingContextPredicate {
return false;
}
}
- return true;
+ true
}
// Workspace > Pane > Editor
//
@@ -305,7 +305,7 @@ impl KeyBindingContextPredicate {
return true;
}
}
- return false;
+ false
}
Self::And(left, right) => {
left.eval_inner(contexts, all_contexts) && right.eval_inner(contexts, all_contexts)
@@ -592,7 +592,7 @@ impl PlatformTextSystem for NoopTextSystem {
}
fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
- return Ok(FontId(1));
+ Ok(FontId(1))
}
fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
@@ -49,7 +49,7 @@ fn parse_pci_id(id: &str) -> anyhow::Result<u32> {
"Expected a 4 digit PCI ID in hexadecimal format"
);
- return u32::from_str_radix(id, 16).context("parsing PCI ID as hex");
+ u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
}
#[cfg(test)]
@@ -441,7 +441,7 @@ impl<P: LinuxClient + 'static> Platform for P {
fn app_path(&self) -> Result<PathBuf> {
// get the path of the executable of the current process
let app_path = env::current_exe()?;
- return Ok(app_path);
+ Ok(app_path)
}
fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
@@ -710,9 +710,7 @@ impl LinuxClient for WaylandClient {
fn set_cursor_style(&self, style: CursorStyle) {
let mut state = self.0.borrow_mut();
- let need_update = state
- .cursor_style
- .map_or(true, |current_style| current_style != style);
+ let need_update = state.cursor_style != Some(style);
if need_update {
let serial = state.serial_tracker.get(SerialKind::MouseEnter);
@@ -1577,7 +1575,7 @@ impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
if state
.keyboard_focused_window
.as_ref()
- .map_or(false, |keyboard_window| window.ptr_eq(keyboard_window))
+ .is_some_and(|keyboard_window| window.ptr_eq(keyboard_window))
{
state.enter_token = None;
}
@@ -669,8 +669,8 @@ impl WaylandWindowStatePtr {
pub fn set_size_and_scale(&self, size: Option<Size<Pixels>>, scale: Option<f32>) {
let (size, scale) = {
let mut state = self.state.borrow_mut();
- if size.map_or(true, |size| size == state.bounds.size)
- && scale.map_or(true, |scale| scale == state.scale)
+ if size.is_none_or(|size| size == state.bounds.size)
+ && scale.is_none_or(|scale| scale == state.scale)
{
return;
}
@@ -1586,11 +1586,11 @@ impl LinuxClient for X11Client {
fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
let state = self.0.borrow_mut();
- return state
+ state
.clipboard
.get_any(clipboard::ClipboardKind::Primary)
.context("X11: Failed to read from clipboard (primary)")
- .log_with_level(log::Level::Debug);
+ .log_with_level(log::Level::Debug)
}
fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
@@ -1603,11 +1603,11 @@ impl LinuxClient for X11Client {
{
return state.clipboard_item.clone();
}
- return state
+ state
.clipboard
.get_any(clipboard::ClipboardKind::Clipboard)
.context("X11: Failed to read from clipboard (clipboard)")
- .log_with_level(log::Level::Debug);
+ .log_with_level(log::Level::Debug)
}
fn run(&self) {
@@ -2010,12 +2010,12 @@ fn check_gtk_frame_extents_supported(
}
fn xdnd_is_atom_supported(atom: u32, atoms: &XcbAtoms) -> bool {
- return atom == atoms.TEXT
+ atom == atoms.TEXT
|| atom == atoms.STRING
|| atom == atoms.UTF8_STRING
|| atom == atoms.TEXT_PLAIN
|| atom == atoms.TEXT_PLAIN_UTF8
- || atom == atoms.TextUriList;
+ || atom == atoms.TextUriList
}
fn xdnd_get_supported_atom(
@@ -2043,7 +2043,7 @@ fn xdnd_get_supported_atom(
}
}
}
- return 0;
+ 0
}
fn xdnd_send_finished(
@@ -2144,7 +2144,7 @@ fn current_pointer_device_states(
if pointer_device_states.is_empty() {
log::error!("Found no xinput mouse pointers.");
}
- return Some(pointer_device_states);
+ Some(pointer_device_states)
}
/// Returns true if the device is a pointer device. Does not include pointer device groups.
@@ -1078,11 +1078,11 @@ impl Clipboard {
} else {
String::from_utf8(result.bytes).map_err(|_| Error::ConversionFailure)?
};
- return Ok(ClipboardItem::new_string(text));
+ Ok(ClipboardItem::new_string(text))
}
pub fn is_owner(&self, selection: ClipboardKind) -> bool {
- return self.inner.is_owner(selection).unwrap_or(false);
+ self.inner.is_owner(selection).unwrap_or(false)
}
}
@@ -104,7 +104,7 @@ fn bit_is_set_in_vec(bit_vec: &Vec<u32>, bit_index: u16) -> bool {
let array_index = bit_index as usize / 32;
bit_vec
.get(array_index)
- .map_or(false, |bits| bit_is_set(*bits, bit_index % 32))
+ .is_some_and(|bits| bit_is_set(*bits, bit_index % 32))
}
fn bit_is_set(bits: u32, bit_index: u16) -> bool {
@@ -311,9 +311,8 @@ unsafe fn parse_keystroke(native_event: id) -> Keystroke {
let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
- && first_char.map_or(true, |ch| {
- !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
- });
+ && first_char
+ .is_none_or(|ch| !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch));
#[allow(non_upper_case_globals)]
let key = match first_char {
@@ -797,7 +797,7 @@ impl Platform for MacPlatform {
.to_owned();
result.set_file_name(&new_filename);
}
- return result;
+ result
})
}
}
@@ -319,7 +319,7 @@ impl MacTextSystemState {
fn is_emoji(&self, font_id: FontId) -> bool {
self.postscript_names_by_font_id
.get(&font_id)
- .map_or(false, |postscript_name| {
+ .is_some_and(|postscript_name| {
postscript_name == "AppleColorEmoji" || postscript_name == ".AppleColorEmojiUI"
})
}
@@ -653,7 +653,7 @@ impl MacWindow {
.and_then(|titlebar| titlebar.traffic_light_position),
transparent_titlebar: titlebar
.as_ref()
- .map_or(true, |titlebar| titlebar.appears_transparent),
+ .is_none_or(|titlebar| titlebar.appears_transparent),
previous_modifiers_changed_event: None,
keystroke_for_do_command: None,
do_command_handled: None,
@@ -688,7 +688,7 @@ impl MacWindow {
});
}
- if titlebar.map_or(true, |titlebar| titlebar.appears_transparent) {
+ if titlebar.is_none_or(|titlebar| titlebar.appears_transparent) {
native_window.setTitlebarAppearsTransparent_(YES);
native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
}
@@ -270,9 +270,7 @@ impl PlatformDispatcher for TestDispatcher {
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>) {
{
let mut state = self.state.lock();
- if label.map_or(false, |label| {
- state.deprioritized_task_labels.contains(&label)
- }) {
+ if label.is_some_and(|label| state.deprioritized_task_labels.contains(&label)) {
state.deprioritized_background.push(runnable);
} else {
state.background.push(runnable);
@@ -573,7 +573,7 @@ impl Style {
if self
.border_color
- .map_or(false, |color| !color.is_transparent())
+ .is_some_and(|color| !color.is_transparent())
{
min.x += self.border_widths.left.to_pixels(rem_size);
max.x -= self.border_widths.right.to_pixels(rem_size);
@@ -633,7 +633,7 @@ impl Style {
window.paint_shadows(bounds, corner_radii, &self.box_shadow);
let background_color = self.background.as_ref().and_then(Fill::color);
- if background_color.map_or(false, |color| !color.is_transparent()) {
+ if background_color.is_some_and(|color| !color.is_transparent()) {
let mut border_color = match background_color {
Some(color) => match color.tag {
BackgroundTag::Solid => color.solid,
@@ -729,7 +729,7 @@ impl Style {
fn is_border_visible(&self) -> bool {
self.border_color
- .map_or(false, |color| !color.is_transparent())
+ .is_some_and(|color| !color.is_transparent())
&& self.border_widths.any(|length| !length.is_zero())
}
}
@@ -435,7 +435,7 @@ impl WindowTextSystem {
});
}
- if decoration_runs.last().map_or(false, |last_run| {
+ if decoration_runs.last().is_some_and(|last_run| {
last_run.color == run.color
&& last_run.underline == run.underline
&& last_run.strikethrough == run.strikethrough
@@ -243,14 +243,14 @@ impl FocusId {
pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
window
.focused(cx)
- .map_or(false, |focused| self.contains(focused.id, window))
+ .is_some_and(|focused| self.contains(focused.id, window))
}
/// Obtains whether the element associated with this handle is contained within the
/// focused element or is itself focused.
pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
let focused = window.focused(cx);
- focused.map_or(false, |focused| focused.id.contains(*self, window))
+ focused.is_some_and(|focused| focused.id.contains(*self, window))
}
/// Obtains whether this handle contains the given handle in the most recently rendered frame.
@@ -504,7 +504,7 @@ impl HitboxId {
return true;
}
}
- return false;
+ false
}
/// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
@@ -634,7 +634,7 @@ impl TooltipId {
window
.tooltip_bounds
.as_ref()
- .map_or(false, |tooltip_bounds| {
+ .is_some_and(|tooltip_bounds| {
tooltip_bounds.id == *self
&& tooltip_bounds.bounds.contains(&window.mouse_position())
})
@@ -4466,7 +4466,7 @@ impl Window {
}
}
}
- return None;
+ None
}
}
@@ -189,7 +189,7 @@ fn extract_cfg_attributes(attrs: &[Attribute]) -> Vec<Attribute> {
fn is_called_from_gpui_crate(_span: Span) -> bool {
// Check if we're being called from within the gpui crate by examining the call site
// This is a heuristic approach - we check if the current crate name is "gpui"
- std::env::var("CARGO_PKG_NAME").map_or(false, |name| name == "gpui")
+ std::env::var("CARGO_PKG_NAME").is_ok_and(|name| name == "gpui")
}
struct MacroExpander;
@@ -1406,7 +1406,7 @@ impl Buffer {
})
.unwrap_or(true);
let result = any_sub_ranges_contain_range;
- return result;
+ result
})
.last()
.map(|info| info.language.clone())
@@ -1520,12 +1520,12 @@ impl Buffer {
let new_syntax_map = parse_task.await;
this.update(cx, move |this, cx| {
let grammar_changed =
- this.language.as_ref().map_or(true, |current_language| {
+ this.language.as_ref().is_none_or(|current_language| {
!Arc::ptr_eq(&language, current_language)
});
let language_registry_changed = new_syntax_map
.contains_unknown_injections()
- && language_registry.map_or(false, |registry| {
+ && language_registry.is_some_and(|registry| {
registry.version() != new_syntax_map.language_registry_version()
});
let parse_again = language_registry_changed
@@ -1719,8 +1719,7 @@ impl Buffer {
})
.with_delta(suggestion.delta, language_indent_size);
- if old_suggestions.get(&new_row).map_or(
- true,
+ if old_suggestions.get(&new_row).is_none_or(
|(old_indentation, was_within_error)| {
suggested_indent != *old_indentation
&& (!suggestion.within_error || *was_within_error)
@@ -2014,7 +2013,7 @@ impl Buffer {
fn was_changed(&mut self) {
self.change_bits.retain(|change_bit| {
- change_bit.upgrade().map_or(false, |bit| {
+ change_bit.upgrade().is_some_and(|bit| {
bit.replace(true);
true
})
@@ -2191,7 +2190,7 @@ impl Buffer {
if self
.remote_selections
.get(&self.text.replica_id())
- .map_or(true, |set| !set.selections.is_empty())
+ .is_none_or(|set| !set.selections.is_empty())
{
self.set_active_selections(Arc::default(), false, Default::default(), cx);
}
@@ -2839,7 +2838,7 @@ impl Buffer {
let mut edits: Vec<(Range<usize>, String)> = Vec::new();
let mut last_end = None;
for _ in 0..old_range_count {
- if last_end.map_or(false, |last_end| last_end >= self.len()) {
+ if last_end.is_some_and(|last_end| last_end >= self.len()) {
break;
}
@@ -3059,14 +3058,14 @@ impl BufferSnapshot {
if config
.decrease_indent_pattern
.as_ref()
- .map_or(false, |regex| regex.is_match(line))
+ .is_some_and(|regex| regex.is_match(line))
{
indent_change_rows.push((row, Ordering::Less));
}
if config
.increase_indent_pattern
.as_ref()
- .map_or(false, |regex| regex.is_match(line))
+ .is_some_and(|regex| regex.is_match(line))
{
indent_change_rows.push((row + 1, Ordering::Greater));
}
@@ -3082,7 +3081,7 @@ impl BufferSnapshot {
}
}
for rule in &config.decrease_indent_patterns {
- if rule.pattern.as_ref().map_or(false, |r| r.is_match(line)) {
+ if rule.pattern.as_ref().is_some_and(|r| r.is_match(line)) {
let row_start_column = self.indent_size_for_line(row).len;
let basis_row = rule
.valid_after
@@ -3295,8 +3294,7 @@ impl BufferSnapshot {
range: Range<D>,
) -> Option<SyntaxLayer<'_>> {
let range = range.to_offset(self);
- return self
- .syntax
+ self.syntax
.layers_for_range(range, &self.text, false)
.max_by(|a, b| {
if a.depth != b.depth {
@@ -3306,7 +3304,7 @@ impl BufferSnapshot {
} else {
a.node().end_byte().cmp(&b.node().end_byte()).reverse()
}
- });
+ })
}
/// Returns the main [`Language`].
@@ -3365,8 +3363,7 @@ impl BufferSnapshot {
}
if let Some(range) = range
- && smallest_range_and_depth.as_ref().map_or(
- true,
+ && smallest_range_and_depth.as_ref().is_none_or(
|(smallest_range, smallest_range_depth)| {
if layer.depth > *smallest_range_depth {
true
@@ -3543,7 +3540,7 @@ impl BufferSnapshot {
}
}
- return Some(cursor.node());
+ Some(cursor.node())
}
/// Returns the outline for the buffer.
@@ -3572,7 +3569,7 @@ impl BufferSnapshot {
)?;
let mut prev_depth = None;
items.retain(|item| {
- let result = prev_depth.map_or(true, |prev_depth| item.depth > prev_depth);
+ let result = prev_depth.is_none_or(|prev_depth| item.depth > prev_depth);
prev_depth = Some(item.depth);
result
});
@@ -4449,7 +4446,7 @@ impl BufferSnapshot {
pub fn words_in_range(&self, query: WordsQuery) -> BTreeMap<String, Range<Anchor>> {
let query_str = query.fuzzy_contents;
- if query_str.map_or(false, |query| query.is_empty()) {
+ if query_str.is_some_and(|query| query.is_empty()) {
return BTreeMap::default();
}
@@ -4490,7 +4487,7 @@ impl BufferSnapshot {
.and_then(|first_chunk| first_chunk.chars().next());
// Skip empty and "words" starting with digits as a heuristic to reduce useless completions
if !query.skip_digits
- || first_char.map_or(true, |first_char| !first_char.is_digit(10))
+ || first_char.is_none_or(|first_char| !first_char.is_digit(10))
{
words.insert(word_text.collect(), word_range);
}
@@ -773,7 +773,7 @@ impl LanguageRegistry {
};
let content_matches = || {
- config.first_line_pattern.as_ref().map_or(false, |pattern| {
+ config.first_line_pattern.as_ref().is_some_and(|pattern| {
content
.as_ref()
.is_some_and(|content| pattern.is_match(content))
@@ -253,7 +253,7 @@ impl EditPredictionSettings {
!self.disabled_globs.iter().any(|glob| {
if glob.is_absolute {
file.as_local()
- .map_or(false, |local| glob.matcher.is_match(local.abs_path(cx)))
+ .is_some_and(|local| glob.matcher.is_match(local.abs_path(cx)))
} else {
glob.matcher.is_match(file.path())
}
@@ -1630,10 +1630,8 @@ impl<'a> SyntaxLayer<'a> {
if offset < range.start || offset > range.end {
continue;
}
- } else {
- if offset <= range.start || offset >= range.end {
- continue;
- }
+ } else if offset <= range.start || offset >= range.end {
+ continue;
}
if let Some((_, smallest_range)) = &smallest_match {
@@ -554,7 +554,7 @@ pub fn into_anthropic(
.into_iter()
.filter_map(|content| match content {
MessageContent::Text(text) => {
- let text = if text.chars().last().map_or(false, |c| c.is_whitespace()) {
+ let text = if text.chars().last().is_some_and(|c| c.is_whitespace()) {
text.trim_end().to_string()
} else {
text
@@ -813,7 +813,7 @@ impl AnthropicEventMapper {
))];
}
}
- return vec![];
+ vec![]
}
},
Event::ContentBlockStop { index } => {
@@ -270,7 +270,7 @@ impl State {
if response.status().is_success() {
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
- return Ok(serde_json::from_str(&body)?);
+ Ok(serde_json::from_str(&body)?)
} else {
let mut body = String::new();
response.body_mut().read_to_string(&mut body).await?;
@@ -530,7 +530,7 @@ pub fn into_google(
let system_instructions = if request
.messages
.first()
- .map_or(false, |msg| matches!(msg.role, Role::System))
+ .is_some_and(|msg| matches!(msg.role, Role::System))
{
let message = request.messages.remove(0);
Some(SystemInstruction {
@@ -71,12 +71,10 @@ impl KeyContextView {
} else {
None
}
+ } else if this.action_matches(&e.action, binding.action()) {
+ Some(true)
} else {
- if this.action_matches(&e.action, binding.action()) {
- Some(true)
- } else {
- Some(false)
- }
+ Some(false)
};
let predicate = if let Some(predicate) = binding.predicate() {
format!("{}", predicate)
@@ -349,7 +349,6 @@ impl LanguageServerState {
.detach();
} else {
cx.propagate();
- return;
}
}
},
@@ -523,7 +522,6 @@ impl LspTool {
if ProjectSettings::get_global(cx).global_lsp_settings.button {
if lsp_tool.lsp_menu.is_none() {
lsp_tool.refresh_lsp_menu(true, window, cx);
- return;
}
} else if lsp_tool.lsp_menu.take().is_some() {
cx.notify();
@@ -452,7 +452,7 @@ async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServ
&& entry
.file_name()
.to_str()
- .map_or(false, |name| name.starts_with("gopls_"))
+ .is_some_and(|name| name.starts_with("gopls_"))
{
last_binary_path = Some(entry.path());
}
@@ -280,7 +280,7 @@ impl JsonLspAdapter {
)
})?;
writer.replace(config.clone());
- return Ok(config);
+ Ok(config)
}
}
@@ -828,7 +828,7 @@ impl ToolchainLister for PythonToolchainProvider {
.get_env_var("CONDA_PREFIX".to_string())
.map(|conda_prefix| {
let is_match = |exe: &Option<PathBuf>| {
- exe.as_ref().map_or(false, |e| e.starts_with(&conda_prefix))
+ exe.as_ref().is_some_and(|e| e.starts_with(&conda_prefix))
};
match (is_match(&lhs.executable), is_match(&rhs.executable)) {
(true, false) => Ordering::Less,
@@ -403,7 +403,7 @@ impl LspAdapter for RustLspAdapter {
} else if completion
.detail
.as_ref()
- .map_or(false, |detail| detail.starts_with("macro_rules! "))
+ .is_some_and(|detail| detail.starts_with("macro_rules! "))
{
let text = completion.label.clone();
let len = text.len();
@@ -496,7 +496,7 @@ impl LspAdapter for RustLspAdapter {
let enable_lsp_tasks = ProjectSettings::get_global(cx)
.lsp
.get(&SERVER_NAME)
- .map_or(false, |s| s.enable_lsp_tasks);
+ .is_some_and(|s| s.enable_lsp_tasks);
if enable_lsp_tasks {
let experimental = json!({
"runnables": {
@@ -159,14 +159,14 @@ impl LivekitWindow {
if output
.audio_output_stream
.as_ref()
- .map_or(false, |(track, _)| track.sid() == unpublish_sid)
+ .is_some_and(|(track, _)| track.sid() == unpublish_sid)
{
output.audio_output_stream.take();
}
if output
.screen_share_output_view
.as_ref()
- .map_or(false, |(track, _)| track.sid() == unpublish_sid)
+ .is_some_and(|(track, _)| track.sid() == unpublish_sid)
{
output.screen_share_output_view.take();
}
@@ -76,22 +76,22 @@ impl<'a> MarkdownParser<'a> {
if self.eof() || (steps + self.cursor) >= self.tokens.len() {
return self.tokens.last();
}
- return self.tokens.get(self.cursor + steps);
+ self.tokens.get(self.cursor + steps)
}
fn previous(&self) -> Option<&(Event<'_>, Range<usize>)> {
if self.cursor == 0 || self.cursor > self.tokens.len() {
return None;
}
- return self.tokens.get(self.cursor - 1);
+ self.tokens.get(self.cursor - 1)
}
fn current(&self) -> Option<&(Event<'_>, Range<usize>)> {
- return self.peek(0);
+ self.peek(0)
}
fn current_event(&self) -> Option<&Event<'_>> {
- return self.current().map(|(event, _)| event);
+ self.current().map(|(event, _)| event)
}
fn is_text_like(event: &Event) -> bool {
@@ -111,11 +111,10 @@ impl RenderContext {
/// buffer font size changes. The callees of this function should be reimplemented to use real
/// relative sizing once that is implemented in GPUI
pub fn scaled_rems(&self, rems: f32) -> Rems {
- return self
- .buffer_text_style
+ self.buffer_text_style
.font_size
.to_rems(self.window_rem_size)
- .mul(rems);
+ .mul(rems)
}
/// This ensures that children inside of block quotes
@@ -24,7 +24,7 @@ fn rename_assistant(
.nodes_for_capture_index(key_capture_ix)
.next()?
.byte_range();
- return Some((key_range, "agent".to_string()));
+ Some((key_range, "agent".to_string()))
}
fn rename_edit_prediction_assistant(
@@ -37,5 +37,5 @@ fn rename_edit_prediction_assistant(
.nodes_for_capture_index(key_capture_ix)
.next()?
.byte_range();
- return Some((key_range, "enabled_in_text_threads".to_string()));
+ Some((key_range, "enabled_in_text_threads".to_string()))
}
@@ -1146,13 +1146,13 @@ impl MultiBuffer {
pub fn last_transaction_id(&self, cx: &App) -> Option<TransactionId> {
if let Some(buffer) = self.as_singleton() {
- return buffer
+ buffer
.read(cx)
.peek_undo_stack()
- .map(|history_entry| history_entry.transaction_id());
+ .map(|history_entry| history_entry.transaction_id())
} else {
let last_transaction = self.history.undo_stack.last()?;
- return Some(last_transaction.id);
+ Some(last_transaction.id)
}
}
@@ -1725,7 +1725,7 @@ impl MultiBuffer {
merged_ranges.push(range.clone());
counts.push(1);
}
- return (merged_ranges, counts);
+ (merged_ranges, counts)
}
fn update_path_excerpts(
@@ -2482,7 +2482,7 @@ impl MultiBuffer {
let base_text_changed = snapshot
.diffs
.get(&buffer_id)
- .map_or(true, |old_diff| !new_diff.base_texts_eq(old_diff));
+ .is_none_or(|old_diff| !new_diff.base_texts_eq(old_diff));
snapshot.diffs.insert(buffer_id, new_diff);
@@ -2776,7 +2776,7 @@ impl MultiBuffer {
if diff_hunk.excerpt_id.cmp(&end_excerpt_id, &snapshot).is_gt() {
continue;
}
- if last_hunk_row.map_or(false, |row| row >= diff_hunk.row_range.start) {
+ if last_hunk_row.is_some_and(|row| row >= diff_hunk.row_range.start) {
continue;
}
let start = Anchor::in_buffer(
@@ -3040,7 +3040,7 @@ impl MultiBuffer {
is_dirty |= buffer.is_dirty();
has_deleted_file |= buffer
.file()
- .map_or(false, |file| file.disk_state() == DiskState::Deleted);
+ .is_some_and(|file| file.disk_state() == DiskState::Deleted);
has_conflict |= buffer.has_conflict();
}
if edited {
@@ -3198,9 +3198,10 @@ impl MultiBuffer {
// If this is the last edit that intersects the current diff transform,
// then recreate the content up to the end of this transform, to prepare
// for reusing additional slices of the old transforms.
- if excerpt_edits.peek().map_or(true, |next_edit| {
- next_edit.old.start >= old_diff_transforms.end().0
- }) {
+ if excerpt_edits
+ .peek()
+ .is_none_or(|next_edit| next_edit.old.start >= old_diff_transforms.end().0)
+ {
let keep_next_old_transform = (old_diff_transforms.start().0 >= edit.old.end)
&& match old_diff_transforms.item() {
Some(DiffTransform::BufferContent {
@@ -3595,7 +3596,7 @@ impl MultiBuffer {
let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
let mut last_end = None;
for _ in 0..edit_count {
- if last_end.map_or(false, |last_end| last_end >= snapshot.len()) {
+ if last_end.is_some_and(|last_end| last_end >= snapshot.len()) {
break;
}
@@ -4649,7 +4650,7 @@ impl MultiBufferSnapshot {
return true;
}
}
- return true;
+ true
}
pub fn prev_non_blank_row(&self, mut row: MultiBufferRow) -> Option<MultiBufferRow> {
@@ -4954,7 +4955,7 @@ impl MultiBufferSnapshot {
while let Some(replacement) = self.replaced_excerpts.get(&excerpt_id) {
excerpt_id = *replacement;
}
- return excerpt_id;
+ excerpt_id
}
pub fn summaries_for_anchors<'a, D, I>(&'a self, anchors: I) -> Vec<D>
@@ -5072,9 +5073,9 @@ impl MultiBufferSnapshot {
if point == region.range.end.key && region.has_trailing_newline {
position.add_assign(&D::from_text_summary(&TextSummary::newline()));
}
- return Some(position);
+ Some(position)
} else {
- return Some(D::from_text_summary(&self.text_summary()));
+ Some(D::from_text_summary(&self.text_summary()))
}
})
}
@@ -5114,7 +5115,7 @@ impl MultiBufferSnapshot {
// Leave min and max anchors unchanged if invalid or
// if the old excerpt still exists at this location
let mut kept_position = next_excerpt
- .map_or(false, |e| e.id == old_excerpt_id && e.contains(&anchor))
+ .is_some_and(|e| e.id == old_excerpt_id && e.contains(&anchor))
|| old_excerpt_id == ExcerptId::max()
|| old_excerpt_id == ExcerptId::min();
@@ -5482,7 +5483,7 @@ impl MultiBufferSnapshot {
let range_filter = |open: Range<usize>, close: Range<usize>| -> bool {
excerpt_buffer_range.contains(&open.start)
&& excerpt_buffer_range.contains(&close.end)
- && range_filter.map_or(true, |filter| filter(buffer, open, close))
+ && range_filter.is_none_or(|filter| filter(buffer, open, close))
};
let (open, close) = excerpt.buffer().innermost_enclosing_bracket_ranges(
@@ -5642,10 +5643,10 @@ impl MultiBufferSnapshot {
.buffer
.line_indents_in_row_range(buffer_start_row..buffer_end_row);
cursor.next();
- return Some(line_indents.map(move |(buffer_row, indent)| {
+ Some(line_indents.map(move |(buffer_row, indent)| {
let row = region.range.start.row + (buffer_row - region.buffer_range.start.row);
(MultiBufferRow(row), indent, ®ion.excerpt.buffer)
- }));
+ }))
})
.flatten()
}
@@ -5682,10 +5683,10 @@ impl MultiBufferSnapshot {
.buffer
.reversed_line_indents_in_row_range(buffer_start_row..buffer_end_row);
cursor.prev();
- return Some(line_indents.map(move |(buffer_row, indent)| {
+ Some(line_indents.map(move |(buffer_row, indent)| {
let row = region.range.start.row + (buffer_row - region.buffer_range.start.row);
(MultiBufferRow(row), indent, ®ion.excerpt.buffer)
- }));
+ }))
})
.flatten()
}
@@ -6545,7 +6546,7 @@ where
&& self
.excerpts
.item()
- .map_or(false, |excerpt| excerpt.id != hunk_info.excerpt_id)
+ .is_some_and(|excerpt| excerpt.id != hunk_info.excerpt_id)
{
self.excerpts.next();
}
@@ -6592,7 +6593,7 @@ where
let prev_transform = self.diff_transforms.item();
self.diff_transforms.next();
- prev_transform.map_or(true, |next_transform| {
+ prev_transform.is_none_or(|next_transform| {
matches!(next_transform, DiffTransform::BufferContent { .. })
})
}
@@ -6607,12 +6608,12 @@ where
}
let next_transform = self.diff_transforms.next_item();
- next_transform.map_or(true, |next_transform| match next_transform {
+ next_transform.is_none_or(|next_transform| match next_transform {
DiffTransform::BufferContent { .. } => true,
DiffTransform::DeletedHunk { hunk_info, .. } => self
.excerpts
.item()
- .map_or(false, |excerpt| excerpt.id != hunk_info.excerpt_id),
+ .is_some_and(|excerpt| excerpt.id != hunk_info.excerpt_id),
})
}
@@ -6645,7 +6646,7 @@ where
buffer_end.add_assign(&buffer_range_len);
let start = self.diff_transforms.start().output_dimension.0;
let end = self.diff_transforms.end().output_dimension.0;
- return Some(MultiBufferRegion {
+ Some(MultiBufferRegion {
buffer,
excerpt,
has_trailing_newline: *has_trailing_newline,
@@ -6655,7 +6656,7 @@ where
)),
buffer_range: buffer_start..buffer_end,
range: start..end,
- });
+ })
}
DiffTransform::BufferContent {
inserted_hunk_info, ..
@@ -7493,61 +7494,59 @@ impl Iterator for MultiBufferRows<'_> {
self.cursor.next();
if let Some(next_region) = self.cursor.region() {
region = next_region;
- } else {
- if self.point == self.cursor.diff_transforms.end().output_dimension.0 {
- let multibuffer_row = MultiBufferRow(self.point.row);
- let last_excerpt = self
- .cursor
- .excerpts
- .item()
- .or(self.cursor.excerpts.prev_item())?;
- let last_row = last_excerpt
- .range
- .context
- .end
- .to_point(&last_excerpt.buffer)
- .row;
+ } else if self.point == self.cursor.diff_transforms.end().output_dimension.0 {
+ let multibuffer_row = MultiBufferRow(self.point.row);
+ let last_excerpt = self
+ .cursor
+ .excerpts
+ .item()
+ .or(self.cursor.excerpts.prev_item())?;
+ let last_row = last_excerpt
+ .range
+ .context
+ .end
+ .to_point(&last_excerpt.buffer)
+ .row;
- let first_row = last_excerpt
- .range
- .context
- .start
- .to_point(&last_excerpt.buffer)
- .row;
+ let first_row = last_excerpt
+ .range
+ .context
+ .start
+ .to_point(&last_excerpt.buffer)
+ .row;
- let expand_info = if self.is_singleton {
- None
- } else {
- let needs_expand_up = first_row == last_row
- && last_row > 0
- && !region.diff_hunk_status.is_some_and(|d| d.is_deleted());
- let needs_expand_down = last_row < last_excerpt.buffer.max_point().row;
-
- if needs_expand_up && needs_expand_down {
- Some(ExpandExcerptDirection::UpAndDown)
- } else if needs_expand_up {
- Some(ExpandExcerptDirection::Up)
- } else if needs_expand_down {
- Some(ExpandExcerptDirection::Down)
- } else {
- None
- }
- .map(|direction| ExpandInfo {
- direction,
- excerpt_id: last_excerpt.id,
- })
- };
- self.point += Point::new(1, 0);
- return Some(RowInfo {
- buffer_id: Some(last_excerpt.buffer_id),
- buffer_row: Some(last_row),
- multibuffer_row: Some(multibuffer_row),
- diff_status: None,
- expand_info,
- });
+ let expand_info = if self.is_singleton {
+ None
} else {
- return None;
- }
+ let needs_expand_up = first_row == last_row
+ && last_row > 0
+ && !region.diff_hunk_status.is_some_and(|d| d.is_deleted());
+ let needs_expand_down = last_row < last_excerpt.buffer.max_point().row;
+
+ if needs_expand_up && needs_expand_down {
+ Some(ExpandExcerptDirection::UpAndDown)
+ } else if needs_expand_up {
+ Some(ExpandExcerptDirection::Up)
+ } else if needs_expand_down {
+ Some(ExpandExcerptDirection::Down)
+ } else {
+ None
+ }
+ .map(|direction| ExpandInfo {
+ direction,
+ excerpt_id: last_excerpt.id,
+ })
+ };
+ self.point += Point::new(1, 0);
+ return Some(RowInfo {
+ buffer_id: Some(last_excerpt.buffer_id),
+ buffer_row: Some(last_row),
+ multibuffer_row: Some(multibuffer_row),
+ diff_status: None,
+ expand_info,
+ });
+ } else {
+ return None;
};
}
@@ -197,7 +197,7 @@ impl NodeRuntime {
state.instance = Some(instance.boxed_clone());
state.last_options = Some(options);
- return instance;
+ instance
}
pub async fn binary_path(&self) -> Result<PathBuf> {
@@ -210,12 +210,12 @@ impl ThemePreviewTile {
}
fn render_borderless(seed: f32, theme: Arc<Theme>) -> impl IntoElement {
- return Self::render_editor(
+ Self::render_editor(
seed,
theme,
Self::SIDEBAR_WIDTH_DEFAULT,
Self::SKELETON_HEIGHT_DEFAULT,
- );
+ )
}
fn render_border(seed: f32, theme: Arc<Theme>) -> impl IntoElement {
@@ -246,7 +246,7 @@ impl ThemePreviewTile {
) -> impl IntoElement {
let sidebar_width = relative(0.20);
- return div()
+ div()
.size_full()
.p(Self::ROOT_PADDING)
.rounded(Self::ROOT_RADIUS)
@@ -278,7 +278,7 @@ impl ThemePreviewTile {
)),
),
)
- .into_any_element();
+ .into_any_element()
}
}
@@ -9,7 +9,7 @@ use strum::EnumIter;
pub const OPEN_AI_API_URL: &str = "https://api.openai.com/v1";
fn is_none_or_empty<T: AsRef<[U]>, U>(opt: &Option<T>) -> bool {
- opt.as_ref().map_or(true, |v| v.as_ref().is_empty())
+ opt.as_ref().is_none_or(|v| v.as_ref().is_empty())
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
@@ -241,7 +241,7 @@ impl Model {
///
/// If the model does not support the parameter, do not pass it up.
pub fn supports_prompt_cache_key(&self) -> bool {
- return true;
+ true
}
}
@@ -8,7 +8,7 @@ use std::convert::TryFrom;
pub const OPEN_ROUTER_API_URL: &str = "https://openrouter.ai/api/v1";
fn is_none_or_empty<T: AsRef<[U]>, U>(opt: &Option<T>) -> bool {
- opt.as_ref().map_or(true, |v| v.as_ref().is_empty())
+ opt.as_ref().is_none_or(|v| v.as_ref().is_empty())
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
@@ -503,16 +503,16 @@ impl SearchData {
&& multi_buffer_snapshot
.chars_at(extended_context_left_border)
.last()
- .map_or(false, |c| !c.is_whitespace());
+ .is_some_and(|c| !c.is_whitespace());
let truncated_right = entire_context_text
.chars()
.last()
- .map_or(true, |c| !c.is_whitespace())
+ .is_none_or(|c| !c.is_whitespace())
&& extended_context_right_border > context_right_border
&& multi_buffer_snapshot
.chars_at(extended_context_right_border)
.next()
- .map_or(false, |c| !c.is_whitespace());
+ .is_some_and(|c| !c.is_whitespace());
search_match_indices.iter_mut().for_each(|range| {
range.start = multi_buffer_snapshot.clip_offset(
range.start.saturating_sub(left_whitespaces_offset),
@@ -1259,7 +1259,7 @@ impl OutlinePanel {
dirs_worktree_id == worktree_id
&& dirs
.last()
- .map_or(false, |dir| dir.path.as_ref() == parent_path)
+ .is_some_and(|dir| dir.path.as_ref() == parent_path)
}
_ => false,
})
@@ -1453,9 +1453,7 @@ impl OutlinePanel {
if self
.unfolded_dirs
.get(&directory_worktree)
- .map_or(true, |unfolded_dirs| {
- !unfolded_dirs.contains(&directory_entry.id)
- })
+ .is_none_or(|unfolded_dirs| !unfolded_dirs.contains(&directory_entry.id))
{
return false;
}
@@ -2156,7 +2154,7 @@ impl OutlinePanel {
ExcerptOutlines::Invalidated(outlines) => Some(outlines),
ExcerptOutlines::NotFetched => None,
})
- .map_or(false, |outlines| !outlines.is_empty());
+ .is_some_and(|outlines| !outlines.is_empty());
let is_expanded = !self
.collapsed_entries
.contains(&CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id));
@@ -2953,7 +2951,7 @@ impl OutlinePanel {
.map(|(parent_dir_id, _)| {
new_unfolded_dirs
.get(&directory.worktree_id)
- .map_or(true, |unfolded_dirs| {
+ .is_none_or(|unfolded_dirs| {
unfolded_dirs
.contains(parent_dir_id)
})
@@ -3444,9 +3442,8 @@ impl OutlinePanel {
}
fn is_singleton_active(&self, cx: &App) -> bool {
- self.active_editor().map_or(false, |active_editor| {
- active_editor.read(cx).buffer().read(cx).is_singleton()
- })
+ self.active_editor()
+ .is_some_and(|active_editor| active_editor.read(cx).buffer().read(cx).is_singleton())
}
fn invalidate_outlines(&mut self, ids: &[ExcerptId]) {
@@ -3664,7 +3661,7 @@ impl OutlinePanel {
let is_root = project
.read(cx)
.worktree_for_id(directory_entry.worktree_id, cx)
- .map_or(false, |worktree| {
+ .is_some_and(|worktree| {
worktree.read(cx).root_entry() == Some(&directory_entry.entry)
});
let folded = auto_fold_dirs
@@ -3672,7 +3669,7 @@ impl OutlinePanel {
&& outline_panel
.unfolded_dirs
.get(&directory_entry.worktree_id)
- .map_or(true, |unfolded_dirs| {
+ .is_none_or(|unfolded_dirs| {
!unfolded_dirs.contains(&directory_entry.entry.id)
});
let fs_depth = outline_panel
@@ -3752,7 +3749,7 @@ impl OutlinePanel {
.iter()
.rev()
.nth(folded_dirs.entries.len() + 1)
- .map_or(true, |parent| parent.expanded);
+ .is_none_or(|parent| parent.expanded);
if start_of_collapsed_dir_sequence
|| parent_expanded
|| query.is_some()
@@ -3812,7 +3809,7 @@ impl OutlinePanel {
.iter()
.all(|entry| entry.path != parent.path)
})
- .map_or(true, |parent| parent.expanded);
+ .is_none_or(|parent| parent.expanded);
if !is_singleton && (parent_expanded || query.is_some()) {
outline_panel.push_entry(
&mut generation_state,
@@ -3837,7 +3834,7 @@ impl OutlinePanel {
.iter()
.all(|entry| entry.path != parent.path)
})
- .map_or(true, |parent| parent.expanded);
+ .is_none_or(|parent| parent.expanded);
if !is_singleton && (parent_expanded || query.is_some()) {
outline_panel.push_entry(
&mut generation_state,
@@ -3958,7 +3955,7 @@ impl OutlinePanel {
.iter()
.all(|entry| entry.path != parent.path)
})
- .map_or(true, |parent| parent.expanded);
+ .is_none_or(|parent| parent.expanded);
if parent_expanded || query.is_some() {
outline_panel.push_entry(
&mut generation_state,
@@ -4438,7 +4435,7 @@ impl OutlinePanel {
}
fn should_replace_active_item(&self, new_active_item: &dyn ItemHandle) -> bool {
- self.active_item().map_or(true, |active_item| {
+ self.active_item().is_none_or(|active_item| {
!self.pinned && active_item.item_id() != new_active_item.item_id()
})
}
@@ -119,7 +119,7 @@ impl Prettier {
None
}
}).any(|workspace_definition| {
- workspace_definition == subproject_path.to_string_lossy() || PathMatcher::new(&[workspace_definition]).ok().map_or(false, |path_matcher| path_matcher.is_match(subproject_path))
+ workspace_definition == subproject_path.to_string_lossy() || PathMatcher::new(&[workspace_definition]).ok().is_some_and(|path_matcher| path_matcher.is_match(subproject_path))
}) {
anyhow::ensure!(has_prettier_in_node_modules(fs, &path_to_check).await?, "Path {path_to_check:?} is the workspace root for project in {closest_package_json_path:?}, but it has no prettier installed");
log::info!("Found prettier path {path_to_check:?} in the workspace root for project in {closest_package_json_path:?}");
@@ -217,7 +217,7 @@ impl Prettier {
workspace_definition == subproject_path.to_string_lossy()
|| PathMatcher::new(&[workspace_definition])
.ok()
- .map_or(false, |path_matcher| {
+ .is_some_and(|path_matcher| {
path_matcher.is_match(subproject_path)
})
})
@@ -234,7 +234,7 @@ impl RemoteBufferStore {
}
}
}
- return Ok(None);
+ Ok(None)
}
pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
@@ -1313,10 +1313,7 @@ impl BufferStore {
let new_path = file.path.clone();
buffer.file_updated(Arc::new(file), cx);
- if old_file
- .as_ref()
- .map_or(true, |old| *old.path() != new_path)
- {
+ if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
Some(old_file)
} else {
None
@@ -102,7 +102,7 @@ fn parse(str: &str, mode: ParseMode) -> Option<Hsla> {
};
}
- return None;
+ None
}
fn parse_component(value: &str, max: f32) -> Option<f32> {
@@ -146,7 +146,7 @@ impl DapLocator for CargoLocator {
let is_test = build_config
.args
.first()
- .map_or(false, |arg| arg == "test" || arg == "t");
+ .is_some_and(|arg| arg == "test" || arg == "t");
let executables = output
.lines()
@@ -28,9 +28,7 @@ impl DapLocator for PythonLocator {
let valid_program = build_config.command.starts_with("$ZED_")
|| Path::new(&build_config.command)
.file_name()
- .map_or(false, |name| {
- name.to_str().is_some_and(|path| path.starts_with("python"))
- });
+ .is_some_and(|name| name.to_str().is_some_and(|path| path.starts_with("python")));
if !valid_program || build_config.args.iter().any(|arg| arg == "-c") {
// We cannot debug selections.
return None;
@@ -329,7 +329,7 @@ impl Iterator for MemoryIterator {
}
if !self.fetch_next_page() {
self.start += 1;
- return Some(MemoryCell(None));
+ Some(MemoryCell(None))
} else {
self.next()
}
@@ -431,7 +431,7 @@ impl RunningMode {
let should_send_exception_breakpoints = capabilities
.exception_breakpoint_filters
.as_ref()
- .map_or(false, |filters| !filters.is_empty())
+ .is_some_and(|filters| !filters.is_empty())
|| !configuration_done_supported;
let supports_exception_filters = capabilities
.supports_exception_filter_options
@@ -710,9 +710,7 @@ where
T: LocalDapCommand + PartialEq + Eq + Hash,
{
fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool {
- (rhs as &dyn Any)
- .downcast_ref::<Self>()
- .map_or(false, |rhs| self == rhs)
+ (rhs as &dyn Any).downcast_ref::<Self>() == Some(self)
}
fn dyn_hash(&self, mut hasher: &mut dyn Hasher) {
@@ -1085,7 +1083,7 @@ impl Session {
})
.detach();
- return tx;
+ tx
}
pub fn is_started(&self) -> bool {
@@ -781,9 +781,7 @@ impl GitStore {
let is_unmerged = self
.repository_and_path_for_buffer_id(buffer_id, cx)
- .map_or(false, |(repo, path)| {
- repo.read(cx).snapshot.has_conflict(&path)
- });
+ .is_some_and(|(repo, path)| repo.read(cx).snapshot.has_conflict(&path));
let git_store = cx.weak_entity();
let buffer_git_state = self
.diffs
@@ -2501,14 +2499,14 @@ impl BufferGitState {
pub fn wait_for_recalculation(&mut self) -> Option<impl Future<Output = ()> + use<>> {
if *self.recalculating_tx.borrow() {
let mut rx = self.recalculating_tx.subscribe();
- return Some(async move {
+ Some(async move {
loop {
let is_recalculating = rx.recv().await;
if is_recalculating != Some(true) {
break;
}
}
- });
+ })
} else {
None
}
@@ -2879,7 +2877,7 @@ impl RepositorySnapshot {
self.merge.conflicted_paths.contains(repo_path);
let has_conflict_currently = self
.status_for_path(repo_path)
- .map_or(false, |entry| entry.status.is_conflicted());
+ .is_some_and(|entry| entry.status.is_conflicted());
had_conflict_on_last_merge_head_change || has_conflict_currently
}
@@ -3531,7 +3529,7 @@ impl Repository {
&& buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state().exists())
+ .is_some_and(|file| file.disk_state().exists())
{
save_futures.push(buffer_store.save_buffer(buffer, cx));
}
@@ -3597,7 +3595,7 @@ impl Repository {
&& buffer
.read(cx)
.file()
- .map_or(false, |file| file.disk_state().exists())
+ .is_some_and(|file| file.disk_state().exists())
{
save_futures.push(buffer_store.save_buffer(buffer, cx));
}
@@ -3447,9 +3447,7 @@ impl LspCommand for GetCodeLens {
.server_capabilities
.code_lens_provider
.as_ref()
- .map_or(false, |code_lens_options| {
- code_lens_options.resolve_provider.unwrap_or(false)
- })
+ .is_some_and(|code_lens_options| code_lens_options.resolve_provider.unwrap_or(false))
}
fn to_lsp(
@@ -1038,7 +1038,7 @@ impl LocalLspStore {
if let Some(LanguageServerState::Running { server, .. }) =
self.language_servers.get(&state.id)
{
- return Some(server);
+ Some(server)
} else {
None
}
@@ -1879,7 +1879,7 @@ impl LocalLspStore {
) -> Result<Vec<(Range<Anchor>, Arc<str>)>> {
let capabilities = &language_server.capabilities();
let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
- if range_formatting_provider.map_or(false, |provider| provider == &OneOf::Left(false)) {
+ if range_formatting_provider == Some(&OneOf::Left(false)) {
anyhow::bail!(
"{} language server does not support range formatting",
language_server.name()
@@ -2642,7 +2642,7 @@ impl LocalLspStore {
this.request_lsp(buffer.clone(), server, request, cx)
})?
.await?;
- return Ok(actions);
+ Ok(actions)
}
pub async fn execute_code_actions_on_server(
@@ -2718,7 +2718,7 @@ impl LocalLspStore {
}
}
}
- return Ok(());
+ Ok(())
}
pub async fn deserialize_text_edits(
@@ -2957,11 +2957,11 @@ impl LocalLspStore {
.update(cx, |this, cx| {
let path = buffer_to_edit.read(cx).project_path(cx);
let active_entry = this.active_entry;
- let is_active_entry = path.clone().map_or(false, |project_path| {
+ let is_active_entry = path.clone().is_some_and(|project_path| {
this.worktree_store
.read(cx)
.entry_for_path(&project_path, cx)
- .map_or(false, |entry| Some(entry.id) == active_entry)
+ .is_some_and(|entry| Some(entry.id) == active_entry)
});
let local = this.as_local_mut().unwrap();
@@ -4038,7 +4038,7 @@ impl LspStore {
servers.push((json_adapter, json_server, json_delegate));
}
- return Some(servers);
+ Some(servers)
})
.ok()
.flatten();
@@ -4050,7 +4050,7 @@ impl LspStore {
let Ok(Some((fs, _))) = this.read_with(cx, |this, _| {
let local = this.as_local()?;
let toolchain_store = local.toolchain_store().clone();
- return Some((local.fs.clone(), toolchain_store));
+ Some((local.fs.clone(), toolchain_store))
}) else {
return;
};
@@ -4312,9 +4312,10 @@ impl LspStore {
local_store.unregister_buffer_from_language_servers(buffer_entity, &file_url, cx);
}
buffer_entity.update(cx, |buffer, cx| {
- if buffer.language().map_or(true, |old_language| {
- !Arc::ptr_eq(old_language, &new_language)
- }) {
+ if buffer
+ .language()
+ .is_none_or(|old_language| !Arc::ptr_eq(old_language, &new_language))
+ {
buffer.set_language(Some(new_language.clone()), cx);
}
});
@@ -4514,7 +4515,7 @@ impl LspStore {
if !request.check_capabilities(language_server.adapter_server_capabilities()) {
return Task::ready(Ok(Default::default()));
}
- return cx.spawn(async move |this, cx| {
+ cx.spawn(async move |this, cx| {
let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
let id = lsp_request.id();
@@ -4573,7 +4574,7 @@ impl LspStore {
)
.await;
response
- });
+ })
}
fn on_settings_changed(&mut self, cx: &mut Context<Self>) {
@@ -7297,7 +7298,7 @@ impl LspStore {
include_ignored
|| worktree
.entry_for_path(path.as_ref())
- .map_or(false, |entry| !entry.is_ignored)
+ .is_some_and(|entry| !entry.is_ignored)
})
.flat_map(move |(path, summaries)| {
summaries.iter().map(move |(server_id, summary)| {
@@ -9341,9 +9342,7 @@ impl LspStore {
let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
.as_ref()
- .map_or(false, |disk_based_token| {
- token.starts_with(disk_based_token)
- });
+ .is_some_and(|disk_based_token| token.starts_with(disk_based_token));
match progress {
lsp::WorkDoneProgress::Begin(report) => {
@@ -10676,7 +10675,7 @@ impl LspStore {
let is_supporting = diagnostic
.related_information
.as_ref()
- .map_or(false, |infos| {
+ .is_some_and(|infos| {
infos.iter().any(|info| {
primary_diagnostic_group_ids.contains_key(&(
source,
@@ -10689,11 +10688,11 @@ impl LspStore {
let is_unnecessary = diagnostic
.tags
.as_ref()
- .map_or(false, |tags| tags.contains(&DiagnosticTag::UNNECESSARY));
+ .is_some_and(|tags| tags.contains(&DiagnosticTag::UNNECESSARY));
let underline = self
.language_server_adapter_for_id(server_id)
- .map_or(true, |adapter| adapter.underline_diagnostic(diagnostic));
+ .is_none_or(|adapter| adapter.underline_diagnostic(diagnostic));
if is_supporting {
supporting_diagnostics.insert(
@@ -10703,7 +10702,7 @@ impl LspStore {
} else {
let group_id = post_inc(&mut self.as_local_mut().unwrap().next_diagnostic_group_id);
let is_disk_based =
- source.map_or(false, |source| disk_based_sources.contains(source));
+ source.is_some_and(|source| disk_based_sources.contains(source));
sources_by_group_id.insert(group_id, source);
primary_diagnostic_group_ids
@@ -12409,7 +12408,7 @@ impl TryFrom<&FileOperationFilter> for RenameActionPredicate {
ops.pattern
.options
.as_ref()
- .map_or(false, |ops| ops.ignore_case.unwrap_or(false)),
+ .is_some_and(|ops| ops.ignore_case.unwrap_or(false)),
)
.build()?
.compile_matcher(),
@@ -12424,7 +12423,7 @@ struct RenameActionPredicate {
impl RenameActionPredicate {
// Returns true if language server should be notified
fn eval(&self, path: &str, is_dir: bool) -> bool {
- self.kind.as_ref().map_or(true, |kind| {
+ self.kind.as_ref().is_none_or(|kind| {
let expected_kind = if is_dir {
FileOperationPatternKind::Folder
} else {
@@ -218,10 +218,8 @@ impl ManifestQueryDelegate {
impl ManifestDelegate for ManifestQueryDelegate {
fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool {
- self.worktree.entry_for_path(path).map_or(false, |entry| {
- is_dir.map_or(true, |is_required_to_be_dir| {
- is_required_to_be_dir == entry.is_dir()
- })
+ self.worktree.entry_for_path(path).is_some_and(|entry| {
+ is_dir.is_none_or(|is_required_to_be_dir| is_required_to_be_dir == entry.is_dir())
})
}
@@ -314,7 +314,7 @@ impl LanguageServerTree {
pub(crate) fn remove_nodes(&mut self, ids: &BTreeSet<LanguageServerId>) {
for (_, servers) in &mut self.instances {
for (_, nodes) in &mut servers.roots {
- nodes.retain(|_, (node, _)| node.id.get().map_or(true, |id| !ids.contains(id)));
+ nodes.retain(|_, (node, _)| node.id.get().is_none_or(|id| !ids.contains(id)));
}
}
}
@@ -1897,7 +1897,7 @@ impl Project {
return true;
}
- return false;
+ false
}
pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
@@ -1905,7 +1905,7 @@ impl Project {
return Some(ssh_state.read(cx).connection_string().into());
}
- return None;
+ None
}
pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
@@ -4134,7 +4134,7 @@ impl Project {
}
})
} else {
- return Task::ready(None);
+ Task::ready(None)
}
}
@@ -5187,7 +5187,7 @@ impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
}
fn prefix(&self) -> Arc<str> {
- if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
+ if self.snapshot.root_entry().is_some_and(|e| e.is_file()) {
self.snapshot.root_name().into()
} else if self.include_root_name {
format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
@@ -5397,7 +5397,7 @@ impl Completion {
self.source
// `lsp::CompletionListItemDefaults` has `insert_text_format` field
.lsp_completion(true)
- .map_or(false, |lsp_completion| {
+ .is_some_and(|lsp_completion| {
lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
})
}
@@ -5453,9 +5453,10 @@ fn provide_inline_values(
.collect::<String>();
let point = snapshot.offset_to_point(capture_range.end);
- while scopes.last().map_or(false, |scope: &Range<_>| {
- !scope.contains(&capture_range.start)
- }) {
+ while scopes
+ .last()
+ .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
+ {
scopes.pop();
}
@@ -5465,7 +5466,7 @@ fn provide_inline_values(
let scope = if scopes
.last()
- .map_or(true, |scope| !scope.contains(&active_debug_line_offset))
+ .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
{
VariableScope::Global
} else {
@@ -188,9 +188,9 @@ pub struct DiagnosticsSettings {
impl DiagnosticsSettings {
pub fn fetch_cargo_diagnostics(&self) -> bool {
- self.cargo.as_ref().map_or(false, |cargo_diagnostics| {
- cargo_diagnostics.fetch_cargo_diagnostics
- })
+ self.cargo
+ .as_ref()
+ .is_some_and(|cargo_diagnostics| cargo_diagnostics.fetch_cargo_diagnostics)
}
}
@@ -2947,9 +2947,10 @@ fn chunks_with_diagnostics<T: ToOffset + ToPoint>(
) -> Vec<(String, Option<DiagnosticSeverity>)> {
let mut chunks: Vec<(String, Option<DiagnosticSeverity>)> = Vec::new();
for chunk in buffer.snapshot().chunks(range, true) {
- if chunks.last().map_or(false, |prev_chunk| {
- prev_chunk.1 == chunk.diagnostic_severity
- }) {
+ if chunks
+ .last()
+ .is_some_and(|prev_chunk| prev_chunk.1 == chunk.diagnostic_severity)
+ {
chunks.last_mut().unwrap().0.push_str(chunk.text);
} else {
chunks.push((chunk.text.to_string(), chunk.diagnostic_severity));
@@ -99,7 +99,7 @@ impl Project {
}
}
- return None;
+ None
}
pub fn create_terminal(
@@ -518,7 +518,7 @@ impl Project {
smol::block_on(fs.metadata(&bin_path))
.ok()
.flatten()
- .map_or(false, |meta| meta.is_dir)
+ .is_some_and(|meta| meta.is_dir)
})
}
@@ -563,7 +563,7 @@ impl ProjectPanel {
if project_panel
.edit_state
.as_ref()
- .map_or(false, |state| state.processing_filename.is_none())
+ .is_some_and(|state| state.processing_filename.is_none())
{
project_panel.edit_state = None;
project_panel.update_visible_entries(None, cx);
@@ -3091,7 +3091,7 @@ impl ProjectPanel {
entry.id == new_entry_id || {
self.ancestors
.get(&entry.id)
- .map_or(false, |entries| entries.ancestors.contains(&new_entry_id))
+ .is_some_and(|entries| entries.ancestors.contains(&new_entry_id))
}
} else {
false
@@ -3974,7 +3974,7 @@ impl ProjectPanel {
let is_marked = self.marked_entries.contains(&selection);
let is_active = self
.selection
- .map_or(false, |selection| selection.entry_id == entry_id);
+ .is_some_and(|selection| selection.entry_id == entry_id);
let file_name = details.filename.clone();
@@ -4181,7 +4181,7 @@ impl ProjectPanel {
|| this
.expanded_dir_ids
.get(&details.worktree_id)
- .map_or(false, |ids| ids.binary_search(&entry_id).is_ok())
+ .is_some_and(|ids| ids.binary_search(&entry_id).is_ok())
{
return;
}
@@ -4401,19 +4401,17 @@ impl ProjectPanel {
} else {
h_flex().child(Icon::from_path(icon.to_string()).color(Color::Muted))
}
+ } else if let Some((icon_name, color)) =
+ entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
+ {
+ h_flex()
+ .size(IconSize::default().rems())
+ .child(Icon::new(icon_name).color(color).size(IconSize::Small))
} else {
- if let Some((icon_name, color)) =
- entry_diagnostic_aware_icon_name_and_color(diagnostic_severity)
- {
- h_flex()
- .size(IconSize::default().rems())
- .child(Icon::new(icon_name).color(color).size(IconSize::Small))
- } else {
- h_flex()
- .size(IconSize::default().rems())
- .invisible()
- .flex_none()
- }
+ h_flex()
+ .size(IconSize::default().rems())
+ .invisible()
+ .flex_none()
})
.child(
if let (Some(editor), true) = (Some(&self.filename_editor), show_editor) {
@@ -4465,7 +4463,7 @@ impl ProjectPanel {
);
} else {
let is_current_target = this.folded_directory_drag_target
- .map_or(false, |target|
+ .is_some_and(|target|
target.entry_id == entry_id &&
target.index == delimiter_target_index &&
target.is_delimiter_target
@@ -4509,7 +4507,7 @@ impl ProjectPanel {
} else {
let is_current_target = this.folded_directory_drag_target
.as_ref()
- .map_or(false, |target|
+ .is_some_and(|target|
target.entry_id == entry_id &&
target.index == index &&
!target.is_delimiter_target
@@ -4528,7 +4526,7 @@ impl ProjectPanel {
this.drag_onto(selections, target_entry_id, kind.is_file(), window, cx);
}
}))
- .when(folded_directory_drag_target.map_or(false, |target|
+ .when(folded_directory_drag_target.is_some_and(|target|
target.entry_id == entry_id &&
target.index == index
), |this| {
@@ -4694,7 +4692,7 @@ impl ProjectPanel {
let is_cut = self
.clipboard
.as_ref()
- .map_or(false, |e| e.is_cut() && e.items().contains(&selection));
+ .is_some_and(|e| e.is_cut() && e.items().contains(&selection));
EntryDetails {
filename,
@@ -4892,7 +4890,7 @@ impl ProjectPanel {
if skip_ignored
&& worktree
.entry_for_id(entry_id)
- .map_or(true, |entry| entry.is_ignored && !entry.is_always_included)
+ .is_none_or(|entry| entry.is_ignored && !entry.is_always_included)
{
anyhow::bail!("can't reveal an ignored entry in the project panel");
}
@@ -5687,7 +5685,7 @@ impl Panel for ProjectPanel {
project.visible_worktrees(cx).any(|tree| {
tree.read(cx)
.root_entry()
- .map_or(false, |entry| entry.is_dir())
+ .is_some_and(|entry| entry.is_dir())
})
}
@@ -196,7 +196,7 @@ impl PickerDelegate for ProjectSymbolsDelegate {
.partition(|candidate| {
project
.entry_for_path(&symbols[candidate.id].path, cx)
- .map_or(false, |e| !e.is_ignored)
+ .is_some_and(|e| !e.is_ignored)
});
delegate.visible_match_candidates = visible_match_candidates;
@@ -247,9 +247,7 @@ impl PromptStore {
if metadata_db
.get(&txn, &prompt_id_v2)?
- .map_or(true, |metadata_v2| {
- metadata_v1.saved_at > metadata_v2.saved_at
- })
+ .is_none_or(|metadata_v2| metadata_v1.saved_at > metadata_v2.saved_at)
{
metadata_db.put(
&mut txn,
@@ -286,7 +286,7 @@ impl PromptBuilder {
break;
}
for event in changed_paths {
- if event.path.starts_with(&templates_dir) && event.path.extension().map_or(false, |ext| ext == "hbs") {
+ if event.path.starts_with(&templates_dir) && event.path.extension().is_some_and(|ext| ext == "hbs") {
log::info!("Reloading prompt template override: {}", event.path.display());
if let Some(content) = params.fs.load(&event.path).await.log_err() {
let file_name = event.path.file_stem().unwrap().to_string_lossy();
@@ -37,7 +37,7 @@ impl ModalView for DisconnectedOverlay {
_window: &mut Window,
_: &mut Context<Self>,
) -> workspace::DismissDecision {
- return workspace::DismissDecision::Dismiss(self.finished);
+ workspace::DismissDecision::Dismiss(self.finished)
}
fn fade_out_background(&self) -> bool {
true
@@ -1410,7 +1410,7 @@ impl RemoteServerProjects {
if ssh_settings
.ssh_connections
.as_ref()
- .map_or(false, |connections| {
+ .is_some_and(|connections| {
state
.servers
.iter()
@@ -436,7 +436,7 @@ impl ModalView for SshConnectionModal {
_window: &mut Window,
_: &mut Context<Self>,
) -> workspace::DismissDecision {
- return workspace::DismissDecision::Dismiss(self.finished);
+ workspace::DismissDecision::Dismiss(self.finished)
}
fn fade_out_background(&self) -> bool {
@@ -1119,7 +1119,7 @@ impl SshRemoteClient {
}
fn state_is(&self, check: impl FnOnce(&State) -> bool) -> bool {
- self.state.lock().as_ref().map_or(false, check)
+ self.state.lock().as_ref().is_some_and(check)
}
fn try_set_state(&self, cx: &mut Context<Self>, map: impl FnOnce(&State) -> Option<State>) {
@@ -1870,7 +1870,7 @@ impl SshRemoteConnection {
.await?;
self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
.await?;
- return Ok(dst_path);
+ Ok(dst_path)
}
async fn download_binary_on_server(
@@ -126,7 +126,7 @@ impl PickerDelegate for KernelPickerDelegate {
.collect()
};
- return Task::ready(());
+ Task::ready(())
}
fn confirm(&mut self, _secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
@@ -434,7 +434,7 @@ fn runnable_ranges(
if start_language
.zip(end_language)
- .map_or(false, |(start, end)| start == end)
+ .is_some_and(|(start, end)| start == end)
{
(vec![snippet_range], None)
} else {
@@ -35,7 +35,7 @@ impl Rope {
&& (self
.chunks
.last()
- .map_or(false, |c| c.text.len() < chunk::MIN_BASE)
+ .is_some_and(|c| c.text.len() < chunk::MIN_BASE)
|| chunk.text.len() < chunk::MIN_BASE)
{
self.push_chunk(chunk.as_slice());
@@ -816,7 +816,7 @@ impl<'a> Chunks<'a> {
}
}
- return true;
+ true
}
}
@@ -703,9 +703,7 @@ impl RulesLibrary {
.delegate
.matches
.get(picker.delegate.selected_index())
- .map_or(true, |old_selected_prompt| {
- old_selected_prompt.id != prompt_id
- })
+ .is_none_or(|old_selected_prompt| old_selected_prompt.id != prompt_id)
&& let Some(ix) = picker
.delegate
.matches
@@ -653,7 +653,7 @@ impl KeymapFile {
let is_only_binding = keymap.0[index]
.bindings
.as_ref()
- .map_or(true, |bindings| bindings.len() == 1);
+ .is_none_or(|bindings| bindings.len() == 1);
let key_path: &[&str] = if is_only_binding {
&[]
} else {
@@ -703,7 +703,7 @@ impl KeymapFile {
} else if keymap.0[index]
.bindings
.as_ref()
- .map_or(true, |bindings| bindings.len() == 1)
+ .is_none_or(|bindings| bindings.len() == 1)
{
// if we are replacing the only binding in the section,
// just update the section in place, updating the context
@@ -1056,10 +1056,10 @@ mod tests {
#[track_caller]
fn parse_keystrokes(keystrokes: &str) -> Vec<Keystroke> {
- return keystrokes
+ keystrokes
.split(' ')
.map(|s| Keystroke::parse(s).expect("Keystrokes valid"))
- .collect();
+ .collect()
}
#[test]
@@ -72,7 +72,7 @@ pub fn update_value_in_json_text<'a>(
}
} else if key_path
.last()
- .map_or(false, |key| preserved_keys.contains(key))
+ .is_some_and(|key| preserved_keys.contains(key))
|| old_value != new_value
{
let mut new_value = new_value.clone();
@@ -384,7 +384,7 @@ pub fn replace_top_level_array_value_in_json_text(
remove_range.start = cursor.node().range().start_byte;
}
}
- return Ok((remove_range, String::new()));
+ Ok((remove_range, String::new()))
} else {
let (mut replace_range, mut replace_value) =
replace_value_in_json_text(value_str, key_path, tab_size, new_value, replace_key);
@@ -405,7 +405,7 @@ pub fn replace_top_level_array_value_in_json_text(
}
}
- return Ok((replace_range, replace_value));
+ Ok((replace_range, replace_value))
}
}
@@ -527,7 +527,7 @@ pub fn append_top_level_array_value_in_json_text(
let descendant_index = cursor.descendant_index();
let res = cursor.goto_first_child() && cursor.node().kind() == kind;
cursor.goto_descendant(descendant_index);
- return res;
+ res
}
}
@@ -1233,8 +1233,7 @@ impl SettingsStore {
// If a local settings file changed, then avoid recomputing local
// settings for any path outside of that directory.
- if changed_local_path.map_or(
- false,
+ if changed_local_path.is_some_and(
|(changed_root_id, changed_local_path)| {
*root_id != changed_root_id
|| !directory_path.starts_with(changed_local_path)
@@ -126,7 +126,7 @@ impl SettingsProfileSelectorDelegate {
) -> Option<String> {
let mat = self.matches.get(self.selected_index)?;
let profile_name = self.profile_names.get(mat.candidate_id)?;
- return Self::update_active_profile_name_global(profile_name.clone(), cx);
+ Self::update_active_profile_name_global(profile_name.clone(), cx)
}
fn update_active_profile_name_global(
@@ -553,7 +553,7 @@ impl KeymapEditor {
if exact_match {
keystrokes_match_exactly(&keystroke_query, keystrokes)
} else if keystroke_query.len() > keystrokes.len() {
- return false;
+ false
} else {
for keystroke_offset in 0..keystrokes.len() {
let mut found_count = 0;
@@ -568,12 +568,9 @@ impl KeymapEditor {
query.modifiers.is_subset_of(&keystroke.modifiers)
&& ((query.key.is_empty()
|| query.key == keystroke.key)
- && query
- .key_char
- .as_ref()
- .map_or(true, |q_kc| {
- q_kc == &keystroke.key
- }));
+ && query.key_char.as_ref().is_none_or(
+ |q_kc| q_kc == &keystroke.key,
+ ));
if matches {
found_count += 1;
query_cursor += 1;
@@ -585,7 +582,7 @@ impl KeymapEditor {
return true;
}
}
- return false;
+ false
}
})
});
@@ -2715,7 +2712,7 @@ impl ActionArgumentsEditor {
})
.ok();
}
- return result;
+ result
})
.detach_and_log_err(cx);
Self {
@@ -2818,7 +2815,7 @@ impl Render for ActionArgumentsEditor {
self.editor
.update(cx, |editor, _| editor.set_text_style_refinement(text_style));
- return v_flex().w_full().child(
+ v_flex().w_full().child(
h_flex()
.min_h_8()
.min_w_48()
@@ -2831,7 +2828,7 @@ impl Render for ActionArgumentsEditor {
.border_color(border_color)
.track_focus(&self.focus_handle)
.child(self.editor.clone()),
- );
+ )
}
}
@@ -2889,9 +2886,9 @@ impl CompletionProvider for KeyContextCompletionProvider {
_menu_is_open: bool,
_cx: &mut Context<Editor>,
) -> bool {
- text.chars().last().map_or(false, |last_char| {
- last_char.is_ascii_alphanumeric() || last_char == '_'
- })
+ text.chars()
+ .last()
+ .is_some_and(|last_char| last_char.is_ascii_alphanumeric() || last_char == '_')
}
}
@@ -2910,7 +2907,7 @@ async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp)
Some(task) => task.await.context("Failed to load JSON language").log_err(),
None => None,
};
- return json_language.unwrap_or_else(|| {
+ json_language.unwrap_or_else(|| {
Arc::new(Language::new(
LanguageConfig {
name: "JSON".into(),
@@ -2918,7 +2915,7 @@ async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp)
},
Some(tree_sitter_json::LANGUAGE.into()),
))
- });
+ })
}
async fn load_keybind_context_language(
@@ -2942,7 +2939,7 @@ async fn load_keybind_context_language(
.log_err(),
None => None,
};
- return language.unwrap_or_else(|| {
+ language.unwrap_or_else(|| {
Arc::new(Language::new(
LanguageConfig {
name: "Zed Keybind Context".into(),
@@ -2950,7 +2947,7 @@ async fn load_keybind_context_language(
},
Some(tree_sitter_rust::LANGUAGE.into()),
))
- });
+ })
}
async fn save_keybinding_update(
@@ -3130,7 +3127,7 @@ fn collect_contexts_from_assets() -> Vec<SharedString> {
let mut contexts = contexts.into_iter().collect::<Vec<_>>();
contexts.sort();
- return contexts;
+ contexts
}
impl SerializableItem for KeymapEditor {
@@ -116,19 +116,19 @@ impl KeystrokeInput {
&& self
.keystrokes
.last()
- .map_or(false, |last| last.key.is_empty())
+ .is_some_and(|last| last.key.is_empty())
{
return &self.keystrokes[..self.keystrokes.len() - 1];
}
- return &self.keystrokes;
+ &self.keystrokes
}
fn dummy(modifiers: Modifiers) -> Keystroke {
- return Keystroke {
+ Keystroke {
modifiers,
key: "".to_string(),
key_char: None,
- };
+ }
}
fn keystrokes_changed(&self, cx: &mut Context<Self>) {
@@ -182,7 +182,7 @@ impl KeystrokeInput {
fn end_close_keystrokes_capture(&mut self) -> Option<usize> {
self.close_keystrokes.take();
self.clear_close_keystrokes_timer.take();
- return self.close_keystrokes_start.take();
+ self.close_keystrokes_start.take()
}
fn handle_possible_close_keystroke(
@@ -233,7 +233,7 @@ impl KeystrokeInput {
return CloseKeystrokeResult::Partial;
}
self.end_close_keystrokes_capture();
- return CloseKeystrokeResult::None;
+ CloseKeystrokeResult::None
}
fn on_modifiers_changed(
@@ -437,7 +437,7 @@ impl KeystrokeInput {
// is a much more reliable check, as the intercept keystroke handlers are installed
// on focus of the inner focus handle, thereby ensuring our recording state does
// not get de-synced
- return self.inner_focus_handle.is_focused(window);
+ self.inner_focus_handle.is_focused(window)
}
}
@@ -934,7 +934,7 @@ mod tests {
let change_tracker = KeystrokeUpdateTracker::new(self.input.clone(), &mut self.cx);
let result = self.input.update_in(&mut self.cx, cb);
KeystrokeUpdateTracker::finish(change_tracker, &self.cx);
- return result;
+ result
}
}
@@ -731,7 +731,7 @@ impl<const COLS: usize> ColumnWidths<COLS> {
}
widths[col_idx] = widths[col_idx] + (diff - diff_remaining);
- return diff_remaining;
+ diff_remaining
}
}
@@ -33,7 +33,7 @@ impl Snippet {
choices: None,
};
- if !tabstops.last().map_or(false, |t| *t == end_tabstop) {
+ if !tabstops.last().is_some_and(|t| *t == end_tabstop) {
tabstops.push(end_tabstop);
}
}
@@ -71,16 +71,16 @@ async fn process_updates(
) -> Result<()> {
let fs = this.read_with(&cx, |this, _| this.fs.clone())?;
for entry_path in entries {
- if !entry_path
+ if entry_path
.extension()
- .map_or(false, |extension| extension == "json")
+ .is_none_or(|extension| extension != "json")
{
continue;
}
let entry_metadata = fs.metadata(&entry_path).await;
// Entry could have been removed, in which case we should no longer show completions for it.
let entry_exists = entry_metadata.is_ok();
- if entry_metadata.map_or(false, |entry| entry.map_or(false, |e| e.is_dir)) {
+ if entry_metadata.is_ok_and(|entry| entry.is_some_and(|e| e.is_dir)) {
// Don't process dirs.
continue;
}
@@ -94,9 +94,7 @@ impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D {
}
impl<'a, T: Summary> Dimension<'a, T> for () {
- fn zero(_: &T::Context) -> Self {
- ()
- }
+ fn zero(_: &T::Context) -> Self {}
fn add_summary(&mut self, _: &'a T, _: &T::Context) {}
}
@@ -728,7 +726,7 @@ impl<T: KeyedItem> SumTree<T> {
if old_item
.as_ref()
- .map_or(false, |old_item| old_item.key() < new_key)
+ .is_some_and(|old_item| old_item.key() < new_key)
{
new_tree.extend(buffered_items.drain(..), cx);
let slice = cursor.slice(&new_key, Bias::Left);
@@ -243,7 +243,7 @@ fn find_relevant_completion<'a>(
None => continue 'completions,
};
- if best_completion.map_or(false, |best| best.len() > trimmed_completion.len()) {
+ if best_completion.is_some_and(|best| best.len() > trimmed_completion.len()) {
continue;
}
@@ -221,9 +221,7 @@ pub fn version_path(version: u64) -> PathBuf {
}
pub async fn has_version(version_path: &Path) -> bool {
- fs::metadata(version_path)
- .await
- .map_or(false, |m| m.is_file())
+ fs::metadata(version_path).await.is_ok_and(|m| m.is_file())
}
pub async fn get_supermaven_agent_path(client: Arc<dyn HttpClient>) -> Result<PathBuf> {
@@ -283,7 +283,7 @@ pub fn task_contexts(
.project()
.read(cx)
.worktree_for_id(*worktree_id, cx)
- .map_or(false, |worktree| is_visible_directory(&worktree, cx))
+ .is_some_and(|worktree| is_visible_directory(&worktree, cx))
})
.or_else(|| {
workspace
@@ -372,7 +372,7 @@ pub fn task_contexts(
fn is_visible_directory(worktree: &Entity<Worktree>, cx: &App) -> bool {
let worktree = worktree.read(cx);
- worktree.is_visible() && worktree.root_entry().map_or(false, |entry| entry.is_dir())
+ worktree.is_visible() && worktree.root_entry().is_some_and(|entry| entry.is_dir())
}
fn worktree_context(worktree_abs_path: &Path) -> TaskContext {
@@ -55,7 +55,6 @@ macro_rules! serialize_property {
pub fn send_event(event: Event) {
if let Some(queue) = TELEMETRY_QUEUE.get() {
queue.unbounded_send(event).ok();
- return;
}
}
@@ -122,7 +122,7 @@ impl PtyProcessInfo {
}
pub(crate) fn kill_current_process(&mut self) -> bool {
- self.refresh().map_or(false, |process| process.kill())
+ self.refresh().is_some_and(|process| process.kill())
}
fn load(&mut self) -> Option<ProcessInfo> {
@@ -1299,23 +1299,19 @@ impl Terminal {
let selection = Selection::new(selection_type, point, side);
self.events
.push_back(InternalEvent::SetSelection(Some((selection, point))));
- return;
}
"escape" => {
self.events.push_back(InternalEvent::SetSelection(None));
- return;
}
"y" => {
self.copy(Some(false));
- return;
}
"i" => {
self.scroll_to_bottom();
self.toggle_vi_mode();
- return;
}
_ => {}
}
@@ -1891,11 +1887,11 @@ impl Terminal {
let e: Option<ExitStatus> = error_code.map(|code| {
#[cfg(unix)]
{
- return std::os::unix::process::ExitStatusExt::from_raw(code);
+ std::os::unix::process::ExitStatusExt::from_raw(code)
}
#[cfg(windows)]
{
- return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
+ std::os::windows::process::ExitStatusExt::from_raw(code as u32)
}
});
@@ -124,12 +124,12 @@ pub(super) fn find_from_grid_point<T: EventListener>(
&& file_path
.chars()
.nth(last_index - 1)
- .map_or(false, |c| c.is_ascii_digit());
+ .is_some_and(|c| c.is_ascii_digit());
let next_is_digit = last_index < file_path.len() - 1
&& file_path
.chars()
.nth(last_index + 1)
- .map_or(true, |c| c.is_ascii_digit());
+ .is_none_or(|c| c.is_ascii_digit());
if prev_is_digit && !next_is_digit {
let stripped_len = file_path.len() - last_index;
word_match = Match::new(
@@ -235,12 +235,10 @@ fn adjust_lightness_for_contrast(
} else {
high = mid;
}
+ } else if should_go_darker {
+ high = mid;
} else {
- if should_go_darker {
- high = mid;
- } else {
- low = mid;
- }
+ low = mid;
}
// If we're close enough to the target, stop
@@ -1478,7 +1478,7 @@ pub fn is_blank(cell: &IndexedCell) -> bool {
return false;
}
- return true;
+ true
}
fn to_highlighted_range_lines(
@@ -350,12 +350,10 @@ impl TerminalPanel {
pane.set_zoomed(false, cx);
});
cx.emit(PanelEvent::Close);
- } else {
- if let Some(focus_on_pane) =
- focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
- {
- focus_on_pane.focus_handle(cx).focus(window);
- }
+ } else if let Some(focus_on_pane) =
+ focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
+ {
+ focus_on_pane.focus_handle(cx).focus(window);
}
}
pane::Event::ZoomIn => {
@@ -896,9 +894,9 @@ impl TerminalPanel {
}
fn is_enabled(&self, cx: &App) -> bool {
- self.workspace.upgrade().map_or(false, |workspace| {
- is_enabled_in_workspace(workspace.read(cx), cx)
- })
+ self.workspace
+ .upgrade()
+ .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
}
fn activate_pane_in_direction(
@@ -1242,20 +1240,18 @@ impl Render for TerminalPanel {
let panes = terminal_panel.center.panes();
if let Some(&pane) = panes.get(action.0) {
window.focus(&pane.read(cx).focus_handle(cx));
- } else {
- if let Some(new_pane) =
- terminal_panel.new_pane_with_cloned_active_terminal(window, cx)
- {
- terminal_panel
- .center
- .split(
- &terminal_panel.active_pane,
- &new_pane,
- SplitDirection::Right,
- )
- .log_err();
- window.focus(&new_pane.focus_handle(cx));
- }
+ } else if let Some(new_pane) =
+ terminal_panel.new_pane_with_cloned_active_terminal(window, cx)
+ {
+ terminal_panel
+ .center
+ .split(
+ &terminal_panel.active_pane,
+ &new_pane,
+ SplitDirection::Right,
+ )
+ .log_err();
+ window.focus(&new_pane.focus_handle(cx));
}
}),
)
@@ -385,9 +385,7 @@ impl TerminalView {
.workspace
.upgrade()
.and_then(|workspace| workspace.read(cx).panel::<TerminalPanel>(cx))
- .map_or(false, |terminal_panel| {
- terminal_panel.read(cx).assistant_enabled()
- });
+ .is_some_and(|terminal_panel| terminal_panel.read(cx).assistant_enabled());
let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
menu.context(self.focus_handle.clone())
.action("New Terminal", Box::new(NewTerminal))
@@ -108,7 +108,7 @@ impl Anchor {
fragment_cursor.seek(&Some(fragment_id), Bias::Left);
fragment_cursor
.item()
- .map_or(false, |fragment| fragment.visible)
+ .is_some_and(|fragment| fragment.visible)
}
}
}
@@ -57,7 +57,7 @@ where
// Push the old edit if its new end is before the new edit's old start.
if let Some(old_edit) = old_edit.as_ref() {
let new_edit = new_edit.as_ref();
- if new_edit.map_or(true, |new_edit| old_edit.new.end < new_edit.old.start) {
+ if new_edit.is_none_or(|new_edit| old_edit.new.end < new_edit.old.start) {
let catchup = old_edit.old.start - old_start;
old_start += catchup;
new_start += catchup;
@@ -78,7 +78,7 @@ where
// Push the new edit if its old end is before the old edit's new start.
if let Some(new_edit) = new_edit.as_ref() {
let old_edit = old_edit.as_ref();
- if old_edit.map_or(true, |old_edit| new_edit.old.end < old_edit.new.start) {
+ if old_edit.is_none_or(|old_edit| new_edit.old.end < old_edit.new.start) {
let catchup = new_edit.new.start - new_start;
old_start += catchup;
new_start += catchup;
@@ -1149,7 +1149,7 @@ impl Buffer {
// Insert the new text before any existing fragments within the range.
if !new_text.is_empty() {
let mut old_start = old_fragments.start().1;
- if old_fragments.item().map_or(false, |f| f.visible) {
+ if old_fragments.item().is_some_and(|f| f.visible) {
old_start += fragment_start.0 - old_fragments.start().0.full_offset().0;
}
let new_start = new_fragments.summary().text.visible;
@@ -1834,7 +1834,7 @@ impl Buffer {
let mut edits: Vec<(Range<usize>, Arc<str>)> = Vec::new();
let mut last_end = None;
for _ in 0..edit_count {
- if last_end.map_or(false, |last_end| last_end >= self.len()) {
+ if last_end.is_some_and(|last_end| last_end >= self.len()) {
break;
}
let new_start = last_end.map_or(0, |last_end| last_end + 1);
@@ -2671,7 +2671,7 @@ impl<D: TextDimension + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator for Ed
if pending_edit
.as_ref()
- .map_or(false, |(change, _)| change.new.end < self.new_end)
+ .is_some_and(|(change, _)| change.new.end < self.new_end)
{
break;
}
@@ -189,7 +189,7 @@ impl TitleBar {
.as_ref()?
.read(cx)
.is_being_followed(collaborator.peer_id);
- let is_present = project_id.map_or(false, |project_id| {
+ let is_present = project_id.is_some_and(|project_id| {
collaborator.location
== ParticipantLocation::SharedProject { project_id }
});
@@ -73,7 +73,7 @@ fn get_dismissed(source: &str) -> bool {
db::kvp::KEY_VALUE_STORE
.read_kvp(&dismissed_at)
.log_err()
- .map_or(false, |dismissed| dismissed.is_some())
+ .is_some_and(|dismissed| dismissed.is_some())
}
fn persist_dismissed(source: &str, cx: &mut App) {
@@ -93,16 +93,16 @@ impl<M: ManagedView> PopoverMenuHandle<M> {
self.0
.borrow()
.as_ref()
- .map_or(false, |state| state.menu.borrow().as_ref().is_some())
+ .is_some_and(|state| state.menu.borrow().as_ref().is_some())
}
pub fn is_focused(&self, window: &Window, cx: &App) -> bool {
- self.0.borrow().as_ref().map_or(false, |state| {
+ self.0.borrow().as_ref().is_some_and(|state| {
state
.menu
.borrow()
.as_ref()
- .map_or(false, |model| model.focus_handle(cx).is_focused(window))
+ .is_some_and(|model| model.focus_handle(cx).is_focused(window))
})
}
@@ -105,7 +105,6 @@ impl Element for StickyItemsElement {
_window: &mut Window,
_cx: &mut App,
) -> Self::PrepaintState {
- ()
}
fn paint(
@@ -1215,11 +1215,11 @@ mod tests {
// Verify iterators advanced correctly
assert!(
- !a_iter.next().map_or(false, |c| c.is_ascii_digit()),
+ !a_iter.next().is_some_and(|c| c.is_ascii_digit()),
"Iterator a should have consumed all digits"
);
assert!(
- !b_iter.next().map_or(false, |c| c.is_ascii_digit()),
+ !b_iter.next().is_some_and(|c| c.is_ascii_digit()),
"Iterator b should have consumed all digits"
);
@@ -7,14 +7,12 @@ pub fn format_file_size(size: u64, use_decimal: bool) -> String {
} else {
format!("{:.1}MB", size as f64 / (1000.0 * 1000.0))
}
+ } else if size < 1024 {
+ format!("{size}B")
+ } else if size < 1024 * 1024 {
+ format!("{:.1}KiB", size as f64 / 1024.0)
} else {
- if size < 1024 {
- format!("{size}B")
- } else if size < 1024 * 1024 {
- format!("{:.1}KiB", size as f64 / 1024.0)
- } else {
- format!("{:.1}MiB", size as f64 / (1024.0 * 1024.0))
- }
+ format!("{:.1}MiB", size as f64 / (1024.0 * 1024.0))
}
}
@@ -301,7 +301,7 @@ pub fn get_shell_safe_zed_path() -> anyhow::Result<String> {
let zed_path_escaped =
shlex::try_quote(&zed_path).context("Failed to shell-escape Zed executable path.")?;
- return Ok(zed_path_escaped.to_string());
+ Ok(zed_path_escaped.to_string())
}
#[cfg(unix)]
@@ -825,7 +825,7 @@ mod rng {
pub fn new(rng: T) -> Self {
Self {
rng,
- simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
+ simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()),
}
}
@@ -566,7 +566,6 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
workspace.update(cx, |workspace, cx| {
e.notify_err(workspace, cx);
});
- return;
}
});
@@ -1444,7 +1443,7 @@ pub fn command_interceptor(mut input: &str, cx: &App) -> Vec<CommandInterceptRes
}];
}
}
- return Vec::default();
+ Vec::default()
}
fn generate_positions(string: &str, query: &str) -> Vec<usize> {
@@ -103,7 +103,6 @@ impl Vim {
window.dispatch_keystroke(keystroke, cx);
});
}
- return;
}
pub fn handle_literal_input(
@@ -47,7 +47,6 @@ impl Vim {
}
self.stop_recording_immediately(action.boxed_clone(), cx);
self.switch_mode(Mode::HelixNormal, false, window, cx);
- return;
}
pub fn helix_normal_motion(
@@ -2375,7 +2375,7 @@ fn matching_tag(map: &DisplaySnapshot, head: DisplayPoint) -> Option<DisplayPoin
}
}
- return None;
+ None
}
fn matching(map: &DisplaySnapshot, display_point: DisplayPoint) -> DisplayPoint {
@@ -2517,7 +2517,7 @@ fn unmatched_forward(
}
display_point = new_point;
}
- return display_point;
+ display_point
}
fn unmatched_backward(
@@ -120,7 +120,6 @@ impl Vim {
});
})
});
- return;
}
fn open_path_mark(
@@ -224,7 +224,7 @@ impl Vim {
.search
.prior_selections
.last()
- .map_or(true, |range| range.start != new_head);
+ .is_none_or(|range| range.start != new_head);
if is_different_head {
count = count.saturating_sub(1)
@@ -606,11 +606,11 @@ impl MarksState {
match target? {
MarkLocation::Buffer(entity_id) => {
let anchors = self.multibuffer_marks.get(entity_id)?;
- return Some(Mark::Buffer(*entity_id, anchors.get(name)?.clone()));
+ Some(Mark::Buffer(*entity_id, anchors.get(name)?.clone()))
}
MarkLocation::Path(path) => {
let points = self.serialized_marks.get(path)?;
- return Some(Mark::Path(path.clone(), points.get(name)?.clone()));
+ Some(Mark::Path(path.clone(), points.get(name)?.clone()))
}
}
}
@@ -46,7 +46,7 @@ fn register_zed_web_search_provider(
let using_zed_provider = language_model_registry
.read(cx)
.default_model()
- .map_or(false, |default| default.is_provided_by_zed());
+ .is_some_and(|default| default.is_provided_by_zed());
if using_zed_provider {
registry.register_provider(cloud::CloudWebSearchProvider::new(client, cx), cx)
} else {
@@ -460,7 +460,7 @@ impl Dock {
};
let was_visible = this.is_open()
- && this.visible_panel().map_or(false, |active_panel| {
+ && this.visible_panel().is_some_and(|active_panel| {
active_panel.panel_id() == Entity::entity_id(&panel)
});
@@ -523,7 +523,7 @@ impl Dock {
PanelEvent::Close => {
if this
.visible_panel()
- .map_or(false, |p| p.panel_id() == Entity::entity_id(panel))
+ .is_some_and(|p| p.panel_id() == Entity::entity_id(panel))
{
this.set_open(false, window, cx);
}
@@ -489,7 +489,7 @@ where
fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
event
.downcast_ref::<T::Event>()
- .map_or(false, |event| self.read(cx).should_serialize(event))
+ .is_some_and(|event| self.read(cx).should_serialize(event))
}
}
@@ -552,9 +552,9 @@ impl Pane {
// to the item, and `focus_handle.contains_focus` returns false because the `active_item`
// is not hooked up to us in the dispatch tree.
self.focus_handle.contains_focused(window, cx)
- || self.active_item().map_or(false, |item| {
- item.item_focus_handle(cx).contains_focused(window, cx)
- })
+ || self
+ .active_item()
+ .is_some_and(|item| item.item_focus_handle(cx).contains_focused(window, cx))
}
fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1021,7 +1021,7 @@ impl Pane {
existing_item
.project_entry_ids(cx)
.first()
- .map_or(false, |existing_entry_id| {
+ .is_some_and(|existing_entry_id| {
Some(existing_entry_id) == project_entry_id.as_ref()
})
} else {
@@ -1558,7 +1558,7 @@ impl Pane {
let other_project_item_ids = open_item.project_item_model_ids(cx);
dirty_project_item_ids.retain(|id| !other_project_item_ids.contains(id));
}
- return dirty_project_item_ids.is_empty();
+ dirty_project_item_ids.is_empty()
}
pub(super) fn file_names_for_prompt(
@@ -2745,7 +2745,7 @@ impl Pane {
worktree
.read(cx)
.root_entry()
- .map_or(false, |entry| entry.is_dir())
+ .is_some_and(|entry| entry.is_dir())
});
let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
@@ -3210,8 +3210,7 @@ impl Pane {
return;
};
- if target.map_or(false, |target| this.is_tab_pinned(target))
- {
+ if target.is_some_and(|target| this.is_tab_pinned(target)) {
this.pin_tab_at(index, window, cx);
}
})
@@ -3615,7 +3614,6 @@ impl Render for Pane {
)
.on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
if cx.stop_active_drag(window) {
- return;
} else {
cx.propagate();
}
@@ -1804,7 +1804,7 @@ impl Workspace {
.max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
});
- latest_project_path_opened.map_or(true, |path| path == history_path)
+ latest_project_path_opened.is_none_or(|path| path == history_path)
})
}
@@ -2284,7 +2284,7 @@ impl Workspace {
// the current session.
if close_intent != CloseIntent::Quit
&& !save_last_workspace
- && save_result.as_ref().map_or(false, |&res| res)
+ && save_result.as_ref().is_ok_and(|&res| res)
{
this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
.await;
@@ -5133,13 +5133,11 @@ impl Workspace {
self.panes.retain(|p| p != pane);
if let Some(focus_on) = focus_on {
focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
- } else {
- if self.active_pane() == pane {
- self.panes
- .last()
- .unwrap()
- .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
- }
+ } else if self.active_pane() == pane {
+ self.panes
+ .last()
+ .unwrap()
+ .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
}
if self.last_active_center_pane == Some(pane.downgrade()) {
self.last_active_center_pane = None;
@@ -5893,7 +5891,6 @@ impl Workspace {
pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
if cx.stop_active_drag(window) {
- return;
} else if let Some((notification_id, _)) = self.notifications.pop() {
dismiss_app_notification(¬ification_id, cx);
} else {
@@ -6100,7 +6097,7 @@ fn open_items(
// here is a directory, it was already opened further above
// with a `find_or_create_worktree`.
if let Ok(task) = abs_path_task
- && task.await.map_or(true, |p| p.is_file())
+ && task.await.is_none_or(|p| p.is_file())
{
return Some((
ix,
@@ -6970,7 +6967,7 @@ async fn join_channel_internal(
&& project.visible_worktrees(cx).any(|tree| {
tree.read(cx)
.root_entry()
- .map_or(false, |entry| entry.is_dir())
+ .is_some_and(|entry| entry.is_dir())
})
{
Some(workspace.project.clone())
@@ -7900,7 +7897,6 @@ fn join_pane_into_active(
cx: &mut App,
) {
if pane == active_pane {
- return;
} else if pane.read(cx).items_len() == 0 {
pane.update(cx, |_, cx| {
cx.emit(pane::Event::Remove {
@@ -9149,11 +9145,11 @@ mod tests {
workspace.update_in(cx, |workspace, window, cx| {
workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
});
- return item;
+ item
}
fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
- return workspace.update_in(cx, |workspace, window, cx| {
+ workspace.update_in(cx, |workspace, window, cx| {
let new_pane = workspace.split_pane(
workspace.active_pane().clone(),
SplitDirection::Right,
@@ -9161,7 +9157,7 @@ mod tests {
cx,
);
new_pane
- });
+ })
}
#[gpui::test]
@@ -3393,12 +3393,10 @@ impl File {
let disk_state = if proto.is_deleted {
DiskState::Deleted
+ } else if let Some(mtime) = proto.mtime.map(&Into::into) {
+ DiskState::Present { mtime }
} else {
- if let Some(mtime) = proto.mtime.map(&Into::into) {
- DiskState::Present { mtime }
- } else {
- DiskState::New
- }
+ DiskState::New
};
Ok(Self {
@@ -4074,10 +4072,10 @@ impl BackgroundScanner {
}
}
- let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
+ let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
snapshot
.entry_for_path(parent)
- .map_or(false, |entry| entry.kind == EntryKind::Dir)
+ .is_some_and(|entry| entry.kind == EntryKind::Dir)
});
if !parent_dir_is_loaded {
log::debug!("ignoring event {relative_path:?} within unloaded directory");
@@ -4630,7 +4628,7 @@ impl BackgroundScanner {
while let Some(parent_abs_path) = ignores_to_update.next() {
while ignores_to_update
.peek()
- .map_or(false, |p| p.starts_with(&parent_abs_path))
+ .is_some_and(|p| p.starts_with(&parent_abs_path))
{
ignores_to_update.next().unwrap();
}
@@ -4797,9 +4795,7 @@ impl BackgroundScanner {
for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
let exists_in_snapshot = snapshot
.entry_for_id(work_directory_id)
- .map_or(false, |entry| {
- snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
- });
+ .is_some_and(|entry| snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some());
if exists_in_snapshot
|| matches!(
@@ -4924,10 +4920,10 @@ fn build_diff(
new_paths.next();
for path in event_paths {
let path = PathKey(path.clone());
- if old_paths.item().map_or(false, |e| e.path < path.0) {
+ if old_paths.item().is_some_and(|e| e.path < path.0) {
old_paths.seek_forward(&path, Bias::Left);
}
- if new_paths.item().map_or(false, |e| e.path < path.0) {
+ if new_paths.item().is_some_and(|e| e.path < path.0) {
new_paths.seek_forward(&path, Bias::Left);
}
loop {
@@ -4977,7 +4973,7 @@ fn build_diff(
let is_newly_loaded = phase == InitialScan
|| last_newly_loaded_dir_path
.as_ref()
- .map_or(false, |dir| new_entry.path.starts_with(dir));
+ .is_some_and(|dir| new_entry.path.starts_with(dir));
changes.push((
new_entry.path.clone(),
new_entry.id,
@@ -4995,7 +4991,7 @@ fn build_diff(
let is_newly_loaded = phase == InitialScan
|| last_newly_loaded_dir_path
.as_ref()
- .map_or(false, |dir| new_entry.path.starts_with(dir));
+ .is_some_and(|dir| new_entry.path.starts_with(dir));
changes.push((
new_entry.path.clone(),
new_entry.id,
@@ -82,7 +82,7 @@ impl Settings for WorktreeSettings {
.ancestors()
.map(|a| a.to_string_lossy().into())
})
- .filter(|p| p != "")
+ .filter(|p: &String| !p.is_empty())
.collect();
file_scan_exclusions.sort();
private_files.sort();
@@ -1625,7 +1625,7 @@ fn open_local_file(
.await
.ok()
.flatten()
- .map_or(false, |metadata| !metadata.is_dir && !metadata.is_fifo);
+ .is_some_and(|metadata| !metadata.is_dir && !metadata.is_fifo);
file_exists
};
@@ -177,7 +177,7 @@ impl ToolbarItemView for MigrationBanner {
}));
}
- return ToolbarItemLocation::Hidden;
+ ToolbarItemLocation::Hidden
}
}
@@ -175,9 +175,9 @@ impl Render for QuickActionBar {
let code_action_menu = menu_ref
.as_ref()
.filter(|menu| matches!(menu, CodeContextMenu::CodeActions(..)));
- code_action_menu.as_ref().map_or(false, |menu| {
- matches!(menu.origin(), ContextMenuOrigin::QuickActionBar)
- })
+ code_action_menu
+ .as_ref()
+ .is_some_and(|menu| matches!(menu.origin(), ContextMenuOrigin::QuickActionBar))
};
let code_action_element = if is_deployed {
editor.update(cx, |editor, cx| {
@@ -85,12 +85,10 @@ fn feature_gate_predict_edits_actions(cx: &mut App) {
CommandPaletteFilter::update_global(cx, |filter, _cx| {
if is_ai_disabled {
filter.hide_action_types(&zeta_all_action_types);
+ } else if has_feature_flag {
+ filter.show_action_types(rate_completion_action_types.iter());
} else {
- if has_feature_flag {
- filter.show_action_types(rate_completion_action_types.iter());
- } else {
- filter.hide_action_types(&rate_completion_action_types);
- }
+ filter.hide_action_types(&rate_completion_action_types);
}
});
})
@@ -46,7 +46,7 @@ impl ZedPredictModal {
user_store.clone(),
client.clone(),
copilot::Copilot::global(cx)
- .map_or(false, |copilot| copilot.read(cx).status().is_configured()),
+ .is_some_and(|copilot| copilot.read(cx).status().is_configured()),
Arc::new({
let this = weak_entity.clone();
move |_window, cx| {
@@ -607,7 +607,7 @@ impl Render for RateCompletionModal {
.children(self.zeta.read(cx).shown_completions().cloned().enumerate().map(
|(index, completion)| {
let selected =
- self.active_completion.as_ref().map_or(false, |selected| {
+ self.active_completion.as_ref().is_some_and(|selected| {
selected.completion.id == completion.id
});
let rated =
@@ -106,7 +106,7 @@ impl Dismissable for ZedPredictUpsell {
if KEY_VALUE_STORE
.read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
.log_err()
- .map_or(false, |s| s.is_some())
+ .is_some_and(|s| s.is_some())
{
return true;
}
@@ -114,7 +114,7 @@ impl Dismissable for ZedPredictUpsell {
KEY_VALUE_STORE
.read_kvp(Self::KEY)
.log_err()
- .map_or(false, |s| s.is_some())
+ .is_some_and(|s| s.is_some())
}
}
@@ -55,7 +55,7 @@ pub fn init_env_filter(filter: env_config::EnvFilter) {
}
pub fn is_possibly_enabled_level(level: log::Level) -> bool {
- return level as u8 <= LEVEL_ENABLED_MAX_CONFIG.load(Ordering::Relaxed);
+ level as u8 <= LEVEL_ENABLED_MAX_CONFIG.load(Ordering::Relaxed)
}
pub fn is_scope_enabled(scope: &Scope, module_path: Option<&str>, level: log::Level) -> bool {
@@ -70,7 +70,7 @@ pub fn is_scope_enabled(scope: &Scope, module_path: Option<&str>, level: log::Le
let is_enabled_by_default = level <= unsafe { LEVEL_ENABLED_MAX_STATIC };
let global_scope_map = SCOPE_MAP.read().unwrap_or_else(|err| {
SCOPE_MAP.clear_poison();
- return err.into_inner();
+ err.into_inner()
});
let Some(map) = global_scope_map.as_ref() else {
@@ -83,11 +83,11 @@ pub fn is_scope_enabled(scope: &Scope, module_path: Option<&str>, level: log::Le
return is_enabled_by_default;
}
let enabled_status = map.is_enabled(scope, module_path, level);
- return match enabled_status {
+ match enabled_status {
EnabledStatus::NotConfigured => is_enabled_by_default,
EnabledStatus::Enabled => true,
EnabledStatus::Disabled => false,
- };
+ }
}
pub fn refresh_from_settings(settings: &HashMap<String, String>) {
@@ -132,7 +132,7 @@ fn level_filter_from_str(level_str: &str) -> Option<log::LevelFilter> {
return None;
}
};
- return Some(level);
+ Some(level)
}
fn scope_alloc_from_scope_str(scope_str: &str) -> Option<ScopeAlloc> {
@@ -143,7 +143,7 @@ fn scope_alloc_from_scope_str(scope_str: &str) -> Option<ScopeAlloc> {
let Some(scope) = scope_iter.next() else {
break;
};
- if scope == "" {
+ if scope.is_empty() {
continue;
}
scope_buf[index] = scope;
@@ -159,7 +159,7 @@ fn scope_alloc_from_scope_str(scope_str: &str) -> Option<ScopeAlloc> {
return None;
}
let scope = scope_buf.map(|s| s.to_string());
- return Some(scope);
+ Some(scope)
}
#[derive(Debug, PartialEq, Eq)]
@@ -280,7 +280,7 @@ impl ScopeMap {
cursor += 1;
}
let sub_items_end = cursor;
- if scope_name == "" {
+ if scope_name.is_empty() {
assert_eq!(sub_items_start + 1, sub_items_end);
assert_ne!(depth, 0);
assert_ne!(parent_index, usize::MAX);
@@ -288,7 +288,7 @@ impl ScopeMap {
this.entries[parent_index].enabled = Some(items[sub_items_start].1);
continue;
}
- let is_valid_scope = scope_name != "";
+ let is_valid_scope = !scope_name.is_empty();
let is_last = depth + 1 == SCOPE_DEPTH_MAX || !is_valid_scope;
let mut enabled = None;
if is_last {
@@ -321,7 +321,7 @@ impl ScopeMap {
}
}
- return this;
+ this
}
pub fn is_empty(&self) -> bool {
@@ -358,7 +358,7 @@ impl ScopeMap {
}
break 'search;
}
- return enabled;
+ enabled
}
let mut enabled = search(self, scope);
@@ -394,7 +394,7 @@ impl ScopeMap {
}
return EnabledStatus::Disabled;
}
- return EnabledStatus::NotConfigured;
+ EnabledStatus::NotConfigured
}
}
@@ -456,7 +456,7 @@ mod tests {
let Some(scope) = scope_iter.next() else {
break;
};
- if scope == "" {
+ if scope.is_empty() {
continue;
}
scope_buf[index] = scope;
@@ -464,7 +464,7 @@ mod tests {
}
assert_ne!(index, 0);
assert!(scope_iter.next().is_none());
- return scope_buf;
+ scope_buf
}
#[test]
@@ -240,7 +240,7 @@ pub mod private {
let Some((crate_name, _)) = module_path.split_at_checked(index) else {
return module_path;
};
- return crate_name;
+ crate_name
}
pub const fn scope_new(scopes: &[&'static str]) -> Scope {
@@ -262,7 +262,7 @@ pub mod private {
}
pub fn scope_to_alloc(scope: &Scope) -> ScopeAlloc {
- return scope.map(|s| s.to_string());
+ scope.map(|s| s.to_string())
}
}
@@ -319,18 +319,18 @@ impl Drop for Timer {
impl Timer {
#[must_use = "Timer will stop when dropped, the result of this function should be saved in a variable prefixed with `_` if it should stop when dropped"]
pub fn new(logger: Logger, name: &'static str) -> Self {
- return Self {
+ Self {
logger,
name,
start_time: std::time::Instant::now(),
warn_if_longer_than: None,
done: false,
- };
+ }
}
pub fn warn_if_gt(mut self, warn_limit: std::time::Duration) -> Self {
self.warn_if_longer_than = Some(warn_limit);
- return self;
+ self
}
pub fn end(mut self) {
@@ -17,7 +17,7 @@ impl GlslExtension {
}
if let Some(path) = &self.cached_binary_path
- && fs::metadata(path).map_or(false, |stat| stat.is_file())
+ && fs::metadata(path).is_ok_and(|stat| stat.is_file())
{
return Ok(path.clone());
}
@@ -60,7 +60,7 @@ impl GlslExtension {
.map_err(|err| format!("failed to create directory '{version_dir}': {err}"))?;
let binary_path = format!("{version_dir}/bin/glsl_analyzer");
- if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
+ if !fs::metadata(&binary_path).is_ok_and(|stat| stat.is_file()) {
zed::set_language_server_installation_status(
language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
@@ -13,7 +13,7 @@ struct HtmlExtension {
impl HtmlExtension {
fn server_exists(&self) -> bool {
- fs::metadata(SERVER_PATH).map_or(false, |stat| stat.is_file())
+ fs::metadata(SERVER_PATH).is_ok_and(|stat| stat.is_file())
}
fn server_script_path(&mut self, language_server_id: &LanguageServerId) -> Result<String> {
@@ -39,7 +39,7 @@ impl RuffExtension {
}
if let Some(path) = &self.cached_binary_path
- && fs::metadata(path).map_or(false, |stat| stat.is_file())
+ && fs::metadata(path).is_ok_and(|stat| stat.is_file())
{
return Ok(RuffBinary {
path: path.clone(),
@@ -94,7 +94,7 @@ impl RuffExtension {
_ => format!("{version_dir}/{asset_stem}/ruff"),
};
- if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
+ if !fs::metadata(&binary_path).is_ok_and(|stat| stat.is_file()) {
zed::set_language_server_installation_status(
language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
@@ -18,7 +18,7 @@ impl SnippetExtension {
}
if let Some(path) = &self.cached_binary_path
- && fs::metadata(path).map_or(false, |stat| stat.is_file())
+ && fs::metadata(path).is_ok_and(|stat| stat.is_file())
{
return Ok(path.clone());
}
@@ -59,7 +59,7 @@ impl SnippetExtension {
let version_dir = format!("simple-completion-language-server-{}", release.version);
let binary_path = format!("{version_dir}/simple-completion-language-server");
- if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
+ if !fs::metadata(&binary_path).is_ok_and(|stat| stat.is_file()) {
zed::set_language_server_installation_status(
language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
@@ -19,7 +19,7 @@ impl TestExtension {
println!("{}", String::from_utf8_lossy(&echo_output.stdout));
if let Some(path) = &self.cached_binary_path
- && fs::metadata(path).map_or(false, |stat| stat.is_file())
+ && fs::metadata(path).is_ok_and(|stat| stat.is_file())
{
return Ok(path.clone());
}
@@ -61,7 +61,7 @@ impl TestExtension {
let version_dir = format!("gleam-{}", release.version);
let binary_path = format!("{version_dir}/gleam");
- if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
+ if !fs::metadata(&binary_path).is_ok_and(|stat| stat.is_file()) {
zed::set_language_server_installation_status(
language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
@@ -40,7 +40,7 @@ impl TomlExtension {
}
if let Some(path) = &self.cached_binary_path
- && fs::metadata(path).map_or(false, |stat| stat.is_file())
+ && fs::metadata(path).is_ok_and(|stat| stat.is_file())
{
return Ok(TaploBinary {
path: path.clone(),
@@ -93,7 +93,7 @@ impl TomlExtension {
}
);
- if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
+ if !fs::metadata(&binary_path).is_ok_and(|stat| stat.is_file()) {
zed::set_language_server_installation_status(
language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
@@ -21,13 +21,11 @@ pub fn run_package_conformity(_args: PackageConformityArgs) -> Result<()> {
.manifest_path
.parent()
.and_then(|parent| parent.parent())
- .map_or(false, |grandparent_dir| {
- grandparent_dir.ends_with("extensions")
- });
+ .is_some_and(|grandparent_dir| grandparent_dir.ends_with("extensions"));
let cargo_toml = read_cargo_toml(&package.manifest_path)?;
- let is_using_workspace_lints = cargo_toml.lints.map_or(false, |lints| lints.workspace);
+ let is_using_workspace_lints = cargo_toml.lints.is_some_and(|lints| lints.workspace);
if !is_using_workspace_lints {
eprintln!(
"{package:?} is not using workspace lints",