items.rs

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