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