items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting,
   3    persistence::{SerializedEditor, DB},
   4    scroll::ScrollAnchor,
   5    Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, FormatTarget,
   6    MultiBuffer, MultiBufferSnapshot, NavigationData, SearchWithinRange, ToPoint as _,
   7};
   8use anyhow::{anyhow, Context as _, Result};
   9use collections::HashSet;
  10use file_icons::FileIcons;
  11use futures::future::try_join_all;
  12use git::status::GitSummary;
  13use gpui::{
  14    point, AnyElement, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
  15    IntoElement, ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window,
  16};
  17use language::{
  18    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, DiskState, Point,
  19    SelectionGoal,
  20};
  21use lsp::DiagnosticSeverity;
  22use project::{
  23    lsp_store::FormatTrigger, project_settings::ProjectSettings, search::SearchQuery, Project,
  24    ProjectItem as _, ProjectPath,
  25};
  26use rpc::proto::{self, update_view, PeerId};
  27use settings::Settings;
  28use std::{
  29    any::TypeId,
  30    borrow::Cow,
  31    cmp::{self, Ordering},
  32    iter,
  33    ops::Range,
  34    path::Path,
  35    sync::Arc,
  36};
  37use text::{BufferId, Selection};
  38use theme::{Theme, ThemeSettings};
  39use ui::{prelude::*, IconDecorationKind};
  40use util::{paths::PathExt, ResultExt, TryFutureExt};
  41use workspace::{
  42    item::{BreadcrumbText, FollowEvent},
  43    searchable::SearchOptions,
  44    OpenVisible,
  45};
  46use workspace::{
  47    item::{Dedup, ItemSettings, SerializableItem, TabContentParams},
  48    OpenOptions,
  49};
  50use workspace::{
  51    item::{FollowableItem, Item, ItemEvent, ProjectItem},
  52    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  53    ItemId, ItemNavHistory, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  54};
  55
  56pub const MAX_TAB_TITLE_LEN: usize = 24;
  57
  58impl FollowableItem for Editor {
  59    fn remote_id(&self) -> Option<ViewId> {
  60        self.remote_id
  61    }
  62
  63    fn from_state_proto(
  64        workspace: Entity<Workspace>,
  65        remote_id: ViewId,
  66        state: &mut Option<proto::view::Variant>,
  67        window: &mut Window,
  68        cx: &mut App,
  69    ) -> Option<Task<Result<Entity<Self>>>> {
  70        let project = workspace.read(cx).project().to_owned();
  71        let Some(proto::view::Variant::Editor(_)) = state else {
  72            return None;
  73        };
  74        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  75            unreachable!()
  76        };
  77
  78        let buffer_ids = state
  79            .excerpts
  80            .iter()
  81            .map(|excerpt| excerpt.buffer_id)
  82            .collect::<HashSet<_>>();
  83        let buffers = project.update(cx, |project, cx| {
  84            buffer_ids
  85                .iter()
  86                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  87                .collect::<Result<Vec<_>>>()
  88        });
  89
  90        Some(window.spawn(cx, |mut cx| async move {
  91            let mut buffers = futures::future::try_join_all(buffers?)
  92                .await
  93                .debug_assert_ok("leaders don't share views for unshared buffers")?;
  94
  95            let editor = cx.update(|window, cx| {
  96                let multibuffer = cx.new(|cx| {
  97                    let mut multibuffer;
  98                    if state.singleton && buffers.len() == 1 {
  99                        multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 100                    } else {
 101                        multibuffer = MultiBuffer::new(project.read(cx).capability());
 102                        let mut excerpts = state.excerpts.into_iter().peekable();
 103                        while let Some(excerpt) = excerpts.peek() {
 104                            let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
 105                                continue;
 106                            };
 107                            let buffer_excerpts = iter::from_fn(|| {
 108                                let excerpt = excerpts.peek()?;
 109                                (excerpt.buffer_id == u64::from(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.new(|cx| {
 132                    let mut editor = Editor::for_multibuffer(
 133                        multibuffer,
 134                        Some(project.clone()),
 135                        true,
 136                        window,
 137                        cx,
 138                    );
 139                    editor.remote_id = Some(remote_id);
 140                    editor
 141                })
 142            })?;
 143
 144            update_editor_from_message(
 145                editor.downgrade(),
 146                project,
 147                proto::update_view::Editor {
 148                    selections: state.selections,
 149                    pending_selection: state.pending_selection,
 150                    scroll_top_anchor: state.scroll_top_anchor,
 151                    scroll_x: state.scroll_x,
 152                    scroll_y: state.scroll_y,
 153                    ..Default::default()
 154                },
 155                &mut cx,
 156            )
 157            .await?;
 158
 159            Ok(editor)
 160        }))
 161    }
 162
 163    fn set_leader_peer_id(
 164        &mut self,
 165        leader_peer_id: Option<PeerId>,
 166        window: &mut Window,
 167        cx: &mut Context<Self>,
 168    ) {
 169        self.leader_peer_id = leader_peer_id;
 170        if self.leader_peer_id.is_some() {
 171            self.buffer.update(cx, |buffer, cx| {
 172                buffer.remove_active_selections(cx);
 173            });
 174        } else if self.focus_handle.is_focused(window) {
 175            self.buffer.update(cx, |buffer, cx| {
 176                buffer.set_active_selections(
 177                    &self.selections.disjoint_anchors(),
 178                    self.selections.line_mode,
 179                    self.cursor_shape,
 180                    cx,
 181                );
 182            });
 183        }
 184        cx.notify();
 185    }
 186
 187    fn to_state_proto(&self, _: &Window, cx: &App) -> Option<proto::view::Variant> {
 188        let buffer = self.buffer.read(cx);
 189        if buffer
 190            .as_singleton()
 191            .and_then(|buffer| buffer.read(cx).file())
 192            .map_or(false, |file| file.is_private())
 193        {
 194            return None;
 195        }
 196
 197        let scroll_anchor = self.scroll_manager.anchor();
 198        let excerpts = buffer
 199            .read(cx)
 200            .excerpts()
 201            .map(|(id, buffer, range)| proto::Excerpt {
 202                id: id.to_proto(),
 203                buffer_id: buffer.remote_id().into(),
 204                context_start: Some(serialize_text_anchor(&range.context.start)),
 205                context_end: Some(serialize_text_anchor(&range.context.end)),
 206                primary_start: range
 207                    .primary
 208                    .as_ref()
 209                    .map(|range| serialize_text_anchor(&range.start)),
 210                primary_end: range
 211                    .primary
 212                    .as_ref()
 213                    .map(|range| serialize_text_anchor(&range.end)),
 214            })
 215            .collect();
 216
 217        Some(proto::view::Variant::Editor(proto::view::Editor {
 218            singleton: buffer.is_singleton(),
 219            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 220            excerpts,
 221            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 222            scroll_x: scroll_anchor.offset.x,
 223            scroll_y: scroll_anchor.offset.y,
 224            selections: self
 225                .selections
 226                .disjoint_anchors()
 227                .iter()
 228                .map(serialize_selection)
 229                .collect(),
 230            pending_selection: self
 231                .selections
 232                .pending_anchor()
 233                .as_ref()
 234                .map(serialize_selection),
 235        }))
 236    }
 237
 238    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 239        match event {
 240            EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
 241            EditorEvent::SelectionsChanged { local }
 242            | EditorEvent::ScrollPositionChanged { local, .. } => {
 243                if *local {
 244                    Some(FollowEvent::Unfollow)
 245                } else {
 246                    None
 247                }
 248            }
 249            _ => None,
 250        }
 251    }
 252
 253    fn add_event_to_update_proto(
 254        &self,
 255        event: &EditorEvent,
 256        update: &mut Option<proto::update_view::Variant>,
 257        _: &Window,
 258        cx: &App,
 259    ) -> bool {
 260        let update =
 261            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 262
 263        match update {
 264            proto::update_view::Variant::Editor(update) => match event {
 265                EditorEvent::ExcerptsAdded {
 266                    buffer,
 267                    predecessor,
 268                    excerpts,
 269                } => {
 270                    let buffer_id = buffer.read(cx).remote_id();
 271                    let mut excerpts = excerpts.iter();
 272                    if let Some((id, range)) = excerpts.next() {
 273                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 274                            previous_excerpt_id: Some(predecessor.to_proto()),
 275                            excerpt: serialize_excerpt(buffer_id, id, range),
 276                        });
 277                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 278                            proto::ExcerptInsertion {
 279                                previous_excerpt_id: None,
 280                                excerpt: serialize_excerpt(buffer_id, id, range),
 281                            }
 282                        }))
 283                    }
 284                    true
 285                }
 286                EditorEvent::ExcerptsRemoved { ids } => {
 287                    update
 288                        .deleted_excerpts
 289                        .extend(ids.iter().map(ExcerptId::to_proto));
 290                    true
 291                }
 292                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 293                    let scroll_anchor = self.scroll_manager.anchor();
 294                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 295                    update.scroll_x = scroll_anchor.offset.x;
 296                    update.scroll_y = scroll_anchor.offset.y;
 297                    true
 298                }
 299                EditorEvent::SelectionsChanged { .. } => {
 300                    update.selections = self
 301                        .selections
 302                        .disjoint_anchors()
 303                        .iter()
 304                        .map(serialize_selection)
 305                        .collect();
 306                    update.pending_selection = self
 307                        .selections
 308                        .pending_anchor()
 309                        .as_ref()
 310                        .map(serialize_selection);
 311                    true
 312                }
 313                _ => false,
 314            },
 315        }
 316    }
 317
 318    fn apply_update_proto(
 319        &mut self,
 320        project: &Entity<Project>,
 321        message: update_view::Variant,
 322        window: &mut Window,
 323        cx: &mut Context<Self>,
 324    ) -> Task<Result<()>> {
 325        let update_view::Variant::Editor(message) = message;
 326        let project = project.clone();
 327        cx.spawn_in(window, |this, mut cx| async move {
 328            update_editor_from_message(this, project, message, &mut cx).await
 329        })
 330    }
 331
 332    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
 333        true
 334    }
 335
 336    fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
 337        let self_singleton = self.buffer.read(cx).as_singleton()?;
 338        let other_singleton = existing.buffer.read(cx).as_singleton()?;
 339        if self_singleton == other_singleton {
 340            Some(Dedup::KeepExisting)
 341        } else {
 342            None
 343        }
 344    }
 345}
 346
 347async fn update_editor_from_message(
 348    this: WeakEntity<Editor>,
 349    project: Entity<Project>,
 350    message: proto::update_view::Editor,
 351    cx: &mut AsyncWindowContext,
 352) -> Result<()> {
 353    // Open all of the buffers of which excerpts were added to the editor.
 354    let inserted_excerpt_buffer_ids = message
 355        .inserted_excerpts
 356        .iter()
 357        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 358        .collect::<HashSet<_>>();
 359    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 360        inserted_excerpt_buffer_ids
 361            .into_iter()
 362            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 363            .collect::<Result<Vec<_>>>()
 364    })??;
 365    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 366
 367    // Update the editor's excerpts.
 368    this.update(cx, |editor, cx| {
 369        editor.buffer.update(cx, |multibuffer, cx| {
 370            let mut removed_excerpt_ids = message
 371                .deleted_excerpts
 372                .into_iter()
 373                .map(ExcerptId::from_proto)
 374                .collect::<Vec<_>>();
 375            removed_excerpt_ids.sort_by({
 376                let multibuffer = multibuffer.read(cx);
 377                move |a, b| a.cmp(b, &multibuffer)
 378            });
 379
 380            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 381            while let Some(insertion) = insertions.next() {
 382                let Some(excerpt) = insertion.excerpt else {
 383                    continue;
 384                };
 385                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 386                    continue;
 387                };
 388                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 389                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
 390                    continue;
 391                };
 392
 393                let adjacent_excerpts = iter::from_fn(|| {
 394                    let insertion = insertions.peek()?;
 395                    if insertion.previous_excerpt_id.is_none()
 396                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 397                    {
 398                        insertions.next()?.excerpt
 399                    } else {
 400                        None
 401                    }
 402                });
 403
 404                multibuffer.insert_excerpts_with_ids_after(
 405                    ExcerptId::from_proto(previous_excerpt_id),
 406                    buffer,
 407                    [excerpt]
 408                        .into_iter()
 409                        .chain(adjacent_excerpts)
 410                        .filter_map(|excerpt| {
 411                            Some((
 412                                ExcerptId::from_proto(excerpt.id),
 413                                deserialize_excerpt_range(excerpt)?,
 414                            ))
 415                        }),
 416                    cx,
 417                );
 418            }
 419
 420            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 421            Result::<(), anyhow::Error>::Ok(())
 422        })
 423    })??;
 424
 425    // Deserialize the editor state.
 426    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 427        let buffer = editor.buffer.read(cx).read(cx);
 428        let selections = message
 429            .selections
 430            .into_iter()
 431            .filter_map(|selection| deserialize_selection(&buffer, selection))
 432            .collect::<Vec<_>>();
 433        let pending_selection = message
 434            .pending_selection
 435            .and_then(|selection| deserialize_selection(&buffer, selection));
 436        let scroll_top_anchor = message
 437            .scroll_top_anchor
 438            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 439        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 440    })??;
 441
 442    // Wait until the buffer has received all of the operations referenced by
 443    // the editor's new state.
 444    this.update(cx, |editor, cx| {
 445        editor.buffer.update(cx, |buffer, cx| {
 446            buffer.wait_for_anchors(
 447                selections
 448                    .iter()
 449                    .chain(pending_selection.as_ref())
 450                    .flat_map(|selection| [selection.start, selection.end])
 451                    .chain(scroll_top_anchor),
 452                cx,
 453            )
 454        })
 455    })?
 456    .await?;
 457
 458    // Update the editor's state.
 459    this.update_in(cx, |editor, window, cx| {
 460        if !selections.is_empty() || pending_selection.is_some() {
 461            editor.set_selections_from_remote(selections, pending_selection, window, cx);
 462            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 463        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 464            editor.set_scroll_anchor_remote(
 465                ScrollAnchor {
 466                    anchor: scroll_top_anchor,
 467                    offset: point(message.scroll_x, message.scroll_y),
 468                },
 469                window,
 470                cx,
 471            );
 472        }
 473    })?;
 474    Ok(())
 475}
 476
 477fn serialize_excerpt(
 478    buffer_id: BufferId,
 479    id: &ExcerptId,
 480    range: &ExcerptRange<language::Anchor>,
 481) -> Option<proto::Excerpt> {
 482    Some(proto::Excerpt {
 483        id: id.to_proto(),
 484        buffer_id: buffer_id.into(),
 485        context_start: Some(serialize_text_anchor(&range.context.start)),
 486        context_end: Some(serialize_text_anchor(&range.context.end)),
 487        primary_start: range
 488            .primary
 489            .as_ref()
 490            .map(|r| serialize_text_anchor(&r.start)),
 491        primary_end: range
 492            .primary
 493            .as_ref()
 494            .map(|r| serialize_text_anchor(&r.end)),
 495    })
 496}
 497
 498fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 499    proto::Selection {
 500        id: selection.id as u64,
 501        start: Some(serialize_anchor(&selection.start)),
 502        end: Some(serialize_anchor(&selection.end)),
 503        reversed: selection.reversed,
 504    }
 505}
 506
 507fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 508    proto::EditorAnchor {
 509        excerpt_id: anchor.excerpt_id.to_proto(),
 510        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 511    }
 512}
 513
 514fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 515    let context = {
 516        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 517        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 518        start..end
 519    };
 520    let primary = excerpt
 521        .primary_start
 522        .zip(excerpt.primary_end)
 523        .and_then(|(start, end)| {
 524            let start = language::proto::deserialize_anchor(start)?;
 525            let end = language::proto::deserialize_anchor(end)?;
 526            Some(start..end)
 527        });
 528    Some(ExcerptRange { context, primary })
 529}
 530
 531fn deserialize_selection(
 532    buffer: &MultiBufferSnapshot,
 533    selection: proto::Selection,
 534) -> Option<Selection<Anchor>> {
 535    Some(Selection {
 536        id: selection.id as usize,
 537        start: deserialize_anchor(buffer, selection.start?)?,
 538        end: deserialize_anchor(buffer, selection.end?)?,
 539        reversed: selection.reversed,
 540        goal: SelectionGoal::None,
 541    })
 542}
 543
 544fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 545    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 546    Some(Anchor {
 547        excerpt_id,
 548        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 549        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 550        diff_base_anchor: None,
 551    })
 552}
 553
 554impl Item for Editor {
 555    type Event = EditorEvent;
 556
 557    fn navigate(
 558        &mut self,
 559        data: Box<dyn std::any::Any>,
 560        window: &mut Window,
 561        cx: &mut Context<Self>,
 562    ) -> bool {
 563        if let Ok(data) = data.downcast::<NavigationData>() {
 564            let newest_selection = self.selections.newest::<Point>(cx);
 565            let buffer = self.buffer.read(cx).read(cx);
 566            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 567                data.cursor_anchor.to_point(&buffer)
 568            } else {
 569                buffer.clip_point(data.cursor_position, Bias::Left)
 570            };
 571
 572            let mut scroll_anchor = data.scroll_anchor;
 573            if !buffer.can_resolve(&scroll_anchor.anchor) {
 574                scroll_anchor.anchor = buffer.anchor_before(
 575                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 576                );
 577            }
 578
 579            drop(buffer);
 580
 581            if newest_selection.head() == offset {
 582                false
 583            } else {
 584                let nav_history = self.nav_history.take();
 585                self.set_scroll_anchor(scroll_anchor, window, cx);
 586                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 587                    s.select_ranges([offset..offset])
 588                });
 589                self.nav_history = nav_history;
 590                true
 591            }
 592        } else {
 593            false
 594        }
 595    }
 596
 597    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 598        let file_path = self
 599            .buffer()
 600            .read(cx)
 601            .as_singleton()?
 602            .read(cx)
 603            .file()
 604            .and_then(|f| f.as_local())?
 605            .abs_path(cx);
 606
 607        let file_path = file_path.compact().to_string_lossy().to_string();
 608
 609        Some(file_path.into())
 610    }
 611
 612    fn telemetry_event_text(&self) -> Option<&'static str> {
 613        None
 614    }
 615
 616    fn tab_description(&self, detail: usize, cx: &App) -> Option<SharedString> {
 617        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 618        Some(path.to_string_lossy().to_string().into())
 619    }
 620
 621    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 622        ItemSettings::get_global(cx)
 623            .file_icons
 624            .then(|| {
 625                path_for_buffer(&self.buffer, 0, true, cx)
 626                    .and_then(|path| FileIcons::get_icon(path.as_ref(), cx))
 627            })
 628            .flatten()
 629            .map(Icon::from_path)
 630    }
 631
 632    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 633        let label_color = if ItemSettings::get_global(cx).git_status {
 634            self.buffer()
 635                .read(cx)
 636                .as_singleton()
 637                .and_then(|buffer| buffer.read(cx).project_path(cx))
 638                .and_then(|path| {
 639                    let project = self.project.as_ref()?.read(cx);
 640                    let entry = project.entry_for_path(&path, cx)?;
 641                    let git_status = project
 642                        .worktree_for_id(path.worktree_id, cx)?
 643                        .read(cx)
 644                        .snapshot()
 645                        .status_for_file(path.path)?;
 646
 647                    Some(entry_git_aware_label_color(
 648                        git_status.summary(),
 649                        entry.is_ignored,
 650                        params.selected,
 651                    ))
 652                })
 653                .unwrap_or_else(|| entry_label_color(params.selected))
 654        } else {
 655            entry_label_color(params.selected)
 656        };
 657
 658        let description = params.detail.and_then(|detail| {
 659            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 660            let description = path.to_string_lossy();
 661            let description = description.trim();
 662
 663            if description.is_empty() {
 664                return None;
 665            }
 666
 667            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 668        });
 669
 670        // Whether the file was saved in the past but is now deleted.
 671        let was_deleted: bool = self
 672            .buffer()
 673            .read(cx)
 674            .as_singleton()
 675            .and_then(|buffer| buffer.read(cx).file())
 676            .map_or(false, |file| file.disk_state() == DiskState::Deleted);
 677
 678        h_flex()
 679            .gap_2()
 680            .child(
 681                Label::new(self.title(cx).to_string())
 682                    .color(label_color)
 683                    .when(params.preview, |this| this.italic())
 684                    .when(was_deleted, |this| this.strikethrough()),
 685            )
 686            .when_some(description, |this, description| {
 687                this.child(
 688                    Label::new(description)
 689                        .size(LabelSize::XSmall)
 690                        .color(Color::Muted),
 691                )
 692            })
 693            .into_any_element()
 694    }
 695
 696    fn for_each_project_item(
 697        &self,
 698        cx: &App,
 699        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 700    ) {
 701        self.buffer
 702            .read(cx)
 703            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 704    }
 705
 706    fn is_singleton(&self, cx: &App) -> bool {
 707        self.buffer.read(cx).is_singleton()
 708    }
 709
 710    fn can_save_as(&self, cx: &App) -> bool {
 711        self.buffer.read(cx).is_singleton()
 712    }
 713
 714    fn clone_on_split(
 715        &self,
 716        _workspace_id: Option<WorkspaceId>,
 717        window: &mut Window,
 718        cx: &mut Context<Self>,
 719    ) -> Option<Entity<Editor>>
 720    where
 721        Self: Sized,
 722    {
 723        Some(cx.new(|cx| self.clone(window, cx)))
 724    }
 725
 726    fn set_nav_history(
 727        &mut self,
 728        history: ItemNavHistory,
 729        _window: &mut Window,
 730        _: &mut Context<Self>,
 731    ) {
 732        self.nav_history = Some(history);
 733    }
 734
 735    fn discarded(&self, _project: Entity<Project>, _: &mut Window, cx: &mut Context<Self>) {
 736        for buffer in self.buffer().clone().read(cx).all_buffers() {
 737            buffer.update(cx, |buffer, cx| buffer.discarded(cx))
 738        }
 739    }
 740
 741    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 742        let selection = self.selections.newest_anchor();
 743        self.push_to_nav_history(selection.head(), None, cx);
 744    }
 745
 746    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 747        self.hide_hovered_link(cx);
 748    }
 749
 750    fn is_dirty(&self, cx: &App) -> bool {
 751        self.buffer().read(cx).read(cx).is_dirty()
 752    }
 753
 754    fn has_deleted_file(&self, cx: &App) -> bool {
 755        self.buffer().read(cx).read(cx).has_deleted_file()
 756    }
 757
 758    fn has_conflict(&self, cx: &App) -> bool {
 759        self.buffer().read(cx).read(cx).has_conflict()
 760    }
 761
 762    fn can_save(&self, cx: &App) -> bool {
 763        let buffer = &self.buffer().read(cx);
 764        if let Some(buffer) = buffer.as_singleton() {
 765            buffer.read(cx).project_path(cx).is_some()
 766        } else {
 767            true
 768        }
 769    }
 770
 771    fn save(
 772        &mut self,
 773        format: bool,
 774        project: Entity<Project>,
 775        window: &mut Window,
 776        cx: &mut Context<Self>,
 777    ) -> Task<Result<()>> {
 778        self.report_editor_event("Editor Saved", None, cx);
 779        let buffers = self.buffer().clone().read(cx).all_buffers();
 780        let buffers = buffers
 781            .into_iter()
 782            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 783            .collect::<HashSet<_>>();
 784        cx.spawn_in(window, |this, mut cx| async move {
 785            if format {
 786                this.update_in(&mut cx, |editor, window, cx| {
 787                    editor.perform_format(
 788                        project.clone(),
 789                        FormatTrigger::Save,
 790                        FormatTarget::Buffers,
 791                        window,
 792                        cx,
 793                    )
 794                })?
 795                .await?;
 796            }
 797
 798            if buffers.len() == 1 {
 799                // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
 800                project
 801                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 802                    .await?;
 803            } else {
 804                // For multi-buffers, only format and save the buffers with changes.
 805                // For clean buffers, we simulate saving by calling `Buffer::did_save`,
 806                // so that language servers or other downstream listeners of save events get notified.
 807                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 808                    buffer
 809                        .update(&mut cx, |buffer, _| {
 810                            buffer.is_dirty() || buffer.has_conflict()
 811                        })
 812                        .unwrap_or(false)
 813                });
 814
 815                project
 816                    .update(&mut cx, |project, cx| {
 817                        project.save_buffers(dirty_buffers, cx)
 818                    })?
 819                    .await?;
 820                for buffer in clean_buffers {
 821                    buffer
 822                        .update(&mut cx, |buffer, cx| {
 823                            let version = buffer.saved_version().clone();
 824                            let mtime = buffer.saved_mtime();
 825                            buffer.did_save(version, mtime, cx);
 826                        })
 827                        .ok();
 828                }
 829            }
 830
 831            Ok(())
 832        })
 833    }
 834
 835    fn save_as(
 836        &mut self,
 837        project: Entity<Project>,
 838        path: ProjectPath,
 839        _: &mut Window,
 840        cx: &mut Context<Self>,
 841    ) -> Task<Result<()>> {
 842        let buffer = self
 843            .buffer()
 844            .read(cx)
 845            .as_singleton()
 846            .expect("cannot call save_as on an excerpt list");
 847
 848        let file_extension = path
 849            .path
 850            .extension()
 851            .map(|a| a.to_string_lossy().to_string());
 852        self.report_editor_event("Editor Saved", file_extension, cx);
 853
 854        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 855    }
 856
 857    fn reload(
 858        &mut self,
 859        project: Entity<Project>,
 860        window: &mut Window,
 861        cx: &mut Context<Self>,
 862    ) -> Task<Result<()>> {
 863        let buffer = self.buffer().clone();
 864        let buffers = self.buffer.read(cx).all_buffers();
 865        let reload_buffers =
 866            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 867        cx.spawn_in(window, |this, mut cx| async move {
 868            let transaction = reload_buffers.log_err().await;
 869            this.update(&mut cx, |editor, cx| {
 870                editor.request_autoscroll(Autoscroll::fit(), cx)
 871            })?;
 872            buffer
 873                .update(&mut cx, |buffer, cx| {
 874                    if let Some(transaction) = transaction {
 875                        if !buffer.is_singleton() {
 876                            buffer.push_transaction(&transaction.0, cx);
 877                        }
 878                    }
 879                })
 880                .ok();
 881            Ok(())
 882        })
 883    }
 884
 885    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 886        Some(Box::new(handle.clone()))
 887    }
 888
 889    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 890        self.pixel_position_of_newest_cursor
 891    }
 892
 893    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 894        if self.show_breadcrumbs {
 895            ToolbarItemLocation::PrimaryLeft
 896        } else {
 897            ToolbarItemLocation::Hidden
 898        }
 899    }
 900
 901    fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 902        let cursor = self.selections.newest_anchor().head();
 903        let multibuffer = &self.buffer().read(cx);
 904        let (buffer_id, symbols) =
 905            multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
 906        let buffer = multibuffer.buffer(buffer_id)?;
 907
 908        let buffer = buffer.read(cx);
 909        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 910            buffer
 911                .snapshot()
 912                .resolve_file_path(
 913                    cx,
 914                    self.project
 915                        .as_ref()
 916                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 917                        .unwrap_or_default(),
 918                )
 919                .map(|path| path.to_string_lossy().to_string())
 920                .unwrap_or_else(|| {
 921                    if multibuffer.is_singleton() {
 922                        multibuffer.title(cx).to_string()
 923                    } else {
 924                        "untitled".to_string()
 925                    }
 926                })
 927        });
 928
 929        let settings = ThemeSettings::get_global(cx);
 930
 931        let mut breadcrumbs = vec![BreadcrumbText {
 932            text,
 933            highlights: None,
 934            font: Some(settings.buffer_font.clone()),
 935        }];
 936
 937        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 938            text: symbol.text,
 939            highlights: Some(symbol.highlight_ranges),
 940            font: Some(settings.buffer_font.clone()),
 941        }));
 942        Some(breadcrumbs)
 943    }
 944
 945    fn added_to_workspace(
 946        &mut self,
 947        workspace: &mut Workspace,
 948        _window: &mut Window,
 949        _: &mut Context<Self>,
 950    ) {
 951        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 952    }
 953
 954    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 955        match event {
 956            EditorEvent::Closed => f(ItemEvent::CloseItem),
 957
 958            EditorEvent::Saved | EditorEvent::TitleChanged => {
 959                f(ItemEvent::UpdateTab);
 960                f(ItemEvent::UpdateBreadcrumbs);
 961            }
 962
 963            EditorEvent::Reparsed(_) => {
 964                f(ItemEvent::UpdateBreadcrumbs);
 965            }
 966
 967            EditorEvent::SelectionsChanged { local } if *local => {
 968                f(ItemEvent::UpdateBreadcrumbs);
 969            }
 970
 971            EditorEvent::DirtyChanged => {
 972                f(ItemEvent::UpdateTab);
 973            }
 974
 975            EditorEvent::BufferEdited => {
 976                f(ItemEvent::Edit);
 977                f(ItemEvent::UpdateBreadcrumbs);
 978            }
 979
 980            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 981                f(ItemEvent::Edit);
 982            }
 983
 984            _ => {}
 985        }
 986    }
 987
 988    fn preserve_preview(&self, cx: &App) -> bool {
 989        self.buffer.read(cx).preserve_preview(cx)
 990    }
 991}
 992
 993impl SerializableItem for Editor {
 994    fn serialized_item_kind() -> &'static str {
 995        "Editor"
 996    }
 997
 998    fn cleanup(
 999        workspace_id: WorkspaceId,
1000        alive_items: Vec<ItemId>,
1001        window: &mut Window,
1002        cx: &mut App,
1003    ) -> Task<Result<()>> {
1004        window.spawn(cx, |_| DB.delete_unloaded_items(workspace_id, alive_items))
1005    }
1006
1007    fn deserialize(
1008        project: Entity<Project>,
1009        workspace: WeakEntity<Workspace>,
1010        workspace_id: workspace::WorkspaceId,
1011        item_id: ItemId,
1012        window: &mut Window,
1013        cx: &mut App,
1014    ) -> Task<Result<Entity<Self>>> {
1015        let serialized_editor = match DB
1016            .get_serialized_editor(item_id, workspace_id)
1017            .context("Failed to query editor state")
1018        {
1019            Ok(Some(serialized_editor)) => {
1020                if ProjectSettings::get_global(cx)
1021                    .session
1022                    .restore_unsaved_buffers
1023                {
1024                    serialized_editor
1025                } else {
1026                    SerializedEditor {
1027                        abs_path: serialized_editor.abs_path,
1028                        contents: None,
1029                        language: None,
1030                        mtime: None,
1031                    }
1032                }
1033            }
1034            Ok(None) => {
1035                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1036            }
1037            Err(error) => {
1038                return Task::ready(Err(error));
1039            }
1040        };
1041
1042        match serialized_editor {
1043            SerializedEditor {
1044                abs_path: None,
1045                contents: Some(contents),
1046                language,
1047                ..
1048            } => window.spawn(cx, |mut cx| {
1049                let project = project.clone();
1050                async move {
1051                    let language_registry =
1052                        project.update(&mut cx, |project, _| project.languages().clone())?;
1053
1054                    let language = if let Some(language_name) = language {
1055                        // We don't fail here, because we'd rather not set the language if the name changed
1056                        // than fail to restore the buffer.
1057                        language_registry
1058                            .language_for_name(&language_name)
1059                            .await
1060                            .ok()
1061                    } else {
1062                        None
1063                    };
1064
1065                    // First create the empty buffer
1066                    let buffer = project
1067                        .update(&mut cx, |project, cx| project.create_buffer(cx))?
1068                        .await?;
1069
1070                    // Then set the text so that the dirty bit is set correctly
1071                    buffer.update(&mut cx, |buffer, cx| {
1072                        buffer.set_language_registry(language_registry);
1073                        if let Some(language) = language {
1074                            buffer.set_language(Some(language), cx);
1075                        }
1076                        buffer.set_text(contents, cx);
1077                        if let Some(entry) = buffer.peek_undo_stack() {
1078                            buffer.forget_transaction(entry.transaction_id());
1079                        }
1080                    })?;
1081
1082                    cx.update(|window, cx| {
1083                        cx.new(|cx| {
1084                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1085
1086                            editor.read_selections_from_db(item_id, workspace_id, window, cx);
1087                            editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1088                            editor
1089                        })
1090                    })
1091                }
1092            }),
1093            SerializedEditor {
1094                abs_path: Some(abs_path),
1095                contents,
1096                mtime,
1097                ..
1098            } => {
1099                let project_item = project.update(cx, |project, cx| {
1100                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1101                    let project_path = ProjectPath {
1102                        worktree_id: worktree.read(cx).id(),
1103                        path: path.into(),
1104                    };
1105                    Some(project.open_path(project_path, cx))
1106                });
1107
1108                match project_item {
1109                    Some(project_item) => {
1110                        window.spawn(cx, |mut cx| async move {
1111                            let (_, project_item) = project_item.await?;
1112                            let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1113                                anyhow!("Project item at stored path was not a buffer")
1114                            })?;
1115
1116                            // This is a bit wasteful: we're loading the whole buffer from
1117                            // disk and then overwrite the content.
1118                            // But for now, it keeps the implementation of the content serialization
1119                            // simple, because we don't have to persist all of the metadata that we get
1120                            // by loading the file (git diff base, ...).
1121                            if let Some(buffer_text) = contents {
1122                                buffer.update(&mut cx, |buffer, cx| {
1123                                    // If we did restore an mtime, we want to store it on the buffer
1124                                    // so that the next edit will mark the buffer as dirty/conflicted.
1125                                    if mtime.is_some() {
1126                                        buffer.did_reload(
1127                                            buffer.version(),
1128                                            buffer.line_ending(),
1129                                            mtime,
1130                                            cx,
1131                                        );
1132                                    }
1133                                    buffer.set_text(buffer_text, cx);
1134                                    if let Some(entry) = buffer.peek_undo_stack() {
1135                                        buffer.forget_transaction(entry.transaction_id());
1136                                    }
1137                                })?;
1138                            }
1139
1140                            cx.update(|window, cx| {
1141                                cx.new(|cx| {
1142                                    let mut editor =
1143                                        Editor::for_buffer(buffer, Some(project), window, cx);
1144
1145                                    editor.read_selections_from_db(
1146                                        item_id,
1147                                        workspace_id,
1148                                        window,
1149                                        cx,
1150                                    );
1151                                    editor.read_scroll_position_from_db(
1152                                        item_id,
1153                                        workspace_id,
1154                                        window,
1155                                        cx,
1156                                    );
1157                                    editor
1158                                })
1159                            })
1160                        })
1161                    }
1162                    None => {
1163                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1164                            workspace.open_abs_path(
1165                                abs_path.clone(),
1166                                OpenOptions {
1167                                    visible: Some(OpenVisible::None),
1168                                    ..Default::default()
1169                                },
1170                                window,
1171                                cx,
1172                            )
1173                        });
1174                        window.spawn(cx, |mut cx| async move {
1175                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1176                            editor.update_in(&mut cx, |editor, window, cx| {
1177                                editor.read_selections_from_db(item_id, workspace_id, window, cx);
1178                                editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1179                            })?;
1180                            Ok(editor)
1181                        })
1182                    }
1183                }
1184            }
1185            SerializedEditor {
1186                abs_path: None,
1187                contents: None,
1188                ..
1189            } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1190        }
1191    }
1192
1193    fn serialize(
1194        &mut self,
1195        workspace: &mut Workspace,
1196        item_id: ItemId,
1197        closing: bool,
1198        window: &mut Window,
1199        cx: &mut Context<Self>,
1200    ) -> Option<Task<Result<()>>> {
1201        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1202
1203        let project = self.project.clone()?;
1204        if project.read(cx).visible_worktrees(cx).next().is_none() {
1205            // If we don't have a worktree, we don't serialize, because
1206            // projects without worktrees aren't deserialized.
1207            serialize_dirty_buffers = false;
1208        }
1209
1210        if closing && !serialize_dirty_buffers {
1211            return None;
1212        }
1213
1214        let workspace_id = workspace.database_id()?;
1215
1216        let buffer = self.buffer().read(cx).as_singleton()?;
1217
1218        let abs_path = buffer.read(cx).file().and_then(|file| {
1219            let worktree_id = file.worktree_id(cx);
1220            project
1221                .read(cx)
1222                .worktree_for_id(worktree_id, cx)
1223                .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1224                .or_else(|| {
1225                    let full_path = file.full_path(cx);
1226                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1227                    project.read(cx).absolute_path(&project_path, cx)
1228                })
1229        });
1230
1231        let is_dirty = buffer.read(cx).is_dirty();
1232        let mtime = buffer.read(cx).saved_mtime();
1233
1234        let snapshot = buffer.read(cx).snapshot();
1235
1236        Some(cx.spawn_in(window, |_this, cx| async move {
1237            cx.background_spawn(async move {
1238                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1239                    let contents = snapshot.text();
1240                    let language = snapshot.language().map(|lang| lang.name().to_string());
1241                    (Some(contents), language)
1242                } else {
1243                    (None, None)
1244                };
1245
1246                let editor = SerializedEditor {
1247                    abs_path,
1248                    contents,
1249                    language,
1250                    mtime,
1251                };
1252                DB.save_serialized_editor(item_id, workspace_id, editor)
1253                    .await
1254                    .context("failed to save serialized editor")
1255            })
1256            .await
1257            .context("failed to save contents of buffer")?;
1258
1259            Ok(())
1260        }))
1261    }
1262
1263    fn should_serialize(&self, event: &Self::Event) -> bool {
1264        matches!(
1265            event,
1266            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1267        )
1268    }
1269}
1270
1271impl ProjectItem for Editor {
1272    type Item = Buffer;
1273
1274    fn for_project_item(
1275        project: Entity<Project>,
1276        buffer: Entity<Buffer>,
1277        window: &mut Window,
1278        cx: &mut Context<Self>,
1279    ) -> Self {
1280        Self::for_buffer(buffer, Some(project), window, cx)
1281    }
1282}
1283
1284impl EventEmitter<SearchEvent> for Editor {}
1285
1286pub(crate) enum BufferSearchHighlights {}
1287impl SearchableItem for Editor {
1288    type Match = Range<Anchor>;
1289
1290    fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1291        self.background_highlights
1292            .get(&TypeId::of::<BufferSearchHighlights>())
1293            .map_or(Vec::new(), |(_color, ranges)| {
1294                ranges.iter().cloned().collect()
1295            })
1296    }
1297
1298    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1299        if self
1300            .clear_background_highlights::<BufferSearchHighlights>(cx)
1301            .is_some()
1302        {
1303            cx.emit(SearchEvent::MatchesInvalidated);
1304        }
1305    }
1306
1307    fn update_matches(
1308        &mut self,
1309        matches: &[Range<Anchor>],
1310        _: &mut Window,
1311        cx: &mut Context<Self>,
1312    ) {
1313        let existing_range = self
1314            .background_highlights
1315            .get(&TypeId::of::<BufferSearchHighlights>())
1316            .map(|(_, range)| range.as_ref());
1317        let updated = existing_range != Some(matches);
1318        self.highlight_background::<BufferSearchHighlights>(
1319            matches,
1320            |theme| theme.search_match_background,
1321            cx,
1322        );
1323        if updated {
1324            cx.emit(SearchEvent::MatchesInvalidated);
1325        }
1326    }
1327
1328    fn has_filtered_search_ranges(&mut self) -> bool {
1329        self.has_background_highlights::<SearchWithinRange>()
1330    }
1331
1332    fn toggle_filtered_search_ranges(
1333        &mut self,
1334        enabled: bool,
1335        _: &mut Window,
1336        cx: &mut Context<Self>,
1337    ) {
1338        if self.has_filtered_search_ranges() {
1339            self.previous_search_ranges = self
1340                .clear_background_highlights::<SearchWithinRange>(cx)
1341                .map(|(_, ranges)| ranges)
1342        }
1343
1344        if !enabled {
1345            return;
1346        }
1347
1348        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1349        if ranges.iter().any(|s| s.start != s.end) {
1350            self.set_search_within_ranges(&ranges, cx);
1351        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1352            self.set_search_within_ranges(&previous_search_ranges, cx)
1353        }
1354    }
1355
1356    fn supported_options(&self) -> SearchOptions {
1357        if self.in_project_search {
1358            SearchOptions {
1359                case: true,
1360                word: true,
1361                regex: true,
1362                replacement: false,
1363                selection: false,
1364                find_in_results: true,
1365            }
1366        } else {
1367            SearchOptions {
1368                case: true,
1369                word: true,
1370                regex: true,
1371                replacement: true,
1372                selection: true,
1373                find_in_results: false,
1374            }
1375        }
1376    }
1377
1378    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1379        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1380        let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1381        let selection = self.selections.newest::<usize>(cx);
1382
1383        match setting {
1384            SeedQuerySetting::Never => String::new(),
1385            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1386                let text: String = snapshot
1387                    .text_for_range(selection.start..selection.end)
1388                    .collect();
1389                if text.contains('\n') {
1390                    String::new()
1391                } else {
1392                    text
1393                }
1394            }
1395            SeedQuerySetting::Selection => String::new(),
1396            SeedQuerySetting::Always => {
1397                let (range, kind) = snapshot.surrounding_word(selection.start, true);
1398                if kind == Some(CharKind::Word) {
1399                    let text: String = snapshot.text_for_range(range).collect();
1400                    if !text.trim().is_empty() {
1401                        return text;
1402                    }
1403                }
1404                String::new()
1405            }
1406        }
1407    }
1408
1409    fn activate_match(
1410        &mut self,
1411        index: usize,
1412        matches: &[Range<Anchor>],
1413        window: &mut Window,
1414        cx: &mut Context<Self>,
1415    ) {
1416        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1417        let range = self.range_for_match(&matches[index]);
1418        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1419            s.select_ranges([range]);
1420        })
1421    }
1422
1423    fn select_matches(
1424        &mut self,
1425        matches: &[Self::Match],
1426        window: &mut Window,
1427        cx: &mut Context<Self>,
1428    ) {
1429        self.unfold_ranges(matches, false, false, cx);
1430        self.change_selections(None, window, cx, |s| {
1431            s.select_ranges(matches.iter().cloned())
1432        });
1433    }
1434    fn replace(
1435        &mut self,
1436        identifier: &Self::Match,
1437        query: &SearchQuery,
1438        window: &mut Window,
1439        cx: &mut Context<Self>,
1440    ) {
1441        let text = self.buffer.read(cx);
1442        let text = text.snapshot(cx);
1443        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1444        let text: Cow<_> = if text.len() == 1 {
1445            text.first().cloned().unwrap().into()
1446        } else {
1447            let joined_chunks = text.join("");
1448            joined_chunks.into()
1449        };
1450
1451        if let Some(replacement) = query.replacement_for(&text) {
1452            self.transact(window, cx, |this, _, cx| {
1453                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1454            });
1455        }
1456    }
1457    fn replace_all(
1458        &mut self,
1459        matches: &mut dyn Iterator<Item = &Self::Match>,
1460        query: &SearchQuery,
1461        window: &mut Window,
1462        cx: &mut Context<Self>,
1463    ) {
1464        let text = self.buffer.read(cx);
1465        let text = text.snapshot(cx);
1466        let mut edits = vec![];
1467        for m in matches {
1468            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1469            let text: Cow<_> = if text.len() == 1 {
1470                text.first().cloned().unwrap().into()
1471            } else {
1472                let joined_chunks = text.join("");
1473                joined_chunks.into()
1474            };
1475
1476            if let Some(replacement) = query.replacement_for(&text) {
1477                edits.push((m.clone(), Arc::from(&*replacement)));
1478            }
1479        }
1480
1481        if !edits.is_empty() {
1482            self.transact(window, cx, |this, _, cx| {
1483                this.edit(edits, cx);
1484            });
1485        }
1486    }
1487    fn match_index_for_direction(
1488        &mut self,
1489        matches: &[Range<Anchor>],
1490        current_index: usize,
1491        direction: Direction,
1492        count: usize,
1493        _: &mut Window,
1494        cx: &mut Context<Self>,
1495    ) -> usize {
1496        let buffer = self.buffer().read(cx).snapshot(cx);
1497        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1498            self.selections.newest_anchor().head()
1499        } else {
1500            matches[current_index].start
1501        };
1502
1503        let mut count = count % matches.len();
1504        if count == 0 {
1505            return current_index;
1506        }
1507        match direction {
1508            Direction::Next => {
1509                if matches[current_index]
1510                    .start
1511                    .cmp(&current_index_position, &buffer)
1512                    .is_gt()
1513                {
1514                    count -= 1
1515                }
1516
1517                (current_index + count) % matches.len()
1518            }
1519            Direction::Prev => {
1520                if matches[current_index]
1521                    .end
1522                    .cmp(&current_index_position, &buffer)
1523                    .is_lt()
1524                {
1525                    count -= 1;
1526                }
1527
1528                if current_index >= count {
1529                    current_index - count
1530                } else {
1531                    matches.len() - (count - current_index)
1532                }
1533            }
1534        }
1535    }
1536
1537    fn find_matches(
1538        &mut self,
1539        query: Arc<project::search::SearchQuery>,
1540        _: &mut Window,
1541        cx: &mut Context<Self>,
1542    ) -> Task<Vec<Range<Anchor>>> {
1543        let buffer = self.buffer().read(cx).snapshot(cx);
1544        let search_within_ranges = self
1545            .background_highlights
1546            .get(&TypeId::of::<SearchWithinRange>())
1547            .map_or(vec![], |(_color, ranges)| {
1548                ranges.iter().cloned().collect::<Vec<_>>()
1549            });
1550
1551        cx.background_spawn(async move {
1552            let mut ranges = Vec::new();
1553
1554            let search_within_ranges = if search_within_ranges.is_empty() {
1555                vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1556            } else {
1557                search_within_ranges
1558            };
1559
1560            for range in search_within_ranges {
1561                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1562                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1563                {
1564                    ranges.extend(
1565                        query
1566                            .search(search_buffer, Some(search_range.clone()))
1567                            .await
1568                            .into_iter()
1569                            .map(|match_range| {
1570                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1571                                    let start = search_buffer
1572                                        .anchor_after(search_range.start + match_range.start);
1573                                    let end = search_buffer
1574                                        .anchor_before(search_range.start + match_range.end);
1575                                    Anchor {
1576                                        diff_base_anchor: Some(start),
1577                                        ..deleted_hunk_anchor
1578                                    }..Anchor {
1579                                        diff_base_anchor: Some(end),
1580                                        ..deleted_hunk_anchor
1581                                    }
1582                                } else {
1583                                    let start = search_buffer
1584                                        .anchor_after(search_range.start + match_range.start);
1585                                    let end = search_buffer
1586                                        .anchor_before(search_range.start + match_range.end);
1587                                    Anchor::range_in_buffer(
1588                                        excerpt_id,
1589                                        search_buffer.remote_id(),
1590                                        start..end,
1591                                    )
1592                                }
1593                            }),
1594                    );
1595                }
1596            }
1597
1598            ranges
1599        })
1600    }
1601
1602    fn active_match_index(
1603        &mut self,
1604        direction: Direction,
1605        matches: &[Range<Anchor>],
1606        _: &mut Window,
1607        cx: &mut Context<Self>,
1608    ) -> Option<usize> {
1609        active_match_index(
1610            direction,
1611            matches,
1612            &self.selections.newest_anchor().head(),
1613            &self.buffer().read(cx).snapshot(cx),
1614        )
1615    }
1616
1617    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1618        self.expect_bounds_change = self.last_bounds;
1619    }
1620}
1621
1622pub fn active_match_index(
1623    direction: Direction,
1624    ranges: &[Range<Anchor>],
1625    cursor: &Anchor,
1626    buffer: &MultiBufferSnapshot,
1627) -> Option<usize> {
1628    if ranges.is_empty() {
1629        None
1630    } else {
1631        let r = ranges.binary_search_by(|probe| {
1632            if probe.end.cmp(cursor, buffer).is_lt() {
1633                Ordering::Less
1634            } else if probe.start.cmp(cursor, buffer).is_gt() {
1635                Ordering::Greater
1636            } else {
1637                Ordering::Equal
1638            }
1639        });
1640        match direction {
1641            Direction::Prev => match r {
1642                Ok(i) => Some(i),
1643                Err(i) => Some(i.saturating_sub(1)),
1644            },
1645            Direction::Next => match r {
1646                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1647            },
1648        }
1649    }
1650}
1651
1652pub fn entry_label_color(selected: bool) -> Color {
1653    if selected {
1654        Color::Default
1655    } else {
1656        Color::Muted
1657    }
1658}
1659
1660pub fn entry_diagnostic_aware_icon_name_and_color(
1661    diagnostic_severity: Option<DiagnosticSeverity>,
1662) -> Option<(IconName, Color)> {
1663    match diagnostic_severity {
1664        Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1665        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1666        _ => None,
1667    }
1668}
1669
1670pub fn entry_diagnostic_aware_icon_decoration_and_color(
1671    diagnostic_severity: Option<DiagnosticSeverity>,
1672) -> Option<(IconDecorationKind, Color)> {
1673    match diagnostic_severity {
1674        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1675        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1676        _ => None,
1677    }
1678}
1679
1680pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1681    let tracked = git_status.index + git_status.worktree;
1682    if ignored {
1683        Color::Ignored
1684    } else if git_status.conflict > 0 {
1685        Color::Conflict
1686    } else if tracked.modified > 0 {
1687        Color::Modified
1688    } else if tracked.added > 0 || git_status.untracked > 0 {
1689        Color::Created
1690    } else {
1691        entry_label_color(selected)
1692    }
1693}
1694
1695fn path_for_buffer<'a>(
1696    buffer: &Entity<MultiBuffer>,
1697    height: usize,
1698    include_filename: bool,
1699    cx: &'a App,
1700) -> Option<Cow<'a, Path>> {
1701    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1702    path_for_file(file.as_ref(), height, include_filename, cx)
1703}
1704
1705fn path_for_file<'a>(
1706    file: &'a dyn language::File,
1707    mut height: usize,
1708    include_filename: bool,
1709    cx: &'a App,
1710) -> Option<Cow<'a, Path>> {
1711    // Ensure we always render at least the filename.
1712    height += 1;
1713
1714    let mut prefix = file.path().as_ref();
1715    while height > 0 {
1716        if let Some(parent) = prefix.parent() {
1717            prefix = parent;
1718            height -= 1;
1719        } else {
1720            break;
1721        }
1722    }
1723
1724    // Here we could have just always used `full_path`, but that is very
1725    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1726    // traversed all the way up to the worktree's root.
1727    if height > 0 {
1728        let full_path = file.full_path(cx);
1729        if include_filename {
1730            Some(full_path.into())
1731        } else {
1732            Some(full_path.parent()?.to_path_buf().into())
1733        }
1734    } else {
1735        let mut path = file.path().strip_prefix(prefix).ok()?;
1736        if !include_filename {
1737            path = path.parent()?;
1738        }
1739        Some(path.into())
1740    }
1741}
1742
1743#[cfg(test)]
1744mod tests {
1745    use crate::editor_tests::init_test;
1746    use fs::Fs;
1747
1748    use super::*;
1749    use fs::MTime;
1750    use gpui::{App, VisualTestContext};
1751    use language::{LanguageMatcher, TestFile};
1752    use project::FakeFs;
1753    use std::path::{Path, PathBuf};
1754    use util::path;
1755
1756    #[gpui::test]
1757    fn test_path_for_file(cx: &mut App) {
1758        let file = TestFile {
1759            path: Path::new("").into(),
1760            root_name: String::new(),
1761            local_root: None,
1762        };
1763        assert_eq!(path_for_file(&file, 0, false, cx), None);
1764    }
1765
1766    async fn deserialize_editor(
1767        item_id: ItemId,
1768        workspace_id: WorkspaceId,
1769        workspace: Entity<Workspace>,
1770        project: Entity<Project>,
1771        cx: &mut VisualTestContext,
1772    ) -> Entity<Editor> {
1773        workspace
1774            .update_in(cx, |workspace, window, cx| {
1775                let pane = workspace.active_pane();
1776                pane.update(cx, |_, cx| {
1777                    Editor::deserialize(
1778                        project.clone(),
1779                        workspace.weak_handle(),
1780                        workspace_id,
1781                        item_id,
1782                        window,
1783                        cx,
1784                    )
1785                })
1786            })
1787            .await
1788            .unwrap()
1789    }
1790
1791    fn rust_language() -> Arc<language::Language> {
1792        Arc::new(language::Language::new(
1793            language::LanguageConfig {
1794                name: "Rust".into(),
1795                matcher: LanguageMatcher {
1796                    path_suffixes: vec!["rs".to_string()],
1797                    ..Default::default()
1798                },
1799                ..Default::default()
1800            },
1801            Some(tree_sitter_rust::LANGUAGE.into()),
1802        ))
1803    }
1804
1805    #[gpui::test]
1806    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1807        init_test(cx, |_| {});
1808
1809        let fs = FakeFs::new(cx.executor());
1810        fs.insert_file(path!("/file.rs"), Default::default()).await;
1811
1812        // Test case 1: Deserialize with path and contents
1813        {
1814            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1815            let (workspace, cx) =
1816                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1817            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1818            let item_id = 1234 as ItemId;
1819            let mtime = fs
1820                .metadata(Path::new(path!("/file.rs")))
1821                .await
1822                .unwrap()
1823                .unwrap()
1824                .mtime;
1825
1826            let serialized_editor = SerializedEditor {
1827                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1828                contents: Some("fn main() {}".to_string()),
1829                language: Some("Rust".to_string()),
1830                mtime: Some(mtime),
1831            };
1832
1833            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1834                .await
1835                .unwrap();
1836
1837            let deserialized =
1838                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1839
1840            deserialized.update(cx, |editor, cx| {
1841                assert_eq!(editor.text(cx), "fn main() {}");
1842                assert!(editor.is_dirty(cx));
1843                assert!(!editor.has_conflict(cx));
1844                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1845                assert!(buffer.file().is_some());
1846            });
1847        }
1848
1849        // Test case 2: Deserialize with only path
1850        {
1851            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1852            let (workspace, cx) =
1853                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1854
1855            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1856
1857            let item_id = 5678 as ItemId;
1858            let serialized_editor = SerializedEditor {
1859                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1860                contents: None,
1861                language: None,
1862                mtime: None,
1863            };
1864
1865            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1866                .await
1867                .unwrap();
1868
1869            let deserialized =
1870                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1871
1872            deserialized.update(cx, |editor, cx| {
1873                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1874                assert!(!editor.is_dirty(cx));
1875                assert!(!editor.has_conflict(cx));
1876
1877                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1878                assert!(buffer.file().is_some());
1879            });
1880        }
1881
1882        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1883        {
1884            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1885            // Add Rust to the language, so that we can restore the language of the buffer
1886            project.update(cx, |project, _| project.languages().add(rust_language()));
1887
1888            let (workspace, cx) =
1889                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1890
1891            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1892
1893            let item_id = 9012 as ItemId;
1894            let serialized_editor = SerializedEditor {
1895                abs_path: None,
1896                contents: Some("hello".to_string()),
1897                language: Some("Rust".to_string()),
1898                mtime: None,
1899            };
1900
1901            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1902                .await
1903                .unwrap();
1904
1905            let deserialized =
1906                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1907
1908            deserialized.update(cx, |editor, cx| {
1909                assert_eq!(editor.text(cx), "hello");
1910                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
1911
1912                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1913                assert_eq!(
1914                    buffer.language().map(|lang| lang.name()),
1915                    Some("Rust".into())
1916                ); // Language should be set to Rust
1917                assert!(buffer.file().is_none()); // The buffer should not have an associated file
1918            });
1919        }
1920
1921        // Test case 4: Deserialize with path, content, and old mtime
1922        {
1923            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1924            let (workspace, cx) =
1925                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1926
1927            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1928
1929            let item_id = 9345 as ItemId;
1930            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
1931            let serialized_editor = SerializedEditor {
1932                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1933                contents: Some("fn main() {}".to_string()),
1934                language: Some("Rust".to_string()),
1935                mtime: Some(old_mtime),
1936            };
1937
1938            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1939                .await
1940                .unwrap();
1941
1942            let deserialized =
1943                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1944
1945            deserialized.update(cx, |editor, cx| {
1946                assert_eq!(editor.text(cx), "fn main() {}");
1947                assert!(editor.has_conflict(cx)); // The editor should have a conflict
1948            });
1949        }
1950    }
1951}