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, PeerId};
  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_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 160        self.leader_peer_id = leader_peer_id;
 161        if self.leader_peer_id.is_some() {
 162            self.buffer.update(cx, |buffer, cx| {
 163                buffer.remove_active_selections(cx);
 164            });
 165        } else {
 166            self.buffer.update(cx, |buffer, cx| {
 167                if self.focused {
 168                    buffer.set_active_selections(
 169                        &self.selections.disjoint_anchors(),
 170                        self.selections.line_mode,
 171                        self.cursor_shape,
 172                        cx,
 173                    );
 174                }
 175            });
 176        }
 177        cx.notify();
 178    }
 179
 180    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 181        let buffer = self.buffer.read(cx);
 182        let scroll_anchor = self.scroll_manager.anchor();
 183        let excerpts = buffer
 184            .read(cx)
 185            .excerpts()
 186            .map(|(id, buffer, range)| proto::Excerpt {
 187                id: id.to_proto(),
 188                buffer_id: buffer.remote_id(),
 189                context_start: Some(serialize_text_anchor(&range.context.start)),
 190                context_end: Some(serialize_text_anchor(&range.context.end)),
 191                primary_start: range
 192                    .primary
 193                    .as_ref()
 194                    .map(|range| serialize_text_anchor(&range.start)),
 195                primary_end: range
 196                    .primary
 197                    .as_ref()
 198                    .map(|range| serialize_text_anchor(&range.end)),
 199            })
 200            .collect();
 201
 202        Some(proto::view::Variant::Editor(proto::view::Editor {
 203            singleton: buffer.is_singleton(),
 204            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 205            excerpts,
 206            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 207            scroll_x: scroll_anchor.offset.x(),
 208            scroll_y: scroll_anchor.offset.y(),
 209            selections: self
 210                .selections
 211                .disjoint_anchors()
 212                .iter()
 213                .map(serialize_selection)
 214                .collect(),
 215            pending_selection: self
 216                .selections
 217                .pending_anchor()
 218                .as_ref()
 219                .map(serialize_selection),
 220        }))
 221    }
 222
 223    fn add_event_to_update_proto(
 224        &self,
 225        event: &Self::Event,
 226        update: &mut Option<proto::update_view::Variant>,
 227        cx: &AppContext,
 228    ) -> bool {
 229        let update =
 230            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 231
 232        match update {
 233            proto::update_view::Variant::Editor(update) => match event {
 234                Event::ExcerptsAdded {
 235                    buffer,
 236                    predecessor,
 237                    excerpts,
 238                } => {
 239                    let buffer_id = buffer.read(cx).remote_id();
 240                    let mut excerpts = excerpts.iter();
 241                    if let Some((id, range)) = excerpts.next() {
 242                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 243                            previous_excerpt_id: Some(predecessor.to_proto()),
 244                            excerpt: serialize_excerpt(buffer_id, id, range),
 245                        });
 246                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 247                            proto::ExcerptInsertion {
 248                                previous_excerpt_id: None,
 249                                excerpt: serialize_excerpt(buffer_id, id, range),
 250                            }
 251                        }))
 252                    }
 253                    true
 254                }
 255                Event::ExcerptsRemoved { ids } => {
 256                    update
 257                        .deleted_excerpts
 258                        .extend(ids.iter().map(ExcerptId::to_proto));
 259                    true
 260                }
 261                Event::ScrollPositionChanged { .. } => {
 262                    let scroll_anchor = self.scroll_manager.anchor();
 263                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 264                    update.scroll_x = scroll_anchor.offset.x();
 265                    update.scroll_y = scroll_anchor.offset.y();
 266                    true
 267                }
 268                Event::SelectionsChanged { .. } => {
 269                    update.selections = self
 270                        .selections
 271                        .disjoint_anchors()
 272                        .iter()
 273                        .map(serialize_selection)
 274                        .collect();
 275                    update.pending_selection = self
 276                        .selections
 277                        .pending_anchor()
 278                        .as_ref()
 279                        .map(serialize_selection);
 280                    true
 281                }
 282                _ => false,
 283            },
 284        }
 285    }
 286
 287    fn apply_update_proto(
 288        &mut self,
 289        project: &ModelHandle<Project>,
 290        message: update_view::Variant,
 291        cx: &mut ViewContext<Self>,
 292    ) -> Task<Result<()>> {
 293        let update_view::Variant::Editor(message) = message;
 294        let project = project.clone();
 295        cx.spawn(|this, mut cx| async move {
 296            update_editor_from_message(this, project, message, &mut cx).await
 297        })
 298    }
 299
 300    fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
 301        match event {
 302            Event::Edited => true,
 303            Event::SelectionsChanged { local } => *local,
 304            Event::ScrollPositionChanged { local, .. } => *local,
 305            _ => false,
 306        }
 307    }
 308
 309    fn is_project_item(&self, _cx: &AppContext) -> bool {
 310        true
 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_for(&text) {
 999            self.transact(cx, |this, cx| {
1000                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1001            });
1002        }
1003    }
1004    fn match_index_for_direction(
1005        &mut self,
1006        matches: &Vec<Range<Anchor>>,
1007        current_index: usize,
1008        direction: Direction,
1009        count: usize,
1010        cx: &mut ViewContext<Self>,
1011    ) -> usize {
1012        let buffer = self.buffer().read(cx).snapshot(cx);
1013        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1014            self.selections.newest_anchor().head()
1015        } else {
1016            matches[current_index].start
1017        };
1018
1019        let mut count = count % matches.len();
1020        if count == 0 {
1021            return current_index;
1022        }
1023        match direction {
1024            Direction::Next => {
1025                if matches[current_index]
1026                    .start
1027                    .cmp(&current_index_position, &buffer)
1028                    .is_gt()
1029                {
1030                    count = count - 1
1031                }
1032
1033                (current_index + count) % matches.len()
1034            }
1035            Direction::Prev => {
1036                if matches[current_index]
1037                    .end
1038                    .cmp(&current_index_position, &buffer)
1039                    .is_lt()
1040                {
1041                    count = count - 1;
1042                }
1043
1044                if current_index >= count {
1045                    current_index - count
1046                } else {
1047                    matches.len() - (count - current_index)
1048                }
1049            }
1050        }
1051    }
1052
1053    fn find_matches(
1054        &mut self,
1055        query: Arc<project::search::SearchQuery>,
1056        cx: &mut ViewContext<Self>,
1057    ) -> Task<Vec<Range<Anchor>>> {
1058        let buffer = self.buffer().read(cx).snapshot(cx);
1059        cx.background().spawn(async move {
1060            let mut ranges = Vec::new();
1061            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1062                ranges.extend(
1063                    query
1064                        .search(excerpt_buffer, None)
1065                        .await
1066                        .into_iter()
1067                        .map(|range| {
1068                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1069                        }),
1070                );
1071            } else {
1072                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1073                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1074                    ranges.extend(
1075                        query
1076                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1077                            .await
1078                            .into_iter()
1079                            .map(|range| {
1080                                let start = excerpt
1081                                    .buffer
1082                                    .anchor_after(excerpt_range.start + range.start);
1083                                let end = excerpt
1084                                    .buffer
1085                                    .anchor_before(excerpt_range.start + range.end);
1086                                buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1087                                    ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1088                            }),
1089                    );
1090                }
1091            }
1092            ranges
1093        })
1094    }
1095
1096    fn active_match_index(
1097        &mut self,
1098        matches: Vec<Range<Anchor>>,
1099        cx: &mut ViewContext<Self>,
1100    ) -> Option<usize> {
1101        active_match_index(
1102            &matches,
1103            &self.selections.newest_anchor().head(),
1104            &self.buffer().read(cx).snapshot(cx),
1105        )
1106    }
1107}
1108
1109pub fn active_match_index(
1110    ranges: &[Range<Anchor>],
1111    cursor: &Anchor,
1112    buffer: &MultiBufferSnapshot,
1113) -> Option<usize> {
1114    if ranges.is_empty() {
1115        None
1116    } else {
1117        match ranges.binary_search_by(|probe| {
1118            if probe.end.cmp(cursor, &*buffer).is_lt() {
1119                Ordering::Less
1120            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1121                Ordering::Greater
1122            } else {
1123                Ordering::Equal
1124            }
1125        }) {
1126            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1127        }
1128    }
1129}
1130
1131pub struct CursorPosition {
1132    position: Option<Point>,
1133    selected_count: usize,
1134    _observe_active_editor: Option<Subscription>,
1135}
1136
1137impl Default for CursorPosition {
1138    fn default() -> Self {
1139        Self::new()
1140    }
1141}
1142
1143impl CursorPosition {
1144    pub fn new() -> Self {
1145        Self {
1146            position: None,
1147            selected_count: 0,
1148            _observe_active_editor: None,
1149        }
1150    }
1151
1152    fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
1153        let editor = editor.read(cx);
1154        let buffer = editor.buffer().read(cx).snapshot(cx);
1155
1156        self.selected_count = 0;
1157        let mut last_selection: Option<Selection<usize>> = None;
1158        for selection in editor.selections.all::<usize>(cx) {
1159            self.selected_count += selection.end - selection.start;
1160            if last_selection
1161                .as_ref()
1162                .map_or(true, |last_selection| selection.id > last_selection.id)
1163            {
1164                last_selection = Some(selection);
1165            }
1166        }
1167        self.position = last_selection.map(|s| s.head().to_point(&buffer));
1168
1169        cx.notify();
1170    }
1171}
1172
1173impl Entity for CursorPosition {
1174    type Event = ();
1175}
1176
1177impl View for CursorPosition {
1178    fn ui_name() -> &'static str {
1179        "CursorPosition"
1180    }
1181
1182    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1183        if let Some(position) = self.position {
1184            let theme = &theme::current(cx).workspace.status_bar;
1185            let mut text = format!(
1186                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1187                position.row + 1,
1188                position.column + 1
1189            );
1190            if self.selected_count > 0 {
1191                write!(text, " ({} selected)", self.selected_count).unwrap();
1192            }
1193            Label::new(text, theme.cursor_position.clone()).into_any()
1194        } else {
1195            Empty::new().into_any()
1196        }
1197    }
1198}
1199
1200impl StatusItemView for CursorPosition {
1201    fn set_active_pane_item(
1202        &mut self,
1203        active_pane_item: Option<&dyn ItemHandle>,
1204        cx: &mut ViewContext<Self>,
1205    ) {
1206        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1207            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1208            self.update_position(editor, cx);
1209        } else {
1210            self.position = None;
1211            self._observe_active_editor = None;
1212        }
1213
1214        cx.notify();
1215    }
1216}
1217
1218fn path_for_buffer<'a>(
1219    buffer: &ModelHandle<MultiBuffer>,
1220    height: usize,
1221    include_filename: bool,
1222    cx: &'a AppContext,
1223) -> Option<Cow<'a, Path>> {
1224    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1225    path_for_file(file.as_ref(), height, include_filename, cx)
1226}
1227
1228fn path_for_file<'a>(
1229    file: &'a dyn language::File,
1230    mut height: usize,
1231    include_filename: bool,
1232    cx: &'a AppContext,
1233) -> Option<Cow<'a, Path>> {
1234    // Ensure we always render at least the filename.
1235    height += 1;
1236
1237    let mut prefix = file.path().as_ref();
1238    while height > 0 {
1239        if let Some(parent) = prefix.parent() {
1240            prefix = parent;
1241            height -= 1;
1242        } else {
1243            break;
1244        }
1245    }
1246
1247    // Here we could have just always used `full_path`, but that is very
1248    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1249    // traversed all the way up to the worktree's root.
1250    if height > 0 {
1251        let full_path = file.full_path(cx);
1252        if include_filename {
1253            Some(full_path.into())
1254        } else {
1255            Some(full_path.parent()?.to_path_buf().into())
1256        }
1257    } else {
1258        let mut path = file.path().strip_prefix(prefix).ok()?;
1259        if !include_filename {
1260            path = path.parent()?;
1261        }
1262        Some(path.into())
1263    }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268    use super::*;
1269    use gpui::AppContext;
1270    use std::{
1271        path::{Path, PathBuf},
1272        sync::Arc,
1273        time::SystemTime,
1274    };
1275
1276    #[gpui::test]
1277    fn test_path_for_file(cx: &mut AppContext) {
1278        let file = TestFile {
1279            path: Path::new("").into(),
1280            full_path: PathBuf::from(""),
1281        };
1282        assert_eq!(path_for_file(&file, 0, false, cx), None);
1283    }
1284
1285    struct TestFile {
1286        path: Arc<Path>,
1287        full_path: PathBuf,
1288    }
1289
1290    impl language::File for TestFile {
1291        fn path(&self) -> &Arc<Path> {
1292            &self.path
1293        }
1294
1295        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1296            self.full_path.clone()
1297        }
1298
1299        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1300            unimplemented!()
1301        }
1302
1303        fn mtime(&self) -> SystemTime {
1304            unimplemented!()
1305        }
1306
1307        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1308            unimplemented!()
1309        }
1310
1311        fn worktree_id(&self) -> usize {
1312            0
1313        }
1314
1315        fn is_deleted(&self) -> bool {
1316            unimplemented!()
1317        }
1318
1319        fn as_any(&self) -> &dyn std::any::Any {
1320            unimplemented!()
1321        }
1322
1323        fn to_proto(&self) -> rpc::proto::File {
1324            unimplemented!()
1325        }
1326    }
1327}