items.rs

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