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