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        _: &mut Context<Self>,
 932    ) {
 933        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 934    }
 935
 936    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 937        match event {
 938            EditorEvent::Closed => f(ItemEvent::CloseItem),
 939
 940            EditorEvent::Saved | EditorEvent::TitleChanged => {
 941                f(ItemEvent::UpdateTab);
 942                f(ItemEvent::UpdateBreadcrumbs);
 943            }
 944
 945            EditorEvent::Reparsed(_) => {
 946                f(ItemEvent::UpdateBreadcrumbs);
 947            }
 948
 949            EditorEvent::SelectionsChanged { local } if *local => {
 950                f(ItemEvent::UpdateBreadcrumbs);
 951            }
 952
 953            EditorEvent::DirtyChanged => {
 954                f(ItemEvent::UpdateTab);
 955            }
 956
 957            EditorEvent::BufferEdited => {
 958                f(ItemEvent::Edit);
 959                f(ItemEvent::UpdateBreadcrumbs);
 960            }
 961
 962            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 963                f(ItemEvent::Edit);
 964            }
 965
 966            _ => {}
 967        }
 968    }
 969
 970    fn preserve_preview(&self, cx: &App) -> bool {
 971        self.buffer.read(cx).preserve_preview(cx)
 972    }
 973}
 974
 975impl SerializableItem for Editor {
 976    fn serialized_item_kind() -> &'static str {
 977        "Editor"
 978    }
 979
 980    fn cleanup(
 981        workspace_id: WorkspaceId,
 982        alive_items: Vec<ItemId>,
 983        window: &mut Window,
 984        cx: &mut App,
 985    ) -> Task<Result<()>> {
 986        window.spawn(cx, async move |_| {
 987            DB.delete_unloaded_items(workspace_id, alive_items).await
 988        })
 989    }
 990
 991    fn deserialize(
 992        project: Entity<Project>,
 993        workspace: WeakEntity<Workspace>,
 994        workspace_id: workspace::WorkspaceId,
 995        item_id: ItemId,
 996        window: &mut Window,
 997        cx: &mut App,
 998    ) -> Task<Result<Entity<Self>>> {
 999        let serialized_editor = match DB
1000            .get_serialized_editor(item_id, workspace_id)
1001            .context("Failed to query editor state")
1002        {
1003            Ok(Some(serialized_editor)) => {
1004                if ProjectSettings::get_global(cx)
1005                    .session
1006                    .restore_unsaved_buffers
1007                {
1008                    serialized_editor
1009                } else {
1010                    SerializedEditor {
1011                        abs_path: serialized_editor.abs_path,
1012                        contents: None,
1013                        language: None,
1014                        mtime: None,
1015                    }
1016                }
1017            }
1018            Ok(None) => {
1019                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1020            }
1021            Err(error) => {
1022                return Task::ready(Err(error));
1023            }
1024        };
1025
1026        match serialized_editor {
1027            SerializedEditor {
1028                abs_path: None,
1029                contents: Some(contents),
1030                language,
1031                ..
1032            } => window.spawn(cx, {
1033                let project = project.clone();
1034                async move |cx| {
1035                    let language_registry =
1036                        project.update(cx, |project, _| project.languages().clone())?;
1037
1038                    let language = if let Some(language_name) = language {
1039                        // We don't fail here, because we'd rather not set the language if the name changed
1040                        // than fail to restore the buffer.
1041                        language_registry
1042                            .language_for_name(&language_name)
1043                            .await
1044                            .ok()
1045                    } else {
1046                        None
1047                    };
1048
1049                    // First create the empty buffer
1050                    let buffer = project
1051                        .update(cx, |project, cx| project.create_buffer(cx))?
1052                        .await?;
1053
1054                    // Then set the text so that the dirty bit is set correctly
1055                    buffer.update(cx, |buffer, cx| {
1056                        buffer.set_language_registry(language_registry);
1057                        if let Some(language) = language {
1058                            buffer.set_language(Some(language), cx);
1059                        }
1060                        buffer.set_text(contents, cx);
1061                        if let Some(entry) = buffer.peek_undo_stack() {
1062                            buffer.forget_transaction(entry.transaction_id());
1063                        }
1064                    })?;
1065
1066                    cx.update(|window, cx| {
1067                        cx.new(|cx| {
1068                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1069
1070                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1071                            editor
1072                        })
1073                    })
1074                }
1075            }),
1076            SerializedEditor {
1077                abs_path: Some(abs_path),
1078                contents,
1079                mtime,
1080                ..
1081            } => {
1082                let project_item = project.update(cx, |project, cx| {
1083                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1084                    let project_path = ProjectPath {
1085                        worktree_id: worktree.read(cx).id(),
1086                        path: path.into(),
1087                    };
1088                    Some(project.open_path(project_path, cx))
1089                });
1090
1091                match project_item {
1092                    Some(project_item) => {
1093                        window.spawn(cx, async move |cx| {
1094                            let (_, project_item) = project_item.await?;
1095                            let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1096                                anyhow!("Project item at stored path was not a buffer")
1097                            })?;
1098
1099                            // This is a bit wasteful: we're loading the whole buffer from
1100                            // disk and then overwrite the content.
1101                            // But for now, it keeps the implementation of the content serialization
1102                            // simple, because we don't have to persist all of the metadata that we get
1103                            // by loading the file (git diff base, ...).
1104                            if let Some(buffer_text) = contents {
1105                                buffer.update(cx, |buffer, cx| {
1106                                    // If we did restore an mtime, we want to store it on the buffer
1107                                    // so that the next edit will mark the buffer as dirty/conflicted.
1108                                    if mtime.is_some() {
1109                                        buffer.did_reload(
1110                                            buffer.version(),
1111                                            buffer.line_ending(),
1112                                            mtime,
1113                                            cx,
1114                                        );
1115                                    }
1116                                    buffer.set_text(buffer_text, cx);
1117                                    if let Some(entry) = buffer.peek_undo_stack() {
1118                                        buffer.forget_transaction(entry.transaction_id());
1119                                    }
1120                                })?;
1121                            }
1122
1123                            cx.update(|window, cx| {
1124                                cx.new(|cx| {
1125                                    let mut editor =
1126                                        Editor::for_buffer(buffer, Some(project), window, cx);
1127
1128                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1129                                    editor
1130                                })
1131                            })
1132                        })
1133                    }
1134                    None => {
1135                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1136                            workspace.open_abs_path(
1137                                abs_path.clone(),
1138                                OpenOptions {
1139                                    visible: Some(OpenVisible::None),
1140                                    ..Default::default()
1141                                },
1142                                window,
1143                                cx,
1144                            )
1145                        });
1146                        window.spawn(cx, async move |cx| {
1147                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1148                            editor.update_in(cx, |editor, window, cx| {
1149                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1150                            })?;
1151                            Ok(editor)
1152                        })
1153                    }
1154                }
1155            }
1156            SerializedEditor {
1157                abs_path: None,
1158                contents: None,
1159                ..
1160            } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1161        }
1162    }
1163
1164    fn serialize(
1165        &mut self,
1166        workspace: &mut Workspace,
1167        item_id: ItemId,
1168        closing: bool,
1169        window: &mut Window,
1170        cx: &mut Context<Self>,
1171    ) -> Option<Task<Result<()>>> {
1172        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1173
1174        let project = self.project.clone()?;
1175        if project.read(cx).visible_worktrees(cx).next().is_none() {
1176            // If we don't have a worktree, we don't serialize, because
1177            // projects without worktrees aren't deserialized.
1178            serialize_dirty_buffers = false;
1179        }
1180
1181        if closing && !serialize_dirty_buffers {
1182            return None;
1183        }
1184
1185        let workspace_id = workspace.database_id()?;
1186
1187        let buffer = self.buffer().read(cx).as_singleton()?;
1188
1189        let abs_path = buffer.read(cx).file().and_then(|file| {
1190            let worktree_id = file.worktree_id(cx);
1191            project
1192                .read(cx)
1193                .worktree_for_id(worktree_id, cx)
1194                .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1195                .or_else(|| {
1196                    let full_path = file.full_path(cx);
1197                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1198                    project.read(cx).absolute_path(&project_path, cx)
1199                })
1200        });
1201
1202        let is_dirty = buffer.read(cx).is_dirty();
1203        let mtime = buffer.read(cx).saved_mtime();
1204
1205        let snapshot = buffer.read(cx).snapshot();
1206
1207        Some(cx.spawn_in(window, async move |_this, cx| {
1208            cx.background_spawn(async move {
1209                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1210                    let contents = snapshot.text();
1211                    let language = snapshot.language().map(|lang| lang.name().to_string());
1212                    (Some(contents), language)
1213                } else {
1214                    (None, None)
1215                };
1216
1217                let editor = SerializedEditor {
1218                    abs_path,
1219                    contents,
1220                    language,
1221                    mtime,
1222                };
1223                DB.save_serialized_editor(item_id, workspace_id, editor)
1224                    .await
1225                    .context("failed to save serialized editor")
1226            })
1227            .await
1228            .context("failed to save contents of buffer")?;
1229
1230            Ok(())
1231        }))
1232    }
1233
1234    fn should_serialize(&self, event: &Self::Event) -> bool {
1235        matches!(
1236            event,
1237            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1238        )
1239    }
1240}
1241
1242#[derive(Debug, Default)]
1243struct EditorRestorationData {
1244    entries: HashMap<PathBuf, RestorationData>,
1245}
1246
1247#[derive(Default, Debug)]
1248pub struct RestorationData {
1249    pub scroll_position: (BufferRow, gpui::Point<f32>),
1250    pub folds: Vec<Range<Point>>,
1251    pub selections: Vec<Range<Point>>,
1252}
1253
1254impl ProjectItem for Editor {
1255    type Item = Buffer;
1256
1257    fn project_item_kind() -> Option<ProjectItemKind> {
1258        Some(ProjectItemKind("Editor"))
1259    }
1260
1261    fn for_project_item(
1262        project: Entity<Project>,
1263        pane: &Pane,
1264        buffer: Entity<Buffer>,
1265        window: &mut Window,
1266        cx: &mut Context<Self>,
1267    ) -> Self {
1268        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1269        if let Some((excerpt_id, buffer_id, snapshot)) =
1270            editor.buffer().read(cx).snapshot(cx).as_singleton()
1271        {
1272            if WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1273                if let Some(restoration_data) = Self::project_item_kind()
1274                    .and_then(|kind| pane.project_item_restoration_data.get(&kind))
1275                    .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1276                    .and_then(|data| {
1277                        let file = project::File::from_dyn(buffer.read(cx).file())?;
1278                        data.entries.get(&file.abs_path(cx))
1279                    })
1280                {
1281                    editor.fold_ranges(
1282                        clip_ranges(&restoration_data.folds, &snapshot),
1283                        false,
1284                        window,
1285                        cx,
1286                    );
1287                    if !restoration_data.selections.is_empty() {
1288                        editor.change_selections(None, window, cx, |s| {
1289                            s.select_ranges(clip_ranges(&restoration_data.selections, &snapshot));
1290                        });
1291                    }
1292                    let (top_row, offset) = restoration_data.scroll_position;
1293                    let anchor = Anchor::in_buffer(
1294                        *excerpt_id,
1295                        buffer_id,
1296                        snapshot.anchor_before(Point::new(top_row, 0)),
1297                    );
1298                    editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1299                }
1300            }
1301        }
1302
1303        editor
1304    }
1305}
1306
1307fn clip_ranges<'a>(
1308    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1309    snapshot: &'a BufferSnapshot,
1310) -> Vec<Range<Point>> {
1311    original
1312        .into_iter()
1313        .map(|range| {
1314            snapshot.clip_point(range.start, Bias::Left)
1315                ..snapshot.clip_point(range.end, Bias::Right)
1316        })
1317        .collect()
1318}
1319
1320impl EventEmitter<SearchEvent> for Editor {}
1321
1322impl Editor {
1323    pub fn update_restoration_data(
1324        &self,
1325        cx: &mut Context<Self>,
1326        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1327    ) {
1328        if !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1329            return;
1330        }
1331
1332        let editor = cx.entity();
1333        cx.defer(move |cx| {
1334            editor.update(cx, |editor, cx| {
1335                let kind = Editor::project_item_kind()?;
1336                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1337                let buffer = editor.buffer().read(cx).as_singleton()?;
1338                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1339                pane.update(cx, |pane, _| {
1340                    let data = pane
1341                        .project_item_restoration_data
1342                        .entry(kind)
1343                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1344                    let data = match data.downcast_mut::<EditorRestorationData>() {
1345                        Some(data) => data,
1346                        None => {
1347                            *data = Box::new(EditorRestorationData::default());
1348                            data.downcast_mut::<EditorRestorationData>()
1349                                .expect("just written the type downcasted to")
1350                        }
1351                    };
1352
1353                    let data = data.entries.entry(file_abs_path).or_default();
1354                    write(data);
1355                    Some(())
1356                })
1357            });
1358        });
1359    }
1360}
1361
1362pub(crate) enum BufferSearchHighlights {}
1363impl SearchableItem for Editor {
1364    type Match = Range<Anchor>;
1365
1366    fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1367        self.background_highlights
1368            .get(&TypeId::of::<BufferSearchHighlights>())
1369            .map_or(Vec::new(), |(_color, ranges)| {
1370                ranges.iter().cloned().collect()
1371            })
1372    }
1373
1374    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1375        if self
1376            .clear_background_highlights::<BufferSearchHighlights>(cx)
1377            .is_some()
1378        {
1379            cx.emit(SearchEvent::MatchesInvalidated);
1380        }
1381    }
1382
1383    fn update_matches(
1384        &mut self,
1385        matches: &[Range<Anchor>],
1386        _: &mut Window,
1387        cx: &mut Context<Self>,
1388    ) {
1389        let existing_range = self
1390            .background_highlights
1391            .get(&TypeId::of::<BufferSearchHighlights>())
1392            .map(|(_, range)| range.as_ref());
1393        let updated = existing_range != Some(matches);
1394        self.highlight_background::<BufferSearchHighlights>(
1395            matches,
1396            |theme| theme.search_match_background,
1397            cx,
1398        );
1399        if updated {
1400            cx.emit(SearchEvent::MatchesInvalidated);
1401        }
1402    }
1403
1404    fn has_filtered_search_ranges(&mut self) -> bool {
1405        self.has_background_highlights::<SearchWithinRange>()
1406    }
1407
1408    fn toggle_filtered_search_ranges(
1409        &mut self,
1410        enabled: bool,
1411        _: &mut Window,
1412        cx: &mut Context<Self>,
1413    ) {
1414        if self.has_filtered_search_ranges() {
1415            self.previous_search_ranges = self
1416                .clear_background_highlights::<SearchWithinRange>(cx)
1417                .map(|(_, ranges)| ranges)
1418        }
1419
1420        if !enabled {
1421            return;
1422        }
1423
1424        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1425        if ranges.iter().any(|s| s.start != s.end) {
1426            self.set_search_within_ranges(&ranges, cx);
1427        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1428            self.set_search_within_ranges(&previous_search_ranges, cx)
1429        }
1430    }
1431
1432    fn supported_options(&self) -> SearchOptions {
1433        if self.in_project_search {
1434            SearchOptions {
1435                case: true,
1436                word: true,
1437                regex: true,
1438                replacement: false,
1439                selection: false,
1440                find_in_results: true,
1441            }
1442        } else {
1443            SearchOptions {
1444                case: true,
1445                word: true,
1446                regex: true,
1447                replacement: true,
1448                selection: true,
1449                find_in_results: false,
1450            }
1451        }
1452    }
1453
1454    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1455        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1456        let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1457        let selection = self.selections.newest::<usize>(cx);
1458
1459        match setting {
1460            SeedQuerySetting::Never => String::new(),
1461            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1462                let text: String = snapshot
1463                    .text_for_range(selection.start..selection.end)
1464                    .collect();
1465                if text.contains('\n') {
1466                    String::new()
1467                } else {
1468                    text
1469                }
1470            }
1471            SeedQuerySetting::Selection => String::new(),
1472            SeedQuerySetting::Always => {
1473                let (range, kind) = snapshot.surrounding_word(selection.start, true);
1474                if kind == Some(CharKind::Word) {
1475                    let text: String = snapshot.text_for_range(range).collect();
1476                    if !text.trim().is_empty() {
1477                        return text;
1478                    }
1479                }
1480                String::new()
1481            }
1482        }
1483    }
1484
1485    fn activate_match(
1486        &mut self,
1487        index: usize,
1488        matches: &[Range<Anchor>],
1489        window: &mut Window,
1490        cx: &mut Context<Self>,
1491    ) {
1492        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1493        let range = self.range_for_match(&matches[index]);
1494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1495            s.select_ranges([range]);
1496        })
1497    }
1498
1499    fn select_matches(
1500        &mut self,
1501        matches: &[Self::Match],
1502        window: &mut Window,
1503        cx: &mut Context<Self>,
1504    ) {
1505        self.unfold_ranges(matches, false, false, cx);
1506        self.change_selections(None, window, cx, |s| {
1507            s.select_ranges(matches.iter().cloned())
1508        });
1509    }
1510    fn replace(
1511        &mut self,
1512        identifier: &Self::Match,
1513        query: &SearchQuery,
1514        window: &mut Window,
1515        cx: &mut Context<Self>,
1516    ) {
1517        let text = self.buffer.read(cx);
1518        let text = text.snapshot(cx);
1519        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1520        let text: Cow<_> = if text.len() == 1 {
1521            text.first().cloned().unwrap().into()
1522        } else {
1523            let joined_chunks = text.join("");
1524            joined_chunks.into()
1525        };
1526
1527        if let Some(replacement) = query.replacement_for(&text) {
1528            self.transact(window, cx, |this, _, cx| {
1529                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1530            });
1531        }
1532    }
1533    fn replace_all(
1534        &mut self,
1535        matches: &mut dyn Iterator<Item = &Self::Match>,
1536        query: &SearchQuery,
1537        window: &mut Window,
1538        cx: &mut Context<Self>,
1539    ) {
1540        let text = self.buffer.read(cx);
1541        let text = text.snapshot(cx);
1542        let mut edits = vec![];
1543        let mut last_point: Option<Point> = None;
1544
1545        for m in matches {
1546            let point = m.start.to_point(&text);
1547            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1548
1549            // Check if the row for the current match is different from the last
1550            // match. If that's not the case and we're still replacing matches
1551            // in the same row/line, skip this match if the `one_match_per_line`
1552            // option is enabled.
1553            if last_point.is_none() {
1554                last_point = Some(point);
1555            } else if last_point.is_some() && point.row != last_point.unwrap().row {
1556                last_point = Some(point);
1557            } else if query.one_match_per_line().is_some_and(|enabled| enabled) {
1558                continue;
1559            }
1560
1561            let text: Cow<_> = if text.len() == 1 {
1562                text.first().cloned().unwrap().into()
1563            } else {
1564                let joined_chunks = text.join("");
1565                joined_chunks.into()
1566            };
1567
1568            if let Some(replacement) = query.replacement_for(&text) {
1569                edits.push((m.clone(), Arc::from(&*replacement)));
1570            }
1571        }
1572
1573        if !edits.is_empty() {
1574            self.transact(window, cx, |this, _, cx| {
1575                this.edit(edits, cx);
1576            });
1577        }
1578    }
1579    fn match_index_for_direction(
1580        &mut self,
1581        matches: &[Range<Anchor>],
1582        current_index: usize,
1583        direction: Direction,
1584        count: usize,
1585        _: &mut Window,
1586        cx: &mut Context<Self>,
1587    ) -> usize {
1588        let buffer = self.buffer().read(cx).snapshot(cx);
1589        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1590            self.selections.newest_anchor().head()
1591        } else {
1592            matches[current_index].start
1593        };
1594
1595        let mut count = count % matches.len();
1596        if count == 0 {
1597            return current_index;
1598        }
1599        match direction {
1600            Direction::Next => {
1601                if matches[current_index]
1602                    .start
1603                    .cmp(&current_index_position, &buffer)
1604                    .is_gt()
1605                {
1606                    count -= 1
1607                }
1608
1609                (current_index + count) % matches.len()
1610            }
1611            Direction::Prev => {
1612                if matches[current_index]
1613                    .end
1614                    .cmp(&current_index_position, &buffer)
1615                    .is_lt()
1616                {
1617                    count -= 1;
1618                }
1619
1620                if current_index >= count {
1621                    current_index - count
1622                } else {
1623                    matches.len() - (count - current_index)
1624                }
1625            }
1626        }
1627    }
1628
1629    fn find_matches(
1630        &mut self,
1631        query: Arc<project::search::SearchQuery>,
1632        _: &mut Window,
1633        cx: &mut Context<Self>,
1634    ) -> Task<Vec<Range<Anchor>>> {
1635        let buffer = self.buffer().read(cx).snapshot(cx);
1636        let search_within_ranges = self
1637            .background_highlights
1638            .get(&TypeId::of::<SearchWithinRange>())
1639            .map_or(vec![], |(_color, ranges)| {
1640                ranges.iter().cloned().collect::<Vec<_>>()
1641            });
1642
1643        cx.background_spawn(async move {
1644            let mut ranges = Vec::new();
1645
1646            let search_within_ranges = if search_within_ranges.is_empty() {
1647                vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1648            } else {
1649                search_within_ranges
1650            };
1651
1652            for range in search_within_ranges {
1653                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1654                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1655                {
1656                    ranges.extend(
1657                        query
1658                            .search(search_buffer, Some(search_range.clone()))
1659                            .await
1660                            .into_iter()
1661                            .map(|match_range| {
1662                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1663                                    let start = search_buffer
1664                                        .anchor_after(search_range.start + match_range.start);
1665                                    let end = search_buffer
1666                                        .anchor_before(search_range.start + match_range.end);
1667                                    Anchor {
1668                                        diff_base_anchor: Some(start),
1669                                        ..deleted_hunk_anchor
1670                                    }..Anchor {
1671                                        diff_base_anchor: Some(end),
1672                                        ..deleted_hunk_anchor
1673                                    }
1674                                } else {
1675                                    let start = search_buffer
1676                                        .anchor_after(search_range.start + match_range.start);
1677                                    let end = search_buffer
1678                                        .anchor_before(search_range.start + match_range.end);
1679                                    Anchor::range_in_buffer(
1680                                        excerpt_id,
1681                                        search_buffer.remote_id(),
1682                                        start..end,
1683                                    )
1684                                }
1685                            }),
1686                    );
1687                }
1688            }
1689
1690            ranges
1691        })
1692    }
1693
1694    fn active_match_index(
1695        &mut self,
1696        direction: Direction,
1697        matches: &[Range<Anchor>],
1698        _: &mut Window,
1699        cx: &mut Context<Self>,
1700    ) -> Option<usize> {
1701        active_match_index(
1702            direction,
1703            matches,
1704            &self.selections.newest_anchor().head(),
1705            &self.buffer().read(cx).snapshot(cx),
1706        )
1707    }
1708
1709    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1710        self.expect_bounds_change = self.last_bounds;
1711    }
1712}
1713
1714pub fn active_match_index(
1715    direction: Direction,
1716    ranges: &[Range<Anchor>],
1717    cursor: &Anchor,
1718    buffer: &MultiBufferSnapshot,
1719) -> Option<usize> {
1720    if ranges.is_empty() {
1721        None
1722    } else {
1723        let r = ranges.binary_search_by(|probe| {
1724            if probe.end.cmp(cursor, buffer).is_lt() {
1725                Ordering::Less
1726            } else if probe.start.cmp(cursor, buffer).is_gt() {
1727                Ordering::Greater
1728            } else {
1729                Ordering::Equal
1730            }
1731        });
1732        match direction {
1733            Direction::Prev => match r {
1734                Ok(i) => Some(i),
1735                Err(i) => Some(i.saturating_sub(1)),
1736            },
1737            Direction::Next => match r {
1738                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1739            },
1740        }
1741    }
1742}
1743
1744pub fn entry_label_color(selected: bool) -> Color {
1745    if selected {
1746        Color::Default
1747    } else {
1748        Color::Muted
1749    }
1750}
1751
1752pub fn entry_diagnostic_aware_icon_name_and_color(
1753    diagnostic_severity: Option<DiagnosticSeverity>,
1754) -> Option<(IconName, Color)> {
1755    match diagnostic_severity {
1756        Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1757        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1758        _ => None,
1759    }
1760}
1761
1762pub fn entry_diagnostic_aware_icon_decoration_and_color(
1763    diagnostic_severity: Option<DiagnosticSeverity>,
1764) -> Option<(IconDecorationKind, Color)> {
1765    match diagnostic_severity {
1766        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1767        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1768        _ => None,
1769    }
1770}
1771
1772pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1773    let tracked = git_status.index + git_status.worktree;
1774    if ignored {
1775        Color::Ignored
1776    } else if git_status.conflict > 0 {
1777        Color::Conflict
1778    } else if tracked.modified > 0 {
1779        Color::Modified
1780    } else if tracked.added > 0 || git_status.untracked > 0 {
1781        Color::Created
1782    } else {
1783        entry_label_color(selected)
1784    }
1785}
1786
1787fn path_for_buffer<'a>(
1788    buffer: &Entity<MultiBuffer>,
1789    height: usize,
1790    include_filename: bool,
1791    cx: &'a App,
1792) -> Option<Cow<'a, Path>> {
1793    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1794    path_for_file(file.as_ref(), height, include_filename, cx)
1795}
1796
1797fn path_for_file<'a>(
1798    file: &'a dyn language::File,
1799    mut height: usize,
1800    include_filename: bool,
1801    cx: &'a App,
1802) -> Option<Cow<'a, Path>> {
1803    // Ensure we always render at least the filename.
1804    height += 1;
1805
1806    let mut prefix = file.path().as_ref();
1807    while height > 0 {
1808        if let Some(parent) = prefix.parent() {
1809            prefix = parent;
1810            height -= 1;
1811        } else {
1812            break;
1813        }
1814    }
1815
1816    // Here we could have just always used `full_path`, but that is very
1817    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1818    // traversed all the way up to the worktree's root.
1819    if height > 0 {
1820        let full_path = file.full_path(cx);
1821        if include_filename {
1822            Some(full_path.into())
1823        } else {
1824            Some(full_path.parent()?.to_path_buf().into())
1825        }
1826    } else {
1827        let mut path = file.path().strip_prefix(prefix).ok()?;
1828        if !include_filename {
1829            path = path.parent()?;
1830        }
1831        Some(path.into())
1832    }
1833}
1834
1835#[cfg(test)]
1836mod tests {
1837    use crate::editor_tests::init_test;
1838    use fs::Fs;
1839
1840    use super::*;
1841    use fs::MTime;
1842    use gpui::{App, VisualTestContext};
1843    use language::{LanguageMatcher, TestFile};
1844    use project::FakeFs;
1845    use std::path::{Path, PathBuf};
1846    use util::path;
1847
1848    #[gpui::test]
1849    fn test_path_for_file(cx: &mut App) {
1850        let file = TestFile {
1851            path: Path::new("").into(),
1852            root_name: String::new(),
1853            local_root: None,
1854        };
1855        assert_eq!(path_for_file(&file, 0, false, cx), None);
1856    }
1857
1858    async fn deserialize_editor(
1859        item_id: ItemId,
1860        workspace_id: WorkspaceId,
1861        workspace: Entity<Workspace>,
1862        project: Entity<Project>,
1863        cx: &mut VisualTestContext,
1864    ) -> Entity<Editor> {
1865        workspace
1866            .update_in(cx, |workspace, window, cx| {
1867                let pane = workspace.active_pane();
1868                pane.update(cx, |_, cx| {
1869                    Editor::deserialize(
1870                        project.clone(),
1871                        workspace.weak_handle(),
1872                        workspace_id,
1873                        item_id,
1874                        window,
1875                        cx,
1876                    )
1877                })
1878            })
1879            .await
1880            .unwrap()
1881    }
1882
1883    fn rust_language() -> Arc<language::Language> {
1884        Arc::new(language::Language::new(
1885            language::LanguageConfig {
1886                name: "Rust".into(),
1887                matcher: LanguageMatcher {
1888                    path_suffixes: vec!["rs".to_string()],
1889                    ..Default::default()
1890                },
1891                ..Default::default()
1892            },
1893            Some(tree_sitter_rust::LANGUAGE.into()),
1894        ))
1895    }
1896
1897    #[gpui::test]
1898    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1899        init_test(cx, |_| {});
1900
1901        let fs = FakeFs::new(cx.executor());
1902        fs.insert_file(path!("/file.rs"), Default::default()).await;
1903
1904        // Test case 1: Deserialize with path and contents
1905        {
1906            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1907            let (workspace, cx) =
1908                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1909            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1910            let item_id = 1234 as ItemId;
1911            let mtime = fs
1912                .metadata(Path::new(path!("/file.rs")))
1913                .await
1914                .unwrap()
1915                .unwrap()
1916                .mtime;
1917
1918            let serialized_editor = SerializedEditor {
1919                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1920                contents: Some("fn main() {}".to_string()),
1921                language: Some("Rust".to_string()),
1922                mtime: Some(mtime),
1923            };
1924
1925            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1926                .await
1927                .unwrap();
1928
1929            let deserialized =
1930                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1931
1932            deserialized.update(cx, |editor, cx| {
1933                assert_eq!(editor.text(cx), "fn main() {}");
1934                assert!(editor.is_dirty(cx));
1935                assert!(!editor.has_conflict(cx));
1936                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1937                assert!(buffer.file().is_some());
1938            });
1939        }
1940
1941        // Test case 2: Deserialize with only path
1942        {
1943            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1944            let (workspace, cx) =
1945                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1946
1947            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1948
1949            let item_id = 5678 as ItemId;
1950            let serialized_editor = SerializedEditor {
1951                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1952                contents: None,
1953                language: None,
1954                mtime: None,
1955            };
1956
1957            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1958                .await
1959                .unwrap();
1960
1961            let deserialized =
1962                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1963
1964            deserialized.update(cx, |editor, cx| {
1965                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1966                assert!(!editor.is_dirty(cx));
1967                assert!(!editor.has_conflict(cx));
1968
1969                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1970                assert!(buffer.file().is_some());
1971            });
1972        }
1973
1974        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1975        {
1976            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1977            // Add Rust to the language, so that we can restore the language of the buffer
1978            project.update(cx, |project, _| project.languages().add(rust_language()));
1979
1980            let (workspace, cx) =
1981                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1982
1983            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1984
1985            let item_id = 9012 as ItemId;
1986            let serialized_editor = SerializedEditor {
1987                abs_path: None,
1988                contents: Some("hello".to_string()),
1989                language: Some("Rust".to_string()),
1990                mtime: None,
1991            };
1992
1993            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1994                .await
1995                .unwrap();
1996
1997            let deserialized =
1998                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1999
2000            deserialized.update(cx, |editor, cx| {
2001                assert_eq!(editor.text(cx), "hello");
2002                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2003
2004                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2005                assert_eq!(
2006                    buffer.language().map(|lang| lang.name()),
2007                    Some("Rust".into())
2008                ); // Language should be set to Rust
2009                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2010            });
2011        }
2012
2013        // Test case 4: Deserialize with path, content, and old mtime
2014        {
2015            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2016            let (workspace, cx) =
2017                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2018
2019            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2020
2021            let item_id = 9345 as ItemId;
2022            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2023            let serialized_editor = SerializedEditor {
2024                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2025                contents: Some("fn main() {}".to_string()),
2026                language: Some("Rust".to_string()),
2027                mtime: Some(old_mtime),
2028            };
2029
2030            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2031                .await
2032                .unwrap();
2033
2034            let deserialized =
2035                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2036
2037            deserialized.update(cx, |editor, cx| {
2038                assert_eq!(editor.text(cx), "fn main() {}");
2039                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2040            });
2041        }
2042    }
2043}