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