items.rs

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