Detailed changes
@@ -573,6 +573,11 @@ single_range_in_vec_init = "allow"
# There are a bunch of rules currently failing in the `style` group, so
# allow all of those, for now.
style = { level = "allow", priority = -1 }
+# We often return trait objects from `new` functions.
+new_ret_no_self = { level = "allow" }
+# We have a few `next` functions that differ in lifetimes
+# compared to Iterator::next. Yet, clippy complains about those.
+should_implement_trait = { level = "allow" }
# Individual rules that have violations in the codebase:
type_complexity = "allow"
@@ -16,7 +16,7 @@ use util::ResultExt as _;
pub use supported_countries::*;
-pub const ANTHROPIC_API_URL: &'static str = "https://api.anthropic.com";
+pub const ANTHROPIC_API_URL: &str = "https://api.anthropic.com";
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
@@ -339,14 +339,12 @@ pub async fn extract_tool_args_from_events(
while let Some(event) = events.next().await {
if let Event::ContentBlockStart {
index,
- content_block,
+ content_block: ResponseContent::ToolUse { name, .. },
} = event?
{
- if let ResponseContent::ToolUse { name, .. } = content_block {
- if name == tool_name {
- tool_use_index = Some(index);
- break;
- }
+ if name == tool_name {
+ tool_use_index = Some(index);
+ break;
}
}
}
@@ -610,9 +608,6 @@ impl ApiError {
}
pub fn is_rate_limit_error(&self) -> bool {
- match self.error_type.as_str() {
- "rate_limit_error" => true,
- _ => false,
- }
+ matches!(self.error_type.as_str(), "rate_limit_error")
}
}
@@ -44,7 +44,7 @@ impl SoundRegistry {
let bytes = self
.assets
.load(&path)?
- .map(|asset| Ok(asset))
+ .map(Ok)
.unwrap_or_else(|| Err(anyhow::anyhow!("No such asset available")))?
.into_owned();
let cursor = Cursor::new(bytes);
@@ -33,6 +33,7 @@ impl Sound {
}
}
+#[derive(Default)]
pub struct Audio {
_output_stream: Option<OutputStream>,
output_handle: Option<OutputStreamHandle>,
@@ -45,10 +46,7 @@ impl Global for GlobalAudio {}
impl Audio {
pub fn new() -> Self {
- Self {
- _output_stream: None,
- output_handle: None,
- }
+ Self::default()
}
fn ensure_output_exists(&mut self) -> Option<&OutputStreamHandle> {
@@ -95,7 +95,7 @@ struct MacOsUnmounter {
impl Drop for MacOsUnmounter {
fn drop(&mut self) {
let unmount_output = std::process::Command::new("hdiutil")
- .args(&["detach", "-force"])
+ .args(["detach", "-force"])
.arg(&self.mount_path)
.output();
@@ -211,7 +211,7 @@ pub fn check(_: &Check, cx: &mut WindowContext) {
return;
}
- if let Some(message) = env::var("ZED_UPDATE_EXPLANATION").ok() {
+ if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
drop(cx.prompt(
gpui::PromptLevel::Info,
"Zed was installed via a package manager.",
@@ -254,7 +254,7 @@ pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<(
let url = &auto_updater
.http_client
.build_url(&format!("/releases/{release_channel}/{current_version}"));
- cx.open_url(&url);
+ cx.open_url(url);
}
None
@@ -722,7 +722,7 @@ async fn install_release_linux(
}
let output = Command::new("rsync")
- .args(&["-av", "--delete"])
+ .args(["-av", "--delete"])
.arg(&from)
.arg(&to)
.output()
@@ -754,10 +754,10 @@ async fn install_release_macos(
mounted_app_path.push("/");
let output = Command::new("hdiutil")
- .args(&["attach", "-nobrowse"])
+ .args(["attach", "-nobrowse"])
.arg(&downloaded_dmg)
.arg("-mountroot")
- .arg(&temp_dir.path())
+ .arg(temp_dir.path())
.output()
.await?;
@@ -773,7 +773,7 @@ async fn install_release_macos(
};
let output = Command::new("rsync")
- .args(&["-av", "--delete"])
+ .args(["-av", "--delete"])
.arg(&mounted_app_path)
.arg(&running_app_path)
.output()
@@ -18,6 +18,12 @@ pub struct Breadcrumbs {
subscription: Option<Subscription>,
}
+impl Default for Breadcrumbs {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Breadcrumbs {
pub fn new() -> Self {
Self {
@@ -259,13 +259,13 @@ impl Room {
None
};
- match room
+ let did_join = room
.update(&mut cx, |room, cx| {
room.leave_when_empty = true;
room.call(called_user_id, initial_project_id, cx)
})?
- .await
- {
+ .await;
+ match did_join {
Ok(()) => Ok(room),
Err(error) => Err(error.context("room creation failed")),
}
@@ -493,7 +493,7 @@ impl Room {
// we leave the room and return an error.
if let Some(this) = this.upgrade() {
log::info!("reconnection failed, leaving room");
- let _ = this.update(&mut cx, |this, cx| this.leave(cx))?.await?;
+ this.update(&mut cx, |this, cx| this.leave(cx))?.await?;
}
Err(anyhow!(
"can't reconnect to room: client failed to re-establish connection"
@@ -933,7 +933,7 @@ impl Room {
let list = this
.follows_by_leader_id_project_id
.entry((leader, project_id))
- .or_insert(Vec::new());
+ .or_default();
if !list.contains(&follower) {
list.push(follower);
}
@@ -942,7 +942,7 @@ impl Room {
this.pending_room_update.take();
if this.should_leave() {
log::info!("room is empty, leaving");
- let _ = this.leave(cx).detach();
+ this.leave(cx).detach();
}
this.user_store.update(cx, |user_store, cx| {
@@ -1017,19 +1017,11 @@ impl Room {
.collect::<Vec<u64>>();
speaker_ids.sort_unstable();
for (sid, participant) in &mut self.remote_participants {
- if let Ok(_) = speaker_ids.binary_search(sid) {
- participant.speaking = true;
- } else {
- participant.speaking = false;
- }
+ participant.speaking = speaker_ids.binary_search(sid).is_ok();
}
if let Some(id) = self.client.user_id() {
if let Some(room) = &mut self.live_kit {
- if let Ok(_) = speaker_ids.binary_search(&id) {
- room.speaking = true;
- } else {
- room.speaking = false;
- }
+ room.speaking = speaker_ids.binary_search(&id).is_ok();
}
}
}
@@ -177,13 +177,10 @@ impl ChannelBuffer {
match event {
language::Event::Operation(operation) => {
if *ZED_ALWAYS_ACTIVE {
- match operation {
- language::Operation::UpdateSelections { selections, .. } => {
- if selections.is_empty() {
- return;
- }
+ if let language::Operation::UpdateSelections { selections, .. } = operation {
+ if selections.is_empty() {
+ return;
}
- _ => {}
}
}
let operation = language::proto::serialize_operation(operation);
@@ -61,9 +61,9 @@ pub enum ChannelMessageId {
Pending(usize),
}
-impl Into<Option<u64>> for ChannelMessageId {
- fn into(self) -> Option<u64> {
- match self {
+impl From<ChannelMessageId> for Option<u64> {
+ fn from(val: ChannelMessageId) -> Self {
+ match val {
ChannelMessageId::Saved(id) => Some(id),
ChannelMessageId::Pending(_) => None,
}
@@ -249,15 +249,14 @@ impl ChannelStore {
}
pub fn initialize(&mut self) {
- if !self.did_subscribe {
- if self
+ if !self.did_subscribe
+ && self
.client
.send(proto::SubscribeToChannels {})
.log_err()
.is_some()
- {
- self.did_subscribe = true;
- }
+ {
+ self.did_subscribe = true;
}
}
@@ -423,7 +422,7 @@ impl ChannelStore {
) {
self.channel_states
.entry(channel_id)
- .or_insert_with(|| Default::default())
+ .or_default()
.acknowledge_message_id(message_id);
cx.notify();
}
@@ -436,7 +435,7 @@ impl ChannelStore {
) {
self.channel_states
.entry(channel_id)
- .or_insert_with(|| Default::default())
+ .or_default()
.update_latest_message_id(message_id);
cx.notify();
}
@@ -450,7 +449,7 @@ impl ChannelStore {
) {
self.channel_states
.entry(channel_id)
- .or_insert_with(|| Default::default())
+ .or_default()
.acknowledge_notes_version(epoch, version);
cx.notify()
}
@@ -464,7 +463,7 @@ impl ChannelStore {
) {
self.channel_states
.entry(channel_id)
- .or_insert_with(|| Default::default())
+ .or_default()
.update_latest_notes_version(epoch, version);
cx.notify()
}
@@ -924,7 +923,7 @@ impl ChannelStore {
if let Some(role) = ChannelRole::from_i32(membership.role) {
this.channel_states
.entry(ChannelId(membership.channel_id))
- .or_insert_with(|| ChannelState::default())
+ .or_default()
.set_role(role)
}
}
@@ -1094,11 +1093,7 @@ impl ChannelStore {
id: ChannelId(channel.id),
visibility: channel.visibility(),
name: channel.name.into(),
- parent_path: channel
- .parent_path
- .into_iter()
- .map(|cid| ChannelId(cid))
- .collect(),
+ parent_path: channel.parent_path.into_iter().map(ChannelId).collect(),
}),
),
}
@@ -1113,14 +1108,11 @@ impl ChannelStore {
if channels_changed {
if !payload.delete_channels.is_empty() {
- let delete_channels: Vec<ChannelId> = payload
- .delete_channels
- .into_iter()
- .map(|cid| ChannelId(cid))
- .collect();
+ let delete_channels: Vec<ChannelId> =
+ payload.delete_channels.into_iter().map(ChannelId).collect();
self.channel_index.delete_channels(&delete_channels);
self.channel_participants
- .retain(|channel_id, _| !delete_channels.contains(&channel_id));
+ .retain(|channel_id, _| !delete_channels.contains(channel_id));
for channel_id in &delete_channels {
let channel_id = *channel_id;
@@ -117,7 +117,7 @@ impl Settings for ClientSettings {
fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
let mut result = sources.json_merge::<Self>()?;
if let Some(server_url) = &*ZED_SERVER_URL {
- result.server_url.clone_from(&server_url)
+ result.server_url.clone_from(server_url)
}
Ok(result)
}
@@ -1141,7 +1141,7 @@ impl Client {
request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
request_headers.insert(
"x-zed-release-channel",
- HeaderValue::from_str(&release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
+ HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
);
match url_scheme {
@@ -1344,16 +1344,14 @@ impl Client {
);
}
- let user = serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
+ serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
log::error!("Error deserializing: {:?}", err);
log::error!(
"GitHub API response text: {:?}",
String::from_utf8_lossy(body.as_slice())
);
anyhow!("error deserializing GitHub user")
- })?;
-
- user
+ })?
};
let query_params = [
@@ -1408,7 +1406,7 @@ impl Client {
pub async fn sign_out(self: &Arc<Self>, cx: &AsyncAppContext) {
self.state.write().credentials = None;
- self.disconnect(&cx);
+ self.disconnect(cx);
if self.has_credentials(cx).await {
self.credentials_provider
@@ -35,12 +35,8 @@ pub(crate) async fn connect_socks_proxy_stream(
}
fn parse_socks_proxy(proxy: Option<&Uri>) -> Option<((String, u16), SocksVersion)> {
- let Some(proxy_uri) = proxy else {
- return None;
- };
- let Some(scheme) = proxy_uri.scheme_str() else {
- return None;
- };
+ let proxy_uri = proxy?;
+ let scheme = proxy_uri.scheme_str()?;
let socks_version = if scheme.starts_with("socks4") {
// socks4
SocksVersion::V4
@@ -670,6 +670,24 @@ impl Telemetry {
}
}
+pub fn calculate_json_checksum(json: &impl AsRef<[u8]>) -> Option<String> {
+ let Some(checksum_seed) = &*ZED_CLIENT_CHECKSUM_SEED else {
+ return None;
+ };
+
+ let mut summer = Sha256::new();
+ summer.update(checksum_seed);
+ summer.update(json);
+ summer.update(checksum_seed);
+ let mut checksum = String::new();
+ for byte in summer.finalize().as_slice() {
+ use std::fmt::Write;
+ write!(&mut checksum, "{:02x}", byte).unwrap();
+ }
+
+ Some(checksum)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -828,21 +846,3 @@ mod tests {
&& telemetry.state.lock().first_event_date_time.is_none()
}
}
-
-pub fn calculate_json_checksum(json: &impl AsRef<[u8]>) -> Option<String> {
- let Some(checksum_seed) = &*ZED_CLIENT_CHECKSUM_SEED else {
- return None;
- };
-
- let mut summer = Sha256::new();
- summer.update(checksum_seed);
- summer.update(&json);
- summer.update(checksum_seed);
- let mut checksum = String::new();
- for byte in summer.finalize().as_slice() {
- use std::fmt::Write;
- write!(&mut checksum, "{:02x}", byte).unwrap();
- }
-
- Some(checksum)
-}
@@ -200,7 +200,7 @@ impl UserStore {
cx.update(|cx| {
if let Some(info) = info {
let disable_staff = std::env::var("ZED_DISABLE_STAFF")
- .map_or(false, |v| v != "" && v != "0");
+ .map_or(false, |v| !v.is_empty() && v != "0");
let staff = info.staff && !disable_staff;
cx.update_flags(staff, info.flags);
client.telemetry.set_authenticated_user_info(
@@ -137,7 +137,7 @@ async fn get_authenticated_user(
)
.await?;
let metrics_id = app.db.get_user_metrics_id(user.id).await?;
- return Ok(Json(AuthenticatedUserResponse { user, metrics_id }));
+ Ok(Json(AuthenticatedUserResponse { user, metrics_id }))
}
#[derive(Deserialize, Debug)]
@@ -600,7 +600,7 @@ async fn find_or_create_billing_customer(
// there's nothing more we need to do.
if let Some(billing_customer) = app
.db
- .get_billing_customer_by_stripe_customer_id(&customer_id)
+ .get_billing_customer_by_stripe_customer_id(customer_id)
.await?
{
return Ok(Some(billing_customer));
@@ -609,7 +609,7 @@ async fn find_or_create_billing_customer(
// If all we have is a customer ID, resolve it to a full customer record by
// hitting the Stripe API.
let customer = match customer_or_id {
- Expandable::Id(id) => Customer::retrieve(&stripe_client, &id, &[]).await?,
+ Expandable::Id(id) => Customer::retrieve(stripe_client, &id, &[]).await?,
Expandable::Object(customer) => *customer,
};
@@ -397,7 +397,7 @@ pub async fn post_events(
match &wrapper.event {
Event::Editor(event) => to_upload.editor_events.push(EditorEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
country_code.clone(),
@@ -410,7 +410,7 @@ pub async fn post_events(
.inline_completion_events
.push(InlineCompletionEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
country_code.clone(),
@@ -419,7 +419,7 @@ pub async fn post_events(
}
Event::Call(event) => to_upload.call_events.push(CallEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
@@ -429,7 +429,7 @@ pub async fn post_events(
.assistant_events
.push(AssistantEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
@@ -437,42 +437,42 @@ pub async fn post_events(
}
Event::Cpu(event) => to_upload.cpu_events.push(CpuEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
)),
Event::Memory(event) => to_upload.memory_events.push(MemoryEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
)),
Event::App(event) => to_upload.app_events.push(AppEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
)),
Event::Setting(event) => to_upload.setting_events.push(SettingEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
)),
Event::Edit(event) => to_upload.edit_events.push(EditEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
)),
Event::Action(event) => to_upload.action_events.push(ActionEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
@@ -486,7 +486,7 @@ pub async fn post_events(
.extension_events
.push(ExtensionEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
metadata,
first_event_at,
@@ -495,7 +495,7 @@ pub async fn post_events(
}
Event::Repl(event) => to_upload.repl_events.push(ReplEventRow::from_event(
event.clone(),
- &wrapper,
+ wrapper,
&request_body,
first_event_at,
checksum_matched,
@@ -1332,7 +1332,7 @@ pub fn calculate_json_checksum(app: Arc<AppState>, json: &impl AsRef<[u8]>) -> O
let mut summer = Sha256::new();
summer.update(checksum_seed);
- summer.update(&json);
+ summer.update(json);
summer.update(checksum_seed);
Some(summer.finalize().into_iter().collect())
}
@@ -319,14 +319,14 @@ async fn fetch_extensions_from_blob_store(
if let Some(extension) = fetch_extension_manifest(
blob_store_client,
blob_store_bucket,
- &extension_id,
- &published_version,
+ extension_id,
+ published_version,
)
.await
.log_err()
{
new_versions
- .entry(&extension_id)
+ .entry(extension_id)
.or_default()
.push(extension);
}
@@ -85,7 +85,7 @@ pub async fn validate_header<B>(mut req: Request<B>, next: Next<B>) -> impl Into
impersonator_id: None,
})
} else {
- verify_access_token(&access_token, user_id, &state.db).await
+ verify_access_token(access_token, user_id, &state.db).await
};
if let Ok(validate_result) = validate_result {
@@ -202,7 +202,7 @@ pub async fn verify_access_token(
.unwrap()
});
- let token: AccessTokenJson = serde_json::from_str(&token)?;
+ let token: AccessTokenJson = serde_json::from_str(token)?;
let db_token = db.get_access_token(token.id).await?;
let token_user_id = db_token.impersonated_user_id.unwrap_or(db_token.user_id);
@@ -249,7 +249,7 @@ pub async fn verify_dev_server_token(
db: &Arc<Database>,
) -> anyhow::Result<dev_server::Model> {
let (id, token) = split_dev_server_token(dev_server_token)?;
- let token_hash = hash_access_token(&token);
+ let token_hash = hash_access_token(token);
let server = db.get_dev_server(id).await?;
if server
@@ -301,18 +301,16 @@ mod test {
.await
.unwrap();
- let token = create_access_token(&db, user.user_id, None).await.unwrap();
+ let token = create_access_token(db, user.user_id, None).await.unwrap();
assert!(matches!(
- verify_access_token(&token, user.user_id, &db)
- .await
- .unwrap(),
+ verify_access_token(&token, user.user_id, db).await.unwrap(),
VerifyAccessTokenResult {
is_valid: true,
impersonator_id: None,
}
));
- let old_token = create_previous_access_token(user.user_id, None, &db)
+ let old_token = create_previous_access_token(user.user_id, None, db)
.await
.unwrap();
@@ -333,7 +331,7 @@ mod test {
assert!(hash.starts_with("$scrypt$"));
assert!(matches!(
- verify_access_token(&old_token, user.user_id, &db)
+ verify_access_token(&old_token, user.user_id, db)
.await
.unwrap(),
VerifyAccessTokenResult {
@@ -355,7 +353,7 @@ mod test {
assert!(hash.starts_with("$sha256$"));
assert!(matches!(
- verify_access_token(&old_token, user.user_id, &db)
+ verify_access_token(&old_token, user.user_id, db)
.await
.unwrap(),
VerifyAccessTokenResult {
@@ -365,9 +363,7 @@ mod test {
));
assert!(matches!(
- verify_access_token(&token, user.user_id, &db)
- .await
- .unwrap(),
+ verify_access_token(&token, user.user_id, db).await.unwrap(),
VerifyAccessTokenResult {
is_valid: true,
impersonator_id: None,
@@ -139,14 +139,12 @@ impl Database {
let (tx, result) = self.with_weak_transaction(&f).await?;
match result {
Ok(result) => match tx.commit().await.map_err(Into::into) {
- Ok(()) => return Ok(result),
- Err(error) => {
- return Err(error);
- }
+ Ok(()) => Ok(result),
+ Err(error) => Err(error),
},
Err(error) => {
tx.rollback().await?;
- return Err(error);
+ Err(error)
}
}
};
@@ -217,7 +215,7 @@ impl Database {
F: Send + Fn(TransactionHandle) -> Fut,
Fut: Send + Future<Output = Result<T>>,
{
- let room_id = Database::room_id_for_project(&self, project_id).await?;
+ let room_id = Database::room_id_for_project(self, project_id).await?;
let body = async {
let mut i = 0;
loop {
@@ -218,9 +218,9 @@ impl From<proto::ChannelRole> for ChannelRole {
}
}
-impl Into<proto::ChannelRole> for ChannelRole {
- fn into(self) -> proto::ChannelRole {
- match self {
+impl From<ChannelRole> for proto::ChannelRole {
+ fn from(val: ChannelRole) -> Self {
+ match val {
ChannelRole::Admin => proto::ChannelRole::Admin,
ChannelRole::Member => proto::ChannelRole::Member,
ChannelRole::Talker => proto::ChannelRole::Talker,
@@ -230,9 +230,9 @@ impl Into<proto::ChannelRole> for ChannelRole {
}
}
-impl Into<i32> for ChannelRole {
- fn into(self) -> i32 {
- let proto: proto::ChannelRole = self.into();
+impl From<ChannelRole> for i32 {
+ fn from(val: ChannelRole) -> Self {
+ let proto: proto::ChannelRole = val.into();
proto.into()
}
}
@@ -259,18 +259,18 @@ impl From<proto::ChannelVisibility> for ChannelVisibility {
}
}
-impl Into<proto::ChannelVisibility> for ChannelVisibility {
- fn into(self) -> proto::ChannelVisibility {
- match self {
+impl From<ChannelVisibility> for proto::ChannelVisibility {
+ fn from(val: ChannelVisibility) -> Self {
+ match val {
ChannelVisibility::Public => proto::ChannelVisibility::Public,
ChannelVisibility::Members => proto::ChannelVisibility::Members,
}
}
}
-impl Into<i32> for ChannelVisibility {
- fn into(self) -> i32 {
- let proto: proto::ChannelVisibility = self.into();
+impl From<ChannelVisibility> for i32 {
+ fn from(val: ChannelVisibility) -> Self {
+ let proto: proto::ChannelVisibility = val.into();
proto.into()
}
}
@@ -391,7 +391,7 @@ impl Database {
drop(rows);
if collaborators.is_empty() {
- self.snapshot_channel_buffer(channel_id, &tx).await?;
+ self.snapshot_channel_buffer(channel_id, tx).await?;
}
Ok(LeftChannelBuffer {
@@ -188,17 +188,16 @@ impl Database {
.anyhow())?;
}
}
- } else if visibility == ChannelVisibility::Members {
- if self
+ } else if visibility == ChannelVisibility::Members
+ && self
.get_channel_descendants_excluding_self([&channel], &tx)
.await?
.into_iter()
.any(|channel| channel.visibility == ChannelVisibility::Public)
- {
- Err(ErrorCode::BadPublicNesting
- .with_tag("direction", "children")
- .anyhow())?;
- }
+ {
+ Err(ErrorCode::BadPublicNesting
+ .with_tag("direction", "children")
+ .anyhow())?;
}
let mut model = channel.into_active_model();
@@ -308,7 +307,7 @@ impl Database {
fn sanitize_channel_name(name: &str) -> Result<&str> {
let new_name = name.trim().trim_start_matches('#');
- if new_name == "" {
+ if new_name.is_empty() {
Err(anyhow!("channel name can't be blank"))?;
}
Ok(new_name)
@@ -985,7 +984,7 @@ impl Database {
.all(&*tx)
.await?
.into_iter()
- .map(|c| Channel::from_model(c))
+ .map(Channel::from_model)
.collect::<Vec<_>>();
Ok((root_id, channels))
@@ -86,14 +86,13 @@ impl Database {
avoid_duplicates: bool,
tx: &DatabaseTransaction,
) -> Result<Option<(UserId, proto::Notification)>> {
- if avoid_duplicates {
- if self
+ if avoid_duplicates
+ && self
.find_notification(recipient_id, ¬ification, tx)
.await?
.is_some()
- {
- return Ok(None);
- }
+ {
+ return Ok(None);
}
let proto = notification.to_proto();
@@ -459,7 +459,7 @@ impl Database {
.await?;
}
- let (channel, room) = self.get_channel_room(room_id, &tx).await?;
+ let (channel, room) = self.get_channel_room(room_id, tx).await?;
let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
Ok(JoinRoom {
room,
@@ -766,13 +766,13 @@ impl Database {
})
.collect::<Vec<_>>();
- return Ok(Some(RejoinedProject {
+ Ok(Some(RejoinedProject {
id: project_id,
old_connection_id,
collaborators,
worktrees,
language_servers,
- }));
+ }))
}
pub async fn leave_room(
@@ -1108,15 +1108,14 @@ impl Database {
.count(tx)
.await?
> 0;
- if requires_zed_cla {
- if contributor::Entity::find()
+ if requires_zed_cla
+ && contributor::Entity::find()
.filter(contributor::Column::UserId.eq(user_id))
.one(tx)
.await?
.is_none()
- {
- Err(anyhow!("user has not signed the Zed CLA"))?;
- }
+ {
+ Err(anyhow!("user has not signed the Zed CLA"))?;
}
}
Ok(())
@@ -48,7 +48,7 @@ impl Model {
id: self.id.to_proto(),
project_id: project.map(|p| p.id.to_proto()),
dev_server_id: self.dev_server_id.to_proto(),
- path: self.paths().get(0).cloned().unwrap_or_default(),
+ path: self.paths().first().cloned().unwrap_or_default(),
paths: self.paths().clone(),
}
}
@@ -22,19 +22,17 @@ async fn test_already_processed_stripe_event(db: &Arc<Database>) {
.await
.unwrap();
- assert_eq!(
+ assert!(
db.already_processed_stripe_event(&processed_event_id)
.await
.unwrap(),
- true,
"Expected {processed_event_id} to already be processed"
);
- assert_eq!(
- db.already_processed_stripe_event(&unprocessed_event_id)
+ assert!(
+ !db.already_processed_stripe_event(&unprocessed_event_id)
.await
.unwrap(),
- false,
"Expected {unprocessed_event_id} to be unprocessed"
);
}
@@ -304,10 +304,7 @@ impl AppState {
db: db.clone(),
live_kit_client,
blob_store_client: build_blob_store_client(&config).await.log_err(),
- stripe_client: build_stripe_client(&config)
- .await
- .map(|client| Arc::new(client))
- .log_err(),
+ stripe_client: build_stripe_client(&config).await.map(Arc::new).log_err(),
rate_limiter: Arc::new(RateLimiter::new(db)),
executor,
clickhouse_client: config
@@ -141,7 +141,7 @@ async fn validate_api_token<B>(mut req: Request<B>, next: Next<B>) -> impl IntoR
})?;
let state = req.extensions().get::<Arc<LlmState>>().unwrap();
- match LlmTokenClaims::validate(&token, &state.config) {
+ match LlmTokenClaims::validate(token, &state.config) {
Ok(claims) => {
if state.db.is_access_token_revoked(&claims.jti).await? {
return Err(Error::http(
@@ -154,7 +154,7 @@ async fn validate_api_token<B>(mut req: Request<B>, next: Next<B>) -> impl IntoR
.record("user_id", claims.user_id)
.record("login", claims.github_user_login.clone())
.record("authn.jti", &claims.jti)
- .record("is_staff", &claims.is_staff);
+ .record("is_staff", claims.is_staff);
req.extensions_mut().insert(claims);
Ok::<_, Error>(next.run(req).await.into_response())
@@ -247,7 +247,7 @@ async fn perform_completion(
};
let mut request: anthropic::Request =
- serde_json::from_str(¶ms.provider_request.get())?;
+ serde_json::from_str(params.provider_request.get())?;
// Override the model on the request with the latest version of the model that is
// known to the server.
@@ -348,7 +348,7 @@ async fn perform_completion(
&state.http_client,
open_ai::OPEN_AI_API_URL,
api_key,
- serde_json::from_str(¶ms.provider_request.get())?,
+ serde_json::from_str(params.provider_request.get())?,
None,
)
.await?;
@@ -379,7 +379,7 @@ async fn perform_completion(
&state.http_client,
google_ai::API_URL,
api_key,
- serde_json::from_str(¶ms.provider_request.get())?,
+ serde_json::from_str(params.provider_request.get())?,
None,
)
.await?;
@@ -412,9 +412,9 @@ async fn perform_completion(
.context("no Qwen2-7B URL configured on the server")?;
let chunks = open_ai::stream_completion(
&state.http_client,
- &api_url,
+ api_url,
api_key,
- serde_json::from_str(¶ms.provider_request.get())?,
+ serde_json::from_str(params.provider_request.get())?,
None,
)
.await?;
@@ -26,19 +26,16 @@ fn authorize_access_to_model(
return Ok(());
}
- match provider {
- LanguageModelProvider::Anthropic => {
- if model == "claude-3-5-sonnet" {
- return Ok(());
- }
+ if provider == LanguageModelProvider::Anthropic {
+ if model == "claude-3-5-sonnet" {
+ return Ok(());
+ }
- if claims.has_llm_closed_beta_feature_flag
- && Some(model) == config.llm_closed_beta_model_name.as_deref()
- {
- return Ok(());
- }
+ if claims.has_llm_closed_beta_feature_flag
+ && Some(model) == config.llm_closed_beta_model_name.as_deref()
+ {
+ return Ok(());
}
- _ => {}
}
Err(Error::http(
@@ -110,14 +110,12 @@ impl LlmDatabase {
let (tx, result) = self.with_transaction(&f).await?;
match result {
Ok(result) => match tx.commit().await.map_err(Into::into) {
- Ok(()) => return Ok(result),
- Err(error) => {
- return Err(error);
- }
+ Ok(()) => Ok(result),
+ Err(error) => Err(error),
},
Err(error) => {
tx.rollback().await?;
- return Err(error);
+ Err(error)
}
}
};
@@ -82,7 +82,7 @@ impl LlmDatabase {
pub async fn insert_models(&mut self, models: &[ModelParams]) -> Result<()> {
let all_provider_ids = &self.provider_ids;
self.transaction(|tx| async move {
- model::Entity::insert_many(models.into_iter().map(|model_params| {
+ model::Entity::insert_many(models.iter().map(|model_params| {
let provider_id = all_provider_ids[&model_params.provider];
model::ActiveModel {
provider_id: ActiveValue::set(provider_id),
@@ -257,7 +257,7 @@ async fn setup_app_database(config: &Config) -> Result<()> {
db.initialize_notification_kinds().await?;
if config.seed_path.is_some() {
- collab::seed::seed(&config, &db, false).await?;
+ collab::seed::seed(config, &db, false).await?;
}
Ok(())
@@ -100,7 +100,7 @@ impl RateLimiter {
pub async fn save(&self) -> Result<()> {
let mut buckets = Vec::new();
self.dirty_buckets.retain(|key| {
- if let Some(bucket) = self.buckets.get(&key) {
+ if let Some(bucket) = self.buckets.get(key) {
buckets.push(crate::db::rate_buckets::Model {
user_id: key.0,
rate_limit_name: key.1.clone(),
@@ -115,16 +115,16 @@ impl Principal {
fn update_span(&self, span: &tracing::Span) {
match &self {
Principal::User(user) => {
- span.record("user_id", &user.id.0);
+ span.record("user_id", user.id.0);
span.record("login", &user.github_login);
}
Principal::Impersonated { user, admin } => {
- span.record("user_id", &user.id.0);
+ span.record("user_id", user.id.0);
span.record("login", &user.github_login);
span.record("impersonator", &admin.github_login);
}
Principal::DevServer(dev_server) => {
- span.record("dev_server_id", &dev_server.id.0);
+ span.record("dev_server_id", dev_server.id.0);
}
}
}
@@ -964,14 +964,10 @@ impl Server {
}
};
- let supermaven_client = if let Some(supermaven_admin_api_key) = this.app_state.config.supermaven_admin_api_key.clone() {
- Some(Arc::new(SupermavenAdminApi::new(
+ let supermaven_client = this.app_state.config.supermaven_admin_api_key.clone().map(|supermaven_admin_api_key| Arc::new(SupermavenAdminApi::new(
supermaven_admin_api_key.to_string(),
http_client.clone(),
- )))
- } else {
- None
- };
+ )));
let session = Session {
principal: principal.clone(),
@@ -1126,7 +1122,7 @@ impl Server {
self.peer.send(connection_id, incoming_call)?;
}
- update_user_contacts(user.id, &session).await?;
+ update_user_contacts(user.id, session).await?;
}
Principal::DevServer(dev_server) => {
{
@@ -1159,7 +1155,7 @@ impl Server {
.db
.dev_server_projects_update(dev_server.user_id)
.await?;
- send_dev_server_projects_update(dev_server.user_id, status, &session).await;
+ send_dev_server_projects_update(dev_server.user_id, status, session).await;
}
}
@@ -1564,21 +1560,17 @@ async fn join_room(
let live_kit_connection_info =
if let Some(live_kit) = session.app_state.live_kit_client.as_ref() {
- if let Some(token) = live_kit
+ live_kit
.room_token(
&joined_room.room.live_kit_room,
&session.user_id().to_string(),
)
.trace_err()
- {
- Some(proto::LiveKitConnectionInfo {
+ .map(|token| proto::LiveKitConnectionInfo {
server_url: live_kit.url().into(),
token,
can_publish: true,
})
- } else {
- None
- }
} else {
None
};
@@ -1863,7 +1855,7 @@ async fn call(
initial_project_id,
)
.await?;
- room_updated(&room, &session.peer);
+ room_updated(room, &session.peer);
mem::take(incoming_call)
};
update_user_contacts(called_user_id, &session).await?;
@@ -2006,13 +1998,13 @@ async fn share_project(
&request.worktrees,
request
.dev_server_project_id
- .map(|id| DevServerProjectId::from_proto(id)),
+ .map(DevServerProjectId::from_proto),
)
.await?;
response.send(proto::ShareProjectResponse {
project_id: project_id.to_proto(),
})?;
- room_updated(&room, &session.peer);
+ room_updated(room, &session.peer);
Ok(())
}
@@ -2269,9 +2261,9 @@ async fn leave_project(request: proto::LeaveProject, session: UserSession) -> Re
"leave project"
);
- project_left(&project, &session);
+ project_left(project, &session);
if let Some(room) = room {
- room_updated(&room, &session.peer);
+ room_updated(room, &session.peer);
}
Ok(())
@@ -2753,7 +2745,7 @@ async fn shutdown_dev_server_internal(
.await
.dev_server_projects_update(dev_server.user_id)
.await?;
- send_dev_server_projects_update(dev_server.user_id, status, &session).await;
+ send_dev_server_projects_update(dev_server.user_id, status, session).await;
Ok(())
}
@@ -2795,7 +2787,7 @@ async fn update_project(
},
);
if let Some(room) = room {
- room_updated(&room, &session.peer);
+ room_updated(room, &session.peer);
}
response.send(proto::Ack {})?;
@@ -3562,7 +3554,7 @@ async fn create_channel(
) -> Result<()> {
let db = session.db().await;
- let parent_id = request.parent_id.map(|id| ChannelId::from_proto(id));
+ let parent_id = request.parent_id.map(ChannelId::from_proto);
let (channel, membership) = db
.create_channel(&request.name, parent_id, session.user_id())
.await?;
@@ -4284,10 +4276,7 @@ async fn send_channel_message(
&request.mentions,
timestamp,
nonce.clone().into(),
- match request.reply_to_message_id {
- Some(reply_to_message_id) => Some(MessageId::from_proto(reply_to_message_id)),
- None => None,
- },
+ request.reply_to_message_id.map(MessageId::from_proto),
)
.await?;
@@ -4848,9 +4837,7 @@ async fn get_notifications(
.get_notifications(
session.user_id(),
NOTIFICATION_COUNT_PER_PAGE,
- request
- .before_id
- .map(|id| db::NotificationId::from_proto(id)),
+ request.before_id.map(db::NotificationId::from_proto),
)
.await?;
response.send(proto::GetNotificationsResponse {
@@ -5104,7 +5091,7 @@ fn build_initial_contacts_update(
for contact in contacts {
match contact {
db::Contact::Accepted { user_id, busy } => {
- update.contacts.push(contact_for_user(user_id, busy, &pool));
+ update.contacts.push(contact_for_user(user_id, busy, pool));
}
db::Contact::Outgoing { user_id } => update.outgoing_requests.push(user_id.to_proto()),
db::Contact::Incoming { user_id } => {
@@ -5161,7 +5148,8 @@ fn channel_updated(
None,
pool.channel_connection_ids(channel.root_id())
.filter_map(|(channel_id, role)| {
- role.can_see_channel(channel.visibility).then(|| channel_id)
+ role.can_see_channel(channel.visibility)
+ .then_some(channel_id)
}),
|peer_id| {
peer.send(
@@ -5239,7 +5227,7 @@ async fn lost_dev_server_connection(session: &DevServerSession) -> Result<()> {
for project_id in project_ids {
// not unshare re-checks the connection ids match, so we get away with no transaction
- unshare_project_internal(project_id, session.connection_id, None, &session).await?;
+ unshare_project_internal(project_id, session.connection_id, None, session).await?;
}
let user_id = session.dev_server().user_id;
@@ -5311,7 +5299,7 @@ async fn leave_room_for_session(session: &UserSession, connection_id: Connection
}
for contact_user_id in contacts_to_update {
- update_user_contacts(contact_user_id, &session).await?;
+ update_user_contacts(contact_user_id, session).await?;
}
if let Some(live_kit) = session.app_state.live_kit_client.as_ref() {
@@ -236,7 +236,7 @@ impl ConnectionPool {
}
PrincipalId::DevServerId(dev_server_id) => {
assert_eq!(
- self.connected_dev_servers.get(&dev_server_id).unwrap(),
+ self.connected_dev_servers.get(dev_server_id).unwrap(),
connection_id
);
}
@@ -300,9 +300,9 @@ impl ChannelPool {
}
pub fn remove_user(&mut self, user_id: &UserId) {
- if let Some(channels) = self.by_user.remove(&user_id) {
+ if let Some(channels) = self.by_user.remove(user_id) {
for channel_id in channels.keys() {
- self.unsubscribe(user_id, &channel_id)
+ self.unsubscribe(user_id, channel_id)
}
}
}
@@ -85,7 +85,7 @@ async fn test_core_channel_buffers(
// Client B sees that client A is gone from the channel buffer.
channel_buffer_b.read_with(cx_b, |buffer, _| {
- assert_collaborators(&buffer.collaborators(), &[client_b.user_id()]);
+ assert_collaborators(buffer.collaborators(), &[client_b.user_id()]);
});
// Client A rejoins the channel buffer
@@ -99,7 +99,7 @@ async fn test_core_channel_buffers(
// Sanity test, make sure we saw A rejoining
channel_buffer_b.read_with(cx_b, |buffer, _| {
assert_collaborators(
- &buffer.collaborators(),
+ buffer.collaborators(),
&[client_a.user_id(), client_b.user_id()],
);
});
@@ -111,7 +111,7 @@ async fn test_core_channel_buffers(
// Client B observes A disconnect
channel_buffer_b.read_with(cx_b, |buffer, _| {
- assert_collaborators(&buffer.collaborators(), &[client_b.user_id()]);
+ assert_collaborators(buffer.collaborators(), &[client_b.user_id()]);
});
// TODO:
@@ -687,7 +687,7 @@ fn assert_collaborators(collaborators: &HashMap<PeerId, Collaborator>, ids: &[Op
user_ids.sort();
assert_eq!(
user_ids,
- ids.into_iter().map(|id| id.unwrap()).collect::<Vec<_>>()
+ ids.iter().map(|id| id.unwrap()).collect::<Vec<_>>()
);
}
@@ -356,7 +356,7 @@ async fn test_channel_message_changes(
let project_b = client_b.build_empty_local_project(cx_b);
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
- let chat_panel_b = workspace_b.update(cx_b, |workspace, cx| ChatPanel::new(workspace, cx));
+ let chat_panel_b = workspace_b.update(cx_b, ChatPanel::new);
chat_panel_b
.update(cx_b, |chat_panel, cx| {
chat_panel.set_active(true, cx);
@@ -96,7 +96,7 @@ async fn test_dev_server(cx: &mut gpui::TestAppContext, cx2: &mut gpui::TestAppC
let content = dev_server
.fs()
- .load(&Path::new("/remote/1.txt"))
+ .load(Path::new("/remote/1.txt"))
.await
.unwrap();
assert_eq!(content, "wow!remote\nremote\nremote\n");
@@ -599,7 +599,7 @@ async fn test_save_as_remote(cx1: &mut gpui::TestAppContext, cx2: &mut gpui::Tes
let title = remote_workspace
.update(&mut cx, |ws, cx| {
let active_item = ws.active_item(cx).unwrap();
- active_item.tab_description(0, &cx).unwrap()
+ active_item.tab_description(0, cx).unwrap()
})
.unwrap();
@@ -607,7 +607,7 @@ async fn test_save_as_remote(cx1: &mut gpui::TestAppContext, cx2: &mut gpui::Tes
let path = Path::new("/remote/2.txt");
assert_eq!(
- dev_server.fs().load(&path).await.unwrap(),
+ dev_server.fs().load(path).await.unwrap(),
"remote\nremote\nremote"
);
}
@@ -632,12 +632,12 @@ async fn test_new_file_remote(cx1: &mut gpui::TestAppContext, cx2: &mut gpui::Te
let title = remote_workspace
.update(&mut cx, |ws, cx| {
- ws.active_item(cx).unwrap().tab_description(0, &cx).unwrap()
+ ws.active_item(cx).unwrap().tab_description(0, cx).unwrap()
})
.unwrap();
assert_eq!(title, "2.txt");
let path = Path::new("/remote/2.txt");
- assert_eq!(dev_server.fs().load(&path).await.unwrap(), "new!");
+ assert_eq!(dev_server.fs().load(path).await.unwrap(), "new!");
}
@@ -2109,7 +2109,7 @@ struct Row10;"#};
editor_cx_a.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
@@ -2146,7 +2146,7 @@ struct Row10;"#};
editor_cx_b.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(1)..=DisplayRow(2), DisplayRow(8)..=DisplayRow(8)],
@@ -2194,7 +2194,7 @@ struct Row10;"#};
editor_cx_a.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
@@ -2209,7 +2209,7 @@ struct Row10;"#};
editor_cx_b.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(5)..=DisplayRow(5)]
@@ -506,7 +506,7 @@ async fn test_basic_following(
// Client B activates an item that doesn't implement following,
// so the previously-opened screen-sharing item gets activated.
- let unfollowable_item = cx_b.new_view(|cx| TestItem::new(cx));
+ let unfollowable_item = cx_b.new_view(TestItem::new);
workspace_b.update(cx_b, |workspace, cx| {
workspace.active_pane().update(cx, |pane, cx| {
pane.add_item(Box::new(unfollowable_item), true, true, None, cx)
@@ -538,10 +538,7 @@ async fn test_joining_channels_and_calling_multiple_users_simultaneously(
// Leave the room
active_call_a
- .update(cx_a, |call, cx| {
- let hang_up = call.hang_up(cx);
- hang_up
- })
+ .update(cx_a, |call, cx| call.hang_up(cx))
.await
.unwrap();
@@ -574,10 +571,7 @@ async fn test_joining_channels_and_calling_multiple_users_simultaneously(
// Leave the room
active_call_a
- .update(cx_a, |call, cx| {
- let hang_up = call.hang_up(cx);
- hang_up
- })
+ .update(cx_a, |call, cx| call.hang_up(cx))
.await
.unwrap();
@@ -2578,7 +2572,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(1..2, "", "two\n")],
);
@@ -2602,7 +2596,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(1..2, "", "two\n")],
);
@@ -2626,7 +2620,7 @@ async fn test_git_diff_base_change(
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(2..3, "", "three\n")],
);
@@ -2641,7 +2635,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(2..3, "", "three\n")],
);
@@ -2684,7 +2678,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(1..2, "", "two\n")],
);
@@ -2708,7 +2702,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(1..2, "", "two\n")],
);
@@ -2741,7 +2735,7 @@ async fn test_git_diff_base_change(
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(2..3, "", "three\n")],
);
@@ -2756,7 +2750,7 @@ async fn test_git_diff_base_change(
);
git::diff::assert_hunks(
buffer.snapshot().git_diff_hunks_in_row_range(0..4),
- &buffer,
+ buffer,
&diff_base,
&[(2..3, "", "three\n")],
);
@@ -2884,8 +2878,8 @@ async fn test_git_status_sync(
client_a.fs().set_status_for_repo_via_git_operation(
Path::new("/dir/.git"),
&[
- (&Path::new(A_TXT), GitFileStatus::Added),
- (&Path::new(B_TXT), GitFileStatus::Added),
+ (Path::new(A_TXT), GitFileStatus::Added),
+ (Path::new(B_TXT), GitFileStatus::Added),
],
);
@@ -2932,8 +2926,8 @@ async fn test_git_status_sync(
client_a.fs().set_status_for_repo_via_working_copy_change(
Path::new("/dir/.git"),
&[
- (&Path::new(A_TXT), GitFileStatus::Modified),
- (&Path::new(B_TXT), GitFileStatus::Modified),
+ (Path::new(A_TXT), GitFileStatus::Modified),
+ (Path::new(B_TXT), GitFileStatus::Modified),
],
);
@@ -6336,7 +6330,7 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
// Close permanent tab
pane.update(cx, |pane, cx| {
- let id = pane.items().nth(0).unwrap().item_id();
+ let id = pane.items().next().unwrap().item_id();
pane.close_item_by_id(id, workspace::SaveIntent::Skip, cx)
})
.await
@@ -6347,7 +6341,7 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
assert_eq!(get_path(pane, 0, cx), path_1.clone());
assert_eq!(
pane.preview_item_id(),
- Some(pane.items().nth(0).unwrap().item_id())
+ Some(pane.items().next().unwrap().item_id())
);
assert!(pane.can_navigate_backward());
@@ -6366,7 +6360,7 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
assert_eq!(get_path(pane, 0, cx), path_1.clone());
assert_eq!(
pane.preview_item_id(),
- Some(pane.items().nth(0).unwrap().item_id())
+ Some(pane.items().next().unwrap().item_id())
);
assert!(pane.can_navigate_backward());
@@ -6395,7 +6389,7 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
assert_eq!(get_path(pane, 0, cx), path_1.clone());
assert_eq!(
pane.preview_item_id(),
- Some(pane.items().nth(0).unwrap().item_id())
+ Some(pane.items().next().unwrap().item_id())
);
assert!(pane.can_navigate_backward());
@@ -6433,7 +6427,7 @@ async fn test_preview_tabs(cx: &mut TestAppContext) {
assert_eq!(get_path(pane, 0, cx), path_2.clone());
assert_eq!(
pane.preview_item_id(),
- Some(pane.items().nth(0).unwrap().item_id())
+ Some(pane.items().next().unwrap().item_id())
);
assert!(pane.can_navigate_backward());
@@ -282,7 +282,7 @@ impl RandomizedTest for ProjectCollaborationTest {
let mut paths = client.fs().paths(false);
paths.remove(0);
let new_root_path = if paths.is_empty() || rng.gen() {
- Path::new("/").join(&plan.next_root_dir_name())
+ Path::new("/").join(plan.next_root_dir_name())
} else {
paths.choose(rng).unwrap().clone()
};
@@ -263,8 +263,7 @@ impl TestServer {
})
});
- let git_hosting_provider_registry =
- cx.update(|cx| GitHostingProviderRegistry::default_global(cx));
+ let git_hosting_provider_registry = cx.update(GitHostingProviderRegistry::default_global);
git_hosting_provider_registry
.register_hosting_provider(Arc::new(git_hosting_providers::Github));
@@ -227,7 +227,7 @@ impl ChannelView {
{
self.editor.update(cx, |editor, cx| {
editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
- s.replace_cursors_with(|map| vec![item.range.start.to_display_point(&map)])
+ s.replace_cursors_with(|map| vec![item.range.start.to_display_point(map)])
})
});
return;
@@ -460,8 +460,7 @@ impl Item for ChannelView {
}
fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
- self.editor
- .update(cx, |editor, cx| Item::deactivated(editor, cx))
+ self.editor.update(cx, Item::deactivated)
}
fn set_nav_history(&mut self, history: ItemNavHistory, cx: &mut ViewContext<Self>) {
@@ -560,7 +560,7 @@ impl ChatPanel {
},
)
.child(
- self.render_popover_buttons(&cx, message_id, can_delete_message, can_edit_message)
+ self.render_popover_buttons(cx, message_id, can_delete_message, can_edit_message)
.mt_neg_2p5(),
)
}
@@ -705,7 +705,7 @@ impl ChatPanel {
menu.entry(
"Copy message text",
None,
- cx.handler_for(&this, move |this, cx| {
+ cx.handler_for(this, move |this, cx| {
if let Some(message) = this.active_chat().and_then(|active_chat| {
active_chat.read(cx).find_loaded_message(message_id)
}) {
@@ -718,7 +718,7 @@ impl ChatPanel {
menu.entry(
"Delete message",
None,
- cx.handler_for(&this, move |this, cx| this.remove_message(message_id, cx)),
+ cx.handler_for(this, move |this, cx| this.remove_message(message_id, cx)),
)
})
})
@@ -802,13 +802,11 @@ impl ChatPanel {
{
task.detach();
}
- } else {
- if let Some(task) = chat
- .update(cx, |chat, cx| chat.send_message(message, cx))
- .log_err()
- {
- task.detach();
- }
+ } else if let Some(task) = chat
+ .update(cx, |chat, cx| chat.send_message(message, cx))
+ .log_err()
+ {
+ task.detach();
}
}
}
@@ -854,7 +852,7 @@ impl ChatPanel {
let scroll_to_message_id = this.update(&mut cx, |this, cx| {
this.set_active_chat(chat.clone(), cx);
- scroll_to_message_id.or_else(|| this.last_acknowledged_message_id)
+ scroll_to_message_id.or(this.last_acknowledged_message_id)
})?;
if let Some(message_id) = scroll_to_message_id {
@@ -293,8 +293,8 @@ impl MessageEditor {
completion_fn: impl Fn(&StringMatch) -> (String, CodeLabel),
) -> Vec<Completion> {
let matches = fuzzy::match_strings(
- &candidates,
- &query,
+ candidates,
+ query,
true,
10,
&Default::default(),
@@ -219,7 +219,7 @@ impl CollabPanel {
})
.detach();
- let channel_name_editor = cx.new_view(|cx| Editor::single_line(cx));
+ let channel_name_editor = cx.new_view(Editor::single_line);
cx.subscribe(&channel_name_editor, |this: &mut Self, _, event, cx| {
if let editor::EditorEvent::Blurred = event {
@@ -328,7 +328,7 @@ impl CollabPanel {
panel.width = serialized_panel.width.map(|w| w.round());
panel.collapsed_channels = serialized_panel
.collapsed_channels
- .unwrap_or_else(|| Vec::new())
+ .unwrap_or_else(Vec::new)
.iter()
.map(|cid| ChannelId(*cid))
.collect();
@@ -955,7 +955,7 @@ impl CollabPanel {
}
fn take_editing_state(&mut self, cx: &mut ViewContext<Self>) -> bool {
- if let Some(_) = self.channel_editing_state.take() {
+ if self.channel_editing_state.take().is_some() {
self.channel_name_editor.update(cx, |editor, cx| {
editor.set_text("", cx);
});
@@ -1850,8 +1850,7 @@ impl CollabPanel {
if let Some(contact) = self.selected_contact() {
self.deploy_contact_context_menu(bounds.center(), contact, cx);
cx.stop_propagation();
- return;
- };
+ }
}
fn selected_channel(&self) -> Option<&Arc<Channel>> {
@@ -2142,7 +2141,7 @@ impl CollabPanel {
} => self
.render_participant_project(
*project_id,
- &worktree_root_names,
+ worktree_root_names,
*host_user_id,
*is_last,
is_selected,
@@ -2401,7 +2400,7 @@ impl CollabPanel {
) -> impl IntoElement {
let github_login = SharedString::from(user.github_login.clone());
let user_id = user.id;
- let is_response_pending = self.user_store.read(cx).is_contact_request_pending(&user);
+ let is_response_pending = self.user_store.read(cx).is_contact_request_pending(user);
let color = if is_response_pending {
Color::Muted
} else {
@@ -2457,7 +2456,7 @@ impl CollabPanel {
let response_is_pending = self
.channel_store
.read(cx)
- .has_pending_channel_invite_response(&channel);
+ .has_pending_channel_invite_response(channel);
let color = if response_is_pending {
Color::Muted
} else {
@@ -2832,7 +2831,7 @@ impl Panel for CollabPanel {
fn icon(&self, cx: &gpui::WindowContext) -> Option<ui::IconName> {
CollaborationPanelSettings::get_global(cx)
.button
- .then(|| ui::IconName::Collab)
+ .then_some(ui::IconName::Collab)
}
fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
@@ -309,7 +309,7 @@ impl PickerDelegate for ChannelModalDelegate {
let members = search_members.await?;
picker.update(&mut cx, |picker, cx| {
picker.delegate.has_all_members =
- query == "" && members.len() < 100;
+ query.is_empty() && members.len() < 100;
picker.delegate.matching_member_indices =
(0..members.len()).collect();
picker.delegate.members = members;
@@ -154,7 +154,7 @@ impl PickerDelegate for ContactFinderDelegate {
.selected(selected)
.start_slot(Avatar::new(user.avatar_uri.clone()))
.child(Label::new(user.github_login.clone()))
- .end_slot::<Icon>(icon_path.map(|icon_path| Icon::from_path(icon_path))),
+ .end_slot::<Icon>(icon_path.map(Icon::from_path)),
)
}
}
@@ -31,7 +31,7 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
chat_panel::init(cx);
collab_panel::init(cx);
notification_panel::init(cx);
- notifications::init(&app_state, cx);
+ notifications::init(app_state, cx);
title_bar::init(cx);
vcs_menu::init(cx);
}
@@ -92,7 +92,7 @@ impl NotificationPanel {
cx.new_view(|cx: &mut ViewContext<Self>| {
let mut status = client.status();
cx.spawn(|this, mut cx| async move {
- while let Some(_) = status.next().await {
+ while (status.next().await).is_some() {
if this
.update(&mut cx, |_, cx| {
cx.notify();
@@ -52,7 +52,7 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
room::Event::RemoteProjectUnshared { project_id }
| room::Event::RemoteProjectJoined { project_id }
| room::Event::RemoteProjectInvitationDiscarded { project_id } => {
- if let Some(windows) = notification_windows.remove(&project_id) {
+ if let Some(windows) = notification_windows.remove(project_id) {
for window in windows {
window
.update(cx, |_, cx| {
@@ -1,4 +1,3 @@
-use anyhow;
use gpui::Pixels;
use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
@@ -273,7 +273,7 @@ impl PickerDelegate for CommandPaletteDelegate {
let mut commands = self.all_commands.clone();
let hit_counts = cx.global::<HitCounts>().clone();
let executor = cx.background_executor().clone();
- let query = trim_consecutive_whitespaces(&query.as_str());
+ let query = trim_consecutive_whitespaces(query.as_str());
async move {
commands.sort_by_key(|action| {
(
@@ -303,7 +303,7 @@ impl PickerDelegate for CommandPaletteDelegate {
})
.collect()
} else {
- let ret = fuzzy::match_strings(
+ fuzzy::match_strings(
&candidates,
&query,
true,
@@ -311,8 +311,7 @@ impl PickerDelegate for CommandPaletteDelegate {
&Default::default(),
executor,
)
- .await;
- ret
+ .await
};
tx.send((commands, matches)).await.log_err();
@@ -118,9 +118,7 @@ impl CommandPaletteInterceptor {
/// Intercepts the given query from the command palette.
pub fn intercept(&self, query: &str, cx: &AppContext) -> Option<CommandInterceptResult> {
- let Some(handler) = self.0.as_ref() else {
- return None;
- };
+ let handler = self.0.as_ref()?;
(handler)(query, cx)
}
@@ -235,13 +235,13 @@ impl Client {
let content = buffer.trim();
if !content.is_empty() {
- if let Ok(response) = serde_json::from_str::<AnyResponse>(&content) {
+ if let Ok(response) = serde_json::from_str::<AnyResponse>(content) {
if let Some(handlers) = response_handlers.lock().as_mut() {
if let Some(handler) = handlers.remove(&response.id) {
handler(Ok(content.to_string()));
}
}
- } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(&content) {
+ } else if let Ok(notification) = serde_json::from_str::<AnyNotification>(content) {
let mut notification_handlers = notification_handlers.lock();
if let Some(handler) =
notification_handlers.get_mut(notification.method.as_str())
@@ -1,5 +1,4 @@
use gpui::{actions, AppContext, Context, ViewContext};
-use log;
use manager::ContextServerManager;
use workspace::Workspace;
@@ -27,7 +26,7 @@ pub fn init(cx: &mut AppContext) {
}
fn restart_servers(_workspace: &mut Workspace, _action: &Restart, cx: &mut ViewContext<Workspace>) {
- let model = ContextServerManager::global(&cx);
+ let model = ContextServerManager::global(cx);
cx.update_model(&model, |manager, cx| {
for server in manager.servers() {
manager
@@ -125,6 +125,12 @@ pub enum Event {
impl Global for ContextServerManager {}
impl EventEmitter<Event> for ContextServerManager {}
+impl Default for ContextServerManager {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ContextServerManager {
pub fn new() -> Self {
Self {
@@ -422,90 +422,86 @@ impl Copilot {
(this, fake_server)
}
- fn start_language_server(
+ async fn start_language_server(
new_server_id: LanguageServerId,
http: Arc<dyn HttpClient>,
node_runtime: Arc<dyn NodeRuntime>,
this: WeakModel<Self>,
mut cx: AsyncAppContext,
- ) -> impl Future<Output = ()> {
- async move {
- let start_language_server = async {
- let server_path = get_copilot_lsp(http).await?;
- let node_path = node_runtime.binary_path().await?;
- let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
- let binary = LanguageServerBinary {
- path: node_path,
- arguments,
- // TODO: We could set HTTP_PROXY etc here and fix the copilot issue.
- env: None,
- };
-
- let root_path = if cfg!(target_os = "windows") {
- Path::new("C:/")
- } else {
- Path::new("/")
- };
-
- let server = LanguageServer::new(
- Arc::new(Mutex::new(None)),
- new_server_id,
- binary,
- root_path,
- None,
- cx.clone(),
- )?;
+ ) {
+ let start_language_server = async {
+ let server_path = get_copilot_lsp(http).await?;
+ let node_path = node_runtime.binary_path().await?;
+ let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
+ let binary = LanguageServerBinary {
+ path: node_path,
+ arguments,
+ // TODO: We could set HTTP_PROXY etc here and fix the copilot issue.
+ env: None,
+ };
- server
- .on_notification::<StatusNotification, _>(
- |_, _| { /* Silence the notification */ },
- )
- .detach();
- let server = cx.update(|cx| server.initialize(None, cx))?.await?;
+ let root_path = if cfg!(target_os = "windows") {
+ Path::new("C:/")
+ } else {
+ Path::new("/")
+ };
- let status = server
- .request::<request::CheckStatus>(request::CheckStatusParams {
- local_checks_only: false,
- })
- .await?;
+ let server = LanguageServer::new(
+ Arc::new(Mutex::new(None)),
+ new_server_id,
+ binary,
+ root_path,
+ None,
+ cx.clone(),
+ )?;
- server
- .request::<request::SetEditorInfo>(request::SetEditorInfoParams {
- editor_info: request::EditorInfo {
- name: "zed".into(),
- version: env!("CARGO_PKG_VERSION").into(),
- },
- editor_plugin_info: request::EditorPluginInfo {
- name: "zed-copilot".into(),
- version: "0.0.1".into(),
- },
- })
- .await?;
+ server
+ .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
+ .detach();
+ let server = cx.update(|cx| server.initialize(None, cx))?.await?;
- anyhow::Ok((server, status))
- };
+ let status = server
+ .request::<request::CheckStatus>(request::CheckStatusParams {
+ local_checks_only: false,
+ })
+ .await?;
- let server = start_language_server.await;
- this.update(&mut cx, |this, cx| {
- cx.notify();
- match server {
- Ok((server, status)) => {
- this.server = CopilotServer::Running(RunningCopilotServer {
- lsp: server,
- sign_in_status: SignInStatus::SignedOut,
- registered_buffers: Default::default(),
- });
- cx.emit(Event::CopilotLanguageServerStarted);
- this.update_sign_in_status(status, cx);
- }
- Err(error) => {
- this.server = CopilotServer::Error(error.to_string().into());
- cx.notify()
- }
+ server
+ .request::<request::SetEditorInfo>(request::SetEditorInfoParams {
+ editor_info: request::EditorInfo {
+ name: "zed".into(),
+ version: env!("CARGO_PKG_VERSION").into(),
+ },
+ editor_plugin_info: request::EditorPluginInfo {
+ name: "zed-copilot".into(),
+ version: "0.0.1".into(),
+ },
+ })
+ .await?;
+
+ anyhow::Ok((server, status))
+ };
+
+ let server = start_language_server.await;
+ this.update(&mut cx, |this, cx| {
+ cx.notify();
+ match server {
+ Ok((server, status)) => {
+ this.server = CopilotServer::Running(RunningCopilotServer {
+ lsp: server,
+ sign_in_status: SignInStatus::SignedOut,
+ registered_buffers: Default::default(),
+ });
+ cx.emit(Event::CopilotLanguageServerStarted);
+ this.update_sign_in_status(status, cx);
}
- })
- .ok();
- }
+ Err(error) => {
+ this.server = CopilotServer::Error(error.to_string().into());
+ cx.notify()
+ }
+ }
+ })
+ .ok();
}
pub fn sign_in(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
@@ -1005,7 +1001,7 @@ async fn get_copilot_lsp(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
let url = &release
.assets
- .get(0)
+ .first()
.context("Github release for copilot contained no assets")?
.browser_download_url;
@@ -15,9 +15,8 @@ use settings::watch_config_file;
use strum::EnumIter;
use ui::Context;
-pub const COPILOT_CHAT_COMPLETION_URL: &'static str =
- "https://api.githubcopilot.com/chat/completions";
-pub const COPILOT_CHAT_AUTH_URL: &'static str = "https://api.github.com/copilot_internal/v2/token";
+pub const COPILOT_CHAT_COMPLETION_URL: &str = "https://api.githubcopilot.com/chat/completions";
+pub const COPILOT_CHAT_AUTH_URL: &str = "https://api.github.com/copilot_internal/v2/token";
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
@@ -145,7 +145,7 @@ impl InlineCompletionProvider for CopilotCompletionProvider {
};
}
Direction::Next => {
- if self.completions.len() == 0 {
+ if self.completions.is_empty() {
self.active_completion_index = 0
} else {
self.active_completion_index =
@@ -221,15 +221,13 @@ impl InlineCompletionProvider for CopilotCompletionProvider {
})
.detach_and_log_err(cx);
- if should_report_inline_completion_event {
- if self.active_completion().is_some() {
- if let Some(telemetry) = self.telemetry.as_ref() {
- telemetry.report_inline_completion_event(
- Self::name().to_string(),
- false,
- self.file_extension.clone(),
- );
- }
+ if should_report_inline_completion_event && self.active_completion().is_some() {
+ if let Some(telemetry) = self.telemetry.as_ref() {
+ telemetry.report_inline_completion_event(
+ Self::name().to_string(),
+ false,
+ self.file_extension.clone(),
+ );
}
}
}
@@ -1148,7 +1146,7 @@ mod tests {
}
fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
- _ = cx.update(|cx| {
+ cx.update(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
theme::init(theme::LoadThemes::JustBase, cx);
@@ -167,7 +167,7 @@ impl Render for CopilotCodeVerification {
let prompt = match &self.status {
Status::SigningIn {
prompt: Some(prompt),
- } => Self::render_prompting_modal(self.connect_clicked, &prompt, cx).into_any_element(),
+ } => Self::render_prompting_modal(self.connect_clicked, prompt, cx).into_any_element(),
Status::Unauthorized => {
self.connect_clicked = false;
Self::render_unauthorized_modal(cx).into_any_element()
@@ -18,7 +18,7 @@ use sqlez::thread_safe_connection::ThreadSafeConnection;
use sqlez_macros::sql;
use std::env;
use std::future::Future;
-use std::path::{Path, PathBuf};
+use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::LazyLock;
use util::{maybe, ResultExt};
@@ -79,7 +79,7 @@ pub async fn open_db<M: Migrator + 'static>(
open_fallback_db().await
}
-async fn open_main_db<M: Migrator>(db_path: &PathBuf) -> Option<ThreadSafeConnection<M>> {
+async fn open_main_db<M: Migrator>(db_path: &Path) -> Option<ThreadSafeConnection<M>> {
log::info!("Opening main db");
ThreadSafeConnection::<M>::builder(db_path.to_string_lossy().as_ref(), true)
.with_db_initialization_query(DB_INITIALIZE_QUERY)
@@ -28,7 +28,7 @@ impl From<proto::DevServerProject> for DevServerProject {
fn from(project: proto::DevServerProject) -> Self {
Self {
id: DevServerProjectId(project.id),
- project_id: project.project_id.map(|id| ProjectId(id)),
+ project_id: project.project_id.map(ProjectId),
paths: project.paths.into_iter().map(|path| path.into()).collect(),
dev_server_id: DevServerId(project.dev_server_id),
}
@@ -432,7 +432,7 @@ impl ProjectDiagnosticsEditor {
.unwrap();
prev_excerpt_id = excerpt_id;
- first_excerpt_id.get_or_insert_with(|| prev_excerpt_id);
+ first_excerpt_id.get_or_insert(prev_excerpt_id);
group_state.excerpts.push(excerpt_id);
let header_position = (excerpt_id, language::Anchor::MIN);
@@ -491,7 +491,7 @@ impl ProjectDiagnosticsEditor {
blocks_to_remove.extend(group_state.blocks.iter().copied());
} else if let Some((_, group_state)) = to_keep {
prev_excerpt_id = *group_state.excerpts.last().unwrap();
- first_excerpt_id.get_or_insert_with(|| prev_excerpt_id);
+ first_excerpt_id.get_or_insert(prev_excerpt_id);
path_state.diagnostic_groups.push(group_state);
}
}
@@ -776,7 +776,7 @@ impl Item for ProjectDiagnosticsEditor {
}
}
-const DIAGNOSTIC_HEADER: &'static str = "diagnostic header";
+const DIAGNOSTIC_HEADER: &str = "diagnostic header";
fn diagnostic_header_renderer(diagnostic: Diagnostic) -> RenderBlock {
let (message, code_ranges) = highlight_diagnostic_message(&diagnostic, None);
@@ -773,9 +773,7 @@ async fn test_random_diagnostics(cx: &mut TestAppContext, mut rng: StdRng) {
(
path.clone(),
server_id,
- current_diagnostics
- .entry((path, server_id))
- .or_insert(vec![]),
+ current_diagnostics.entry((path, server_id)).or_default(),
)
}
};
@@ -853,8 +851,8 @@ fn get_diagnostics_excerpts(
result.push(ExcerptInfo {
path: buffer.file().unwrap().path().to_path_buf(),
range: ExcerptRange {
- context: range.context.to_point(&buffer),
- primary: range.primary.map(|range| range.to_point(&buffer)),
+ context: range.context.to_point(buffer),
+ primary: range.primary.map(|range| range.to_point(buffer)),
},
group_id: usize::MAX,
primary: false,
@@ -962,9 +960,9 @@ fn random_diagnostic(
}
}
-const FILE_HEADER: &'static str = "file header";
-const EXCERPT_HEADER: &'static str = "excerpt header";
-const EXCERPT_FOOTER: &'static str = "excerpt footer";
+const FILE_HEADER: &str = "file header";
+const EXCERPT_HEADER: &str = "excerpt header";
+const EXCERPT_FOOTER: &str = "excerpt footer";
fn editor_blocks(
editor: &View<Editor>,
@@ -18,7 +18,7 @@ impl Render for ToolbarControls {
let editor = editor.read(cx);
include_warnings = editor.include_warnings;
has_stale_excerpts = !editor.paths_to_update.is_empty();
- is_updating = editor.update_paths_tx.len() > 0
+ is_updating = !editor.update_paths_tx.is_empty()
|| editor
.project
.read(cx)
@@ -84,6 +84,12 @@ impl ToolbarItemView for ToolbarControls {
}
}
+impl Default for ToolbarControls {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ToolbarControls {
pub fn new() -> Self {
ToolbarControls { editor: None }
@@ -28,7 +28,7 @@ pub fn switch_source_header(
};
let Some((_, _, server_to_query, buffer)) =
- find_specific_language_server_in_selection(&editor, cx, &is_c_language, CLANGD_SERVER_NAME)
+ find_specific_language_server_in_selection(editor, cx, is_c_language, CLANGD_SERVER_NAME)
else {
return;
};
@@ -85,7 +85,7 @@ pub fn switch_source_header(
pub fn apply_related_actions(editor: &View<Editor>, cx: &mut WindowContext) {
if editor.update(cx, |e, cx| {
- find_specific_language_server_in_selection(e, cx, &is_c_language, CLANGD_SERVER_NAME)
+ find_specific_language_server_in_selection(e, cx, is_c_language, CLANGD_SERVER_NAME)
.is_some()
}) {
register_action(editor, cx, switch_source_header);
@@ -12,7 +12,7 @@
//! - [`WrapMap`] that handles soft wrapping.
//! - [`BlockMap`] that tracks custom blocks such as diagnostics that should be displayed within buffer.
//! - [`DisplayMap`] that adds background highlights to the regions of text.
-//! Each one of those builds on top of preceding map.
+//! Each one of those builds on top of preceding map.
//!
//! [Editor]: crate::Editor
//! [EditorElement]: crate::element::EditorElement
@@ -588,7 +588,7 @@ impl DisplaySnapshot {
pub fn display_point_to_anchor(&self, point: DisplayPoint, bias: Bias) -> Anchor {
self.buffer_snapshot
- .anchor_at(point.to_offset(&self, bias), bias)
+ .anchor_at(point.to_offset(self, bias), bias)
}
fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
@@ -735,7 +735,7 @@ impl DisplaySnapshot {
let mut line = String::new();
let range = display_row..display_row.next_row();
- for chunk in self.highlighted_chunks(range, false, &editor_style) {
+ for chunk in self.highlighted_chunks(range, false, editor_style) {
line.push_str(chunk.text);
let text_style = if let Some(style) = chunk.style {
@@ -1286,7 +1286,7 @@ pub mod tests {
height,
disposition,
render: Box::new(|_| div().into_any()),
- priority: priority,
+ priority,
}
})
.collect::<Vec<_>>();
@@ -60,9 +60,9 @@ pub struct BlockSnapshot {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CustomBlockId(usize);
-impl Into<ElementId> for CustomBlockId {
- fn into(self) -> ElementId {
- ElementId::Integer(self.0)
+impl From<CustomBlockId> for ElementId {
+ fn from(val: CustomBlockId) -> Self {
+ ElementId::Integer(val.0)
}
}
@@ -657,7 +657,7 @@ impl BlockMap {
.flatten()
}
- pub(crate) fn sort_blocks<B: BlockLike>(blocks: &mut Vec<(u32, B)>) {
+ pub(crate) fn sort_blocks<B: BlockLike>(blocks: &mut [(u32, B)]) {
// Place excerpt headers and footers above custom blocks on the same row
blocks.sort_unstable_by(|(row_a, block_a), (row_b, block_b)| {
row_a.cmp(row_b).then_with(|| {
@@ -1478,7 +1478,7 @@ mod tests {
#[gpui::test]
fn test_basic_blocks(cx: &mut gpui::TestAppContext) {
- cx.update(|cx| init_test(cx));
+ cx.update(init_test);
let text = "aaa\nbbb\nccc\nddd";
@@ -1734,7 +1734,7 @@ mod tests {
#[gpui::test]
fn test_replace_with_heights(cx: &mut gpui::TestAppContext) {
- let _update = cx.update(|cx| init_test(cx));
+ cx.update(init_test);
let text = "aaa\nbbb\nccc\nddd";
@@ -1838,7 +1838,7 @@ mod tests {
#[cfg(target_os = "macos")]
#[gpui::test]
fn test_blocks_on_wrapped_lines(cx: &mut gpui::TestAppContext) {
- cx.update(|cx| init_test(cx));
+ cx.update(init_test);
let _font_id = cx.text_system().font_id(&font("Helvetica")).unwrap();
@@ -1885,7 +1885,7 @@ mod tests {
#[gpui::test(iterations = 100)]
fn test_random_blocks(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
- cx.update(|cx| init_test(cx));
+ cx.update(init_test);
let operations = env::var("OPERATIONS")
.map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
@@ -46,7 +46,7 @@ impl CreaseSnapshot {
Ordering::Greater => break,
}
}
- return None;
+ None
}
pub fn crease_items_with_offsets(
@@ -183,7 +183,7 @@ impl CreaseMap {
}
}
removals.sort_unstable_by(|(a_id, a_range), (b_id, b_range)| {
- AnchorRangeExt::cmp(a_range, b_range, snapshot).then(b_id.cmp(&a_id))
+ AnchorRangeExt::cmp(a_range, b_range, snapshot).then(b_id.cmp(a_id))
});
self.snapshot.creases = {
@@ -122,7 +122,7 @@ impl<'a> FoldMapWriter<'a> {
let snapshot = self.0.snapshot.inlay_snapshot.clone();
for (range, fold_text) in ranges.into_iter() {
let buffer = &snapshot.buffer;
- let range = range.start.to_offset(&buffer)..range.end.to_offset(&buffer);
+ let range = range.start.to_offset(buffer)..range.end.to_offset(buffer);
// Ignore any empty ranges.
if range.start == range.end {
@@ -420,7 +420,7 @@ impl FoldMap {
}
if fold_range.end > fold_range.start {
- const ELLIPSIS: &'static str = "⋯";
+ const ELLIPSIS: &str = "⋯";
let fold_id = fold.id;
new_transforms.push(
@@ -850,7 +850,8 @@ fn consolidate_inlay_edits(mut edits: Vec<InlayEdit>) -> Vec<InlayEdit> {
let _old_alloc_ptr = edits.as_ptr();
let mut inlay_edits = edits.into_iter();
- let inlay_edits = if let Some(mut first_edit) = inlay_edits.next() {
+
+ if let Some(mut first_edit) = inlay_edits.next() {
// This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
#[allow(clippy::filter_map_identity)]
let mut v: Vec<_> = inlay_edits
@@ -872,9 +873,7 @@ fn consolidate_inlay_edits(mut edits: Vec<InlayEdit>) -> Vec<InlayEdit> {
v
} else {
vec![]
- };
-
- inlay_edits
+ }
}
fn consolidate_fold_edits(mut edits: Vec<FoldEdit>) -> Vec<FoldEdit> {
@@ -886,7 +885,8 @@ fn consolidate_fold_edits(mut edits: Vec<FoldEdit>) -> Vec<FoldEdit> {
});
let _old_alloc_ptr = edits.as_ptr();
let mut fold_edits = edits.into_iter();
- let fold_edits = if let Some(mut first_edit) = fold_edits.next() {
+
+ if let Some(mut first_edit) = fold_edits.next() {
// This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
#[allow(clippy::filter_map_identity)]
let mut v: Vec<_> = fold_edits
@@ -907,9 +907,7 @@ fn consolidate_fold_edits(mut edits: Vec<FoldEdit>) -> Vec<FoldEdit> {
v
} else {
vec![]
- };
-
- fold_edits
+ }
}
#[derive(Clone, Debug, Default)]
@@ -956,9 +954,9 @@ impl sum_tree::Summary for TransformSummary {
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
pub struct FoldId(usize);
-impl Into<ElementId> for FoldId {
- fn into(self) -> ElementId {
- ElementId::Integer(self.0)
+impl From<FoldId> for ElementId {
+ fn from(val: FoldId) -> Self {
+ ElementId::Integer(val.0)
}
}
@@ -324,7 +324,7 @@ impl<'a> Iterator for InlayChunks<'a> {
} else {
next_inlay_highlight_endpoint = range.end - offset_in_inlay.0;
highlight_style
- .get_or_insert_with(|| Default::default())
+ .get_or_insert_with(Default::default)
.highlight(*style);
}
} else {
@@ -451,15 +451,14 @@ impl InlayMap {
) -> (InlaySnapshot, Vec<InlayEdit>) {
let snapshot = &mut self.snapshot;
- if buffer_edits.is_empty() {
- if snapshot.buffer.trailing_excerpt_update_count()
+ if buffer_edits.is_empty()
+ && snapshot.buffer.trailing_excerpt_update_count()
!= buffer_snapshot.trailing_excerpt_update_count()
- {
- buffer_edits.push(Edit {
- old: snapshot.buffer.len()..snapshot.buffer.len(),
- new: buffer_snapshot.len()..buffer_snapshot.len(),
- });
- }
+ {
+ buffer_edits.push(Edit {
+ old: snapshot.buffer.len()..snapshot.buffer.len(),
+ new: buffer_snapshot.len()..buffer_snapshot.len(),
+ });
}
if buffer_edits.is_empty() {
@@ -654,7 +654,7 @@ mod tests {
fn test_marking_tabs(cx: &mut gpui::AppContext) {
let input = "\t \thello";
- let buffer = MultiBuffer::build_simple(&input, cx);
+ let buffer = MultiBuffer::build_simple(input, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
@@ -111,7 +111,7 @@ impl WrapMap {
} else {
self.edits_since_sync = self
.edits_since_sync
- .compose(&self.snapshot.interpolate(tab_snapshot, &edits));
+ .compose(self.snapshot.interpolate(tab_snapshot, &edits));
self.snapshot.interpolated = false;
}
@@ -213,7 +213,7 @@ impl WrapMap {
}
let new_rows = self.snapshot.transforms.summary().output.lines.row + 1;
self.snapshot.interpolated = false;
- self.edits_since_sync = self.edits_since_sync.compose(&Patch::new(vec![WrapEdit {
+ self.edits_since_sync = self.edits_since_sync.compose(Patch::new(vec![WrapEdit {
old: 0..old_rows,
new: 0..new_rows,
}]));
@@ -1009,7 +1009,8 @@ impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
let _old_alloc_ptr = edits.as_ptr();
let mut wrap_edits = edits.into_iter();
- let wrap_edits = if let Some(mut first_edit) = wrap_edits.next() {
+
+ if let Some(mut first_edit) = wrap_edits.next() {
// This code relies on reusing allocations from the Vec<_> - at the time of writing .flatten() prevents them.
#[allow(clippy::filter_map_identity)]
let mut v: Vec<_> = wrap_edits
@@ -1030,9 +1031,7 @@ fn consolidate_wrap_edits(edits: Vec<WrapEdit>) -> Vec<WrapEdit> {
v
} else {
vec![]
- };
-
- wrap_edits
+ }
}
#[cfg(test)]
@@ -1003,11 +1003,11 @@ impl CompletionsMenu {
cx,
);
- return cx.spawn(move |this, mut cx| async move {
+ cx.spawn(move |this, mut cx| async move {
if let Some(true) = resolve_task.await.log_err() {
this.update(&mut cx, |_, cx| cx.notify()).ok();
}
- });
+ })
}
fn attempt_resolve_selected_completion_documentation(
@@ -2350,7 +2350,7 @@ impl Editor {
if let Some(show_inline_completions) = self.show_inline_completions_override {
show_inline_completions
} else {
- self.mode == EditorMode::Full && provider.is_enabled(&buffer, buffer_position, cx)
+ self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
}
} else {
false
@@ -2729,7 +2729,7 @@ impl Editor {
if !add || click_count > 1 {
None
- } else if selected_points.len() > 0 {
+ } else if !selected_points.is_empty() {
Some(selected_points[0].id)
} else {
let clicked_point_already_selected =
@@ -2738,17 +2738,13 @@ impl Editor {
|| selection.end.to_point(buffer) == end.to_point(buffer)
});
- if let Some(selection) = clicked_point_already_selected {
- Some(selection.id)
- } else {
- None
- }
+ clicked_point_already_selected.map(|selection| selection.id)
}
};
let selections_count = self.selections.count();
- self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
+ self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
if let Some(point_to_delete) = point_to_delete {
s.delete(point_to_delete);
@@ -2981,10 +2977,10 @@ impl Editor {
return;
}
- if self.mode == EditorMode::Full {
- if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
- return;
- }
+ if self.mode == EditorMode::Full
+ && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
+ {
+ return;
}
cx.propagate();
@@ -3023,11 +3019,9 @@ impl Editor {
return true;
}
- if self.mode == EditorMode::Full {
- if self.active_diagnostics.is_some() {
- self.dismiss_diagnostics(cx);
- return true;
- }
+ if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
+ self.dismiss_diagnostics(cx);
+ return true;
}
false
@@ -3550,10 +3544,10 @@ impl Editor {
.unwrap_or_default();
let mut new_text =
String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
- new_text.push_str("\n");
+ new_text.push('\n');
new_text.extend(indent.chars());
if let Some(delimiter) = &comment_delimiter {
- new_text.push_str(&delimiter);
+ new_text.push_str(delimiter);
}
if insert_extra_newline {
new_text = new_text.repeat(2);
@@ -4187,7 +4181,7 @@ impl Editor {
};
let trigger_kind = match (&options.trigger, is_followup_invoke) {
(_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
- (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
+ (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
CompletionTriggerKind::TRIGGER_CHARACTER
}
@@ -4627,33 +4621,30 @@ impl Editor {
&& code_actions
.as_ref()
.map_or(true, |actions| actions.is_empty());
- if let Some(task) = editor
- .update(&mut cx, |editor, cx| {
- *editor.context_menu.write() =
- Some(ContextMenu::CodeActions(CodeActionsMenu {
- buffer,
- actions: CodeActionContents {
- tasks: resolved_tasks,
- actions: code_actions,
- },
- selected_item: Default::default(),
- scroll_handle: UniformListScrollHandle::default(),
- deployed_from_indicator,
- }));
- if spawn_straight_away {
- if let Some(task) = editor.confirm_code_action(
- &ConfirmCodeAction { item_ix: Some(0) },
- cx,
- ) {
- cx.notify();
- return task;
- }
+ if let Ok(task) = editor.update(&mut cx, |editor, cx| {
+ *editor.context_menu.write() =
+ Some(ContextMenu::CodeActions(CodeActionsMenu {
+ buffer,
+ actions: CodeActionContents {
+ tasks: resolved_tasks,
+ actions: code_actions,
+ },
+ selected_item: Default::default(),
+ scroll_handle: UniformListScrollHandle::default(),
+ deployed_from_indicator,
+ }));
+ if spawn_straight_away {
+ if let Some(task) = editor.confirm_code_action(
+ &ConfirmCodeAction { item_ix: Some(0) },
+ cx,
+ ) {
+ cx.notify();
+ return task;
}
- cx.notify();
- Task::ready(Ok(()))
- })
- .ok()
- {
+ }
+ cx.notify();
+ Task::ready(Ok(()))
+ }) {
task.await
} else {
Ok(())
@@ -5257,7 +5248,7 @@ impl Editor {
}
fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
- if let Some(_) = self.tasks.insert(key, value) {
+ if self.tasks.insert(key, value).is_some() {
// This case should hopefully be rare, but just in case...
log::error!("multiple different run targets found on a single line, only the last target will be rendered")
}
@@ -6060,7 +6051,7 @@ impl Editor {
Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
&multi_buffer_snapshot,
) {
- Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
+ Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
}
if !revert_changes.is_empty() {
self.transact(cx, |editor, cx| {
@@ -6634,7 +6625,7 @@ impl Editor {
head = display_map.clip_point(head, Bias::Right);
let goal = SelectionGoal::HorizontalPosition(
display_map
- .x_for_display_point(head, &text_layout_details)
+ .x_for_display_point(head, text_layout_details)
.into(),
);
selection.collapse_to(head, goal);
@@ -6967,7 +6958,7 @@ impl Editor {
selection.start,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7003,7 +6994,7 @@ impl Editor {
action.lines,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7034,7 +7025,7 @@ impl Editor {
action.lines,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7045,7 +7036,7 @@ impl Editor {
let text_layout_details = &self.text_layout_details(cx);
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
+ movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
})
})
}
@@ -7054,7 +7045,7 @@ impl Editor {
let text_layout_details = &self.text_layout_details(cx);
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
+ movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
})
})
}
@@ -7068,7 +7059,7 @@ impl Editor {
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
+ movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
})
})
}
@@ -7117,7 +7108,7 @@ impl Editor {
row_count,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7128,7 +7119,7 @@ impl Editor {
let text_layout_details = &self.text_layout_details(cx);
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::up(map, head, goal, false, &text_layout_details)
+ movement::up(map, head, goal, false, text_layout_details)
})
})
}
@@ -7156,7 +7147,7 @@ impl Editor {
selection.end,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7177,7 +7168,7 @@ impl Editor {
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
+ movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
})
})
}
@@ -7225,7 +7216,7 @@ impl Editor {
row_count,
selection.goal,
false,
- &text_layout_details,
+ text_layout_details,
);
selection.collapse_to(cursor, goal);
});
@@ -7236,7 +7227,7 @@ impl Editor {
let text_layout_details = &self.text_layout_details(cx);
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.move_heads_with(|map, head, goal| {
- movement::down(map, head, goal, false, &text_layout_details)
+ movement::down(map, head, goal, false, text_layout_details)
})
});
}
@@ -7919,12 +7910,12 @@ impl Editor {
let query_match = query_match.unwrap(); // can only fail due to I/O
let offset_range =
start_offset + query_match.start()..start_offset + query_match.end();
- let display_range = offset_range.start.to_display_point(&display_map)
- ..offset_range.end.to_display_point(&display_map);
+ let display_range = offset_range.start.to_display_point(display_map)
+ ..offset_range.end.to_display_point(display_map);
if !select_next_state.wordwise
- || (!movement::is_inside_word(&display_map, display_range.start)
- && !movement::is_inside_word(&display_map, display_range.end))
+ || (!movement::is_inside_word(display_map, display_range.start)
+ && !movement::is_inside_word(display_map, display_range.end))
{
// TODO: This is n^2, because we might check all the selections
if !selections
@@ -7988,11 +7979,11 @@ impl Editor {
if only_carets {
for selection in &mut selections {
let word_range = movement::surrounding_word(
- &display_map,
- selection.start.to_display_point(&display_map),
+ display_map,
+ selection.start.to_display_point(display_map),
);
- selection.start = word_range.start.to_offset(&display_map, Bias::Left);
- selection.end = word_range.end.to_offset(&display_map, Bias::Left);
+ selection.start = word_range.start.to_offset(display_map, Bias::Left);
+ selection.end = word_range.end.to_offset(display_map, Bias::Left);
selection.goal = SelectionGoal::None;
selection.reversed = false;
select_next_match_ranges(
@@ -8525,7 +8516,7 @@ impl Editor {
let display_point = point.to_display_point(display_snapshot);
let goal = SelectionGoal::HorizontalPosition(
display_snapshot
- .x_for_display_point(display_point, &text_layout_details)
+ .x_for_display_point(display_point, text_layout_details)
.into(),
);
(display_point, goal)
@@ -8550,8 +8541,8 @@ impl Editor {
let cursor = selection.head();
let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
for symbol in symbols.iter().rev() {
- let start = symbol.range.start.to_offset(&buffer_snap);
- let end = symbol.range.end.to_offset(&buffer_snap);
+ let start = symbol.range.start.to_offset(buffer_snap);
+ let end = symbol.range.end.to_offset(buffer_snap);
let new_range = start..end;
if start < selection.start || end > selection.end {
return Some(Selection {
@@ -8836,12 +8827,10 @@ impl Editor {
} else {
open.start
}
+ } else if inside {
+ *close.start()
} else {
- if inside {
- *close.start()
- } else {
- *close.end()
- }
+ *close.end()
},
);
}
@@ -8912,7 +8901,7 @@ impl Editor {
self.buffer.update(cx, |buffer, cx| {
buffer.expand_excerpts(
selections
- .into_iter()
+ .iter()
.map(|selection| selection.head().excerpt_id)
.dedup(),
lines,
@@ -9109,7 +9098,7 @@ impl Editor {
) -> bool {
let display_point = initial_point.to_display_point(snapshot);
let mut hunks = hunks
- .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
+ .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
.filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
.dedup();
@@ -9790,9 +9779,10 @@ impl Editor {
}
editor
});
- cx.subscribe(&rename_editor, |_, _, e, cx| match e {
- EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
- _ => {}
+ cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
+ if e == &EditorEvent::Focused {
+ cx.emit(EditorEvent::FocusedIn)
+ }
})
.detach();
@@ -10579,9 +10569,7 @@ impl Editor {
pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
let settings = self.buffer.read(cx).settings_at(0, cx);
- let mode = self
- .soft_wrap_mode_override
- .unwrap_or_else(|| settings.soft_wrap);
+ let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
match mode {
language_settings::SoftWrap::None => SoftWrap::None,
language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
@@ -11046,8 +11034,8 @@ impl Editor {
highlight
.range
.start()
- .cmp(&rows.start(), &snapshot)
- .then(highlight.range.end().cmp(&rows.end(), &snapshot))
+ .cmp(rows.start(), &snapshot)
+ .then(highlight.range.end().cmp(rows.end(), &snapshot))
});
match (color, existing_highlight_index) {
(Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
@@ -11126,7 +11114,7 @@ impl Editor {
if highlight.color.is_none() || !highlight.should_autoscroll {
return None;
}
- Some(highlight.range.start().to_display_point(&snapshot).row())
+ Some(highlight.range.start().to_display_point(snapshot).row())
})
.min()
}
@@ -11300,8 +11288,8 @@ impl Editor {
break;
}
- let start = range.start.to_display_point(&display_snapshot);
- let end = range.end.to_display_point(&display_snapshot);
+ let start = range.start.to_display_point(display_snapshot);
+ let end = range.end.to_display_point(display_snapshot);
results.push((start..end, color))
}
}
@@ -11413,8 +11401,8 @@ impl Editor {
break;
}
- let start = range.start.to_display_point(&display_snapshot);
- let end = range.end.to_display_point(&display_snapshot);
+ let start = range.start.to_display_point(display_snapshot);
+ let end = range.end.to_display_point(display_snapshot);
results.push((start..end, color))
}
}
@@ -12168,8 +12156,8 @@ fn hunks_for_selections(
let buffer_rows_for_selections = selections.iter().map(|selection| {
let head = selection.head();
let tail = selection.tail();
- let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
- let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
+ let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
+ let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
if start > end {
end..start
} else {
@@ -12349,10 +12337,7 @@ fn snippet_completions(
filter_range: 0..matching_prefix.len(),
},
server_id: LanguageServerId(usize::MAX),
- documentation: snippet
- .description
- .clone()
- .map(|description| Documentation::SingleLine(description)),
+ documentation: snippet.description.clone().map(Documentation::SingleLine),
lsp_completion: lsp::CompletionItem {
label: snippet.prefix.first().unwrap().clone(),
kind: Some(CompletionItemKind::SNIPPET),
@@ -12390,7 +12375,7 @@ impl CompletionProvider for Model<Project> {
) -> Task<Result<Vec<Completion>>> {
self.update(cx, |project, cx| {
let snippets = snippet_completions(project, buffer, buffer_position, cx);
- let project_completions = project.completions(&buffer, buffer_position, options, cx);
+ let project_completions = project.completions(buffer, buffer_position, options, cx);
cx.background_executor().spawn(async move {
let mut completions = project_completions.await?;
//let snippets = snippets.into_iter().;
@@ -12847,7 +12832,7 @@ impl ViewInputHandler for Editor {
fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
let snapshot = self.buffer.read(cx).read(cx);
- let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
+ let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
}
@@ -13276,7 +13261,7 @@ pub fn highlight_diagnostic_message(
let mut code_ranges = Vec::new();
if let Some(source) = &diagnostic.source {
- text_without_backticks.push_str(&source);
+ text_without_backticks.push_str(source);
code_ranges.push(0..source.len());
text_without_backticks.push_str(": ");
}
@@ -13415,7 +13400,7 @@ pub trait RangeToAnchorExt: Sized {
fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
- anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
+ anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
}
}
@@ -14,6 +14,12 @@ use crate::EditorSettings;
#[derive(IntoElement)]
pub struct EditorSettingsControls {}
+impl Default for EditorSettingsControls {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl EditorSettingsControls {
pub fn new() -> Self {
Self {}
@@ -235,13 +241,7 @@ impl EditableSettingControl for BufferFontLigaturesControl {
let mut features = settings
.buffer_font_features
.as_ref()
- .map(|features| {
- features
- .tag_value_list()
- .into_iter()
- .cloned()
- .collect::<Vec<_>>()
- })
+ .map(|features| features.tag_value_list().to_vec())
.unwrap_or_default();
if let Some(calt_index) = features.iter().position(|(tag, _)| tag == "calt") {
@@ -195,7 +195,7 @@ fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {
editor.change_selections(None, cx, |s| s.select_ranges([2..2]));
// Simulate an edit in another editor
- _ = buffer.update(cx, |buffer, cx| {
+ buffer.update(cx, |buffer, cx| {
buffer.start_transaction_at(now, cx);
buffer.edit([(0..1, "a")], None, cx);
buffer.edit([(1..1, "b")], None, cx);
@@ -661,7 +661,7 @@ async fn test_navigation_history(cx: &mut TestAppContext) {
let buffer = MultiBuffer::build_simple(&sample_text(300, 5, 'a'), cx);
let mut editor = build_editor(buffer.clone(), cx);
let handle = cx.view();
- editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(&handle)));
+ editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(handle)));
fn pop_history(editor: &mut Editor, cx: &mut WindowContext) -> Option<NavigationEntry> {
editor.nav_history.as_mut().unwrap().pop_backward(cx)
@@ -1088,7 +1088,7 @@ fn test_move_cursor(cx: &mut TestAppContext) {
let buffer = cx.update(|cx| MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx));
let view = cx.add_window(|cx| build_editor(buffer.clone(), cx));
- _ = buffer.update(cx, |buffer, cx| {
+ buffer.update(cx, |buffer, cx| {
buffer.edit(
vec![
(Point::new(1, 0)..Point::new(1, 0), "\t"),
@@ -1822,7 +1822,7 @@ async fn test_scroll_page_up_page_down(cx: &mut gpui::TestAppContext) {
cx.simulate_window_resize(window, size(px(1000.), 4. * line_height + px(0.5)));
cx.set_state(
- &r#"ˇone
+ r#"ˇone
two
three
four
@@ -1886,7 +1886,7 @@ async fn test_autoscroll(cx: &mut gpui::TestAppContext) {
cx.simulate_window_resize(window, size(px(1000.), 6. * line_height));
cx.set_state(
- &r#"ˇone
+ r#"ˇone
two
three
four
@@ -4650,17 +4650,8 @@ let foo = «2ˇ»;"#,
async fn test_select_previous_multibuffer(cx: &mut gpui::TestAppContext) {
init_test(cx, |_| {});
- let mut cx = EditorTestContext::new_multibuffer(
- cx,
- [
- &indoc! {
- "aaa\n«bbb\nccc\n»ddd"
- },
- &indoc! {
- "aaa\n«bbb\nccc\n»ddd"
- },
- ],
- );
+ let mut cx =
+ EditorTestContext::new_multibuffer(cx, ["aaa\n«bbb\nccc\n»ddd", "aaa\n«bbb\nccc\n»ddd"]);
cx.assert_editor_state(indoc! {"
ˇbbb
@@ -4809,7 +4800,7 @@ async fn test_select_larger_smaller_syntax_node(cx: &mut gpui::TestAppContext) {
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
editor
- .condition::<crate::EditorEvent>(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
+ .condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
editor.update(cx, |view, cx| {
@@ -5021,7 +5012,7 @@ async fn test_autoindent_selections(cx: &mut gpui::TestAppContext) {
.condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
.await;
- _ = editor.update(cx, |editor, cx| {
+ editor.update(cx, |editor, cx| {
editor.change_selections(None, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
editor.newline(&Newline, cx);
assert_eq!(editor.text(cx), "fn a(\n \n) {\n \n}\n");
@@ -5702,7 +5693,7 @@ async fn test_surround_with_pair(cx: &mut gpui::TestAppContext) {
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
- _ = view.update(cx, |view, cx| {
+ view.update(cx, |view, cx| {
view.change_selections(None, cx, |s| {
s.select_display_ranges([
DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
@@ -5852,7 +5843,7 @@ async fn test_delete_autoclose_pair(cx: &mut gpui::TestAppContext) {
.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
- _ = editor.update(cx, |editor, cx| {
+ editor.update(cx, |editor, cx| {
editor.change_selections(None, cx, |s| {
s.select_ranges([
Point::new(0, 1)..Point::new(0, 1),
@@ -6042,7 +6033,7 @@ async fn test_auto_replace_emoji_shortcode(cx: &mut gpui::TestAppContext) {
.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
- _ = editor.update(cx, |editor, cx| {
+ editor.update(cx, |editor, cx| {
editor.set_auto_replace_emoji_shortcode(true);
editor.handle_input("Hello ", cx);
@@ -6111,7 +6102,7 @@ async fn test_snippets(cx: &mut gpui::TestAppContext) {
let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
- _ = editor.update(cx, |editor, cx| {
+ editor.update(cx, |editor, cx| {
let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
editor
@@ -6738,7 +6729,7 @@ async fn test_document_format_manual_trigger(cx: &mut gpui::TestAppContext) {
let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
- _ = editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
let format = editor
.update(cx, |editor, cx| {
@@ -6766,7 +6757,7 @@ async fn test_document_format_manual_trigger(cx: &mut gpui::TestAppContext) {
"one, two\nthree\n"
);
- _ = editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
+ editor.update(cx, |editor, cx| editor.set_text("one\ntwo\nthree\n", cx));
// Ensure we don't lock if formatting hangs.
fake_server.handle_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
assert_eq!(
@@ -7765,7 +7756,7 @@ async fn test_completion(cx: &mut gpui::TestAppContext) {
handle_resolve_completion_request(&mut cx, None).await;
apply_additional_edits.await.unwrap();
- _ = cx.update(|cx| {
+ cx.update(|cx| {
cx.update_global::<SettingsStore, _>(|settings, cx| {
settings.update_user_settings::<EditorSettings>(cx, |settings| {
settings.show_completions_on_input = Some(false);
@@ -8371,7 +8362,7 @@ fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
});
let (view, cx) = cx.add_window_view(|cx| build_editor(multibuffer, cx));
- _ = view.update(cx, |view, cx| {
+ view.update(cx, |view, cx| {
assert_eq!(view.text(cx), "aaaa\nbbbb");
view.change_selections(None, cx, |s| {
s.select_ranges([
@@ -8441,7 +8432,7 @@ fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
});
let (view, cx) = cx.add_window_view(|cx| build_editor(multibuffer, cx));
- _ = view.update(cx, |view, cx| {
+ view.update(cx, |view, cx| {
let (expected_text, selection_ranges) = marked_text_ranges(
indoc! {"
aaaa
@@ -8545,7 +8536,7 @@ fn test_refresh_selections(cx: &mut TestAppContext) {
);
});
- _ = multibuffer.update(cx, |multibuffer, cx| {
+ multibuffer.update(cx, |multibuffer, cx| {
multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
});
_ = editor.update(cx, |editor, cx| {
@@ -8612,7 +8603,7 @@ fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
editor
});
- _ = multibuffer.update(cx, |multibuffer, cx| {
+ multibuffer.update(cx, |multibuffer, cx| {
multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
});
_ = editor.update(cx, |editor, cx| {
@@ -8679,7 +8670,7 @@ async fn test_extra_newline_insertion(cx: &mut gpui::TestAppContext) {
view.condition::<crate::EditorEvent>(cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
.await;
- _ = view.update(cx, |view, cx| {
+ view.update(cx, |view, cx| {
view.change_selections(None, cx, |s| {
s.select_display_ranges([
DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
@@ -8864,7 +8855,7 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
_ = follower.update(cx, |follower, cx| {
assert_eq!(follower.selections.ranges(cx), vec![1..1]);
});
- assert_eq!(*is_still_following.borrow(), true);
+ assert!(*is_still_following.borrow());
assert_eq!(*follower_edit_event_count.borrow(), 0);
// Update the scroll position only
@@ -8884,7 +8875,7 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
.unwrap(),
gpui::Point::new(1.5, 3.5)
);
- assert_eq!(*is_still_following.borrow(), true);
+ assert!(*is_still_following.borrow());
assert_eq!(*follower_edit_event_count.borrow(), 0);
// Update the selections and scroll position. The follower's scroll position is updated
@@ -8905,7 +8896,7 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
assert_eq!(follower.scroll_position(cx), gpui::Point::new(1.5, 0.0));
assert_eq!(follower.selections.ranges(cx), vec![0..0]);
});
- assert_eq!(*is_still_following.borrow(), true);
+ assert!(*is_still_following.borrow());
// Creating a pending selection that precedes another selection
_ = leader.update(cx, |leader, cx| {
@@ -8922,7 +8913,7 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
_ = follower.update(cx, |follower, cx| {
assert_eq!(follower.selections.ranges(cx), vec![0..0, 1..1]);
});
- assert_eq!(*is_still_following.borrow(), true);
+ assert!(*is_still_following.borrow());
// Extend the pending selection so that it surrounds another selection
_ = leader.update(cx, |leader, cx| {
@@ -8950,7 +8941,7 @@ async fn test_following(cx: &mut gpui::TestAppContext) {
cx,
);
});
- assert_eq!(*is_still_following.borrow(), false);
+ assert!(!(*is_still_following.borrow()));
}
#[gpui::test]
@@ -9011,7 +9002,7 @@ async fn test_following_with_multiple_excerpts(cx: &mut gpui::TestAppContext) {
});
// Insert some excerpts.
- _ = leader.update(cx, |leader, cx| {
+ leader.update(cx, |leader, cx| {
leader.buffer.update(cx, |multibuffer, cx| {
let excerpt_ids = multibuffer.push_excerpts(
buffer_1.clone(),
@@ -9086,7 +9077,7 @@ async fn test_following_with_multiple_excerpts(cx: &mut gpui::TestAppContext) {
);
// Remove some excerpts.
- _ = leader.update(cx, |leader, cx| {
+ leader.update(cx, |leader, cx| {
leader.buffer.update(cx, |multibuffer, cx| {
let excerpt_ids = multibuffer.excerpt_ids();
multibuffer.remove_excerpts([excerpt_ids[1], excerpt_ids[2]], cx);
@@ -9129,8 +9120,8 @@ async fn go_to_prev_overlapping_diagnostic(
}
"});
- _ = cx.update(|cx| {
- _ = project.update(cx, |project, cx| {
+ cx.update(|cx| {
+ project.update(cx, |project, cx| {
project
.update_diagnostics(
LanguageServerId(0),
@@ -9568,7 +9559,7 @@ async fn test_on_type_formatting_not_triggered(cx: &mut gpui::TestAppContext) {
cx.executor().run_until_parked();
- _ = buffer.update(cx, |buffer, _| {
+ buffer.update(cx, |buffer, _| {
assert_eq!(
buffer.text(),
"fn main() { let a = {5}; }",
@@ -9971,7 +9962,7 @@ async fn test_document_format_with_prettier(cx: &mut gpui::TestAppContext) {
let buffer_text = "one\ntwo\nthree\n";
let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
let (editor, cx) = cx.add_window_view(|cx| build_editor(buffer, cx));
- _ = editor.update(cx, |editor, cx| editor.set_text(buffer_text, cx));
+ editor.update(cx, |editor, cx| editor.set_text(buffer_text, cx));
editor
.update(cx, |editor, cx| {
@@ -10913,7 +10904,7 @@ async fn test_toggle_hunk_diff(executor: BackgroundExecutor, cx: &mut gpui::Test
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(1)..=DisplayRow(1), DisplayRow(7)..=DisplayRow(7), DisplayRow(9)..=DisplayRow(9)],
@@ -11058,7 +11049,7 @@ async fn test_toggled_diff_base_change(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(9)..=DisplayRow(10), DisplayRow(13)..=DisplayRow(14)],
@@ -11240,7 +11231,7 @@ async fn test_fold_unfold_diff(executor: BackgroundExecutor, cx: &mut gpui::Test
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![
@@ -11317,7 +11308,7 @@ async fn test_fold_unfold_diff(executor: BackgroundExecutor, cx: &mut gpui::Test
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(0)..=DisplayRow(0), DisplayRow(5)..=DisplayRow(5)],
@@ -11410,7 +11401,7 @@ async fn test_fold_unfold_diff(executor: BackgroundExecutor, cx: &mut gpui::Test
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![
@@ -11622,7 +11613,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut gpui::TestAppContext)
multi_buffer_editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(all_hunks, expected_all_hunks);
assert_eq!(all_expanded_hunks, Vec::new());
@@ -11636,7 +11627,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut gpui::TestAppContext)
multi_buffer_editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![
@@ -11655,7 +11646,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut gpui::TestAppContext)
multi_buffer_editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(all_hunks, expected_all_hunks);
assert_eq!(all_expanded_hunks, Vec::new());
@@ -11668,7 +11659,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut gpui::TestAppContext)
multi_buffer_editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![
@@ -11687,7 +11678,7 @@ async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut gpui::TestAppContext)
multi_buffer_editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(all_hunks, expected_all_hunks);
assert_eq!(all_expanded_hunks, Vec::new());
@@ -11775,7 +11766,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -11815,7 +11806,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -11860,7 +11851,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -11904,7 +11895,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -11952,7 +11943,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -11988,7 +11979,7 @@ async fn test_edits_around_toggled_additions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![
@@ -12103,7 +12094,7 @@ async fn test_edits_around_toggled_deletions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
@@ -12139,7 +12130,7 @@ async fn test_edits_around_toggled_deletions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
Vec::new(),
@@ -12178,7 +12169,7 @@ async fn test_edits_around_toggled_deletions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
@@ -12213,7 +12204,7 @@ async fn test_edits_around_toggled_deletions(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
all_hunks,
vec![(
@@ -12315,7 +12306,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(6)],
@@ -12358,7 +12349,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(6)],
@@ -12404,7 +12395,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(8)],
@@ -12448,7 +12439,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(9)],
@@ -12492,7 +12483,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(8)],
@@ -12533,7 +12524,7 @@ async fn test_edits_around_toggled_modifications(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
Vec::new(),
@@ -12636,7 +12627,7 @@ async fn test_multiple_expanded_hunks_merge(
cx.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
- let all_expanded_hunks = expanded_hunks(&editor, &snapshot, cx);
+ let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(6)..=DisplayRow(6)],
@@ -12689,8 +12680,8 @@ async fn setup_indent_guides_editor(
let buffer_id = cx.update_editor(|editor, cx| {
editor.set_text(text, cx);
let buffer_ids = editor.buffer().read(cx).excerpt_buffer_ids();
- let buffer_id = buffer_ids[0];
- buffer_id
+
+ buffer_ids[0]
});
(buffer_id, cx)
@@ -13249,7 +13240,7 @@ fn test_crease_insertion_and_rendering(cx: &mut TestAppContext) {
let render_args = render_args.lock().take().unwrap();
assert_eq!(render_args.row, MultiBufferRow(1));
- assert_eq!(render_args.folded, false);
+ assert!(!render_args.folded);
assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
cx.update_window(*editor, |_, cx| (render_args.callback)(true, cx))
@@ -13616,7 +13607,7 @@ pub(crate) fn update_test_language_settings(
cx: &mut TestAppContext,
f: impl Fn(&mut AllLanguageSettingsContent),
) {
- _ = cx.update(|cx| {
+ cx.update(|cx| {
SettingsStore::update_global(cx, |store, cx| {
store.update_user_settings::<AllLanguageSettings>(cx, f);
});
@@ -13627,7 +13618,7 @@ pub(crate) fn update_test_project_settings(
cx: &mut TestAppContext,
f: impl Fn(&mut ProjectSettings),
) {
- _ = cx.update(|cx| {
+ cx.update(|cx| {
SettingsStore::update_global(cx, |store, cx| {
store.update_user_settings::<ProjectSettings>(cx, f);
});
@@ -13635,7 +13626,7 @@ pub(crate) fn update_test_project_settings(
}
pub(crate) fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
- _ = cx.update(|cx| {
+ cx.update(|cx| {
assets::Assets.load_test_fonts(cx);
let store = SettingsStore::test(cx);
cx.set_global(store);
@@ -241,7 +241,7 @@ impl EditorElement {
if text.is_empty() {
return;
}
- editor.handle_input(&text, cx);
+ editor.handle_input(text, cx);
});
register_action(view, cx, |editor, _: &HalfPageUp, cx| {
editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
@@ -652,30 +652,11 @@ impl EditorElement {
cx.stop_propagation();
} else if end_selection && pending_nonempty_selections {
cx.stop_propagation();
- } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
- if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
- return;
- }
-
- #[cfg(target_os = "linux")]
- if EditorSettings::get_global(cx).middle_click_paste {
- if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
- let point_for_position =
- position_map.point_for_position(text_hitbox.bounds, event.position);
- let position = point_for_position.previous_valid;
-
- editor.select(
- SelectPhase::Begin {
- position,
- add: false,
- click_count: 1,
- },
- cx,
- );
- editor.insert(&text, cx);
- }
- cx.stop_propagation()
- }
+ } else if cfg!(target_os = "linux")
+ && event.button == MouseButton::Middle
+ && (!text_hitbox.is_hovered(cx) || editor.read_only(cx))
+ {
+ return;
}
}
@@ -1315,7 +1296,7 @@ impl EditorElement {
let hitbox = match hunk {
DisplayDiffHunk::Unfolded { .. } => {
let hunk_bounds = Self::diff_hunk_bounds(
- &snapshot,
+ snapshot,
line_height,
gutter_hitbox.bounds,
&hunk,
@@ -1610,7 +1591,7 @@ impl EditorElement {
.tasks
.as_ref()
.map(|tasks| tasks.position.to_display_point(snapshot).row())
- .or_else(|| *deployed_from_indicator)
+ .or(*deployed_from_indicator)
} else {
None
};
@@ -2794,7 +2775,7 @@ impl EditorElement {
let hover_popovers = self.editor.update(cx, |editor, cx| {
editor
.hover_state
- .render(&snapshot, visible_display_row_range.clone(), max_size, cx)
+ .render(snapshot, visible_display_row_range.clone(), max_size, cx)
});
let Some((position, hover_popovers)) = hover_popovers else {
return;
@@ -3199,7 +3180,7 @@ impl EditorElement {
&layout.position_map.snapshot,
line_height,
layout.gutter_hitbox.bounds,
- &hunk,
+ hunk,
);
Some((
hunk_bounds,
@@ -3454,7 +3435,7 @@ impl EditorElement {
let corner_radius = 0.15 * layout.position_map.line_height;
for (player_color, selections) in &layout.selections {
- for selection in selections.into_iter() {
+ for selection in selections.iter() {
self.paint_highlighted_range(
selection.range.clone(),
player_color.selection,
@@ -3772,20 +3753,18 @@ impl EditorElement {
if is_symbol_occurrences {
color.fade_out(0.5);
}
- let marker_row_ranges =
- background_ranges.into_iter().map(|range| {
- let display_start = range
- .start
- .to_display_point(&snapshot.display_snapshot);
- let display_end = range
- .end
- .to_display_point(&snapshot.display_snapshot);
- ColoredRange {
- start: display_start.row(),
- end: display_end.row(),
- color,
- }
- });
+ let marker_row_ranges = background_ranges.iter().map(|range| {
+ let display_start = range
+ .start
+ .to_display_point(&snapshot.display_snapshot);
+ let display_end =
+ range.end.to_display_point(&snapshot.display_snapshot);
+ ColoredRange {
+ start: display_start.row(),
+ end: display_end.row(),
+ color,
+ }
+ });
marker_quads.extend(
scrollbar_layout
.marker_quads_for_ranges(marker_row_ranges, Some(1)),
@@ -4608,7 +4587,7 @@ impl LineWithInvisibles {
}
self.draw_invisibles(
- &selection_ranges,
+ selection_ranges,
layout,
content_origin,
line_y,
@@ -4661,7 +4640,7 @@ impl LineWithInvisibles {
let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
match whitespace_setting {
- ShowWhitespaceSetting::None => return,
+ ShowWhitespaceSetting::None => (),
ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
let invisible_point = DisplayPoint::new(row, start as u32);
@@ -4717,7 +4696,7 @@ impl LineWithInvisibles {
last_seen = Some((should_render, end, paint));
}
}
- };
+ }
}
pub fn x_for_index(&self, index: usize) -> Pixels {
@@ -5452,7 +5431,7 @@ impl Element for EditorElement {
let show_code_actions = snapshot
.show_code_actions
- .unwrap_or_else(|| gutter_settings.code_actions);
+ .unwrap_or(gutter_settings.code_actions);
if show_code_actions {
let newest_selection_point =
newest_selection_head.to_point(&snapshot.display_snapshot);
@@ -6273,6 +6252,73 @@ fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
(delta.pow(1.2) / 300.0).into()
}
+pub fn register_action<T: Action>(
+ view: &View<Editor>,
+ cx: &mut WindowContext,
+ listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
+) {
+ let view = view.clone();
+ cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
+ let action = action.downcast_ref().unwrap();
+ if phase == DispatchPhase::Bubble {
+ view.update(cx, |editor, cx| {
+ listener(editor, action, cx);
+ })
+ }
+ })
+}
+
+fn compute_auto_height_layout(
+ editor: &mut Editor,
+ max_lines: usize,
+ max_line_number_width: Pixels,
+ known_dimensions: Size<Option<Pixels>>,
+ available_width: AvailableSpace,
+ cx: &mut ViewContext<Editor>,
+) -> Option<Size<Pixels>> {
+ let width = known_dimensions.width.or({
+ if let AvailableSpace::Definite(available_width) = available_width {
+ Some(available_width)
+ } else {
+ None
+ }
+ })?;
+ if let Some(height) = known_dimensions.height {
+ return Some(size(width, height));
+ }
+
+ let style = editor.style.as_ref().unwrap();
+ let font_id = cx.text_system().resolve_font(&style.text.font());
+ let font_size = style.text.font_size.to_pixels(cx.rem_size());
+ let line_height = style.text.line_height_in_pixels(cx.rem_size());
+ let em_width = cx
+ .text_system()
+ .typographic_bounds(font_id, font_size, 'm')
+ .unwrap()
+ .size
+ .width;
+
+ let mut snapshot = editor.snapshot(cx);
+ let gutter_dimensions =
+ snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
+
+ editor.gutter_dimensions = gutter_dimensions;
+ let text_width = width - gutter_dimensions.width;
+ let overscroll = size(em_width, px(0.));
+
+ let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
+ if editor.set_wrap_width(Some(editor_width), cx) {
+ snapshot = editor.snapshot(cx);
+ }
+
+ let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
+ let height = scroll_height
+ .max(line_height)
+ .min(line_height * max_lines as f32);
+
+ Some(size(width, height))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -6605,7 +6651,7 @@ mod tests {
});
let actual_invisibles =
- collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
+ collect_invisibles_from_new_editor(cx, EditorMode::Full, input_text, px(500.0));
assert_eq!(expected_invisibles, actual_invisibles);
}
@@ -6730,7 +6776,7 @@ mod tests {
editor_width.0
);
let window = cx.add_window(|cx| {
- let buffer = MultiBuffer::build_simple(&input_text, cx);
+ let buffer = MultiBuffer::build_simple(input_text, cx);
Editor::new(editor_mode, buffer, None, true, cx)
});
let cx = &mut VisualTestContext::from_window(*window, cx);
@@ -6754,70 +6800,3 @@ mod tests {
.collect()
}
}
-
-pub fn register_action<T: Action>(
- view: &View<Editor>,
- cx: &mut WindowContext,
- listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
-) {
- let view = view.clone();
- cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
- let action = action.downcast_ref().unwrap();
- if phase == DispatchPhase::Bubble {
- view.update(cx, |editor, cx| {
- listener(editor, action, cx);
- })
- }
- })
-}
-
-fn compute_auto_height_layout(
- editor: &mut Editor,
- max_lines: usize,
- max_line_number_width: Pixels,
- known_dimensions: Size<Option<Pixels>>,
- available_width: AvailableSpace,
- cx: &mut ViewContext<Editor>,
-) -> Option<Size<Pixels>> {
- let width = known_dimensions.width.or_else(|| {
- if let AvailableSpace::Definite(available_width) = available_width {
- Some(available_width)
- } else {
- None
- }
- })?;
- if let Some(height) = known_dimensions.height {
- return Some(size(width, height));
- }
-
- let style = editor.style.as_ref().unwrap();
- let font_id = cx.text_system().resolve_font(&style.text.font());
- let font_size = style.text.font_size.to_pixels(cx.rem_size());
- let line_height = style.text.line_height_in_pixels(cx.rem_size());
- let em_width = cx
- .text_system()
- .typographic_bounds(font_id, font_size, 'm')
- .unwrap()
- .size
- .width;
-
- let mut snapshot = editor.snapshot(cx);
- let gutter_dimensions =
- snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
-
- editor.gutter_dimensions = gutter_dimensions;
- let text_width = width - gutter_dimensions.width;
- let overscroll = size(em_width, px(0.));
-
- let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
- if editor.set_wrap_width(Some(editor_width), cx) {
- snapshot = editor.snapshot(cx);
- }
-
- let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
- let height = scroll_height
- .max(line_height)
- .min(line_height * max_lines as f32);
-
- Some(size(width, height))
-}
@@ -455,7 +455,7 @@ async fn parse_commit_messages(
.and_then(|remote_url| parse_git_remote_url(provider_registry, remote_url));
for (oid, message) in messages {
- let parsed_message = parse_markdown(&message, &languages).await;
+ let parsed_message = parse_markdown(&message, languages).await;
let permalink = if let Some((provider, git_remote)) = parsed_remote_url.as_ref() {
Some(provider.build_commit_permalink(
@@ -134,7 +134,7 @@ impl Editor {
}
None => {
update_inlay_link_and_hover_points(
- &snapshot,
+ snapshot,
point_for_position,
self,
modifiers.secondary(),
@@ -490,12 +490,12 @@ pub fn show_link_definition(
.is_some_and(|d| matches!(d, HoverLink::Url(_)));
if same_kind {
- if is_cached && (&hovered_link_state.last_trigger_point == &trigger_point)
+ if is_cached && (hovered_link_state.last_trigger_point == trigger_point)
|| hovered_link_state
.symbol_range
.as_ref()
.is_some_and(|symbol_range| {
- symbol_range.point_within_range(&trigger_point, &snapshot)
+ symbol_range.point_within_range(&trigger_point, snapshot)
})
{
editor.hovered_link_state = Some(hovered_link_state);
@@ -596,7 +596,7 @@ pub fn show_link_definition(
if let Some((symbol_range, definitions)) = result {
hovered_link_state.links = definitions;
- let underline_hovered_link = hovered_link_state.links.len() > 0
+ let underline_hovered_link = !hovered_link_state.links.is_empty()
|| hovered_link_state.symbol_range.is_some();
if underline_hovered_link {
@@ -718,7 +718,7 @@ pub(crate) async fn find_file(
let existing_path = project
.update(cx, |project, cx| {
- project.resolve_existing_file_path(&candidate_file_path, &buffer, cx)
+ project.resolve_existing_file_path(&candidate_file_path, buffer, cx)
})
.ok()?
.await?;
@@ -1258,7 +1258,7 @@ mod tests {
let variable« »= TestStruct;
}
"})
- .get(0)
+ .first()
.cloned()
.unwrap();
let midpoint = cx.update_editor(|editor, cx| {
@@ -74,7 +74,7 @@ pub fn show_keyboard_hover(editor: &mut Editor, cx: &mut ViewContext<Editor>) ->
}
}
- return false;
+ false
}
pub struct InlayHover {
@@ -648,7 +648,7 @@ impl HoverState {
}
}
}
- return hover_popover_is_focused;
+ hover_popover_is_focused
}
}
@@ -1445,7 +1445,7 @@ mod tests {
let variable« »= TestNewType(TestStruct);
}
"})
- .get(0)
+ .first()
.cloned()
.unwrap();
let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
@@ -337,8 +337,8 @@ impl Editor {
.offset_to_point(hunk.diff_base_byte_range.start)
.row;
let diff_end_row = diff_base.offset_to_point(hunk.diff_base_byte_range.end).row;
- let line_count = diff_end_row - diff_start_row;
- line_count
+
+ diff_end_row - diff_start_row
})?;
Some((diff_base_buffer, deleted_text_lines))
} else {
@@ -358,7 +358,7 @@ impl Editor {
let block = match hunk.status {
DiffHunkStatus::Removed => {
- self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, &hunk, cx)
+ self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, hunk, cx)
}
DiffHunkStatus::Added => {
self.highlight_rows::<DiffRowHighlight>(
@@ -376,7 +376,7 @@ impl Editor {
false,
cx,
);
- self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, &hunk, cx)
+ self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, hunk, cx)
}
};
self.expanded_hunks.hunks.insert(
@@ -591,7 +591,7 @@ impl Editor {
.to_display_point(&snapshot)
.row();
while let Some(buffer_hunk) = recalculated_hunks.peek() {
- match diff_hunk_to_display(&buffer_hunk, &snapshot) {
+ match diff_hunk_to_display(buffer_hunk, &snapshot) {
DisplayDiffHunk::Folded { display_row } => {
recalculated_hunks.next();
if !expanded_hunk.folded
@@ -710,12 +710,12 @@ fn to_diff_hunk(
.multi_buffer_range
.start
.buffer_id
- .or_else(|| hovered_hunk.multi_buffer_range.end.buffer_id)?;
+ .or(hovered_hunk.multi_buffer_range.end.buffer_id)?;
let buffer_range = hovered_hunk.multi_buffer_range.start.text_anchor
..hovered_hunk.multi_buffer_range.end.text_anchor;
let point_range = hovered_hunk
.multi_buffer_range
- .to_point(&multi_buffer_snapshot);
+ .to_point(multi_buffer_snapshot);
Some(DiffHunk {
associated_range: MultiBufferRow(point_range.start.row)
..MultiBufferRow(point_range.end.row),
@@ -466,7 +466,7 @@ impl InlayHintCache {
to_insert.push(Inlay::hint(
cached_hint_id.id(),
anchor,
- &cached_hint,
+ cached_hint,
));
}
}
@@ -490,7 +490,7 @@ impl InlayHintCache {
to_insert.push(Inlay::hint(
cached_hint_id.id(),
anchor,
- &maybe_missed_cached_hint,
+ maybe_missed_cached_hint,
));
}
}
@@ -844,7 +844,7 @@ fn new_update_task(
.get_mut(&query.excerpt_id)
{
let buffer_snapshot = excerpt_buffer.read(cx).snapshot();
- task_ranges.invalidate_range(&buffer_snapshot, &range);
+ task_ranges.invalidate_range(&buffer_snapshot, range);
}
})
.ok()
@@ -3424,7 +3424,7 @@ pub mod tests {
pub fn cached_hint_labels(editor: &Editor) -> Vec<String> {
let mut labels = Vec::new();
- for (_, excerpt_hints) in &editor.inlay_hint_cache().hints {
+ for excerpt_hints in editor.inlay_hint_cache().hints.values() {
let excerpt_hints = excerpt_hints.read();
for id in &excerpt_hints.ordered_hints {
labels.push(excerpt_hints.hints_by_id[id].text());
@@ -356,7 +356,7 @@ async fn update_editor_from_message(
.collect::<Vec<_>>();
removed_excerpt_ids.sort_by({
let multibuffer = multibuffer.read(cx);
- move |a, b| a.cmp(&b, &multibuffer)
+ move |a, b| a.cmp(b, &multibuffer)
});
let mut insertions = message.inserted_excerpts.into_iter().peekable();
@@ -604,7 +604,7 @@ impl Item for Editor {
.and_then(|path| FileIcons::get_icon(path.path.as_ref(), cx))
})
.flatten()
- .map(|icon| Icon::from_path(icon))
+ .map(Icon::from_path)
}
fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
@@ -631,7 +631,7 @@ impl Item for Editor {
return None;
}
- Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
+ Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
});
h_flex()
@@ -829,7 +829,7 @@ impl Item for Editor {
let cursor = self.selections.newest_anchor().head();
let multibuffer = &self.buffer().read(cx);
let (buffer_id, symbols) =
- multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
+ multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
let buffer = multibuffer.buffer(buffer_id)?;
let buffer = buffer.read(cx);
@@ -1154,7 +1154,7 @@ impl SearchableItem for Editor {
self.background_highlights
.get(&TypeId::of::<BufferSearchHighlights>())
.map_or(Vec::new(), |(_color, ranges)| {
- ranges.iter().map(|range| range.clone()).collect()
+ ranges.iter().cloned().collect()
})
}
@@ -1254,7 +1254,7 @@ impl SearchableItem for Editor {
self.unfold_ranges(matches.to_vec(), false, false, cx);
let mut ranges = Vec::new();
for m in matches {
- ranges.push(self.range_for_match(&m))
+ ranges.push(self.range_for_match(m))
}
self.change_selections(None, cx, |s| s.select_ranges(ranges));
}
@@ -1335,7 +1335,7 @@ impl SearchableItem for Editor {
.cmp(¤t_index_position, &buffer)
.is_gt()
{
- count = count - 1
+ count -= 1
}
(current_index + count) % matches.len()
@@ -1346,7 +1346,7 @@ impl SearchableItem for Editor {
.cmp(¤t_index_position, &buffer)
.is_lt()
{
- count = count - 1;
+ count -= 1;
}
if current_index >= count {
@@ -1368,7 +1368,7 @@ impl SearchableItem for Editor {
.background_highlights
.get(&TypeId::of::<SearchWithinRange>())
.map_or(vec![], |(_color, ranges)| {
- ranges.iter().map(|range| range.clone()).collect::<Vec<_>>()
+ ranges.iter().cloned().collect::<Vec<_>>()
});
cx.background_executor().spawn(async move {
@@ -1411,7 +1411,7 @@ impl SearchableItem for Editor {
if !search_range.is_empty() {
ranges.extend(
query
- .search(&search_buffer, Some(search_range.clone()))
+ .search(search_buffer, Some(search_range.clone()))
.await
.into_iter()
.map(|match_range| {
@@ -73,7 +73,7 @@ pub(super) fn refresh_linked_ranges(this: &mut Editor, cx: &mut ViewContext<Edit
let snapshot = buffer.read(cx).snapshot();
let buffer_id = buffer.read(cx).remote_id();
- let linked_edits_task = project.linked_edit(&buffer, *start, cx);
+ let linked_edits_task = project.linked_edit(buffer, *start, cx);
let highlights = move || async move {
let edits = linked_edits_task.await.log_err()?;
// Find the range containing our current selection.
@@ -87,9 +87,7 @@ pub(super) fn refresh_linked_ranges(this: &mut Editor, cx: &mut ViewContext<Edit
range.start.to_point(&snapshot) <= start_point
&& range.end.to_point(&snapshot) >= end_point
});
- if _current_selection_contains_range.is_none() {
- return None;
- }
+ _current_selection_contains_range?;
// Now link every range as each-others sibling.
let mut siblings: HashMap<Range<text::Anchor>, Vec<_>> = Default::default();
let mut insert_sorted_anchor =
@@ -23,7 +23,7 @@ where
editor
.selections
.disjoint_anchors()
- .into_iter()
+ .iter()
.filter(|selection| selection.start == selection.end)
.filter_map(|selection| Some((selection.start.buffer_id?, selection.start)))
.filter_map(|(buffer_id, trigger_anchor)| {
@@ -113,7 +113,7 @@ fn display_ranges<'a>(
.disjoint
.iter()
.chain(pending)
- .map(move |s| s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map))
+ .map(move |s| s.start.to_display_point(display_map)..s.end.to_display_point(display_map))
}
pub fn deploy_context_menu(
@@ -416,7 +416,7 @@ pub fn find_preceding_boundary_point(
mut is_boundary: impl FnMut(char, char) -> bool,
) -> Point {
let mut prev_ch = None;
- let mut offset = from.to_offset(&buffer_snapshot);
+ let mut offset = from.to_offset(buffer_snapshot);
for ch in buffer_snapshot.reversed_chars_at(offset) {
if find_range == FindRange::SingleLine && ch == '\n' {
@@ -432,7 +432,7 @@ pub fn find_preceding_boundary_point(
prev_ch = Some(ch);
}
- offset.to_point(&buffer_snapshot)
+ offset.to_point(buffer_snapshot)
}
/// Scans for a boundary preceding the given start point `from` until a boundary is found,
@@ -466,7 +466,7 @@ pub fn find_boundary_point(
mut is_boundary: impl FnMut(char, char) -> bool,
return_point_before_boundary: bool,
) -> DisplayPoint {
- let mut offset = from.to_offset(&map, Bias::Right);
+ let mut offset = from.to_offset(map, Bias::Right);
let mut prev_offset = offset;
let mut prev_ch = None;
@@ -496,7 +496,7 @@ pub fn find_boundary(
find_range: FindRange,
is_boundary: impl FnMut(char, char) -> bool,
) -> DisplayPoint {
- return find_boundary_point(map, from, find_range, is_boundary, false);
+ find_boundary_point(map, from, find_range, is_boundary, false)
}
pub fn find_boundary_exclusive(
@@ -505,7 +505,7 @@ pub fn find_boundary_exclusive(
find_range: FindRange,
is_boundary: impl FnMut(char, char) -> bool,
) -> DisplayPoint {
- return find_boundary_point(map, from, find_range, is_boundary, true);
+ find_boundary_point(map, from, find_range, is_boundary, true)
}
/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
@@ -517,7 +517,7 @@ pub fn chars_after(
) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
map.buffer_snapshot.chars_at(offset).map(move |ch| {
let before = offset;
- offset = offset + ch.len_utf8();
+ offset += ch.len_utf8();
(ch, before..offset)
})
}
@@ -533,7 +533,7 @@ pub fn chars_before(
.reversed_chars_at(offset)
.map(move |ch| {
let after = offset;
- offset = offset - ch.len_utf8();
+ offset -= ch.len_utf8();
(ch, offset..after)
})
}
@@ -220,7 +220,6 @@ impl EditorDb {
#[cfg(test)]
mod tests {
use super::*;
- use gpui;
#[gpui::test]
async fn test_save_and_get_serialized_editor() {
@@ -19,7 +19,7 @@ fn is_rust_language(language: &Language) -> bool {
pub fn apply_related_actions(editor: &View<Editor>, cx: &mut WindowContext) {
if editor
.update(cx, |e, cx| {
- find_specific_language_server_in_selection(e, cx, &is_rust_language, RUST_ANALYZER_NAME)
+ find_specific_language_server_in_selection(e, cx, is_rust_language, RUST_ANALYZER_NAME)
})
.is_some()
{
@@ -44,9 +44,9 @@ pub fn expand_macro_recursively(
let Some((trigger_anchor, rust_language, server_to_query, buffer)) =
find_specific_language_server_in_selection(
- &editor,
+ editor,
cx,
- &is_rust_language,
+ is_rust_language,
RUST_ANALYZER_NAME,
)
else {
@@ -50,7 +50,7 @@ impl ScrollAnchor {
scroll_position.y = 0.;
} else {
let scroll_top = self.anchor.to_display_point(snapshot).row().as_f32();
- scroll_position.y = scroll_top + scroll_position.y;
+ scroll_position.y += scroll_top;
}
scroll_position
}
@@ -224,7 +224,7 @@ impl ScrollManager {
};
let scroll_top_buffer_point =
- DisplayPoint::new(DisplayRow(scroll_top as u32), 0).to_point(&map);
+ DisplayPoint::new(DisplayRow(scroll_top as u32), 0).to_point(map);
let top_anchor = map
.buffer_snapshot
.anchor_at(scroll_top_buffer_point, Bias::Right);
@@ -234,7 +234,7 @@ impl ScrollManager {
anchor: top_anchor,
offset: point(
scroll_position.x.max(0.),
- scroll_top - top_anchor.to_display_point(&map).row().as_f32(),
+ scroll_top - top_anchor.to_display_point(map).row().as_f32(),
),
},
scroll_top_buffer_point.row,
@@ -339,7 +339,7 @@ impl SelectionsCollection {
let is_empty = positions.start == positions.end;
let line_len = display_map.line_len(row);
- let line = display_map.layout_row(row, &text_layout_details);
+ let line = display_map.layout_row(row, text_layout_details);
let start_col = line.closest_index_for_x(positions.start) as u32;
if start_col < line_len || (is_empty && positions.start == line.width) {
@@ -13,7 +13,7 @@ pub use popover::SignatureHelpPopover;
pub use state::SignatureHelpState;
// Language-specific settings may define quotes as "brackets", so filter them out separately.
-const QUOTE_PAIRS: [(&'static str, &'static str); 3] = [("'", "'"), ("\"", "\""), ("`", "`")];
+const QUOTE_PAIRS: [(&str, &str); 3] = [("'", "'"), ("\"", "\""), ("`", "`")];
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SignatureHelpHiddenBy {
@@ -167,10 +167,10 @@ impl Editor {
let language = editor.language_at(position, cx);
let project = editor.project.clone()?;
let (markdown, language_registry) = {
- project.update(cx, |project, mut cx| {
+ project.update(cx, |project, cx| {
let language_registry = project.languages().clone();
(
- project.signature_help(&buffer, buffer_position, &mut cx),
+ project.signature_help(&buffer, buffer_position, cx),
language_registry,
)
})
@@ -120,8 +120,7 @@ impl EditorTestContext {
where
F: FnOnce(&Editor, &ViewContext<Editor>) -> T,
{
- self.editor
- .update(&mut self.cx, |this, cx| read(&this, &cx))
+ self.editor.update(&mut self.cx, |this, cx| read(this, cx))
}
#[track_caller]
@@ -327,8 +326,8 @@ impl EditorTestContext {
.background_highlights
.get(&TypeId::of::<Tag>())
.map(|h| h.1.clone())
- .unwrap_or_else(|| Arc::default())
- .into_iter()
+ .unwrap_or_default()
+ .iter()
.map(|range| range.to_offset(&snapshot.buffer_snapshot))
.collect()
});
@@ -424,6 +423,12 @@ pub struct AssertionContextManager {
contexts: Arc<RwLock<BTreeMap<usize, String>>>,
}
+impl Default for AssertionContextManager {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl AssertionContextManager {
pub fn new() -> Self {
Self {
@@ -77,7 +77,7 @@ impl ExtensionBuilder {
extension_manifest: &mut ExtensionManifest,
options: CompileExtensionOptions,
) -> Result<()> {
- populate_defaults(extension_manifest, &extension_dir)?;
+ populate_defaults(extension_manifest, extension_dir)?;
if extension_dir.is_relative() {
bail!(
@@ -123,7 +123,7 @@ impl ExtensionBuilder {
self.install_rust_wasm_target_if_needed()?;
let adapter_bytes = self.install_wasi_preview1_adapter_if_needed().await?;
- let cargo_toml_content = fs::read_to_string(&extension_dir.join("Cargo.toml"))?;
+ let cargo_toml_content = fs::read_to_string(extension_dir.join("Cargo.toml"))?;
let cargo_toml: CargoToml = toml::from_str(&cargo_toml_content)?;
log::info!(
@@ -135,7 +135,7 @@ impl ExtensionBuilder {
.args(options.release.then_some("--release"))
.arg("--target-dir")
.arg(extension_dir.join("target"))
- .current_dir(&extension_dir)
+ .current_dir(extension_dir)
.output()
.context("failed to run `cargo`")?;
if !output.status.success() {
@@ -281,12 +281,12 @@ impl ExtensionBuilder {
);
}
} else {
- fs::create_dir_all(&directory).with_context(|| {
+ fs::create_dir_all(directory).with_context(|| {
format!("failed to create grammar directory {}", directory.display(),)
})?;
let init_output = Command::new("git")
.arg("init")
- .current_dir(&directory)
+ .current_dir(directory)
.output()?;
if !init_output.status.success() {
bail!(
@@ -312,15 +312,15 @@ impl ExtensionBuilder {
let fetch_output = Command::new("git")
.arg("--git-dir")
.arg(&git_dir)
- .args(["fetch", "--depth", "1", "origin", &rev])
+ .args(["fetch", "--depth", "1", "origin", rev])
.output()
.context("failed to execute `git fetch`")?;
let checkout_output = Command::new("git")
.arg("--git-dir")
.arg(&git_dir)
- .args(["checkout", &rev])
- .current_dir(&directory)
+ .args(["checkout", rev])
+ .current_dir(directory)
.output()
.context("failed to execute `git checkout`")?;
if !checkout_output.status.success() {
@@ -488,14 +488,10 @@ impl ExtensionBuilder {
_ => {}
}
- match &payload {
- CustomSection(c) => {
- if strip_custom_section(c.name()) {
- continue;
- }
+ if let CustomSection(c) = &payload {
+ if strip_custom_section(c.name()) {
+ continue;
}
-
- _ => {}
}
if let Some((id, range)) = payload.as_section() {
@@ -243,7 +243,7 @@ impl LspAdapter for ExtensionLspAdapter {
language: &Arc<Language>,
) -> Result<Vec<Option<CodeLabel>>> {
let completions = completions
- .into_iter()
+ .iter()
.map(|completion| wit::Completion::from(completion.clone()))
.collect::<Vec<_>>();
@@ -276,7 +276,7 @@ impl LspAdapter for ExtensionLspAdapter {
language: &Arc<Language>,
) -> Result<Vec<Option<CodeLabel>>> {
let symbols = symbols
- .into_iter()
+ .iter()
.cloned()
.map(|(name, kind)| wit::Symbol {
name,
@@ -317,7 +317,7 @@ fn labels_from_wit(
} else {
language.highlight_text(&label.code.as_str().into(), 0..label.code.len())
};
- build_code_label(&label, &runs, &language)
+ build_code_label(&label, &runs, language)
})
.collect()
}
@@ -364,7 +364,7 @@ fn build_code_label(
.grammar()
.zip(span.highlight_name.as_ref())
.and_then(|(grammar, highlight_name)| {
- grammar.highlight_id_for_name(&highlight_name)
+ grammar.highlight_id_for_name(highlight_name)
})
.unwrap_or_default();
let ix = text.len();
@@ -290,7 +290,7 @@ impl ExtensionStore {
// it must be asynchronously rebuilt.
let mut extension_index = ExtensionIndex::default();
let mut extension_index_needs_rebuild = true;
- if let Some(index_content) = index_content.ok() {
+ if let Ok(index_content) = index_content {
if let Some(index) = serde_json::from_str(&index_content).log_err() {
extension_index = index;
if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
@@ -582,11 +582,11 @@ impl ExtensionStore {
query: &[(&str, &str)],
cx: &mut ModelContext<'_, ExtensionStore>,
) -> Task<Result<Vec<ExtensionMetadata>>> {
- let url = self.http_client.build_zed_api_url(path, &query);
+ let url = self.http_client.build_zed_api_url(path, query);
let http_client = self.http_client.clone();
cx.spawn(move |_, _| async move {
let mut response = http_client
- .get(&url?.as_ref(), AsyncBody::empty(), true)
+ .get(url?.as_ref(), AsyncBody::empty(), true)
.await?;
let mut body = Vec::new();
@@ -651,7 +651,7 @@ impl ExtensionStore {
});
let mut response = http_client
- .get(&url.as_ref(), Default::default(), true)
+ .get(url.as_ref(), Default::default(), true)
.await
.map_err(|err| anyhow!("error downloading extension: {}", err))?;
@@ -687,14 +687,11 @@ impl ExtensionStore {
})?
.await;
- match operation {
- ExtensionOperation::Install => {
- this.update(&mut cx, |_, cx| {
- cx.emit(Event::ExtensionInstalled(extension_id));
- })
- .ok();
- }
- _ => {}
+ if let ExtensionOperation::Install = operation {
+ this.update(&mut cx, |_, cx| {
+ cx.emit(Event::ExtensionInstalled(extension_id));
+ })
+ .ok();
}
anyhow::Ok(())
@@ -873,10 +870,10 @@ impl ExtensionStore {
.await?;
let output_path = &extensions_dir.join(extension_id.as_ref());
- if let Some(metadata) = fs.metadata(&output_path).await? {
+ if let Some(metadata) = fs.metadata(output_path).await? {
if metadata.is_symlink {
fs.remove_file(
- &output_path,
+ output_path,
RemoveOptions {
recursive: false,
ignore_if_not_exists: true,
@@ -967,7 +964,7 @@ impl ExtensionStore {
(Some(_), None) => {
extensions_to_unload.push(old_keys.next().unwrap().0.clone());
}
- (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(&new_key) {
+ (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
Ordering::Equal => {
let (old_key, old_value) = old_keys.next().unwrap();
let (new_key, new_value) = new_keys.next().unwrap();
@@ -1140,7 +1137,7 @@ impl ExtensionStore {
async move {
for theme_path in &themes_to_add {
theme_registry
- .load_user_theme(&theme_path, fs.clone())
+ .load_user_theme(theme_path, fs.clone())
.await
.log_err();
}
@@ -587,11 +587,8 @@ async fn test_extension_store_with_test_extension(cx: &mut TestAppContext) {
let executor = cx.executor();
let _task = cx.executor().spawn(async move {
while let Some(event) = events.next().await {
- match event {
- crate::Event::StartedReloading => {
- executor.advance_clock(RELOAD_DEBOUNCE_DURATION);
- }
- _ => (),
+ if let crate::Event::StartedReloading = event {
+ executor.advance_clock(RELOAD_DEBOUNCE_DURATION);
}
}
});
@@ -173,11 +173,11 @@ impl WasmHost {
.preopened_dir(&extension_work_dir, ".", dir_perms, file_perms)?
.preopened_dir(
&extension_work_dir,
- &extension_work_dir.to_string_lossy(),
+ extension_work_dir.to_string_lossy(),
dir_perms,
file_perms,
)?
- .env("PWD", &extension_work_dir.to_string_lossy())
+ .env("PWD", extension_work_dir.to_string_lossy())
.env("RUST_BACKTRACE", "full")
.build())
}
@@ -74,14 +74,14 @@ impl Extension {
if version >= latest::MIN_VERSION {
let (extension, instance) =
- latest::Extension::instantiate_async(store, &component, latest::linker())
+ latest::Extension::instantiate_async(store, component, latest::linker())
.await
.context("failed to instantiate wasm extension")?;
Ok((Self::V010(extension), instance))
} else if version >= since_v0_0_6::MIN_VERSION {
let (extension, instance) = since_v0_0_6::Extension::instantiate_async(
store,
- &component,
+ component,
since_v0_0_6::linker(),
)
.await
@@ -90,7 +90,7 @@ impl Extension {
} else if version >= since_v0_0_4::MIN_VERSION {
let (extension, instance) = since_v0_0_4::Extension::instantiate_async(
store,
- &component,
+ component,
since_v0_0_4::linker(),
)
.await
@@ -99,7 +99,7 @@ impl Extension {
} else {
let (extension, instance) = since_v0_0_1::Extension::instantiate_async(
store,
- &component,
+ component,
since_v0_0_1::linker(),
)
.await
@@ -2,7 +2,7 @@ fn main() {
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
let out_dir = std::env::var("OUT_DIR").unwrap();
- let mut parts = version.split(|c: char| !c.is_digit(10));
+ let mut parts = version.split(|c: char| !c.is_ascii_digit());
let major = parts.next().unwrap().parse::<u16>().unwrap().to_be_bytes();
let minor = parts.next().unwrap().parse::<u16>().unwrap().to_be_bytes();
let patch = parts.next().unwrap().parse::<u16>().unwrap().to_be_bytes();
@@ -182,7 +182,7 @@ static mut EXTENSION: Option<Box<dyn Extension>> = None;
pub static ZED_API_VERSION: [u8; 6] = *include_bytes!(concat!(env!("OUT_DIR"), "/version_bytes"));
mod wit {
- #![allow(clippy::too_many_arguments)]
+ #![allow(clippy::too_many_arguments, clippy::missing_safety_doc)]
wit_bindgen::generate!({
skip: ["init-extension"],
@@ -17,7 +17,7 @@ impl HttpRequest {
/// Executes the [`HttpRequest`] with [`fetch_stream`].
pub fn fetch_stream(&self) -> Result<HttpResponseStream, String> {
- fetch_stream(&self)
+ fetch_stream(self)
}
}
@@ -31,6 +31,12 @@ pub struct HttpRequestBuilder {
redirect_policy: RedirectPolicy,
}
+impl Default for HttpRequestBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl HttpRequestBuilder {
/// Returns a new [`HttpRequestBuilder`].
pub fn new() -> Self {
@@ -89,7 +89,7 @@ async fn main() -> Result<()> {
let tar_output = Command::new("tar")
.current_dir(&output_dir)
- .args(&["-czvf", "archive.tar.gz", "-C", "archive", "."])
+ .args(["-czvf", "archive.tar.gz", "-C", "archive", "."])
.output()
.context("failed to run tar")?;
if !tar_output.status.success() {
@@ -122,7 +122,7 @@ async fn copy_extension_resources(
output_dir: &Path,
fs: Arc<dyn Fs>,
) -> Result<()> {
- fs::create_dir_all(&output_dir).context("failed to create output dir")?;
+ fs::create_dir_all(output_dir).context("failed to create output dir")?;
let manifest_toml = toml::to_string(&manifest).context("failed to serialize manifest")?;
fs::write(output_dir.join("extension.toml"), &manifest_toml)
@@ -144,8 +144,8 @@ async fn copy_extension_resources(
let mut grammar_filename = PathBuf::from(grammar_name.as_ref());
grammar_filename.set_extension("wasm");
fs::copy(
- &source_grammars_dir.join(&grammar_filename),
- &output_grammars_dir.join(&grammar_filename),
+ source_grammars_dir.join(&grammar_filename),
+ output_grammars_dir.join(&grammar_filename),
)
.with_context(|| format!("failed to copy grammar '{}'", grammar_filename.display()))?;
}
@@ -77,11 +77,11 @@ fn suggested_extensions() -> &'static HashMap<&'static str, Arc<str>> {
static SUGGESTIONS_BY_PATH_SUFFIX: OnceLock<HashMap<&str, Arc<str>>> = OnceLock::new();
SUGGESTIONS_BY_PATH_SUFFIX.get_or_init(|| {
SUGGESTIONS_BY_EXTENSION_ID
- .into_iter()
+ .iter()
.flat_map(|(name, path_suffixes)| {
let name = Arc::<str>::from(*name);
path_suffixes
- .into_iter()
+ .iter()
.map(move |suffix| (*suffix, name.clone()))
})
.collect()
@@ -95,11 +95,10 @@ pub fn init(cx: &mut AppContext) {
.detach();
});
- cx.subscribe(workspace.project(), |_, _, event, cx| match event {
- project::Event::LanguageNotFound(buffer) => {
+ cx.subscribe(workspace.project(), |_, _, event, cx| {
+ if let project::Event::LanguageNotFound(buffer) = event {
extension_suggest::suggest(buffer.clone(), cx);
}
- _ => {}
})
.detach();
})
@@ -642,7 +641,7 @@ impl ExtensionsPage {
context_menu.entry(
"Install Another Version...",
None,
- cx.handler_for(&this, move |this, cx| {
+ cx.handler_for(this, move |this, cx| {
this.show_extension_version_list(extension_id.clone(), cx)
}),
)
@@ -692,8 +691,7 @@ impl ExtensionsPage {
has_dev_extension: bool,
cx: &mut ViewContext<Self>,
) -> (Button, Option<Button>) {
- let is_compatible =
- extension::is_version_compatible(ReleaseChannel::global(cx), &extension);
+ let is_compatible = extension::is_version_compatible(ReleaseChannel::global(cx), extension);
if has_dev_extension {
// If we have a dev extension for the given extension, just treat it as uninstalled.
@@ -833,7 +831,7 @@ impl ExtensionsPage {
};
EditorElement::new(
- &editor,
+ editor,
EditorStyle {
background: cx.theme().colors().editor_background,
local_player: cx.theme().players().local(),
@@ -869,7 +867,7 @@ impl ExtensionsPage {
// If the search was just cleared then we can just reload the list
// of extensions without a debounce, which allows us to avoid seeing
// an intermittent flash of a "no extensions" state.
- if let Some(_) = search {
+ if search.is_some() {
cx.background_executor()
.timer(Duration::from_millis(250))
.await;
@@ -965,7 +963,7 @@ impl ExtensionsPage {
{
self.upsells.insert(*feature);
} else {
- self.upsells.remove(&feature);
+ self.upsells.remove(feature);
}
}
}
@@ -39,7 +39,7 @@ pub fn init(cx: &mut AppContext) {
feedback_modal::FeedbackModal::register(workspace, cx);
workspace
.register_action(|_, _: &CopySystemSpecsIntoClipboard, cx| {
- let specs = SystemSpecs::new(&cx);
+ let specs = SystemSpecs::new(cx);
cx.spawn(|_, mut cx| async move {
let specs = specs.await.to_string();
@@ -62,7 +62,7 @@ pub fn init(cx: &mut AppContext) {
cx.open_url(request_feature_url());
})
.register_action(move |_, _: &FileBugReport, cx| {
- let specs = SystemSpecs::new(&cx);
+ let specs = SystemSpecs::new(cx);
cx.spawn(|_, mut cx| async move {
let specs = specs.await;
cx.update(|cx| {
@@ -302,7 +302,7 @@ impl FeedbackModal {
let http_client = zed_client.http_client();
let feedback_endpoint = http_client.build_url("/api/feedback");
let request = FeedbackRequestBody {
- feedback_text: &feedback_text,
+ feedback_text,
email,
metrics_id,
installation_id,
@@ -354,7 +354,7 @@ impl Fs for RealFs {
// Use the directory of the destination as temp dir to avoid
// invalid cross-device link error, and XDG_CACHE_DIR for fallback.
// See https://github.com/zed-industries/zed/pull/8437 for more details.
- NamedTempFile::new_in(path.parent().unwrap_or(&paths::temp_dir()))
+ NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
} else if cfg!(target_os = "windows") {
// If temp dir is set to a different drive than the destination,
// we receive error:
@@ -364,7 +364,7 @@ impl Fs for RealFs {
//
// So we use the directory of the destination as a temp dir to avoid it.
// https://github.com/zed-industries/zed/issues/16571
- NamedTempFile::new_in(path.parent().unwrap_or(&paths::temp_dir()))
+ NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
} else {
NamedTempFile::new()
}?;
@@ -1007,7 +1007,7 @@ impl FakeFs {
self.create_dir(path).await.unwrap();
for entry in std::fs::read_dir(&src_path).unwrap() {
let entry = entry.unwrap();
- self.insert_tree_from_real_fs(&path.join(entry.file_name()), &entry.path())
+ self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
.await;
}
}
@@ -1313,7 +1313,7 @@ impl Fs for FakeFs {
}
})
.unwrap();
- state.emit_event(&[path]);
+ state.emit_event([path]);
Ok(())
}
@@ -32,7 +32,7 @@ impl Blame {
remote_url: Option<String>,
provider_registry: Arc<GitHostingProviderRegistry>,
) -> Result<Self> {
- let output = run_git_blame(git_binary, working_directory, path, &content)?;
+ let output = run_git_blame(git_binary, working_directory, path, content)?;
let mut entries = parse_git_blame(&output)?;
entries.sort_unstable_by(|a, b| a.range.start.cmp(&b.range.start));
@@ -60,7 +60,7 @@ impl Blame {
let shas = unique_shas.into_iter().collect::<Vec<_>>();
let messages =
- get_messages(&working_directory, &shas).context("failed to get commit messages")?;
+ get_messages(working_directory, &shas).context("failed to get commit messages")?;
Ok(Self {
entries,
@@ -71,8 +71,8 @@ impl Blame {
}
}
-const GIT_BLAME_NO_COMMIT_ERROR: &'static str = "fatal: no such ref: HEAD";
-const GIT_BLAME_NO_PATH: &'static str = "fatal: no such path";
+const GIT_BLAME_NO_COMMIT_ERROR: &str = "fatal: no such ref: HEAD";
+const GIT_BLAME_NO_PATH: &str = "fatal: no such path";
fn run_git_blame(
git_binary: &Path,
@@ -12,7 +12,7 @@ pub fn get_messages(working_directory: &Path, shas: &[Oid]) -> Result<HashMap<Oi
return Ok(HashMap::default());
}
- const MARKER: &'static str = "<MARKER>";
+ const MARKER: &str = "<MARKER>";
let mut command = Command::new("git");
@@ -63,6 +63,12 @@ pub struct BufferDiff {
tree: SumTree<DiffHunk<Anchor>>,
}
+impl Default for BufferDiff {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl BufferDiff {
pub fn new() -> BufferDiff {
BufferDiff {
@@ -49,7 +49,7 @@ impl FromStr for Oid {
fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
libgit::Oid::from_str(s)
.map_err(|error| anyhow!("failed to parse git oid: {}", error))
- .map(|oid| Self(oid))
+ .map(Self)
}
}
@@ -171,7 +171,7 @@ pub fn parse_git_remote_url(
.into_iter()
.find_map(|provider| {
provider
- .parse_remote_url(&url)
+ .parse_remote_url(url)
.map(|parsed_remote| (provider, parsed_remote))
})
}
@@ -98,7 +98,7 @@ impl CursorPosition {
if wrote_once {
write!(text, ", ").unwrap();
}
- let name = if is_short_format { &name[..1] } else { &name };
+ let name = if is_short_format { &name[..1] } else { name };
let plural_suffix = if count > 1 && !is_short_format {
"s"
} else {
@@ -81,9 +81,12 @@ mod macos {
fn generate_shader_bindings() -> PathBuf {
let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h");
let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
- let mut config = Config::default();
- config.include_guard = Some("SCENE_H".into());
- config.language = cbindgen::Language::C;
+ let mut config = Config {
+ include_guard: Some("SCENE_H".into()),
+ language: cbindgen::Language::C,
+ no_includes: true,
+ ..Default::default()
+ };
config.export.include.extend([
"Bounds".into(),
"Corners".into(),
@@ -178,7 +181,7 @@ mod macos {
"-c",
shader_path,
"-include",
- &header_path.to_str().unwrap(),
+ (header_path.to_str().unwrap()),
"-o",
])
.arg(&air_output_path)
@@ -9,7 +9,7 @@ impl AssetSource for Assets {
std::fs::read(path)
.map(Into::into)
.map_err(Into::into)
- .map(|result| Some(result))
+ .map(Some)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
@@ -23,7 +23,7 @@ impl AssetSource for Assets {
}
}
-const ARROW_CIRCLE_SVG: &'static str = concat!(
+const ARROW_CIRCLE_SVG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/image/arrow_circle.svg"
);
@@ -298,9 +298,7 @@ impl ViewInputHandler for TextInput {
bounds: Bounds<Pixels>,
_cx: &mut ViewContext<Self>,
) -> Option<Bounds<Pixels>> {
- let Some(last_layout) = self.last_layout.as_ref() else {
- return None;
- };
+ let last_layout = self.last_layout.as_ref()?;
let range = self.range_from_utf16(&range_utf16);
Some(Bounds::from_corners(
point(
@@ -66,8 +66,6 @@ impl HelloWorld {
break;
}
}
-
- ()
}));
}
}
@@ -514,7 +514,7 @@ impl AppContext {
}
Err(e) => {
cx.windows.remove(id);
- return Err(e);
+ Err(e)
}
}
})
@@ -666,7 +666,7 @@ impl LeakDetector {
let handles = self.entity_handles.entry(entity_id).or_default();
handles.insert(
handle_id,
- LEAK_BACKTRACE.then(|| backtrace::Backtrace::new_unresolved()),
+ LEAK_BACKTRACE.then(backtrace::Backtrace::new_unresolved),
);
handle_id
}
@@ -679,7 +679,7 @@ impl LeakDetector {
pub fn assert_released(&mut self, entity_id: EntityId) {
let handles = self.entity_handles.entry(entity_id).or_default();
if !handles.is_empty() {
- for (_, backtrace) in handles {
+ for backtrace in handles.values_mut() {
if let Some(mut backtrace) = backtrace.take() {
backtrace.resolve();
eprintln!("Leaked handle: {:#?}", backtrace);
@@ -52,11 +52,9 @@ where
// the surface area the least. This attempts to keep the tree balanced
// in terms of surface area. If there is an intersection with the other child,
// add its keys to the intersections vector.
- let left_cost = new_bounds
- .union(&self.nodes[left].bounds())
- .half_perimeter();
+ let left_cost = new_bounds.union(self.nodes[left].bounds()).half_perimeter();
let right_cost = new_bounds
- .union(&self.nodes[right].bounds())
+ .union(self.nodes[right].bounds())
.half_perimeter();
if left_cost < right_cost {
max_intersecting_ordering =
@@ -119,13 +119,13 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {
done = true;
delta = 1.0;
} else {
- delta = delta % 1.0;
+ delta %= 1.0;
}
}
let delta = (self.animation.easing)(delta);
debug_assert!(
- delta >= 0.0 && delta <= 1.0,
+ (0.0..=1.0).contains(&delta),
"delta should always be between 0 and 1"
);
@@ -110,6 +110,6 @@ impl DefaultColor {
/// Returns the HSLA color for the given color type.
pub fn hsla(&self, colors: &DefaultColors) -> Hsla {
- self.color(&colors).into()
+ self.color(colors).into()
}
}
@@ -1314,16 +1314,14 @@ impl Interactivity {
// If there's an explicit focus handle we're tracking, use that. Otherwise
// create a new handle and store it in the element state, which lives for as
// as frames contain an element with this id.
- if self.focusable {
- if self.tracked_focus_handle.is_none() {
- if let Some(element_state) = element_state.as_mut() {
- self.tracked_focus_handle = Some(
- element_state
- .focus_handle
- .get_or_insert_with(|| cx.focus_handle())
- .clone(),
- );
- }
+ if self.focusable && self.tracked_focus_handle.is_none() {
+ if let Some(element_state) = element_state.as_mut() {
+ self.tracked_focus_handle = Some(
+ element_state
+ .focus_handle
+ .get_or_insert_with(|| cx.focus_handle())
+ .clone(),
+ );
}
}
@@ -1336,7 +1334,7 @@ impl Interactivity {
self.scroll_offset = Some(
element_state
.scroll_offset
- .get_or_insert_with(|| Rc::default())
+ .get_or_insert_with(Rc::default)
.clone(),
);
}
@@ -1360,7 +1358,7 @@ impl Interactivity {
) -> R {
self.content_size = content_size;
if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
- cx.set_focus_handle(&focus_handle);
+ cx.set_focus_handle(focus_handle);
}
cx.with_optional_element_state::<InteractiveElementState, _>(
global_id,
@@ -1949,10 +1947,10 @@ impl Interactivity {
let tooltip_is_hovered =
tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
- if !tooltip_is_hoverable || !tooltip_is_hovered {
- if active_tooltip.borrow_mut().take().is_some() {
- cx.refresh();
- }
+ if (!tooltip_is_hoverable || !tooltip_is_hovered)
+ && active_tooltip.borrow_mut().take().is_some()
+ {
+ cx.refresh();
}
}
});
@@ -1963,10 +1961,10 @@ impl Interactivity {
move |_: &ScrollWheelEvent, _, cx| {
let tooltip_is_hovered =
tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
- if !tooltip_is_hoverable || !tooltip_is_hovered {
- if active_tooltip.borrow_mut().take().is_some() {
- cx.refresh();
- }
+ if (!tooltip_is_hoverable || !tooltip_is_hovered)
+ && active_tooltip.borrow_mut().take().is_some()
+ {
+ cx.refresh();
}
}
})
@@ -5,7 +5,6 @@ use crate::{
SvgSize, UriOrPath, WindowContext,
};
use futures::{AsyncReadExt, Future};
-use http_client;
use image::{
codecs::gif::GifDecoder, AnimationDecoder, Frame, ImageBuffer, ImageError, ImageFormat,
};
@@ -47,7 +46,7 @@ impl From<SharedUri> for ImageSource {
impl From<&'static str> for ImageSource {
fn from(s: &'static str) -> Self {
- if is_uri(&s) {
+ if is_uri(s) {
Self::Uri(s.into())
} else {
Self::Embedded(s.into())
@@ -187,18 +186,17 @@ impl Element for Img {
}
let image_size = data.size(frame_index);
- match (style.size.width, style.size.height) {
- (Length::Auto, Length::Auto) => {
- style.size = Size {
- width: Length::Definite(DefiniteLength::Absolute(
- AbsoluteLength::Pixels(px(image_size.width.0 as f32)),
- )),
- height: Length::Definite(DefiniteLength::Absolute(
- AbsoluteLength::Pixels(px(image_size.height.0 as f32)),
- )),
- }
+
+ if let (Length::Auto, Length::Auto) = (style.size.width, style.size.height)
+ {
+ style.size = Size {
+ width: Length::Definite(DefiniteLength::Absolute(
+ AbsoluteLength::Pixels(px(image_size.width.0 as f32)),
+ )),
+ height: Length::Definite(DefiniteLength::Absolute(
+ AbsoluteLength::Pixels(px(image_size.height.0 as f32)),
+ )),
}
- _ => {}
}
if global_id.is_some() && data.frame_count() > 1 {
@@ -71,7 +71,6 @@ impl Element for Surface {
_request_layout: &mut Self::RequestLayoutState,
_cx: &mut WindowContext,
) -> Self::PrepaintState {
- ()
}
fn paint(
@@ -604,7 +604,7 @@ impl Element for InteractiveText {
let mut interactive_state = interactive_state.unwrap_or_default();
if let Some(click_listener) = self.click_listener.take() {
let mouse_position = cx.mouse_position();
- if let Some(ix) = text_layout.index_for_position(mouse_position).ok() {
+ if let Ok(ix) = text_layout.index_for_position(mouse_position) {
if self
.clickable_ranges
.iter()
@@ -621,8 +621,8 @@ impl Element for InteractiveText {
let clickable_ranges = mem::take(&mut self.clickable_ranges);
cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
- if let Some(mouse_up_index) =
- text_layout.index_for_position(event.position).ok()
+ if let Ok(mouse_up_index) =
+ text_layout.index_for_position(event.position)
{
click_listener(
&clickable_ranges,
@@ -642,8 +642,8 @@ impl Element for InteractiveText {
let hitbox = hitbox.clone();
cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
- if let Some(mouse_down_index) =
- text_layout.index_for_position(event.position).ok()
+ if let Ok(mouse_down_index) =
+ text_layout.index_for_position(event.position)
{
mouse_down.set(Some(mouse_down_index));
cx.refresh();
@@ -210,10 +210,10 @@ impl BackgroundExecutor {
Poll::Pending => {
let timeout =
deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
- if !self.dispatcher.park(timeout) {
- if deadline.is_some_and(|deadline| deadline < Instant::now()) {
- return Err(future);
- }
+ if !self.dispatcher.park(timeout)
+ && deadline.is_some_and(|deadline| deadline < Instant::now())
+ {
+ return Err(future);
}
}
}
@@ -2146,7 +2146,7 @@ pub struct Percentage(pub f32);
/// Generate a `Radian` from a percentage of a full circle.
pub fn percentage(value: f32) -> Percentage {
debug_assert!(
- value >= 0.0 && value <= 1.0,
+ (0.0..=1.0).contains(&value),
"Percentage must be between 0 and 1"
);
Percentage(value)
@@ -3133,12 +3133,12 @@ mod tests {
};
// Test Case 1: Intersecting bounds
- assert_eq!(bounds1.intersects(&bounds2), true);
+ assert!(bounds1.intersects(&bounds2));
// Test Case 2: Non-Intersecting bounds
- assert_eq!(bounds1.intersects(&bounds3), false);
+ assert!(!bounds1.intersects(&bounds3));
// Test Case 3: Bounds intersecting with themselves
- assert_eq!(bounds1.intersects(&bounds1), true);
+ assert!(bounds1.intersects(&bounds1));
}
}
@@ -402,7 +402,7 @@ impl DispatchTree {
keymap
.bindings_for_action(action)
.filter(|binding| {
- let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, &context_stack);
+ let (bindings, _) = keymap.bindings_for_input(&binding.keystrokes, context_stack);
bindings
.iter()
.next()
@@ -424,7 +424,7 @@ impl DispatchTree {
self.keymap
.borrow()
- .bindings_for_input(&input, &context_stack)
+ .bindings_for_input(input, &context_stack)
}
/// dispatch_key processes the keystroke
@@ -463,7 +463,7 @@ impl DispatchTree {
let mut result = self.dispatch_key(suffix, keystroke, dispatch_path);
to_replay.extend(result.to_replay);
result.to_replay = to_replay;
- return result;
+ result
}
/// If the user types a matching prefix of a binding and then waits for a timeout
@@ -475,7 +475,7 @@ impl DispatchTree {
) -> SmallVec<[Replay; 1]> {
let (suffix, mut to_replay) = self.replay_prefix(input, dispatch_path);
- if suffix.len() > 0 {
+ if !suffix.is_empty() {
to_replay.extend(self.flush_dispatch(suffix, dispatch_path))
}
@@ -130,7 +130,7 @@ impl Keymap {
})
.collect();
- return (bindings, is_pending.unwrap_or_default());
+ (bindings, is_pending.unwrap_or_default())
}
/// Check if the given binding is enabled, given a certain key context.
@@ -57,7 +57,7 @@ impl KeyBinding {
}
}
- return Some(self.keystrokes.len() > typed.len());
+ Some(self.keystrokes.len() > typed.len())
}
/// Get the keystrokes associated with this binding
@@ -593,9 +593,7 @@ impl PlatformInputHandler {
}
pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
- let Some(selection) = self.handler.selected_text_range(true, cx) else {
- return None;
- };
+ let selection = self.handler.selected_text_range(true, cx)?;
self.handler.bounds_for_range(
if selection.reversed {
selection.range.start..selection.range.start
@@ -22,7 +22,8 @@ use std::{mem, sync::Arc};
const MAX_FRAME_TIME_MS: u32 = 10000;
#[cfg(target_os = "macos")]
-pub type Context = ();
+#[derive(Clone, Default)]
+pub struct Context {}
#[cfg(target_os = "macos")]
pub type Renderer = BladeRenderer;
@@ -161,13 +161,39 @@ impl Keystroke {
}
fn is_printable_key(key: &str) -> bool {
- match key {
- "f1" | "f2" | "f3" | "f4" | "f5" | "f6" | "f7" | "f8" | "f9" | "f10" | "f11" | "f12"
- | "f13" | "f14" | "f15" | "f16" | "f17" | "f18" | "f19" | "backspace" | "delete"
- | "left" | "right" | "up" | "down" | "pageup" | "pagedown" | "insert" | "home" | "end"
- | "escape" => false,
- _ => true,
- }
+ !matches!(
+ key,
+ "f1" | "f2"
+ | "f3"
+ | "f4"
+ | "f5"
+ | "f6"
+ | "f7"
+ | "f8"
+ | "f9"
+ | "f10"
+ | "f11"
+ | "f12"
+ | "f13"
+ | "f14"
+ | "f15"
+ | "f16"
+ | "f17"
+ | "f18"
+ | "f19"
+ | "backspace"
+ | "delete"
+ | "left"
+ | "right"
+ | "up"
+ | "down"
+ | "pageup"
+ | "pagedown"
+ | "insert"
+ | "home"
+ | "end"
+ | "escape"
+ )
}
impl std::fmt::Display for Keystroke {
@@ -250,12 +276,12 @@ impl Modifiers {
pub fn secondary(&self) -> bool {
#[cfg(target_os = "macos")]
{
- return self.platform;
+ self.platform
}
#[cfg(not(target_os = "macos"))]
{
- return self.control;
+ self.control
}
}
@@ -76,7 +76,7 @@ fn generate_feature_array(features: &FontFeatures) -> CFMutableArrayRef {
for (tag, value) in features.tag_value_list() {
let keys = [kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureValue];
let values = [
- CFString::new(&tag).as_CFTypeRef(),
+ CFString::new(tag).as_CFTypeRef(),
CFNumber::from(*value as i32).as_CFTypeRef(),
];
let dict = CFDictionaryCreate(
@@ -540,8 +540,6 @@ impl Platform for MacPlatform {
handle: AnyWindowHandle,
options: WindowParams,
) -> Result<Box<dyn PlatformWindow>> {
- // Clippy thinks that this evaluates to `()`, for some reason.
- #[allow(clippy::unit_arg, clippy::clone_on_copy)]
let renderer_context = self.0.lock().renderer_context.clone();
Ok(Box::new(MacWindow::open(
handle,
@@ -449,7 +449,7 @@ impl MacWindowState {
window_frame.origin.y =
screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
- let bounds = Bounds::new(
+ Bounds::new(
point(
px((window_frame.origin.x - screen_frame.origin.x) as f32),
px((window_frame.origin.y + screen_frame.origin.y) as f32),
@@ -458,8 +458,7 @@ impl MacWindowState {
px(window_frame.size.width as f32),
px(window_frame.size.height as f32),
),
- );
- bounds
+ )
}
fn content_size(&self) -> Size<Pixels> {
@@ -537,7 +536,7 @@ impl MacWindow {
let display = display_id
.and_then(MacDisplay::find_by_id)
- .unwrap_or_else(|| MacDisplay::primary());
+ .unwrap_or_else(MacDisplay::primary);
let mut target_screen = nil;
let mut screen_frame = None;
@@ -1981,13 +1980,10 @@ fn send_to_input_handler(window: &Object, ime: ImeInput) {
}
window_state.lock().input_handler = Some(input_handler);
} else {
- match ime {
- ImeInput::InsertText(text, range) => {
- if let Some(ime_input) = lock.last_ime_inputs.as_mut() {
- ime_input.push((text, range));
- }
+ if let ImeInput::InsertText(text, range) = ime {
+ if let Some(ime_input) = lock.last_ime_inputs.as_mut() {
+ ime_input.push((text, range));
}
- _ => {}
}
}
}
@@ -145,7 +145,7 @@ impl TestPlatform {
}
pub(crate) fn did_prompt_for_new_path(&self) -> bool {
- self.prompts.borrow().new_path.len() > 0
+ !self.prompts.borrow().new_path.is_empty()
}
}
@@ -592,9 +592,9 @@ impl TransformationMatrix {
pub fn apply(&self, point: Point<Pixels>) -> Point<Pixels> {
let input = [point.x.0, point.y.0];
let mut output = self.translation;
- for i in 0..2 {
- for k in 0..2 {
- output[i] += self.rotation_scale[i][k] * input[k];
+ for (i, output_cell) in output.iter_mut().enumerate() {
+ for (k, input_cell) in input.iter().enumerate() {
+ *output_cell += self.rotation_scale[i][k] * *input_cell;
}
}
Point::new(output[0].into(), output[1].into())
@@ -52,7 +52,7 @@ impl ObjectFit {
let image_ratio = image_size.width / image_size.height;
let bounds_ratio = bounds.size.width / bounds.size.height;
- let result_bounds = match self {
+ match self {
ObjectFit::Fill => bounds,
ObjectFit::Contain => {
let new_size = if bounds_ratio > image_ratio {
@@ -136,9 +136,7 @@ impl ObjectFit {
origin: bounds.origin,
size: image_size,
},
- };
-
- result_bounds
+ }
}
}
@@ -46,7 +46,7 @@ impl SvgRenderer {
}
pub fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {
- let tree = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
+ let tree = usvg::Tree::from_data(bytes, &usvg::Options::default())?;
let size = match size {
SvgSize::Size(size) => size,
@@ -69,7 +69,7 @@ impl TaffyLayoutEngine {
.expect(EXPECT_MESSAGE)
.into();
self.children_to_parents
- .extend(children.into_iter().map(|child_id| (*child_id, parent_id)));
+ .extend(children.iter().map(|child_id| (*child_id, parent_id)));
parent_id
};
self.styles.insert(layout_id, style);
@@ -11,7 +11,7 @@ pub struct FontFallbacks(pub Arc<Vec<String>>);
impl FontFallbacks {
/// Get the fallback fonts family names
pub fn fallback_list(&self) -> &[String] {
- &self.0.as_slice()
+ self.0.as_slice()
}
/// Create a font fallback from a list of strings
@@ -10,7 +10,7 @@ impl FontFeatures {
/// Get the tag name list of the font OpenType features
/// only enabled or disabled features are returned
pub fn tag_value_list(&self) -> &[(String, u32)] {
- &self.0.as_slice()
+ self.0.as_slice()
}
/// Returns whether the `calt` feature is enabled.
@@ -134,11 +134,14 @@ impl schemars::JsonSchema for FontFeatures {
InstanceType::Object,
)));
{
- let mut property = SchemaObject::default();
- property.instance_type = Some(schemars::schema::SingleOrVec::Vec(vec![
- InstanceType::Boolean,
- InstanceType::Integer,
- ]));
+ let mut property = SchemaObject {
+ instance_type: Some(schemars::schema::SingleOrVec::Vec(vec![
+ InstanceType::Boolean,
+ InstanceType::Integer,
+ ])),
+ ..Default::default()
+ };
+
{
let mut number_constraints = property.number();
number_constraints.multiple_of = Some(1.0);
@@ -74,7 +74,7 @@ impl<'a> std::fmt::Debug for CwdBacktrace<'a> {
if frame
.symbols()
.iter()
- .any(|s| s.filename().map_or(false, |f| f.starts_with(&cwd)))
+ .any(|s| s.filename().map_or(false, |f| f.starts_with(cwd)))
{
formatted_frame.backtrace_frame(frame)?;
}
@@ -3262,24 +3262,23 @@ impl<'a> WindowContext<'a> {
&& self.window.pending_modifier.modifiers.number_of_modifiers() == 1
&& !self.window.pending_modifier.saw_keystroke
{
- if event.modifiers.number_of_modifiers() == 0 {
- let key = match self.window.pending_modifier.modifiers {
- modifiers if modifiers.shift => Some("shift"),
- modifiers if modifiers.control => Some("control"),
- modifiers if modifiers.alt => Some("alt"),
- modifiers if modifiers.platform => Some("platform"),
- modifiers if modifiers.function => Some("function"),
- _ => None,
- };
- if let Some(key) = key {
- keystroke = Some(Keystroke {
- key: key.to_string(),
- ime_key: None,
- modifiers: Modifiers::default(),
- });
- }
+ let key = match self.window.pending_modifier.modifiers {
+ modifiers if modifiers.shift => Some("shift"),
+ modifiers if modifiers.control => Some("control"),
+ modifiers if modifiers.alt => Some("alt"),
+ modifiers if modifiers.platform => Some("platform"),
+ modifiers if modifiers.function => Some("function"),
+ _ => None,
+ };
+ if let Some(key) = key {
+ keystroke = Some(Keystroke {
+ key: key.to_string(),
+ ime_key: None,
+ modifiers: Modifiers::default(),
+ });
}
}
+
if self.window.pending_modifier.modifiers.number_of_modifiers() == 0
&& event.modifiers.number_of_modifiers() == 1
{
@@ -41,7 +41,7 @@ impl PromptHandle {
sender.send(e.0).ok();
cx.window.prompt.take();
if let Some(previous_focus) = &previous_focus {
- cx.focus(&previous_focus);
+ cx.focus(previous_focus);
}
}
})
@@ -541,7 +541,7 @@ fn generate_box_style_methods(
quote! { DefiniteLength }
},
&box_style_prefix.fields,
- &box_style_prefix.doc_string_prefix,
+ box_style_prefix.doc_string_prefix,
));
for box_style_suffix in &suffixes {
@@ -46,7 +46,7 @@ pub fn init(client: Arc<Client>, app_state: AppState, cx: &mut AppContext) -> Ta
// Set up a handler when the dev server is shut down
// with ctrl-c or kill
let (tx, rx) = futures::channel::oneshot::channel();
- let mut signals = Signals::new(&[SIGTERM, SIGINT]).unwrap();
+ let mut signals = Signals::new([SIGTERM, SIGINT]).unwrap();
std::thread::spawn({
move || {
if let Some(sig) = signals.forever().next() {
@@ -63,7 +63,7 @@ pub fn init(client: Arc<Client>, app_state: AppState, cx: &mut AppContext) -> Ta
.detach();
}
- let server_url = ClientSettings::get_global(&cx).server_url.clone();
+ let server_url = ClientSettings::get_global(cx).server_url.clone();
cx.spawn(|cx| async move {
client
.authenticate_and_connect(false, &cx)
@@ -321,7 +321,7 @@ impl DevServer {
for config in dev_server_project.paths.iter() {
tasks.push(project.find_or_create_worktree(
- &shellexpand::tilde(config).to_string(),
+ shellexpand::tilde(config).to_string(),
true,
cx,
));
@@ -9,7 +9,7 @@ use html5ever::Attribute;
/// [MDN: List of "inline" elements](https://yari-demos.prod.mdn.mozit.cloud/en-US/docs/Web/HTML/Inline_elements)
fn inline_elements() -> &'static HashSet<&'static str> {
static INLINE_ELEMENTS: OnceLock<HashSet<&str>> = OnceLock::new();
- &INLINE_ELEMENTS.get_or_init(|| {
+ INLINE_ELEMENTS.get_or_init(|| {
HashSet::from_iter([
"a", "abbr", "acronym", "audio", "b", "bdi", "bdo", "big", "br", "button", "canvas",
"cite", "code", "data", "datalist", "del", "dfn", "em", "embed", "i", "iframe", "img",
@@ -18,7 +18,7 @@ pub use crate::html_element::*;
pub use crate::markdown_writer::*;
/// Converts the provided HTML to Markdown.
-pub fn convert_html_to_markdown(html: impl Read, handlers: &mut Vec<TagHandler>) -> Result<String> {
+pub fn convert_html_to_markdown(html: impl Read, handlers: &mut [TagHandler]) -> Result<String> {
let dom = parse_html(html).context("failed to parse HTML")?;
let markdown_writer = MarkdownWriter::new();
@@ -5,10 +5,7 @@ pub struct WebpageChromeRemover;
impl HandleTag for WebpageChromeRemover {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "head" | "script" | "style" | "nav" => true,
- _ => false,
- }
+ matches!(tag, "head" | "script" | "style" | "nav")
}
fn handle_tag_start(
@@ -39,19 +36,18 @@ impl HandleTag for ParagraphHandler {
) -> StartTagOutcome {
if tag.is_inline() && writer.is_inside("p") {
if let Some(parent) = writer.current_element_stack().iter().last() {
- if !parent.is_inline() {
- if !(writer.markdown.ends_with(' ') || writer.markdown.ends_with('\n')) {
- writer.push_str(" ");
- }
+ if !(parent.is_inline()
+ || writer.markdown.ends_with(' ')
+ || writer.markdown.ends_with('\n'))
+ {
+ writer.push_str(" ");
}
}
}
- match tag.tag() {
- "p" => writer.push_blank_line(),
- _ => {}
+ if tag.tag() == "p" {
+ writer.push_blank_line()
}
-
StartTagOutcome::Continue
}
}
@@ -60,10 +56,7 @@ pub struct HeadingHandler;
impl HandleTag for HeadingHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => true,
- _ => false,
- }
+ matches!(tag, "h1" | "h2" | "h3" | "h4" | "h5" | "h6")
}
fn handle_tag_start(
@@ -96,10 +89,7 @@ pub struct ListHandler;
impl HandleTag for ListHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "ul" | "ol" | "li" => true,
- _ => false,
- }
+ matches!(tag, "ul" | "ol" | "li")
}
fn handle_tag_start(
@@ -142,12 +132,15 @@ impl TableHandler {
}
}
+impl Default for TableHandler {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl HandleTag for TableHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "table" | "thead" | "tbody" | "tr" | "th" | "td" => true,
- _ => false,
- }
+ matches!(tag, "table" | "thead" | "tbody" | "tr" | "th" | "td")
}
fn handle_tag_start(
@@ -210,10 +203,7 @@ pub struct StyledTextHandler;
impl HandleTag for StyledTextHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "strong" | "em" => true,
- _ => false,
- }
+ matches!(tag, "strong" | "em")
}
fn handle_tag_start(
@@ -243,10 +233,7 @@ pub struct CodeHandler;
impl HandleTag for CodeHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "pre" | "code" => true,
- _ => false,
- }
+ matches!(tag, "pre" | "code")
}
fn handle_tag_start(
@@ -281,7 +268,7 @@ impl HandleTag for CodeHandler {
fn handle_text(&mut self, text: &str, writer: &mut MarkdownWriter) -> HandlerOutcome {
if writer.is_inside("pre") {
- writer.push_str(&text);
+ writer.push_str(text);
return HandlerOutcome::Handled;
}
@@ -31,6 +31,12 @@ pub struct MarkdownWriter {
pub(crate) markdown: String,
}
+impl Default for MarkdownWriter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl MarkdownWriter {
pub fn new() -> Self {
Self {
@@ -64,8 +70,8 @@ impl MarkdownWriter {
self.push_str("\n\n");
}
- pub fn run(mut self, root_node: &Handle, handlers: &mut Vec<TagHandler>) -> Result<String> {
- self.visit_node(&root_node, handlers)?;
+ pub fn run(mut self, root_node: &Handle, handlers: &mut [TagHandler]) -> Result<String> {
+ self.visit_node(root_node, handlers)?;
Ok(Self::prettify_markdown(self.markdown))
}
@@ -104,7 +110,7 @@ impl MarkdownWriter {
}
if let Some(current_element) = current_element.as_ref() {
- match self.start_tag(¤t_element, handlers) {
+ match self.start_tag(current_element, handlers) {
StartTagOutcome::Continue => {}
StartTagOutcome::Skip => return Ok(()),
}
@@ -54,13 +54,8 @@ impl HandleTag for WikipediaInfoboxHandler {
tag: &HtmlElement,
_writer: &mut MarkdownWriter,
) -> StartTagOutcome {
- match tag.tag() {
- "table" => {
- if tag.has_class("infobox") {
- return StartTagOutcome::Skip;
- }
- }
- _ => {}
+ if tag.tag() == "table" && tag.has_class("infobox") {
+ return StartTagOutcome::Skip;
}
StartTagOutcome::Continue
@@ -77,12 +72,15 @@ impl WikipediaCodeHandler {
}
}
+impl Default for WikipediaCodeHandler {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl HandleTag for WikipediaCodeHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "div" | "pre" | "code" => true,
- _ => false,
- }
+ matches!(tag, "div" | "pre" | "code")
}
fn handle_tag_start(
@@ -134,7 +132,7 @@ impl HandleTag for WikipediaCodeHandler {
fn handle_text(&mut self, text: &str, writer: &mut MarkdownWriter) -> HandlerOutcome {
if writer.is_inside("pre") {
- writer.push_str(&text);
+ writer.push_str(text);
return HandlerOutcome::Handled;
}
@@ -92,7 +92,7 @@ impl Item for ImageView {
.file_icons
.then(|| FileIcons::get_icon(self.path.as_path(), cx))
.flatten()
- .map(|icon| Icon::from_path(icon))
+ .map(Icon::from_path)
}
fn clone_on_split(
@@ -235,7 +235,7 @@ async fn index_rustdoc(
while let Some(item_with_history) = items_to_visit.pop_front() {
let item = &item_with_history.item;
- let Some(result) = fetch_page(&package, Some(&item)).await.with_context(|| {
+ let Some(result) = fetch_page(&package, Some(item)).await.with_context(|| {
#[cfg(debug_assertions)]
{
format!(
@@ -268,11 +268,8 @@ async fn index_rustdoc(
seen_items.insert(item.clone());
item.path.extend(parent_item.path.clone());
- match parent_item.kind {
- RustdocItemKind::Mod => {
- item.path.push(parent_item.name.clone());
- }
- _ => {}
+ if parent_item.kind == RustdocItemKind::Mod {
+ item.path.push(parent_item.name.clone());
}
items_to_visit.push_back(RustdocItemWithHistory {
@@ -76,10 +76,7 @@ pub struct RustdocCodeHandler;
impl HandleTag for RustdocCodeHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "pre" | "code" => true,
- _ => false,
- }
+ matches!(tag, "pre" | "code")
}
fn handle_tag_start(
@@ -97,7 +94,7 @@ impl HandleTag for RustdocCodeHandler {
let classes = tag.classes();
let is_rust = classes.iter().any(|class| class == "rust");
let language = is_rust
- .then(|| "rs")
+ .then_some("rs")
.or_else(|| {
classes.iter().find_map(|class| {
if let Some((_, language)) = class.split_once("language-") {
@@ -131,7 +128,7 @@ impl HandleTag for RustdocCodeHandler {
fn handle_text(&mut self, text: &str, writer: &mut MarkdownWriter) -> HandlerOutcome {
if writer.is_inside("pre") {
- writer.push_str(&text);
+ writer.push_str(text);
return HandlerOutcome::Handled;
}
@@ -156,10 +153,7 @@ impl RustdocItemHandler {
impl HandleTag for RustdocItemHandler {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "div" | "span" => true,
- _ => false,
- }
+ matches!(tag, "div" | "span")
}
fn handle_tag_start(
@@ -211,10 +205,10 @@ pub struct RustdocChromeRemover;
impl HandleTag for RustdocChromeRemover {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "head" | "script" | "nav" | "summary" | "button" | "a" | "div" | "span" => true,
- _ => false,
- }
+ matches!(
+ tag,
+ "head" | "script" | "nav" | "summary" | "button" | "a" | "div" | "span"
+ )
}
fn handle_tag_start(
@@ -310,23 +304,20 @@ impl HandleTag for RustdocItemCollector {
tag: &HtmlElement,
writer: &mut MarkdownWriter,
) -> StartTagOutcome {
- match tag.tag() {
- "a" => {
- let is_reexport = writer.current_element_stack().iter().any(|element| {
- if let Some(id) = element.attr("id") {
- id.starts_with("reexport.") || id.starts_with("method.")
- } else {
- false
- }
- });
-
- if !is_reexport {
- if let Some(item) = Self::parse_item(tag) {
- self.items.insert(item);
- }
+ if tag.tag() == "a" {
+ let is_reexport = writer.current_element_stack().iter().any(|element| {
+ if let Some(id) = element.attr("id") {
+ id.starts_with("reexport.") || id.starts_with("method.")
+ } else {
+ false
+ }
+ });
+
+ if !is_reexport {
+ if let Some(item) = Self::parse_item(tag) {
+ self.items.insert(item);
}
}
- _ => {}
}
StartTagOutcome::Continue
@@ -53,7 +53,7 @@ impl Render for InlineCompletionButton {
let all_language_settings = all_language_settings(None, cx);
match all_language_settings.inline_completions.provider {
- InlineCompletionProvider::None => return div(),
+ InlineCompletionProvider::None => div(),
InlineCompletionProvider::Copilot => {
let Some(copilot) = Copilot::global(cx) else {
@@ -61,7 +61,7 @@ pub fn init(_: Arc<AppState>, cx: &mut AppContext) {
cx.observe_new_views(
|workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
workspace.register_action(|workspace, _: &NewJournalEntry, cx| {
- new_journal_entry(&workspace, cx);
+ new_journal_entry(workspace, cx);
});
},
)
@@ -169,7 +169,7 @@ fn journal_dir(path: &str) -> Option<PathBuf> {
.ok()
.map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
- return expanded_journal_dir;
+ expanded_journal_dir
}
fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
@@ -68,7 +68,7 @@ pub use lsp::DiagnosticSeverity;
/// A label for the background task spawned by the buffer to compute
/// a diff against the contents of its file.
-pub static BUFFER_DIFF_TASK: LazyLock<TaskLabel> = LazyLock::new(|| TaskLabel::new());
+pub static BUFFER_DIFF_TASK: LazyLock<TaskLabel> = LazyLock::new(TaskLabel::new);
/// Indicate whether a [Buffer] has permissions to edit.
#[derive(PartialEq, Clone, Copy, Debug)]
@@ -1105,7 +1105,6 @@ impl Buffer {
{
Ok(new_syntax_snapshot) => {
self.did_finish_parsing(new_syntax_snapshot, cx);
- return;
}
Err(parse_task) => {
self.parsing_in_background = true;
@@ -1938,25 +1937,23 @@ impl Buffer {
);
}
- if space_above {
- if position.row > 0 && !self.is_line_blank(position.row - 1) {
- self.edit(
- [(position..position, "\n")],
- Some(AutoindentMode::EachLine),
- cx,
- );
- position.row += 1;
- }
+ if space_above && position.row > 0 && !self.is_line_blank(position.row - 1) {
+ self.edit(
+ [(position..position, "\n")],
+ Some(AutoindentMode::EachLine),
+ cx,
+ );
+ position.row += 1;
}
- if space_below {
- if position.row == self.max_point().row || !self.is_line_blank(position.row + 1) {
- self.edit(
- [(position..position, "\n")],
- Some(AutoindentMode::EachLine),
- cx,
- );
- }
+ if space_below
+ && (position.row == self.max_point().row || !self.is_line_blank(position.row + 1))
+ {
+ self.edit(
+ [(position..position, "\n")],
+ Some(AutoindentMode::EachLine),
+ cx,
+ );
}
self.end_transaction(cx);
@@ -2094,7 +2091,7 @@ impl Buffer {
) {
if lamport_timestamp > self.diagnostics_timestamp {
let ix = self.diagnostics.binary_search_by_key(&server_id, |e| e.0);
- if diagnostics.len() == 0 {
+ if diagnostics.is_empty() {
if let Ok(ix) = ix {
self.diagnostics.remove(ix);
}
@@ -2582,7 +2579,7 @@ impl BufferSnapshot {
});
let highlight_maps = captures
.grammars()
- .into_iter()
+ .iter()
.map(|grammar| grammar.highlight_map())
.collect();
(captures, highlight_maps)
@@ -3422,31 +3419,35 @@ impl BufferSnapshot {
current_depth
};
- if depth < current_depth {
- for _ in 0..(current_depth - depth) {
- let mut indent = indent_stack.pop().unwrap();
- if last_row != first_row {
- // In this case, we landed on an empty row, had to seek forward,
- // and discovered that the indent we where on is ending.
- // This means that the last display row must
- // be on line that ends this indent range, so we
- // should display the range up to the first non-empty line
- indent.end_row = first_row.saturating_sub(1);
- }
+ match depth.cmp(¤t_depth) {
+ Ordering::Less => {
+ for _ in 0..(current_depth - depth) {
+ let mut indent = indent_stack.pop().unwrap();
+ if last_row != first_row {
+ // In this case, we landed on an empty row, had to seek forward,
+ // and discovered that the indent we where on is ending.
+ // This means that the last display row must
+ // be on line that ends this indent range, so we
+ // should display the range up to the first non-empty line
+ indent.end_row = first_row.saturating_sub(1);
+ }
- result_vec.push(indent)
+ result_vec.push(indent)
+ }
}
- } else if depth > current_depth {
- for next_depth in current_depth..depth {
- indent_stack.push(IndentGuide {
- buffer_id: self.remote_id(),
- start_row: first_row,
- end_row: last_row,
- depth: next_depth,
- tab_size,
- settings,
- });
+ Ordering::Greater => {
+ for next_depth in current_depth..depth {
+ indent_stack.push(IndentGuide {
+ buffer_id: self.remote_id(),
+ start_row: first_row,
+ end_row: last_row,
+ depth: next_depth,
+ tab_size,
+ settings,
+ });
+ }
}
+ _ => {}
}
for indent in indent_stack.iter_mut() {
@@ -110,6 +110,10 @@ impl DiagnosticSet {
pub fn len(&self) -> usize {
self.diagnostics.summary().count
}
+ /// Returns true when there are no diagnostics in this diagnostic set
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
/// Returns an iterator over the diagnostic entries in the set.
pub fn iter(&self) -> impl Iterator<Item = &DiagnosticEntry<Anchor>> {
@@ -2,7 +2,7 @@
//! features (the other big contributors being project and lsp crates that revolve around LSP features).
//! Namely, this crate:
//! - Provides [`Language`], [`Grammar`] and [`LanguageRegistry`] types that
-//! use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
+//! use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
//! - Exposes [`LanguageConfig`] that describes how constructs (like brackets or line comments) should be handled by the editor for a source file of a particular language.
//!
//! Notably we do *not* assign a single language to a single file; in real world a single file can consist of multiple programming languages - HTML is a good example of that - and `language` crate tends to reflect that status quo in its API.
@@ -433,7 +433,7 @@ pub trait LspAdapter: 'static + Send + Sync {
language: &Arc<Language>,
) -> Result<Vec<Option<CodeLabel>>> {
let mut labels = Vec::new();
- for (ix, completion) in completions.into_iter().enumerate() {
+ for (ix, completion) in completions.iter().enumerate() {
let label = self.label_for_completion(completion, language).await;
if let Some(label) = label {
labels.resize(ix + 1, None);
@@ -457,7 +457,7 @@ pub trait LspAdapter: 'static + Send + Sync {
language: &Arc<Language>,
) -> Result<Vec<Option<CodeLabel>>> {
let mut labels = Vec::new();
- for (ix, (name, kind)) in symbols.into_iter().enumerate() {
+ for (ix, (name, kind)) in symbols.iter().enumerate() {
let label = self.label_for_symbol(name, *kind, language).await;
if let Some(label) = label {
labels.resize(ix + 1, None);
@@ -668,7 +668,7 @@ impl LanguageRegistry {
.ok_or_else(|| anyhow!("invalid grammar filename"))?;
anyhow::Ok(with_parser(|parser| {
let mut store = parser.take_wasm_store().unwrap();
- let grammar = store.load_language(&grammar_name, &wasm_bytes);
+ let grammar = store.load_language(grammar_name, &wasm_bytes);
parser.set_wasm_store(store).unwrap();
grammar
})?)
@@ -699,7 +699,7 @@ impl LanguageRegistry {
}
pub fn to_vec(&self) -> Vec<Arc<Language>> {
- self.state.read().languages.iter().cloned().collect()
+ self.state.read().languages.to_vec()
}
pub fn lsp_adapters(&self, language: &Arc<Language>) -> Vec<Arc<CachedLspAdapter>> {
@@ -971,7 +971,7 @@ impl LanguageRegistryState {
self.available_languages
.retain(|language| !languages_to_remove.contains(&language.name));
self.grammars
- .retain(|name, _| !grammars_to_remove.contains(&name));
+ .retain(|name, _| !grammars_to_remove.contains(name));
self.version += 1;
self.reload_count += 1;
*self.subscription.0.borrow_mut() = ();
@@ -20,11 +20,11 @@ use settings::{add_references_to_properties, Settings, SettingsLocation, Setting
use std::{num::NonZeroU32, path::Path, sync::Arc};
use util::serde::default_true;
-impl<'a> Into<SettingsLocation<'a>> for &'a dyn File {
- fn into(self) -> SettingsLocation<'a> {
+impl<'a> From<&'a dyn File> for SettingsLocation<'a> {
+ fn from(val: &'a dyn File) -> Self {
SettingsLocation {
- worktree_id: self.worktree_id(),
- path: self.path().as_ref(),
+ worktree_id: val.worktree_id(),
+ path: val.path().as_ref(),
}
}
}
@@ -155,10 +155,10 @@ impl LanguageSettings {
);
let rest = available_language_servers
- .into_iter()
+ .iter()
.filter(|&available_language_server| {
- !disabled_language_servers.contains(&&available_language_server.0)
- && !enabled_language_servers.contains(&&available_language_server.0)
+ !disabled_language_servers.contains(&available_language_server.0)
+ && !enabled_language_servers.contains(&available_language_server.0)
})
.cloned()
.collect::<Vec<_>>();
@@ -414,13 +414,15 @@ impl JsonSchema for FormatOnSave {
.into(),
);
- let mut valid_raw_values = SchemaObject::default();
- valid_raw_values.enum_values = Some(vec![
- Value::String("on".into()),
- Value::String("off".into()),
- Value::String("prettier".into()),
- Value::String("language_server".into()),
- ]);
+ let valid_raw_values = SchemaObject {
+ enum_values: Some(vec![
+ Value::String("on".into()),
+ Value::String("off".into()),
+ Value::String("prettier".into()),
+ Value::String("language_server".into()),
+ ]),
+ ..Default::default()
+ };
let mut nested_values = SchemaObject::default();
nested_values.array().items = Some(formatter_schema.clone().into());
@@ -545,12 +547,15 @@ impl JsonSchema for SelectedFormatter {
.into(),
);
- let mut valid_raw_values = SchemaObject::default();
- valid_raw_values.enum_values = Some(vec![
- Value::String("auto".into()),
- Value::String("prettier".into()),
- Value::String("language_server".into()),
- ]);
+ let valid_raw_values = SchemaObject {
+ enum_values: Some(vec![
+ Value::String("auto".into()),
+ Value::String("prettier".into()),
+ Value::String("language_server".into()),
+ ]),
+ ..Default::default()
+ };
+
let mut nested_values = SchemaObject::default();
nested_values.array().items = Some(formatter_schema.clone().into());
@@ -633,7 +638,7 @@ impl AsRef<[Formatter]> for FormatterList {
fn as_ref(&self) -> &[Formatter] {
match &self.0 {
SingleOrVec::Single(single) => slice::from_ref(single),
- SingleOrVec::Vec(v) => &v,
+ SingleOrVec::Vec(v) => v,
}
}
}
@@ -1145,7 +1150,7 @@ mod tests {
pub fn test_resolve_language_servers() {
fn language_server_names(names: &[&str]) -> Vec<LanguageServerName> {
names
- .into_iter()
+ .iter()
.copied()
.map(|name| LanguageServerName(name.into()))
.collect::<Vec<_>>()
@@ -191,7 +191,7 @@ pub async fn parse_markdown_block(
style.strikethrough = true;
}
- if let Some(link) = link_url.clone().and_then(|u| Link::identify(u)) {
+ if let Some(link) = link_url.clone().and_then(Link::identify) {
region_ranges.push(prev_len..text.len());
regions.push(ParsedRegion {
code: false,
@@ -222,7 +222,7 @@ pub async fn parse_markdown_block(
text.push_str(t.as_ref());
region_ranges.push(prev_len..text.len());
- let link = link_url.clone().and_then(|u| Link::identify(u));
+ let link = link_url.clone().and_then(Link::identify);
if link.is_some() {
highlights.push((
prev_len..text.len(),
@@ -336,7 +336,7 @@ pub fn highlight_code(
}
/// Appends a new paragraph to the provided `text` buffer.
-pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
+pub fn new_paragraph(text: &mut String, list_stack: &mut [(Option<u64>, bool)]) {
let mut is_subsequent_paragraph_of_list = false;
if let Some((_, has_content)) = list_stack.last_mut() {
if *has_content {
@@ -198,8 +198,10 @@ pub fn render_item<T>(
match_ranges: impl IntoIterator<Item = Range<usize>>,
cx: &AppContext,
) -> StyledText {
- let mut highlight_style = HighlightStyle::default();
- highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
+ let highlight_style = HighlightStyle {
+ background_color: Some(color_alpha(cx.theme().colors().text_accent, 0.3)),
+ ..Default::default()
+ };
let custom_highlights = match_ranges
.into_iter()
.map(|range| (range, highlight_style));
@@ -734,19 +734,24 @@ impl SyntaxSnapshot {
let mut max_depth = 0;
let mut prev_range: Option<Range<Anchor>> = None;
for layer in self.layers.iter() {
- if layer.depth == max_depth {
- if let Some(prev_range) = prev_range {
- match layer.range.start.cmp(&prev_range.start, text) {
- Ordering::Less => panic!("layers out of order"),
- Ordering::Equal => {
- assert!(layer.range.end.cmp(&prev_range.end, text).is_ge())
+ match Ord::cmp(&layer.depth, &max_depth) {
+ Ordering::Less => {
+ panic!("layers out of order")
+ }
+ Ordering::Equal => {
+ if let Some(prev_range) = prev_range {
+ match layer.range.start.cmp(&prev_range.start, text) {
+ Ordering::Less => panic!("layers out of order"),
+ Ordering::Equal => {
+ assert!(layer.range.end.cmp(&prev_range.end, text).is_ge())
+ }
+ Ordering::Greater => {}
}
- Ordering::Greater => {}
}
}
- } else if layer.depth < max_depth {
- panic!("layers out of order")
+ Ordering::Greater => {}
}
+
max_depth = layer.depth;
prev_range = Some(layer.range.clone());
}
@@ -1343,7 +1348,7 @@ pub(crate) fn splice_included_ranges(
new_ranges: &[tree_sitter::Range],
) -> (Vec<tree_sitter::Range>, Range<usize>) {
let mut removed_ranges = removed_ranges.iter().cloned().peekable();
- let mut new_ranges = new_ranges.into_iter().cloned().peekable();
+ let mut new_ranges = new_ranges.iter().cloned().peekable();
let mut ranges_ix = 0;
let mut changed_portion: Option<Range<usize>> = None;
loop {
@@ -1709,7 +1714,7 @@ impl<'a> SeekTarget<'a, SyntaxLayerSummary, SyntaxLayerSummary>
{
fn cmp(&self, cursor_location: &SyntaxLayerSummary, buffer: &BufferSnapshot) -> Ordering {
if self.change.cmp(cursor_location, buffer).is_le() {
- return Ordering::Less;
+ Ordering::Less
} else {
self.position.cmp(cursor_location, buffer)
}
@@ -1759,7 +1764,7 @@ impl<'a> Iterator for ByteChunks<'a> {
impl QueryCursorHandle {
pub fn new() -> Self {
- let mut cursor = QUERY_CURSORS.lock().pop().unwrap_or_else(QueryCursor::new);
+ let mut cursor = QUERY_CURSORS.lock().pop().unwrap_or_default();
cursor.set_match_limit(64);
QueryCursorHandle(Some(cursor))
}
@@ -958,7 +958,7 @@ fn check_interpolation(
new_buffer: &BufferSnapshot,
) {
let edits = new_buffer
- .edits_since::<usize>(&old_buffer.version())
+ .edits_since::<usize>(old_buffer.version())
.collect::<Vec<_>>();
for (old_layer, new_layer) in old_syntax_map
@@ -1086,7 +1086,7 @@ fn test_edit_sequence(
mutated_syntax_map.set_language_registry(registry.clone());
mutated_syntax_map.reparse(language.clone(), &buffer);
- for (i, marked_string) in steps.into_iter().enumerate() {
+ for (i, marked_string) in steps.iter().enumerate() {
let marked_string = marked_string.unindent();
log::info!("incremental parse {i}: {marked_string:?}");
buffer.edit_via_marked_text(&marked_string);
@@ -1302,7 +1302,7 @@ fn assert_layers_for_range(
expected_layers: &[&str],
) {
let layers = syntax_map
- .layers_for_range(range, &buffer, true)
+ .layers_for_range(range, buffer, true)
.collect::<Vec<_>>();
assert_eq!(
layers.len(),
@@ -1338,7 +1338,7 @@ fn assert_capture_ranges(
.collect::<Vec<_>>();
for capture in captures {
let name = &queries[capture.grammar_index].capture_names()[capture.index as usize];
- if highlight_query_capture_names.contains(&name) {
+ if highlight_query_capture_names.contains(name) {
actual_ranges.push(capture.node.byte_range());
}
}
@@ -58,7 +58,7 @@ pub struct AnthropicLanguageModelProvider {
state: gpui::Model<State>,
}
-const ANTHROPIC_API_KEY_VAR: &'static str = "ANTHROPIC_API_KEY";
+const ANTHROPIC_API_KEY_VAR: &str = "ANTHROPIC_API_KEY";
pub struct State {
api_key: Option<String>,
@@ -48,7 +48,7 @@ fn zed_cloud_provider_additional_models() -> &'static [AvailableModel] {
static ADDITIONAL_MODELS: LazyLock<Vec<AvailableModel>> = LazyLock::new(|| {
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON
.map(|json| serde_json::from_str(json).unwrap())
- .unwrap_or(Vec::new())
+ .unwrap_or_default()
});
ADDITIONAL_MODELS.as_slice()
}
@@ -777,12 +777,12 @@ impl LlmApiToken {
if let Some(token) = lock.as_ref() {
Ok(token.to_string())
} else {
- Self::fetch(RwLockUpgradableReadGuard::upgrade(lock).await, &client).await
+ Self::fetch(RwLockUpgradableReadGuard::upgrade(lock).await, client).await
}
}
async fn refresh(&self, client: &Arc<Client>) -> Result<String> {
- Self::fetch(self.0.write().await, &client).await
+ Self::fetch(self.0.write().await, client).await
}
async fn fetch<'a>(
@@ -51,7 +51,7 @@ pub struct State {
_subscription: Subscription,
}
-const GOOGLE_AI_API_KEY_VAR: &'static str = "GOOGLE_AI_API_KEY";
+const GOOGLE_AI_API_KEY_VAR: &str = "GOOGLE_AI_API_KEY";
impl State {
fn is_authenticated(&self) -> bool {
@@ -55,7 +55,7 @@ pub struct State {
_subscription: Subscription,
}
-const OPENAI_API_KEY_VAR: &'static str = "OPENAI_API_KEY";
+const OPENAI_API_KEY_VAR: &str = "OPENAI_API_KEY";
impl State {
fn is_authenticated(&self) -> bool {
@@ -176,7 +176,7 @@ impl LanguageModelRegistry {
model_id: &LanguageModelId,
cx: &mut ModelContext<Self>,
) {
- let Some(provider) = self.provider(&provider) else {
+ let Some(provider) = self.provider(provider) else {
return;
};
@@ -212,7 +212,7 @@ impl LanguageModelRequestMessage {
self.content.is_empty()
|| self
.content
- .get(0)
+ .first()
.map(|content| match content {
MessageContent::Text(text) => text.trim().is_empty(),
MessageContent::ToolResult(tool_result) => {
@@ -180,13 +180,13 @@ pub(crate) struct LogMenuItem {
actions!(debug, [OpenLanguageServerLogs]);
pub fn init(cx: &mut AppContext) {
- let log_store = cx.new_model(|cx| LogStore::new(cx));
+ let log_store = cx.new_model(LogStore::new);
cx.observe_new_views(move |workspace: &mut Workspace, cx| {
let project = workspace.project();
if project.read(cx).is_local_or_ssh() {
log_store.update(cx, |store, cx| {
- store.add_project(&project, cx);
+ store.add_project(project, cx);
});
}
@@ -215,37 +215,34 @@ impl LogStore {
let copilot_subscription = Copilot::global(cx).map(|copilot| {
let copilot = &copilot;
cx.subscribe(copilot, |this, copilot, inline_completion_event, cx| {
- match inline_completion_event {
- copilot::Event::CopilotLanguageServerStarted => {
- if let Some(server) = copilot.read(cx).language_server() {
- let server_id = server.server_id();
- let weak_this = cx.weak_model();
- this.copilot_log_subscription =
- Some(server.on_notification::<copilot::request::LogMessage, _>(
- move |params, mut cx| {
- weak_this
- .update(&mut cx, |this, cx| {
- this.add_language_server_log(
- server_id,
- MessageType::LOG,
- ¶ms.message,
- cx,
- );
- })
- .ok();
- },
- ));
- this.add_language_server(
- LanguageServerKind::Global {
- name: LanguageServerName(Arc::from("copilot")),
+ if let copilot::Event::CopilotLanguageServerStarted = inline_completion_event {
+ if let Some(server) = copilot.read(cx).language_server() {
+ let server_id = server.server_id();
+ let weak_this = cx.weak_model();
+ this.copilot_log_subscription =
+ Some(server.on_notification::<copilot::request::LogMessage, _>(
+ move |params, mut cx| {
+ weak_this
+ .update(&mut cx, |this, cx| {
+ this.add_language_server_log(
+ server_id,
+ MessageType::LOG,
+ ¶ms.message,
+ cx,
+ );
+ })
+ .ok();
},
- server.server_id(),
- Some(server.clone()),
- cx,
- );
- }
+ ));
+ this.add_language_server(
+ LanguageServerKind::Global {
+ name: LanguageServerName(Arc::from("copilot")),
+ },
+ server.server_id(),
+ Some(server.clone()),
+ cx,
+ );
}
- _ => {}
}
})
});
@@ -593,21 +590,19 @@ impl LspLogView {
});
let events_subscriptions = cx.subscribe(&log_store, |log_view, _, e, cx| match e {
Event::NewServerLogEntry { id, entry, kind } => {
- if log_view.current_server_id == Some(*id) {
- if *kind == log_view.active_entry_kind {
- log_view.editor.update(cx, |editor, cx| {
- editor.set_read_only(false);
- let last_point = editor.buffer().read(cx).len(cx);
- editor.edit(
- vec![
- (last_point..last_point, entry.trim()),
- (last_point..last_point, "\n"),
- ],
- cx,
- );
- editor.set_read_only(true);
- });
- }
+ if log_view.current_server_id == Some(*id) && *kind == log_view.active_entry_kind {
+ log_view.editor.update(cx, |editor, cx| {
+ editor.set_read_only(false);
+ let last_point = editor.buffer().read(cx).len(cx);
+ editor.edit(
+ vec![
+ (last_point..last_point, entry.trim()),
+ (last_point..last_point, "\n"),
+ ],
+ cx,
+ );
+ editor.set_read_only(true);
+ });
}
}
});
@@ -877,8 +872,8 @@ fn log_filter<T: Message>(line: &T, cmp: <T as Message>::Level) -> Option<&str>
fn log_contents<T: Message>(lines: &VecDeque<T>, cmp: <T as Message>::Level) -> String {
let (a, b) = lines.as_slices();
- let a = a.into_iter().filter_map(move |v| log_filter(v, cmp));
- let b = b.into_iter().filter_map(move |v| log_filter(v, cmp));
+ let a = a.iter().filter_map(move |v| log_filter(v, cmp));
+ let b = b.iter().filter_map(move |v| log_filter(v, cmp));
a.chain(b).fold(String::new(), |mut acc, el| {
acc.push_str(el);
acc.push('\n');
@@ -1275,6 +1270,12 @@ const RPC_MESSAGES: &str = "RPC Messages";
const SERVER_LOGS: &str = "Server Logs";
const SERVER_TRACE: &str = "Server Trace";
+impl Default for LspLogToolbarItemView {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl LspLogToolbarItemView {
pub fn new() -> Self {
Self {
@@ -53,7 +53,7 @@ async fn test_lsp_logs(cx: &mut TestAppContext) {
},
);
- let log_store = cx.new_model(|cx| LogStore::new(cx));
+ let log_store = cx.new_model(LogStore::new);
log_store.update(cx, |store, cx| store.add_project(&project, cx));
let _rust_buffer = project
@@ -249,24 +249,23 @@ impl SyntaxTreeView {
}
let node = cursor.node();
- return row
- .child(if node.is_named() {
- Label::new(node.kind()).color(Color::Default)
- } else {
- Label::new(format!("\"{}\"", node.kind())).color(Color::Created)
- })
- .child(
- div()
- .child(Label::new(format_node_range(node)).color(Color::Muted))
- .pl_1(),
- )
- .text_bg(if selected {
- colors.element_selected
- } else {
- Hsla::default()
- })
- .pl(rems(depth as f32))
- .hover(|style| style.bg(colors.element_hover));
+ row.child(if node.is_named() {
+ Label::new(node.kind()).color(Color::Default)
+ } else {
+ Label::new(format!("\"{}\"", node.kind())).color(Color::Created)
+ })
+ .child(
+ div()
+ .child(Label::new(format_node_range(node)).color(Color::Muted))
+ .pl_1(),
+ )
+ .text_bg(if selected {
+ colors.element_selected
+ } else {
+ Hsla::default()
+ })
+ .pl(rems(depth as f32))
+ .hover(|style| style.bg(colors.element_hover))
}
}
@@ -406,6 +405,12 @@ impl Item for SyntaxTreeView {
}
}
+impl Default for SyntaxTreeToolbarItemView {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl SyntaxTreeToolbarItemView {
pub fn new() -> Self {
Self {
@@ -117,7 +117,7 @@ impl JsonLspAdapter {
},
{
"fileMatch": [schema_file_match(paths::keymap_file())],
- "schema": KeymapFile::generate_json_schema(&action_names),
+ "schema": KeymapFile::generate_json_schema(action_names),
},
{
"fileMatch": [
@@ -249,7 +249,7 @@ impl LspAdapter for RustLspAdapter {
static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
let detail = detail.unwrap();
- const FUNCTION_PREFIXES: [&'static str; 6] = [
+ const FUNCTION_PREFIXES: [&str; 6] = [
"async fn",
"async unsafe fn",
"const fn",
@@ -421,8 +421,8 @@ impl ContextProvider for RustContextProvider {
.is_some();
if is_main_function {
- if let Some((package_name, bin_name)) = local_abs_path
- .and_then(|local_abs_path| package_name_and_bin_name_from_abs_path(local_abs_path))
+ if let Some((package_name, bin_name)) =
+ local_abs_path.and_then(package_name_and_bin_name_from_abs_path)
{
return Ok(TaskVariables::from_iter([
(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name),
@@ -449,7 +449,7 @@ impl ContextProvider for RustContextProvider {
file: Option<Arc<dyn language::File>>,
cx: &AppContext,
) -> Option<TaskTemplates> {
- const DEFAULT_RUN_NAME_STR: &'static str = "RUST_DEFAULT_PACKAGE_RUN";
+ const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
let package_to_run = all_language_settings(file.as_ref(), cx)
.language(Some("Rust"))
.tasks
@@ -383,7 +383,7 @@ impl LspAdapter for EsLintLspAdapter {
"workspaceFolder": {
"uri": workspace_root,
"name": workspace_root.file_name()
- .unwrap_or_else(|| workspace_root.as_os_str()),
+ .unwrap_or(workspace_root.as_os_str()),
},
"problems": problems,
"codeActionOnSave": code_action_on_save,
@@ -49,7 +49,7 @@ struct TypeScriptVersions {
server_version: String,
}
-const SERVER_NAME: &'static str = "vtsls";
+const SERVER_NAME: &str = "vtsls";
#[async_trait(?Send)]
impl LspAdapter for VtslsLspAdapter {
fn name(&self) -> LanguageServerName {
@@ -220,7 +220,7 @@ impl LspAdapter for VtslsLspAdapter {
self: Arc<Self>,
adapter: &Arc<dyn LspAdapterDelegate>,
) -> Result<Option<serde_json::Value>> {
- let tsdk_path = Self::tsdk_path(&adapter).await;
+ let tsdk_path = Self::tsdk_path(adapter).await;
let config = serde_json::json!({
"tsdk": tsdk_path,
"suggest": {
@@ -81,7 +81,7 @@ fn main() {
{
let remote_tracks = room_b.remote_audio_tracks("test-participant-1");
assert_eq!(remote_tracks[0].sid(), track_id);
- assert_eq!(muted, true);
+ assert!(muted);
} else {
panic!("unexpected message");
}
@@ -93,7 +93,7 @@ fn main() {
{
let remote_tracks = room_b.remote_audio_tracks("test-participant-1");
assert_eq!(remote_tracks[0].sid(), track_id);
- assert_eq!(muted, false);
+ assert!(!muted);
} else {
panic!("unexpected message");
}
@@ -320,7 +320,7 @@ impl TestServer {
.try_broadcast(RoomUpdate::SubscribedToRemoteAudioTrack(
Arc::new(RemoteAudioTrack {
server_track: track.clone(),
- room: Arc::downgrade(&client_room),
+ room: Arc::downgrade(client_room),
}),
publication.clone(),
))
@@ -332,7 +332,7 @@ impl TestServer {
}
fn set_track_muted(&self, token: &str, track_sid: &str, muted: bool) -> Result<()> {
- let claims = live_kit_server::token::validate(&token, &self.secret_key)?;
+ let claims = live_kit_server::token::validate(token, &self.secret_key)?;
let room_name = claims.video.room.unwrap();
let identity = claims.sub.unwrap();
let mut server_rooms = self.rooms.lock();
@@ -363,7 +363,7 @@ impl TestServer {
}
fn is_track_muted(&self, token: &str, track_sid: &str) -> Option<bool> {
- let claims = live_kit_server::token::validate(&token, &self.secret_key).ok()?;
+ let claims = live_kit_server::token::validate(token, &self.secret_key).ok()?;
let room_name = claims.video.room.unwrap();
let mut server_rooms = self.rooms.lock();
@@ -419,7 +419,7 @@ impl TestServer {
.map(|track| {
Arc::new(RemoteAudioTrack {
server_track: track.clone(),
- room: Arc::downgrade(&client_room),
+ room: Arc::downgrade(client_room),
})
})
.collect())
@@ -842,6 +842,12 @@ pub struct MacOSDisplay {
),
}
+impl Default for MacOSDisplay {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl MacOSDisplay {
pub fn new() -> Self {
Self {
@@ -16,17 +16,14 @@ use crate::{
AnyNotification, AnyResponse, IoHandler, IoKind, RequestId, ResponseHandler, CONTENT_LEN_HEADER,
};
-const HEADER_DELIMITER: &'static [u8; 4] = b"\r\n\r\n";
+const HEADER_DELIMITER: &[u8; 4] = b"\r\n\r\n";
/// Handler for stdout of language server.
pub struct LspStdoutHandler {
pub(super) loop_handle: Task<Result<()>>,
pub(super) notifications_channel: UnboundedReceiver<AnyNotification>,
}
-pub(self) async fn read_headers<Stdout>(
- reader: &mut BufReader<Stdout>,
- buffer: &mut Vec<u8>,
-) -> Result<()>
+async fn read_headers<Stdout>(reader: &mut BufReader<Stdout>, buffer: &mut Vec<u8>) -> Result<()>
where
Stdout: AsyncRead + Unpin + Send + 'static,
{
@@ -9,7 +9,7 @@ use theme::LoadThemes;
use ui::prelude::*;
use ui::{div, WindowContext};
-const MARKDOWN_EXAMPLE: &'static str = r#"
+const MARKDOWN_EXAMPLE: &str = r#"
# Markdown Example Document
## Headings
@@ -9,7 +9,7 @@ use theme::LoadThemes;
use ui::div;
use ui::prelude::*;
-const MARKDOWN_EXAMPLE: &'static str = r#"
+const MARKDOWN_EXAMPLE: &str = r#"
this text should be selectable
wow so cool
@@ -260,7 +260,7 @@ impl ParsedMarkdown {
}
pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> {
- return &self.events;
+ &self.events
}
}
@@ -473,17 +473,15 @@ impl MarkdownElement {
cx.open_url(&pressed_link.destination_url);
}
}
- } else {
- if markdown.selection.pending {
- markdown.selection.pending = false;
- #[cfg(target_os = "linux")]
- {
- let text = rendered_text
- .text_for_range(markdown.selection.start..markdown.selection.end);
- cx.write_to_primary(ClipboardItem::new_string(text))
- }
- cx.notify();
+ } else if markdown.selection.pending {
+ markdown.selection.pending = false;
+ #[cfg(target_os = "linux")]
+ {
+ let text = rendered_text
+ .text_for_range(markdown.selection.start..markdown.selection.end);
+ cx.write_to_primary(ClipboardItem::new_string(text))
}
+ cx.notify();
}
}
});
@@ -97,7 +97,7 @@ pub fn parse_links_only(text: &str) -> Vec<(Range<usize>, MarkdownEvent)> {
start: 0,
end: text.len(),
};
- for link in finder.links(&text) {
+ for link in finder.links(text) {
let link_range = link.start()..link.end();
if link_range.start > text_range.start {
@@ -110,6 +110,12 @@ pub struct ParsedMarkdownTableRow {
pub children: Vec<ParsedMarkdownText>,
}
+impl Default for ParsedMarkdownTableRow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ParsedMarkdownTableRow {
pub fn new() -> Self {
Self {
@@ -90,9 +90,9 @@ impl<'a> MarkdownParser<'a> {
| Event::Start(Tag::Strong)
| Event::Start(Tag::Strikethrough)
| Event::Start(Tag::Image { link_type: _, dest_url: _, title: _, id: _ }) => {
- return true;
+ true
}
- _ => return false,
+ _ => false,
}
}
@@ -252,7 +252,7 @@ impl<'a> MarkdownParser<'a> {
let mut finder = linkify::LinkFinder::new();
finder.kinds(&[linkify::LinkKind::Url]);
let mut last_link_len = prev_len;
- for link in finder.links(&t) {
+ for link in finder.links(t) {
let start = link.start();
let end = link.end();
let range = (prev_len + start)..(prev_len + end);
@@ -415,10 +415,7 @@ impl<'a> MarkdownParser<'a> {
let mut body = vec![];
let mut current_row = vec![];
let mut in_header = true;
- let column_alignments = alignment
- .iter()
- .map(|a| Self::convert_alignment(a))
- .collect();
+ let column_alignments = alignment.iter().map(Self::convert_alignment).collect();
loop {
if self.eof() {
@@ -440,7 +437,7 @@ impl<'a> MarkdownParser<'a> {
}
Event::End(TagEnd::TableHead) | Event::End(TagEnd::TableRow) => {
self.cursor += 1;
- let new_row = std::mem::replace(&mut current_row, vec![]);
+ let new_row = std::mem::take(&mut current_row);
if in_header {
header.children = new_row;
in_header = false;
@@ -683,7 +680,7 @@ impl<'a> MarkdownParser<'a> {
let (current, _source_range) = self.current().unwrap();
match current {
Event::Text(text) => {
- code.push_str(&text);
+ code.push_str(text);
self.cursor += 1;
}
Event::End(TagEnd::CodeBlock) => {
@@ -113,7 +113,7 @@ pub fn render_parsed_markdown(
elements.push(render_markdown_block(child, &mut cx));
}
- return elements;
+ elements
}
pub fn render_markdown_block(block: &ParsedMarkdownElement, cx: &mut RenderContext) -> AnyElement {
@@ -595,7 +595,7 @@ impl MultiBuffer {
if start_excerpt.id == end_excerpt.id {
buffer_edits
.entry(start_excerpt.buffer_id)
- .or_insert(Vec::new())
+ .or_default()
.push(BufferEdit {
range: buffer_start..buffer_end,
new_text,
@@ -618,7 +618,7 @@ impl MultiBuffer {
..buffer_end;
buffer_edits
.entry(start_excerpt.buffer_id)
- .or_insert(Vec::new())
+ .or_default()
.push(BufferEdit {
range: start_excerpt_range,
new_text: new_text.clone(),
@@ -627,7 +627,7 @@ impl MultiBuffer {
});
buffer_edits
.entry(end_excerpt.buffer_id)
- .or_insert(Vec::new())
+ .or_default()
.push(BufferEdit {
range: end_excerpt_range,
new_text: new_text.clone(),
@@ -643,7 +643,7 @@ impl MultiBuffer {
}
buffer_edits
.entry(excerpt.buffer_id)
- .or_insert(Vec::new())
+ .or_default()
.push(BufferEdit {
range: excerpt.range.context.to_offset(&excerpt.buffer),
new_text: new_text.clone(),
@@ -844,7 +844,7 @@ impl MultiBuffer {
let mut cursor = snapshot.excerpts.cursor::<ExcerptSummary>();
for (buffer_id, buffer_transaction) in &transaction.buffer_transactions {
- let Some(buffer_state) = buffers.get(&buffer_id) else {
+ let Some(buffer_state) = buffers.get(buffer_id) else {
continue;
};
@@ -891,26 +891,24 @@ impl MultiBuffer {
buffer.update(cx, |buffer, _| {
buffer.merge_transactions(transaction, destination)
});
- } else {
- if let Some(transaction) = self.history.forget(transaction) {
- if let Some(destination) = self.history.transaction_mut(destination) {
- for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
- if let Some(destination_buffer_transaction_id) =
- destination.buffer_transactions.get(&buffer_id)
- {
- if let Some(state) = self.buffers.borrow().get(&buffer_id) {
- state.buffer.update(cx, |buffer, _| {
- buffer.merge_transactions(
- buffer_transaction_id,
- *destination_buffer_transaction_id,
- )
- });
- }
- } else {
- destination
- .buffer_transactions
- .insert(buffer_id, buffer_transaction_id);
+ } else if let Some(transaction) = self.history.forget(transaction) {
+ if let Some(destination) = self.history.transaction_mut(destination) {
+ for (buffer_id, buffer_transaction_id) in transaction.buffer_transactions {
+ if let Some(destination_buffer_transaction_id) =
+ destination.buffer_transactions.get(&buffer_id)
+ {
+ if let Some(state) = self.buffers.borrow().get(&buffer_id) {
+ state.buffer.update(cx, |buffer, _| {
+ buffer.merge_transactions(
+ buffer_transaction_id,
+ *destination_buffer_transaction_id,
+ )
+ });
}
+ } else {
+ destination
+ .buffer_transactions
+ .insert(buffer_id, buffer_transaction_id);
}
}
}
@@ -2202,10 +2200,8 @@ impl MultiBuffer {
if excerpt.locator <= Locator::min() {
panic!("invalid first excerpt locator {:?}", excerpt.locator);
}
- } else {
- if excerpt.locator <= excerpts[ix - 1].locator {
- panic!("excerpts are out-of-order: {:?}", excerpts);
- }
+ } else if excerpt.locator <= excerpts[ix - 1].locator {
+ panic!("excerpts are out-of-order: {:?}", excerpts);
}
}
@@ -2214,10 +2210,8 @@ impl MultiBuffer {
if entry.id.cmp(&ExcerptId::min(), &snapshot).is_le() {
panic!("invalid first excerpt id {:?}", entry.id);
}
- } else {
- if entry.id <= excerpt_ids[ix - 1].id {
- panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
- }
+ } else if entry.id <= excerpt_ids[ix - 1].id {
+ panic!("excerpt ids are out-of-order: {:?}", excerpt_ids);
}
}
}
@@ -3336,28 +3330,25 @@ impl MultiBufferSnapshot {
) -> impl Iterator<Item = Range<usize>> + 'a {
let range = range.start.to_offset(self)..range.end.to_offset(self);
self.excerpts_for_range(range.clone())
- .filter_map(move |(excerpt, excerpt_offset)| {
- redaction_enabled(excerpt.buffer.file()).then(move || {
- let excerpt_buffer_start =
- excerpt.range.context.start.to_offset(&excerpt.buffer);
+ .filter(move |&(excerpt, _)| redaction_enabled(excerpt.buffer.file()))
+ .flat_map(move |(excerpt, excerpt_offset)| {
+ let excerpt_buffer_start = excerpt.range.context.start.to_offset(&excerpt.buffer);
- excerpt
- .buffer
- .redacted_ranges(excerpt.range.context.clone())
- .map(move |mut redacted_range| {
- // Re-base onto the excerpts coordinates in the multibuffer
- redacted_range.start = excerpt_offset
- + redacted_range.start.saturating_sub(excerpt_buffer_start);
- redacted_range.end = excerpt_offset
- + redacted_range.end.saturating_sub(excerpt_buffer_start);
-
- redacted_range
- })
- .skip_while(move |redacted_range| redacted_range.end < range.start)
- .take_while(move |redacted_range| redacted_range.start < range.end)
- })
+ excerpt
+ .buffer
+ .redacted_ranges(excerpt.range.context.clone())
+ .map(move |mut redacted_range| {
+ // Re-base onto the excerpts coordinates in the multibuffer
+ redacted_range.start = excerpt_offset
+ + redacted_range.start.saturating_sub(excerpt_buffer_start);
+ redacted_range.end = excerpt_offset
+ + redacted_range.end.saturating_sub(excerpt_buffer_start);
+
+ redacted_range
+ })
+ .skip_while(move |redacted_range| redacted_range.end < range.start)
+ .take_while(move |redacted_range| redacted_range.start < range.end)
})
- .flatten()
}
pub fn runnable_ranges(
@@ -4467,9 +4458,9 @@ impl ExcerptId {
}
}
-impl Into<usize> for ExcerptId {
- fn into(self) -> usize {
- self.0
+impl From<ExcerptId> for usize {
+ fn from(val: ExcerptId) -> Self {
+ val.0
}
}
@@ -4758,7 +4749,6 @@ impl<'a> ReversedMultiBufferBytes<'a> {
self.excerpt_bytes = Some(excerpt_bytes);
}
}
- } else {
}
}
}
@@ -5842,7 +5832,7 @@ mod tests {
);
}
let snapshot = multibuffer.read(cx).read(cx);
- ids_to_remove.sort_unstable_by(|a, b| a.cmp(&b, &snapshot));
+ ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
drop(snapshot);
multibuffer.update(cx, |multibuffer, cx| {
multibuffer.remove_excerpts(ids_to_remove, cx)
@@ -6396,13 +6386,13 @@ mod tests {
}
fn validate_excerpts(
- actual: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
+ actual: &[(ExcerptId, BufferId, Range<Anchor>)],
expected: &Vec<(ExcerptId, BufferId, Range<Anchor>)>,
) {
assert_eq!(actual.len(), expected.len());
actual
- .into_iter()
+ .iter()
.zip(expected)
.map(|(actual, expected)| {
assert_eq!(actual.0, expected.0);
@@ -6437,7 +6427,7 @@ mod tests {
(
excerpt_id,
buffer.read(cx).remote_id(),
- map_range_from_excerpt(&snapshot, excerpt_id, &buffer.read(cx).snapshot(), range),
+ map_range_from_excerpt(snapshot, excerpt_id, &buffer.read(cx).snapshot(), range),
)
}
@@ -20,7 +20,7 @@ pub async fn extract_zip<R: AsyncRead + Unpin>(destination: &Path, reader: R) ->
std::fs::create_dir_all(&path)?;
} else {
let parent_dir = path.parent().expect("failed to get parent directory");
- std::fs::create_dir_all(&parent_dir)?;
+ std::fs::create_dir_all(parent_dir)?;
let mut file = smol::fs::File::create(&path).await?;
futures::io::copy(entry_reader, &mut file).await?;
}
@@ -82,11 +82,11 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let dst = dir.path();
- std::fs::write(&dst.join("test"), "Hello world.").unwrap();
- std::fs::create_dir_all(&dst.join("foo/bar")).unwrap();
- std::fs::write(&dst.join("foo/bar.txt"), "Foo bar.").unwrap();
- std::fs::write(&dst.join("foo/dar.md"), "Bar dar.").unwrap();
- std::fs::write(&dst.join("foo/bar/dar你好.txt"), "你好世界").unwrap();
+ std::fs::write(dst.join("test"), "Hello world.").unwrap();
+ std::fs::create_dir_all(dst.join("foo/bar")).unwrap();
+ std::fs::write(dst.join("foo/bar.txt"), "Foo bar.").unwrap();
+ std::fs::write(dst.join("foo/dar.md"), "Bar dar.").unwrap();
+ std::fs::write(dst.join("foo/bar/dar你好.txt"), "你好世界").unwrap();
dir
}
@@ -102,7 +102,7 @@ mod tests {
let zip_file = test_dir.path().join("test.zip");
smol::block_on(async {
- compress_zip(&test_dir.path(), &zip_file).await.unwrap();
+ compress_zip(test_dir.path(), &zip_file).await.unwrap();
let reader = read_archive(&zip_file).await;
let dir = tempfile::tempdir().unwrap();
@@ -72,7 +72,7 @@ pub trait NodeRuntime: Send + Sync {
async fn npm_package_installed_version(
&self,
- local_package_directory: &PathBuf,
+ local_package_directory: &Path,
name: &str,
) -> Result<Option<String>>;
@@ -80,7 +80,7 @@ pub trait NodeRuntime: Send + Sync {
&self,
package_name: &str,
local_executable_path: &Path,
- local_package_directory: &PathBuf,
+ local_package_directory: &Path,
latest_version: &str,
) -> bool {
// In the case of the local system not having the package installed,
@@ -102,7 +102,7 @@ pub trait NodeRuntime: Send + Sync {
let Some(installed_version) = Version::parse(&installed_version).log_err() else {
return true;
};
- let Some(latest_version) = Version::parse(&latest_version).log_err() else {
+ let Some(latest_version) = Version::parse(latest_version).log_err() else {
return true;
};
@@ -360,10 +360,10 @@ impl NodeRuntime for RealNodeRuntime {
async fn npm_package_installed_version(
&self,
- local_package_directory: &PathBuf,
+ local_package_directory: &Path,
name: &str,
) -> Result<Option<String>> {
- let mut package_json_path = local_package_directory.clone();
+ let mut package_json_path = local_package_directory.to_owned();
package_json_path.extend(["node_modules", name, "package.json"]);
let mut file = match fs::File::open(package_json_path).await {
@@ -394,7 +394,7 @@ impl NodeRuntime for RealNodeRuntime {
packages: &[(&str, &str)],
) -> Result<()> {
let packages: Vec<_> = packages
- .into_iter()
+ .iter()
.map(|(name, version)| format!("{name}@{version}"))
.collect();
@@ -448,7 +448,7 @@ impl NodeRuntime for FakeNodeRuntime {
async fn npm_package_installed_version(
&self,
- _local_package_directory: &PathBuf,
+ _local_package_directory: &Path,
name: &str,
) -> Result<Option<String>> {
unreachable!("Should not query npm package '{name}' for installed version")
@@ -29,7 +29,7 @@ pub fn toggle(editor: View<Editor>, _: &ToggleOutline, cx: &mut WindowContext) {
.buffer()
.read(cx)
.snapshot(cx)
- .outline(Some(&cx.theme().syntax()));
+ .outline(Some(cx.theme().syntax()));
if let Some((workspace, outline)) = editor.read(cx).workspace().zip(outline) {
workspace.update(cx, |workspace, cx| {
@@ -338,9 +338,9 @@ mod tests {
.unwrap();
let ensure_outline_view_contents =
|outline_view: &View<Picker<OutlineViewDelegate>>, cx: &mut VisualTestContext| {
- assert_eq!(query(&outline_view, cx), "");
+ assert_eq!(query(outline_view, cx), "");
assert_eq!(
- outline_names(&outline_view, cx),
+ outline_names(outline_view, cx),
vec![
"struct SingleLine",
"struct MultiLine",
@@ -155,7 +155,7 @@ impl SearchState {
.collect(),
highlight_search_match_tx,
_search_match_highlighter: cx.background_executor().spawn(async move {
- while let Some(highlight_arguments) = highlight_search_match_rx.recv().await.ok() {
+ while let Ok(highlight_arguments) = highlight_search_match_rx.recv().await {
let highlight_data = &highlight_arguments.search_data.highlights_data;
if highlight_data.get().is_some() {
continue;
@@ -220,7 +220,7 @@ impl SearchState {
}
}),
_search_match_notify: cx.spawn(|outline_panel, mut cx| async move {
- while let Some(()) = notify_rx.recv().await.ok() {
+ while let Ok(()) = notify_rx.recv().await {
let update_result = outline_panel.update(&mut cx, |_, cx| {
cx.notify();
});
@@ -400,7 +400,7 @@ impl SearchData {
match_range: &Range<editor::Anchor>,
multi_buffer_snapshot: &MultiBufferSnapshot,
) -> Self {
- let match_point_range = match_range.to_point(&multi_buffer_snapshot);
+ let match_point_range = match_range.to_point(multi_buffer_snapshot);
let context_left_border = multi_buffer_snapshot.clip_point(
language::Point::new(
match_point_range.start.row,
@@ -420,9 +420,9 @@ impl SearchData {
);
let context_anchor_range =
- (context_left_border..context_right_border).to_anchors(&multi_buffer_snapshot);
- let context_offset_range = context_anchor_range.to_offset(&multi_buffer_snapshot);
- let match_offset_range = match_range.to_offset(&multi_buffer_snapshot);
+ (context_left_border..context_right_border).to_anchors(multi_buffer_snapshot);
+ let context_offset_range = context_anchor_range.to_offset(multi_buffer_snapshot);
+ let match_offset_range = match_range.to_offset(multi_buffer_snapshot);
let mut search_match_indices = vec![
multi_buffer_snapshot.clip_offset(
@@ -485,7 +485,7 @@ impl SearchData {
Self {
highlights_data: Arc::default(),
search_match_indices,
- context_range: trimmed_row_offset_range.to_anchors(&multi_buffer_snapshot),
+ context_range: trimmed_row_offset_range.to_anchors(multi_buffer_snapshot),
context_text: trimmed_text,
truncated_left,
truncated_right,
@@ -898,8 +898,7 @@ impl OutlinePanel {
.iter()
.map(|cached_entry| &cached_entry.entry)
.skip_while(|entry| entry != &selected_entry)
- .skip(1)
- .next()
+ .nth(1)
.cloned()
}) {
self.select_entry(entry_to_select, true, cx);
@@ -915,8 +914,7 @@ impl OutlinePanel {
.rev()
.map(|cached_entry| &cached_entry.entry)
.skip_while(|entry| entry != &selected_entry)
- .skip(1)
- .next()
+ .nth(1)
.cloned()
}) {
self.select_entry(entry_to_select, true, cx);
@@ -975,11 +973,11 @@ impl OutlinePanel {
previous_entries.find(|entry| match entry {
PanelEntry::Fs(FsEntry::File(_, _, file_buffer_id, file_excerpts)) => {
file_buffer_id == excerpt_buffer_id
- && file_excerpts.contains(&excerpt_id)
+ && file_excerpts.contains(excerpt_id)
}
PanelEntry::Fs(FsEntry::ExternalFile(file_buffer_id, file_excerpts)) => {
file_buffer_id == excerpt_buffer_id
- && file_excerpts.contains(&excerpt_id)
+ && file_excerpts.contains(excerpt_id)
}
_ => false,
})
@@ -1012,7 +1010,7 @@ impl OutlinePanel {
}
fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
- if let Some(first_entry) = self.cached_entries.iter().next() {
+ if let Some(first_entry) = self.cached_entries.first() {
self.select_entry(first_entry.entry.clone(), true, cx);
}
}
@@ -1358,7 +1356,7 @@ impl OutlinePanel {
fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
if let Some(clipboard_text) = self
.selected_entry()
- .and_then(|entry| self.abs_path(&entry, cx))
+ .and_then(|entry| self.abs_path(entry, cx))
.map(|p| p.to_string_lossy().to_string())
{
cx.write_to_clipboard(ClipboardItem::new_string(clipboard_text));
@@ -1369,7 +1367,7 @@ impl OutlinePanel {
if let Some(clipboard_text) = self
.selected_entry()
.and_then(|entry| match entry {
- PanelEntry::Fs(entry) => self.relative_path(&entry, cx),
+ PanelEntry::Fs(entry) => self.relative_path(entry, cx),
PanelEntry::FoldedDirs(_, dirs) => dirs.last().map(|entry| entry.path.clone()),
PanelEntry::Search(_) | PanelEntry::Outline(..) => None,
})
@@ -1382,7 +1380,7 @@ impl OutlinePanel {
fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
if let Some(abs_path) = self
.selected_entry()
- .and_then(|entry| self.abs_path(&entry, cx))
+ .and_then(|entry| self.abs_path(entry, cx))
{
cx.reveal_path(&abs_path);
}
@@ -1390,7 +1388,7 @@ impl OutlinePanel {
fn open_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
let selected_entry = self.selected_entry();
- let abs_path = selected_entry.and_then(|entry| self.abs_path(&entry, cx));
+ let abs_path = selected_entry.and_then(|entry| self.abs_path(entry, cx));
let working_directory = if let (
Some(abs_path),
Some(PanelEntry::Fs(FsEntry::File(..) | FsEntry::ExternalFile(..))),
@@ -1517,13 +1515,12 @@ impl OutlinePanel {
);
let mut current_entry = buffer_entry;
loop {
- if current_entry.is_dir() {
- if outline_panel
+ if current_entry.is_dir()
+ && outline_panel
.collapsed_entries
.remove(&CollapsedEntry::Dir(worktree_id, current_entry.id))
- {
- dirs_to_expand.push(current_entry.id);
- }
+ {
+ dirs_to_expand.push(current_entry.id);
}
if traversal.back_to_parent() {
@@ -1630,7 +1627,7 @@ impl OutlinePanel {
rendered_outline.range, &rendered_outline.text,
))),
language::render_item(
- &rendered_outline,
+ rendered_outline,
string_match
.map(|string_match| string_match.ranges().collect::<Vec<_>>())
.unwrap_or_default(),
@@ -1882,7 +1879,7 @@ impl OutlinePanel {
name_ranges: search_data.search_match_indices.clone(),
body_range: Some(search_data.context_range.clone()),
},
- match_ranges.into_iter().cloned(),
+ match_ranges.iter().cloned(),
cx,
);
let truncated_contents_label = || Label::new(TRUNCATED_CONTEXT_MARK);
@@ -2161,7 +2158,7 @@ impl OutlinePanel {
if processed_external_buffers.insert(buffer_id) {
external_excerpts
.entry(buffer_id)
- .or_insert_with(|| Vec::new())
+ .or_insert_with(Vec::new)
.extend(excerpts);
}
}
@@ -2169,7 +2166,7 @@ impl OutlinePanel {
} else if processed_external_buffers.insert(buffer_id) {
external_excerpts
.entry(buffer_id)
- .or_insert_with(|| Vec::new())
+ .or_insert_with(Vec::new)
.extend(excerpts);
}
}
@@ -2249,7 +2246,7 @@ impl OutlinePanel {
} else {
if auto_fold_dirs {
let children = new_children_count
- .get(&worktree_id)
+ .get(worktree_id)
.and_then(|children_count| {
children_count.get(&dir_entry.path)
})
@@ -2262,10 +2259,10 @@ impl OutlinePanel {
.last()
.map(|(parent_dir_id, _)| {
new_unfolded_dirs
- .get(&worktree_id)
+ .get(worktree_id)
.map_or(true, |unfolded_dirs| {
unfolded_dirs
- .contains(&parent_dir_id)
+ .contains(parent_dir_id)
})
})
.unwrap_or(true))
@@ -2643,7 +2640,7 @@ impl OutlinePanel {
fn invalidate_outlines(&mut self, ids: &[ExcerptId]) {
self.outline_fetch_tasks.clear();
- let mut ids = ids.into_iter().collect::<HashSet<_>>();
+ let mut ids = ids.iter().collect::<HashSet<_>>();
for excerpts in self.excerpts.values_mut() {
ids.retain(|id| {
if let Some(excerpt) = excerpts.get_mut(id) {
@@ -2675,7 +2672,7 @@ impl OutlinePanel {
match fs_entry {
FsEntry::File(_, _, buffer_id, file_excerpts)
| FsEntry::ExternalFile(buffer_id, file_excerpts) => {
- let excerpts = self.excerpts.get(&buffer_id);
+ let excerpts = self.excerpts.get(buffer_id);
for &file_excerpt in file_excerpts {
if let Some(excerpt) = excerpts
.and_then(|excerpts| excerpts.get(&file_excerpt))
@@ -2918,8 +2915,7 @@ impl OutlinePanel {
&& parent_dirs
.iter()
.rev()
- .skip(folded_dirs.len() + 1)
- .next()
+ .nth(folded_dirs.len() + 1)
.map_or(true, |parent| parent.expanded);
if start_of_collapsed_dir_sequence
|| parent_expanded
@@ -3079,7 +3075,7 @@ impl OutlinePanel {
if let Some((buffer_id, entry_excerpts)) = excerpts_to_consider {
outline_panel.add_excerpt_entries(
buffer_id,
- &entry_excerpts,
+ entry_excerpts,
depth,
track_matches,
is_singleton,
@@ -3510,15 +3506,14 @@ impl OutlinePanel {
let new_search_entries = new_search_matches
.map(|(match_range, search_data)| {
- let previous_search_data = previous_search_matches
- .get(&(kind, &match_range))
- .map(|&data| data);
+ let previous_search_data =
+ previous_search_matches.get(&(kind, match_range)).copied();
let render_data = search_data
.get()
- .or_else(|| previous_search_data)
+ .or(previous_search_data)
.unwrap_or_else(|| {
search_data.get_or_init(|| {
- Arc::new(SearchData::new(&match_range, &multi_buffer_snapshot))
+ Arc::new(SearchData::new(match_range, &multi_buffer_snapshot))
})
});
if let (Some(previous_highlights), None) = (
@@ -3698,14 +3693,13 @@ fn cleanup_fs_entries_without_search_children(
}
PanelEntry::Search(_) | PanelEntry::Outline(_) => Vec::new(),
};
- if !collapsed_entries_to_check.is_empty() {
- if collapsed_entries_to_check
+ if !collapsed_entries_to_check.is_empty()
+ && collapsed_entries_to_check
.iter()
.any(|collapsed_entry| collapsed_entries.contains(collapsed_entry))
- {
- previous_entry = Some(&entry.entry);
- continue;
- }
+ {
+ previous_entry = Some(&entry.entry);
+ continue;
}
match_ids_to_remove.insert(id);
previous_entry = None;
@@ -3817,7 +3811,7 @@ impl Panel for OutlinePanel {
fn icon(&self, cx: &WindowContext) -> Option<IconName> {
OutlinePanelSettings::get_global(cx)
.button
- .then(|| IconName::ListTree)
+ .then_some(IconName::ListTree)
}
fn icon_tooltip(&self, _: &WindowContext) -> Option<&'static str> {
@@ -4107,7 +4101,7 @@ fn subscribe_for_editor_events(
);
}
EditorEvent::ExcerptsRemoved { ids } => {
- let mut ids = ids.into_iter().collect::<HashSet<_>>();
+ let mut ids = ids.iter().collect::<HashSet<_>>();
for excerpts in outline_panel.excerpts.values_mut() {
excerpts.retain(|excerpt_id, _| !ids.remove(excerpt_id));
if ids.is_empty() {
@@ -4227,9 +4221,9 @@ mod tests {
config.rs
search: param_names_for_lifetime_elision_hints: self"#;
let select_first_in_all_matches = |line_to_select: &str| {
- assert!(all_matches.contains(&line_to_select));
+ assert!(all_matches.contains(line_to_select));
all_matches.replacen(
- &line_to_select,
+ line_to_select,
&format!("{line_to_select}{SELECTED_MARKER}"),
1,
)
@@ -4490,9 +4484,7 @@ mod tests {
let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let outline_panel = window
- .update(cx, |_, cx| {
- cx.spawn(|workspace_handle, cx| OutlinePanel::load(workspace_handle, cx))
- })
+ .update(cx, |_, cx| cx.spawn(OutlinePanel::load))
.unwrap()
.await
.expect("Failed to load outline panel");
@@ -1,4 +1,3 @@
-use anyhow;
use gpui::Pixels;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -32,7 +32,7 @@ impl Head {
blur_handler: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
cx: &mut ViewContext<V>,
) -> Self {
- let head = cx.new_view(|cx| EmptyHead::new(cx));
+ let head = cx.new_view(EmptyHead::new);
cx.on_blur(&head.focus_handle(cx), blur_handler).detach();
Self::Empty(head)
}
@@ -91,11 +91,10 @@ impl BufferStore {
remote_id: Option<u64>,
cx: &mut ModelContext<Self>,
) -> Self {
- cx.subscribe(&worktree_store, |this, _, event, cx| match event {
- WorktreeStoreEvent::WorktreeAdded(worktree) => {
+ cx.subscribe(&worktree_store, |this, _, event, cx| {
+ if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
this.subscribe_to_worktree(worktree, cx);
}
- _ => {}
})
.detach();
@@ -711,7 +710,7 @@ impl BufferStore {
pub fn get_by_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Model<Buffer>> {
self.buffers().find_map(|buffer| {
let file = File::from_dyn(buffer.read(cx).file())?;
- if file.worktree_id(cx) == path.worktree_id && &file.path == &path.path {
+ if file.worktree_id(cx) == path.worktree_id && file.path == path.path {
Some(buffer)
} else {
None
@@ -885,11 +884,8 @@ impl BufferStore {
event: &BufferEvent,
cx: &mut ModelContext<Self>,
) {
- match event {
- BufferEvent::FileHandleChanged => {
- self.buffer_changed_file(buffer, cx);
- }
- _ => {}
+ if event == &BufferEvent::FileHandleChanged {
+ self.buffer_changed_file(buffer, cx);
}
}
@@ -204,7 +204,7 @@ impl Manager {
// we leave the room and return an error.
if let Some(this) = this.upgrade() {
log::info!("reconnection failed, disconnecting projects");
- let _ = this.update(&mut cx, |this, cx| this.connection_lost(cx))?;
+ this.update(&mut cx, |this, cx| this.connection_lost(cx))?;
}
Ok(())
@@ -8,6 +8,12 @@ pub struct DebouncedDelay<E: 'static> {
_phantom_data: PhantomData<E>,
}
+impl<E: 'static> Default for DebouncedDelay<E> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<E: 'static> DebouncedDelay<E> {
pub fn new() -> Self {
Self {
@@ -29,11 +29,10 @@ impl ProjectEnvironment {
cx: &mut AppContext,
) -> Model<Self> {
cx.new_model(|cx| {
- cx.subscribe(worktree_store, |this: &mut Self, _, event, _| match event {
- WorktreeStoreEvent::WorktreeRemoved(_, id) => {
+ cx.subscribe(worktree_store, |this: &mut Self, _, event, _| {
+ if let WorktreeStoreEvent::WorktreeRemoved(_, id) = event {
this.remove_worktree_environment(*id);
}
- _ => {}
})
.detach();
@@ -160,9 +159,9 @@ enum EnvironmentOrigin {
WorktreeShell,
}
-impl Into<String> for EnvironmentOrigin {
- fn into(self) -> String {
- match self {
+impl From<EnvironmentOrigin> for String {
+ fn from(val: EnvironmentOrigin) -> Self {
+ match val {
EnvironmentOrigin::Cli => "cli".into(),
EnvironmentOrigin::WorktreeShell => "worktree-shell".into(),
}
@@ -728,11 +728,10 @@ impl LspCommand for GetTypeDefinition {
type ProtoRequest = proto::GetTypeDefinition;
fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
- match &capabilities.server_capabilities.type_definition_provider {
- None => false,
- Some(lsp::TypeDefinitionProviderCapability::Simple(false)) => false,
- _ => true,
- }
+ !matches!(
+ &capabilities.server_capabilities.type_definition_provider,
+ None | Some(lsp::TypeDefinitionProviderCapability::Simple(false))
+ )
}
fn to_lsp(
@@ -1037,7 +1036,7 @@ impl LspCommand for GetReferences {
type ProtoRequest = proto::GetReferences;
fn status(&self) -> Option<String> {
- return Some("Finding references...".to_owned());
+ Some("Finding references...".to_owned())
}
fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
@@ -1469,7 +1468,7 @@ impl LspCommand for GetSignatureHelp {
let language = buffer.update(&mut cx, |buffer, _| buffer.language().cloned())?;
Ok(response
.signature_help
- .map(|proto_help| proto_to_lsp_signature(proto_help))
+ .map(proto_to_lsp_signature)
.and_then(|lsp_help| SignatureHelp::new(lsp_help, language)))
}
@@ -2835,7 +2834,7 @@ impl LspCommand for InlayHints {
proto::InlayHintsResponse {
hints: response
.into_iter()
- .map(|response_hint| InlayHints::project_to_proto_hint(response_hint))
+ .map(InlayHints::project_to_proto_hint)
.collect(),
version: serialize_version(buffer_version),
}
@@ -2883,7 +2882,7 @@ impl LspCommand for LinkedEditingRange {
if let LinkedEditingRangeServerCapabilities::Simple(false) = linked_editing_options {
return false;
}
- return true;
+ true
}
fn to_lsp(
@@ -2913,7 +2912,8 @@ impl LspCommand for LinkedEditingRange {
) -> Result<Vec<Range<Anchor>>> {
if let Some(lsp::LinkedEditingRanges { mut ranges, .. }) = message {
ranges.sort_by_key(|range| range.start);
- let ranges = buffer.read_with(&cx, |buffer, _| {
+
+ buffer.read_with(&cx, |buffer, _| {
ranges
.into_iter()
.map(|range| {
@@ -2923,9 +2923,7 @@ impl LspCommand for LinkedEditingRange {
buffer.anchor_before(start)..buffer.anchor_after(end)
})
.collect()
- });
-
- ranges
+ })
} else {
Ok(vec![])
}
@@ -117,9 +117,7 @@ pub fn lsp_to_proto_signature(lsp_help: lsp::SignatureHelp) -> proto::SignatureH
.into_iter()
.map(|signature| proto::SignatureInformation {
label: signature.label,
- documentation: signature
- .documentation
- .map(|documentation| lsp_to_proto_documentation(documentation)),
+ documentation: signature.documentation.map(lsp_to_proto_documentation),
parameters: signature
.parameters
.unwrap_or_default()
@@ -204,7 +202,7 @@ pub fn proto_to_lsp_signature(proto_help: proto::SignatureHelp) -> lsp::Signatur
}
fn proto_to_lsp_documentation(documentation: proto::Documentation) -> Option<lsp::Documentation> {
- let documentation = {
+ {
Some(match documentation.content? {
documentation::Content::Value(string) => lsp::Documentation::String(string),
documentation::Content::MarkupContent(markup) => {
@@ -221,8 +219,7 @@ fn proto_to_lsp_documentation(documentation: proto::Documentation) -> Option<lsp
})
}
})
- };
- documentation
+ }
}
#[cfg(test)]
@@ -270,11 +270,11 @@ impl LspStore {
}
BufferStoreEvent::BufferChangedFilePath { buffer, old_file } => {
if let Some(old_file) = File::from_dyn(old_file.as_ref()) {
- self.unregister_buffer_from_language_servers(&buffer, old_file, cx);
+ self.unregister_buffer_from_language_servers(buffer, old_file, cx);
}
- self.detect_language_for_buffer(&buffer, cx);
- self.register_buffer_with_language_servers(&buffer, cx);
+ self.detect_language_for_buffer(buffer, cx);
+ self.register_buffer_with_language_servers(buffer, cx);
}
BufferStoreEvent::BufferDropped(_) => {}
}
@@ -657,7 +657,7 @@ impl LspStore {
pub async fn execute_code_actions_on_servers(
this: &WeakModel<LspStore>,
- adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
+ adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)],
code_actions: Vec<lsp::CodeActionKind>,
buffer: &Model<Buffer>,
push_to_history: bool,
@@ -679,7 +679,7 @@ impl LspStore {
.await?;
for mut action in actions {
- Self::try_resolve_code_action(&language_server, &mut action)
+ Self::try_resolve_code_action(language_server, &mut action)
.await
.context("resolving a formatting code action")?;
@@ -733,14 +733,13 @@ impl LspStore {
lang_server: &LanguageServer,
action: &mut CodeAction,
) -> anyhow::Result<()> {
- if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
- if action.lsp_action.data.is_some()
- && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
- {
- action.lsp_action = lang_server
- .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
- .await?;
- }
+ if GetCodeActions::can_resolve_actions(&lang_server.capabilities())
+ && action.lsp_action.data.is_some()
+ && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
+ {
+ action.lsp_action = lang_server
+ .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
+ .await?;
}
anyhow::Ok(())
@@ -814,10 +813,7 @@ impl LspStore {
})
.await;
- if let Err(err) = result {
- // TODO: LSP ERROR
- return Err(err);
- }
+ result?;
return this.update(&mut cx, |this, _| {
this.last_workspace_edits_by_language_server
@@ -1157,7 +1153,7 @@ impl LspStore {
})
} else {
let all_actions_task = self.request_multiple_lsp_locally(
- &buffer_handle,
+ buffer_handle,
Some(range.start),
GetCodeActions {
range: range.clone(),
@@ -1280,7 +1276,7 @@ impl LspStore {
let buffer_id = buffer.read(cx).remote_id();
let buffer_snapshot = buffer.read(cx).snapshot();
- cx.spawn(move |this, mut cx| async move {
+ cx.spawn(move |this, cx| async move {
let mut did_resolve = false;
if let Some(client) = client {
for completion_index in completion_indices {
@@ -1326,7 +1322,7 @@ impl LspStore {
};
let server = this
- .read_with(&mut cx, |this, _| this.language_server_for_id(server_id))
+ .read_with(&cx, |this, _| this.language_server_for_id(server_id))
.ok()
.flatten();
let Some(server) = server else {
@@ -1776,7 +1772,7 @@ impl LspStore {
})
} else {
let all_actions_task = self.request_multiple_lsp_locally(
- &buffer,
+ buffer,
Some(position),
GetHover { position },
cx,
@@ -2785,7 +2781,7 @@ impl LspStore {
})
.collect::<FuturesUnordered<_>>();
- return cx.spawn(|_, _| async move {
+ cx.spawn(|_, _| async move {
let mut responses = Vec::with_capacity(response_results.len());
while let Some(response_result) = response_results.next().await {
if let Some(response) = response_result.log_err() {
@@ -2793,7 +2789,7 @@ impl LspStore {
}
}
responses
- });
+ })
}
async fn handle_lsp_command<T: LspCommand>(
@@ -3279,7 +3275,7 @@ impl LspStore {
if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
builders
.entry(tree.id())
- .or_insert_with(|| GlobSetBuilder::new())
+ .or_insert_with(GlobSetBuilder::new)
.add(glob);
}
return true;
@@ -3674,7 +3670,7 @@ impl LspStore {
let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
let completion = this
- .read_with(&mut cx, |this, _| {
+ .read_with(&cx, |this, _| {
let id = LanguageServerId(envelope.payload.language_server_id as usize);
let Some(server) = this.language_server_for_id(id) else {
return Err(anyhow!("No language server {id}"));
@@ -4875,9 +4871,12 @@ impl LspStore {
lsp_name: name.clone(),
};
- if let Ok(_) = this.update(&mut cx, |_, cx| {
- cx.emit(LspStoreEvent::LanguageServerPrompt(request));
- }) {
+ let did_update = this
+ .update(&mut cx, |_, cx| {
+ cx.emit(LspStoreEvent::LanguageServerPrompt(request));
+ })
+ .is_ok();
+ if did_update {
let response = rx.next().await;
Ok(response)
@@ -5240,7 +5239,7 @@ impl LspStore {
if file.worktree.read(cx).id() != key.0
|| !self
.languages
- .lsp_adapters(&language)
+ .lsp_adapters(language)
.iter()
.any(|a| a.name == key.1)
{
@@ -5272,7 +5271,7 @@ impl LspStore {
lsp::DidOpenTextDocumentParams {
text_document: lsp::TextDocumentItem::new(
uri,
- adapter.language_id(&language),
+ adapter.language_id(language),
version,
initial_snapshot.text(),
),
@@ -5498,24 +5497,32 @@ impl LspStore {
) {
let status = self.language_server_statuses.get(&server_id);
let server = self.language_servers.get(&server_id);
- if let Some((server, status)) = server.zip(status) {
- if let LanguageServerState::Running { server, .. } = server {
- for (token, progress) in &status.pending_work {
- if let Some(token_to_cancel) = token_to_cancel.as_ref() {
- if token != token_to_cancel {
- continue;
- }
- }
- if progress.is_cancellable {
- server
- .notify::<lsp::notification::WorkDoneProgressCancel>(
- WorkDoneProgressCancelParams {
- token: lsp::NumberOrString::String(token.clone()),
- },
- )
- .ok();
+ if let Some((LanguageServerState::Running { server, .. }, status)) = server.zip(status) {
+ for (token, progress) in &status.pending_work {
+ if let Some(token_to_cancel) = token_to_cancel.as_ref() {
+ if token != token_to_cancel {
+ continue;
}
}
+ if progress.is_cancellable {
+ server
+ .notify::<lsp::notification::WorkDoneProgressCancel>(
+ WorkDoneProgressCancelParams {
+ token: lsp::NumberOrString::String(token.clone()),
+ },
+ )
+ .ok();
+ }
+
+ if progress.is_cancellable {
+ server
+ .notify::<lsp::notification::WorkDoneProgressCancel>(
+ WorkDoneProgressCancelParams {
+ token: lsp::NumberOrString::String(token.clone()),
+ },
+ )
+ .ok();
+ }
}
}
}
@@ -5538,7 +5545,7 @@ impl LspStore {
if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
let worktree_id = file.worktree_id(cx);
self.languages
- .lsp_adapters(&language)
+ .lsp_adapters(language)
.iter()
.flat_map(|adapter| {
let key = (worktree_id, adapter.name.clone());
@@ -5956,7 +5963,7 @@ async fn populate_labels_for_completions(
.zip(labels.into_iter().chain(iter::repeat(None)))
{
let documentation = if let Some(docs) = &lsp_completion.documentation {
- Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
+ Some(prepare_completion_documentation(docs, language_registry, language.clone()).await)
} else {
None
};
@@ -6089,7 +6096,7 @@ impl DiagnosticSummary {
fn glob_literal_prefix(glob: &str) -> &str {
let mut literal_end = 0;
for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
- if part.contains(&['*', '?', '{', '}']) {
+ if part.contains(['*', '?', '{', '}']) {
break;
} else {
if i > 0 {
@@ -6173,7 +6180,7 @@ impl LspAdapterDelegate for ProjectLspAdapterDelegate {
async fn which(&self, command: &OsStr) -> Option<PathBuf> {
let worktree_abs_path = self.worktree.abs_path();
let shell_path = self.shell_env().await.get("PATH").cloned();
- which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
+ which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
}
#[cfg(target_os = "windows")]
@@ -6280,10 +6287,10 @@ async fn populate_labels_for_symbols(
fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
match server.capabilities().text_document_sync.as_ref()? {
- lsp::TextDocumentSyncCapability::Kind(kind) => match kind {
- &lsp::TextDocumentSyncKind::NONE => None,
- &lsp::TextDocumentSyncKind::FULL => Some(true),
- &lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
+ lsp::TextDocumentSyncCapability::Kind(kind) => match *kind {
+ lsp::TextDocumentSyncKind::NONE => None,
+ lsp::TextDocumentSyncKind::FULL => Some(true),
+ lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
_ => None,
},
lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
@@ -49,9 +49,7 @@ pub(super) async fn format_with_prettier(
.ok()?
.await;
- let Some((prettier_path, prettier_task)) = prettier_instance else {
- return None;
- };
+ let (prettier_path, prettier_task) = prettier_instance?;
let prettier_description = match prettier_path.as_ref() {
Some(path) => format!("prettier at {path:?}"),
@@ -262,10 +260,10 @@ fn start_default_prettier(
});
new_default_prettier
})?;
- return Ok(new_default_prettier);
+ Ok(new_default_prettier)
}
ControlFlow::Break(instance) => match instance.prettier {
- Some(instance) => return Ok(instance),
+ Some(instance) => Ok(instance),
None => {
let new_default_prettier = project.update(&mut cx, |project, cx| {
let new_default_prettier =
@@ -277,7 +275,7 @@ fn start_default_prettier(
});
new_default_prettier
})?;
- return Ok(new_default_prettier);
+ Ok(new_default_prettier)
}
},
}
@@ -900,7 +900,7 @@ impl Project {
dev_server_project_id: response
.payload
.dev_server_project_id
- .map(|dev_server_project_id| DevServerProjectId(dev_server_project_id)),
+ .map(DevServerProjectId),
search_history: Self::new_search_history(),
search_included_history: Self::new_search_history(),
search_excluded_history: Self::new_search_history(),
@@ -911,7 +911,7 @@ impl Project {
};
this.set_role(role, cx);
for worktree in worktrees {
- let _ = this.add_worktree(&worktree, cx);
+ this.add_worktree(&worktree, cx);
}
this
})?;
@@ -1194,7 +1194,7 @@ impl Project {
{
prettier_plugins_by_worktree
.entry(worktree)
- .or_insert_with(|| HashSet::default())
+ .or_insert_with(HashSet::default)
.extend(plugins.iter().cloned());
}
}
@@ -2090,7 +2090,7 @@ impl Project {
};
let buffer_file = buffer.read(cx).file().cloned();
let settings =
- language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
+ language_settings(Some(new_language), buffer_file.as_ref(), cx).clone();
let buffer_file = File::from_dyn(buffer_file.as_ref());
let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
if let Some(prettier_plugins) =
@@ -2233,7 +2233,7 @@ impl Project {
}
})
.collect();
- if paths.len() > 0 {
+ if !paths.is_empty() {
let request = self.client.request(proto::UpdateDevServerProject {
dev_server_project_id: dev_server_project_id.0,
paths,
@@ -2739,7 +2739,7 @@ impl Project {
.as_ref()
.zip(buffer_abs_path.as_ref());
- let prettier_settings = buffer.read_with(&mut cx, |buffer, cx| {
+ let prettier_settings = buffer.read_with(&cx, |buffer, cx| {
language_settings(buffer.language(), buffer.file(), cx)
.prettier
.clone()
@@ -2823,7 +2823,7 @@ impl Project {
FormatOnSave::List(formatters) => {
for formatter in formatters.as_ref() {
let diff = Self::perform_format(
- &formatter,
+ formatter,
server_and_buffer,
project.clone(),
buffer,
@@ -2968,10 +2968,10 @@ impl Project {
buffer: &Model<Buffer>,
buffer_abs_path: &Option<PathBuf>,
settings: &LanguageSettings,
- adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
+ adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)],
push_to_history: bool,
transaction: &mut ProjectTransaction,
- mut cx: &mut AsyncAppContext,
+ cx: &mut AsyncAppContext,
) -> Result<Option<FormatOperation>, anyhow::Error> {
let result = match formatter {
Formatter::LanguageServer { name } => {
@@ -2982,7 +2982,7 @@ impl Project {
.find_map(|(adapter, server)| {
adapter.name.0.as_ref().eq(name.as_str()).then_some(server)
})
- .unwrap_or_else(|| language_server)
+ .unwrap_or(language_server)
} else {
language_server
};
@@ -3004,36 +3004,28 @@ impl Project {
None
}
}
- Formatter::Prettier => {
- prettier_support::format_with_prettier(&project, buffer, &mut cx)
- .await
- .transpose()
- .ok()
- .flatten()
- }
+ Formatter::Prettier => prettier_support::format_with_prettier(&project, buffer, cx)
+ .await
+ .transpose()
+ .ok()
+ .flatten(),
Formatter::External { command, arguments } => {
let buffer_abs_path = buffer_abs_path.as_ref().map(|path| path.as_path());
- Self::format_via_external_command(
- buffer,
- buffer_abs_path,
- &command,
- &arguments,
- &mut cx,
- )
- .await
- .context(format!(
- "failed to format via external command {:?}",
- command
- ))?
- .map(FormatOperation::External)
+ Self::format_via_external_command(buffer, buffer_abs_path, command, arguments, cx)
+ .await
+ .context(format!(
+ "failed to format via external command {:?}",
+ command
+ ))?
+ .map(FormatOperation::External)
}
Formatter::CodeActions(code_actions) => {
- let code_actions = deserialize_code_actions(&code_actions);
+ let code_actions = deserialize_code_actions(code_actions);
let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
if !code_actions.is_empty() {
LspStore::execute_code_actions_on_servers(
&lsp_store,
- &adapters_and_servers,
+ adapters_and_servers,
code_actions,
buffer,
push_to_history,
@@ -3549,9 +3541,9 @@ impl Project {
) -> Receiver<Model<Buffer>> {
if self.is_local() {
let fs = self.fs.clone();
- return self.buffer_store.update(cx, |buffer_store, cx| {
+ self.buffer_store.update(cx, |buffer_store, cx| {
buffer_store.find_search_candidates(query, limit, fs, cx)
- });
+ })
} else {
self.search_for_candidate_buffers_remote(query, limit, cx)
}
@@ -3582,7 +3574,7 @@ impl Project {
}
}
}
- return true;
+ true
})
.collect::<Vec<_>>();
let (tx, rx) = smol::channel::unbounded();
@@ -3777,10 +3769,10 @@ impl Project {
.update(&mut cx, |worktree, _| {
let root_entry_path = &worktree.root_entry()?.path;
- let resolved = resolve_path(&root_entry_path, candidate);
+ let resolved = resolve_path(root_entry_path, candidate);
let stripped =
- resolved.strip_prefix(&root_entry_path).unwrap_or(&resolved);
+ resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
worktree.entry_for_path(stripped).map(|entry| {
ResolvedPath::ProjectPath(ProjectPath {
@@ -3878,7 +3870,7 @@ impl Project {
let fs = self.fs.clone();
let task_abs_path = abs_path.clone();
let tasks_file_rx =
- watch_config_file(&cx.background_executor(), fs, task_abs_path);
+ watch_config_file(cx.background_executor(), fs, task_abs_path);
task_inventory.add_source(
TaskSourceKind::Worktree {
id: remote_worktree_id,
@@ -3898,7 +3890,7 @@ impl Project {
let fs = self.fs.clone();
let task_abs_path = abs_path.clone();
let tasks_file_rx =
- watch_config_file(&cx.background_executor(), fs, task_abs_path);
+ watch_config_file(cx.background_executor(), fs, task_abs_path);
task_inventory.add_source(
TaskSourceKind::Worktree {
id: remote_worktree_id,
@@ -5191,11 +5183,11 @@ impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
impl EventEmitter<Event> for Project {}
-impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
- fn into(self) -> SettingsLocation<'a> {
+impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
+ fn from(val: &'a ProjectPath) -> Self {
SettingsLocation {
- worktree_id: self.worktree_id.to_usize(),
- path: self.path.as_ref(),
+ worktree_id: val.worktree_id.to_usize(),
+ path: val.path.as_ref(),
}
}
}
@@ -5347,7 +5339,7 @@ fn deserialize_location(
})
}
-pub fn sort_worktree_entries(entries: &mut Vec<Entry>) {
+pub fn sort_worktree_entries(entries: &mut [Entry]) {
entries.sort_by(|entry_a, entry_b| {
compare_paths(
(&entry_a.path, entry_a.is_file()),
@@ -25,6 +25,7 @@ pub struct ProjectSettings {
///
/// The following settings can be overridden for specific language servers:
/// - initialization_options
+ ///
/// To override settings for a language, add an entry for that language server's
/// name to the lsp value.
/// Default: null
@@ -335,16 +336,13 @@ impl SettingsObserver {
event: &WorktreeStoreEvent,
cx: &mut ModelContext<Self>,
) {
- match event {
- WorktreeStoreEvent::WorktreeAdded(worktree) => cx
- .subscribe(worktree, |this, worktree, event, cx| match event {
- worktree::Event::UpdatedEntries(changes) => {
- this.update_local_worktree_settings(&worktree, changes, cx)
- }
- _ => {}
- })
- .detach(),
- _ => {}
+ if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
+ cx.subscribe(worktree, |this, worktree, event, cx| {
+ if let worktree::Event::UpdatedEntries(changes) = event {
+ this.update_local_worktree_settings(&worktree, changes, cx)
+ }
+ })
+ .detach()
}
}
@@ -72,10 +72,10 @@ async fn test_symlinks(cx: &mut gpui::TestAppContext) {
}));
let root_link_path = dir.path().join("root_link");
- os::unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
+ os::unix::fs::symlink(dir.path().join("root"), &root_link_path).unwrap();
os::unix::fs::symlink(
- &dir.path().join("root/fennel"),
- &dir.path().join("root/finnochio"),
+ dir.path().join("root/fennel"),
+ dir.path().join("root/finnochio"),
)
.unwrap();
@@ -4699,7 +4699,7 @@ async fn test_multiple_language_server_hovers(cx: &mut gpui::TestAppContext) {
let mut fake_tsx_language_servers = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[0],
+ name: language_server_names[0],
capabilities: lsp::ServerCapabilities {
hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4710,7 +4710,7 @@ async fn test_multiple_language_server_hovers(cx: &mut gpui::TestAppContext) {
let _a = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[1],
+ name: language_server_names[1],
capabilities: lsp::ServerCapabilities {
hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4721,7 +4721,7 @@ async fn test_multiple_language_server_hovers(cx: &mut gpui::TestAppContext) {
let _b = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[2],
+ name: language_server_names[2],
capabilities: lsp::ServerCapabilities {
hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4732,7 +4732,7 @@ async fn test_multiple_language_server_hovers(cx: &mut gpui::TestAppContext) {
let _c = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[3],
+ name: language_server_names[3],
capabilities: lsp::ServerCapabilities {
hover_provider: None,
..lsp::ServerCapabilities::default()
@@ -4919,7 +4919,7 @@ async fn test_multiple_language_server_actions(cx: &mut gpui::TestAppContext) {
let mut fake_tsx_language_servers = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[0],
+ name: language_server_names[0],
capabilities: lsp::ServerCapabilities {
code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4930,7 +4930,7 @@ async fn test_multiple_language_server_actions(cx: &mut gpui::TestAppContext) {
let _a = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[1],
+ name: language_server_names[1],
capabilities: lsp::ServerCapabilities {
code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4941,7 +4941,7 @@ async fn test_multiple_language_server_actions(cx: &mut gpui::TestAppContext) {
let _b = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[2],
+ name: language_server_names[2],
capabilities: lsp::ServerCapabilities {
code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
..lsp::ServerCapabilities::default()
@@ -4952,7 +4952,7 @@ async fn test_multiple_language_server_actions(cx: &mut gpui::TestAppContext) {
let _c = language_registry.register_fake_lsp_adapter(
"tsx",
FakeLspAdapter {
- name: &language_server_names[3],
+ name: language_server_names[3],
capabilities: lsp::ServerCapabilities {
code_action_provider: None,
..lsp::ServerCapabilities::default()
@@ -89,7 +89,7 @@ impl SearchQuery {
let query = query.to_string();
let search = AhoCorasickBuilder::new()
.ascii_case_insensitive(!case_sensitive)
- .build(&[&query])?;
+ .build([&query])?;
let inner = SearchInputs {
query: query.into(),
files_to_exclude,
@@ -481,7 +481,8 @@ pub fn deserialize_path_matches(glob_set: &str) -> anyhow::Result<PathMatcher> {
let globs = glob_set
.split(',')
.map(str::trim)
- .filter_map(|glob_str| (!glob_str.is_empty()).then(|| glob_str.to_owned()))
+ .filter(|&glob_str| (!glob_str.is_empty()))
+ .map(|glob_str| glob_str.to_owned())
.collect::<Vec<_>>();
Ok(PathMatcher::new(&globs)?)
}
@@ -395,7 +395,7 @@ fn task_lru_comparator(
) -> cmp::Ordering {
lru_score_a
// First, display recently used templates above all.
- .cmp(&lru_score_b)
+ .cmp(lru_score_b)
// Then, ensure more specific sources are displayed first.
.then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
// After that, display first more specific tasks, using more template variables.
@@ -60,7 +60,7 @@ impl Project {
let worktree = self.worktrees(cx).next()?;
let worktree = worktree.read(cx);
if worktree.root_entry()?.is_dir() {
- return Some(worktree.abs_path().to_path_buf());
+ Some(worktree.abs_path().to_path_buf())
} else {
None
}
@@ -261,7 +261,7 @@ impl Project {
let venv_settings = settings.detect_venv.as_option()?;
venv_settings
.directories
- .into_iter()
+ .iter()
.map(|virtual_environment_name| abs_path.join(virtual_environment_name))
.find(|venv_path| {
let bin_path = venv_path.join("bin");
@@ -335,7 +335,7 @@ pub fn wrap_for_ssh(
}
}
if let Some(venv_directory) = venv_directory {
- if let Some(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()).ok() {
+ if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
env_changes.push_str(&format!("PATH={}:$PATH ", str));
}
}
@@ -349,7 +349,7 @@ pub fn wrap_for_ssh(
let (program, mut args) = match ssh_command {
SshCommand::DevServer(ssh_command) => {
- let mut args = shlex::split(&ssh_command).unwrap_or_default();
+ let mut args = shlex::split(ssh_command).unwrap_or_default();
let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
(program, args)
}
@@ -168,11 +168,10 @@ impl WorktreeStore {
}
let task = self.loading_worktrees.get(&path).unwrap().clone();
cx.background_executor().spawn(async move {
- let result = match task.await {
+ match task.await {
Ok(worktree) => Ok(worktree),
Err(err) => Err(anyhow!("{}", err)),
- };
- result
+ }
})
}
@@ -549,7 +548,7 @@ impl WorktreeStore {
drop(filters);
})
.detach();
- return matching_paths_rx;
+ matching_paths_rx
}
fn scan_ignored_dir<'a>(
@@ -562,7 +561,7 @@ impl WorktreeStore {
output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
) -> BoxFuture<'a, Result<()>> {
async move {
- let abs_path = snapshot.abs_path().join(&path);
+ let abs_path = snapshot.abs_path().join(path);
let Some(mut files) = fs
.read_dir(&abs_path)
.await
@@ -49,7 +49,7 @@ fn resolve_virtual(path: &Path) -> Option<Arc<Path>> {
continue;
}
}
- non_virtual_path.push(&components[i]);
+ non_virtual_path.push(components[i]);
i += 1;
}
@@ -85,7 +85,7 @@ impl YarnPathStore {
path
};
- let as_virtual = resolve_virtual(&path);
+ let as_virtual = resolve_virtual(path);
let Some(path) = as_virtual.or_else(|| is_zip.then(|| Arc::from(path))) else {
return Task::ready(None);
};
@@ -235,7 +235,7 @@ impl ProjectPanel {
})
.detach();
- let filename_editor = cx.new_view(|cx| Editor::single_line(cx));
+ let filename_editor = cx.new_view(Editor::single_line);
cx.subscribe(&filename_editor, |this, _, event, cx| match event {
editor::EditorEvent::BufferEdited
@@ -557,7 +557,7 @@ impl ProjectPanel {
if let Some(parent_path) = entry.path.parent() {
let snapshot = worktree.snapshot();
- let mut child_entries = snapshot.child_entries(&parent_path);
+ let mut child_entries = snapshot.child_entries(parent_path);
if let Some(child) = child_entries.next() {
if child_entries.next().is_none() {
return child.kind.is_dir();
@@ -758,7 +758,7 @@ impl ProjectPanel {
worktree_id,
entry_id: NEW_ENTRY_ID,
});
- let new_path = entry.path.join(&filename.trim_start_matches('/'));
+ let new_path = entry.path.join(filename.trim_start_matches('/'));
if path_already_exists(new_path.as_path()) {
return None;
}
@@ -1537,7 +1537,6 @@ impl ProjectPanel {
.move_worktree(worktree_id, destination_id, cx)
.log_err();
});
- return;
}
fn move_worktree_entry(
@@ -1652,8 +1651,7 @@ impl ProjectPanel {
let project = self.project.read(cx);
self.last_worktree_root_id = project
.visible_worktrees(cx)
- .rev()
- .next()
+ .next_back()
.and_then(|worktree| worktree.read(cx).root_entry())
.map(|entry| entry.id);
@@ -1794,10 +1792,7 @@ impl ProjectPanel {
entry_id: ProjectEntryId,
cx: &mut ViewContext<Self>,
) {
- let mut paths: Vec<Arc<Path>> = paths
- .into_iter()
- .map(|path| Arc::from(path.clone()))
- .collect();
+ let mut paths: Vec<Arc<Path>> = paths.iter().map(|path| Arc::from(path.clone())).collect();
let open_file_after_drop = paths.len() == 1 && paths[0].is_file();
@@ -1882,7 +1877,7 @@ impl ProjectPanel {
.clone();
for selection in selections.items() {
let new_path = self.create_paste_path(
- &selection,
+ selection,
(target_worktree.clone(), &target_entry),
cx,
)?;
@@ -1945,7 +1940,7 @@ impl ProjectPanel {
.collect()
});
for entry in visible_worktree_entries[entry_range].iter() {
- let status = git_status_setting.then(|| entry.git_status).flatten();
+ let status = git_status_setting.then_some(entry.git_status).flatten();
let is_expanded = expanded_entry_ids.binary_search(&entry.id).is_ok();
let icon = match entry.kind {
EntryKind::File => {
@@ -1965,7 +1960,7 @@ impl ProjectPanel {
};
let (depth, difference) =
- ProjectPanel::calculate_depth_and_difference(entry, &entries);
+ ProjectPanel::calculate_depth_and_difference(entry, entries);
let filename = match difference {
diff if diff > 1 => entry
@@ -2463,7 +2458,7 @@ impl ProjectPanel {
impl Render for ProjectPanel {
fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> impl IntoElement {
- let has_worktree = self.visible_entries.len() != 0;
+ let has_worktree = !self.visible_entries.is_empty();
let project = self.project.read(cx);
if has_worktree {
@@ -2693,7 +2688,7 @@ impl Panel for ProjectPanel {
fn icon(&self, cx: &WindowContext) -> Option<IconName> {
ProjectPanelSettings::get_global(cx)
.button
- .then(|| IconName::FileTree)
+ .then_some(IconName::FileTree)
}
fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
@@ -2796,9 +2791,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
assert_eq!(
visible_entries_as_strings(&panel, 0..50, cx),
&[
@@ -2895,9 +2888,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
assert_eq!(
visible_entries_as_strings(&panel, 0..50, cx),
&[
@@ -3011,9 +3002,7 @@ mod tests {
cx,
);
});
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
assert_eq!(
visible_entries_as_strings(&panel, 0..10, cx),
&[
@@ -3665,9 +3654,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root1".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
panel.update(cx, |panel, cx| {
panel.select_next(&Default::default(), cx);
@@ -3758,9 +3745,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
select_path(&panel, "root1/three.txt", cx);
panel.update(cx, |panel, cx| {
@@ -3856,9 +3841,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root1".as_ref(), "/root2".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
select_path(&panel, "root1/three.txt", cx);
panel.update(cx, |panel, cx| {
@@ -3975,9 +3958,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
select_path(&panel, "root/a", cx);
panel.update(cx, |panel, cx| {
@@ -4068,9 +4049,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/src".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
toggle_expand_dir(&panel, "src/test", cx);
select_path(&panel, "src/test/first.rs", cx);
@@ -4329,9 +4308,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/project_root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
panel.update(cx, |panel, cx| panel.open(&Open, cx));
cx.executor().run_until_parked();
@@ -4382,9 +4359,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/project_root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
panel.update(cx, |panel, cx| {
panel.collapse_all_entries(&CollapseAllEntries, cx)
@@ -4421,9 +4396,7 @@ mod tests {
let project = Project::test(fs, ["/root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
// Make a new buffer with no backing file
workspace
@@ -4503,9 +4476,7 @@ mod tests {
cx.update(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
cx.update(|cx| {
panel.update(cx, |this, cx| {
this.select_next(&Default::default(), cx);
@@ -4697,9 +4668,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/project_root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
assert_eq!(
visible_entries_as_strings(&panel, 0..20, cx),
@@ -4935,9 +4904,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/project_root".as_ref()], cx).await;
let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let cx = &mut VisualTestContext::from_window(*workspace, cx);
- let panel = workspace
- .update(cx, |workspace, cx| ProjectPanel::new(workspace, cx))
- .unwrap();
+ let panel = workspace.update(cx, ProjectPanel::new).unwrap();
assert_eq!(
visible_entries_as_strings(&panel, 0..20, cx),
@@ -1,4 +1,3 @@
-use anyhow;
use gpui::Pixels;
use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
@@ -316,7 +316,7 @@ fn session_state(session: View<Session>, cx: &WindowContext) -> ReplMenuState {
}
};
- let menu_state = match &session.kernel {
+ match &session.kernel {
Kernel::Restarting => ReplMenuState {
tooltip: format!("Restarting {}", kernel_name).into(),
icon_is_animating: true,
@@ -376,7 +376,5 @@ fn session_state(session: View<Session>, cx: &WindowContext) -> ReplMenuState {
status: KernelStatus::Shutdown,
..fill_fields()
},
- };
-
- menu_state
+ }
}
@@ -174,7 +174,7 @@ impl DevServerProjects {
) {
let mut path = self.project_path_input.read(cx).text(cx).trim().to_string();
- if path == "" {
+ if path.is_empty() {
return;
}
@@ -598,7 +598,7 @@ impl DevServerProjects {
})
.log_err();
- return Err(e);
+ Err(e)
}
}
}
@@ -735,7 +735,6 @@ impl DevServerProjects {
..Default::default()
});
cx.notify();
- return;
}
_ => {
self.mode = Mode::Default(None);
@@ -1308,12 +1307,10 @@ impl DevServerProjects {
} else {
"Create"
}
+ } else if dev_server_id.is_some() {
+ "Reconnect"
} else {
- if dev_server_id.is_some() {
- "Reconnect"
- } else {
- "Connect"
- }
+ "Connect"
},
)
.style(ButtonStyle::Filled)
@@ -136,8 +136,8 @@ impl RecentProjects {
let weak = cx.view().downgrade();
workspace.toggle_modal(cx, |cx| {
let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
- let modal = Self::new(delegate, 34., cx);
- modal
+
+ Self::new(delegate, 34., cx)
})
}
}
@@ -94,7 +94,7 @@ impl SshPrompt {
connection_string,
status_message: None,
prompt: None,
- editor: cx.new_view(|cx| Editor::single_line(cx)),
+ editor: cx.new_view(Editor::single_line),
}
}
@@ -120,10 +120,7 @@ impl ReleaseChannel {
/// Returns whether we want to poll for updates for this [`ReleaseChannel`]
pub fn poll_for_updates(&self) -> bool {
- match self {
- ReleaseChannel::Dev => false,
- _ => true,
- }
+ !matches!(self, ReleaseChannel::Dev)
}
/// Returns the display name for this [`ReleaseChannel`].
@@ -158,7 +158,7 @@ impl SshSession {
let mut remote_server_child = socket
.ssh_command(&format!(
"RUST_LOG={} {:?} run",
- std::env::var("RUST_LOG").unwrap_or(String::new()),
+ std::env::var("RUST_LOG").unwrap_or_default(),
remote_binary_path,
))
.spawn()
@@ -241,7 +241,7 @@ impl SshSession {
let line_ix = start_ix + ix;
let content = &stderr_buffer[start_ix..line_ix];
start_ix = line_ix + 1;
- if let Ok(record) = serde_json::from_slice::<LogRecord>(&content) {
+ if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
record.log(log::logger())
} else {
eprintln!("(remote) {}", String::from_utf8_lossy(content));
@@ -582,7 +582,7 @@ impl SshClientState {
let mut server_binary_exists = false;
if cfg!(not(debug_assertions)) {
if let Ok(installed_version) =
- run_cmd(self.socket.ssh_command(&dst_path).arg("version")).await
+ run_cmd(self.socket.ssh_command(dst_path).arg("version")).await
{
if installed_version.trim() == version.to_string() {
server_binary_exists = true;
@@ -621,7 +621,7 @@ impl SshClientState {
self.socket
.ssh_command("chmod")
.arg(format!("{:o}", server_mode))
- .arg(&dst_path),
+ .arg(dst_path),
)
.await?;
@@ -660,7 +660,7 @@ impl SshClientState {
.map(|port| vec!["-P".to_string(), port.to_string()])
.unwrap_or_default(),
)
- .arg(&src_path)
+ .arg(src_path)
.arg(&format!(
"{}:{}",
self.socket.connection_options.scp_url(),
@@ -27,7 +27,7 @@ fn main() {
env::set_var("RUST_BACKTRACE", "1");
env_logger::builder()
.format(|buf, record| {
- serde_json::to_writer(&mut *buf, &LogRecord::new(&record))?;
+ serde_json::to_writer(&mut *buf, &LogRecord::new(record))?;
buf.write_all(b"\n")?;
Ok(())
})
@@ -145,20 +145,14 @@ impl Kernel {
}
pub fn set_execution_state(&mut self, status: &ExecutionState) {
- match self {
- Kernel::RunningKernel(running_kernel) => {
- running_kernel.execution_state = status.clone();
- }
- _ => {}
+ if let Kernel::RunningKernel(running_kernel) = self {
+ running_kernel.execution_state = status.clone();
}
}
pub fn set_kernel_info(&mut self, kernel_info: &KernelInfoReply) {
- match self {
- Kernel::RunningKernel(running_kernel) => {
- running_kernel.kernel_info = Some(kernel_info.clone());
- }
- _ => {}
+ if let Kernel::RunningKernel(running_kernel) = self {
+ running_kernel.kernel_info = Some(kernel_info.clone());
}
}
@@ -76,10 +76,10 @@ fn rank_mime_type(mimetype: &MimeType) -> usize {
pub(crate) trait OutputContent {
fn clipboard_content(&self, cx: &WindowContext) -> Option<ClipboardItem>;
fn has_clipboard_content(&self, _cx: &WindowContext) -> bool {
- return false;
+ false
}
fn has_buffer_content(&self, _cx: &WindowContext) -> bool {
- return false;
+ false
}
fn buffer_content(&mut self, _cx: &mut WindowContext) -> Option<Model<Buffer>> {
None
@@ -184,10 +184,7 @@ impl Output {
multi_buffer
});
- let editor =
- Editor::for_multibuffer(multibuffer, None, false, cx);
-
- editor
+ Editor::for_multibuffer(multibuffer, None, false, cx)
}));
workspace
.update(cx, |workspace, cx| {
@@ -360,30 +357,9 @@ impl ExecutionView {
}
JupyterMessageContent::ExecuteReply(reply) => {
for payload in reply.payload.iter() {
- match payload {
- // Pager data comes in via `?` at the end of a statement in Python, used for showing documentation.
- // Some UI will show this as a popup. For ease of implementation, it's included as an output here.
- runtimelib::Payload::Page { data, .. } => {
- let output = Output::new(data, None, cx);
- self.outputs.push(output);
- }
-
- // There are other payloads that could be handled here, such as updating the input.
- // Below are the other payloads that _could_ be handled, but are not required for Zed.
-
- // Set next input adds text to the next cell. Not required to support.
- // However, this could be implemented by adding text to the buffer.
- // Trigger in python using `get_ipython().set_next_input("text")`
- //
- // runtimelib::Payload::SetNextInput { text, replace } => {},
-
- // Not likely to be used in the context of Zed, where someone could just open the buffer themselves
- // Python users can trigger this with the `%edit` magic command
- // runtimelib::Payload::EditMagic { filename, line_number } => {},
-
- // Ask the user if they want to exit the kernel. Not required to support.
- // runtimelib::Payload::AskExit { keepkernel } => {},
- _ => {}
+ if let runtimelib::Payload::Page { data, .. } = payload {
+ let output = Output::new(data, None, cx);
+ self.outputs.push(output);
}
}
cx.notify();
@@ -450,21 +426,17 @@ impl ExecutionView {
fn apply_terminal_text(&mut self, text: &str, cx: &mut ViewContext<Self>) -> Option<Output> {
if let Some(last_output) = self.outputs.last_mut() {
- match last_output {
- Output::Stream {
- content: last_stream,
- } => {
- // Don't need to add a new output, we already have a terminal output
- // and can just update the most recent terminal output
- last_stream.update(cx, |last_stream, cx| {
- last_stream.append_text(text, cx);
- cx.notify();
- });
- return None;
- }
- // A different output type is "in the way", so we need to create a new output,
- // which is the same as having no prior stream/terminal text
- _ => {}
+ if let Output::Stream {
+ content: last_stream,
+ } = last_output
+ {
+ // Don't need to add a new output, we already have a terminal output
+ // and can just update the most recent terminal output
+ last_stream.update(cx, |last_stream, cx| {
+ last_stream.append_text(text, cx);
+ cx.notify();
+ });
+ return None;
}
}
@@ -517,7 +489,7 @@ impl Render for ExecutionView {
.into_any_element(),
};
- if self.outputs.len() == 0 {
+ if self.outputs.is_empty() {
return v_flex()
.min_h(cx.line_height())
.justify_center()
@@ -50,12 +50,12 @@ impl ImageView {
id: gpui_image_data.id.0 as u64,
});
- return Ok(ImageView {
+ Ok(ImageView {
clipboard_image,
height,
width,
image: Arc::new(gpui_image_data),
- });
+ })
}
}
@@ -323,7 +323,7 @@ impl OutputContent for TerminalOutput {
}
fn buffer_content(&mut self, cx: &mut WindowContext) -> Option<Model<Buffer>> {
- if let Some(_) = self.full_buffer.as_ref() {
+ if self.full_buffer.as_ref().is_some() {
return self.full_buffer.clone();
}
@@ -73,7 +73,7 @@ pub struct TableView {
}
fn cell_content(row: &Value, field: &str) -> String {
- match row.get(&field) {
+ match row.get(field) {
Some(Value::String(s)) => s.clone(),
Some(Value::Number(n)) => n.to_string(),
Some(Value::Bool(b)) => b.to_string(),
@@ -116,7 +116,7 @@ impl TableView {
};
for row in data {
- let content = cell_content(&row, &field.name);
+ let content = cell_content(row, &field.name);
runs[0].len = content.len();
let cell_width = cx
.text_system()
@@ -130,7 +130,7 @@ impl TableView {
widths.push(width)
}
- let cached_clipboard_content = Self::create_clipboard_content(&table);
+ let cached_clipboard_content = Self::create_clipboard_content(table);
Self {
table: table.clone(),
@@ -272,7 +272,7 @@ impl Render for TableView {
let body = data
.iter()
- .map(|row| self.render_row(&self.table.schema, false, &row, cx));
+ .map(|row| self.render_row(&self.table.schema, false, row, cx));
v_flex()
.id("table")
@@ -242,7 +242,7 @@ impl Render for ReplSessionsPage {
for spec in kernel_specifications {
kernels_by_language
.entry(spec.kernelspec.language.clone())
- .or_insert_with(Vec::new)
+ .or_default()
.push(spec);
}
@@ -129,7 +129,7 @@ impl ReplStore {
// Top priority is the selected kernel
return runtime_specification.name.to_lowercase() == selected.to_lowercase();
}
- return false;
+ false
})
.cloned();
@@ -260,7 +260,7 @@ impl Session {
let stderr = kernel.process.stderr.take();
cx.spawn(|_session, mut _cx| async move {
- if let None = stderr {
+ if stderr.is_none() {
return;
}
let reader = BufReader::new(stderr.unwrap());
@@ -275,7 +275,7 @@ impl Session {
let stdout = kernel.process.stdout.take();
cx.spawn(|_session, mut _cx| async move {
- if let None = stdout {
+ if stdout.is_none() {
return;
}
let reader = BufReader::new(stdout.unwrap());
@@ -411,11 +411,8 @@ impl Session {
}
fn send(&mut self, message: JupyterMessage, _cx: &mut ViewContext<Self>) -> anyhow::Result<()> {
- match &mut self.kernel {
- Kernel::RunningKernel(kernel) => {
- kernel.request_tx.try_send(message).ok();
- }
- _ => {}
+ if let Kernel::RunningKernel(kernel) = &mut self.kernel {
+ kernel.request_tx.try_send(message).ok();
}
anyhow::Ok(())
@@ -571,7 +568,7 @@ impl Session {
cx.notify();
}
JupyterMessageContent::KernelInfoReply(reply) => {
- self.kernel.set_kernel_info(&reply);
+ self.kernel.set_kernel_info(reply);
cx.notify();
}
JupyterMessageContent::UpdateDisplayData(update) => {
@@ -592,8 +589,7 @@ impl Session {
}
if let Some(block) = self.blocks.get_mut(parent_message_id) {
- block.handle_message(&message, cx);
- return;
+ block.handle_message(message, cx);
}
}
@@ -584,10 +584,8 @@ impl<'a> Chunks<'a> {
if self.offset <= self.range.start || self.offset > self.range.end {
return false;
}
- } else {
- if self.offset < self.range.start || self.offset >= self.range.end {
- return false;
- }
+ } else if self.offset < self.range.start || self.offset >= self.range.end {
+ return false;
}
true
@@ -1110,10 +1108,10 @@ impl Chunk {
let mut grapheme_cursor = GraphemeCursor::new(column, bytes.len(), true);
loop {
- if line.is_char_boundary(column) {
- if grapheme_cursor.is_boundary(line, 0).unwrap_or(false) {
- break;
- }
+ if line.is_char_boundary(column)
+ && grapheme_cursor.is_boundary(line, 0).unwrap_or(false)
+ {
+ break;
}
match bias {
@@ -1713,7 +1711,7 @@ mod tests {
None
}
})
- .or_else(|| {
+ .or({
if offset > 0 && start_ix == 0 {
Some(0)
} else {
@@ -34,11 +34,11 @@ pub struct ConnectionId {
pub id: u32,
}
-impl Into<PeerId> for ConnectionId {
- fn into(self) -> PeerId {
+impl From<ConnectionId> for PeerId {
+ fn from(id: ConnectionId) -> Self {
PeerId {
- owner_id: self.owner_id,
- id: self.id,
+ owner_id: id.owner_id,
+ id: id.id,
}
}
}
@@ -478,7 +478,7 @@ impl Peer {
let (response, received_at, _barrier) =
rx.await.map_err(|_| anyhow!("connection was closed"))?;
if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
- return Err(RpcError::from_proto(&error, type_name));
+ return Err(RpcError::from_proto(error, type_name));
}
Ok((response, received_at))
}
@@ -516,7 +516,7 @@ impl Peer {
future::ready(match response {
Ok(response) => {
if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
- Some(Err(RpcError::from_proto(&error, T::NAME)))
+ Some(Err(RpcError::from_proto(error, T::NAME)))
} else if let Some(proto::envelope::Payload::EndStream(_)) =
&response.payload
{
@@ -122,7 +122,7 @@ impl BufferSearchBar {
};
EditorElement::new(
- &editor,
+ editor,
EditorStyle {
background: cx.theme().colors().editor_background,
local_player: cx.theme().players().local(),
@@ -498,10 +498,10 @@ impl BufferSearchBar {
}
pub fn new(cx: &mut ViewContext<Self>) -> Self {
- let query_editor = cx.new_view(|cx| Editor::single_line(cx));
+ let query_editor = cx.new_view(Editor::single_line);
cx.subscribe(&query_editor, Self::on_query_editor_event)
.detach();
- let replacement_editor = cx.new_view(|cx| Editor::single_line(cx));
+ let replacement_editor = cx.new_view(Editor::single_line);
cx.subscribe(&replacement_editor, Self::on_replacement_editor_event)
.detach();
@@ -784,13 +784,12 @@ impl BufferSearchBar {
.filter(|matches| !matches.is_empty())
{
// If 'wrapscan' is disabled, searches do not wrap around the end of the file.
- if !EditorSettings::get_global(cx).search_wrap {
- if (direction == Direction::Next && index + count >= matches.len())
- || (direction == Direction::Prev && index < count)
- {
- crate::show_no_more_matches(cx);
- return;
- }
+ if !EditorSettings::get_global(cx).search_wrap
+ && ((direction == Direction::Next && index + count >= matches.len())
+ || (direction == Direction::Prev && index < count))
+ {
+ crate::show_no_more_matches(cx);
+ return;
}
let new_match_index = searchable_item
.match_index_for_direction(matches, index, direction, count, cx);
@@ -808,7 +807,7 @@ impl BufferSearchBar {
.searchable_items_with_matches
.get(&searchable_item.downgrade())
{
- if matches.len() == 0 {
+ if matches.is_empty() {
return;
}
let new_match_index = matches.len() - 1;
@@ -1100,7 +1099,7 @@ impl BufferSearchBar {
cx.focus(handle);
}
fn toggle_replace(&mut self, _: &ToggleReplace, cx: &mut ViewContext<Self>) {
- if let Some(_) = &self.active_searchable_item {
+ if self.active_searchable_item.is_some() {
self.replace_enabled = !self.replace_enabled;
let handle = if self.replace_enabled {
self.replacement_editor.focus_handle(cx)
@@ -1708,7 +1707,7 @@ mod tests {
let last_match_selections = window
.update(cx, |_, cx| {
assert!(
- editor.read(cx).is_focused(&cx),
+ editor.read(cx).is_focused(cx),
"Should still have editor focused after SelectPrevMatch"
);
@@ -234,13 +234,13 @@ impl ProjectSearch {
.search_history_mut(SearchInputKind::Query)
.add(&mut self.search_history_cursor, query.as_str().to_string());
let included = query.as_inner().files_to_include().sources().join(",");
- if included.len() > 0 {
+ if !included.is_empty() {
project
.search_history_mut(SearchInputKind::Include)
.add(&mut self.search_included_history_cursor, included);
}
let excluded = query.as_inner().files_to_exclude().sources().join(",");
- if excluded.len() > 0 {
+ if !excluded.is_empty() {
project
.search_history_mut(SearchInputKind::Exclude)
.add(&mut self.search_excluded_history_cursor, excluded);
@@ -692,20 +692,16 @@ impl ProjectSearchView {
// Subscribe to query_editor in order to reraise editor events for workspace item activation purposes
subscriptions.push(
cx.subscribe(&query_editor, |this, _, event: &EditorEvent, cx| {
- match event {
- EditorEvent::Edited { .. } => {
- if EditorSettings::get_global(cx).use_smartcase_search {
- let query = this.search_query_text(cx);
- if !query.is_empty() {
- if this.search_options.contains(SearchOptions::CASE_SENSITIVE)
- != is_contains_uppercase(&query)
- {
- this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
- }
- }
+ if let EditorEvent::Edited { .. } = event {
+ if EditorSettings::get_global(cx).use_smartcase_search {
+ let query = this.search_query_text(cx);
+ if !query.is_empty()
+ && this.search_options.contains(SearchOptions::CASE_SENSITIVE)
+ != is_contains_uppercase(&query)
+ {
+ this.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx);
}
}
- _ => {}
}
cx.emit(ViewEvent::EditorEvent(event.clone()))
}),
@@ -904,11 +900,7 @@ impl ProjectSearchView {
.0
.get(&workspace.project().downgrade());
- let settings = if let Some(settings) = settings {
- Some(settings.clone())
- } else {
- None
- };
+ let settings = settings.cloned();
let weak_workspace = cx.view().downgrade();
@@ -1075,13 +1067,12 @@ impl ProjectSearchView {
if let Some(index) = self.active_match_index {
let match_ranges = self.model.read(cx).match_ranges.clone();
- if !EditorSettings::get_global(cx).search_wrap {
- if (direction == Direction::Next && index + 1 >= match_ranges.len())
- || (direction == Direction::Prev && index == 0)
- {
- crate::show_no_more_matches(cx);
- return;
- }
+ if !EditorSettings::get_global(cx).search_wrap
+ && ((direction == Direction::Next && index + 1 >= match_ranges.len())
+ || (direction == Direction::Prev && index == 0))
+ {
+ crate::show_no_more_matches(cx);
+ return;
}
let new_index = self.results_editor.update(cx, |editor, cx| {
@@ -1109,14 +1100,12 @@ impl ProjectSearchView {
fn set_query(&mut self, query: &str, cx: &mut ViewContext<Self>) {
self.set_search_editor(SearchInputKind::Query, query, cx);
- if EditorSettings::get_global(cx).use_smartcase_search {
- if !query.is_empty() {
- if self.search_options.contains(SearchOptions::CASE_SENSITIVE)
- != is_contains_uppercase(query)
- {
- self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
- }
- }
+ if EditorSettings::get_global(cx).use_smartcase_search
+ && !query.is_empty()
+ && self.search_options.contains(SearchOptions::CASE_SENSITIVE)
+ != is_contains_uppercase(query)
+ {
+ self.toggle_search_option(SearchOptions::CASE_SENSITIVE, cx)
}
}
@@ -1258,7 +1247,7 @@ impl ProjectSearchView {
&& !self.model.read(cx).match_ranges.is_empty()
{
cx.stop_propagation();
- return self.focus_results_editor(cx);
+ self.focus_results_editor(cx)
}
}
@@ -1268,6 +1257,12 @@ impl ProjectSearchView {
}
}
+impl Default for ProjectSearchBar {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ProjectSearchBar {
pub fn new() -> Self {
Self {
@@ -1498,7 +1493,7 @@ impl ProjectSearchBar {
.project
.read(cx)
.search_history(kind)
- .current(&search_view.model.read(cx).cursor(kind))
+ .current(search_view.model.read(cx).cursor(kind))
.map(str::to_string)
{
search_view.set_search_editor(kind, &new_query, cx);
@@ -1511,7 +1506,7 @@ impl ProjectSearchBar {
project.update(cx, |project, _| {
project
.search_history_mut(kind)
- .previous(&mut model.cursor_mut(kind))
+ .previous(model.cursor_mut(kind))
.map(str::to_string)
})
}) {
@@ -1557,7 +1552,7 @@ impl ProjectSearchBar {
};
EditorElement::new(
- &editor,
+ editor,
EditorStyle {
background: cx.theme().colors().editor_background,
local_player: cx.theme().players().local(),
@@ -3115,7 +3110,7 @@ pub mod tests {
let search_bar_2 = window.build_view(cx, |_| ProjectSearchBar::new());
assert_eq!(panes.len(), 1);
- let first_pane = panes.get(0).cloned().unwrap();
+ let first_pane = panes.first().cloned().unwrap();
assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
window
.update(cx, |workspace, cx| {
@@ -3327,7 +3322,7 @@ pub mod tests {
.update(cx, |this, _| this.panes().to_owned())
.unwrap();
assert_eq!(panes.len(), 1);
- let first_pane = panes.get(0).cloned().unwrap();
+ let first_pane = panes.first().cloned().unwrap();
assert_eq!(cx.update(|cx| first_pane.read(cx).items_len()), 0);
window
.update(cx, |workspace, cx| {
@@ -51,7 +51,7 @@ fn syntactic_ranges(
let outline = grammar.outline_config.as_ref()?;
let tree = with_parser(|parser| {
parser.set_language(&grammar.ts_language).log_err()?;
- parser.parse(&text, None)
+ parser.parse(text, None)
});
let Some(tree) = tree else {
@@ -41,7 +41,7 @@ impl EmbeddingProvider for OllamaEmbeddingProvider {
OllamaEmbeddingModel::MxbaiEmbedLarge => "mxbai-embed-large",
};
- futures::future::try_join_all(texts.into_iter().map(|to_embed| {
+ futures::future::try_join_all(texts.iter().map(|to_embed| {
let request = OllamaEmbeddingRequest {
model: model.to_string(),
prompt: to_embed.text.to_string(),
@@ -1047,7 +1047,7 @@ mod tests {
use std::{future, path::Path, sync::Arc};
fn init_test(cx: &mut TestAppContext) {
- _ = cx.update(|cx| {
+ cx.update(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
language::init(cx);
@@ -1068,10 +1068,10 @@ mod tests {
batch_size: usize,
compute_embedding: impl 'static + Fn(&str) -> Result<Embedding> + Send + Sync,
) -> Self {
- return Self {
+ Self {
batch_size,
compute_embedding: Box::new(compute_embedding),
- };
+ }
}
}
@@ -11,12 +11,12 @@ pub struct Session {
old_window_ids: Option<Vec<WindowId>>,
}
-const SESSION_ID_KEY: &'static str = "session_id";
-const SESSION_WINDOW_STACK_KEY: &'static str = "session_window_stack";
+const SESSION_ID_KEY: &str = "session_id";
+const SESSION_WINDOW_STACK_KEY: &str = "session_window_stack";
impl Session {
pub async fn new() -> Self {
- let old_session_id = KEY_VALUE_STORE.read_kvp(&SESSION_ID_KEY).ok().flatten();
+ let old_session_id = KEY_VALUE_STORE.read_kvp(SESSION_ID_KEY).ok().flatten();
let session_id = Uuid::new_v4().to_string();
@@ -26,7 +26,7 @@ impl Session {
.log_err();
let old_window_ids = KEY_VALUE_STORE
- .read_kvp(&SESSION_WINDOW_STACK_KEY)
+ .read_kvp(SESSION_WINDOW_STACK_KEY)
.ok()
.flatten()
.and_then(|json| serde_json::from_str::<Vec<u64>>(&json).ok())
@@ -36,16 +36,15 @@ impl KeymapBlock {
#[serde(transparent)]
pub struct KeymapAction(Value);
-impl ToString for KeymapAction {
- fn to_string(&self) -> String {
+impl std::fmt::Display for KeymapAction {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
- Value::String(s) => s.clone(),
- Value::Array(arr) => arr
- .iter()
- .map(|v| v.to_string())
- .collect::<Vec<_>>()
- .join(", "),
- _ => self.0.to_string(),
+ Value::String(s) => write!(f, "{}", s),
+ Value::Array(arr) => {
+ let strings: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
+ write!(f, "{}", strings.join(", "))
+ }
+ _ => write!(f, "{}", self.0),
}
}
}
@@ -926,7 +926,7 @@ fn update_value_in_json_text<'a>(
}
} else if key_path
.last()
- .map_or(false, |key| preserved_keys.contains(&key))
+ .map_or(false, |key| preserved_keys.contains(key))
|| old_value != new_value
{
let mut new_value = new_value.clone();
@@ -351,13 +351,7 @@ impl EditableSettingControl for UiFontLigaturesControl {
let mut features = settings
.ui_font_features
.as_ref()
- .map(|features| {
- features
- .tag_value_list()
- .into_iter()
- .cloned()
- .collect::<Vec<_>>()
- })
+ .map(|features| features.tag_value_list().to_vec())
.unwrap_or_default();
if let Some(calt_index) = features.iter().position(|(tag, _)| tag == "calt") {
@@ -182,7 +182,7 @@ impl SnippetProvider {
) -> Vec<Arc<Snippet>> {
let mut user_snippets: Vec<_> = self
.snippets
- .get(&language)
+ .get(language)
.cloned()
.unwrap_or_default()
.into_iter()
@@ -22,8 +22,7 @@ type WriteQueueConstructor = Box<dyn 'static + Send + FnMut() -> WriteQueue>;
/// and have a single worker thread per db file. This means many thread safe connections
/// (possibly with different migrations) could all be communicating with the same background
/// thread.
-static QUEUES: LazyLock<RwLock<HashMap<Arc<str>, WriteQueue>>> =
- LazyLock::new(|| Default::default());
+static QUEUES: LazyLock<RwLock<HashMap<Arc<str>, WriteQueue>>> = LazyLock::new(Default::default);
/// Thread safe connection to a given database file or in memory db. This can be cloned, shared, static,
/// whatever. It derefs to a synchronous connection by thread that is read only. A write capable connection
@@ -184,6 +184,12 @@ pub struct StorySection {
children: SmallVec<[AnyElement; 2]>,
}
+impl Default for StorySection {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl StorySection {
pub fn new() -> Self {
Self {
@@ -19,7 +19,7 @@ impl AssetSource for Assets {
Self::get(path)
.map(|f| f.data)
.ok_or_else(|| anyhow!("could not find asset at path \"{}\"", path))
- .map(|data| Some(data))
+ .map(Some)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
@@ -986,7 +986,7 @@ mod tests {
}
if before_start {
- assert_eq!(cursor.next_item(), reference_items.get(0));
+ assert_eq!(cursor.next_item(), reference_items.first());
} else if pos + 1 < reference_items.len() {
assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]);
} else {
@@ -365,7 +365,7 @@ mod tests {
let result = map
.iter_from(&"ba")
- .take_while(|(key, _)| key.starts_with(&"ba"))
+ .take_while(|(key, _)| key.starts_with("ba"))
.collect::<Vec<_>>();
assert_eq!(result.len(), 2);
@@ -374,7 +374,7 @@ mod tests {
let result = map
.iter_from(&"c")
- .take_while(|(key, _)| key.starts_with(&"c"))
+ .take_while(|(key, _)| key.starts_with("c"))
.collect::<Vec<_>>();
assert_eq!(result.len(), 1);
@@ -411,7 +411,7 @@ mod tests {
impl MapSeekTarget<PathBuf> for PathDescendants<'_> {
fn cmp_cursor(&self, key: &PathBuf) -> Ordering {
- if key.starts_with(&self.0) {
+ if key.starts_with(self.0) {
Ordering::Greater
} else {
self.0.cmp(key)
@@ -307,7 +307,7 @@ impl SupermavenAgent {
break;
}
}
- return anyhow::Ok(());
+ anyhow::Ok(())
}
})
.detach();
@@ -355,7 +355,7 @@ impl SupermavenAgent {
let Some(line) = line.strip_prefix(MESSAGE_PREFIX) else {
continue;
};
- let Some(message) = serde_json::from_str::<SupermavenMessage>(&line)
+ let Some(message) = serde_json::from_str::<SupermavenMessage>(line)
.with_context(|| format!("failed to deserialize line from stdout: {:?}", line))
.log_err()
else {
@@ -119,15 +119,13 @@ impl InlineCompletionProvider for SupermavenCompletionProvider {
should_report_inline_completion_event: bool,
_cx: &mut ModelContext<Self>,
) {
- if should_report_inline_completion_event {
- if self.completion_id.is_some() {
- if let Some(telemetry) = self.telemetry.as_ref() {
- telemetry.report_inline_completion_event(
- Self::name().to_string(),
- false,
- self.file_extension.clone(),
- );
- }
+ if should_report_inline_completion_event && self.completion_id.is_some() {
+ if let Some(telemetry) = self.telemetry.as_ref() {
+ telemetry.report_inline_completion_event(
+ Self::name().to_string(),
+ false,
+ self.file_extension.clone(),
+ );
}
}
@@ -163,7 +161,7 @@ impl InlineCompletionProvider for SupermavenCompletionProvider {
}
fn trim_to_end_of_line_unless_leading_newline(text: &str) -> &str {
- if has_leading_newline(&text) {
+ if has_leading_newline(text) {
text
} else if let Some(i) = text.find('\n') {
&text[..i]
@@ -1,6 +1,6 @@
use anyhow::{anyhow, Context, Result};
use futures::io::BufReader;
-use futures::{AsyncReadExt, Future};
+use futures::AsyncReadExt;
use http_client::{AsyncBody, HttpClient, Request as HttpRequest};
use paths::supermaven_dir;
use serde::{Deserialize, Serialize};
@@ -225,71 +225,67 @@ pub async fn has_version(version_path: &Path) -> bool {
.map_or(false, |m| m.is_file())
}
-pub fn get_supermaven_agent_path(
- client: Arc<dyn HttpClient>,
-) -> impl Future<Output = Result<PathBuf>> {
- async move {
- fs::create_dir_all(supermaven_dir())
- .await
- .with_context(|| {
- format!(
- "Could not create Supermaven Agent Directory at {:?}",
- supermaven_dir()
- )
- })?;
-
- let platform = match std::env::consts::OS {
- "macos" => "darwin",
- "windows" => "windows",
- "linux" => "linux",
- _ => return Err(anyhow!("unsupported platform")),
- };
-
- let arch = match std::env::consts::ARCH {
- "x86_64" => "amd64",
- "aarch64" => "arm64",
- _ => return Err(anyhow!("unsupported architecture")),
- };
-
- let download_info = latest_release(client.clone(), platform, arch).await?;
-
- let binary_path = version_path(download_info.version);
+pub async fn get_supermaven_agent_path(client: Arc<dyn HttpClient>) -> Result<PathBuf> {
+ fs::create_dir_all(supermaven_dir())
+ .await
+ .with_context(|| {
+ format!(
+ "Could not create Supermaven Agent Directory at {:?}",
+ supermaven_dir()
+ )
+ })?;
+
+ let platform = match std::env::consts::OS {
+ "macos" => "darwin",
+ "windows" => "windows",
+ "linux" => "linux",
+ _ => return Err(anyhow!("unsupported platform")),
+ };
+
+ let arch = match std::env::consts::ARCH {
+ "x86_64" => "amd64",
+ "aarch64" => "arm64",
+ _ => return Err(anyhow!("unsupported architecture")),
+ };
+
+ let download_info = latest_release(client.clone(), platform, arch).await?;
+
+ let binary_path = version_path(download_info.version);
+
+ if has_version(&binary_path).await {
+ return Ok(binary_path);
+ }
- if has_version(&binary_path).await {
- return Ok(binary_path);
- }
+ let request = HttpRequest::get(&download_info.download_url);
- let request = HttpRequest::get(&download_info.download_url);
+ let mut response = client
+ .send(request.body(AsyncBody::default())?)
+ .await
+ .with_context(|| "Unable to download Supermaven Agent".to_string())?;
- let mut response = client
- .send(request.body(AsyncBody::default())?)
- .await
- .with_context(|| "Unable to download Supermaven Agent".to_string())?;
+ let mut file = File::create(&binary_path)
+ .await
+ .with_context(|| format!("Unable to create file at {:?}", binary_path))?;
- let mut file = File::create(&binary_path)
- .await
- .with_context(|| format!("Unable to create file at {:?}", binary_path))?;
+ futures::io::copy(BufReader::new(response.body_mut()), &mut file)
+ .await
+ .with_context(|| format!("Unable to write binary to file at {:?}", binary_path))?;
- futures::io::copy(BufReader::new(response.body_mut()), &mut file)
- .await
- .with_context(|| format!("Unable to write binary to file at {:?}", binary_path))?;
-
- #[cfg(not(windows))]
- {
- file.set_permissions(<fs::Permissions as fs::unix::PermissionsExt>::from_mode(
- 0o755,
- ))
- .await?;
- }
+ #[cfg(not(windows))]
+ {
+ file.set_permissions(<fs::Permissions as fs::unix::PermissionsExt>::from_mode(
+ 0o755,
+ ))
+ .await?;
+ }
- let mut old_binary_paths = fs::read_dir(supermaven_dir()).await?;
- while let Some(old_binary_path) = old_binary_paths.next().await {
- let old_binary_path = old_binary_path?;
- if old_binary_path.path() != binary_path {
- fs::remove_file(old_binary_path.path()).await?;
- }
+ let mut old_binary_paths = fs::read_dir(supermaven_dir()).await?;
+ while let Some(old_binary_path) = old_binary_paths.next().await {
+ let old_binary_path = old_binary_path?;
+ if old_binary_path.path() != binary_path {
+ fs::remove_file(old_binary_path.path()).await?;
}
-
- Ok(binary_path)
}
+
+ Ok(binary_path)
}
@@ -174,7 +174,7 @@ impl TaskTemplate {
&mut substituted_variables,
)?;
- let task_hash = to_hex_hash(&self)
+ let task_hash = to_hex_hash(self)
.context("hashing task template")
.log_err()?;
let variables_hash = to_hex_hash(&task_variables)
@@ -319,13 +319,13 @@ fn substitute_all_template_variables_in_map(
let mut new_map: HashMap<String, String> = Default::default();
for (key, value) in keys_and_values {
let new_value = substitute_all_template_variables_in_str(
- &value,
+ value,
task_variables,
variable_names,
substituted_variables,
)?;
let new_key = substitute_all_template_variables_in_str(
- &key,
+ key,
task_variables,
variable_names,
substituted_variables,
@@ -67,7 +67,7 @@ impl EnvVariableReplacer {
// Got a VSCode->Zed hit, perform a substitution
let mut name = format!("${{{substitution}");
append_previous_default(&mut name);
- name.push_str("}");
+ name.push('}');
return Some(name);
}
// This is an unknown variable.
@@ -84,7 +84,7 @@ impl EnvVariableReplacer {
}
impl VsCodeTaskDefinition {
- fn to_zed_format(self, replacer: &EnvVariableReplacer) -> anyhow::Result<TaskTemplate> {
+ fn into_zed_format(self, replacer: &EnvVariableReplacer) -> anyhow::Result<TaskTemplate> {
if self.other_attributes.contains_key("dependsOn") {
bail!("Encountered unsupported `dependsOn` key during deserialization");
}
@@ -143,7 +143,7 @@ impl TryFrom<VsCodeTaskFile> for TaskTemplates {
let templates = value
.tasks
.into_iter()
- .filter_map(|vscode_definition| vscode_definition.to_zed_format(&replacer).log_err())
+ .filter_map(|vscode_definition| vscode_definition.into_zed_format(&replacer).log_err())
.collect();
Ok(Self(templates))
}
@@ -200,9 +200,9 @@ mod tests {
#[test]
fn can_deserialize_ts_tasks() {
- static TYPESCRIPT_TASKS: &'static str = include_str!("../test_data/typescript.json");
+ static TYPESCRIPT_TASKS: &str = include_str!("../test_data/typescript.json");
let vscode_definitions: VsCodeTaskFile =
- serde_json_lenient::from_str(&TYPESCRIPT_TASKS).unwrap();
+ serde_json_lenient::from_str(TYPESCRIPT_TASKS).unwrap();
let expected = vec![
VsCodeTaskDefinition {
@@ -290,9 +290,9 @@ mod tests {
#[test]
fn can_deserialize_rust_analyzer_tasks() {
- static RUST_ANALYZER_TASKS: &'static str = include_str!("../test_data/rust-analyzer.json");
+ static RUST_ANALYZER_TASKS: &str = include_str!("../test_data/rust-analyzer.json");
let vscode_definitions: VsCodeTaskFile =
- serde_json_lenient::from_str(&RUST_ANALYZER_TASKS).unwrap();
+ serde_json_lenient::from_str(RUST_ANALYZER_TASKS).unwrap();
let expected = vec![
VsCodeTaskDefinition {
label: "Build Extension in Background".to_string(),
@@ -389,7 +389,7 @@ impl PickerDelegate for TasksModalDelegate {
TaskSourceKind::Worktree { .. } => Some(Icon::new(IconName::FileTree)),
TaskSourceKind::Language { name } => file_icons::FileIcons::get(cx)
.get_type_icon(&name.to_lowercase())
- .map(|icon_path| Icon::from_path(icon_path)),
+ .map(Icon::from_path),
}
.map(|icon| icon.color(Color::Muted).size(IconSize::Small));
let history_run_icon = if Some(ix) <= self.divider_index {
@@ -11,14 +11,14 @@ use gpui::{px, Modifiers, MouseButton, MouseMoveEvent, Pixels, Point, ScrollWhee
use crate::TerminalSize;
enum MouseFormat {
- SGR,
+ Sgr,
Normal(bool),
}
impl MouseFormat {
fn from_mode(mode: TermMode) -> Self {
if mode.contains(TermMode::SGR_MOUSE) {
- MouseFormat::SGR
+ MouseFormat::Sgr
} else if mode.contains(TermMode::UTF8_MOUSE) {
MouseFormat::Normal(true)
} else {
@@ -77,10 +77,7 @@ impl AlacMouseButton {
}
fn is_other(&self) -> bool {
- match self {
- AlacMouseButton::Other => true,
- _ => false,
- }
+ matches!(self, AlacMouseButton::Other)
}
}
@@ -219,7 +216,7 @@ fn mouse_report(
}
match format {
- MouseFormat::SGR => {
+ MouseFormat::Sgr => {
Some(sgr_mouse_report(point, button as u8 + mods, pressed).into_bytes())
}
MouseFormat::Normal(utf8) => {
@@ -823,9 +823,9 @@ impl Terminal {
let mut min_index = point;
loop {
let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
- if new_min_index == min_index {
- break;
- } else if term.grid().index(new_min_index).hyperlink() != link {
+ if new_min_index == min_index
+ || term.grid().index(new_min_index).hyperlink() != link
+ {
break;
} else {
min_index = new_min_index
@@ -835,9 +835,9 @@ impl Terminal {
let mut max_index = point;
loop {
let new_max_index = max_index.add(term, Boundary::Cursor, 1);
- if new_max_index == max_index {
- break;
- } else if term.grid().index(new_max_index).hyperlink() != link {
+ if new_max_index == max_index
+ || term.grid().index(new_max_index).hyperlink() != link
+ {
break;
} else {
max_index = new_max_index
@@ -1410,12 +1410,10 @@ impl Terminal {
&& !e.shift
{
self.pty_tx.notify(alt_scroll(scroll_lines))
- } else {
- if scroll_lines != 0 {
- let scroll = AlacScroll::Delta(scroll_lines);
+ } else if scroll_lines != 0 {
+ let scroll = AlacScroll::Delta(scroll_lines);
- self.events.push_back(InternalEvent::Scroll(scroll));
- }
+ self.events.push_back(InternalEvent::Scroll(scroll));
}
}
}
@@ -1496,7 +1494,7 @@ impl Terminal {
let process_name = format!(
"{}{}",
fpi.name,
- if argv.len() >= 1 {
+ if !argv.is_empty() {
format!(" {}", (argv[1..]).join(" "))
} else {
"".to_string()
@@ -1612,16 +1610,16 @@ fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, Str
/// The library
///
/// * does not increment inner grid cursor's _lines_ on `input` calls
-/// (but displaying the lines correctly and incrementing cursor's columns)
+/// (but displaying the lines correctly and incrementing cursor's columns)
///
/// * ignores `\n` and \r` character input, requiring the `newline` call instead
///
/// * does not alter grid state after `newline` call
-/// so its `bottommost_line` is always the same additions, and
-/// the cursor's `point` is not updated to the new line and column values
+/// so its `bottommost_line` is always the same additions, and
+/// the cursor's `point` is not updated to the new line and column values
///
/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
-/// Still, concequent `append_text_to_term` invocations are possible and display the contents correctly.
+/// Still, concequent `append_text_to_term` invocations are possible and display the contents correctly.
///
/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
@@ -269,7 +269,7 @@ impl TerminalElement {
cur_rect = Some(LayoutRect::new(
AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
1,
- convert_color(&bg, &theme),
+ convert_color(&bg, theme),
));
}
}
@@ -344,7 +344,7 @@ impl TerminalElement {
hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
) -> TextRun {
let flags = indexed.cell.flags;
- let mut fg = convert_color(&fg, &colors);
+ let mut fg = convert_color(&fg, colors);
// Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
// uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
@@ -439,7 +439,7 @@ impl TerminalElement {
move |e, cx| {
cx.focus(&focus);
terminal.update(cx, |terminal, cx| {
- terminal.mouse_down(&e, origin, cx);
+ terminal.mouse_down(e, origin, cx);
cx.notify();
})
}
@@ -460,18 +460,16 @@ impl TerminalElement {
if terminal.selection_started() {
terminal.mouse_drag(e, origin, hitbox.bounds);
cx.notify();
- } else {
- if hovered {
- terminal.mouse_drag(e, origin, hitbox.bounds);
- cx.notify();
- }
+ } else if hovered {
+ terminal.mouse_drag(e, origin, hitbox.bounds);
+ cx.notify();
}
})
}
if hitbox.is_hovered(cx) {
terminal.update(cx, |terminal, cx| {
- terminal.mouse_move(&e, origin);
+ terminal.mouse_move(e, origin);
cx.notify();
})
}
@@ -485,7 +483,7 @@ impl TerminalElement {
origin,
focus.clone(),
move |terminal, origin, e, cx| {
- terminal.mouse_up(&e, origin, cx);
+ terminal.mouse_up(e, origin, cx);
},
),
);
@@ -496,7 +494,7 @@ impl TerminalElement {
origin,
focus.clone(),
move |terminal, origin, e, cx| {
- terminal.mouse_down(&e, origin, cx);
+ terminal.mouse_down(e, origin, cx);
},
),
);
@@ -522,7 +520,7 @@ impl TerminalElement {
origin,
focus.clone(),
move |terminal, origin, e, cx| {
- terminal.mouse_down(&e, origin, cx);
+ terminal.mouse_down(e, origin, cx);
},
),
);
@@ -533,7 +531,7 @@ impl TerminalElement {
origin,
focus.clone(),
move |terminal, origin, e, cx| {
- terminal.mouse_up(&e, origin, cx);
+ terminal.mouse_up(e, origin, cx);
},
),
);
@@ -544,7 +542,7 @@ impl TerminalElement {
origin,
focus,
move |terminal, origin, e, cx| {
- terminal.mouse_up(&e, origin, cx);
+ terminal.mouse_up(e, origin, cx);
},
),
);
@@ -591,9 +589,8 @@ impl Element for TerminalElement {
style.size.width = relative(1.).into();
style.size.height = relative(1.).into();
// style.overflow = point(Overflow::Hidden, Overflow::Hidden);
- let layout_id = cx.request_layout(style, None);
- layout_id
+ cx.request_layout(style, None)
});
(layout_id, ())
}
@@ -625,7 +622,7 @@ impl Element for TerminalElement {
.font_fallbacks
.as_ref()
.or(settings.buffer_font.fallbacks.as_ref())
- .map(|fallbacks| fallbacks.clone());
+ .cloned();
let font_features = terminal_settings
.font_features
@@ -758,7 +755,7 @@ impl Element for TerminalElement {
let (cells, rects) = TerminalElement::layout_grid(
cells.iter().cloned(),
&text_style,
- &cx.text_system(),
+ cx.text_system(),
last_hovered_word
.as_ref()
.map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
@@ -926,7 +923,7 @@ impl Element for TerminalElement {
layout.relative_highlighted_ranges.iter()
{
if let Some((start_y, highlighted_range_lines)) =
- to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
+ to_highlighted_range_lines(relative_highlighted_range, layout, origin)
{
let hr = HighlightedRange {
start_y,
@@ -1069,7 +1066,7 @@ pub fn is_blank(cell: &IndexedCell) -> bool {
return false;
}
- return true;
+ true
}
fn to_highlighted_range_lines(
@@ -786,9 +786,9 @@ impl Panel for TerminalPanel {
let settings = TerminalSettings::get_global(cx);
match self.position(cx) {
DockPosition::Left | DockPosition::Right => {
- self.width.unwrap_or_else(|| settings.default_width)
+ self.width.unwrap_or(settings.default_width)
}
- DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
+ DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
}
}
@@ -886,9 +886,9 @@ fn retrieve_system_shell() -> Option<String> {
use anyhow::Context;
use util::ResultExt;
- return std::env::var("SHELL")
+ std::env::var("SHELL")
.context("Error finding SHELL in env.")
- .log_err();
+ .log_err()
}
// `alacritty_terminal` uses this as default on Windows. See:
// https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
@@ -645,7 +645,7 @@ fn subscribe_for_terminal_events(
&path_like_target.maybe_path,
cx,
);
- smol::block_on(valid_files_to_open_task).len() > 0
+ !smol::block_on(valid_files_to_open_task).is_empty()
} else {
false
}
@@ -867,7 +867,7 @@ pub fn regex_search_for_query(query: &project::search::SearchQuery) -> Option<Re
if query == "." {
return None;
}
- let searcher = RegexSearch::new(&query);
+ let searcher = RegexSearch::new(query);
searcher.ok()
}
@@ -1239,7 +1239,7 @@ impl SearchableItem for TerminalView {
let searcher = match &*query {
SearchQuery::Text { .. } => regex_search_for_query(
&(SearchQuery::text(
- regex_to_literal(&query.as_str()),
+ regex_to_literal(query.as_str()),
query.whole_word(),
query.case_sensitive(),
query.include_ignored(),
@@ -1269,7 +1269,7 @@ impl SearchableItem for TerminalView {
// Selection head might have a value if there's a selection that isn't
// associated with a match. Therefore, if there are no matches, we should
// report None, no matter the state of the terminal
- let res = if matches.len() > 0 {
+ let res = if !matches.is_empty() {
if let Some(selection_head) = self.terminal().read(cx).selection_head {
// If selection head is contained in a match. Return that match
if let Some(ix) = matches
@@ -2,8 +2,8 @@ use smallvec::{smallvec, SmallVec};
use std::iter;
use std::sync::LazyLock;
-static MIN: LazyLock<Locator> = LazyLock::new(|| Locator::min());
-static MAX: LazyLock<Locator> = LazyLock::new(|| Locator::max());
+static MIN: LazyLock<Locator> = LazyLock::new(Locator::min);
+static MAX: LazyLock<Locator> = LazyLock::new(Locator::max);
/// An identifier for a position in a ordered collection.
///
@@ -121,12 +121,8 @@ impl ThemeStyleContent {
.background_color
.as_ref()
.and_then(|color| try_parse_color(color).ok()),
- font_style: style
- .font_style
- .map(|font_style| FontStyle::from(font_style)),
- font_weight: style
- .font_weight
- .map(|font_weight| FontWeight::from(font_weight)),
+ font_style: style.font_style.map(FontStyle::from),
+ font_weight: style.font_weight.map(FontWeight::from),
..Default::default()
},
)
@@ -70,9 +70,9 @@ impl From<String> for UiDensity {
}
}
-impl Into<String> for UiDensity {
- fn into(self) -> String {
- match self {
+impl From<UiDensity> for String {
+ fn from(val: UiDensity) -> Self {
+ match val {
UiDensity::Compact => "compact".to_string(),
UiDensity::Default => "default".to_string(),
UiDensity::Comfortable => "comfortable".to_string(),
@@ -15,7 +15,7 @@ impl AssetSource for Assets {
Self::get(path)
.map(|f| f.data)
.ok_or_else(|| anyhow!("could not find asset at path \"{}\"", path))
- .map(|result| Some(result))
+ .map(Some)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
@@ -246,12 +246,12 @@ impl VsCodeThemeConverter {
.settings
.font_style
.as_ref()
- .and_then(|style| try_parse_font_style(&style)),
+ .and_then(|style| try_parse_font_style(style)),
font_weight: token_color
.settings
.font_style
.as_ref()
- .and_then(|style| try_parse_font_weight(&style)),
+ .and_then(|style| try_parse_font_weight(style)),
};
if highlight_style.is_empty() {
@@ -163,14 +163,12 @@ fn calculate_month_difference(timestamp: OffsetDateTime, reference: OffsetDateTi
let year_diff = (reference_year - timestamp_year) as usize;
if year_diff == 0 {
reference_month as usize - timestamp_month as usize
+ } else if month_diff == 0 {
+ year_diff * 12
+ } else if timestamp_month > reference_month {
+ (year_diff - 1) * 12 + month_diff
} else {
- if month_diff == 0 {
- year_diff * 12
- } else if timestamp_month > reference_month {
- (year_diff - 1) * 12 + month_diff
- } else {
- year_diff * 12 + month_diff
- }
+ year_diff * 12 + month_diff
}
}
@@ -120,7 +120,7 @@ impl TitleBar {
room.is_speaking(),
room.is_muted(),
None,
- &room,
+ room,
project_id,
¤t_user,
cx,
@@ -151,7 +151,7 @@ impl TitleBar {
collaborator.speaking,
collaborator.muted,
is_following.then_some(player_color.selection),
- &room,
+ room,
project_id,
¤t_user,
cx,
@@ -1,7 +1,133 @@
-mod avatar;
mod avatar_audio_status_indicator;
mod avatar_availability_indicator;
-pub use avatar::*;
pub use avatar_audio_status_indicator::*;
pub use avatar_availability_indicator::*;
+
+use crate::prelude::*;
+
+use gpui::{img, AnyElement, Hsla, ImageSource, Img, IntoElement, Styled};
+
+/// The shape of an [`Avatar`].
+#[derive(Debug, Default, PartialEq, Clone)]
+pub enum AvatarShape {
+ /// The avatar is shown in a circle.
+ #[default]
+ Circle,
+ /// The avatar is shown in a rectangle with rounded corners.
+ RoundedRectangle,
+}
+
+/// An element that renders a user avatar with customizable appearance options.
+///
+/// # Examples
+///
+/// ```
+/// use ui::{Avatar, AvatarShape};
+///
+/// Avatar::new("path/to/image.png")
+/// .shape(AvatarShape::Circle)
+/// .grayscale(true)
+/// .border_color(gpui::red());
+/// ```
+#[derive(IntoElement)]
+pub struct Avatar {
+ image: Img,
+ size: Option<AbsoluteLength>,
+ border_color: Option<Hsla>,
+ indicator: Option<AnyElement>,
+}
+
+impl Avatar {
+ pub fn new(src: impl Into<ImageSource>) -> Self {
+ Avatar {
+ image: img(src),
+ size: None,
+ border_color: None,
+ indicator: None,
+ }
+ }
+
+ /// Sets the shape of the avatar image.
+ ///
+ /// This method allows the shape of the avatar to be specified using an [`AvatarShape`].
+ /// It modifies the corner radius of the image to match the specified shape.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::{Avatar, AvatarShape};
+ ///
+ /// Avatar::new("path/to/image.png").shape(AvatarShape::Circle);
+ /// ```
+ pub fn shape(mut self, shape: AvatarShape) -> Self {
+ self.image = match shape {
+ AvatarShape::Circle => self.image.rounded_full(),
+ AvatarShape::RoundedRectangle => self.image.rounded_md(),
+ };
+ self
+ }
+
+ /// Applies a grayscale filter to the avatar image.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::{Avatar, AvatarShape};
+ ///
+ /// let avatar = Avatar::new("path/to/image.png").grayscale(true);
+ /// ```
+ pub fn grayscale(mut self, grayscale: bool) -> Self {
+ self.image = self.image.grayscale(grayscale);
+ self
+ }
+
+ pub fn border_color(mut self, color: impl Into<Hsla>) -> Self {
+ self.border_color = Some(color.into());
+ self
+ }
+
+ /// Size overrides the avatar size. By default they are 1rem.
+ pub fn size<L: Into<AbsoluteLength>>(mut self, size: impl Into<Option<L>>) -> Self {
+ self.size = size.into().map(Into::into);
+ self
+ }
+
+ pub fn indicator<E: IntoElement>(mut self, indicator: impl Into<Option<E>>) -> Self {
+ self.indicator = indicator.into().map(IntoElement::into_any_element);
+ self
+ }
+}
+
+impl RenderOnce for Avatar {
+ fn render(mut self, cx: &mut WindowContext) -> impl IntoElement {
+ if self.image.style().corner_radii.top_left.is_none() {
+ self = self.shape(AvatarShape::Circle);
+ }
+
+ let border_width = if self.border_color.is_some() {
+ px(2.)
+ } else {
+ px(0.)
+ };
+
+ let image_size = self.size.unwrap_or_else(|| rems(1.).into());
+ let container_size = image_size.to_pixels(cx.rem_size()) + border_width * 2.;
+
+ div()
+ .size(container_size)
+ .map(|mut div| {
+ div.style().corner_radii = self.image.style().corner_radii.clone();
+ div
+ })
+ .when_some(self.border_color, |this, color| {
+ this.border(border_width).border_color(color)
+ })
+ .child(
+ self.image
+ .size(image_size)
+ .bg(cx.theme().colors().ghost_element_background),
+ )
+ .children(self.indicator.map(|indicator| div().child(indicator)))
+ }
+}
@@ -1,127 +0,0 @@
-use crate::prelude::*;
-
-use gpui::{img, AnyElement, Hsla, ImageSource, Img, IntoElement, Styled};
-
-/// The shape of an [`Avatar`].
-#[derive(Debug, Default, PartialEq, Clone)]
-pub enum AvatarShape {
- /// The avatar is shown in a circle.
- #[default]
- Circle,
- /// The avatar is shown in a rectangle with rounded corners.
- RoundedRectangle,
-}
-
-/// An element that renders a user avatar with customizable appearance options.
-///
-/// # Examples
-///
-/// ```
-/// use ui::{Avatar, AvatarShape};
-///
-/// Avatar::new("path/to/image.png")
-/// .shape(AvatarShape::Circle)
-/// .grayscale(true)
-/// .border_color(gpui::red());
-/// ```
-#[derive(IntoElement)]
-pub struct Avatar {
- image: Img,
- size: Option<AbsoluteLength>,
- border_color: Option<Hsla>,
- indicator: Option<AnyElement>,
-}
-
-impl Avatar {
- pub fn new(src: impl Into<ImageSource>) -> Self {
- Avatar {
- image: img(src),
- size: None,
- border_color: None,
- indicator: None,
- }
- }
-
- /// Sets the shape of the avatar image.
- ///
- /// This method allows the shape of the avatar to be specified using an [`AvatarShape`].
- /// It modifies the corner radius of the image to match the specified shape.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::{Avatar, AvatarShape};
- ///
- /// Avatar::new("path/to/image.png").shape(AvatarShape::Circle);
- /// ```
- pub fn shape(mut self, shape: AvatarShape) -> Self {
- self.image = match shape {
- AvatarShape::Circle => self.image.rounded_full(),
- AvatarShape::RoundedRectangle => self.image.rounded_md(),
- };
- self
- }
-
- /// Applies a grayscale filter to the avatar image.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::{Avatar, AvatarShape};
- ///
- /// let avatar = Avatar::new("path/to/image.png").grayscale(true);
- /// ```
- pub fn grayscale(mut self, grayscale: bool) -> Self {
- self.image = self.image.grayscale(grayscale);
- self
- }
-
- pub fn border_color(mut self, color: impl Into<Hsla>) -> Self {
- self.border_color = Some(color.into());
- self
- }
-
- /// Size overrides the avatar size. By default they are 1rem.
- pub fn size<L: Into<AbsoluteLength>>(mut self, size: impl Into<Option<L>>) -> Self {
- self.size = size.into().map(Into::into);
- self
- }
-
- pub fn indicator<E: IntoElement>(mut self, indicator: impl Into<Option<E>>) -> Self {
- self.indicator = indicator.into().map(IntoElement::into_any_element);
- self
- }
-}
-
-impl RenderOnce for Avatar {
- fn render(mut self, cx: &mut WindowContext) -> impl IntoElement {
- if self.image.style().corner_radii.top_left.is_none() {
- self = self.shape(AvatarShape::Circle);
- }
-
- let border_width = if self.border_color.is_some() {
- px(2.)
- } else {
- px(0.)
- };
-
- let image_size = self.size.unwrap_or_else(|| rems(1.).into());
- let container_size = image_size.to_pixels(cx.rem_size()) + border_width * 2.;
-
- div()
- .size(container_size)
- .map(|mut div| {
- div.style().corner_radii = self.image.style().corner_radii.clone();
- div
- })
- .when_some(self.border_color, |this, color| {
- this.border(border_width).border_color(color)
- })
- .child(
- self.image
- .size(image_size)
- .bg(cx.theme().colors().ghost_element_background),
- )
- .children(self.indicator.map(|indicator| div().child(indicator)))
- }
-}
@@ -1,10 +1,445 @@
-mod button;
-pub(self) mod button_icon;
+mod button_icon;
mod button_like;
mod icon_button;
mod toggle_button;
-pub use button::*;
pub use button_like::*;
pub use icon_button::*;
pub use toggle_button::*;
+
+use gpui::{AnyView, DefiniteLength};
+
+use crate::{prelude::*, ElevationIndex, KeyBinding, Spacing};
+use crate::{IconName, IconSize, Label, LineHeightStyle};
+
+use button_icon::ButtonIcon;
+
+/// An element that creates a button with a label and an optional icon.
+///
+/// Common buttons:
+/// - Label, Icon + Label: [`Button`] (this component)
+/// - Icon only: [`IconButton`]
+/// - Custom: [`ButtonLike`]
+///
+/// To create a more complex button than what the [`Button`] or [`IconButton`] components provide, use
+/// [`ButtonLike`] directly.
+///
+/// # Examples
+///
+/// **A button with a label**, is typically used in scenarios such as a form, where the button's label
+/// indicates what action will be performed when the button is clicked.
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// Button::new("button_id", "Click me!")
+/// .on_click(|event, cx| {
+/// // Handle click event
+/// });
+/// ```
+///
+/// **A toggleable button**, is typically used in scenarios such as a toolbar,
+/// where the button's state indicates whether a feature is enabled or not, or
+/// a trigger for a popover menu, where clicking the button toggles the visibility of the menu.
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// Button::new("button_id", "Click me!")
+/// .icon(IconName::Check)
+/// .selected(true)
+/// .on_click(|event, cx| {
+/// // Handle click event
+/// });
+/// ```
+///
+/// To change the style of the button when it is selected use the [`selected_style`][Button::selected_style] method.
+///
+/// ```
+/// use ui::prelude::*;
+/// use ui::TintColor;
+///
+/// Button::new("button_id", "Click me!")
+/// .selected(true)
+/// .selected_style(ButtonStyle::Tinted(TintColor::Accent))
+/// .on_click(|event, cx| {
+/// // Handle click event
+/// });
+/// ```
+/// This will create a button with a blue tinted background when selected.
+///
+/// **A full-width button**, is typically used in scenarios such as the bottom of a modal or form, where it occupies the entire width of its container.
+/// The button's content, including text and icons, is centered by default.
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// let button = Button::new("button_id", "Click me!")
+/// .full_width()
+/// .on_click(|event, cx| {
+/// // Handle click event
+/// });
+/// ```
+///
+#[derive(IntoElement)]
+pub struct Button {
+ base: ButtonLike,
+ label: SharedString,
+ label_color: Option<Color>,
+ label_size: Option<LabelSize>,
+ selected_label: Option<SharedString>,
+ selected_label_color: Option<Color>,
+ icon: Option<IconName>,
+ icon_position: Option<IconPosition>,
+ icon_size: Option<IconSize>,
+ icon_color: Option<Color>,
+ selected_icon: Option<IconName>,
+ selected_icon_color: Option<Color>,
+ key_binding: Option<KeyBinding>,
+ alpha: Option<f32>,
+}
+
+impl Button {
+ /// Creates a new [`Button`] with a specified identifier and label.
+ ///
+ /// This is the primary constructor for a [`Button`] component. It initializes
+ /// the button with the provided identifier and label text, setting all other
+ /// properties to their default values, which can be customized using the
+ /// builder pattern methods provided by this struct.
+ pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
+ Self {
+ base: ButtonLike::new(id),
+ label: label.into(),
+ label_color: None,
+ label_size: None,
+ selected_label: None,
+ selected_label_color: None,
+ icon: None,
+ icon_position: None,
+ icon_size: None,
+ icon_color: None,
+ selected_icon: None,
+ selected_icon_color: None,
+ key_binding: None,
+ alpha: None,
+ }
+ }
+
+ /// Sets the color of the button's label.
+ pub fn color(mut self, label_color: impl Into<Option<Color>>) -> Self {
+ self.label_color = label_color.into();
+ self
+ }
+
+ /// Defines the size of the button's label.
+ pub fn label_size(mut self, label_size: impl Into<Option<LabelSize>>) -> Self {
+ self.label_size = label_size.into();
+ self
+ }
+
+ /// Sets the label used when the button is in a selected state.
+ pub fn selected_label<L: Into<SharedString>>(mut self, label: impl Into<Option<L>>) -> Self {
+ self.selected_label = label.into().map(Into::into);
+ self
+ }
+
+ /// Sets the label color used when the button is in a selected state.
+ pub fn selected_label_color(mut self, color: impl Into<Option<Color>>) -> Self {
+ self.selected_label_color = color.into();
+ self
+ }
+
+ /// Assigns an icon to the button.
+ pub fn icon(mut self, icon: impl Into<Option<IconName>>) -> Self {
+ self.icon = icon.into();
+ self
+ }
+
+ /// Sets the position of the icon relative to the label.
+ pub fn icon_position(mut self, icon_position: impl Into<Option<IconPosition>>) -> Self {
+ self.icon_position = icon_position.into();
+ self
+ }
+
+ /// Specifies the size of the button's icon.
+ pub fn icon_size(mut self, icon_size: impl Into<Option<IconSize>>) -> Self {
+ self.icon_size = icon_size.into();
+ self
+ }
+
+ /// Sets the color of the button's icon.
+ pub fn icon_color(mut self, icon_color: impl Into<Option<Color>>) -> Self {
+ self.icon_color = icon_color.into();
+ self
+ }
+
+ /// Chooses an icon to display when the button is in a selected state.
+ pub fn selected_icon(mut self, icon: impl Into<Option<IconName>>) -> Self {
+ self.selected_icon = icon.into();
+ self
+ }
+
+ /// Sets the icon color used when the button is in a selected state.
+ pub fn selected_icon_color(mut self, color: impl Into<Option<Color>>) -> Self {
+ self.selected_icon_color = color.into();
+ self
+ }
+
+ /// Binds a key combination to the button for keyboard shortcuts.
+ pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
+ self.key_binding = key_binding.into();
+ self
+ }
+
+ /// Sets the alpha property of the color of label.
+ pub fn alpha(mut self, alpha: f32) -> Self {
+ self.alpha = Some(alpha);
+ self
+ }
+}
+
+impl Selectable for Button {
+ /// Sets the selected state of the button.
+ ///
+ /// This method allows the selection state of the button to be specified.
+ /// It modifies the button's appearance to reflect its selected state.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .selected(true)
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ ///
+ /// Use [`selected_style`](Button::selected_style) to change the style of the button when it is selected.
+ fn selected(mut self, selected: bool) -> Self {
+ self.base = self.base.selected(selected);
+ self
+ }
+}
+
+impl SelectableButton for Button {
+ /// Sets the style for the button when selected.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ /// use ui::TintColor;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .selected(true)
+ /// .selected_style(ButtonStyle::Tinted(TintColor::Accent))
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ /// This results in a button with a blue tinted background when selected.
+ fn selected_style(mut self, style: ButtonStyle) -> Self {
+ self.base = self.base.selected_style(style);
+ self
+ }
+}
+
+impl Disableable for Button {
+ /// Disables the button.
+ ///
+ /// This method allows the button to be disabled. When a button is disabled,
+ /// it doesn't react to user interactions and its appearance is updated to reflect this.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .disabled(true)
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ ///
+ /// This results in a button that is disabled and does not respond to click events.
+ fn disabled(mut self, disabled: bool) -> Self {
+ self.base = self.base.disabled(disabled);
+ self
+ }
+}
+
+impl Clickable for Button {
+ /// Sets the click event handler for the button.
+ fn on_click(
+ mut self,
+ handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static,
+ ) -> Self {
+ self.base = self.base.on_click(handler);
+ self
+ }
+
+ fn cursor_style(mut self, cursor_style: gpui::CursorStyle) -> Self {
+ self.base = self.base.cursor_style(cursor_style);
+ self
+ }
+}
+
+impl FixedWidth for Button {
+ /// Sets a fixed width for the button.
+ ///
+ /// This function allows a button to have a fixed width instead of automatically growing or shrinking.
+ /// Sets a fixed width for the button.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .width(px(100.).into())
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ ///
+ /// This sets the button's width to be exactly 100 pixels.
+ fn width(mut self, width: DefiniteLength) -> Self {
+ self.base = self.base.width(width);
+ self
+ }
+
+ /// Sets the button to occupy the full width of its container.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .full_width()
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ ///
+ /// This stretches the button to the full width of its container.
+ fn full_width(mut self) -> Self {
+ self.base = self.base.full_width();
+ self
+ }
+}
+
+impl ButtonCommon for Button {
+ /// Sets the button's id.
+ fn id(&self) -> &ElementId {
+ self.base.id()
+ }
+
+ /// Sets the visual style of the button using a [`ButtonStyle`].
+ fn style(mut self, style: ButtonStyle) -> Self {
+ self.base = self.base.style(style);
+ self
+ }
+
+ /// Sets the button's size using a [`ButtonSize`].
+ fn size(mut self, size: ButtonSize) -> Self {
+ self.base = self.base.size(size);
+ self
+ }
+
+ /// Sets a tooltip for the button.
+ ///
+ /// This method allows a tooltip to be set for the button. The tooltip is a function that
+ /// takes a mutable reference to a [`WindowContext`] and returns an [`AnyView`]. The tooltip
+ /// is displayed when the user hovers over the button.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ /// use ui::Tooltip;
+ ///
+ /// Button::new("button_id", "Click me!")
+ /// .tooltip(move |cx| {
+ /// Tooltip::text("This is a tooltip", cx)
+ /// })
+ /// .on_click(|event, cx| {
+ /// // Handle click event
+ /// });
+ /// ```
+ ///
+ /// This will create a button with a tooltip that displays "This is a tooltip" when hovered over.
+ fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
+ self.base = self.base.tooltip(tooltip);
+ self
+ }
+
+ fn layer(mut self, elevation: ElevationIndex) -> Self {
+ self.base = self.base.layer(elevation);
+ self
+ }
+}
+
+impl RenderOnce for Button {
+ #[allow(refining_impl_trait)]
+ fn render(self, cx: &mut WindowContext) -> ButtonLike {
+ let is_disabled = self.base.disabled;
+ let is_selected = self.base.selected;
+
+ let label = self
+ .selected_label
+ .filter(|_| is_selected)
+ .unwrap_or(self.label);
+
+ let label_color = if is_disabled {
+ Color::Disabled
+ } else if is_selected {
+ self.selected_label_color.unwrap_or(Color::Selected)
+ } else {
+ self.label_color.unwrap_or_default()
+ };
+
+ self.base.child(
+ h_flex()
+ .gap(Spacing::Small.rems(cx))
+ .when(self.icon_position == Some(IconPosition::Start), |this| {
+ this.children(self.icon.map(|icon| {
+ ButtonIcon::new(icon)
+ .disabled(is_disabled)
+ .selected(is_selected)
+ .selected_icon(self.selected_icon)
+ .selected_icon_color(self.selected_icon_color)
+ .size(self.icon_size)
+ .color(self.icon_color)
+ }))
+ })
+ .child(
+ h_flex()
+ .gap(Spacing::Medium.rems(cx))
+ .justify_between()
+ .child(
+ Label::new(label)
+ .color(label_color)
+ .size(self.label_size.unwrap_or_default())
+ .when_some(self.alpha, |this, alpha| this.alpha(alpha))
+ .line_height_style(LineHeightStyle::UiLabel),
+ )
+ .children(self.key_binding),
+ )
+ .when(self.icon_position != Some(IconPosition::Start), |this| {
+ this.children(self.icon.map(|icon| {
+ ButtonIcon::new(icon)
+ .disabled(is_disabled)
+ .selected(is_selected)
+ .selected_icon(self.selected_icon)
+ .selected_icon_color(self.selected_icon_color)
+ .size(self.icon_size)
+ .color(self.icon_color)
+ }))
+ }),
+ )
+ }
+}
@@ -1,438 +0,0 @@
-use gpui::{AnyView, DefiniteLength};
-
-use crate::{prelude::*, ElevationIndex, IconPosition, KeyBinding, Spacing};
-use crate::{
- ButtonCommon, ButtonLike, ButtonSize, ButtonStyle, IconName, IconSize, Label, LineHeightStyle,
-};
-
-use super::button_icon::ButtonIcon;
-
-/// An element that creates a button with a label and an optional icon.
-///
-/// Common buttons:
-/// - Label, Icon + Label: [`Button`] (this component)
-/// - Icon only: [`IconButton`]
-/// - Custom: [`ButtonLike`]
-///
-/// To create a more complex button than what the [`Button`] or [`IconButton`] components provide, use
-/// [`ButtonLike`] directly.
-///
-/// # Examples
-///
-/// **A button with a label**, is typically used in scenarios such as a form, where the button's label
-/// indicates what action will be performed when the button is clicked.
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// Button::new("button_id", "Click me!")
-/// .on_click(|event, cx| {
-/// // Handle click event
-/// });
-/// ```
-///
-/// **A toggleable button**, is typically used in scenarios such as a toolbar,
-/// where the button's state indicates whether a feature is enabled or not, or
-/// a trigger for a popover menu, where clicking the button toggles the visibility of the menu.
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// Button::new("button_id", "Click me!")
-/// .icon(IconName::Check)
-/// .selected(true)
-/// .on_click(|event, cx| {
-/// // Handle click event
-/// });
-/// ```
-///
-/// To change the style of the button when it is selected use the [`selected_style`][Button::selected_style] method.
-///
-/// ```
-/// use ui::prelude::*;
-/// use ui::TintColor;
-///
-/// Button::new("button_id", "Click me!")
-/// .selected(true)
-/// .selected_style(ButtonStyle::Tinted(TintColor::Accent))
-/// .on_click(|event, cx| {
-/// // Handle click event
-/// });
-/// ```
-/// This will create a button with a blue tinted background when selected.
-///
-/// **A full-width button**, is typically used in scenarios such as the bottom of a modal or form, where it occupies the entire width of its container.
-/// The button's content, including text and icons, is centered by default.
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// let button = Button::new("button_id", "Click me!")
-/// .full_width()
-/// .on_click(|event, cx| {
-/// // Handle click event
-/// });
-/// ```
-///
-#[derive(IntoElement)]
-pub struct Button {
- base: ButtonLike,
- label: SharedString,
- label_color: Option<Color>,
- label_size: Option<LabelSize>,
- selected_label: Option<SharedString>,
- selected_label_color: Option<Color>,
- icon: Option<IconName>,
- icon_position: Option<IconPosition>,
- icon_size: Option<IconSize>,
- icon_color: Option<Color>,
- selected_icon: Option<IconName>,
- selected_icon_color: Option<Color>,
- key_binding: Option<KeyBinding>,
- alpha: Option<f32>,
-}
-
-impl Button {
- /// Creates a new [`Button`] with a specified identifier and label.
- ///
- /// This is the primary constructor for a [`Button`] component. It initializes
- /// the button with the provided identifier and label text, setting all other
- /// properties to their default values, which can be customized using the
- /// builder pattern methods provided by this struct.
- pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
- Self {
- base: ButtonLike::new(id),
- label: label.into(),
- label_color: None,
- label_size: None,
- selected_label: None,
- selected_label_color: None,
- icon: None,
- icon_position: None,
- icon_size: None,
- icon_color: None,
- selected_icon: None,
- selected_icon_color: None,
- key_binding: None,
- alpha: None,
- }
- }
-
- /// Sets the color of the button's label.
- pub fn color(mut self, label_color: impl Into<Option<Color>>) -> Self {
- self.label_color = label_color.into();
- self
- }
-
- /// Defines the size of the button's label.
- pub fn label_size(mut self, label_size: impl Into<Option<LabelSize>>) -> Self {
- self.label_size = label_size.into();
- self
- }
-
- /// Sets the label used when the button is in a selected state.
- pub fn selected_label<L: Into<SharedString>>(mut self, label: impl Into<Option<L>>) -> Self {
- self.selected_label = label.into().map(Into::into);
- self
- }
-
- /// Sets the label color used when the button is in a selected state.
- pub fn selected_label_color(mut self, color: impl Into<Option<Color>>) -> Self {
- self.selected_label_color = color.into();
- self
- }
-
- /// Assigns an icon to the button.
- pub fn icon(mut self, icon: impl Into<Option<IconName>>) -> Self {
- self.icon = icon.into();
- self
- }
-
- /// Sets the position of the icon relative to the label.
- pub fn icon_position(mut self, icon_position: impl Into<Option<IconPosition>>) -> Self {
- self.icon_position = icon_position.into();
- self
- }
-
- /// Specifies the size of the button's icon.
- pub fn icon_size(mut self, icon_size: impl Into<Option<IconSize>>) -> Self {
- self.icon_size = icon_size.into();
- self
- }
-
- /// Sets the color of the button's icon.
- pub fn icon_color(mut self, icon_color: impl Into<Option<Color>>) -> Self {
- self.icon_color = icon_color.into();
- self
- }
-
- /// Chooses an icon to display when the button is in a selected state.
- pub fn selected_icon(mut self, icon: impl Into<Option<IconName>>) -> Self {
- self.selected_icon = icon.into();
- self
- }
-
- /// Sets the icon color used when the button is in a selected state.
- pub fn selected_icon_color(mut self, color: impl Into<Option<Color>>) -> Self {
- self.selected_icon_color = color.into();
- self
- }
-
- /// Binds a key combination to the button for keyboard shortcuts.
- pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
- self.key_binding = key_binding.into();
- self
- }
-
- /// Sets the alpha property of the color of label.
- pub fn alpha(mut self, alpha: f32) -> Self {
- self.alpha = Some(alpha);
- self
- }
-}
-
-impl Selectable for Button {
- /// Sets the selected state of the button.
- ///
- /// This method allows the selection state of the button to be specified.
- /// It modifies the button's appearance to reflect its selected state.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// Button::new("button_id", "Click me!")
- /// .selected(true)
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- ///
- /// Use [`selected_style`](Button::selected_style) to change the style of the button when it is selected.
- fn selected(mut self, selected: bool) -> Self {
- self.base = self.base.selected(selected);
- self
- }
-}
-
-impl SelectableButton for Button {
- /// Sets the style for the button when selected.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- /// use ui::TintColor;
- ///
- /// Button::new("button_id", "Click me!")
- /// .selected(true)
- /// .selected_style(ButtonStyle::Tinted(TintColor::Accent))
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- /// This results in a button with a blue tinted background when selected.
- fn selected_style(mut self, style: ButtonStyle) -> Self {
- self.base = self.base.selected_style(style);
- self
- }
-}
-
-impl Disableable for Button {
- /// Disables the button.
- ///
- /// This method allows the button to be disabled. When a button is disabled,
- /// it doesn't react to user interactions and its appearance is updated to reflect this.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// Button::new("button_id", "Click me!")
- /// .disabled(true)
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- ///
- /// This results in a button that is disabled and does not respond to click events.
- fn disabled(mut self, disabled: bool) -> Self {
- self.base = self.base.disabled(disabled);
- self
- }
-}
-
-impl Clickable for Button {
- /// Sets the click event handler for the button.
- fn on_click(
- mut self,
- handler: impl Fn(&gpui::ClickEvent, &mut WindowContext) + 'static,
- ) -> Self {
- self.base = self.base.on_click(handler);
- self
- }
-
- fn cursor_style(mut self, cursor_style: gpui::CursorStyle) -> Self {
- self.base = self.base.cursor_style(cursor_style);
- self
- }
-}
-
-impl FixedWidth for Button {
- /// Sets a fixed width for the button.
- ///
- /// This function allows a button to have a fixed width instead of automatically growing or shrinking.
- /// Sets a fixed width for the button.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// Button::new("button_id", "Click me!")
- /// .width(px(100.).into())
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- ///
- /// This sets the button's width to be exactly 100 pixels.
- fn width(mut self, width: DefiniteLength) -> Self {
- self.base = self.base.width(width);
- self
- }
-
- /// Sets the button to occupy the full width of its container.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// Button::new("button_id", "Click me!")
- /// .full_width()
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- ///
- /// This stretches the button to the full width of its container.
- fn full_width(mut self) -> Self {
- self.base = self.base.full_width();
- self
- }
-}
-
-impl ButtonCommon for Button {
- /// Sets the button's id.
- fn id(&self) -> &ElementId {
- self.base.id()
- }
-
- /// Sets the visual style of the button using a [`ButtonStyle`].
- fn style(mut self, style: ButtonStyle) -> Self {
- self.base = self.base.style(style);
- self
- }
-
- /// Sets the button's size using a [`ButtonSize`].
- fn size(mut self, size: ButtonSize) -> Self {
- self.base = self.base.size(size);
- self
- }
-
- /// Sets a tooltip for the button.
- ///
- /// This method allows a tooltip to be set for the button. The tooltip is a function that
- /// takes a mutable reference to a [`WindowContext`] and returns an [`AnyView`]. The tooltip
- /// is displayed when the user hovers over the button.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- /// use ui::Tooltip;
- ///
- /// Button::new("button_id", "Click me!")
- /// .tooltip(move |cx| {
- /// Tooltip::text("This is a tooltip", cx)
- /// })
- /// .on_click(|event, cx| {
- /// // Handle click event
- /// });
- /// ```
- ///
- /// This will create a button with a tooltip that displays "This is a tooltip" when hovered over.
- fn tooltip(mut self, tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self {
- self.base = self.base.tooltip(tooltip);
- self
- }
-
- fn layer(mut self, elevation: ElevationIndex) -> Self {
- self.base = self.base.layer(elevation);
- self
- }
-}
-
-impl RenderOnce for Button {
- #[allow(refining_impl_trait)]
- fn render(self, cx: &mut WindowContext) -> ButtonLike {
- let is_disabled = self.base.disabled;
- let is_selected = self.base.selected;
-
- let label = self
- .selected_label
- .filter(|_| is_selected)
- .unwrap_or(self.label);
-
- let label_color = if is_disabled {
- Color::Disabled
- } else if is_selected {
- self.selected_label_color.unwrap_or(Color::Selected)
- } else {
- self.label_color.unwrap_or_default()
- };
-
- self.base.child(
- h_flex()
- .gap(Spacing::Small.rems(cx))
- .when(self.icon_position == Some(IconPosition::Start), |this| {
- this.children(self.icon.map(|icon| {
- ButtonIcon::new(icon)
- .disabled(is_disabled)
- .selected(is_selected)
- .selected_icon(self.selected_icon)
- .selected_icon_color(self.selected_icon_color)
- .size(self.icon_size)
- .color(self.icon_color)
- }))
- })
- .child(
- h_flex()
- .gap(Spacing::Medium.rems(cx))
- .justify_between()
- .child(
- Label::new(label)
- .color(label_color)
- .size(self.label_size.unwrap_or_default())
- .when_some(self.alpha, |this, alpha| this.alpha(alpha))
- .line_height_style(LineHeightStyle::UiLabel),
- )
- .children(self.key_binding),
- )
- .when(self.icon_position != Some(IconPosition::Start), |this| {
- this.children(self.icon.map(|icon| {
- ButtonIcon::new(icon)
- .disabled(is_disabled)
- .selected(is_selected)
- .selected_icon(self.selected_icon)
- .selected_icon_color(self.selected_icon_color)
- .size(self.icon_size)
- .color(self.icon_color)
- }))
- }),
- )
- }
-}
@@ -284,7 +284,7 @@ impl ButtonStyle {
elevation: Option<Elevation>,
cx: &mut WindowContext,
) -> ButtonLikeStyles {
- let filled_background = element_bg_from_elevation(elevation, cx).fade_out(0.82);
+ element_bg_from_elevation(elevation, cx).fade_out(0.82);
match self {
ButtonStyle::Filled => ButtonLikeStyles {
@@ -1,7 +1,8 @@
use gpui::{AnyView, DefiniteLength};
+use super::button_like::{ButtonCommon, ButtonLike, ButtonSize, ButtonStyle};
use crate::{prelude::*, ElevationIndex, SelectableButton};
-use crate::{ButtonCommon, ButtonLike, ButtonSize, ButtonStyle, IconName, IconSize};
+use crate::{IconName, IconSize};
use super::button_icon::ButtonIcon;
@@ -1,5 +1,116 @@
-mod checkbox;
mod checkbox_with_label;
-pub use checkbox::*;
pub use checkbox_with_label::*;
+
+use gpui::{div, prelude::*, ElementId, IntoElement, Styled, WindowContext};
+
+use crate::prelude::*;
+use crate::{Color, Icon, IconName, Selection};
+
+/// # Checkbox
+///
+/// Checkboxes are used for multiple choices, not for mutually exclusive choices.
+/// Each checkbox works independently from other checkboxes in the list,
+/// therefore checking an additional box does not affect any other selections.
+#[derive(IntoElement)]
+pub struct Checkbox {
+ id: ElementId,
+ checked: Selection,
+ disabled: bool,
+ on_click: Option<Box<dyn Fn(&Selection, &mut WindowContext) + 'static>>,
+}
+
+impl Checkbox {
+ pub fn new(id: impl Into<ElementId>, checked: Selection) -> Self {
+ Self {
+ id: id.into(),
+ checked,
+ disabled: false,
+ on_click: None,
+ }
+ }
+
+ pub fn disabled(mut self, disabled: bool) -> Self {
+ self.disabled = disabled;
+ self
+ }
+
+ pub fn on_click(mut self, handler: impl Fn(&Selection, &mut WindowContext) + 'static) -> Self {
+ self.on_click = Some(Box::new(handler));
+ self
+ }
+}
+
+impl RenderOnce for Checkbox {
+ fn render(self, cx: &mut WindowContext) -> impl IntoElement {
+ let group_id = format!("checkbox_group_{:?}", self.id);
+
+ let icon = match self.checked {
+ Selection::Selected => Some(Icon::new(IconName::Check).size(IconSize::Small).color(
+ if self.disabled {
+ Color::Disabled
+ } else {
+ Color::Selected
+ },
+ )),
+ Selection::Indeterminate => Some(
+ Icon::new(IconName::Dash)
+ .size(IconSize::Small)
+ .color(if self.disabled {
+ Color::Disabled
+ } else {
+ Color::Selected
+ }),
+ ),
+ Selection::Unselected => None,
+ };
+
+ let selected =
+ self.checked == Selection::Selected || self.checked == Selection::Indeterminate;
+
+ let (bg_color, border_color) = match (self.disabled, selected) {
+ (true, _) => (
+ cx.theme().colors().ghost_element_disabled,
+ cx.theme().colors().border_disabled,
+ ),
+ (false, true) => (
+ cx.theme().colors().element_selected,
+ cx.theme().colors().border,
+ ),
+ (false, false) => (
+ cx.theme().colors().element_background,
+ cx.theme().colors().border,
+ ),
+ };
+
+ h_flex()
+ .id(self.id)
+ .justify_center()
+ .items_center()
+ .size(crate::styles::custom_spacing(cx, 20.))
+ .group(group_id.clone())
+ .child(
+ div()
+ .flex()
+ .flex_none()
+ .justify_center()
+ .items_center()
+ .m(Spacing::Small.px(cx))
+ .size(crate::styles::custom_spacing(cx, 16.))
+ .rounded_sm()
+ .bg(bg_color)
+ .border_1()
+ .border_color(border_color)
+ .when(!self.disabled, |this| {
+ this.group_hover(group_id.clone(), |el| {
+ el.bg(cx.theme().colors().element_hover)
+ })
+ })
+ .children(icon),
+ )
+ .when_some(
+ self.on_click.filter(|_| !self.disabled),
+ |this, on_click| this.on_click(move |_, cx| on_click(&self.checked.inverse(), cx)),
+ )
+ }
+}
@@ -212,16 +212,16 @@ impl ContextMenu {
pub fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
let context = self.action_context.as_ref();
- match self.selected_index.and_then(|ix| self.items.get(ix)) {
- Some(
- ContextMenuItem::Entry {
- handler,
- disabled: false,
- ..
- }
- | ContextMenuItem::CustomEntry { handler, .. },
- ) => (handler)(context, cx),
- _ => {}
+ if let Some(
+ ContextMenuItem::Entry {
+ handler,
+ disabled: false,
+ ..
+ }
+ | ContextMenuItem::CustomEntry { handler, .. },
+ ) = self.selected_index.and_then(|ix| self.items.get(ix))
+ {
+ (handler)(context, cx)
}
cx.emit(DismissEvent);
@@ -1,7 +1,190 @@
mod highlighted_label;
-mod label;
mod label_like;
pub use highlighted_label::*;
-pub use label::*;
pub use label_like::*;
+
+use gpui::{StyleRefinement, WindowContext};
+
+use crate::prelude::*;
+
+/// A struct representing a label element in the UI.
+///
+/// The `Label` struct stores the label text and common properties for a label element.
+/// It provides methods for modifying these properties.
+///
+/// # Examples
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// Label::new("Hello, World!");
+/// ```
+///
+/// **A colored label**, for example labeling a dangerous action:
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// let my_label = Label::new("Delete").color(Color::Error);
+/// ```
+///
+/// **A label with a strikethrough**, for example labeling something that has been deleted:
+///
+/// ```
+/// use ui::prelude::*;
+///
+/// let my_label = Label::new("Deleted").strikethrough(true);
+/// ```
+#[derive(IntoElement)]
+pub struct Label {
+ base: LabelLike,
+ label: SharedString,
+ single_line: bool,
+}
+
+impl Label {
+ /// Creates a new [`Label`] with the given text.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!");
+ /// ```
+ pub fn new(label: impl Into<SharedString>) -> Self {
+ Self {
+ base: LabelLike::new(),
+ label: label.into(),
+ single_line: false,
+ }
+ }
+
+ /// Make the label display in a single line mode
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").single_line();
+ /// ```
+ pub fn single_line(mut self) -> Self {
+ self.single_line = true;
+ self
+ }
+}
+
+// Style methods.
+impl Label {
+ fn style(&mut self) -> &mut StyleRefinement {
+ self.base.base.style()
+ }
+
+ gpui::margin_style_methods!({
+ visibility: pub
+ });
+}
+
+impl LabelCommon for Label {
+ /// Sets the size of the label using a [`LabelSize`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").size(LabelSize::Small);
+ /// ```
+ fn size(mut self, size: LabelSize) -> Self {
+ self.base = self.base.size(size);
+ self
+ }
+
+ fn weight(mut self, weight: gpui::FontWeight) -> Self {
+ self.base = self.base.weight(weight);
+ self
+ }
+
+ /// Sets the line height style of the label using a [`LineHeightStyle`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").line_height_style(LineHeightStyle::UiLabel);
+ /// ```
+ fn line_height_style(mut self, line_height_style: LineHeightStyle) -> Self {
+ self.base = self.base.line_height_style(line_height_style);
+ self
+ }
+
+ /// Sets the color of the label using a [`Color`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").color(Color::Accent);
+ /// ```
+ fn color(mut self, color: Color) -> Self {
+ self.base = self.base.color(color);
+ self
+ }
+
+ /// Sets the strikethrough property of the label.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").strikethrough(true);
+ /// ```
+ fn strikethrough(mut self, strikethrough: bool) -> Self {
+ self.base = self.base.strikethrough(strikethrough);
+ self
+ }
+
+ /// Sets the italic property of the label.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").italic(true);
+ /// ```
+ fn italic(mut self, italic: bool) -> Self {
+ self.base = self.base.italic(italic);
+ self
+ }
+
+ /// Sets the alpha property of the color of label.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use ui::prelude::*;
+ ///
+ /// let my_label = Label::new("Hello, World!").alpha(0.5);
+ /// ```
+ fn alpha(mut self, alpha: f32) -> Self {
+ self.base = self.base.alpha(alpha);
+ self
+ }
+}
+
+impl RenderOnce for Label {
+ fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
+ let target_label = if self.single_line {
+ SharedString::from(self.label.replace('\n', ""))
+ } else {
+ self.label
+ };
+ self.base.child(target_label)
+ }
+}
@@ -62,7 +62,7 @@ impl LabelCommon for HighlightedLabel {
pub fn highlight_ranges(
text: &str,
- indices: &Vec<usize>,
+ indices: &[usize],
style: HighlightStyle,
) -> Vec<(Range<usize>, HighlightStyle)> {
let mut highlight_indices = indices.iter().copied().peekable();
@@ -1,184 +0,0 @@
-use gpui::{StyleRefinement, WindowContext};
-
-use crate::{prelude::*, LabelCommon, LabelLike, LabelSize, LineHeightStyle};
-
-/// A struct representing a label element in the UI.
-///
-/// The `Label` struct stores the label text and common properties for a label element.
-/// It provides methods for modifying these properties.
-///
-/// # Examples
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// Label::new("Hello, World!");
-/// ```
-///
-/// **A colored label**, for example labeling a dangerous action:
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// let my_label = Label::new("Delete").color(Color::Error);
-/// ```
-///
-/// **A label with a strikethrough**, for example labeling something that has been deleted:
-///
-/// ```
-/// use ui::prelude::*;
-///
-/// let my_label = Label::new("Deleted").strikethrough(true);
-/// ```
-#[derive(IntoElement)]
-pub struct Label {
- base: LabelLike,
- label: SharedString,
- single_line: bool,
-}
-
-impl Label {
- /// Creates a new [`Label`] with the given text.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!");
- /// ```
- pub fn new(label: impl Into<SharedString>) -> Self {
- Self {
- base: LabelLike::new(),
- label: label.into(),
- single_line: false,
- }
- }
-
- /// Make the label display in a single line mode
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").single_line();
- /// ```
- pub fn single_line(mut self) -> Self {
- self.single_line = true;
- self
- }
-}
-
-// Style methods.
-impl Label {
- fn style(&mut self) -> &mut StyleRefinement {
- self.base.base.style()
- }
-
- gpui::margin_style_methods!({
- visibility: pub
- });
-}
-
-impl LabelCommon for Label {
- /// Sets the size of the label using a [`LabelSize`].
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").size(LabelSize::Small);
- /// ```
- fn size(mut self, size: LabelSize) -> Self {
- self.base = self.base.size(size);
- self
- }
-
- fn weight(mut self, weight: gpui::FontWeight) -> Self {
- self.base = self.base.weight(weight);
- self
- }
-
- /// Sets the line height style of the label using a [`LineHeightStyle`].
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").line_height_style(LineHeightStyle::UiLabel);
- /// ```
- fn line_height_style(mut self, line_height_style: LineHeightStyle) -> Self {
- self.base = self.base.line_height_style(line_height_style);
- self
- }
-
- /// Sets the color of the label using a [`Color`].
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").color(Color::Accent);
- /// ```
- fn color(mut self, color: Color) -> Self {
- self.base = self.base.color(color);
- self
- }
-
- /// Sets the strikethrough property of the label.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").strikethrough(true);
- /// ```
- fn strikethrough(mut self, strikethrough: bool) -> Self {
- self.base = self.base.strikethrough(strikethrough);
- self
- }
-
- /// Sets the italic property of the label.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").italic(true);
- /// ```
- fn italic(mut self, italic: bool) -> Self {
- self.base = self.base.italic(italic);
- self
- }
-
- /// Sets the alpha property of the color of label.
- ///
- /// # Examples
- ///
- /// ```
- /// use ui::prelude::*;
- ///
- /// let my_label = Label::new("Hello, World!").alpha(0.5);
- /// ```
- fn alpha(mut self, alpha: f32) -> Self {
- self.base = self.base.alpha(alpha);
- self
- }
-}
-
-impl RenderOnce for Label {
- fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
- let target_label = if self.single_line {
- SharedString::from(self.label.replace('\n', ""))
- } else {
- self.label
- };
- self.base.child(target_label)
- }
-}
@@ -59,6 +59,12 @@ pub struct LabelLike {
alpha: Option<f32>,
}
+impl Default for LabelLike {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl LabelLike {
pub fn new() -> Self {
Self {
@@ -1,11 +1,76 @@
-mod list;
mod list_header;
mod list_item;
mod list_separator;
mod list_sub_header;
-pub use list::*;
pub use list_header::*;
pub use list_item::*;
pub use list_separator::*;
pub use list_sub_header::*;
+
+use gpui::AnyElement;
+use smallvec::SmallVec;
+
+use crate::{prelude::*, v_flex, Label};
+
+pub use ListHeader;
+
+#[derive(IntoElement)]
+pub struct List {
+ /// Message to display when the list is empty
+ /// Defaults to "No items"
+ empty_message: SharedString,
+ header: Option<ListHeader>,
+ toggle: Option<bool>,
+ children: SmallVec<[AnyElement; 2]>,
+}
+
+impl Default for List {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl List {
+ pub fn new() -> Self {
+ Self {
+ empty_message: "No items".into(),
+ header: None,
+ toggle: None,
+ children: SmallVec::new(),
+ }
+ }
+
+ pub fn empty_message(mut self, empty_message: impl Into<SharedString>) -> Self {
+ self.empty_message = empty_message.into();
+ self
+ }
+
+ pub fn header(mut self, header: impl Into<Option<ListHeader>>) -> Self {
+ self.header = header.into();
+ self
+ }
+
+ pub fn toggle(mut self, toggle: impl Into<Option<bool>>) -> Self {
+ self.toggle = toggle.into();
+ self
+ }
+}
+
+impl ParentElement for List {
+ fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
+ self.children.extend(elements)
+ }
+}
+
+impl RenderOnce for List {
+ fn render(self, _cx: &mut WindowContext) -> impl IntoElement {
+ v_flex().w_full().py_1().children(self.header).map(|this| {
+ match (self.children.is_empty(), self.toggle) {
+ (false, _) => this.children(self.children),
+ (true, Some(false)) => this,
+ (true, _) => this.child(Label::new(self.empty_message.clone()).color(Color::Muted)),
+ }
+ })
+ }
+}
@@ -13,6 +13,12 @@ pub struct List {
children: SmallVec<[AnyElement; 2]>,
}
+impl Default for List {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl List {
pub fn new() -> Self {
Self {
@@ -97,6 +97,12 @@ pub struct ModalHeader {
show_back_button: bool,
}
+impl Default for ModalHeader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ModalHeader {
pub fn new() -> Self {
Self {
@@ -182,6 +188,12 @@ pub struct ModalRow {
children: SmallVec<[AnyElement; 2]>,
}
+impl Default for ModalRow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ModalRow {
pub fn new() -> Self {
Self {
@@ -208,6 +220,12 @@ pub struct ModalFooter {
end_slot: Option<AnyElement>,
}
+impl Default for ModalFooter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ModalFooter {
pub fn new() -> Self {
Self {
@@ -247,6 +265,12 @@ pub struct Section {
children: SmallVec<[AnyElement; 2]>,
}
+impl Default for Section {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Section {
pub fn new() -> Self {
Self {
@@ -381,15 +405,15 @@ impl RenderOnce for SectionHeader {
}
}
-impl Into<SectionHeader> for SharedString {
- fn into(self) -> SectionHeader {
- SectionHeader::new(self)
+impl From<SharedString> for SectionHeader {
+ fn from(val: SharedString) -> Self {
+ SectionHeader::new(val)
}
}
-impl Into<SectionHeader> for &'static str {
- fn into(self) -> SectionHeader {
- let label: SharedString = self.into();
+impl From<&'static str> for SectionHeader {
+ fn from(val: &'static str) -> Self {
+ let label: SharedString = val.into();
SectionHeader::new(label)
}
}
@@ -56,6 +56,12 @@ impl RenderOnce for Popover {
}
}
+impl Default for Popover {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Popover {
pub fn new() -> Self {
Self {
@@ -156,7 +156,7 @@ impl<M: ManagedView> PopoverMenu<M> {
}
fn resolved_attach(&self) -> AnchorCorner {
- self.attach.unwrap_or_else(|| match self.anchor {
+ self.attach.unwrap_or(match self.anchor {
AnchorCorner::TopLeft => AnchorCorner::BottomLeft,
AnchorCorner::TopRight => AnchorCorner::BottomRight,
AnchorCorner::BottomLeft => AnchorCorner::TopLeft,
@@ -322,7 +322,7 @@ impl<M: ManagedView> Element for PopoverMenu<M> {
menu.prepaint(cx);
}
- let hitbox_id = request_layout.child_layout_id.map(|layout_id| {
+ request_layout.child_layout_id.map(|layout_id| {
let bounds = cx.layout_bounds(layout_id);
cx.with_element_state(global_id.unwrap(), |element_state, _cx| {
let mut element_state: PopoverMenuElementState<M> = element_state.unwrap();
@@ -331,9 +331,7 @@ impl<M: ManagedView> Element for PopoverMenu<M> {
});
cx.insert_hitbox(bounds, false).id
- });
-
- hitbox_id
+ })
}
fn paint(
@@ -8,6 +8,12 @@ pub struct SettingsContainer {
children: SmallVec<[AnyElement; 2]>,
}
+impl Default for SettingsContainer {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl SettingsContainer {
pub fn new() -> Self {
Self {
@@ -23,7 +23,7 @@ pub fn text_for_action_in(
pub fn text_for_key_binding(key_binding: KeyBinding, platform_style: PlatformStyle) -> String {
key_binding
.keystrokes()
- .into_iter()
+ .iter()
.map(|keystroke| text_for_keystroke(keystroke, platform_style))
.collect::<Vec<_>>()
.join(" ")
@@ -18,9 +18,8 @@ pub fn window_appearance(cx: &WindowContext) -> WindowBackgroundAppearance {
/// Helps determine if you need to take extra steps to prevent
/// transparent backgrounds.
pub fn window_is_transparent(cx: &WindowContext) -> bool {
- match window_appearance(cx) {
- WindowBackgroundAppearance::Transparent => true,
- WindowBackgroundAppearance::Blurred => true,
- _ => false,
- }
+ matches!(
+ window_appearance(cx),
+ WindowBackgroundAppearance::Transparent | WindowBackgroundAppearance::Blurred
+ )
}
@@ -9,9 +9,9 @@ pub enum Elevation {
ElementIndex(ElementIndex),
}
-impl Into<Elevation> for ElevationIndex {
- fn into(self) -> Elevation {
- Elevation::ElevationIndex(self)
+impl From<ElevationIndex> for Elevation {
+ fn from(val: ElevationIndex) -> Self {
+ Elevation::ElevationIndex(val)
}
}
@@ -42,16 +42,6 @@ impl FormatDistance {
Self::new(date, DateTimeType::Local(Local::now()))
}
- pub fn to_string(self) -> String {
- format_distance(
- self.date,
- self.base_date.to_naive(),
- self.include_seconds,
- self.add_suffix,
- self.hide_prefix,
- )
- }
-
pub fn include_seconds(mut self, include_seconds: bool) -> Self {
self.include_seconds = include_seconds;
self
@@ -68,6 +58,21 @@ impl FormatDistance {
}
}
+impl std::fmt::Display for FormatDistance {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "{}",
+ format_distance(
+ self.date,
+ self.base_date.to_naive(),
+ self.include_seconds,
+ self.add_suffix,
+ self.hide_prefix,
+ )
+ )
+ }
+}
/// Calculates the distance in seconds between two [`NaiveDateTime`] objects.
/// It returns a signed integer denoting the difference. If `date` is earlier than `base_date`, the returned value will be negative.
///
@@ -118,12 +123,7 @@ fn distance_string(
}
.to_string()
} else if distance < 40 && include_seconds {
- if hide_prefix {
- "half a minute"
- } else {
- "half a minute"
- }
- .to_string()
+ "half a minute".to_string()
} else if distance < 60 && include_seconds {
if hide_prefix {
"a minute"
@@ -234,8 +234,8 @@ impl Eq for PathMatcher {}
impl PathMatcher {
pub fn new(globs: &[String]) -> Result<Self, globset::Error> {
let globs = globs
- .into_iter()
- .map(|glob| Glob::new(&glob))
+ .iter()
+ .map(|glob| Glob::new(glob))
.collect::<Result<Vec<_>, _>>()?;
let sources = globs.iter().map(|glob| glob.glob().to_owned()).collect();
let mut glob_builder = GlobSetBuilder::new();
@@ -263,7 +263,7 @@ impl PathMatcher {
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)
}
@@ -251,7 +251,7 @@ pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
for line in env.split_terminator('\n') {
if let Some(separator_index) = line.find('=') {
- if &line[..separator_index] != "" {
+ if !line[..separator_index].is_empty() {
if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
f(key, value)
}
@@ -91,7 +91,7 @@ impl BranchListDelegate {
branch_name_trailoff_after: usize,
cx: &AppContext,
) -> Result<Self> {
- let project = workspace.project().read(&cx);
+ let project = workspace.project().read(cx);
let repo = project
.get_first_worktree_root_repo(cx)
.context("failed to get root repository for first worktree")?;
@@ -317,12 +317,12 @@ impl PickerDelegate for BranchListDelegate {
let repo = project.get_first_worktree_root_repo(cx).context(
"failed to get root repository for first worktree",
)?;
- let status = repo.create_branch(¤t_pick);
+ let status = repo.create_branch(current_pick);
if status.is_err() {
this.delegate.display_error_toast(format!("Failed to create branch '{current_pick}', check for conflicts or unstashed files"), cx);
status?;
}
- let status = repo.change_branch(¤t_pick);
+ let status = repo.change_branch(current_pick);
if status.is_err() {
this.delegate.display_error_toast(format!("Failed to check branch '{current_pick}', check for conflicts or unstashed files"), cx);
status?;
@@ -633,7 +633,7 @@ pub fn command_interceptor(mut input: &str, cx: &AppContext) -> Option<CommandIn
let range_prefix = input[0..(input.len() - query.len())].to_string();
let query = query.as_str().trim();
- let action = if range.is_some() && query == "" {
+ let action = if range.is_some() && query.is_empty() {
Some(
GoToLine {
range: range.clone().unwrap(),
@@ -681,7 +681,7 @@ pub fn command_interceptor(mut input: &str, cx: &AppContext) -> Option<CommandIn
}
for command in commands(cx).iter() {
- if let Some(action) = command.parse(&query, cx) {
+ if let Some(action) = command.parse(query, cx) {
let string = ":".to_owned() + &range_prefix + command.prefix + command.suffix;
let positions = generate_positions(&string, &(range_prefix + query));
@@ -847,7 +847,7 @@ mod test {
cx.simulate_keystrokes("i @ escape");
cx.simulate_keystrokes(": w enter");
- assert_eq!(fs.load(&path).await.unwrap(), "@\n");
+ assert_eq!(fs.load(path).await.unwrap(), "@\n");
fs.as_fake().insert_file(path, b"oops\n".to_vec()).await;
@@ -857,12 +857,12 @@ mod test {
assert!(cx.has_pending_prompt());
// "Cancel"
cx.simulate_prompt_answer(0);
- assert_eq!(fs.load(&path).await.unwrap(), "oops\n");
+ assert_eq!(fs.load(path).await.unwrap(), "oops\n");
assert!(!cx.has_pending_prompt());
// force overwrite
cx.simulate_keystrokes(": w ! enter");
assert!(!cx.has_pending_prompt());
- assert_eq!(fs.load(&path).await.unwrap(), "@@\n");
+ assert_eq!(fs.load(path).await.unwrap(), "@@\n");
}
#[gpui::test]
@@ -41,7 +41,7 @@ impl Vim {
second_char: char,
cx: &mut ViewContext<Self>,
) {
- let text = lookup_digraph(first_char, second_char, &cx);
+ let text = lookup_digraph(first_char, second_char, cx);
self.pop_operator(cx);
if self.editor_input_enabled() {
@@ -634,16 +634,16 @@ impl Motion {
Backspace => (backspace(map, point, times), SelectionGoal::None),
Down {
display_lines: false,
- } => up_down_buffer_rows(map, point, goal, times as isize, &text_layout_details),
+ } => up_down_buffer_rows(map, point, goal, times as isize, text_layout_details),
Down {
display_lines: true,
- } => down_display(map, point, goal, times, &text_layout_details),
+ } => down_display(map, point, goal, times, text_layout_details),
Up {
display_lines: false,
- } => up_down_buffer_rows(map, point, goal, 0 - times as isize, &text_layout_details),
+ } => up_down_buffer_rows(map, point, goal, 0 - times as isize, text_layout_details),
Up {
display_lines: true,
- } => up_display(map, point, goal, times, &text_layout_details),
+ } => up_display(map, point, goal, times, text_layout_details),
Right => (right(map, point, times), SelectionGoal::None),
Space => (space(map, point, times), SelectionGoal::None),
NextWordStart { ignore_punctuation } => (
@@ -802,9 +802,9 @@ impl Motion {
StartOfLineDownward => (next_line_start(map, point, times - 1), SelectionGoal::None),
EndOfLineDownward => (last_non_whitespace(map, point, times), SelectionGoal::None),
GoToColumn => (go_to_column(map, point, times), SelectionGoal::None),
- WindowTop => window_top(map, point, &text_layout_details, times - 1),
- WindowMiddle => window_middle(map, point, &text_layout_details),
- WindowBottom => window_bottom(map, point, &text_layout_details, times - 1),
+ WindowTop => window_top(map, point, text_layout_details, times - 1),
+ WindowMiddle => window_middle(map, point, text_layout_details),
+ WindowBottom => window_bottom(map, point, text_layout_details, times - 1),
Jump { line, anchor } => mark::jump_motion(map, *anchor, *line),
ZedSearchResult { new_selections, .. } => {
// There will be only one selection, as
@@ -864,7 +864,7 @@ impl Motion {
selection.head(),
selection.goal,
times,
- &text_layout_details,
+ text_layout_details,
) {
let mut selection = selection.clone();
selection.set_head(new_head, goal);
@@ -896,11 +896,11 @@ impl Motion {
ignore_punctuation: _,
} = self
{
- let start_row = MultiBufferRow(selection.start.to_point(&map).row);
- if selection.end.to_point(&map).row > start_row.0 {
+ let start_row = MultiBufferRow(selection.start.to_point(map).row);
+ if selection.end.to_point(map).row > start_row.0 {
selection.end =
Point::new(start_row.0, map.buffer_snapshot.line_len(start_row))
- .to_display_point(&map)
+ .to_display_point(map)
}
}
@@ -909,8 +909,8 @@ impl Motion {
// becomes inclusive. Example: "}" moves to the first line after a paragraph,
// but "d}" will not include that line.
let mut inclusive = self.inclusive();
- let start_point = selection.start.to_point(&map);
- let mut end_point = selection.end.to_point(&map);
+ let start_point = selection.start.to_point(map);
+ let mut end_point = selection.end.to_point(map);
// DisplayPoint
@@ -1108,7 +1108,7 @@ fn up_display(
text_layout_details: &TextLayoutDetails,
) -> (DisplayPoint, SelectionGoal) {
for _ in 0..times {
- (point, goal) = movement::up(map, point, goal, true, &text_layout_details);
+ (point, goal) = movement::up(map, point, goal, true, text_layout_details);
}
(point, goal)
@@ -1558,7 +1558,7 @@ fn sentence_backwards(
point: DisplayPoint,
mut times: usize,
) -> DisplayPoint {
- let mut start = point.to_point(&map).to_offset(&map.buffer_snapshot);
+ let mut start = point.to_point(map).to_offset(&map.buffer_snapshot);
let mut chars = map.reverse_buffer_chars_at(start).peekable();
let mut was_newline = map
@@ -1585,7 +1585,7 @@ fn sentence_backwards(
return map.clip_point(
start_of_next_sentence
.to_offset(&map.buffer_snapshot)
- .to_display_point(&map),
+ .to_display_point(map),
Bias::Left,
);
}
@@ -1596,11 +1596,11 @@ fn sentence_backwards(
was_newline = ch == '\n';
}
- return DisplayPoint::zero();
+ DisplayPoint::zero()
}
fn sentence_forwards(map: &DisplaySnapshot, point: DisplayPoint, mut times: usize) -> DisplayPoint {
- let start = point.to_point(&map).to_offset(&map.buffer_snapshot);
+ let start = point.to_point(map).to_offset(&map.buffer_snapshot);
let mut chars = map.buffer_chars_at(start).peekable();
let mut was_newline = map
@@ -1629,7 +1629,7 @@ fn sentence_forwards(map: &DisplaySnapshot, point: DisplayPoint, mut times: usiz
return map.clip_point(
start_of_next_sentence
.to_offset(&map.buffer_snapshot)
- .to_display_point(&map),
+ .to_display_point(map),
Bias::Right,
);
}
@@ -1638,7 +1638,7 @@ fn sentence_forwards(map: &DisplaySnapshot, point: DisplayPoint, mut times: usiz
was_newline = ch == '\n' && chars.peek().is_some_and(|(c, _)| *c == '\n');
}
- return map.max_point();
+ map.max_point()
}
fn next_non_blank(map: &DisplaySnapshot, start: usize) -> usize {
@@ -1648,16 +1648,16 @@ fn next_non_blank(map: &DisplaySnapshot, start: usize) -> usize {
}
}
- return map.buffer_snapshot.len();
+ map.buffer_snapshot.len()
}
// given the offset after a ., !, or ? find the start of the next sentence.
// if this is not a sentence boundary, returns None.
fn start_of_next_sentence(map: &DisplaySnapshot, end_of_sentence: usize) -> Option<usize> {
- let mut chars = map.buffer_chars_at(end_of_sentence);
+ let chars = map.buffer_chars_at(end_of_sentence);
let mut seen_space = false;
- while let Some((char, offset)) = chars.next() {
+ for (char, offset) in chars {
if !seen_space && (char == ')' || char == ']' || char == '"' || char == '\'') {
continue;
}
@@ -1673,7 +1673,7 @@ fn start_of_next_sentence(map: &DisplaySnapshot, end_of_sentence: usize) -> Opti
}
}
- return Some(map.buffer_snapshot.len());
+ Some(map.buffer_snapshot.len())
}
fn start_of_document(map: &DisplaySnapshot, point: DisplayPoint, line: usize) -> DisplayPoint {
@@ -1839,7 +1839,7 @@ fn next_line_start(map: &DisplaySnapshot, point: DisplayPoint, times: usize) ->
}
fn previous_line_start(map: &DisplaySnapshot, point: DisplayPoint, times: usize) -> DisplayPoint {
- let correct_line = start_of_relative_buffer_row(map, point, (times as isize) * -1);
+ let correct_line = start_of_relative_buffer_row(map, point, -(times as isize));
first_non_whitespace(map, false, correct_line)
}
@@ -139,7 +139,7 @@ impl Vim {
}
Mode::VisualBlock => {
ranges.push(selection.start..selection.end);
- if cursor_positions.len() == 0 {
+ if cursor_positions.is_empty() {
cursor_positions.push(selection.start..selection.start);
}
}
@@ -165,7 +165,7 @@ impl Vim {
let text = snapshot
.text_for_range(range.start..range.end)
.flat_map(|s| s.chars())
- .flat_map(|c| transform(c))
+ .flat_map(transform)
.collect::<String>();
buffer.edit([(range, text)], None, cx)
@@ -61,7 +61,7 @@ impl Vim {
selection.start.to_offset(map, Bias::Left);
let classifier = map
.buffer_snapshot
- .char_classifier_at(selection.start.to_point(&map));
+ .char_classifier_at(selection.start.to_point(map));
for (ch, offset) in map.buffer_chars_at(start_offset) {
if ch == '\n' || !classifier.is_whitespace(ch) {
break;
@@ -136,7 +136,7 @@ fn expand_changed_word_selection(
.next()
.map(|(c, _)| !classifier.is_whitespace(c))
.unwrap_or_default();
- return in_word;
+ in_word
};
if (times.is_none() || times.unwrap() == 1) && is_in_word() {
let next_char = map
@@ -164,7 +164,7 @@ fn expand_changed_word_selection(
} else {
Motion::NextWordStart { ignore_punctuation }
};
- motion.expand_selection(map, selection, times, false, &text_layout_details)
+ motion.expand_selection(map, selection, times, false, text_layout_details)
}
}
@@ -36,13 +36,13 @@ impl Vim {
if selection.is_empty()
&& map
.buffer_snapshot
- .line_len(MultiBufferRow(selection.start.to_point(&map).row))
+ .line_len(MultiBufferRow(selection.start.to_point(map).row))
== 0
{
selection.end = map
.buffer_snapshot
.clip_point(
- Point::new(selection.start.to_point(&map).row + 1, 0),
+ Point::new(selection.start.to_point(map).row + 1, 0),
Bias::Left,
)
.to_display_point(map)
@@ -34,7 +34,7 @@ pub fn register(editor: &mut Editor, cx: &mut ViewContext<Vim>) {
vim.record_current_action(cx);
let count = vim.take_count(cx).unwrap_or(1);
let step = if action.step { -1 } else { 0 };
- vim.increment(count as i32 * -1, step, cx)
+ vim.increment(-(count as i32), step, cx)
});
}
@@ -47,10 +47,10 @@ impl Vim {
let snapshot = editor.buffer().read(cx).snapshot(cx);
for selection in editor.selections.all_adjusted(cx) {
- if !selection.is_empty() {
- if vim.mode != Mode::VisualBlock || new_anchors.is_empty() {
- new_anchors.push((true, snapshot.anchor_before(selection.start)))
- }
+ if !selection.is_empty()
+ && (vim.mode != Mode::VisualBlock || new_anchors.is_empty())
+ {
+ new_anchors.push((true, snapshot.anchor_before(selection.start)))
}
for row in selection.start.row..=selection.end.row {
let start = if row == selection.start.row {
@@ -80,10 +80,8 @@ impl Vim {
if selection.is_empty() {
new_anchors.push((false, snapshot.anchor_after(range.end)))
}
- } else {
- if selection.is_empty() {
- new_anchors.push((true, snapshot.anchor_after(start)))
- }
+ } else if selection.is_empty() {
+ new_anchors.push((true, snapshot.anchor_after(start)))
}
}
}
@@ -140,7 +138,11 @@ fn find_number(
begin = None;
num = String::new();
}
- if num == "0" && ch == 'x' && chars.peek().is_some() && chars.peek().unwrap().is_digit(16) {
+ if num == "0"
+ && ch == 'x'
+ && chars.peek().is_some()
+ && chars.peek().unwrap().is_ascii_hexdigit()
+ {
radix = 16;
begin = None;
num = String::new();
@@ -156,13 +158,11 @@ fn find_number(
begin = Some(offset);
}
num.push(ch);
- } else {
- if begin.is_some() {
- end = Some(offset);
- break;
- } else if ch == '\n' {
- break;
- }
+ } else if begin.is_some() {
+ end = Some(offset);
+ break;
+ } else if ch == '\n' {
+ break;
}
offset += ch.len_utf8();
}
@@ -102,7 +102,6 @@ impl Vim {
cx,
)
}
- return;
} else {
self.update_editor(cx, |_, editor, cx| {
let map = editor.snapshot(cx);
@@ -117,7 +117,7 @@ impl Vim {
to_insert = "\n".to_owned() + &to_insert;
}
} else if !line_mode && vim.mode == Mode::VisualLine {
- to_insert = to_insert + "\n";
+ to_insert += "\n";
}
let display_range = if !selection.is_empty() {
@@ -432,7 +432,7 @@ mod test {
the laˇzy dog"});
// paste in visual mode
cx.simulate_shared_keystrokes("v i w p").await;
- cx.shared_state().await.assert_eq(&indoc! {"
+ cx.shared_state().await.assert_eq(indoc! {"
The quick brown
the•
ˇfox jumps over
@@ -178,10 +178,7 @@ impl Vim {
}
globals.last_replayed_register = Some(register);
- let mut replayer = globals
- .replayer
- .get_or_insert_with(|| Replayer::new())
- .clone();
+ let mut replayer = globals.replayer.get_or_insert_with(Replayer::new).clone();
replayer.replay(repeated_actions, cx);
}
@@ -313,10 +310,7 @@ impl Vim {
let globals = Vim::globals(cx);
globals.dot_replaying = true;
- let mut replayer = globals
- .replayer
- .get_or_insert_with(|| Replayer::new())
- .clone();
+ let mut replayer = globals.replayer.get_or_insert_with(Replayer::new).clone();
replayer.replay(actions, cx);
}
}
@@ -298,7 +298,7 @@ impl Vim {
return None;
}
let mut query = action.query.clone();
- if query == "" {
+ if query.is_empty() {
query = search_bar.query(cx);
};
@@ -365,7 +365,7 @@ impl Vim {
if replacement.is_case_sensitive {
options.set(SearchOptions::CASE_SENSITIVE, true)
}
- let search = if replacement.search == "" {
+ let search = if replacement.search.is_empty() {
search_bar.query(cx)
} else {
replacement.search
@@ -442,7 +442,7 @@ impl Replacement {
for c in chars {
if escaped {
escaped = false;
- if phase == 1 && c.is_digit(10) {
+ if phase == 1 && c.is_ascii_digit() {
buffer.push('$')
// unescape escaped parens
} else if phase == 0 && c == '(' || c == ')' {
@@ -121,7 +121,7 @@ impl Vim {
if is_first {
is_first = false;
} else {
- text.push_str("\n");
+ text.push('\n');
}
let initial_len = text.len();
@@ -147,7 +147,7 @@ impl Vim {
text.push_str(chunk);
}
if is_last_line {
- text.push_str("\n");
+ text.push('\n');
}
clipboard_selections.push(ClipboardSelection {
len: text.len() - initial_len,
@@ -452,10 +452,10 @@ fn argument(
// TODO: Is there any better way to filter out string brackets?
// Used to filter out string brackets
- return matches!(
+ matches!(
buffer.chars_at(open.start).next(),
Some('(' | '[' | '{' | '<' | '|')
- );
+ )
};
// Find the brackets containing the cursor
@@ -481,9 +481,7 @@ fn argument(
parent_covers_bracket_range = covers_bracket_range;
// Unable to find a child node with a parent that covers the bracket range, so no argument to select
- if cursor.goto_first_child_for_byte(offset).is_none() {
- return None;
- }
+ cursor.goto_first_child_for_byte(offset)?;
}
let mut argument_node = cursor.node();
@@ -656,7 +654,7 @@ fn is_sentence_end(map: &DisplaySnapshot, offset: usize) -> bool {
}
}
- return false;
+ false
}
/// Expands the passed range to include whitespace on one side or the other in a line. Attempts to add the
@@ -669,8 +667,8 @@ fn expand_to_include_whitespace(
let mut range = range.start.to_offset(map, Bias::Left)..range.end.to_offset(map, Bias::Right);
let mut whitespace_included = false;
- let mut chars = map.buffer_chars_at(range.end).peekable();
- while let Some((char, offset)) = chars.next() {
+ let chars = map.buffer_chars_at(range.end).peekable();
+ for (char, offset) in chars {
if char == '\n' && stop_at_newline {
break;
}
@@ -1053,7 +1051,7 @@ mod test {
.assert_matches();
}
- const PARAGRAPH_EXAMPLES: &[&'static str] = &[
+ const PARAGRAPH_EXAMPLES: &[&str] = &[
// Single line
"ˇThe quick brown fox jumpˇs over the lazy dogˇ.ˇ",
// Multiple lines without empty lines
@@ -1140,7 +1138,7 @@ mod test {
async fn test_visual_paragraph_object(cx: &mut gpui::TestAppContext) {
let mut cx = NeovimBackedTestContext::new(cx).await;
- const EXAMPLES: &[&'static str] = &[
+ const EXAMPLES: &[&str] = &[
indoc! {"
ˇThe quick brown
fox jumps over
@@ -255,7 +255,7 @@ mod test {
async fn test_replace_mode_undo(cx: &mut gpui::TestAppContext) {
let mut cx: NeovimBackedTestContext = NeovimBackedTestContext::new(cx).await;
- const UNDO_REPLACE_EXAMPLES: &[&'static str] = &[
+ const UNDO_REPLACE_EXAMPLES: &[&str] = &[
// replace undo with single line
"ˇThe quick brown fox jumps over the lazy dog.",
// replace undo with ending line
@@ -63,7 +63,7 @@ impl Vim {
object.range(&display_map, selection.clone(), false)
}
SurroundsType::Motion(motion) => {
- let range = motion
+ motion
.range(
&display_map,
selection.clone(),
@@ -89,8 +89,7 @@ impl Vim {
);
}
range
- });
- range
+ })
}
SurroundsType::Selection => Some(selection.range()),
};
@@ -270,17 +269,14 @@ impl Vim {
let mut open_str = pair.start.clone();
let start = offset;
let mut end = start + 1;
- match chars_and_offset.peek() {
- Some((next_ch, _)) => {
- // If the next position is already a space or line break,
- // we don't need to splice another space even under around
- if surround && !next_ch.is_whitespace() {
- open_str.push_str(" ");
- } else if !surround && next_ch.to_string() == " " {
- end += 1;
- }
+ if let Some((next_ch, _)) = chars_and_offset.peek() {
+ // If the next position is already a space or line break,
+ // we don't need to splice another space even under around
+ if surround && !next_ch.is_whitespace() {
+ open_str.push(' ');
+ } else if !surround && next_ch.to_string() == " " {
+ end += 1;
}
- None => {}
}
edits.push((start..end, open_str));
anchors.push(start..start);
@@ -300,7 +296,7 @@ impl Vim {
let end = start + 1;
if let Some((next_ch, _)) = reverse_chars_and_offsets.peek() {
if surround && !next_ch.is_whitespace() {
- close_str.insert_str(0, " ")
+ close_str.insert(0, ' ')
} else if !surround && next_ch.to_string() == " " {
start -= 1;
}
@@ -317,7 +313,7 @@ impl Vim {
let stable_anchors = editor
.selections
.disjoint_anchors()
- .into_iter()
+ .iter()
.map(|selection| {
let start = selection.start.bias_left(&display_map.buffer_snapshot);
start..start
@@ -367,12 +363,12 @@ impl Vim {
&& selection.end.row() == range.end.row())
{
valid = true;
- let mut chars_and_offset = display_map
+ let chars_and_offset = display_map
.buffer_chars_at(
range.start.to_offset(&display_map, Bias::Left),
)
.peekable();
- while let Some((ch, offset)) = chars_and_offset.next() {
+ for (ch, offset) in chars_and_offset {
if ch.to_string() == pair.start {
anchors.push(offset..offset);
break;
@@ -392,7 +388,7 @@ impl Vim {
});
});
}
- return valid;
+ valid
}
}
@@ -401,7 +397,7 @@ fn find_surround_pair<'a>(pairs: &'a [BracketPair], ch: &str) -> Option<&'a Brac
}
fn all_support_surround_pair() -> Vec<BracketPair> {
- return vec![
+ vec![
BracketPair {
start: "{".into(),
end: "}".into(),
@@ -465,7 +461,7 @@ fn all_support_surround_pair() -> Vec<BracketPair> {
surround: true,
newline: false,
},
- ];
+ ]
}
fn pair_to_object(pair: &BracketPair) -> Option<Object> {
@@ -443,15 +443,14 @@ impl Vim {
// Sync editor settings like clip mode
self.sync_vim_settings(cx);
- if VimSettings::get_global(cx).toggle_relative_line_numbers {
- if self.mode != self.last_mode {
- if self.mode == Mode::Insert || self.last_mode == Mode::Insert {
- self.update_editor(cx, |vim, editor, cx| {
- let is_relative = vim.mode != Mode::Insert;
- editor.set_relative_line_number(Some(is_relative), cx)
- });
- }
- }
+ if VimSettings::get_global(cx).toggle_relative_line_numbers
+ && self.mode != self.last_mode
+ && (self.mode == Mode::Insert || self.last_mode == Mode::Insert)
+ {
+ self.update_editor(cx, |vim, editor, cx| {
+ let is_relative = vim.mode != Mode::Insert;
+ editor.set_relative_line_number(Some(is_relative), cx)
+ });
}
if leave_selections {
@@ -510,10 +509,8 @@ impl Vim {
point = movement::left(map, selection.head());
}
selection.collapse_to(point, selection.goal)
- } else if !last_mode.is_visual() && mode.is_visual() {
- if selection.is_empty() {
- selection.end = movement::right(map, selection.start);
- }
+ } else if !last_mode.is_visual() && mode.is_visual() && selection.is_empty() {
+ selection.end = movement::right(map, selection.start);
}
});
})
@@ -526,7 +523,7 @@ impl Vim {
return global_state.recorded_count;
}
- let count = if self.post_count == None && self.pre_count == None {
+ let count = if self.post_count.is_none() && self.pre_count.is_none() {
return None;
} else {
Some(self.post_count.take().unwrap_or(1) * self.pre_count.take().unwrap_or(1))
@@ -1046,10 +1043,11 @@ impl Vim {
}
},
Some(Operator::Jump { line }) => self.jump(text, line, cx),
- _ => match self.mode {
- Mode::Replace => self.multi_replace(text, cx),
- _ => {}
- },
+ _ => {
+ if self.mode == Mode::Replace {
+ self.multi_replace(text, cx)
+ }
+ }
}
}
@@ -83,7 +83,7 @@ pub fn register(editor: &mut Editor, cx: &mut ViewContext<Vim>) {
return;
};
let ranges = start
- .into_iter()
+ .iter()
.zip(end)
.zip(reversed)
.map(|((start, end), reversed)| (*start, *end, reversed))
@@ -229,7 +229,7 @@ impl Vim {
head = movement::saturating_left(map, head);
}
- let Some((new_head, _)) = move_selection(&map, head, goal) else {
+ let Some((new_head, _)) = move_selection(map, head, goal) else {
return;
};
head = new_head;
@@ -479,7 +479,7 @@ impl Vim {
let stable_anchors = editor
.selections
.disjoint_anchors()
- .into_iter()
+ .iter()
.map(|selection| {
let start = selection.start.bias_left(&display_map.buffer_snapshot);
start..start
@@ -79,7 +79,7 @@ impl BaseKeymap {
Self::OPTIONS
.iter()
.copied()
- .find_map(|(name, value)| (name == option).then(|| value))
+ .find_map(|(name, value)| (name == option).then_some(value))
.unwrap_or_default()
}
}
@@ -18,6 +18,12 @@ const NUMBER_OF_HINTS: usize = 10;
const SHOWN_COUNT_KEY: &str = "MULTIBUFFER_HINT_SHOWN_COUNT";
+impl Default for MultibufferHint {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl MultibufferHint {
pub fn new() -> Self {
Self {
@@ -187,7 +187,7 @@ pub enum DockPosition {
}
impl DockPosition {
- fn to_label(&self) -> &'static str {
+ fn label(&self) -> &'static str {
match self {
Self::Left => "left",
Self::Bottom => "bottom",
@@ -485,7 +485,7 @@ impl Dock {
self.set_open(serialized.visible, cx);
return true;
}
- return false;
+ false
}
pub fn remove_panel<T: Panel>(&mut self, panel: &View<T>, cx: &mut ViewContext<Self>) {
@@ -494,11 +494,15 @@ impl Dock {
.iter()
.position(|entry| entry.panel.panel_id() == Entity::entity_id(panel))
{
- if panel_ix == self.active_panel_index {
- self.active_panel_index = 0;
- self.set_open(false, cx);
- } else if panel_ix < self.active_panel_index {
- self.active_panel_index -= 1;
+ match panel_ix.cmp(&self.active_panel_index) {
+ std::cmp::Ordering::Less => {
+ self.active_panel_index -= 1;
+ }
+ std::cmp::Ordering::Equal => {
+ self.active_panel_index = 0;
+ self.set_open(false, cx);
+ }
+ std::cmp::Ordering::Greater => {}
}
self.panel_entries.remove(panel_ix);
cx.notify();
@@ -726,7 +730,7 @@ impl Render for PanelButtons {
let action = dock.toggle_action();
let tooltip: SharedString =
- format!("Close {} dock", dock.position.to_label()).into();
+ format!("Close {} dock", dock.position.label()).into();
(action, tooltip)
} else {
@@ -751,7 +755,7 @@ impl Render for PanelButtons {
{
let panel = panel.clone();
menu = menu.entry(
- format!("Dock {}", position.to_label()),
+ format!("Dock {}", position.label()),
None,
move |cx| {
panel.set_position(position, cx);
@@ -685,7 +685,6 @@ impl<T: Item> ItemHandle for View<T> {
pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
})
.detach_and_log_err(cx);
- return;
}
ItemEvent::UpdateTab => {
@@ -48,6 +48,12 @@ pub struct ModalLayer {
dismiss_on_focus_lost: bool,
}
+impl Default for ModalLayer {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl ModalLayer {
pub fn new() -> Self {
Self {
@@ -657,14 +657,14 @@ where
if let Err(err) = result.as_ref() {
log::error!("{err:?}");
if let Ok(prompt) = cx.update(|cx| {
- let detail = f(&err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
+ let detail = f(err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
}) {
prompt.await.ok();
}
return None;
}
- return Some(result.unwrap());
+ Some(result.unwrap())
})
}
@@ -484,10 +484,8 @@ impl Pane {
.find_position(|item| item.item_id() == alternative.id());
if let Some((ix, _)) = existing {
self.activate_item(ix, true, true, cx);
- } else {
- if let Some(upgraded) = alternative.upgrade() {
- self.add_item(upgraded, true, true, None, cx);
- }
+ } else if let Some(upgraded) = alternative.upgrade() {
+ self.add_item(upgraded, true, true, None, cx);
}
}
}
@@ -781,9 +779,7 @@ impl Pane {
}
pub fn close_current_preview_item(&mut self, cx: &mut ViewContext<Self>) -> Option<usize> {
- let Some(item_idx) = self.preview_item_idx() else {
- return None;
- };
+ let item_idx = self.preview_item_idx()?;
let prev_active_item_index = self.active_item_index;
self.remove_item(item_idx, false, false, cx);
@@ -805,7 +801,7 @@ impl Pane {
cx: &mut ViewContext<Self>,
) {
if item.is_singleton(cx) {
- if let Some(&entry_id) = item.project_entry_ids(cx).get(0) {
+ if let Some(&entry_id) = item.project_entry_ids(cx).first() {
let project = self.project.read(cx);
if let Some(project_path) = project.path_for_entry(entry_id, cx) {
let abs_path = project.absolute_path(&project_path, cx);
@@ -831,7 +827,7 @@ impl Pane {
// Does the item already exist?
let project_entry_id = if item.is_singleton(cx) {
- item.project_entry_ids(cx).get(0).copied()
+ item.project_entry_ids(cx).first().copied()
} else {
None
};
@@ -842,7 +838,7 @@ impl Pane {
} else if existing_item.is_singleton(cx) {
existing_item
.project_entry_ids(cx)
- .get(0)
+ .first()
.map_or(false, |existing_entry_id| {
Some(existing_entry_id) == project_entry_id.as_ref()
})
@@ -1600,12 +1596,10 @@ impl Pane {
project: Model<Project>,
cx: &mut WindowContext,
) -> Task<Result<()>> {
- let format =
- if let AutosaveSetting::AfterDelay { .. } = item.workspace_settings(cx).autosave {
- false
- } else {
- true
- };
+ let format = !matches!(
+ item.workspace_settings(cx).autosave,
+ AutosaveSetting::AfterDelay { .. }
+ );
if Self::can_autosave_item(item, cx) {
item.save(format, project, cx)
} else {
@@ -1817,7 +1811,7 @@ impl Pane {
let icon_color = if ItemSettings::get_global(cx).git_status {
project_path
.as_ref()
- .and_then(|path| self.project.read(cx).entry_for_path(&path, cx))
+ .and_then(|path| self.project.read(cx).entry_for_path(path, cx))
.map(|entry| {
Self::git_aware_icon_color(entry.git_status, entry.is_ignored, is_active)
})
@@ -2458,20 +2452,17 @@ impl Pane {
split_direction = None;
}
- if let Some(open_task) = workspace
- .update(&mut cx, |workspace, cx| {
- if let Some(split_direction) = split_direction {
- to_pane = workspace.split_pane(to_pane, split_direction, cx);
- }
- workspace.open_paths(
- paths,
- OpenVisible::OnlyDirectories,
- Some(to_pane.downgrade()),
- cx,
- )
- })
- .ok()
- {
+ if let Ok(open_task) = workspace.update(&mut cx, |workspace, cx| {
+ if let Some(split_direction) = split_direction {
+ to_pane = workspace.split_pane(to_pane, split_direction, cx);
+ }
+ workspace.open_paths(
+ paths,
+ OpenVisible::OnlyDirectories,
+ Some(to_pane.downgrade()),
+ cx,
+ )
+ }) {
let opened_items: Vec<_> = open_task.await;
_ = workspace.update(&mut cx, |workspace, cx| {
for item in opened_items.into_iter().flatten() {
@@ -2887,14 +2878,14 @@ fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
.and_then(|p| {
p.path
.to_str()
- .and_then(|s| if s == "" { None } else { Some(s) })
+ .and_then(|s| if s.is_empty() { None } else { Some(s) })
})
.unwrap_or("This buffer");
let path = truncate_and_remove_front(path, 80);
format!("{path} contains unsaved edits. Do you want to save it?")
}
-pub fn tab_details(items: &Vec<Box<dyn ItemHandle>>, cx: &AppContext) -> Vec<usize> {
+pub fn tab_details(items: &[Box<dyn ItemHandle>], cx: &AppContext) -> Vec<usize> {
let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
let mut tab_descriptions = HashMap::default();
let mut done = false;
@@ -2942,6 +2933,25 @@ pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &WindowContext) -> O
})
}
+impl Render for DraggedTab {
+ fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
+ let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
+ let label = self.item.tab_content(
+ TabContentParams {
+ detail: Some(self.detail),
+ selected: false,
+ preview: false,
+ },
+ cx,
+ );
+ Tab::new("")
+ .selected(self.is_active)
+ .child(label)
+ .render(cx)
+ .font(ui_font)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -3484,22 +3494,3 @@ mod tests {
})
}
}
-
-impl Render for DraggedTab {
- fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
- let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
- let label = self.item.tab_content(
- TabContentParams {
- detail: Some(self.detail),
- selected: false,
- preview: false,
- },
- cx,
- );
- Tab::new("")
- .selected(self.is_active)
- .child(label)
- .render(cx)
- .font(ui_font)
- }
-}
@@ -631,7 +631,7 @@ mod element {
use std::{cell::RefCell, iter, rc::Rc, sync::Arc};
use gpui::{
- px, relative, Along, AnyElement, Axis, Bounds, Element, GlobalElementId, IntoElement,
+ px, relative, size, Along, AnyElement, Axis, Bounds, Element, GlobalElementId, IntoElement,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, Size, Style,
WeakView, WindowContext,
};
@@ -838,12 +838,13 @@ mod element {
_global_id: Option<&GlobalElementId>,
cx: &mut ui::prelude::WindowContext,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
- let mut style = Style::default();
- style.flex_grow = 1.;
- style.flex_shrink = 1.;
- style.flex_basis = relative(0.).into();
- style.size.width = relative(1.).into();
- style.size.height = relative(1.).into();
+ let style = Style {
+ flex_grow: 1.,
+ flex_shrink: 1.,
+ flex_basis: relative(0.).into(),
+ size: size(relative(1.).into(), relative(1.).into()),
+ ..Style::default()
+ };
(cx.request_layout(style, None), ())
}
@@ -922,11 +923,9 @@ mod element {
}
for (ix, child_layout) in layout.children.iter_mut().enumerate() {
- if active_pane_magnification.is_none() {
- if ix < len - 1 {
- child_layout.handle =
- Some(Self::layout_handle(self.axis, child_layout.bounds, cx));
- }
+ if active_pane_magnification.is_none() && ix < len - 1 {
+ child_layout.handle =
+ Some(Self::layout_handle(self.axis, child_layout.bounds, cx));
}
}
@@ -986,19 +985,17 @@ mod element {
let axis = self.axis;
move |e: &MouseMoveEvent, phase, cx| {
let dragged_handle = dragged_handle.borrow();
- if phase.bubble() {
- if *dragged_handle == Some(ix) {
- Self::compute_resize(
- &flexes,
- e,
- ix,
- axis,
- child_bounds.origin,
- bounds.size,
- workspace.clone(),
- cx,
- )
- }
+ if phase.bubble() && *dragged_handle == Some(ix) {
+ Self::compute_resize(
+ &flexes,
+ e,
+ ix,
+ axis,
+ child_bounds.origin,
+ bounds.size,
+ workspace.clone(),
+ cx,
+ )
}
}
});
@@ -731,7 +731,7 @@ impl WorkspaceDb {
LIMIT 1
))?;
let result = prepared_query()?;
- Ok(result.into_iter().next().unwrap_or_else(|| (None, None)))
+ Ok(result.into_iter().next().unwrap_or((None, None)))
}
query! {
@@ -819,7 +819,7 @@ impl WorkspaceDb {
if location.paths().iter().all(|path| path.exists())
&& location.paths().iter().any(|path| path.is_dir())
{
- workspaces.push((location, window_id.map(|id| WindowId::from(id))));
+ workspaces.push((location, window_id.map(WindowId::from)));
}
}
@@ -1330,7 +1330,7 @@ mod tests {
let mut workspace_3 = SerializedWorkspace {
id: WorkspaceId(3),
location: SerializedWorkspaceLocation::Local(
- LocalPaths::new(&["/tmp", "/tmp2"]),
+ LocalPaths::new(["/tmp", "/tmp2"]),
LocalPathsOrder::new([1, 0]),
),
center_group: Default::default(),
@@ -356,7 +356,11 @@ impl SerializedPaneGroup {
if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
let pane = pane.upgrade()?;
- Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
+ Some((
+ Member::Pane(pane.clone()),
+ active.then_some(pane),
+ new_items,
+ ))
} else {
let pane = pane.upgrade()?;
workspace
@@ -121,7 +121,7 @@ impl StatusBar {
return Some(index + self.left_items.len());
}
}
- return None;
+ None
}
pub fn insert_item_after<T>(
@@ -139,6 +139,12 @@ impl Render for Toolbar {
}
}
+impl Default for Toolbar {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Toolbar {
pub fn new() -> Self {
Self {
@@ -300,9 +300,9 @@ impl Column for WorkspaceId {
.with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
}
}
-impl Into<i64> for WorkspaceId {
- fn into(self) -> i64 {
- self.0
+impl From<WorkspaceId> for i64 {
+ fn from(val: WorkspaceId) -> Self {
+ val.0
}
}
@@ -383,12 +383,12 @@ impl Global for ProjectItemOpeners {}
pub fn register_project_item<I: ProjectItem>(cx: &mut AppContext) {
let builders = cx.default_global::<ProjectItemOpeners>();
builders.push(|project, project_path, cx| {
- let project_item = <I::Item as project::Item>::try_open(&project, project_path, cx)?;
+ let project_item = <I::Item as project::Item>::try_open(project, project_path, cx)?;
let project = project.clone();
Some(cx.spawn(|cx| async move {
let project_item = project_item.await?;
let project_entry_id: Option<ProjectEntryId> =
- project_item.read_with(&cx, |item, cx| project::Item::entry_id(item, cx))?;
+ project_item.read_with(&cx, project::Item::entry_id)?;
let build_workspace_item = Box::new(|cx: &mut ViewContext<Pane>| {
Box::new(cx.new_view(|cx| I::for_project_item(project, project_item, cx)))
as Box<dyn ItemHandle>
@@ -963,7 +963,7 @@ impl Workspace {
.await;
this.update(&mut cx, |this, cx| {
if let Some(display) = cx.display() {
- if let Some(display_uuid) = display.uuid().ok() {
+ if let Ok(display_uuid) = display.uuid() {
let window_bounds = cx.window_bounds();
if let Some(database_id) = workspace_id {
cx.background_executor()
@@ -1782,7 +1782,7 @@ impl Workspace {
let project = self.project.clone();
cx.spawn(|workspace, mut cx| async move {
- let dirty_items = if save_intent == SaveIntent::Close && dirty_items.len() > 0 {
+ let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
let (serialize_tasks, remaining_dirty_items) =
workspace.update(&mut cx, |workspace, cx| {
let mut remaining_dirty_items = Vec::new();
@@ -2877,9 +2877,7 @@ impl Workspace {
direction: SplitDirection,
cx: &WindowContext,
) -> Option<View<Pane>> {
- let Some(bounding_box) = self.center.bounding_box_for_pane(&self.active_pane) else {
- return None;
- };
+ let bounding_box = self.center.bounding_box_for_pane(&self.active_pane)?;
let cursor = self.active_pane.read(cx).pixel_position_of_cursor(cx);
let center = match cursor {
Some(cursor) if bounding_box.contains(&cursor) => cursor,
@@ -2910,10 +2908,7 @@ impl Workspace {
direction: SplitDirection,
cx: &mut ViewContext<Self>,
) {
- if let Some(to) = self
- .find_pane_in_direction(direction, cx)
- .map(|pane| pane.clone())
- {
+ if let Some(to) = self.find_pane_in_direction(direction, cx) {
self.center.swap(&self.active_pane.clone(), &to);
cx.notify();
}
@@ -3355,7 +3350,7 @@ impl Workspace {
// if you're already following, find the right pane and focus it.
if let Some(follower_state) = self.follower_states.get(&leader_id) {
- cx.focus_view(&follower_state.pane());
+ cx.focus_view(follower_state.pane());
return;
}
@@ -3621,7 +3616,7 @@ impl Workspace {
return Err(anyhow!("no id for view"));
};
let id = ViewId::from_proto(id)?;
- let panel_id = view.panel_id.and_then(|id| proto::PanelId::from_i32(id));
+ let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
let pane = this.update(cx, |this, _cx| {
let state = this
@@ -4143,7 +4138,7 @@ impl Workspace {
let dev_server_project = SerializedDevServerProject {
id: dev_server_project_id,
dev_server_name: dev_server.name.to_string(),
- paths: project.paths.iter().map(|path| path.clone()).collect(),
+ paths: project.paths.to_vec(),
};
Some(SerializedWorkspaceLocation::DevServer(dev_server_project))
})
@@ -4961,7 +4956,7 @@ impl ViewId {
})
}
- pub(crate) fn to_proto(&self) -> proto::ViewId {
+ pub(crate) fn to_proto(self) -> proto::ViewId {
proto::ViewId {
creator: Some(self.creator),
id: self.id,
@@ -5061,7 +5056,7 @@ async fn join_channel_internal(
let already_in_channel = room.channel_id() == Some(channel_id);
let should_prompt = room.is_sharing_project()
- && room.remote_participants().len() > 0
+ && !room.remote_participants().is_empty()
&& !already_in_channel;
let open_room = if already_in_channel {
active_call.room().cloned()
@@ -5266,7 +5261,7 @@ pub fn join_channel(
}
// return ok, we showed the error to the user.
- return anyhow::Ok(());
+ anyhow::Ok(())
})
}
@@ -5468,7 +5463,7 @@ pub fn join_hosted_project(
.is_ok_and(|workspace| {
workspace.project().read(cx).hosted_project_id() == Some(hosted_project_id)
})
- .then(|| workspace)
+ .then_some(workspace)
})
})?;
@@ -5488,8 +5483,7 @@ pub fn join_hosted_project(
let window_bounds_override = window_bounds_env_override();
cx.update(|cx| {
let mut options = (app_state.build_window_options)(None, cx);
- options.window_bounds =
- window_bounds_override.map(|bounds| WindowBounds::Windowed(bounds));
+ options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
cx.open_window(options, |cx| {
cx.new_view(|cx| {
Workspace::new(Default::default(), project, app_state.clone(), cx)
@@ -5563,8 +5557,7 @@ pub fn join_dev_server_project(
let window_bounds_override = window_bounds_env_override();
cx.update(|cx| {
let mut options = (app_state.build_window_options)(None, cx);
- options.window_bounds =
- window_bounds_override.map(|bounds| WindowBounds::Windowed(bounds));
+ options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
cx.open_window(options, |cx| {
cx.new_view(|cx| {
Workspace::new(Some(workspace_id), project, app_state.clone(), cx)
@@ -5626,8 +5619,7 @@ pub fn join_in_room_project(
let window_bounds_override = window_bounds_env_override();
cx.update(|cx| {
let mut options = (app_state.build_window_options)(None, cx);
- options.window_bounds =
- window_bounds_override.map(|bounds| WindowBounds::Windowed(bounds));
+ options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
cx.open_window(options, |cx| {
cx.new_view(|cx| {
Workspace::new(Default::default(), project, app_state.clone(), cx)
@@ -5733,6 +5725,224 @@ fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
Some(size(px(width as f32), px(height as f32)))
}
+pub fn client_side_decorations(element: impl IntoElement, cx: &mut WindowContext) -> Stateful<Div> {
+ const BORDER_SIZE: Pixels = px(1.0);
+ let decorations = cx.window_decorations();
+
+ if matches!(decorations, Decorations::Client { .. }) {
+ cx.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW);
+ }
+
+ struct GlobalResizeEdge(ResizeEdge);
+ impl Global for GlobalResizeEdge {}
+
+ div()
+ .id("window-backdrop")
+ .bg(transparent_black())
+ .map(|div| match decorations {
+ Decorations::Server => div,
+ Decorations::Client { tiling, .. } => div
+ .when(!(tiling.top || tiling.right), |div| {
+ div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.top || tiling.left), |div| {
+ div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.bottom || tiling.right), |div| {
+ div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.bottom || tiling.left), |div| {
+ div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!tiling.top, |div| {
+ div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
+ })
+ .when(!tiling.bottom, |div| {
+ div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
+ })
+ .when(!tiling.left, |div| {
+ div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
+ })
+ .when(!tiling.right, |div| {
+ div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
+ })
+ .on_mouse_move(move |e, cx| {
+ let size = cx.window_bounds().get_bounds().size;
+ let pos = e.position;
+
+ let new_edge =
+ resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
+
+ let edge = cx.try_global::<GlobalResizeEdge>();
+ if new_edge != edge.map(|edge| edge.0) {
+ cx.window_handle()
+ .update(cx, |workspace, cx| cx.notify(workspace.entity_id()))
+ .ok();
+ }
+ })
+ .on_mouse_down(MouseButton::Left, move |e, cx| {
+ let size = cx.window_bounds().get_bounds().size;
+ let pos = e.position;
+
+ let edge = match resize_edge(
+ pos,
+ theme::CLIENT_SIDE_DECORATION_SHADOW,
+ size,
+ tiling,
+ ) {
+ Some(value) => value,
+ None => return,
+ };
+
+ cx.start_window_resize(edge);
+ }),
+ })
+ .size_full()
+ .child(
+ div()
+ .cursor(CursorStyle::Arrow)
+ .map(|div| match decorations {
+ Decorations::Server => div,
+ Decorations::Client { tiling } => div
+ .border_color(cx.theme().colors().border)
+ .when(!(tiling.top || tiling.right), |div| {
+ div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.top || tiling.left), |div| {
+ div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.bottom || tiling.right), |div| {
+ div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!(tiling.bottom || tiling.left), |div| {
+ div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
+ })
+ .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
+ .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
+ .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
+ .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
+ .when(!tiling.is_tiled(), |div| {
+ div.shadow(smallvec::smallvec![gpui::BoxShadow {
+ color: Hsla {
+ h: 0.,
+ s: 0.,
+ l: 0.,
+ a: 0.4,
+ },
+ blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
+ spread_radius: px(0.),
+ offset: point(px(0.0), px(0.0)),
+ }])
+ }),
+ })
+ .on_mouse_move(|_e, cx| {
+ cx.stop_propagation();
+ })
+ .size_full()
+ .child(element),
+ )
+ .map(|div| match decorations {
+ Decorations::Server => div,
+ Decorations::Client { tiling, .. } => div.child(
+ canvas(
+ |_bounds, cx| {
+ cx.insert_hitbox(
+ Bounds::new(
+ point(px(0.0), px(0.0)),
+ cx.window_bounds().get_bounds().size,
+ ),
+ false,
+ )
+ },
+ move |_bounds, hitbox, cx| {
+ let mouse = cx.mouse_position();
+ let size = cx.window_bounds().get_bounds().size;
+ let Some(edge) =
+ resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
+ else {
+ return;
+ };
+ cx.set_global(GlobalResizeEdge(edge));
+ cx.set_cursor_style(
+ match edge {
+ ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
+ ResizeEdge::Left | ResizeEdge::Right => {
+ CursorStyle::ResizeLeftRight
+ }
+ ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
+ CursorStyle::ResizeUpLeftDownRight
+ }
+ ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
+ CursorStyle::ResizeUpRightDownLeft
+ }
+ },
+ &hitbox,
+ );
+ },
+ )
+ .size_full()
+ .absolute(),
+ ),
+ })
+}
+
+fn resize_edge(
+ pos: Point<Pixels>,
+ shadow_size: Pixels,
+ window_size: Size<Pixels>,
+ tiling: Tiling,
+) -> Option<ResizeEdge> {
+ let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
+ if bounds.contains(&pos) {
+ return None;
+ }
+
+ let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
+ let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
+ if !tiling.top && top_left_bounds.contains(&pos) {
+ return Some(ResizeEdge::TopLeft);
+ }
+
+ let top_right_bounds = Bounds::new(
+ Point::new(window_size.width - corner_size.width, px(0.)),
+ corner_size,
+ );
+ if !tiling.top && top_right_bounds.contains(&pos) {
+ return Some(ResizeEdge::TopRight);
+ }
+
+ let bottom_left_bounds = Bounds::new(
+ Point::new(px(0.), window_size.height - corner_size.height),
+ corner_size,
+ );
+ if !tiling.bottom && bottom_left_bounds.contains(&pos) {
+ return Some(ResizeEdge::BottomLeft);
+ }
+
+ let bottom_right_bounds = Bounds::new(
+ Point::new(
+ window_size.width - corner_size.width,
+ window_size.height - corner_size.height,
+ ),
+ corner_size,
+ );
+ if !tiling.bottom && bottom_right_bounds.contains(&pos) {
+ return Some(ResizeEdge::BottomRight);
+ }
+
+ if !tiling.top && pos.y < shadow_size {
+ Some(ResizeEdge::Top)
+ } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
+ Some(ResizeEdge::Bottom)
+ } else if !tiling.left && pos.x < shadow_size {
+ Some(ResizeEdge::Left)
+ } else if !tiling.right && pos.x > window_size.width - shadow_size {
+ Some(ResizeEdge::Right)
+ } else {
+ None
+ }
+}
+
#[cfg(test)]
mod tests {
use std::{cell::RefCell, rc::Rc};
@@ -5906,7 +6116,7 @@ mod tests {
let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
// When there are no dirty items, there's nothing to do.
- let item1 = cx.new_view(|cx| TestItem::new(cx));
+ let item1 = cx.new_view(TestItem::new);
workspace.update(cx, |w, cx| {
w.add_item_to_active_pane(Box::new(item1.clone()), None, true, cx)
});
@@ -6381,7 +6591,7 @@ mod tests {
let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
pane.update(cx, |pane, cx| {
- let item = cx.new_view(|cx| TestItem::new(cx));
+ let item = cx.new_view(TestItem::new);
pane.add_item(Box::new(item), true, true, None, cx);
});
@@ -7189,221 +7399,3 @@ mod tests {
});
}
}
-
-pub fn client_side_decorations(element: impl IntoElement, cx: &mut WindowContext) -> Stateful<Div> {
- const BORDER_SIZE: Pixels = px(1.0);
- let decorations = cx.window_decorations();
-
- if matches!(decorations, Decorations::Client { .. }) {
- cx.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW);
- }
-
- struct GlobalResizeEdge(ResizeEdge);
- impl Global for GlobalResizeEdge {}
-
- div()
- .id("window-backdrop")
- .bg(transparent_black())
- .map(|div| match decorations {
- Decorations::Server => div,
- Decorations::Client { tiling, .. } => div
- .when(!(tiling.top || tiling.right), |div| {
- div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.top || tiling.left), |div| {
- div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.bottom || tiling.right), |div| {
- div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.bottom || tiling.left), |div| {
- div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!tiling.top, |div| {
- div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
- })
- .when(!tiling.bottom, |div| {
- div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
- })
- .when(!tiling.left, |div| {
- div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
- })
- .when(!tiling.right, |div| {
- div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
- })
- .on_mouse_move(move |e, cx| {
- let size = cx.window_bounds().get_bounds().size;
- let pos = e.position;
-
- let new_edge =
- resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
-
- let edge = cx.try_global::<GlobalResizeEdge>();
- if new_edge != edge.map(|edge| edge.0) {
- cx.window_handle()
- .update(cx, |workspace, cx| cx.notify(workspace.entity_id()))
- .ok();
- }
- })
- .on_mouse_down(MouseButton::Left, move |e, cx| {
- let size = cx.window_bounds().get_bounds().size;
- let pos = e.position;
-
- let edge = match resize_edge(
- pos,
- theme::CLIENT_SIDE_DECORATION_SHADOW,
- size,
- tiling,
- ) {
- Some(value) => value,
- None => return,
- };
-
- cx.start_window_resize(edge);
- }),
- })
- .size_full()
- .child(
- div()
- .cursor(CursorStyle::Arrow)
- .map(|div| match decorations {
- Decorations::Server => div,
- Decorations::Client { tiling } => div
- .border_color(cx.theme().colors().border)
- .when(!(tiling.top || tiling.right), |div| {
- div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.top || tiling.left), |div| {
- div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.bottom || tiling.right), |div| {
- div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!(tiling.bottom || tiling.left), |div| {
- div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
- })
- .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
- .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
- .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
- .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
- .when(!tiling.is_tiled(), |div| {
- div.shadow(smallvec::smallvec![gpui::BoxShadow {
- color: Hsla {
- h: 0.,
- s: 0.,
- l: 0.,
- a: 0.4,
- },
- blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
- spread_radius: px(0.),
- offset: point(px(0.0), px(0.0)),
- }])
- }),
- })
- .on_mouse_move(|_e, cx| {
- cx.stop_propagation();
- })
- .size_full()
- .child(element),
- )
- .map(|div| match decorations {
- Decorations::Server => div,
- Decorations::Client { tiling, .. } => div.child(
- canvas(
- |_bounds, cx| {
- cx.insert_hitbox(
- Bounds::new(
- point(px(0.0), px(0.0)),
- cx.window_bounds().get_bounds().size,
- ),
- false,
- )
- },
- move |_bounds, hitbox, cx| {
- let mouse = cx.mouse_position();
- let size = cx.window_bounds().get_bounds().size;
- let Some(edge) =
- resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
- else {
- return;
- };
- cx.set_global(GlobalResizeEdge(edge));
- cx.set_cursor_style(
- match edge {
- ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
- ResizeEdge::Left | ResizeEdge::Right => {
- CursorStyle::ResizeLeftRight
- }
- ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
- CursorStyle::ResizeUpLeftDownRight
- }
- ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
- CursorStyle::ResizeUpRightDownLeft
- }
- },
- &hitbox,
- );
- },
- )
- .size_full()
- .absolute(),
- ),
- })
-}
-
-fn resize_edge(
- pos: Point<Pixels>,
- shadow_size: Pixels,
- window_size: Size<Pixels>,
- tiling: Tiling,
-) -> Option<ResizeEdge> {
- let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
- if bounds.contains(&pos) {
- return None;
- }
-
- let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
- let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
- if !tiling.top && top_left_bounds.contains(&pos) {
- return Some(ResizeEdge::TopLeft);
- }
-
- let top_right_bounds = Bounds::new(
- Point::new(window_size.width - corner_size.width, px(0.)),
- corner_size,
- );
- if !tiling.top && top_right_bounds.contains(&pos) {
- return Some(ResizeEdge::TopRight);
- }
-
- let bottom_left_bounds = Bounds::new(
- Point::new(px(0.), window_size.height - corner_size.height),
- corner_size,
- );
- if !tiling.bottom && bottom_left_bounds.contains(&pos) {
- return Some(ResizeEdge::BottomLeft);
- }
-
- let bottom_right_bounds = Bounds::new(
- Point::new(
- window_size.width - corner_size.width,
- window_size.height - corner_size.height,
- ),
- corner_size,
- );
- if !tiling.bottom && bottom_right_bounds.contains(&pos) {
- return Some(ResizeEdge::BottomRight);
- }
-
- if !tiling.top && pos.y < shadow_size {
- Some(ResizeEdge::Top)
- } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
- Some(ResizeEdge::Bottom)
- } else if !tiling.left && pos.x < shadow_size {
- Some(ResizeEdge::Left)
- } else if !tiling.right && pos.x > window_size.width - shadow_size {
- Some(ResizeEdge::Right)
- } else {
- None
- }
-}
@@ -797,11 +797,9 @@ impl Worktree {
}
Worktree::Remote(this) => {
let relative_worktree_source_path =
- if let Some(relative_worktree_source_path) = relative_worktree_source_path {
- Some(relative_worktree_source_path.to_string_lossy().into())
- } else {
- None
- };
+ relative_worktree_source_path.map(|relative_worktree_source_path| {
+ relative_worktree_source_path.to_string_lossy().into()
+ });
let response = this.client.request(proto::CopyProjectEntry {
project_id: this.project_id,
entry_id: entry_id.to_proto(),
@@ -958,13 +956,8 @@ impl Worktree {
mut cx: AsyncAppContext,
) -> Result<proto::ProjectEntryResponse> {
let (scan_id, task) = this.update(&mut cx, |this, cx| {
- let relative_worktree_source_path = if let Some(relative_worktree_source_path) =
- request.relative_worktree_source_path
- {
- Some(PathBuf::from(relative_worktree_source_path))
- } else {
- None
- };
+ let relative_worktree_source_path =
+ request.relative_worktree_source_path.map(PathBuf::from);
(
this.scan_id(),
this.copy_entry(
@@ -1454,26 +1447,24 @@ impl LocalWorktree {
} else {
fs.remove_file(&abs_path?, Default::default()).await?;
}
+ } else if trash {
+ fs.trash_dir(
+ &abs_path?,
+ RemoveOptions {
+ recursive: true,
+ ignore_if_not_exists: false,
+ },
+ )
+ .await?;
} else {
- if trash {
- fs.trash_dir(
- &abs_path?,
- RemoveOptions {
- recursive: true,
- ignore_if_not_exists: false,
- },
- )
- .await?;
- } else {
- fs.remove_dir(
- &abs_path?,
- RemoveOptions {
- recursive: true,
- ignore_if_not_exists: false,
- },
- )
- .await?;
- }
+ fs.remove_dir(
+ &abs_path?,
+ RemoveOptions {
+ recursive: true,
+ ignore_if_not_exists: false,
+ },
+ )
+ .await?;
}
anyhow::Ok(entry.path)
});
@@ -2123,14 +2114,10 @@ impl Snapshot {
update.removed_repositories.sort_unstable();
self.repository_entries.retain(|_, entry| {
- if let Ok(_) = update
+ update
.removed_repositories
.binary_search(&entry.work_directory.to_proto())
- {
- false
- } else {
- true
- }
+ .is_err()
});
for repository in update.updated_repositories {
@@ -2566,7 +2553,7 @@ impl LocalSnapshot {
new_ignores.push((ancestor, None));
}
}
- if ancestor.join(&*DOT_GIT).is_dir() {
+ if ancestor.join(*DOT_GIT).is_dir() {
break;
}
}
@@ -2658,9 +2645,9 @@ impl LocalSnapshot {
for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
let ignore_parent_path =
ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
- assert!(self.entry_for_path(&ignore_parent_path).is_some());
+ assert!(self.entry_for_path(ignore_parent_path).is_some());
assert!(self
- .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
+ .entry_for_path(ignore_parent_path.join(*GITIGNORE))
.is_some());
}
}
@@ -2811,7 +2798,7 @@ impl BackgroundScannerState {
}
if let Some(ignore) = ignore {
- let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
+ let abs_parent_path = self.snapshot.abs_path.join(parent_path).into();
self.snapshot
.ignores_by_parent_abs_path
.insert(abs_parent_path, (ignore, false));
@@ -2892,7 +2879,7 @@ impl BackgroundScannerState {
);
self.snapshot
.git_repositories
- .retain(|id, _| removed_ids.binary_search(&id).is_err());
+ .retain(|id, _| removed_ids.binary_search(id).is_err());
self.snapshot
.repository_entries
.retain(|repo_path, _| !repo_path.0.starts_with(path));
@@ -3381,13 +3368,12 @@ impl sum_tree::Item for Entry {
}
let mut statuses = GitStatuses::default();
- match self.git_status {
- Some(status) => match status {
+ if let Some(status) = self.git_status {
+ match status {
GitFileStatus::Added => statuses.added = 1,
GitFileStatus::Modified => statuses.modified = 1,
GitFileStatus::Conflict => statuses.conflict = 1,
- },
- None => {}
+ }
}
EntrySummary {
@@ -3536,7 +3522,7 @@ impl BackgroundScanner {
for (index, ancestor) in root_abs_path.ancestors().enumerate() {
if index != 0 {
if let Ok(ignore) =
- build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
+ build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
{
self.state
.lock()
@@ -3546,7 +3532,7 @@ impl BackgroundScanner {
}
}
- let ancestor_dot_git = ancestor.join(&*DOT_GIT);
+ let ancestor_dot_git = ancestor.join(*DOT_GIT);
if ancestor_dot_git.is_dir() {
if index != 0 {
// We canonicalize, since the FS events use the canonicalized path.
@@ -3714,7 +3700,7 @@ impl BackgroundScanner {
let mut relative_paths = Vec::with_capacity(abs_paths.len());
let mut dot_git_paths = Vec::new();
abs_paths.sort_unstable();
- abs_paths.dedup_by(|a, b| a.starts_with(&b));
+ abs_paths.dedup_by(|a, b| a.starts_with(b));
abs_paths.retain(|abs_path| {
let snapshot = &self.state.lock().snapshot;
{
@@ -3832,7 +3818,7 @@ impl BackgroundScanner {
self.scan_dir(&job).await.log_err();
}
- mem::take(&mut self.state.lock().paths_to_scan).len() > 0
+ !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
}
async fn scan_dirs(
@@ -4208,7 +4194,7 @@ impl BackgroundScanner {
repo_paths: Vec::new(),
relative_paths: Vec::new(),
})
- .add_paths(&relative_path, repo_path);
+ .add_paths(relative_path, repo_path);
}
}
}
@@ -4223,7 +4209,7 @@ impl BackgroundScanner {
});
for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
- let abs_path: Arc<Path> = root_abs_path.join(&path).into();
+ let abs_path: Arc<Path> = root_abs_path.join(path).into();
match metadata {
Ok(Some((metadata, canonical_path))) => {
let ignore_stack = state
@@ -4320,7 +4306,7 @@ impl BackgroundScanner {
}
}
- let ignore_path = parent_path.join(&*GITIGNORE);
+ let ignore_path = parent_path.join(*GITIGNORE);
if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
return false;
}
@@ -4430,7 +4416,7 @@ impl BackgroundScanner {
path_entry.is_ignored = entry.is_ignored;
if !entry.is_dir() && !entry.is_ignored && !entry.is_external {
if let Some((ref repo_entry, local_repo)) = repo {
- if let Ok(repo_path) = repo_entry.relativize(&snapshot, &entry.path) {
+ if let Ok(repo_path) = repo_entry.relativize(snapshot, &entry.path) {
let status = local_repo
.repo_ptr
.status(&[repo_path.0.clone()])
@@ -4612,7 +4598,7 @@ impl BackgroundScanner {
let git_status = if let Some(location) = &job.location_in_repo {
statuses.get(&location.join(repo_path))
} else {
- statuses.get(&repo_path)
+ statuses.get(repo_path)
};
if file.git_status != git_status {
let mut entry = file.clone();
@@ -4732,7 +4718,7 @@ impl BackgroundScanner {
let is_newly_loaded = self.phase == InitialScan
|| last_newly_loaded_dir_path
.as_ref()
- .map_or(false, |dir| new_entry.path.starts_with(&dir));
+ .map_or(false, |dir| new_entry.path.starts_with(dir));
changes.push((
new_entry.path.clone(),
new_entry.id,
@@ -4750,7 +4736,7 @@ impl BackgroundScanner {
let is_newly_loaded = self.phase == InitialScan
|| last_newly_loaded_dir_path
.as_ref()
- .map_or(false, |dir| new_entry.path.starts_with(&dir));
+ .map_or(false, |dir| new_entry.path.starts_with(dir));
changes.push((
new_entry.path.clone(),
new_entry.id,
@@ -5222,7 +5208,7 @@ impl<'a> Iterator for ChildEntriesIter<'a> {
fn next(&mut self) -> Option<Self::Item> {
if let Some(item) = self.traversal.entry() {
- if item.path.starts_with(&self.parent_path) {
+ if item.path.starts_with(self.parent_path) {
self.traversal.advance_to_sibling();
return Some(item);
}
@@ -16,12 +16,12 @@ pub struct WorktreeSettings {
impl WorktreeSettings {
pub fn is_path_private(&self, path: &Path) -> bool {
path.ancestors()
- .any(|ancestor| self.private_files.is_match(&ancestor))
+ .any(|ancestor| self.private_files.is_match(ancestor))
}
pub fn is_path_excluded(&self, path: &Path) -> bool {
path.ancestors()
- .any(|ancestor| self.file_scan_exclusions.is_match(&ancestor))
+ .any(|ancestor| self.file_scan_exclusions.is_match(ancestor))
}
}
@@ -725,7 +725,7 @@ async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
});
fs.set_status_for_repo_via_working_copy_change(
- &Path::new("/root/tree/.git"),
+ Path::new("/root/tree/.git"),
&[(Path::new("tracked-dir/tracked-file2"), GitFileStatus::Added)],
);
@@ -809,7 +809,7 @@ async fn test_update_gitignore(cx: &mut TestAppContext) {
.unwrap();
fs.set_status_for_repo_via_working_copy_change(
- &Path::new("/root/.git"),
+ Path::new("/root/.git"),
&[(Path::new("b.txt"), GitFileStatus::Added)],
);
@@ -1266,7 +1266,7 @@ async fn test_bump_mtime_of_git_repo_workdir(cx: &mut TestAppContext) {
// Regression test: changes to the git repository should still be
// detected.
fs.set_status_for_repo_via_git_operation(
- &Path::new("/root/.git"),
+ Path::new("/root/.git"),
&[(Path::new("b/c.txt"), GitFileStatus::Modified)],
);
cx.executor().run_until_parked();
@@ -1646,7 +1646,7 @@ fn check_worktree_change_events(tree: &mut Worktree, cx: &mut ModelContext<Workt
cx.subscribe(&cx.handle(), move |tree, _, event, _| {
if let Event::UpdatedEntries(changes) = event {
for (path, _, change_type) in changes.iter() {
- let entry = tree.entry_for_path(&path).cloned();
+ let entry = tree.entry_for_path(path).cloned();
let ix = match entries.binary_search_by_key(&path, |e| &e.path) {
Ok(ix) | Err(ix) => ix,
};
@@ -1781,16 +1781,16 @@ async fn randomly_mutate_fs(
}
} else if rng.gen_bool(0.05) {
let ignore_dir_path = dirs.choose(rng).unwrap();
- let ignore_path = ignore_dir_path.join(&*GITIGNORE);
+ let ignore_path = ignore_dir_path.join(*GITIGNORE);
let subdirs = dirs
.iter()
- .filter(|d| d.starts_with(&ignore_dir_path))
+ .filter(|d| d.starts_with(ignore_dir_path))
.cloned()
.collect::<Vec<_>>();
let subfiles = files
.iter()
- .filter(|d| d.starts_with(&ignore_dir_path))
+ .filter(|d| d.starts_with(ignore_dir_path))
.cloned()
.collect::<Vec<_>>();
let files_to_ignore = {
@@ -1808,7 +1808,7 @@ async fn randomly_mutate_fs(
ignore_contents,
"{}",
path_to_ignore
- .strip_prefix(&ignore_dir_path)
+ .strip_prefix(ignore_dir_path)
.unwrap()
.to_str()
.unwrap()
@@ -1817,7 +1817,7 @@ async fn randomly_mutate_fs(
}
log::info!(
"creating gitignore {:?} with contents:\n{}",
- ignore_path.strip_prefix(&root_path).unwrap(),
+ ignore_path.strip_prefix(root_path).unwrap(),
ignore_contents
);
fs.save(
@@ -1843,10 +1843,10 @@ async fn randomly_mutate_fs(
.unwrap();
let overwrite_existing_dir =
- !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
+ !old_path.starts_with(new_path_parent) && rng.gen_bool(0.3);
let new_path = if overwrite_existing_dir {
fs.remove_dir(
- &new_path_parent,
+ new_path_parent,
RemoveOptions {
recursive: true,
ignore_if_not_exists: true,
@@ -1861,16 +1861,16 @@ async fn randomly_mutate_fs(
log::info!(
"renaming {:?} to {}{:?}",
- old_path.strip_prefix(&root_path).unwrap(),
+ old_path.strip_prefix(root_path).unwrap(),
if overwrite_existing_dir {
"overwrite "
} else {
""
},
- new_path.strip_prefix(&root_path).unwrap()
+ new_path.strip_prefix(root_path).unwrap()
);
fs.rename(
- &old_path,
+ old_path,
&new_path,
fs::RenameOptions {
overwrite: true,
@@ -1879,19 +1879,19 @@ async fn randomly_mutate_fs(
)
.await
.unwrap();
- } else if fs.is_file(&old_path).await {
+ } else if fs.is_file(old_path).await {
log::info!(
"deleting file {:?}",
- old_path.strip_prefix(&root_path).unwrap()
+ old_path.strip_prefix(root_path).unwrap()
);
fs.remove_file(old_path, Default::default()).await.unwrap();
} else {
log::info!(
"deleting dir {:?}",
- old_path.strip_prefix(&root_path).unwrap()
+ old_path.strip_prefix(root_path).unwrap()
);
fs.remove_dir(
- &old_path,
+ old_path,
RemoveOptions {
recursive: true,
ignore_if_not_exists: true,
@@ -2048,7 +2048,7 @@ async fn test_git_repository_for_path(cx: &mut TestAppContext) {
(
entry.path.as_ref(),
repo.and_then(|repo| {
- repo.work_directory(&tree)
+ repo.work_directory(tree)
.map(|work_directory| work_directory.0.to_path_buf())
}),
)
@@ -2262,7 +2262,7 @@ async fn test_git_status(cx: &mut TestAppContext) {
tree.read_with(cx, |tree, _cx| {
let snapshot = tree.snapshot();
assert_eq!(
- snapshot.status_for_file(&project_path.join(renamed_dir_name).join(RENAMED_FILE)),
+ snapshot.status_for_file(project_path.join(renamed_dir_name).join(RENAMED_FILE)),
Some(GitFileStatus::Added)
);
});
@@ -2413,7 +2413,7 @@ async fn test_propagate_git_statuses(cx: &mut TestAppContext) {
.await;
fs.set_status_for_repo_via_git_operation(
- &Path::new("/root/.git"),
+ Path::new("/root/.git"),
&[
(Path::new("a/b/c1.txt"), GitFileStatus::Added),
(Path::new("a/d/e2.txt"), GitFileStatus::Modified),
@@ -2527,7 +2527,7 @@ fn git_commit(msg: &'static str, repo: &git2::Repository) {
let signature = Signature::now("test", "test@zed.dev").unwrap();
let oid = repo.index().unwrap().write_tree().unwrap();
let tree = repo.find_tree(oid).unwrap();
- if let Some(head) = repo.head().ok() {
+ if let Ok(head) = repo.head() {
let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
let parent_commit = parent_obj.as_commit().unwrap();
@@ -2566,10 +2566,9 @@ fn git_reset(offset: usize, repo: &git2::Repository) {
.inspect(|parnet| {
parnet.message();
})
- .skip(offset)
- .next()
+ .nth(offset)
.expect("Not enough history");
- repo.reset(&new_head.as_object(), git2::ResetType::Soft, None)
+ repo.reset(new_head.as_object(), git2::ResetType::Soft, None)
.expect("Could not reset");
}
@@ -23,7 +23,6 @@ use gpui::{
Action, App, AppContext, AsyncAppContext, Context, DismissEvent, Global, Task,
UpdateGlobal as _, VisualContext,
};
-use image_viewer;
use language::LanguageRegistry;
use log::LevelFilter;
@@ -728,12 +727,12 @@ fn handle_open_request(
async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
if stdout_is_a_pty() {
if *client::ZED_DEVELOPMENT_AUTH {
- client.authenticate_and_connect(true, &cx).await?;
+ client.authenticate_and_connect(true, cx).await?;
} else if client::IMPERSONATE_LOGIN.is_some() {
- client.authenticate_and_connect(false, &cx).await?;
+ client.authenticate_and_connect(false, cx).await?;
}
- } else if client.has_credentials(&cx).await {
- client.authenticate_and_connect(true, &cx).await?;
+ } else if client.has_credentials(cx).await {
+ client.authenticate_and_connect(true, cx).await?;
}
Ok::<_, anyhow::Error>(())
}
@@ -1082,7 +1081,7 @@ fn parse_url_arg(arg: &str, cx: &AppContext) -> Result<String> {
|| arg.starts_with("ssh://")
{
Ok(arg.into())
- } else if let Some(_) = parse_zed_link(&arg, cx) {
+ } else if parse_zed_link(arg, cx).is_some() {
Ok(arg.into())
} else {
Err(anyhow!("error parsing path argument: {}", error))
@@ -1141,7 +1140,7 @@ fn load_user_themes_in_background(fs: Arc<dyn fs::Fs>, cx: &mut AppContext) {
}
}
theme_registry.load_user_themes(themes_dir, fs).await?;
- cx.update(|cx| ThemeSettings::reload_current_theme(cx))?;
+ cx.update(ThemeSettings::reload_current_theme)?;
}
anyhow::Ok(())
}
@@ -1168,8 +1167,7 @@ fn watch_themes(fs: Arc<dyn fs::Fs>, cx: &mut AppContext) {
.await
.log_err()
{
- cx.update(|cx| ThemeSettings::reload_current_theme(cx))
- .log_err();
+ cx.update(ThemeSettings::reload_current_theme).log_err();
}
}
}
@@ -50,7 +50,7 @@ pub fn init_panic_hook(
.payload()
.downcast_ref::<&str>()
.map(|s| s.to_string())
- .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
+ .or_else(|| info.payload().downcast_ref::<String>().cloned())
.unwrap_or_else(|| "Box<Any>".to_string());
if *release_channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
@@ -226,7 +226,7 @@ pub fn monitor_main_thread_hangs(
let (mut tx, mut rx) = futures::channel::mpsc::channel(3);
foreground_executor
- .spawn(async move { while let Some(_) = rx.next().await {} })
+ .spawn(async move { while (rx.next().await).is_some() {} })
.detach();
background_executor
@@ -259,7 +259,7 @@ pub fn monitor_main_thread_hangs(
let os_version = client::telemetry::os_version();
loop {
- while let Some(_) = backtrace_rx.recv().ok() {
+ while backtrace_rx.recv().is_ok() {
if !telemetry_settings.diagnostics {
return;
}
@@ -440,7 +440,7 @@ async fn upload_previous_panics(
Ok::<_, anyhow::Error>(most_recent_panic)
}
-static LAST_CRASH_UPLOADED: &'static str = "LAST_CRASH_UPLOADED";
+static LAST_CRASH_UPLOADED: &str = "LAST_CRASH_UPLOADED";
/// upload crashes from apple's diagnostic reports to our server.
/// (only if telemetry is enabled)
@@ -203,7 +203,7 @@ pub fn initialize_workspace(
activity_indicator::ActivityIndicator::new(workspace, app_state.languages.clone(), cx);
let active_buffer_language =
cx.new_view(|_| language_selector::ActiveBufferLanguage::new(workspace));
- let vim_mode_indicator = cx.new_view(|cx| vim::ModeIndicator::new(cx));
+ let vim_mode_indicator = cx.new_view(vim::ModeIndicator::new);
let cursor_position =
cx.new_view(|_| go_to_line::cursor_position::CursorPosition::new(workspace));
workspace.status_bar().update(cx, |status_bar, cx| {
@@ -236,7 +236,7 @@ pub fn initialize_workspace(
let fs = app_state.fs.clone();
project.task_inventory().update(cx, |inventory, cx| {
let tasks_file_rx =
- watch_config_file(&cx.background_executor(), fs, paths::tasks_file().clone());
+ watch_config_file(cx.background_executor(), fs, paths::tasks_file().clone());
inventory.add_source(
TaskSourceKind::AbsPath {
id_base: "global_tasks".into(),
@@ -423,7 +423,7 @@ pub fn initialize_workspace(
move |_: &mut Workspace,
_: &zed_actions::OpenKeymap,
cx: &mut ViewContext<Workspace>| {
- open_settings_file(&paths::keymap_file(), || settings::initial_keymap_content().as_ref().into(), cx);
+ open_settings_file(paths::keymap_file(), || settings::initial_keymap_content().as_ref().into(), cx);
},
)
.register_action(
@@ -628,8 +628,8 @@ fn quit(_: &Quit, cx: &mut AppContext) {
// If multiple windows have unsaved changes, and need a save prompt,
// prompt in the active window before switching to a different window.
- cx.update(|mut cx| {
- workspace_windows.sort_by_key(|window| window.is_active(&mut cx) == Some(false));
+ cx.update(|cx| {
+ workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
})
.log_err();
@@ -1029,7 +1029,7 @@ fn open_settings_file(
// TODO: Do note that all other external files (e.g. drag and drop from OS) still have their worktrees released on file close, causing LSP servers' restarts.
project.find_or_create_worktree(paths::config_dir().as_path(), false, cx)
});
- let settings_open_task = create_and_open_local_file(&abs_path, cx, default_content);
+ let settings_open_task = create_and_open_local_file(abs_path, cx, default_content);
(worktree_creation_task, settings_open_task)
})?;
@@ -1040,6 +1040,11 @@ fn open_settings_file(
.detach_and_log_err(cx);
}
+async fn register_zed_scheme(cx: &AsyncAppContext) -> anyhow::Result<()> {
+ cx.update(|cx| cx.register_url_scheme(ZED_URL_SCHEME))?
+ .await
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -3368,7 +3373,7 @@ mod tests {
#[gpui::test]
async fn test_bundled_languages(cx: &mut TestAppContext) {
env_logger::builder().is_test(true).try_init().ok();
- let settings = cx.update(|cx| SettingsStore::test(cx));
+ let settings = cx.update(SettingsStore::test);
cx.set_global(settings);
let languages = LanguageRegistry::test(cx.executor());
let languages = Arc::new(languages);
@@ -3387,7 +3392,7 @@ mod tests {
}
pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
- init_test_with_state(cx, cx.update(|cx| AppState::test(cx)))
+ init_test_with_state(cx, cx.update(AppState::test))
}
fn init_test_with_state(
@@ -3506,8 +3511,3 @@ mod tests {
}
}
}
-
-async fn register_zed_scheme(cx: &AsyncAppContext) -> anyhow::Result<()> {
- cx.update(|cx| cx.register_url_scheme(ZED_URL_SCHEME))?
- .await
-}
@@ -352,14 +352,14 @@ async fn open_workspaces(
wait: bool,
app_state: Arc<AppState>,
env: Option<collections::HashMap<String, String>>,
- mut cx: &mut AsyncAppContext,
+ cx: &mut AsyncAppContext,
) -> Result<()> {
let grouped_paths = if paths.is_empty() {
// If no paths are provided, restore from previous workspaces unless a new workspace is requested with -n
if open_new_workspace == Some(true) {
Vec::new()
} else {
- let locations = restorable_workspace_locations(&mut cx, &app_state).await;
+ let locations = restorable_workspace_locations(cx, &app_state).await;
locations
.into_iter()
.flat_map(|locations| {
@@ -423,7 +423,7 @@ async fn open_workspaces(
responses,
env.as_ref(),
&app_state,
- &mut cx,
+ cx,
)
.await;
@@ -22,7 +22,7 @@ impl ClojureExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -60,7 +60,7 @@ impl ClojureExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -76,7 +76,7 @@ impl ClojureExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -38,7 +38,7 @@ impl CsharpExtension {
}
if let Some(path) = &self.cached_binary_path {
- if fs::metadata(&path).map_or(false, |stat| stat.is_file()) {
+ if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
return Ok(OmnisharpBinary {
path: path.clone(),
args: binary_args,
@@ -107,7 +107,7 @@ impl CsharpExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -25,7 +25,7 @@ impl DenoExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -63,7 +63,7 @@ impl DenoExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -79,7 +79,7 @@ impl DenoExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -28,7 +28,7 @@ impl zed::Extension for ElixirExtension {
) -> Result<zed::Command> {
match language_server_id.as_ref() {
ElixirLs::LANGUAGE_SERVER_ID => {
- let elixir_ls = self.elixir_ls.get_or_insert_with(|| ElixirLs::new());
+ let elixir_ls = self.elixir_ls.get_or_insert_with(ElixirLs::new);
Ok(zed::Command {
command: elixir_ls.language_server_binary_path(language_server_id, worktree)?,
@@ -37,7 +37,7 @@ impl zed::Extension for ElixirExtension {
})
}
NextLs::LANGUAGE_SERVER_ID => {
- let next_ls = self.next_ls.get_or_insert_with(|| NextLs::new());
+ let next_ls = self.next_ls.get_or_insert_with(NextLs::new);
Ok(zed::Command {
command: next_ls.language_server_binary_path(language_server_id, worktree)?,
@@ -46,7 +46,7 @@ impl zed::Extension for ElixirExtension {
})
}
Lexical::LANGUAGE_SERVER_ID => {
- let lexical = self.lexical.get_or_insert_with(|| Lexical::new());
+ let lexical = self.lexical.get_or_insert_with(Lexical::new);
let lexical_binary =
lexical.language_server_binary(language_server_id, worktree)?;
@@ -110,13 +110,10 @@ impl zed::Extension for ElixirExtension {
language_server_id: &LanguageServerId,
worktree: &zed::Worktree,
) -> Result<Option<serde_json::Value>> {
- match language_server_id.as_ref() {
- ElixirLs::LANGUAGE_SERVER_ID => {
- if let Some(elixir_ls) = self.elixir_ls.as_mut() {
- return elixir_ls.language_server_workspace_configuration(worktree);
- }
+ if language_server_id.as_ref() == ElixirLs::LANGUAGE_SERVER_ID {
+ if let Some(elixir_ls) = self.elixir_ls.as_mut() {
+ return elixir_ls.language_server_workspace_configuration(worktree);
}
- _ => (),
}
Ok(None)
@@ -34,7 +34,7 @@ impl ElixirLs {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -63,7 +63,7 @@ impl ElixirLs {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -83,7 +83,7 @@ impl ElixirLs {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -59,7 +59,7 @@ impl Lexical {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -83,7 +83,7 @@ impl Lexical {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -103,7 +103,7 @@ impl Lexical {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -33,7 +33,7 @@ impl NextLs {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -77,7 +77,7 @@ impl NextLs {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -95,7 +95,7 @@ impl NextLs {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -24,7 +24,7 @@ impl ElmExtension {
}
zed::set_language_server_installation_status(
- &server_id,
+ server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let version = zed::npm_package_latest_version(PACKAGE_NAME)?;
@@ -33,7 +33,7 @@ impl ElmExtension {
|| zed::npm_package_installed_version(PACKAGE_NAME)?.as_ref() != Some(&version)
{
zed::set_language_server_installation_status(
- &server_id,
+ server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
let result = zed::npm_install_package(PACKAGE_NAME, &version);
@@ -24,7 +24,7 @@ impl zed::Extension for ErlangExtension {
) -> Result<zed::Command> {
match language_server_id.as_ref() {
ErlangLs::LANGUAGE_SERVER_ID => {
- let erlang_ls = self.erlang_ls.get_or_insert_with(|| ErlangLs::new());
+ let erlang_ls = self.erlang_ls.get_or_insert_with(ErlangLs::new);
Ok(zed::Command {
command: erlang_ls.language_server_binary_path(language_server_id, worktree)?,
@@ -35,7 +35,7 @@ impl zed::Extension for ErlangExtension {
ErlangLanguagePlatform::LANGUAGE_SERVER_ID => {
let erlang_language_platform = self
.erlang_language_platform
- .get_or_insert_with(|| ErlangLanguagePlatform::new());
+ .get_or_insert_with(ErlangLanguagePlatform::new);
erlang_language_platform.language_server_command(language_server_id, worktree)
}
language_server_id => Err(format!("unknown language server: {language_server_id}")),
@@ -43,7 +43,7 @@ impl ErlangLanguagePlatform {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -85,7 +85,7 @@ impl ErlangLanguagePlatform {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -101,7 +101,7 @@ impl ErlangLanguagePlatform {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -30,7 +30,7 @@ impl GleamExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -68,7 +68,7 @@ impl GleamExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -84,7 +84,7 @@ impl GleamExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -157,12 +157,12 @@ impl zed::Extension for GleamExtension {
) -> Result<SlashCommandOutput, String> {
match command.name.as_str() {
"gleam-project" => {
- let worktree = worktree.ok_or_else(|| "no worktree")?;
+ let worktree = worktree.ok_or("no worktree")?;
let mut text = String::new();
text.push_str("You are in a Gleam project.\n");
- if let Some(gleam_toml) = worktree.read_text_file("gleam.toml").ok() {
+ if let Ok(gleam_toml) = worktree.read_text_file("gleam.toml") {
text.push_str("The `gleam.toml` is as follows:\n");
text.push_str(&gleam_toml);
}
@@ -244,6 +244,6 @@ mod tests {
let detail = "fn(\n Method,\n List(#(String, String)),\n a,\n Scheme,\n String,\n Option(Int),\n String,\n Option(String),\n) -> Request(a)";
let expected = "fn(Method, List(#(String, String)), a, Scheme, String, Option(Int), String, Option(String)) -> Request(a)";
- assert_eq!(strip_newlines_from_detail(&detail), expected);
+ assert_eq!(strip_newlines_from_detail(detail), expected);
}
}
@@ -130,10 +130,10 @@ pub struct GleamChromeRemover;
impl HandleTag for GleamChromeRemover {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "head" | "script" | "style" | "svg" | "header" | "footer" | "a" => true,
- _ => false,
- }
+ matches!(
+ tag,
+ "head" | "script" | "style" | "svg" | "header" | "footer" | "a"
+ )
}
fn handle_tag_start(
@@ -188,10 +188,7 @@ impl GleamModuleCollector {
impl HandleTag for GleamModuleCollector {
fn should_handle(&self, tag: &str) -> bool {
- match tag {
- "h2" | "a" => true,
- _ => false,
- }
+ matches!(tag, "h2" | "a")
}
fn handle_tag_start(
@@ -199,15 +196,10 @@ impl HandleTag for GleamModuleCollector {
tag: &HtmlElement,
writer: &mut MarkdownWriter,
) -> StartTagOutcome {
- match tag.tag() {
- "a" => {
- if self.has_seen_modules_header && writer.is_inside("li") {
- if let Some(module_name) = Self::parse_module(tag) {
- self.modules.insert(module_name);
- }
- }
+ if tag.tag() == "a" && self.has_seen_modules_header && writer.is_inside("li") {
+ if let Some(module_name) = Self::parse_module(tag) {
+ self.modules.insert(module_name);
}
- _ => {}
}
StartTagOutcome::Continue
@@ -23,7 +23,7 @@ impl GlslExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -62,7 +62,7 @@ impl GlslExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -83,7 +83,7 @@ impl GlslExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -31,7 +31,7 @@ impl HtmlExtension {
|| zed::npm_package_installed_version(PACKAGE_NAME)?.as_ref() != Some(&version)
{
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
let result = zed::npm_install_package(PACKAGE_NAME, &version);
@@ -24,7 +24,7 @@ impl LuaExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -72,7 +72,7 @@ impl LuaExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -91,7 +91,7 @@ impl LuaExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -72,7 +72,7 @@ impl zed::Extension for OcamlExtension {
}
Some((CompletionKind::Field, detail)) => {
- let filter_range_start = if name.starts_with(&['~', '?']) { 1 } else { 0 };
+ let filter_range_start = if name.starts_with(['~', '?']) { 1 } else { 0 };
let record_prefix = "type t = { ";
let record_suffix = "; }";
@@ -58,7 +58,7 @@ impl Intelephense {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let version = zed::npm_package_latest_version(PACKAGE_NAME)?;
@@ -67,7 +67,7 @@ impl Intelephense {
|| zed::npm_package_installed_version(PACKAGE_NAME)?.as_ref() != Some(&version)
{
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
let result = zed::npm_install_package(PACKAGE_NAME, &version);
@@ -31,7 +31,7 @@ impl Phpactor {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -56,7 +56,7 @@ impl Phpactor {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -74,7 +74,7 @@ impl Phpactor {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -24,11 +24,11 @@ impl zed::Extension for PhpExtension {
) -> Result<zed::Command> {
match language_server_id.as_ref() {
Intelephense::LANGUAGE_SERVER_ID => {
- let intelephense = self.intelephense.get_or_insert_with(|| Intelephense::new());
+ let intelephense = self.intelephense.get_or_insert_with(Intelephense::new);
intelephense.language_server_command(language_server_id, worktree)
}
Phpactor::LANGUAGE_SERVER_ID => {
- let phpactor = self.phpactor.get_or_insert_with(|| Phpactor::new());
+ let phpactor = self.phpactor.get_or_insert_with(Phpactor::new);
Ok(zed::Command {
command: phpactor.language_server_binary_path(language_server_id, worktree)?,
@@ -45,13 +45,10 @@ impl zed::Extension for PhpExtension {
language_server_id: &LanguageServerId,
worktree: &zed::Worktree,
) -> Result<Option<serde_json::Value>> {
- match language_server_id.as_ref() {
- Intelephense::LANGUAGE_SERVER_ID => {
- if let Some(intelephense) = self.intelephense.as_mut() {
- return intelephense.language_server_workspace_configuration(worktree);
- }
+ if language_server_id.as_ref() == Intelephense::LANGUAGE_SERVER_ID {
+ if let Some(intelephense) = self.intelephense.as_mut() {
+ return intelephense.language_server_workspace_configuration(worktree);
}
- _ => (),
}
Ok(None)
@@ -88,7 +88,7 @@ impl RubyLsp {
pub fn label_for_symbol(&self, symbol: Symbol) -> Option<CodeLabel> {
let name = &symbol.name;
- return match symbol.kind {
+ match symbol.kind {
SymbolKind::Method => {
let code = format!("def {name}; end");
let filter_range = 0..name.len();
@@ -123,6 +123,6 @@ impl RubyLsp {
})
}
_ => None,
- };
+ }
}
}
@@ -29,15 +29,15 @@ impl zed::Extension for RubyExtension {
) -> Result<zed::Command> {
match language_server_id.as_ref() {
Solargraph::LANGUAGE_SERVER_ID => {
- let solargraph = self.solargraph.get_or_insert_with(|| Solargraph::new());
+ let solargraph = self.solargraph.get_or_insert_with(Solargraph::new);
solargraph.language_server_command(language_server_id, worktree)
}
RubyLsp::LANGUAGE_SERVER_ID => {
- let ruby_lsp = self.ruby_lsp.get_or_insert_with(|| RubyLsp::new());
+ let ruby_lsp = self.ruby_lsp.get_or_insert_with(RubyLsp::new);
ruby_lsp.language_server_command(language_server_id, worktree)
}
Rubocop::LANGUAGE_SERVER_ID => {
- let rubocop = self.rubocop.get_or_insert_with(|| Rubocop::new());
+ let rubocop = self.rubocop.get_or_insert_with(Rubocop::new);
rubocop.language_server_command(language_server_id, worktree)
}
language_server_id => Err(format!("unknown language server: {language_server_id}")),
@@ -39,7 +39,7 @@ impl RuffExtension {
}
if let Some(path) = &self.cached_binary_path {
- if fs::metadata(&path).map_or(false, |stat| stat.is_file()) {
+ if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
return Ok(RuffBinary {
path: path.clone(),
args: binary_args,
@@ -48,7 +48,7 @@ impl RuffExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -93,7 +93,7 @@ impl RuffExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
let file_kind = match platform {
@@ -108,7 +108,7 @@ impl RuffExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -24,7 +24,7 @@ impl SnippetExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -61,7 +61,7 @@ impl SnippetExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -77,7 +77,7 @@ impl SnippetExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -23,7 +23,7 @@ impl TerraformExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -55,7 +55,7 @@ impl TerraformExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -69,7 +69,7 @@ impl TerraformExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -20,7 +20,7 @@ impl TestExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -58,7 +58,7 @@ impl TestExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -74,7 +74,7 @@ impl TestExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -18,7 +18,7 @@ impl TomlExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
let release = zed::latest_github_release(
@@ -64,7 +64,7 @@ impl TomlExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -82,7 +82,7 @@ impl TomlExtension {
for entry in entries {
let entry = entry.map_err(|err| format!("failed to load directory entry {err}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -48,7 +48,7 @@ impl ZigExtension {
}
if let Some(path) = &self.cached_binary_path {
- if fs::metadata(&path).map_or(false, |stat| stat.is_file()) {
+ if fs::metadata(path).map_or(false, |stat| stat.is_file()) {
return Ok(ZlsBinary {
path: path.clone(),
args,
@@ -58,7 +58,7 @@ impl ZigExtension {
}
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::CheckingForUpdate,
);
@@ -100,7 +100,7 @@ impl ZigExtension {
if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {
zed::set_language_server_installation_status(
- &language_server_id,
+ language_server_id,
&zed::LanguageServerInstallationStatus::Downloading,
);
@@ -121,7 +121,7 @@ impl ZigExtension {
for entry in entries {
let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;
if entry.file_name().to_str() != Some(&version_dir) {
- fs::remove_dir_all(&entry.path()).ok();
+ fs::remove_dir_all(entry.path()).ok();
}
}
}
@@ -9,7 +9,7 @@ use crate::workspace::load_workspace;
pub struct LicensesArgs {}
pub fn run_licenses(_args: LicensesArgs) -> Result<()> {
- const LICENSE_FILES: &[&'static str] = &["LICENSE-APACHE", "LICENSE-GPL", "LICENSE-AGPL"];
+ const LICENSE_FILES: &[&str] = &["LICENSE-APACHE", "LICENSE-GPL", "LICENSE-AGPL"];
let workspace = load_workspace()?;
@@ -19,7 +19,7 @@ pub fn run_licenses(_args: LicensesArgs) -> Result<()> {
.parent()
.ok_or_else(|| anyhow!("no crate directory for {}", package.name))?;
- if let Some(license_file) = first_license_file(&crate_dir, &LICENSE_FILES) {
+ if let Some(license_file) = first_license_file(crate_dir, LICENSE_FILES) {
if !license_file.is_symlink() {
println!("{} is not a symlink", license_file.display());
}
@@ -71,7 +71,7 @@ pub fn run_package_conformity(_args: PackageConformityArgs) -> Result<()> {
/// Returns the contents of the `Cargo.toml` file at the given path.
fn read_cargo_toml(path: impl AsRef<Path>) -> Result<Manifest> {
let path = path.as_ref();
- let cargo_toml_bytes = fs::read(&path)?;
+ let cargo_toml_bytes = fs::read(path)?;
Manifest::from_slice(&cargo_toml_bytes)
.with_context(|| anyhow!("failed to read Cargo.toml at {path:?}"))
}