items.rs

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