items.rs

   1use crate::{
   2    Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, FormatTarget,
   3    MultiBuffer, MultiBufferSnapshot, NavigationData, SearchWithinRange, ToPoint as _,
   4    editor_settings::SeedQuerySetting,
   5    persistence::{DB, SerializedEditor},
   6    scroll::ScrollAnchor,
   7};
   8use anyhow::{Context as _, Result, anyhow};
   9use collections::{HashMap, HashSet};
  10use file_icons::FileIcons;
  11use futures::future::try_join_all;
  12use git::status::GitSummary;
  13use gpui::{
  14    AnyElement, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter, IntoElement,
  15    ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window, point,
  16};
  17use language::{
  18    Bias, Buffer, BufferRow, CharKind, DiskState, LocalFile, Point, SelectionGoal,
  19    proto::serialize_anchor as serialize_text_anchor,
  20};
  21use lsp::DiagnosticSeverity;
  22use project::{
  23    Project, ProjectItem as _, ProjectPath, lsp_store::FormatTrigger,
  24    project_settings::ProjectSettings, search::SearchQuery,
  25};
  26use rpc::proto::{self, PeerId, update_view};
  27use settings::Settings;
  28use std::{
  29    any::TypeId,
  30    borrow::Cow,
  31    cmp::{self, Ordering},
  32    iter,
  33    ops::Range,
  34    path::{Path, PathBuf},
  35    sync::Arc,
  36};
  37use text::{BufferId, BufferSnapshot, Selection};
  38use theme::{Theme, ThemeSettings};
  39use ui::{IconDecorationKind, prelude::*};
  40use util::{ResultExt, TryFutureExt, paths::PathExt};
  41use workspace::{
  42    ItemId, ItemNavHistory, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  43    item::{FollowableItem, Item, ItemEvent, ProjectItem},
  44    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  45};
  46use workspace::{
  47    OpenOptions,
  48    item::{Dedup, ItemSettings, SerializableItem, TabContentParams},
  49};
  50use workspace::{
  51    OpenVisible, Pane, WorkspaceSettings,
  52    item::{BreadcrumbText, FollowEvent, ProjectItemKind},
  53    searchable::SearchOptions,
  54};
  55
  56pub const MAX_TAB_TITLE_LEN: usize = 24;
  57
  58impl FollowableItem for Editor {
  59    fn remote_id(&self) -> Option<ViewId> {
  60        self.remote_id
  61    }
  62
  63    fn from_state_proto(
  64        workspace: Entity<Workspace>,
  65        remote_id: ViewId,
  66        state: &mut Option<proto::view::Variant>,
  67        window: &mut Window,
  68        cx: &mut App,
  69    ) -> Option<Task<Result<Entity<Self>>>> {
  70        let project = workspace.read(cx).project().to_owned();
  71        let Some(proto::view::Variant::Editor(_)) = state else {
  72            return None;
  73        };
  74        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  75            unreachable!()
  76        };
  77
  78        let buffer_ids = state
  79            .excerpts
  80            .iter()
  81            .map(|excerpt| excerpt.buffer_id)
  82            .collect::<HashSet<_>>();
  83        let buffers = project.update(cx, |project, cx| {
  84            buffer_ids
  85                .iter()
  86                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  87                .collect::<Result<Vec<_>>>()
  88        });
  89
  90        Some(window.spawn(cx, async move |cx| {
  91            let mut buffers = futures::future::try_join_all(buffers?)
  92                .await
  93                .debug_assert_ok("leaders don't share views for unshared buffers")?;
  94
  95            let editor = cx.update(|window, cx| {
  96                let multibuffer = cx.new(|cx| {
  97                    let mut multibuffer;
  98                    if state.singleton && buffers.len() == 1 {
  99                        multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 100                    } else {
 101                        multibuffer = MultiBuffer::new(project.read(cx).capability());
 102                        let mut excerpts = state.excerpts.into_iter().peekable();
 103                        while let Some(excerpt) = excerpts.peek() {
 104                            let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
 105                                continue;
 106                            };
 107                            let buffer_excerpts = iter::from_fn(|| {
 108                                let excerpt = excerpts.peek()?;
 109                                (excerpt.buffer_id == u64::from(buffer_id))
 110                                    .then(|| excerpts.next().unwrap())
 111                            });
 112                            let buffer =
 113                                buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 114                            if let Some(buffer) = buffer {
 115                                multibuffer.push_excerpts(
 116                                    buffer.clone(),
 117                                    buffer_excerpts.filter_map(deserialize_excerpt_range),
 118                                    cx,
 119                                );
 120                            }
 121                        }
 122                    };
 123
 124                    if let Some(title) = &state.title {
 125                        multibuffer = multibuffer.with_title(title.clone())
 126                    }
 127
 128                    multibuffer
 129                });
 130
 131                cx.new(|cx| {
 132                    let mut editor =
 133                        Editor::for_multibuffer(multibuffer, Some(project.clone()), window, cx);
 134                    editor.remote_id = Some(remote_id);
 135                    editor
 136                })
 137            })?;
 138
 139            update_editor_from_message(
 140                editor.downgrade(),
 141                project,
 142                proto::update_view::Editor {
 143                    selections: state.selections,
 144                    pending_selection: state.pending_selection,
 145                    scroll_top_anchor: state.scroll_top_anchor,
 146                    scroll_x: state.scroll_x,
 147                    scroll_y: state.scroll_y,
 148                    ..Default::default()
 149                },
 150                cx,
 151            )
 152            .await?;
 153
 154            Ok(editor)
 155        }))
 156    }
 157
 158    fn set_leader_peer_id(
 159        &mut self,
 160        leader_peer_id: Option<PeerId>,
 161        window: &mut Window,
 162        cx: &mut Context<Self>,
 163    ) {
 164        self.leader_peer_id = leader_peer_id;
 165        if self.leader_peer_id.is_some() {
 166            self.buffer.update(cx, |buffer, cx| {
 167                buffer.remove_active_selections(cx);
 168            });
 169        } else if self.focus_handle.is_focused(window) {
 170            self.buffer.update(cx, |buffer, cx| {
 171                buffer.set_active_selections(
 172                    &self.selections.disjoint_anchors(),
 173                    self.selections.line_mode,
 174                    self.cursor_shape,
 175                    cx,
 176                );
 177            });
 178        }
 179        cx.notify();
 180    }
 181
 182    fn to_state_proto(&self, _: &Window, cx: &App) -> Option<proto::view::Variant> {
 183        let buffer = self.buffer.read(cx);
 184        if buffer
 185            .as_singleton()
 186            .and_then(|buffer| buffer.read(cx).file())
 187            .map_or(false, |file| file.is_private())
 188        {
 189            return None;
 190        }
 191
 192        let scroll_anchor = self.scroll_manager.anchor();
 193        let excerpts = buffer
 194            .read(cx)
 195            .excerpts()
 196            .map(|(id, buffer, range)| proto::Excerpt {
 197                id: id.to_proto(),
 198                buffer_id: buffer.remote_id().into(),
 199                context_start: Some(serialize_text_anchor(&range.context.start)),
 200                context_end: Some(serialize_text_anchor(&range.context.end)),
 201                primary_start: Some(serialize_text_anchor(&range.primary.start)),
 202                primary_end: Some(serialize_text_anchor(&range.primary.end)),
 203            })
 204            .collect();
 205
 206        Some(proto::view::Variant::Editor(proto::view::Editor {
 207            singleton: buffer.is_singleton(),
 208            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 209            excerpts,
 210            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 211            scroll_x: scroll_anchor.offset.x,
 212            scroll_y: scroll_anchor.offset.y,
 213            selections: self
 214                .selections
 215                .disjoint_anchors()
 216                .iter()
 217                .map(serialize_selection)
 218                .collect(),
 219            pending_selection: self
 220                .selections
 221                .pending_anchor()
 222                .as_ref()
 223                .map(serialize_selection),
 224        }))
 225    }
 226
 227    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 228        match event {
 229            EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
 230            EditorEvent::SelectionsChanged { local }
 231            | EditorEvent::ScrollPositionChanged { local, .. } => {
 232                if *local {
 233                    Some(FollowEvent::Unfollow)
 234                } else {
 235                    None
 236                }
 237            }
 238            _ => None,
 239        }
 240    }
 241
 242    fn add_event_to_update_proto(
 243        &self,
 244        event: &EditorEvent,
 245        update: &mut Option<proto::update_view::Variant>,
 246        _: &Window,
 247        cx: &App,
 248    ) -> bool {
 249        let update =
 250            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 251
 252        match update {
 253            proto::update_view::Variant::Editor(update) => match event {
 254                EditorEvent::ExcerptsAdded {
 255                    buffer,
 256                    predecessor,
 257                    excerpts,
 258                } => {
 259                    let buffer_id = buffer.read(cx).remote_id();
 260                    let mut excerpts = excerpts.iter();
 261                    if let Some((id, range)) = excerpts.next() {
 262                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 263                            previous_excerpt_id: Some(predecessor.to_proto()),
 264                            excerpt: serialize_excerpt(buffer_id, id, range),
 265                        });
 266                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 267                            proto::ExcerptInsertion {
 268                                previous_excerpt_id: None,
 269                                excerpt: serialize_excerpt(buffer_id, id, range),
 270                            }
 271                        }))
 272                    }
 273                    true
 274                }
 275                EditorEvent::ExcerptsRemoved { ids } => {
 276                    update
 277                        .deleted_excerpts
 278                        .extend(ids.iter().map(ExcerptId::to_proto));
 279                    true
 280                }
 281                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 282                    let scroll_anchor = self.scroll_manager.anchor();
 283                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 284                    update.scroll_x = scroll_anchor.offset.x;
 285                    update.scroll_y = scroll_anchor.offset.y;
 286                    true
 287                }
 288                EditorEvent::SelectionsChanged { .. } => {
 289                    update.selections = self
 290                        .selections
 291                        .disjoint_anchors()
 292                        .iter()
 293                        .map(serialize_selection)
 294                        .collect();
 295                    update.pending_selection = self
 296                        .selections
 297                        .pending_anchor()
 298                        .as_ref()
 299                        .map(serialize_selection);
 300                    true
 301                }
 302                _ => false,
 303            },
 304        }
 305    }
 306
 307    fn apply_update_proto(
 308        &mut self,
 309        project: &Entity<Project>,
 310        message: update_view::Variant,
 311        window: &mut Window,
 312        cx: &mut Context<Self>,
 313    ) -> Task<Result<()>> {
 314        let update_view::Variant::Editor(message) = message;
 315        let project = project.clone();
 316        cx.spawn_in(window, async move |this, cx| {
 317            update_editor_from_message(this, project, message, cx).await
 318        })
 319    }
 320
 321    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
 322        true
 323    }
 324
 325    fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
 326        let self_singleton = self.buffer.read(cx).as_singleton()?;
 327        let other_singleton = existing.buffer.read(cx).as_singleton()?;
 328        if self_singleton == other_singleton {
 329            Some(Dedup::KeepExisting)
 330        } else {
 331            None
 332        }
 333    }
 334}
 335
 336async fn update_editor_from_message(
 337    this: WeakEntity<Editor>,
 338    project: Entity<Project>,
 339    message: proto::update_view::Editor,
 340    cx: &mut AsyncWindowContext,
 341) -> Result<()> {
 342    // Open all of the buffers of which excerpts were added to the editor.
 343    let inserted_excerpt_buffer_ids = message
 344        .inserted_excerpts
 345        .iter()
 346        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 347        .collect::<HashSet<_>>();
 348    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 349        inserted_excerpt_buffer_ids
 350            .into_iter()
 351            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 352            .collect::<Result<Vec<_>>>()
 353    })??;
 354    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 355
 356    // Update the editor's excerpts.
 357    this.update(cx, |editor, cx| {
 358        editor.buffer.update(cx, |multibuffer, cx| {
 359            let mut removed_excerpt_ids = message
 360                .deleted_excerpts
 361                .into_iter()
 362                .map(ExcerptId::from_proto)
 363                .collect::<Vec<_>>();
 364            removed_excerpt_ids.sort_by({
 365                let multibuffer = multibuffer.read(cx);
 366                move |a, b| a.cmp(b, &multibuffer)
 367            });
 368
 369            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 370            while let Some(insertion) = insertions.next() {
 371                let Some(excerpt) = insertion.excerpt else {
 372                    continue;
 373                };
 374                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 375                    continue;
 376                };
 377                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 378                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
 379                    continue;
 380                };
 381
 382                let adjacent_excerpts = iter::from_fn(|| {
 383                    let insertion = insertions.peek()?;
 384                    if insertion.previous_excerpt_id.is_none()
 385                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 386                    {
 387                        insertions.next()?.excerpt
 388                    } else {
 389                        None
 390                    }
 391                });
 392
 393                multibuffer.insert_excerpts_with_ids_after(
 394                    ExcerptId::from_proto(previous_excerpt_id),
 395                    buffer,
 396                    [excerpt]
 397                        .into_iter()
 398                        .chain(adjacent_excerpts)
 399                        .filter_map(|excerpt| {
 400                            Some((
 401                                ExcerptId::from_proto(excerpt.id),
 402                                deserialize_excerpt_range(excerpt)?,
 403                            ))
 404                        }),
 405                    cx,
 406                );
 407            }
 408
 409            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 410            Result::<(), anyhow::Error>::Ok(())
 411        })
 412    })??;
 413
 414    // Deserialize the editor state.
 415    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 416        let buffer = editor.buffer.read(cx).read(cx);
 417        let selections = message
 418            .selections
 419            .into_iter()
 420            .filter_map(|selection| deserialize_selection(&buffer, selection))
 421            .collect::<Vec<_>>();
 422        let pending_selection = message
 423            .pending_selection
 424            .and_then(|selection| deserialize_selection(&buffer, selection));
 425        let scroll_top_anchor = message
 426            .scroll_top_anchor
 427            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 428        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 429    })??;
 430
 431    // Wait until the buffer has received all of the operations referenced by
 432    // the editor's new state.
 433    this.update(cx, |editor, cx| {
 434        editor.buffer.update(cx, |buffer, cx| {
 435            buffer.wait_for_anchors(
 436                selections
 437                    .iter()
 438                    .chain(pending_selection.as_ref())
 439                    .flat_map(|selection| [selection.start, selection.end])
 440                    .chain(scroll_top_anchor),
 441                cx,
 442            )
 443        })
 444    })?
 445    .await?;
 446
 447    // Update the editor's state.
 448    this.update_in(cx, |editor, window, cx| {
 449        if !selections.is_empty() || pending_selection.is_some() {
 450            editor.set_selections_from_remote(selections, pending_selection, window, cx);
 451            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 452        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 453            editor.set_scroll_anchor_remote(
 454                ScrollAnchor {
 455                    anchor: scroll_top_anchor,
 456                    offset: point(message.scroll_x, message.scroll_y),
 457                },
 458                window,
 459                cx,
 460            );
 461        }
 462    })?;
 463    Ok(())
 464}
 465
 466fn serialize_excerpt(
 467    buffer_id: BufferId,
 468    id: &ExcerptId,
 469    range: &ExcerptRange<language::Anchor>,
 470) -> Option<proto::Excerpt> {
 471    Some(proto::Excerpt {
 472        id: id.to_proto(),
 473        buffer_id: buffer_id.into(),
 474        context_start: Some(serialize_text_anchor(&range.context.start)),
 475        context_end: Some(serialize_text_anchor(&range.context.end)),
 476        primary_start: Some(serialize_text_anchor(&range.primary.start)),
 477        primary_end: Some(serialize_text_anchor(&range.primary.end)),
 478    })
 479}
 480
 481fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 482    proto::Selection {
 483        id: selection.id as u64,
 484        start: Some(serialize_anchor(&selection.start)),
 485        end: Some(serialize_anchor(&selection.end)),
 486        reversed: selection.reversed,
 487    }
 488}
 489
 490fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 491    proto::EditorAnchor {
 492        excerpt_id: anchor.excerpt_id.to_proto(),
 493        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 494    }
 495}
 496
 497fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 498    let context = {
 499        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 500        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 501        start..end
 502    };
 503    let primary = excerpt
 504        .primary_start
 505        .zip(excerpt.primary_end)
 506        .and_then(|(start, end)| {
 507            let start = language::proto::deserialize_anchor(start)?;
 508            let end = language::proto::deserialize_anchor(end)?;
 509            Some(start..end)
 510        })
 511        .unwrap_or_else(|| context.clone());
 512    Some(ExcerptRange { context, primary })
 513}
 514
 515fn deserialize_selection(
 516    buffer: &MultiBufferSnapshot,
 517    selection: proto::Selection,
 518) -> Option<Selection<Anchor>> {
 519    Some(Selection {
 520        id: selection.id as usize,
 521        start: deserialize_anchor(buffer, selection.start?)?,
 522        end: deserialize_anchor(buffer, selection.end?)?,
 523        reversed: selection.reversed,
 524        goal: SelectionGoal::None,
 525    })
 526}
 527
 528fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 529    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 530    Some(Anchor {
 531        excerpt_id,
 532        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 533        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 534        diff_base_anchor: None,
 535    })
 536}
 537
 538impl Item for Editor {
 539    type Event = EditorEvent;
 540
 541    fn navigate(
 542        &mut self,
 543        data: Box<dyn std::any::Any>,
 544        window: &mut Window,
 545        cx: &mut Context<Self>,
 546    ) -> bool {
 547        if let Ok(data) = data.downcast::<NavigationData>() {
 548            let newest_selection = self.selections.newest::<Point>(cx);
 549            let buffer = self.buffer.read(cx).read(cx);
 550            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 551                data.cursor_anchor.to_point(&buffer)
 552            } else {
 553                buffer.clip_point(data.cursor_position, Bias::Left)
 554            };
 555
 556            let mut scroll_anchor = data.scroll_anchor;
 557            if !buffer.can_resolve(&scroll_anchor.anchor) {
 558                scroll_anchor.anchor = buffer.anchor_before(
 559                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 560                );
 561            }
 562
 563            drop(buffer);
 564
 565            if newest_selection.head() == offset {
 566                false
 567            } else {
 568                let nav_history = self.nav_history.take();
 569                self.set_scroll_anchor(scroll_anchor, window, cx);
 570                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 571                    s.select_ranges([offset..offset])
 572                });
 573                self.nav_history = nav_history;
 574                true
 575            }
 576        } else {
 577            false
 578        }
 579    }
 580
 581    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 582        let file_path = self
 583            .buffer()
 584            .read(cx)
 585            .as_singleton()?
 586            .read(cx)
 587            .file()
 588            .and_then(|f| f.as_local())?
 589            .abs_path(cx);
 590
 591        let file_path = file_path.compact().to_string_lossy().to_string();
 592
 593        Some(file_path.into())
 594    }
 595
 596    fn telemetry_event_text(&self) -> Option<&'static str> {
 597        None
 598    }
 599
 600    fn tab_description(&self, detail: usize, cx: &App) -> Option<SharedString> {
 601        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 602        Some(path.to_string_lossy().to_string().into())
 603    }
 604
 605    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 606        ItemSettings::get_global(cx)
 607            .file_icons
 608            .then(|| {
 609                path_for_buffer(&self.buffer, 0, true, cx)
 610                    .and_then(|path| FileIcons::get_icon(path.as_ref(), cx))
 611            })
 612            .flatten()
 613            .map(Icon::from_path)
 614    }
 615
 616    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 617        let label_color = if ItemSettings::get_global(cx).git_status {
 618            self.buffer()
 619                .read(cx)
 620                .as_singleton()
 621                .and_then(|buffer| {
 622                    let buffer = buffer.read(cx);
 623                    let path = buffer.project_path(cx)?;
 624                    let buffer_id = buffer.remote_id();
 625                    let project = self.project.as_ref()?.read(cx);
 626                    let entry = project.entry_for_path(&path, cx)?;
 627                    let (repo, repo_path) = project
 628                        .git_store()
 629                        .read(cx)
 630                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 631                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 632
 633                    Some(entry_git_aware_label_color(
 634                        status.summary(),
 635                        entry.is_ignored,
 636                        params.selected,
 637                    ))
 638                })
 639                .unwrap_or_else(|| entry_label_color(params.selected))
 640        } else {
 641            entry_label_color(params.selected)
 642        };
 643
 644        let description = params.detail.and_then(|detail| {
 645            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 646            let description = path.to_string_lossy();
 647            let description = description.trim();
 648
 649            if description.is_empty() {
 650                return None;
 651            }
 652
 653            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 654        });
 655
 656        // Whether the file was saved in the past but is now deleted.
 657        let was_deleted: bool = self
 658            .buffer()
 659            .read(cx)
 660            .as_singleton()
 661            .and_then(|buffer| buffer.read(cx).file())
 662            .map_or(false, |file| file.disk_state() == DiskState::Deleted);
 663
 664        h_flex()
 665            .gap_2()
 666            .child(
 667                Label::new(self.title(cx).to_string())
 668                    .color(label_color)
 669                    .when(params.preview, |this| this.italic())
 670                    .when(was_deleted, |this| this.strikethrough()),
 671            )
 672            .when_some(description, |this, description| {
 673                this.child(
 674                    Label::new(description)
 675                        .size(LabelSize::XSmall)
 676                        .color(Color::Muted),
 677                )
 678            })
 679            .into_any_element()
 680    }
 681
 682    fn for_each_project_item(
 683        &self,
 684        cx: &App,
 685        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 686    ) {
 687        self.buffer
 688            .read(cx)
 689            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 690    }
 691
 692    fn is_singleton(&self, cx: &App) -> bool {
 693        self.buffer.read(cx).is_singleton()
 694    }
 695
 696    fn can_save_as(&self, cx: &App) -> bool {
 697        self.buffer.read(cx).is_singleton()
 698    }
 699
 700    fn clone_on_split(
 701        &self,
 702        _workspace_id: Option<WorkspaceId>,
 703        window: &mut Window,
 704        cx: &mut Context<Self>,
 705    ) -> Option<Entity<Editor>>
 706    where
 707        Self: Sized,
 708    {
 709        Some(cx.new(|cx| self.clone(window, cx)))
 710    }
 711
 712    fn set_nav_history(
 713        &mut self,
 714        history: ItemNavHistory,
 715        _window: &mut Window,
 716        _: &mut Context<Self>,
 717    ) {
 718        self.nav_history = Some(history);
 719    }
 720
 721    fn discarded(&self, _project: Entity<Project>, _: &mut Window, cx: &mut Context<Self>) {
 722        for buffer in self.buffer().clone().read(cx).all_buffers() {
 723            buffer.update(cx, |buffer, cx| buffer.discarded(cx))
 724        }
 725    }
 726
 727    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 728        let selection = self.selections.newest_anchor();
 729        self.push_to_nav_history(selection.head(), None, true, cx);
 730    }
 731
 732    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 733        self.hide_hovered_link(cx);
 734    }
 735
 736    fn is_dirty(&self, cx: &App) -> bool {
 737        self.buffer().read(cx).read(cx).is_dirty()
 738    }
 739
 740    fn has_deleted_file(&self, cx: &App) -> bool {
 741        self.buffer().read(cx).read(cx).has_deleted_file()
 742    }
 743
 744    fn has_conflict(&self, cx: &App) -> bool {
 745        self.buffer().read(cx).read(cx).has_conflict()
 746    }
 747
 748    fn can_save(&self, cx: &App) -> bool {
 749        let buffer = &self.buffer().read(cx);
 750        if let Some(buffer) = buffer.as_singleton() {
 751            buffer.read(cx).project_path(cx).is_some()
 752        } else {
 753            true
 754        }
 755    }
 756
 757    fn save(
 758        &mut self,
 759        format: bool,
 760        project: Entity<Project>,
 761        window: &mut Window,
 762        cx: &mut Context<Self>,
 763    ) -> Task<Result<()>> {
 764        self.report_editor_event("Editor Saved", None, cx);
 765        let buffers = self.buffer().clone().read(cx).all_buffers();
 766        let buffers = buffers
 767            .into_iter()
 768            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 769            .collect::<HashSet<_>>();
 770        cx.spawn_in(window, async move |this, cx| {
 771            if format {
 772                this.update_in(cx, |editor, window, cx| {
 773                    editor.perform_format(
 774                        project.clone(),
 775                        FormatTrigger::Save,
 776                        FormatTarget::Buffers,
 777                        window,
 778                        cx,
 779                    )
 780                })?
 781                .await?;
 782            }
 783
 784            if buffers.len() == 1 {
 785                // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
 786                project
 787                    .update(cx, |project, cx| project.save_buffers(buffers, cx))?
 788                    .await?;
 789            } else {
 790                // For multi-buffers, only format and save the buffers with changes.
 791                // For clean buffers, we simulate saving by calling `Buffer::did_save`,
 792                // so that language servers or other downstream listeners of save events get notified.
 793                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 794                    buffer
 795                        .update(cx, |buffer, _| buffer.is_dirty() || buffer.has_conflict())
 796                        .unwrap_or(false)
 797                });
 798
 799                project
 800                    .update(cx, |project, cx| project.save_buffers(dirty_buffers, cx))?
 801                    .await?;
 802                for buffer in clean_buffers {
 803                    buffer
 804                        .update(cx, |buffer, cx| {
 805                            let version = buffer.saved_version().clone();
 806                            let mtime = buffer.saved_mtime();
 807                            buffer.did_save(version, mtime, cx);
 808                        })
 809                        .ok();
 810                }
 811            }
 812
 813            Ok(())
 814        })
 815    }
 816
 817    fn save_as(
 818        &mut self,
 819        project: Entity<Project>,
 820        path: ProjectPath,
 821        _: &mut Window,
 822        cx: &mut Context<Self>,
 823    ) -> Task<Result<()>> {
 824        let buffer = self
 825            .buffer()
 826            .read(cx)
 827            .as_singleton()
 828            .expect("cannot call save_as on an excerpt list");
 829
 830        let file_extension = path
 831            .path
 832            .extension()
 833            .map(|a| a.to_string_lossy().to_string());
 834        self.report_editor_event("Editor Saved", file_extension, cx);
 835
 836        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 837    }
 838
 839    fn reload(
 840        &mut self,
 841        project: Entity<Project>,
 842        window: &mut Window,
 843        cx: &mut Context<Self>,
 844    ) -> Task<Result<()>> {
 845        let buffer = self.buffer().clone();
 846        let buffers = self.buffer.read(cx).all_buffers();
 847        let reload_buffers =
 848            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 849        cx.spawn_in(window, async move |this, cx| {
 850            let transaction = reload_buffers.log_err().await;
 851            this.update(cx, |editor, cx| {
 852                editor.request_autoscroll(Autoscroll::fit(), cx)
 853            })?;
 854            buffer
 855                .update(cx, |buffer, cx| {
 856                    if let Some(transaction) = transaction {
 857                        if !buffer.is_singleton() {
 858                            buffer.push_transaction(&transaction.0, cx);
 859                        }
 860                    }
 861                })
 862                .ok();
 863            Ok(())
 864        })
 865    }
 866
 867    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 868        Some(Box::new(handle.clone()))
 869    }
 870
 871    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 872        self.pixel_position_of_newest_cursor
 873    }
 874
 875    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 876        if self.show_breadcrumbs {
 877            ToolbarItemLocation::PrimaryLeft
 878        } else {
 879            ToolbarItemLocation::Hidden
 880        }
 881    }
 882
 883    fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 884        let cursor = self.selections.newest_anchor().head();
 885        let multibuffer = &self.buffer().read(cx);
 886        let (buffer_id, symbols) =
 887            multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
 888        let buffer = multibuffer.buffer(buffer_id)?;
 889
 890        let buffer = buffer.read(cx);
 891        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 892            buffer
 893                .snapshot()
 894                .resolve_file_path(
 895                    cx,
 896                    self.project
 897                        .as_ref()
 898                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 899                        .unwrap_or_default(),
 900                )
 901                .map(|path| path.to_string_lossy().to_string())
 902                .unwrap_or_else(|| {
 903                    if multibuffer.is_singleton() {
 904                        multibuffer.title(cx).to_string()
 905                    } else {
 906                        "untitled".to_string()
 907                    }
 908                })
 909        });
 910
 911        let settings = ThemeSettings::get_global(cx);
 912
 913        let mut breadcrumbs = vec![BreadcrumbText {
 914            text,
 915            highlights: None,
 916            font: Some(settings.buffer_font.clone()),
 917        }];
 918
 919        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 920            text: symbol.text,
 921            highlights: Some(symbol.highlight_ranges),
 922            font: Some(settings.buffer_font.clone()),
 923        }));
 924        Some(breadcrumbs)
 925    }
 926
 927    fn added_to_workspace(
 928        &mut self,
 929        workspace: &mut Workspace,
 930        _window: &mut Window,
 931        cx: &mut Context<Self>,
 932    ) {
 933        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 934        if let Some(workspace) = &workspace.weak_handle().upgrade() {
 935            cx.subscribe(&workspace, |editor, _, event: &workspace::Event, _cx| {
 936                if matches!(event, workspace::Event::ModalOpened) {
 937                    editor.mouse_context_menu.take();
 938                }
 939            })
 940            .detach();
 941        }
 942    }
 943
 944    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 945        match event {
 946            EditorEvent::Closed => f(ItemEvent::CloseItem),
 947
 948            EditorEvent::Saved | EditorEvent::TitleChanged => {
 949                f(ItemEvent::UpdateTab);
 950                f(ItemEvent::UpdateBreadcrumbs);
 951            }
 952
 953            EditorEvent::Reparsed(_) => {
 954                f(ItemEvent::UpdateBreadcrumbs);
 955            }
 956
 957            EditorEvent::SelectionsChanged { local } if *local => {
 958                f(ItemEvent::UpdateBreadcrumbs);
 959            }
 960
 961            EditorEvent::DirtyChanged => {
 962                f(ItemEvent::UpdateTab);
 963            }
 964
 965            EditorEvent::BufferEdited => {
 966                f(ItemEvent::Edit);
 967                f(ItemEvent::UpdateBreadcrumbs);
 968            }
 969
 970            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 971                f(ItemEvent::Edit);
 972            }
 973
 974            _ => {}
 975        }
 976    }
 977
 978    fn preserve_preview(&self, cx: &App) -> bool {
 979        self.buffer.read(cx).preserve_preview(cx)
 980    }
 981}
 982
 983impl SerializableItem for Editor {
 984    fn serialized_item_kind() -> &'static str {
 985        "Editor"
 986    }
 987
 988    fn cleanup(
 989        workspace_id: WorkspaceId,
 990        alive_items: Vec<ItemId>,
 991        window: &mut Window,
 992        cx: &mut App,
 993    ) -> Task<Result<()>> {
 994        window.spawn(cx, async move |_| {
 995            DB.delete_unloaded_items(workspace_id, alive_items).await
 996        })
 997    }
 998
 999    fn deserialize(
1000        project: Entity<Project>,
1001        workspace: WeakEntity<Workspace>,
1002        workspace_id: workspace::WorkspaceId,
1003        item_id: ItemId,
1004        window: &mut Window,
1005        cx: &mut App,
1006    ) -> Task<Result<Entity<Self>>> {
1007        let serialized_editor = match DB
1008            .get_serialized_editor(item_id, workspace_id)
1009            .context("Failed to query editor state")
1010        {
1011            Ok(Some(serialized_editor)) => {
1012                if ProjectSettings::get_global(cx)
1013                    .session
1014                    .restore_unsaved_buffers
1015                {
1016                    serialized_editor
1017                } else {
1018                    SerializedEditor {
1019                        abs_path: serialized_editor.abs_path,
1020                        contents: None,
1021                        language: None,
1022                        mtime: None,
1023                    }
1024                }
1025            }
1026            Ok(None) => {
1027                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1028            }
1029            Err(error) => {
1030                return Task::ready(Err(error));
1031            }
1032        };
1033
1034        match serialized_editor {
1035            SerializedEditor {
1036                abs_path: None,
1037                contents: Some(contents),
1038                language,
1039                ..
1040            } => window.spawn(cx, {
1041                let project = project.clone();
1042                async move |cx| {
1043                    let language_registry =
1044                        project.update(cx, |project, _| project.languages().clone())?;
1045
1046                    let language = if let Some(language_name) = language {
1047                        // We don't fail here, because we'd rather not set the language if the name changed
1048                        // than fail to restore the buffer.
1049                        language_registry
1050                            .language_for_name(&language_name)
1051                            .await
1052                            .ok()
1053                    } else {
1054                        None
1055                    };
1056
1057                    // First create the empty buffer
1058                    let buffer = project
1059                        .update(cx, |project, cx| project.create_buffer(cx))?
1060                        .await?;
1061
1062                    // Then set the text so that the dirty bit is set correctly
1063                    buffer.update(cx, |buffer, cx| {
1064                        buffer.set_language_registry(language_registry);
1065                        if let Some(language) = language {
1066                            buffer.set_language(Some(language), cx);
1067                        }
1068                        buffer.set_text(contents, cx);
1069                        if let Some(entry) = buffer.peek_undo_stack() {
1070                            buffer.forget_transaction(entry.transaction_id());
1071                        }
1072                    })?;
1073
1074                    cx.update(|window, cx| {
1075                        cx.new(|cx| {
1076                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1077
1078                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1079                            editor
1080                        })
1081                    })
1082                }
1083            }),
1084            SerializedEditor {
1085                abs_path: Some(abs_path),
1086                contents,
1087                mtime,
1088                ..
1089            } => {
1090                let project_item = project.update(cx, |project, cx| {
1091                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1092                    let project_path = ProjectPath {
1093                        worktree_id: worktree.read(cx).id(),
1094                        path: path.into(),
1095                    };
1096                    Some(project.open_path(project_path, cx))
1097                });
1098
1099                match project_item {
1100                    Some(project_item) => {
1101                        window.spawn(cx, async move |cx| {
1102                            let (_, project_item) = project_item.await?;
1103                            let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1104                                anyhow!("Project item at stored path was not a buffer")
1105                            })?;
1106
1107                            // This is a bit wasteful: we're loading the whole buffer from
1108                            // disk and then overwrite the content.
1109                            // But for now, it keeps the implementation of the content serialization
1110                            // simple, because we don't have to persist all of the metadata that we get
1111                            // by loading the file (git diff base, ...).
1112                            if let Some(buffer_text) = contents {
1113                                buffer.update(cx, |buffer, cx| {
1114                                    // If we did restore an mtime, we want to store it on the buffer
1115                                    // so that the next edit will mark the buffer as dirty/conflicted.
1116                                    if mtime.is_some() {
1117                                        buffer.did_reload(
1118                                            buffer.version(),
1119                                            buffer.line_ending(),
1120                                            mtime,
1121                                            cx,
1122                                        );
1123                                    }
1124                                    buffer.set_text(buffer_text, cx);
1125                                    if let Some(entry) = buffer.peek_undo_stack() {
1126                                        buffer.forget_transaction(entry.transaction_id());
1127                                    }
1128                                })?;
1129                            }
1130
1131                            cx.update(|window, cx| {
1132                                cx.new(|cx| {
1133                                    let mut editor =
1134                                        Editor::for_buffer(buffer, Some(project), window, cx);
1135
1136                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1137                                    editor
1138                                })
1139                            })
1140                        })
1141                    }
1142                    None => {
1143                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1144                            workspace.open_abs_path(
1145                                abs_path.clone(),
1146                                OpenOptions {
1147                                    visible: Some(OpenVisible::None),
1148                                    ..Default::default()
1149                                },
1150                                window,
1151                                cx,
1152                            )
1153                        });
1154                        window.spawn(cx, async move |cx| {
1155                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1156                            editor.update_in(cx, |editor, window, cx| {
1157                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1158                            })?;
1159                            Ok(editor)
1160                        })
1161                    }
1162                }
1163            }
1164            SerializedEditor {
1165                abs_path: None,
1166                contents: None,
1167                ..
1168            } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1169        }
1170    }
1171
1172    fn serialize(
1173        &mut self,
1174        workspace: &mut Workspace,
1175        item_id: ItemId,
1176        closing: bool,
1177        window: &mut Window,
1178        cx: &mut Context<Self>,
1179    ) -> Option<Task<Result<()>>> {
1180        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1181
1182        let project = self.project.clone()?;
1183        if project.read(cx).visible_worktrees(cx).next().is_none() {
1184            // If we don't have a worktree, we don't serialize, because
1185            // projects without worktrees aren't deserialized.
1186            serialize_dirty_buffers = false;
1187        }
1188
1189        if closing && !serialize_dirty_buffers {
1190            return None;
1191        }
1192
1193        let workspace_id = workspace.database_id()?;
1194
1195        let buffer = self.buffer().read(cx).as_singleton()?;
1196
1197        let abs_path = buffer.read(cx).file().and_then(|file| {
1198            let worktree_id = file.worktree_id(cx);
1199            project
1200                .read(cx)
1201                .worktree_for_id(worktree_id, cx)
1202                .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1203                .or_else(|| {
1204                    let full_path = file.full_path(cx);
1205                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1206                    project.read(cx).absolute_path(&project_path, cx)
1207                })
1208        });
1209
1210        let is_dirty = buffer.read(cx).is_dirty();
1211        let mtime = buffer.read(cx).saved_mtime();
1212
1213        let snapshot = buffer.read(cx).snapshot();
1214
1215        Some(cx.spawn_in(window, async move |_this, cx| {
1216            cx.background_spawn(async move {
1217                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1218                    let contents = snapshot.text();
1219                    let language = snapshot.language().map(|lang| lang.name().to_string());
1220                    (Some(contents), language)
1221                } else {
1222                    (None, None)
1223                };
1224
1225                let editor = SerializedEditor {
1226                    abs_path,
1227                    contents,
1228                    language,
1229                    mtime,
1230                };
1231                DB.save_serialized_editor(item_id, workspace_id, editor)
1232                    .await
1233                    .context("failed to save serialized editor")
1234            })
1235            .await
1236            .context("failed to save contents of buffer")?;
1237
1238            Ok(())
1239        }))
1240    }
1241
1242    fn should_serialize(&self, event: &Self::Event) -> bool {
1243        matches!(
1244            event,
1245            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1246        )
1247    }
1248}
1249
1250#[derive(Debug, Default)]
1251struct EditorRestorationData {
1252    entries: HashMap<PathBuf, RestorationData>,
1253}
1254
1255#[derive(Default, Debug)]
1256pub struct RestorationData {
1257    pub scroll_position: (BufferRow, gpui::Point<f32>),
1258    pub folds: Vec<Range<Point>>,
1259    pub selections: Vec<Range<Point>>,
1260}
1261
1262impl ProjectItem for Editor {
1263    type Item = Buffer;
1264
1265    fn project_item_kind() -> Option<ProjectItemKind> {
1266        Some(ProjectItemKind("Editor"))
1267    }
1268
1269    fn for_project_item(
1270        project: Entity<Project>,
1271        pane: &Pane,
1272        buffer: Entity<Buffer>,
1273        window: &mut Window,
1274        cx: &mut Context<Self>,
1275    ) -> Self {
1276        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1277        if let Some((excerpt_id, buffer_id, snapshot)) =
1278            editor.buffer().read(cx).snapshot(cx).as_singleton()
1279        {
1280            if WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1281                if let Some(restoration_data) = Self::project_item_kind()
1282                    .and_then(|kind| pane.project_item_restoration_data.get(&kind))
1283                    .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1284                    .and_then(|data| {
1285                        let file = project::File::from_dyn(buffer.read(cx).file())?;
1286                        data.entries.get(&file.abs_path(cx))
1287                    })
1288                {
1289                    editor.fold_ranges(
1290                        clip_ranges(&restoration_data.folds, &snapshot),
1291                        false,
1292                        window,
1293                        cx,
1294                    );
1295                    if !restoration_data.selections.is_empty() {
1296                        editor.change_selections(None, window, cx, |s| {
1297                            s.select_ranges(clip_ranges(&restoration_data.selections, &snapshot));
1298                        });
1299                    }
1300                    let (top_row, offset) = restoration_data.scroll_position;
1301                    let anchor = Anchor::in_buffer(
1302                        *excerpt_id,
1303                        buffer_id,
1304                        snapshot.anchor_before(Point::new(top_row, 0)),
1305                    );
1306                    editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1307                }
1308            }
1309        }
1310
1311        editor
1312    }
1313}
1314
1315fn clip_ranges<'a>(
1316    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1317    snapshot: &'a BufferSnapshot,
1318) -> Vec<Range<Point>> {
1319    original
1320        .into_iter()
1321        .map(|range| {
1322            snapshot.clip_point(range.start, Bias::Left)
1323                ..snapshot.clip_point(range.end, Bias::Right)
1324        })
1325        .collect()
1326}
1327
1328impl EventEmitter<SearchEvent> for Editor {}
1329
1330impl Editor {
1331    pub fn update_restoration_data(
1332        &self,
1333        cx: &mut Context<Self>,
1334        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1335    ) {
1336        if !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1337            return;
1338        }
1339
1340        let editor = cx.entity();
1341        cx.defer(move |cx| {
1342            editor.update(cx, |editor, cx| {
1343                let kind = Editor::project_item_kind()?;
1344                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1345                let buffer = editor.buffer().read(cx).as_singleton()?;
1346                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1347                pane.update(cx, |pane, _| {
1348                    let data = pane
1349                        .project_item_restoration_data
1350                        .entry(kind)
1351                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1352                    let data = match data.downcast_mut::<EditorRestorationData>() {
1353                        Some(data) => data,
1354                        None => {
1355                            *data = Box::new(EditorRestorationData::default());
1356                            data.downcast_mut::<EditorRestorationData>()
1357                                .expect("just written the type downcasted to")
1358                        }
1359                    };
1360
1361                    let data = data.entries.entry(file_abs_path).or_default();
1362                    write(data);
1363                    Some(())
1364                })
1365            });
1366        });
1367    }
1368}
1369
1370pub(crate) enum BufferSearchHighlights {}
1371impl SearchableItem for Editor {
1372    type Match = Range<Anchor>;
1373
1374    fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1375        self.background_highlights
1376            .get(&TypeId::of::<BufferSearchHighlights>())
1377            .map_or(Vec::new(), |(_color, ranges)| {
1378                ranges.iter().cloned().collect()
1379            })
1380    }
1381
1382    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1383        if self
1384            .clear_background_highlights::<BufferSearchHighlights>(cx)
1385            .is_some()
1386        {
1387            cx.emit(SearchEvent::MatchesInvalidated);
1388        }
1389    }
1390
1391    fn update_matches(
1392        &mut self,
1393        matches: &[Range<Anchor>],
1394        _: &mut Window,
1395        cx: &mut Context<Self>,
1396    ) {
1397        let existing_range = self
1398            .background_highlights
1399            .get(&TypeId::of::<BufferSearchHighlights>())
1400            .map(|(_, range)| range.as_ref());
1401        let updated = existing_range != Some(matches);
1402        self.highlight_background::<BufferSearchHighlights>(
1403            matches,
1404            |theme| theme.search_match_background,
1405            cx,
1406        );
1407        if updated {
1408            cx.emit(SearchEvent::MatchesInvalidated);
1409        }
1410    }
1411
1412    fn has_filtered_search_ranges(&mut self) -> bool {
1413        self.has_background_highlights::<SearchWithinRange>()
1414    }
1415
1416    fn toggle_filtered_search_ranges(
1417        &mut self,
1418        enabled: bool,
1419        _: &mut Window,
1420        cx: &mut Context<Self>,
1421    ) {
1422        if self.has_filtered_search_ranges() {
1423            self.previous_search_ranges = self
1424                .clear_background_highlights::<SearchWithinRange>(cx)
1425                .map(|(_, ranges)| ranges)
1426        }
1427
1428        if !enabled {
1429            return;
1430        }
1431
1432        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1433        if ranges.iter().any(|s| s.start != s.end) {
1434            self.set_search_within_ranges(&ranges, cx);
1435        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1436            self.set_search_within_ranges(&previous_search_ranges, cx)
1437        }
1438    }
1439
1440    fn supported_options(&self) -> SearchOptions {
1441        if self.in_project_search {
1442            SearchOptions {
1443                case: true,
1444                word: true,
1445                regex: true,
1446                replacement: false,
1447                selection: false,
1448                find_in_results: true,
1449            }
1450        } else {
1451            SearchOptions {
1452                case: true,
1453                word: true,
1454                regex: true,
1455                replacement: true,
1456                selection: true,
1457                find_in_results: false,
1458            }
1459        }
1460    }
1461
1462    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1463        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1464        let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1465        let selection = self.selections.newest::<usize>(cx);
1466
1467        match setting {
1468            SeedQuerySetting::Never => String::new(),
1469            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1470                let text: String = snapshot
1471                    .text_for_range(selection.start..selection.end)
1472                    .collect();
1473                if text.contains('\n') {
1474                    String::new()
1475                } else {
1476                    text
1477                }
1478            }
1479            SeedQuerySetting::Selection => String::new(),
1480            SeedQuerySetting::Always => {
1481                let (range, kind) = snapshot.surrounding_word(selection.start, true);
1482                if kind == Some(CharKind::Word) {
1483                    let text: String = snapshot.text_for_range(range).collect();
1484                    if !text.trim().is_empty() {
1485                        return text;
1486                    }
1487                }
1488                String::new()
1489            }
1490        }
1491    }
1492
1493    fn activate_match(
1494        &mut self,
1495        index: usize,
1496        matches: &[Range<Anchor>],
1497        window: &mut Window,
1498        cx: &mut Context<Self>,
1499    ) {
1500        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1501        let range = self.range_for_match(&matches[index]);
1502        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1503            s.select_ranges([range]);
1504        })
1505    }
1506
1507    fn select_matches(
1508        &mut self,
1509        matches: &[Self::Match],
1510        window: &mut Window,
1511        cx: &mut Context<Self>,
1512    ) {
1513        self.unfold_ranges(matches, false, false, cx);
1514        self.change_selections(None, window, cx, |s| {
1515            s.select_ranges(matches.iter().cloned())
1516        });
1517    }
1518    fn replace(
1519        &mut self,
1520        identifier: &Self::Match,
1521        query: &SearchQuery,
1522        window: &mut Window,
1523        cx: &mut Context<Self>,
1524    ) {
1525        let text = self.buffer.read(cx);
1526        let text = text.snapshot(cx);
1527        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1528        let text: Cow<_> = if text.len() == 1 {
1529            text.first().cloned().unwrap().into()
1530        } else {
1531            let joined_chunks = text.join("");
1532            joined_chunks.into()
1533        };
1534
1535        if let Some(replacement) = query.replacement_for(&text) {
1536            self.transact(window, cx, |this, _, cx| {
1537                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1538            });
1539        }
1540    }
1541    fn replace_all(
1542        &mut self,
1543        matches: &mut dyn Iterator<Item = &Self::Match>,
1544        query: &SearchQuery,
1545        window: &mut Window,
1546        cx: &mut Context<Self>,
1547    ) {
1548        let text = self.buffer.read(cx);
1549        let text = text.snapshot(cx);
1550        let mut edits = vec![];
1551        let mut last_point: Option<Point> = None;
1552
1553        for m in matches {
1554            let point = m.start.to_point(&text);
1555            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1556
1557            // Check if the row for the current match is different from the last
1558            // match. If that's not the case and we're still replacing matches
1559            // in the same row/line, skip this match if the `one_match_per_line`
1560            // option is enabled.
1561            if last_point.is_none() {
1562                last_point = Some(point);
1563            } else if last_point.is_some() && point.row != last_point.unwrap().row {
1564                last_point = Some(point);
1565            } else if query.one_match_per_line().is_some_and(|enabled| enabled) {
1566                continue;
1567            }
1568
1569            let text: Cow<_> = if text.len() == 1 {
1570                text.first().cloned().unwrap().into()
1571            } else {
1572                let joined_chunks = text.join("");
1573                joined_chunks.into()
1574            };
1575
1576            if let Some(replacement) = query.replacement_for(&text) {
1577                edits.push((m.clone(), Arc::from(&*replacement)));
1578            }
1579        }
1580
1581        if !edits.is_empty() {
1582            self.transact(window, cx, |this, _, cx| {
1583                this.edit(edits, cx);
1584            });
1585        }
1586    }
1587    fn match_index_for_direction(
1588        &mut self,
1589        matches: &[Range<Anchor>],
1590        current_index: usize,
1591        direction: Direction,
1592        count: usize,
1593        _: &mut Window,
1594        cx: &mut Context<Self>,
1595    ) -> usize {
1596        let buffer = self.buffer().read(cx).snapshot(cx);
1597        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1598            self.selections.newest_anchor().head()
1599        } else {
1600            matches[current_index].start
1601        };
1602
1603        let mut count = count % matches.len();
1604        if count == 0 {
1605            return current_index;
1606        }
1607        match direction {
1608            Direction::Next => {
1609                if matches[current_index]
1610                    .start
1611                    .cmp(&current_index_position, &buffer)
1612                    .is_gt()
1613                {
1614                    count -= 1
1615                }
1616
1617                (current_index + count) % matches.len()
1618            }
1619            Direction::Prev => {
1620                if matches[current_index]
1621                    .end
1622                    .cmp(&current_index_position, &buffer)
1623                    .is_lt()
1624                {
1625                    count -= 1;
1626                }
1627
1628                if current_index >= count {
1629                    current_index - count
1630                } else {
1631                    matches.len() - (count - current_index)
1632                }
1633            }
1634        }
1635    }
1636
1637    fn find_matches(
1638        &mut self,
1639        query: Arc<project::search::SearchQuery>,
1640        _: &mut Window,
1641        cx: &mut Context<Self>,
1642    ) -> Task<Vec<Range<Anchor>>> {
1643        let buffer = self.buffer().read(cx).snapshot(cx);
1644        let search_within_ranges = self
1645            .background_highlights
1646            .get(&TypeId::of::<SearchWithinRange>())
1647            .map_or(vec![], |(_color, ranges)| {
1648                ranges.iter().cloned().collect::<Vec<_>>()
1649            });
1650
1651        cx.background_spawn(async move {
1652            let mut ranges = Vec::new();
1653
1654            let search_within_ranges = if search_within_ranges.is_empty() {
1655                vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1656            } else {
1657                search_within_ranges
1658            };
1659
1660            for range in search_within_ranges {
1661                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1662                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1663                {
1664                    ranges.extend(
1665                        query
1666                            .search(search_buffer, Some(search_range.clone()))
1667                            .await
1668                            .into_iter()
1669                            .map(|match_range| {
1670                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1671                                    let start = search_buffer
1672                                        .anchor_after(search_range.start + match_range.start);
1673                                    let end = search_buffer
1674                                        .anchor_before(search_range.start + match_range.end);
1675                                    Anchor {
1676                                        diff_base_anchor: Some(start),
1677                                        ..deleted_hunk_anchor
1678                                    }..Anchor {
1679                                        diff_base_anchor: Some(end),
1680                                        ..deleted_hunk_anchor
1681                                    }
1682                                } else {
1683                                    let start = search_buffer
1684                                        .anchor_after(search_range.start + match_range.start);
1685                                    let end = search_buffer
1686                                        .anchor_before(search_range.start + match_range.end);
1687                                    Anchor::range_in_buffer(
1688                                        excerpt_id,
1689                                        search_buffer.remote_id(),
1690                                        start..end,
1691                                    )
1692                                }
1693                            }),
1694                    );
1695                }
1696            }
1697
1698            ranges
1699        })
1700    }
1701
1702    fn active_match_index(
1703        &mut self,
1704        direction: Direction,
1705        matches: &[Range<Anchor>],
1706        _: &mut Window,
1707        cx: &mut Context<Self>,
1708    ) -> Option<usize> {
1709        active_match_index(
1710            direction,
1711            matches,
1712            &self.selections.newest_anchor().head(),
1713            &self.buffer().read(cx).snapshot(cx),
1714        )
1715    }
1716
1717    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1718        self.expect_bounds_change = self.last_bounds;
1719    }
1720}
1721
1722pub fn active_match_index(
1723    direction: Direction,
1724    ranges: &[Range<Anchor>],
1725    cursor: &Anchor,
1726    buffer: &MultiBufferSnapshot,
1727) -> Option<usize> {
1728    if ranges.is_empty() {
1729        None
1730    } else {
1731        let r = ranges.binary_search_by(|probe| {
1732            if probe.end.cmp(cursor, buffer).is_lt() {
1733                Ordering::Less
1734            } else if probe.start.cmp(cursor, buffer).is_gt() {
1735                Ordering::Greater
1736            } else {
1737                Ordering::Equal
1738            }
1739        });
1740        match direction {
1741            Direction::Prev => match r {
1742                Ok(i) => Some(i),
1743                Err(i) => Some(i.saturating_sub(1)),
1744            },
1745            Direction::Next => match r {
1746                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1747            },
1748        }
1749    }
1750}
1751
1752pub fn entry_label_color(selected: bool) -> Color {
1753    if selected {
1754        Color::Default
1755    } else {
1756        Color::Muted
1757    }
1758}
1759
1760pub fn entry_diagnostic_aware_icon_name_and_color(
1761    diagnostic_severity: Option<DiagnosticSeverity>,
1762) -> Option<(IconName, Color)> {
1763    match diagnostic_severity {
1764        Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1765        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1766        _ => None,
1767    }
1768}
1769
1770pub fn entry_diagnostic_aware_icon_decoration_and_color(
1771    diagnostic_severity: Option<DiagnosticSeverity>,
1772) -> Option<(IconDecorationKind, Color)> {
1773    match diagnostic_severity {
1774        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1775        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1776        _ => None,
1777    }
1778}
1779
1780pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1781    let tracked = git_status.index + git_status.worktree;
1782    if ignored {
1783        Color::Ignored
1784    } else if git_status.conflict > 0 {
1785        Color::Conflict
1786    } else if tracked.modified > 0 {
1787        Color::Modified
1788    } else if tracked.added > 0 || git_status.untracked > 0 {
1789        Color::Created
1790    } else {
1791        entry_label_color(selected)
1792    }
1793}
1794
1795fn path_for_buffer<'a>(
1796    buffer: &Entity<MultiBuffer>,
1797    height: usize,
1798    include_filename: bool,
1799    cx: &'a App,
1800) -> Option<Cow<'a, Path>> {
1801    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1802    path_for_file(file.as_ref(), height, include_filename, cx)
1803}
1804
1805fn path_for_file<'a>(
1806    file: &'a dyn language::File,
1807    mut height: usize,
1808    include_filename: bool,
1809    cx: &'a App,
1810) -> Option<Cow<'a, Path>> {
1811    // Ensure we always render at least the filename.
1812    height += 1;
1813
1814    let mut prefix = file.path().as_ref();
1815    while height > 0 {
1816        if let Some(parent) = prefix.parent() {
1817            prefix = parent;
1818            height -= 1;
1819        } else {
1820            break;
1821        }
1822    }
1823
1824    // Here we could have just always used `full_path`, but that is very
1825    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1826    // traversed all the way up to the worktree's root.
1827    if height > 0 {
1828        let full_path = file.full_path(cx);
1829        if include_filename {
1830            Some(full_path.into())
1831        } else {
1832            Some(full_path.parent()?.to_path_buf().into())
1833        }
1834    } else {
1835        let mut path = file.path().strip_prefix(prefix).ok()?;
1836        if !include_filename {
1837            path = path.parent()?;
1838        }
1839        Some(path.into())
1840    }
1841}
1842
1843#[cfg(test)]
1844mod tests {
1845    use crate::editor_tests::init_test;
1846    use fs::Fs;
1847
1848    use super::*;
1849    use fs::MTime;
1850    use gpui::{App, VisualTestContext};
1851    use language::{LanguageMatcher, TestFile};
1852    use project::FakeFs;
1853    use std::path::{Path, PathBuf};
1854    use util::path;
1855
1856    #[gpui::test]
1857    fn test_path_for_file(cx: &mut App) {
1858        let file = TestFile {
1859            path: Path::new("").into(),
1860            root_name: String::new(),
1861            local_root: None,
1862        };
1863        assert_eq!(path_for_file(&file, 0, false, cx), None);
1864    }
1865
1866    async fn deserialize_editor(
1867        item_id: ItemId,
1868        workspace_id: WorkspaceId,
1869        workspace: Entity<Workspace>,
1870        project: Entity<Project>,
1871        cx: &mut VisualTestContext,
1872    ) -> Entity<Editor> {
1873        workspace
1874            .update_in(cx, |workspace, window, cx| {
1875                let pane = workspace.active_pane();
1876                pane.update(cx, |_, cx| {
1877                    Editor::deserialize(
1878                        project.clone(),
1879                        workspace.weak_handle(),
1880                        workspace_id,
1881                        item_id,
1882                        window,
1883                        cx,
1884                    )
1885                })
1886            })
1887            .await
1888            .unwrap()
1889    }
1890
1891    fn rust_language() -> Arc<language::Language> {
1892        Arc::new(language::Language::new(
1893            language::LanguageConfig {
1894                name: "Rust".into(),
1895                matcher: LanguageMatcher {
1896                    path_suffixes: vec!["rs".to_string()],
1897                    ..Default::default()
1898                },
1899                ..Default::default()
1900            },
1901            Some(tree_sitter_rust::LANGUAGE.into()),
1902        ))
1903    }
1904
1905    #[gpui::test]
1906    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1907        init_test(cx, |_| {});
1908
1909        let fs = FakeFs::new(cx.executor());
1910        fs.insert_file(path!("/file.rs"), Default::default()).await;
1911
1912        // Test case 1: Deserialize with path and contents
1913        {
1914            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1915            let (workspace, cx) =
1916                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1917            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1918            let item_id = 1234 as ItemId;
1919            let mtime = fs
1920                .metadata(Path::new(path!("/file.rs")))
1921                .await
1922                .unwrap()
1923                .unwrap()
1924                .mtime;
1925
1926            let serialized_editor = SerializedEditor {
1927                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1928                contents: Some("fn main() {}".to_string()),
1929                language: Some("Rust".to_string()),
1930                mtime: Some(mtime),
1931            };
1932
1933            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1934                .await
1935                .unwrap();
1936
1937            let deserialized =
1938                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1939
1940            deserialized.update(cx, |editor, cx| {
1941                assert_eq!(editor.text(cx), "fn main() {}");
1942                assert!(editor.is_dirty(cx));
1943                assert!(!editor.has_conflict(cx));
1944                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1945                assert!(buffer.file().is_some());
1946            });
1947        }
1948
1949        // Test case 2: Deserialize with only path
1950        {
1951            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1952            let (workspace, cx) =
1953                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1954
1955            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1956
1957            let item_id = 5678 as ItemId;
1958            let serialized_editor = SerializedEditor {
1959                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1960                contents: None,
1961                language: None,
1962                mtime: None,
1963            };
1964
1965            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1966                .await
1967                .unwrap();
1968
1969            let deserialized =
1970                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1971
1972            deserialized.update(cx, |editor, cx| {
1973                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1974                assert!(!editor.is_dirty(cx));
1975                assert!(!editor.has_conflict(cx));
1976
1977                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1978                assert!(buffer.file().is_some());
1979            });
1980        }
1981
1982        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1983        {
1984            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1985            // Add Rust to the language, so that we can restore the language of the buffer
1986            project.update(cx, |project, _| project.languages().add(rust_language()));
1987
1988            let (workspace, cx) =
1989                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1990
1991            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1992
1993            let item_id = 9012 as ItemId;
1994            let serialized_editor = SerializedEditor {
1995                abs_path: None,
1996                contents: Some("hello".to_string()),
1997                language: Some("Rust".to_string()),
1998                mtime: None,
1999            };
2000
2001            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2002                .await
2003                .unwrap();
2004
2005            let deserialized =
2006                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2007
2008            deserialized.update(cx, |editor, cx| {
2009                assert_eq!(editor.text(cx), "hello");
2010                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2011
2012                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2013                assert_eq!(
2014                    buffer.language().map(|lang| lang.name()),
2015                    Some("Rust".into())
2016                ); // Language should be set to Rust
2017                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2018            });
2019        }
2020
2021        // Test case 4: Deserialize with path, content, and old mtime
2022        {
2023            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2024            let (workspace, cx) =
2025                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2026
2027            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2028
2029            let item_id = 9345 as ItemId;
2030            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2031            let serialized_editor = SerializedEditor {
2032                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2033                contents: Some("fn main() {}".to_string()),
2034                language: Some("Rust".to_string()),
2035                mtime: Some(old_mtime),
2036            };
2037
2038            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2039                .await
2040                .unwrap();
2041
2042            let deserialized =
2043                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2044
2045            deserialized.update(cx, |editor, cx| {
2046                assert_eq!(editor.text(cx), "fn main() {}");
2047                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2048            });
2049        }
2050    }
2051}