items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll,
   3    Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
   4    NavigationData, SearchWithinRange, ToPoint as _,
   5};
   6use anyhow::{anyhow, Context as _, Result};
   7use collections::HashSet;
   8use futures::future::try_join_all;
   9use git::repository::GitFileStatus;
  10use gpui::{
  11    point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
  12    IntoElement, Model, ParentElement, Pixels, SharedString, Styled, Task, View, ViewContext,
  13    VisualContext, WeakView, WindowContext,
  14};
  15use language::{
  16    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, Point, SelectionGoal,
  17};
  18use multi_buffer::AnchorRangeExt;
  19use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
  20use rpc::proto::{self, update_view, PeerId};
  21use settings::Settings;
  22use workspace::item::{Dedup, ItemSettings, TabContentParams};
  23
  24use std::{
  25    any::TypeId,
  26    borrow::Cow,
  27    cmp::{self, Ordering},
  28    iter,
  29    ops::Range,
  30    path::Path,
  31    sync::Arc,
  32};
  33use text::{BufferId, Selection};
  34use theme::{Theme, ThemeSettings};
  35use ui::{h_flex, prelude::*, Label};
  36use util::{paths::PathExt, ResultExt, TryFutureExt};
  37use workspace::item::{BreadcrumbText, FollowEvent};
  38use workspace::{
  39    item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
  40    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  41    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  42};
  43
  44pub const MAX_TAB_TITLE_LEN: usize = 24;
  45
  46impl FollowableItem for Editor {
  47    fn remote_id(&self) -> Option<ViewId> {
  48        self.remote_id
  49    }
  50
  51    fn from_state_proto(
  52        workspace: View<Workspace>,
  53        remote_id: ViewId,
  54        state: &mut Option<proto::view::Variant>,
  55        cx: &mut WindowContext,
  56    ) -> Option<Task<Result<View<Self>>>> {
  57        let project = workspace.read(cx).project().to_owned();
  58        let Some(proto::view::Variant::Editor(_)) = state else {
  59            return None;
  60        };
  61        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  62            unreachable!()
  63        };
  64
  65        let replica_id = project.read(cx).replica_id();
  66        let buffer_ids = state
  67            .excerpts
  68            .iter()
  69            .map(|excerpt| excerpt.buffer_id)
  70            .collect::<HashSet<_>>();
  71        let buffers = project.update(cx, |project, cx| {
  72            buffer_ids
  73                .iter()
  74                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  75                .collect::<Result<Vec<_>>>()
  76        });
  77
  78        Some(cx.spawn(|mut cx| async move {
  79            let mut buffers = futures::future::try_join_all(buffers?)
  80                .await
  81                .debug_assert_ok("leaders don't share views for unshared buffers")?;
  82
  83            let editor = cx.update(|cx| {
  84                let multibuffer = cx.new_model(|cx| {
  85                    let mut multibuffer;
  86                    if state.singleton && buffers.len() == 1 {
  87                        multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
  88                    } else {
  89                        multibuffer = MultiBuffer::new(replica_id, project.read(cx).capability());
  90                        let mut excerpts = state.excerpts.into_iter().peekable();
  91                        while let Some(excerpt) = excerpts.peek() {
  92                            let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
  93                                continue;
  94                            };
  95                            let buffer_excerpts = iter::from_fn(|| {
  96                                let excerpt = excerpts.peek()?;
  97                                (excerpt.buffer_id == u64::from(buffer_id))
  98                                    .then(|| excerpts.next().unwrap())
  99                            });
 100                            let buffer =
 101                                buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 102                            if let Some(buffer) = buffer {
 103                                multibuffer.push_excerpts(
 104                                    buffer.clone(),
 105                                    buffer_excerpts.filter_map(deserialize_excerpt_range),
 106                                    cx,
 107                                );
 108                            }
 109                        }
 110                    };
 111
 112                    if let Some(title) = &state.title {
 113                        multibuffer = multibuffer.with_title(title.clone())
 114                    }
 115
 116                    multibuffer
 117                });
 118
 119                cx.new_view(|cx| {
 120                    let mut editor =
 121                        Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx);
 122                    editor.remote_id = Some(remote_id);
 123                    editor
 124                })
 125            })?;
 126
 127            update_editor_from_message(
 128                editor.downgrade(),
 129                project,
 130                proto::update_view::Editor {
 131                    selections: state.selections,
 132                    pending_selection: state.pending_selection,
 133                    scroll_top_anchor: state.scroll_top_anchor,
 134                    scroll_x: state.scroll_x,
 135                    scroll_y: state.scroll_y,
 136                    ..Default::default()
 137                },
 138                &mut cx,
 139            )
 140            .await?;
 141
 142            Ok(editor)
 143        }))
 144    }
 145
 146    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 147        self.leader_peer_id = leader_peer_id;
 148        if self.leader_peer_id.is_some() {
 149            self.buffer.update(cx, |buffer, cx| {
 150                buffer.remove_active_selections(cx);
 151            });
 152        } else if self.focus_handle.is_focused(cx) {
 153            self.buffer.update(cx, |buffer, cx| {
 154                buffer.set_active_selections(
 155                    &self.selections.disjoint_anchors(),
 156                    self.selections.line_mode,
 157                    self.cursor_shape,
 158                    cx,
 159                );
 160            });
 161        }
 162        cx.notify();
 163    }
 164
 165    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 166        let buffer = self.buffer.read(cx);
 167        if buffer
 168            .as_singleton()
 169            .and_then(|buffer| buffer.read(cx).file())
 170            .map_or(false, |file| file.is_private())
 171        {
 172            return None;
 173        }
 174
 175        let scroll_anchor = self.scroll_manager.anchor();
 176        let excerpts = buffer
 177            .read(cx)
 178            .excerpts()
 179            .map(|(id, buffer, range)| proto::Excerpt {
 180                id: id.to_proto(),
 181                buffer_id: buffer.remote_id().into(),
 182                context_start: Some(serialize_text_anchor(&range.context.start)),
 183                context_end: Some(serialize_text_anchor(&range.context.end)),
 184                primary_start: range
 185                    .primary
 186                    .as_ref()
 187                    .map(|range| serialize_text_anchor(&range.start)),
 188                primary_end: range
 189                    .primary
 190                    .as_ref()
 191                    .map(|range| serialize_text_anchor(&range.end)),
 192            })
 193            .collect();
 194
 195        Some(proto::view::Variant::Editor(proto::view::Editor {
 196            singleton: buffer.is_singleton(),
 197            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 198            excerpts,
 199            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 200            scroll_x: scroll_anchor.offset.x,
 201            scroll_y: scroll_anchor.offset.y,
 202            selections: self
 203                .selections
 204                .disjoint_anchors()
 205                .iter()
 206                .map(serialize_selection)
 207                .collect(),
 208            pending_selection: self
 209                .selections
 210                .pending_anchor()
 211                .as_ref()
 212                .map(serialize_selection),
 213        }))
 214    }
 215
 216    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 217        match event {
 218            EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
 219            EditorEvent::SelectionsChanged { local }
 220            | EditorEvent::ScrollPositionChanged { local, .. } => {
 221                if *local {
 222                    Some(FollowEvent::Unfollow)
 223                } else {
 224                    None
 225                }
 226            }
 227            _ => None,
 228        }
 229    }
 230
 231    fn add_event_to_update_proto(
 232        &self,
 233        event: &EditorEvent,
 234        update: &mut Option<proto::update_view::Variant>,
 235        cx: &WindowContext,
 236    ) -> bool {
 237        let update =
 238            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 239
 240        match update {
 241            proto::update_view::Variant::Editor(update) => match event {
 242                EditorEvent::ExcerptsAdded {
 243                    buffer,
 244                    predecessor,
 245                    excerpts,
 246                } => {
 247                    let buffer_id = buffer.read(cx).remote_id();
 248                    let mut excerpts = excerpts.iter();
 249                    if let Some((id, range)) = excerpts.next() {
 250                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 251                            previous_excerpt_id: Some(predecessor.to_proto()),
 252                            excerpt: serialize_excerpt(buffer_id, id, range),
 253                        });
 254                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 255                            proto::ExcerptInsertion {
 256                                previous_excerpt_id: None,
 257                                excerpt: serialize_excerpt(buffer_id, id, range),
 258                            }
 259                        }))
 260                    }
 261                    true
 262                }
 263                EditorEvent::ExcerptsRemoved { ids } => {
 264                    update
 265                        .deleted_excerpts
 266                        .extend(ids.iter().map(ExcerptId::to_proto));
 267                    true
 268                }
 269                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 270                    let scroll_anchor = self.scroll_manager.anchor();
 271                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 272                    update.scroll_x = scroll_anchor.offset.x;
 273                    update.scroll_y = scroll_anchor.offset.y;
 274                    true
 275                }
 276                EditorEvent::SelectionsChanged { .. } => {
 277                    update.selections = self
 278                        .selections
 279                        .disjoint_anchors()
 280                        .iter()
 281                        .map(serialize_selection)
 282                        .collect();
 283                    update.pending_selection = self
 284                        .selections
 285                        .pending_anchor()
 286                        .as_ref()
 287                        .map(serialize_selection);
 288                    true
 289                }
 290                _ => false,
 291            },
 292        }
 293    }
 294
 295    fn apply_update_proto(
 296        &mut self,
 297        project: &Model<Project>,
 298        message: update_view::Variant,
 299        cx: &mut ViewContext<Self>,
 300    ) -> Task<Result<()>> {
 301        let update_view::Variant::Editor(message) = message;
 302        let project = project.clone();
 303        cx.spawn(|this, mut cx| async move {
 304            update_editor_from_message(this, project, message, &mut cx).await
 305        })
 306    }
 307
 308    fn is_project_item(&self, _cx: &WindowContext) -> bool {
 309        true
 310    }
 311
 312    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup> {
 313        let self_singleton = self.buffer.read(cx).as_singleton()?;
 314        let other_singleton = existing.buffer.read(cx).as_singleton()?;
 315        if self_singleton == other_singleton {
 316            Some(Dedup::KeepExisting)
 317        } else {
 318            None
 319        }
 320    }
 321}
 322
 323async fn update_editor_from_message(
 324    this: WeakView<Editor>,
 325    project: Model<Project>,
 326    message: proto::update_view::Editor,
 327    cx: &mut AsyncWindowContext,
 328) -> Result<()> {
 329    // Open all of the buffers of which excerpts were added to the editor.
 330    let inserted_excerpt_buffer_ids = message
 331        .inserted_excerpts
 332        .iter()
 333        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 334        .collect::<HashSet<_>>();
 335    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 336        inserted_excerpt_buffer_ids
 337            .into_iter()
 338            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 339            .collect::<Result<Vec<_>>>()
 340    })??;
 341    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 342
 343    // Update the editor's excerpts.
 344    this.update(cx, |editor, cx| {
 345        editor.buffer.update(cx, |multibuffer, cx| {
 346            let mut removed_excerpt_ids = message
 347                .deleted_excerpts
 348                .into_iter()
 349                .map(ExcerptId::from_proto)
 350                .collect::<Vec<_>>();
 351            removed_excerpt_ids.sort_by({
 352                let multibuffer = multibuffer.read(cx);
 353                move |a, b| a.cmp(&b, &multibuffer)
 354            });
 355
 356            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 357            while let Some(insertion) = insertions.next() {
 358                let Some(excerpt) = insertion.excerpt else {
 359                    continue;
 360                };
 361                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 362                    continue;
 363                };
 364                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 365                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
 366                    continue;
 367                };
 368
 369                let adjacent_excerpts = iter::from_fn(|| {
 370                    let insertion = insertions.peek()?;
 371                    if insertion.previous_excerpt_id.is_none()
 372                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 373                    {
 374                        insertions.next()?.excerpt
 375                    } else {
 376                        None
 377                    }
 378                });
 379
 380                multibuffer.insert_excerpts_with_ids_after(
 381                    ExcerptId::from_proto(previous_excerpt_id),
 382                    buffer,
 383                    [excerpt]
 384                        .into_iter()
 385                        .chain(adjacent_excerpts)
 386                        .filter_map(|excerpt| {
 387                            Some((
 388                                ExcerptId::from_proto(excerpt.id),
 389                                deserialize_excerpt_range(excerpt)?,
 390                            ))
 391                        }),
 392                    cx,
 393                );
 394            }
 395
 396            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 397            Result::<(), anyhow::Error>::Ok(())
 398        })
 399    })??;
 400
 401    // Deserialize the editor state.
 402    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 403        let buffer = editor.buffer.read(cx).read(cx);
 404        let selections = message
 405            .selections
 406            .into_iter()
 407            .filter_map(|selection| deserialize_selection(&buffer, selection))
 408            .collect::<Vec<_>>();
 409        let pending_selection = message
 410            .pending_selection
 411            .and_then(|selection| deserialize_selection(&buffer, selection));
 412        let scroll_top_anchor = message
 413            .scroll_top_anchor
 414            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 415        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 416    })??;
 417
 418    // Wait until the buffer has received all of the operations referenced by
 419    // the editor's new state.
 420    this.update(cx, |editor, cx| {
 421        editor.buffer.update(cx, |buffer, cx| {
 422            buffer.wait_for_anchors(
 423                selections
 424                    .iter()
 425                    .chain(pending_selection.as_ref())
 426                    .flat_map(|selection| [selection.start, selection.end])
 427                    .chain(scroll_top_anchor),
 428                cx,
 429            )
 430        })
 431    })?
 432    .await?;
 433
 434    // Update the editor's state.
 435    this.update(cx, |editor, cx| {
 436        if !selections.is_empty() || pending_selection.is_some() {
 437            editor.set_selections_from_remote(selections, pending_selection, cx);
 438            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 439        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 440            editor.set_scroll_anchor_remote(
 441                ScrollAnchor {
 442                    anchor: scroll_top_anchor,
 443                    offset: point(message.scroll_x, message.scroll_y),
 444                },
 445                cx,
 446            );
 447        }
 448    })?;
 449    Ok(())
 450}
 451
 452fn serialize_excerpt(
 453    buffer_id: BufferId,
 454    id: &ExcerptId,
 455    range: &ExcerptRange<language::Anchor>,
 456) -> Option<proto::Excerpt> {
 457    Some(proto::Excerpt {
 458        id: id.to_proto(),
 459        buffer_id: buffer_id.into(),
 460        context_start: Some(serialize_text_anchor(&range.context.start)),
 461        context_end: Some(serialize_text_anchor(&range.context.end)),
 462        primary_start: range
 463            .primary
 464            .as_ref()
 465            .map(|r| serialize_text_anchor(&r.start)),
 466        primary_end: range
 467            .primary
 468            .as_ref()
 469            .map(|r| serialize_text_anchor(&r.end)),
 470    })
 471}
 472
 473fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 474    proto::Selection {
 475        id: selection.id as u64,
 476        start: Some(serialize_anchor(&selection.start)),
 477        end: Some(serialize_anchor(&selection.end)),
 478        reversed: selection.reversed,
 479    }
 480}
 481
 482fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 483    proto::EditorAnchor {
 484        excerpt_id: anchor.excerpt_id.to_proto(),
 485        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 486    }
 487}
 488
 489fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 490    let context = {
 491        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 492        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 493        start..end
 494    };
 495    let primary = excerpt
 496        .primary_start
 497        .zip(excerpt.primary_end)
 498        .and_then(|(start, end)| {
 499            let start = language::proto::deserialize_anchor(start)?;
 500            let end = language::proto::deserialize_anchor(end)?;
 501            Some(start..end)
 502        });
 503    Some(ExcerptRange { context, primary })
 504}
 505
 506fn deserialize_selection(
 507    buffer: &MultiBufferSnapshot,
 508    selection: proto::Selection,
 509) -> Option<Selection<Anchor>> {
 510    Some(Selection {
 511        id: selection.id as usize,
 512        start: deserialize_anchor(buffer, selection.start?)?,
 513        end: deserialize_anchor(buffer, selection.end?)?,
 514        reversed: selection.reversed,
 515        goal: SelectionGoal::None,
 516    })
 517}
 518
 519fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 520    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 521    Some(Anchor {
 522        excerpt_id,
 523        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 524        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 525    })
 526}
 527
 528impl Item for Editor {
 529    type Event = EditorEvent;
 530
 531    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
 532        if let Ok(data) = data.downcast::<NavigationData>() {
 533            let newest_selection = self.selections.newest::<Point>(cx);
 534            let buffer = self.buffer.read(cx).read(cx);
 535            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 536                data.cursor_anchor.to_point(&buffer)
 537            } else {
 538                buffer.clip_point(data.cursor_position, Bias::Left)
 539            };
 540
 541            let mut scroll_anchor = data.scroll_anchor;
 542            if !buffer.can_resolve(&scroll_anchor.anchor) {
 543                scroll_anchor.anchor = buffer.anchor_before(
 544                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 545                );
 546            }
 547
 548            drop(buffer);
 549
 550            if newest_selection.head() == offset {
 551                false
 552            } else {
 553                let nav_history = self.nav_history.take();
 554                self.set_scroll_anchor(scroll_anchor, cx);
 555                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 556                    s.select_ranges([offset..offset])
 557                });
 558                self.nav_history = nav_history;
 559                true
 560            }
 561        } else {
 562            false
 563        }
 564    }
 565
 566    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 567        let file_path = self
 568            .buffer()
 569            .read(cx)
 570            .as_singleton()?
 571            .read(cx)
 572            .file()
 573            .and_then(|f| f.as_local())?
 574            .abs_path(cx);
 575
 576        let file_path = file_path.compact().to_string_lossy().to_string();
 577
 578        Some(file_path.into())
 579    }
 580
 581    fn telemetry_event_text(&self) -> Option<&'static str> {
 582        None
 583    }
 584
 585    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
 586        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 587        Some(path.to_string_lossy().to_string().into())
 588    }
 589
 590    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 591        let label_color = if ItemSettings::get_global(cx).git_status {
 592            self.buffer()
 593                .read(cx)
 594                .as_singleton()
 595                .and_then(|buffer| buffer.read(cx).project_path(cx))
 596                .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
 597                .map(|entry| {
 598                    entry_git_aware_label_color(entry.git_status, entry.is_ignored, params.selected)
 599                })
 600                .unwrap_or_else(|| entry_label_color(params.selected))
 601        } else {
 602            entry_label_color(params.selected)
 603        };
 604
 605        let description = params.detail.and_then(|detail| {
 606            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 607            let description = path.to_string_lossy();
 608            let description = description.trim();
 609
 610            if description.is_empty() {
 611                return None;
 612            }
 613
 614            Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
 615        });
 616
 617        h_flex()
 618            .gap_2()
 619            .child(
 620                Label::new(self.title(cx).to_string())
 621                    .color(label_color)
 622                    .italic(params.preview),
 623            )
 624            .when_some(description, |this, description| {
 625                this.child(
 626                    Label::new(description)
 627                        .size(LabelSize::XSmall)
 628                        .color(Color::Muted),
 629                )
 630            })
 631            .into_any_element()
 632    }
 633
 634    fn for_each_project_item(
 635        &self,
 636        cx: &AppContext,
 637        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 638    ) {
 639        self.buffer
 640            .read(cx)
 641            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 642    }
 643
 644    fn is_singleton(&self, cx: &AppContext) -> bool {
 645        self.buffer.read(cx).is_singleton()
 646    }
 647
 648    fn clone_on_split(
 649        &self,
 650        _workspace_id: Option<WorkspaceId>,
 651        cx: &mut ViewContext<Self>,
 652    ) -> Option<View<Editor>>
 653    where
 654        Self: Sized,
 655    {
 656        Some(cx.new_view(|cx| self.clone(cx)))
 657    }
 658
 659    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 660        self.nav_history = Some(history);
 661    }
 662
 663    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 664        let selection = self.selections.newest_anchor();
 665        self.push_to_nav_history(selection.head(), None, cx);
 666    }
 667
 668    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 669        self.hide_hovered_link(cx);
 670    }
 671
 672    fn is_dirty(&self, cx: &AppContext) -> bool {
 673        self.buffer().read(cx).read(cx).is_dirty()
 674    }
 675
 676    fn has_conflict(&self, cx: &AppContext) -> bool {
 677        self.buffer().read(cx).read(cx).has_conflict()
 678    }
 679
 680    fn can_save(&self, cx: &AppContext) -> bool {
 681        let buffer = &self.buffer().read(cx);
 682        if let Some(buffer) = buffer.as_singleton() {
 683            buffer.read(cx).project_path(cx).is_some()
 684        } else {
 685            true
 686        }
 687    }
 688
 689    fn save(
 690        &mut self,
 691        format: bool,
 692        project: Model<Project>,
 693        cx: &mut ViewContext<Self>,
 694    ) -> Task<Result<()>> {
 695        self.report_editor_event("save", None, cx);
 696        let buffers = self.buffer().clone().read(cx).all_buffers();
 697        cx.spawn(|this, mut cx| async move {
 698            if format {
 699                this.update(&mut cx, |editor, cx| {
 700                    editor.perform_format(project.clone(), FormatTrigger::Save, cx)
 701                })?
 702                .await?;
 703            }
 704
 705            if buffers.len() == 1 {
 706                // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
 707                project
 708                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 709                    .await?;
 710            } else {
 711                // For multi-buffers, only format and save the buffers with changes.
 712                // For clean buffers, we simulate saving by calling `Buffer::did_save`,
 713                // so that language servers or other downstream listeners of save events get notified.
 714                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 715                    buffer
 716                        .update(&mut cx, |buffer, _| {
 717                            buffer.is_dirty() || buffer.has_conflict()
 718                        })
 719                        .unwrap_or(false)
 720                });
 721
 722                project
 723                    .update(&mut cx, |project, cx| {
 724                        project.save_buffers(dirty_buffers, cx)
 725                    })?
 726                    .await?;
 727                for buffer in clean_buffers {
 728                    buffer
 729                        .update(&mut cx, |buffer, cx| {
 730                            let version = buffer.saved_version().clone();
 731                            let mtime = buffer.saved_mtime();
 732                            buffer.did_save(version, mtime, cx);
 733                        })
 734                        .ok();
 735                }
 736            }
 737
 738            Ok(())
 739        })
 740    }
 741
 742    fn save_as(
 743        &mut self,
 744        project: Model<Project>,
 745        path: ProjectPath,
 746        cx: &mut ViewContext<Self>,
 747    ) -> Task<Result<()>> {
 748        let buffer = self
 749            .buffer()
 750            .read(cx)
 751            .as_singleton()
 752            .expect("cannot call save_as on an excerpt list");
 753
 754        let file_extension = path
 755            .path
 756            .extension()
 757            .map(|a| a.to_string_lossy().to_string());
 758        self.report_editor_event("save", file_extension, cx);
 759
 760        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 761    }
 762
 763    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 764        let buffer = self.buffer().clone();
 765        let buffers = self.buffer.read(cx).all_buffers();
 766        let reload_buffers =
 767            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 768        cx.spawn(|this, mut cx| async move {
 769            let transaction = reload_buffers.log_err().await;
 770            this.update(&mut cx, |editor, cx| {
 771                editor.request_autoscroll(Autoscroll::fit(), cx)
 772            })?;
 773            buffer
 774                .update(&mut cx, |buffer, cx| {
 775                    if let Some(transaction) = transaction {
 776                        if !buffer.is_singleton() {
 777                            buffer.push_transaction(&transaction.0, cx);
 778                        }
 779                    }
 780                })
 781                .ok();
 782            Ok(())
 783        })
 784    }
 785
 786    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 787        Some(Box::new(handle.clone()))
 788    }
 789
 790    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 791        self.pixel_position_of_newest_cursor
 792    }
 793
 794    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 795        if self.show_breadcrumbs {
 796            ToolbarItemLocation::PrimaryLeft
 797        } else {
 798            ToolbarItemLocation::Hidden
 799        }
 800    }
 801
 802    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 803        let cursor = self.selections.newest_anchor().head();
 804        let multibuffer = &self.buffer().read(cx);
 805        let (buffer_id, symbols) =
 806            multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
 807        let buffer = multibuffer.buffer(buffer_id)?;
 808
 809        let buffer = buffer.read(cx);
 810        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 811            buffer
 812                .snapshot()
 813                .resolve_file_path(
 814                    cx,
 815                    self.project
 816                        .as_ref()
 817                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 818                        .unwrap_or_default(),
 819                )
 820                .map(|path| path.to_string_lossy().to_string())
 821                .unwrap_or_else(|| "untitled".to_string())
 822        });
 823
 824        let settings = ThemeSettings::get_global(cx);
 825
 826        let mut breadcrumbs = vec![BreadcrumbText {
 827            text,
 828            highlights: None,
 829            font: Some(settings.buffer_font.clone()),
 830        }];
 831
 832        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 833            text: symbol.text,
 834            highlights: Some(symbol.highlight_ranges),
 835            font: Some(settings.buffer_font.clone()),
 836        }));
 837        Some(breadcrumbs)
 838    }
 839
 840    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 841        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 842        let Some(workspace_id) = workspace.database_id() else {
 843            return;
 844        };
 845
 846        let item_id = cx.view().item_id().as_u64() as ItemId;
 847
 848        fn serialize(
 849            buffer: Model<Buffer>,
 850            workspace_id: WorkspaceId,
 851            item_id: ItemId,
 852            cx: &mut AppContext,
 853        ) {
 854            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 855                let path = file.abs_path(cx);
 856
 857                cx.background_executor()
 858                    .spawn(async move {
 859                        DB.save_path(item_id, workspace_id, path.clone())
 860                            .await
 861                            .log_err()
 862                    })
 863                    .detach();
 864            }
 865        }
 866
 867        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 868            serialize(buffer.clone(), workspace_id, item_id, cx);
 869
 870            cx.subscribe(&buffer, |this, buffer, event, cx| {
 871                if let Some((_, Some(workspace_id))) = this.workspace.as_ref() {
 872                    if let language::Event::FileHandleChanged = event {
 873                        serialize(
 874                            buffer,
 875                            *workspace_id,
 876                            cx.view().item_id().as_u64() as ItemId,
 877                            cx,
 878                        );
 879                    }
 880                }
 881            })
 882            .detach();
 883        }
 884    }
 885
 886    fn serialized_item_kind() -> Option<&'static str> {
 887        Some("Editor")
 888    }
 889
 890    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 891        match event {
 892            EditorEvent::Closed => f(ItemEvent::CloseItem),
 893
 894            EditorEvent::Saved | EditorEvent::TitleChanged => {
 895                f(ItemEvent::UpdateTab);
 896                f(ItemEvent::UpdateBreadcrumbs);
 897            }
 898
 899            EditorEvent::Reparsed(_) => {
 900                f(ItemEvent::UpdateBreadcrumbs);
 901            }
 902
 903            EditorEvent::SelectionsChanged { local } if *local => {
 904                f(ItemEvent::UpdateBreadcrumbs);
 905            }
 906
 907            EditorEvent::DirtyChanged => {
 908                f(ItemEvent::UpdateTab);
 909            }
 910
 911            EditorEvent::BufferEdited => {
 912                f(ItemEvent::Edit);
 913                f(ItemEvent::UpdateBreadcrumbs);
 914            }
 915
 916            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 917                f(ItemEvent::Edit);
 918            }
 919
 920            _ => {}
 921        }
 922    }
 923
 924    fn deserialize(
 925        project: Model<Project>,
 926        _workspace: WeakView<Workspace>,
 927        workspace_id: workspace::WorkspaceId,
 928        item_id: ItemId,
 929        cx: &mut ViewContext<Pane>,
 930    ) -> Task<Result<View<Self>>> {
 931        let project_item: Result<_> = project.update(cx, |project, cx| {
 932            // Look up the path with this key associated, create a self with that path
 933            let path = DB
 934                .get_path(item_id, workspace_id)?
 935                .context("No path stored for this editor")?;
 936
 937            let (worktree, path) = project
 938                .find_worktree(&path, cx)
 939                .with_context(|| format!("No worktree for path: {path:?}"))?;
 940            let project_path = ProjectPath {
 941                worktree_id: worktree.read(cx).id(),
 942                path: path.into(),
 943            };
 944
 945            Ok(project.open_path(project_path, cx))
 946        });
 947
 948        project_item
 949            .map(|project_item| {
 950                cx.spawn(|pane, mut cx| async move {
 951                    let (_, project_item) = project_item.await?;
 952                    let buffer = project_item
 953                        .downcast::<Buffer>()
 954                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 955                    pane.update(&mut cx, |_, cx| {
 956                        cx.new_view(|cx| {
 957                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 958
 959                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 960                            editor
 961                        })
 962                    })
 963                })
 964            })
 965            .unwrap_or_else(|error| Task::ready(Err(error)))
 966    }
 967}
 968
 969impl ProjectItem for Editor {
 970    type Item = Buffer;
 971
 972    fn for_project_item(
 973        project: Model<Project>,
 974        buffer: Model<Buffer>,
 975        cx: &mut ViewContext<Self>,
 976    ) -> Self {
 977        Self::for_buffer(buffer, Some(project), cx)
 978    }
 979}
 980
 981impl EventEmitter<SearchEvent> for Editor {}
 982
 983pub(crate) enum BufferSearchHighlights {}
 984impl SearchableItem for Editor {
 985    type Match = Range<Anchor>;
 986
 987    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 988        self.clear_background_highlights::<BufferSearchHighlights>(cx);
 989    }
 990
 991    fn update_matches(&mut self, matches: &[Range<Anchor>], cx: &mut ViewContext<Self>) {
 992        self.highlight_background::<BufferSearchHighlights>(
 993            matches,
 994            |theme| theme.search_match_background,
 995            cx,
 996        );
 997    }
 998
 999    fn has_filtered_search_ranges(&mut self) -> bool {
1000        self.has_background_highlights::<SearchWithinRange>()
1001    }
1002
1003    fn toggle_filtered_search_ranges(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1004        if self.has_filtered_search_ranges() {
1005            self.previous_search_ranges = self
1006                .clear_background_highlights::<SearchWithinRange>(cx)
1007                .map(|(_, ranges)| ranges)
1008        }
1009
1010        if !enabled {
1011            return;
1012        }
1013
1014        let ranges = self.selections.disjoint_anchor_ranges();
1015        if ranges.iter().any(|range| range.start != range.end) {
1016            self.set_search_within_ranges(&ranges, cx);
1017        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1018            self.set_search_within_ranges(&previous_search_ranges, cx)
1019        }
1020    }
1021
1022    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1023        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1024        let snapshot = &self.snapshot(cx).buffer_snapshot;
1025        let selection = self.selections.newest::<usize>(cx);
1026
1027        match setting {
1028            SeedQuerySetting::Never => String::new(),
1029            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1030                let text: String = snapshot
1031                    .text_for_range(selection.start..selection.end)
1032                    .collect();
1033                if text.contains('\n') {
1034                    String::new()
1035                } else {
1036                    text
1037                }
1038            }
1039            SeedQuerySetting::Selection => String::new(),
1040            SeedQuerySetting::Always => {
1041                let (range, kind) = snapshot.surrounding_word(selection.start);
1042                if kind == Some(CharKind::Word) {
1043                    let text: String = snapshot.text_for_range(range).collect();
1044                    if !text.trim().is_empty() {
1045                        return text;
1046                    }
1047                }
1048                String::new()
1049            }
1050        }
1051    }
1052
1053    fn activate_match(
1054        &mut self,
1055        index: usize,
1056        matches: &[Range<Anchor>],
1057        cx: &mut ViewContext<Self>,
1058    ) {
1059        self.unfold_ranges([matches[index].clone()], false, true, cx);
1060        let range = self.range_for_match(&matches[index]);
1061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1062            s.select_ranges([range]);
1063        })
1064    }
1065
1066    fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1067        self.unfold_ranges(matches.to_vec(), false, false, cx);
1068        let mut ranges = Vec::new();
1069        for m in matches {
1070            ranges.push(self.range_for_match(&m))
1071        }
1072        self.change_selections(None, cx, |s| s.select_ranges(ranges));
1073    }
1074    fn replace(
1075        &mut self,
1076        identifier: &Self::Match,
1077        query: &SearchQuery,
1078        cx: &mut ViewContext<Self>,
1079    ) {
1080        let text = self.buffer.read(cx);
1081        let text = text.snapshot(cx);
1082        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1083        let text: Cow<_> = if text.len() == 1 {
1084            text.first().cloned().unwrap().into()
1085        } else {
1086            let joined_chunks = text.join("");
1087            joined_chunks.into()
1088        };
1089
1090        if let Some(replacement) = query.replacement_for(&text) {
1091            self.transact(cx, |this, cx| {
1092                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1093            });
1094        }
1095    }
1096    fn replace_all(
1097        &mut self,
1098        matches: &mut dyn Iterator<Item = &Self::Match>,
1099        query: &SearchQuery,
1100        cx: &mut ViewContext<Self>,
1101    ) {
1102        let text = self.buffer.read(cx);
1103        let text = text.snapshot(cx);
1104        let mut edits = vec![];
1105        for m in matches {
1106            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1107            let text: Cow<_> = if text.len() == 1 {
1108                text.first().cloned().unwrap().into()
1109            } else {
1110                let joined_chunks = text.join("");
1111                joined_chunks.into()
1112            };
1113
1114            if let Some(replacement) = query.replacement_for(&text) {
1115                edits.push((m.clone(), Arc::from(&*replacement)));
1116            }
1117        }
1118
1119        if !edits.is_empty() {
1120            self.transact(cx, |this, cx| {
1121                this.edit(edits, cx);
1122            });
1123        }
1124    }
1125    fn match_index_for_direction(
1126        &mut self,
1127        matches: &[Range<Anchor>],
1128        current_index: usize,
1129        direction: Direction,
1130        count: usize,
1131        cx: &mut ViewContext<Self>,
1132    ) -> usize {
1133        let buffer = self.buffer().read(cx).snapshot(cx);
1134        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1135            self.selections.newest_anchor().head()
1136        } else {
1137            matches[current_index].start
1138        };
1139
1140        let mut count = count % matches.len();
1141        if count == 0 {
1142            return current_index;
1143        }
1144        match direction {
1145            Direction::Next => {
1146                if matches[current_index]
1147                    .start
1148                    .cmp(&current_index_position, &buffer)
1149                    .is_gt()
1150                {
1151                    count = count - 1
1152                }
1153
1154                (current_index + count) % matches.len()
1155            }
1156            Direction::Prev => {
1157                if matches[current_index]
1158                    .end
1159                    .cmp(&current_index_position, &buffer)
1160                    .is_lt()
1161                {
1162                    count = count - 1;
1163                }
1164
1165                if current_index >= count {
1166                    current_index - count
1167                } else {
1168                    matches.len() - (count - current_index)
1169                }
1170            }
1171        }
1172    }
1173
1174    fn find_matches(
1175        &mut self,
1176        query: Arc<project::search::SearchQuery>,
1177        cx: &mut ViewContext<Self>,
1178    ) -> Task<Vec<Range<Anchor>>> {
1179        let buffer = self.buffer().read(cx).snapshot(cx);
1180        let search_within_ranges = self
1181            .background_highlights
1182            .get(&TypeId::of::<SearchWithinRange>())
1183            .map_or(vec![], |(_color, ranges)| {
1184                ranges.iter().map(|range| range.clone()).collect::<Vec<_>>()
1185            });
1186
1187        cx.background_executor().spawn(async move {
1188            let mut ranges = Vec::new();
1189
1190            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1191                let search_within_ranges = if search_within_ranges.is_empty() {
1192                    vec![None]
1193                } else {
1194                    search_within_ranges
1195                        .into_iter()
1196                        .map(|range| Some(range.to_offset(&buffer)))
1197                        .collect::<Vec<_>>()
1198                };
1199
1200                for range in search_within_ranges {
1201                    let buffer = &buffer;
1202                    ranges.extend(
1203                        query
1204                            .search(excerpt_buffer, range.clone())
1205                            .await
1206                            .into_iter()
1207                            .map(|matched_range| {
1208                                let offset = range.clone().map(|r| r.start).unwrap_or(0);
1209                                buffer.anchor_after(matched_range.start + offset)
1210                                    ..buffer.anchor_before(matched_range.end + offset)
1211                            }),
1212                    );
1213                }
1214            } else {
1215                let search_within_ranges = if search_within_ranges.is_empty() {
1216                    vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1217                } else {
1218                    search_within_ranges
1219                };
1220
1221                for (excerpt_id, search_buffer, search_range) in
1222                    buffer.excerpts_in_ranges(search_within_ranges)
1223                {
1224                    if !search_range.is_empty() {
1225                        ranges.extend(
1226                            query
1227                                .search(&search_buffer, Some(search_range.clone()))
1228                                .await
1229                                .into_iter()
1230                                .map(|match_range| {
1231                                    let start = search_buffer
1232                                        .anchor_after(search_range.start + match_range.start);
1233                                    let end = search_buffer
1234                                        .anchor_before(search_range.start + match_range.end);
1235                                    buffer.anchor_in_excerpt(excerpt_id, start).unwrap()
1236                                        ..buffer.anchor_in_excerpt(excerpt_id, end).unwrap()
1237                                }),
1238                        );
1239                    }
1240                }
1241            };
1242
1243            ranges
1244        })
1245    }
1246
1247    fn active_match_index(
1248        &mut self,
1249        matches: &[Range<Anchor>],
1250        cx: &mut ViewContext<Self>,
1251    ) -> Option<usize> {
1252        active_match_index(
1253            matches,
1254            &self.selections.newest_anchor().head(),
1255            &self.buffer().read(cx).snapshot(cx),
1256        )
1257    }
1258
1259    fn search_bar_visibility_changed(&mut self, _visible: bool, _cx: &mut ViewContext<Self>) {
1260        self.expect_bounds_change = self.last_bounds;
1261    }
1262}
1263
1264pub fn active_match_index(
1265    ranges: &[Range<Anchor>],
1266    cursor: &Anchor,
1267    buffer: &MultiBufferSnapshot,
1268) -> Option<usize> {
1269    if ranges.is_empty() {
1270        None
1271    } else {
1272        match ranges.binary_search_by(|probe| {
1273            if probe.end.cmp(cursor, buffer).is_lt() {
1274                Ordering::Less
1275            } else if probe.start.cmp(cursor, buffer).is_gt() {
1276                Ordering::Greater
1277            } else {
1278                Ordering::Equal
1279            }
1280        }) {
1281            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1282        }
1283    }
1284}
1285
1286pub fn entry_label_color(selected: bool) -> Color {
1287    if selected {
1288        Color::Default
1289    } else {
1290        Color::Muted
1291    }
1292}
1293
1294pub fn entry_git_aware_label_color(
1295    git_status: Option<GitFileStatus>,
1296    ignored: bool,
1297    selected: bool,
1298) -> Color {
1299    if ignored {
1300        Color::Ignored
1301    } else {
1302        match git_status {
1303            Some(GitFileStatus::Added) => Color::Created,
1304            Some(GitFileStatus::Modified) => Color::Modified,
1305            Some(GitFileStatus::Conflict) => Color::Conflict,
1306            None => entry_label_color(selected),
1307        }
1308    }
1309}
1310
1311fn path_for_buffer<'a>(
1312    buffer: &Model<MultiBuffer>,
1313    height: usize,
1314    include_filename: bool,
1315    cx: &'a AppContext,
1316) -> Option<Cow<'a, Path>> {
1317    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1318    path_for_file(file.as_ref(), height, include_filename, cx)
1319}
1320
1321fn path_for_file<'a>(
1322    file: &'a dyn language::File,
1323    mut height: usize,
1324    include_filename: bool,
1325    cx: &'a AppContext,
1326) -> Option<Cow<'a, Path>> {
1327    // Ensure we always render at least the filename.
1328    height += 1;
1329
1330    let mut prefix = file.path().as_ref();
1331    while height > 0 {
1332        if let Some(parent) = prefix.parent() {
1333            prefix = parent;
1334            height -= 1;
1335        } else {
1336            break;
1337        }
1338    }
1339
1340    // Here we could have just always used `full_path`, but that is very
1341    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1342    // traversed all the way up to the worktree's root.
1343    if height > 0 {
1344        let full_path = file.full_path(cx);
1345        if include_filename {
1346            Some(full_path.into())
1347        } else {
1348            Some(full_path.parent()?.to_path_buf().into())
1349        }
1350    } else {
1351        let mut path = file.path().strip_prefix(prefix).ok()?;
1352        if !include_filename {
1353            path = path.parent()?;
1354        }
1355        Some(path.into())
1356    }
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361    use super::*;
1362    use gpui::AppContext;
1363    use language::TestFile;
1364    use std::path::Path;
1365
1366    #[gpui::test]
1367    fn test_path_for_file(cx: &mut AppContext) {
1368        let file = TestFile {
1369            path: Path::new("").into(),
1370            root_name: String::new(),
1371        };
1372        assert_eq!(path_for_file(&file, 0, false, cx), None);
1373    }
1374}