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>, 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()))
 601            .when_some(description, |this, description| {
 602                this.child(Label::new(description).color(Color::Muted))
 603            })
 604            .into_any_element()
 605    }
 606
 607    fn for_each_project_item(
 608        &self,
 609        cx: &AppContext,
 610        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 611    ) {
 612        self.buffer
 613            .read(cx)
 614            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 615    }
 616
 617    fn is_singleton(&self, cx: &AppContext) -> bool {
 618        self.buffer.read(cx).is_singleton()
 619    }
 620
 621    fn clone_on_split(
 622        &self,
 623        _workspace_id: WorkspaceId,
 624        cx: &mut ViewContext<Self>,
 625    ) -> Option<View<Editor>>
 626    where
 627        Self: Sized,
 628    {
 629        Some(cx.build_view(|cx| self.clone(cx)))
 630    }
 631
 632    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 633        self.nav_history = Some(history);
 634    }
 635
 636    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 637        let selection = self.selections.newest_anchor();
 638        self.push_to_nav_history(selection.head(), None, cx);
 639    }
 640
 641    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 642        hide_link_definition(self, cx);
 643        self.link_go_to_definition_state.last_trigger_point = None;
 644    }
 645
 646    fn is_dirty(&self, cx: &AppContext) -> bool {
 647        self.buffer().read(cx).read(cx).is_dirty()
 648    }
 649
 650    fn has_conflict(&self, cx: &AppContext) -> bool {
 651        self.buffer().read(cx).read(cx).has_conflict()
 652    }
 653
 654    fn can_save(&self, cx: &AppContext) -> bool {
 655        let buffer = &self.buffer().read(cx);
 656        if let Some(buffer) = buffer.as_singleton() {
 657            buffer.read(cx).project_path(cx).is_some()
 658        } else {
 659            true
 660        }
 661    }
 662
 663    fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 664        self.report_editor_event("save", None, cx);
 665        let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
 666        let buffers = self.buffer().clone().read(cx).all_buffers();
 667        cx.spawn(|_, mut cx| async move {
 668            format.await?;
 669
 670            if buffers.len() == 1 {
 671                project
 672                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 673                    .await?;
 674            } else {
 675                // For multi-buffers, only save those ones that contain changes. For clean buffers
 676                // we simulate saving by calling `Buffer::did_save`, so that language servers or
 677                // other downstream listeners of save events get notified.
 678                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 679                    buffer
 680                        .update(&mut cx, |buffer, _| {
 681                            buffer.is_dirty() || buffer.has_conflict()
 682                        })
 683                        .unwrap_or(false)
 684                });
 685
 686                project
 687                    .update(&mut cx, |project, cx| {
 688                        project.save_buffers(dirty_buffers, cx)
 689                    })?
 690                    .await?;
 691                for buffer in clean_buffers {
 692                    buffer.update(&mut cx, |buffer, cx| {
 693                        let version = buffer.saved_version().clone();
 694                        let fingerprint = buffer.saved_version_fingerprint();
 695                        let mtime = buffer.saved_mtime();
 696                        buffer.did_save(version, fingerprint, mtime, cx);
 697                    });
 698                }
 699            }
 700
 701            Ok(())
 702        })
 703    }
 704
 705    fn save_as(
 706        &mut self,
 707        project: Model<Project>,
 708        abs_path: PathBuf,
 709        cx: &mut ViewContext<Self>,
 710    ) -> Task<Result<()>> {
 711        let buffer = self
 712            .buffer()
 713            .read(cx)
 714            .as_singleton()
 715            .expect("cannot call save_as on an excerpt list");
 716
 717        let file_extension = abs_path
 718            .extension()
 719            .map(|a| a.to_string_lossy().to_string());
 720        self.report_editor_event("save", file_extension, cx);
 721
 722        project.update(cx, |project, cx| {
 723            project.save_buffer_as(buffer, abs_path, cx)
 724        })
 725    }
 726
 727    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 728        let buffer = self.buffer().clone();
 729        let buffers = self.buffer.read(cx).all_buffers();
 730        let reload_buffers =
 731            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 732        cx.spawn(|this, mut cx| async move {
 733            let transaction = reload_buffers.log_err().await;
 734            this.update(&mut cx, |editor, cx| {
 735                editor.request_autoscroll(Autoscroll::fit(), cx)
 736            })?;
 737            buffer.update(&mut cx, |buffer, cx| {
 738                if let Some(transaction) = transaction {
 739                    if !buffer.is_singleton() {
 740                        buffer.push_transaction(&transaction.0, cx);
 741                    }
 742                }
 743            });
 744            Ok(())
 745        })
 746    }
 747
 748    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 749        Some(Box::new(handle.clone()))
 750    }
 751
 752    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 753        self.pixel_position_of_newest_cursor
 754    }
 755
 756    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 757        ToolbarItemLocation::PrimaryLeft
 758    }
 759
 760    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 761        let cursor = self.selections.newest_anchor().head();
 762        let multibuffer = &self.buffer().read(cx);
 763        let (buffer_id, symbols) =
 764            multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
 765        let buffer = multibuffer.buffer(buffer_id)?;
 766
 767        let buffer = buffer.read(cx);
 768        let filename = buffer
 769            .snapshot()
 770            .resolve_file_path(
 771                cx,
 772                self.project
 773                    .as_ref()
 774                    .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 775                    .unwrap_or_default(),
 776            )
 777            .map(|path| path.to_string_lossy().to_string())
 778            .unwrap_or_else(|| "untitled".to_string());
 779
 780        let mut breadcrumbs = vec![BreadcrumbText {
 781            text: filename,
 782            highlights: None,
 783        }];
 784        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 785            text: symbol.text,
 786            highlights: Some(symbol.highlight_ranges),
 787        }));
 788        Some(breadcrumbs)
 789    }
 790
 791    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 792        let workspace_id = workspace.database_id();
 793        let item_id = cx.view().item_id().as_u64() as ItemId;
 794        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 795
 796        fn serialize(
 797            buffer: Model<Buffer>,
 798            workspace_id: WorkspaceId,
 799            item_id: ItemId,
 800            cx: &mut AppContext,
 801        ) {
 802            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 803                let path = file.abs_path(cx);
 804
 805                cx.background_executor()
 806                    .spawn(async move {
 807                        DB.save_path(item_id, workspace_id, path.clone())
 808                            .await
 809                            .log_err()
 810                    })
 811                    .detach();
 812            }
 813        }
 814
 815        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 816            serialize(buffer.clone(), workspace_id, item_id, cx);
 817
 818            cx.subscribe(&buffer, |this, buffer, event, cx| {
 819                if let Some((_, workspace_id)) = this.workspace.as_ref() {
 820                    if let language::Event::FileHandleChanged = event {
 821                        serialize(
 822                            buffer,
 823                            *workspace_id,
 824                            cx.view().item_id().as_u64() as ItemId,
 825                            cx,
 826                        );
 827                    }
 828                }
 829            })
 830            .detach();
 831        }
 832    }
 833
 834    fn serialized_item_kind() -> Option<&'static str> {
 835        Some("Editor")
 836    }
 837
 838    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 839        match event {
 840            EditorEvent::Closed => f(ItemEvent::CloseItem),
 841
 842            EditorEvent::Saved | EditorEvent::TitleChanged => {
 843                f(ItemEvent::UpdateTab);
 844                f(ItemEvent::UpdateBreadcrumbs);
 845            }
 846
 847            EditorEvent::Reparsed => {
 848                f(ItemEvent::UpdateBreadcrumbs);
 849            }
 850
 851            EditorEvent::SelectionsChanged { local } if *local => {
 852                f(ItemEvent::UpdateBreadcrumbs);
 853            }
 854
 855            EditorEvent::DirtyChanged => {
 856                f(ItemEvent::UpdateTab);
 857            }
 858
 859            EditorEvent::BufferEdited => {
 860                f(ItemEvent::Edit);
 861                f(ItemEvent::UpdateBreadcrumbs);
 862            }
 863
 864            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 865                f(ItemEvent::Edit);
 866            }
 867
 868            _ => {}
 869        }
 870    }
 871
 872    fn deserialize(
 873        project: Model<Project>,
 874        _workspace: WeakView<Workspace>,
 875        workspace_id: workspace::WorkspaceId,
 876        item_id: ItemId,
 877        cx: &mut ViewContext<Pane>,
 878    ) -> Task<Result<View<Self>>> {
 879        let project_item: Result<_> = project.update(cx, |project, cx| {
 880            // Look up the path with this key associated, create a self with that path
 881            let path = DB
 882                .get_path(item_id, workspace_id)?
 883                .context("No path stored for this editor")?;
 884
 885            let (worktree, path) = project
 886                .find_local_worktree(&path, cx)
 887                .with_context(|| format!("No worktree for path: {path:?}"))?;
 888            let project_path = ProjectPath {
 889                worktree_id: worktree.read(cx).id(),
 890                path: path.into(),
 891            };
 892
 893            Ok(project.open_path(project_path, cx))
 894        });
 895
 896        project_item
 897            .map(|project_item| {
 898                cx.spawn(|pane, mut cx| async move {
 899                    let (_, project_item) = project_item.await?;
 900                    let buffer = project_item
 901                        .downcast::<Buffer>()
 902                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 903                    Ok(pane.update(&mut cx, |_, cx| {
 904                        cx.build_view(|cx| {
 905                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 906
 907                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 908                            editor
 909                        })
 910                    })?)
 911                })
 912            })
 913            .unwrap_or_else(|error| Task::ready(Err(error)))
 914    }
 915}
 916
 917impl ProjectItem for Editor {
 918    type Item = Buffer;
 919
 920    fn for_project_item(
 921        project: Model<Project>,
 922        buffer: Model<Buffer>,
 923        cx: &mut ViewContext<Self>,
 924    ) -> Self {
 925        Self::for_buffer(buffer, Some(project), cx)
 926    }
 927}
 928
 929impl EventEmitter<SearchEvent> for Editor {}
 930
 931pub(crate) enum BufferSearchHighlights {}
 932impl SearchableItem for Editor {
 933    type Match = Range<Anchor>;
 934
 935    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 936        self.clear_background_highlights::<BufferSearchHighlights>(cx);
 937    }
 938
 939    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
 940        self.highlight_background::<BufferSearchHighlights>(
 941            matches,
 942            |theme| theme.search_match_background,
 943            cx,
 944        );
 945    }
 946
 947    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 948        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
 949        let snapshot = &self.snapshot(cx).buffer_snapshot;
 950        let selection = self.selections.newest::<usize>(cx);
 951
 952        match setting {
 953            SeedQuerySetting::Never => String::new(),
 954            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
 955                snapshot
 956                    .text_for_range(selection.start..selection.end)
 957                    .collect()
 958            }
 959            SeedQuerySetting::Selection => String::new(),
 960            SeedQuerySetting::Always => {
 961                let (range, kind) = snapshot.surrounding_word(selection.start);
 962                if kind == Some(CharKind::Word) {
 963                    let text: String = snapshot.text_for_range(range).collect();
 964                    if !text.trim().is_empty() {
 965                        return text;
 966                    }
 967                }
 968                String::new()
 969            }
 970        }
 971    }
 972
 973    fn activate_match(
 974        &mut self,
 975        index: usize,
 976        matches: Vec<Range<Anchor>>,
 977        cx: &mut ViewContext<Self>,
 978    ) {
 979        self.unfold_ranges([matches[index].clone()], false, true, cx);
 980        let range = self.range_for_match(&matches[index]);
 981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 982            s.select_ranges([range]);
 983        })
 984    }
 985
 986    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
 987        self.unfold_ranges(matches.clone(), false, false, cx);
 988        let mut ranges = Vec::new();
 989        for m in &matches {
 990            ranges.push(self.range_for_match(&m))
 991        }
 992        self.change_selections(None, cx, |s| s.select_ranges(ranges));
 993    }
 994    fn replace(
 995        &mut self,
 996        identifier: &Self::Match,
 997        query: &SearchQuery,
 998        cx: &mut ViewContext<Self>,
 999    ) {
1000        let text = self.buffer.read(cx);
1001        let text = text.snapshot(cx);
1002        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1003        let text: Cow<_> = if text.len() == 1 {
1004            text.first().cloned().unwrap().into()
1005        } else {
1006            let joined_chunks = text.join("");
1007            joined_chunks.into()
1008        };
1009
1010        if let Some(replacement) = query.replacement_for(&text) {
1011            self.transact(cx, |this, cx| {
1012                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1013            });
1014        }
1015    }
1016    fn match_index_for_direction(
1017        &mut self,
1018        matches: &Vec<Range<Anchor>>,
1019        current_index: usize,
1020        direction: Direction,
1021        count: usize,
1022        cx: &mut ViewContext<Self>,
1023    ) -> usize {
1024        let buffer = self.buffer().read(cx).snapshot(cx);
1025        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1026            self.selections.newest_anchor().head()
1027        } else {
1028            matches[current_index].start
1029        };
1030
1031        let mut count = count % matches.len();
1032        if count == 0 {
1033            return current_index;
1034        }
1035        match direction {
1036            Direction::Next => {
1037                if matches[current_index]
1038                    .start
1039                    .cmp(&current_index_position, &buffer)
1040                    .is_gt()
1041                {
1042                    count = count - 1
1043                }
1044
1045                (current_index + count) % matches.len()
1046            }
1047            Direction::Prev => {
1048                if matches[current_index]
1049                    .end
1050                    .cmp(&current_index_position, &buffer)
1051                    .is_lt()
1052                {
1053                    count = count - 1;
1054                }
1055
1056                if current_index >= count {
1057                    current_index - count
1058                } else {
1059                    matches.len() - (count - current_index)
1060                }
1061            }
1062        }
1063    }
1064
1065    fn find_matches(
1066        &mut self,
1067        query: Arc<project::search::SearchQuery>,
1068        cx: &mut ViewContext<Self>,
1069    ) -> Task<Vec<Range<Anchor>>> {
1070        let buffer = self.buffer().read(cx).snapshot(cx);
1071        cx.background_executor().spawn(async move {
1072            let mut ranges = Vec::new();
1073            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1074                ranges.extend(
1075                    query
1076                        .search(excerpt_buffer, None)
1077                        .await
1078                        .into_iter()
1079                        .map(|range| {
1080                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1081                        }),
1082                );
1083            } else {
1084                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1085                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1086                    ranges.extend(
1087                        query
1088                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1089                            .await
1090                            .into_iter()
1091                            .map(|range| {
1092                                let start = excerpt
1093                                    .buffer
1094                                    .anchor_after(excerpt_range.start + range.start);
1095                                let end = excerpt
1096                                    .buffer
1097                                    .anchor_before(excerpt_range.start + range.end);
1098                                buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1099                                    ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1100                            }),
1101                    );
1102                }
1103            }
1104            ranges
1105        })
1106    }
1107
1108    fn active_match_index(
1109        &mut self,
1110        matches: Vec<Range<Anchor>>,
1111        cx: &mut ViewContext<Self>,
1112    ) -> Option<usize> {
1113        active_match_index(
1114            &matches,
1115            &self.selections.newest_anchor().head(),
1116            &self.buffer().read(cx).snapshot(cx),
1117        )
1118    }
1119}
1120
1121pub fn active_match_index(
1122    ranges: &[Range<Anchor>],
1123    cursor: &Anchor,
1124    buffer: &MultiBufferSnapshot,
1125) -> Option<usize> {
1126    if ranges.is_empty() {
1127        None
1128    } else {
1129        match ranges.binary_search_by(|probe| {
1130            if probe.end.cmp(cursor, &*buffer).is_lt() {
1131                Ordering::Less
1132            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1133                Ordering::Greater
1134            } else {
1135                Ordering::Equal
1136            }
1137        }) {
1138            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1139        }
1140    }
1141}
1142
1143pub struct CursorPosition {
1144    position: Option<Point>,
1145    selected_count: usize,
1146    _observe_active_editor: Option<Subscription>,
1147}
1148
1149impl Default for CursorPosition {
1150    fn default() -> Self {
1151        Self::new()
1152    }
1153}
1154
1155impl CursorPosition {
1156    pub fn new() -> Self {
1157        Self {
1158            position: None,
1159            selected_count: 0,
1160            _observe_active_editor: None,
1161        }
1162    }
1163
1164    fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1165        let editor = editor.read(cx);
1166        let buffer = editor.buffer().read(cx).snapshot(cx);
1167
1168        self.selected_count = 0;
1169        let mut last_selection: Option<Selection<usize>> = None;
1170        for selection in editor.selections.all::<usize>(cx) {
1171            self.selected_count += selection.end - selection.start;
1172            if last_selection
1173                .as_ref()
1174                .map_or(true, |last_selection| selection.id > last_selection.id)
1175            {
1176                last_selection = Some(selection);
1177            }
1178        }
1179        self.position = last_selection.map(|s| s.head().to_point(&buffer));
1180
1181        cx.notify();
1182    }
1183}
1184
1185impl Render for CursorPosition {
1186    type Element = Div;
1187
1188    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1189        div().when_some(self.position, |el, position| {
1190            let mut text = format!(
1191                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1192                position.row + 1,
1193                position.column + 1
1194            );
1195            if self.selected_count > 0 {
1196                write!(text, " ({} selected)", self.selected_count).unwrap();
1197            }
1198
1199            el.child(Label::new(text))
1200        })
1201    }
1202}
1203
1204impl StatusItemView for CursorPosition {
1205    fn set_active_pane_item(
1206        &mut self,
1207        active_pane_item: Option<&dyn ItemHandle>,
1208        cx: &mut ViewContext<Self>,
1209    ) {
1210        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1211            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1212            self.update_position(editor, cx);
1213        } else {
1214            self.position = None;
1215            self._observe_active_editor = None;
1216        }
1217
1218        cx.notify();
1219    }
1220}
1221
1222fn path_for_buffer<'a>(
1223    buffer: &Model<MultiBuffer>,
1224    height: usize,
1225    include_filename: bool,
1226    cx: &'a AppContext,
1227) -> Option<Cow<'a, Path>> {
1228    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1229    path_for_file(file.as_ref(), height, include_filename, cx)
1230}
1231
1232fn path_for_file<'a>(
1233    file: &'a dyn language::File,
1234    mut height: usize,
1235    include_filename: bool,
1236    cx: &'a AppContext,
1237) -> Option<Cow<'a, Path>> {
1238    // Ensure we always render at least the filename.
1239    height += 1;
1240
1241    let mut prefix = file.path().as_ref();
1242    while height > 0 {
1243        if let Some(parent) = prefix.parent() {
1244            prefix = parent;
1245            height -= 1;
1246        } else {
1247            break;
1248        }
1249    }
1250
1251    // Here we could have just always used `full_path`, but that is very
1252    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1253    // traversed all the way up to the worktree's root.
1254    if height > 0 {
1255        let full_path = file.full_path(cx);
1256        if include_filename {
1257            Some(full_path.into())
1258        } else {
1259            Some(full_path.parent()?.to_path_buf().into())
1260        }
1261    } else {
1262        let mut path = file.path().strip_prefix(prefix).ok()?;
1263        if !include_filename {
1264            path = path.parent()?;
1265        }
1266        Some(path.into())
1267    }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use super::*;
1273    use gpui::AppContext;
1274    use std::{
1275        path::{Path, PathBuf},
1276        sync::Arc,
1277        time::SystemTime,
1278    };
1279
1280    #[gpui::test]
1281    fn test_path_for_file(cx: &mut AppContext) {
1282        let file = TestFile {
1283            path: Path::new("").into(),
1284            full_path: PathBuf::from(""),
1285        };
1286        assert_eq!(path_for_file(&file, 0, false, cx), None);
1287    }
1288
1289    struct TestFile {
1290        path: Arc<Path>,
1291        full_path: PathBuf,
1292    }
1293
1294    impl language::File for TestFile {
1295        fn path(&self) -> &Arc<Path> {
1296            &self.path
1297        }
1298
1299        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1300            self.full_path.clone()
1301        }
1302
1303        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1304            unimplemented!()
1305        }
1306
1307        fn mtime(&self) -> SystemTime {
1308            unimplemented!()
1309        }
1310
1311        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1312            unimplemented!()
1313        }
1314
1315        fn worktree_id(&self) -> usize {
1316            0
1317        }
1318
1319        fn is_deleted(&self) -> bool {
1320            unimplemented!()
1321        }
1322
1323        fn as_any(&self) -> &dyn std::any::Any {
1324            unimplemented!()
1325        }
1326
1327        fn to_proto(&self) -> rpc::proto::File {
1328            unimplemented!()
1329        }
1330    }
1331}