1use crate::{
2 Anchor, Autoscroll, BufferSerialization, Editor, EditorEvent, EditorSettings, ExcerptId,
3 ExcerptRange, FormatTarget, MultiBuffer, MultiBufferSnapshot, NavigationData,
4 ReportEditorEvent, SearchWithinRange, 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 can_split(&self) -> bool {
761 true
762 }
763
764 fn clone_on_split(
765 &self,
766 _workspace_id: Option<WorkspaceId>,
767 window: &mut Window,
768 cx: &mut Context<Self>,
769 ) -> Task<Option<Entity<Editor>>>
770 where
771 Self: Sized,
772 {
773 Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
774 }
775
776 fn set_nav_history(
777 &mut self,
778 history: ItemNavHistory,
779 _window: &mut Window,
780 _: &mut Context<Self>,
781 ) {
782 self.nav_history = Some(history);
783 }
784
785 fn on_removed(&self, cx: &App) {
786 self.report_editor_event(ReportEditorEvent::Closed, None, cx);
787 }
788
789 fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
790 let selection = self.selections.newest_anchor();
791 self.push_to_nav_history(selection.head(), None, true, false, cx);
792 }
793
794 fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
795 self.hide_hovered_link(cx);
796 }
797
798 fn is_dirty(&self, cx: &App) -> bool {
799 self.buffer().read(cx).read(cx).is_dirty()
800 }
801
802 fn has_deleted_file(&self, cx: &App) -> bool {
803 self.buffer().read(cx).read(cx).has_deleted_file()
804 }
805
806 fn has_conflict(&self, cx: &App) -> bool {
807 self.buffer().read(cx).read(cx).has_conflict()
808 }
809
810 fn can_save(&self, cx: &App) -> bool {
811 let buffer = &self.buffer().read(cx);
812 if let Some(buffer) = buffer.as_singleton() {
813 buffer.read(cx).project_path(cx).is_some()
814 } else {
815 true
816 }
817 }
818
819 fn save(
820 &mut self,
821 options: SaveOptions,
822 project: Entity<Project>,
823 window: &mut Window,
824 cx: &mut Context<Self>,
825 ) -> Task<Result<()>> {
826 // Add meta data tracking # of auto saves
827 if options.autosave {
828 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
829 } else {
830 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
831 }
832
833 let buffers = self.buffer().clone().read(cx).all_buffers();
834 let buffers = buffers
835 .into_iter()
836 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
837 .collect::<HashSet<_>>();
838
839 // let mut buffers_to_save =
840 let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
841 buffers
842 } else {
843 buffers
844 .into_iter()
845 .filter(|buffer| buffer.read(cx).is_dirty())
846 .collect()
847 };
848
849 cx.spawn_in(window, async move |this, cx| {
850 if options.format {
851 this.update_in(cx, |editor, window, cx| {
852 editor.perform_format(
853 project.clone(),
854 FormatTrigger::Save,
855 FormatTarget::Buffers(buffers_to_save.clone()),
856 window,
857 cx,
858 )
859 })?
860 .await?;
861 }
862
863 if !buffers_to_save.is_empty() {
864 project
865 .update(cx, |project, cx| {
866 project.save_buffers(buffers_to_save.clone(), cx)
867 })?
868 .await?;
869 }
870
871 Ok(())
872 })
873 }
874
875 fn save_as(
876 &mut self,
877 project: Entity<Project>,
878 path: ProjectPath,
879 _: &mut Window,
880 cx: &mut Context<Self>,
881 ) -> Task<Result<()>> {
882 let buffer = self
883 .buffer()
884 .read(cx)
885 .as_singleton()
886 .expect("cannot call save_as on an excerpt list");
887
888 let file_extension = path.path.extension().map(|a| a.to_string());
889 self.report_editor_event(
890 ReportEditorEvent::Saved { auto_saved: false },
891 file_extension,
892 cx,
893 );
894
895 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
896 }
897
898 fn reload(
899 &mut self,
900 project: Entity<Project>,
901 window: &mut Window,
902 cx: &mut Context<Self>,
903 ) -> Task<Result<()>> {
904 let buffer = self.buffer().clone();
905 let buffers = self.buffer.read(cx).all_buffers();
906 let reload_buffers =
907 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
908 cx.spawn_in(window, async move |this, cx| {
909 let transaction = reload_buffers.log_err().await;
910 this.update(cx, |editor, cx| {
911 editor.request_autoscroll(Autoscroll::fit(), cx)
912 })?;
913 buffer
914 .update(cx, |buffer, cx| {
915 if let Some(transaction) = transaction
916 && !buffer.is_singleton()
917 {
918 buffer.push_transaction(&transaction.0, cx);
919 }
920 })
921 .ok();
922 Ok(())
923 })
924 }
925
926 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
927 Some(Box::new(handle.clone()))
928 }
929
930 fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
931 self.pixel_position_of_newest_cursor
932 }
933
934 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
935 if self.show_breadcrumbs {
936 ToolbarItemLocation::PrimaryLeft
937 } else {
938 ToolbarItemLocation::Hidden
939 }
940 }
941
942 fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
943 let cursor = self.selections.newest_anchor().head();
944 let multibuffer = &self.buffer().read(cx);
945 let (buffer_id, symbols) = multibuffer
946 .read(cx)
947 .symbols_containing(cursor, Some(variant.syntax()))?;
948 let buffer = multibuffer.buffer(buffer_id)?;
949
950 let buffer = buffer.read(cx);
951 let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
952 buffer
953 .snapshot()
954 .resolve_file_path(
955 self.project
956 .as_ref()
957 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
958 .unwrap_or_default(),
959 cx,
960 )
961 .unwrap_or_else(|| {
962 if multibuffer.is_singleton() {
963 multibuffer.title(cx).to_string()
964 } else {
965 "untitled".to_string()
966 }
967 })
968 });
969
970 let settings = ThemeSettings::get_global(cx);
971
972 let mut breadcrumbs = vec![BreadcrumbText {
973 text,
974 highlights: None,
975 font: Some(settings.buffer_font.clone()),
976 }];
977
978 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
979 text: symbol.text,
980 highlights: Some(symbol.highlight_ranges),
981 font: Some(settings.buffer_font.clone()),
982 }));
983 Some(breadcrumbs)
984 }
985
986 fn added_to_workspace(
987 &mut self,
988 workspace: &mut Workspace,
989 _window: &mut Window,
990 cx: &mut Context<Self>,
991 ) {
992 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
993 if let Some(workspace) = &workspace.weak_handle().upgrade() {
994 cx.subscribe(workspace, |editor, _, event: &workspace::Event, _cx| {
995 if let workspace::Event::ModalOpened = event {
996 editor.mouse_context_menu.take();
997 editor.inline_blame_popover.take();
998 }
999 })
1000 .detach();
1001 }
1002 }
1003
1004 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
1005 match event {
1006 EditorEvent::Saved | EditorEvent::TitleChanged => {
1007 f(ItemEvent::UpdateTab);
1008 f(ItemEvent::UpdateBreadcrumbs);
1009 }
1010
1011 EditorEvent::Reparsed(_) => {
1012 f(ItemEvent::UpdateBreadcrumbs);
1013 }
1014
1015 EditorEvent::SelectionsChanged { local } if *local => {
1016 f(ItemEvent::UpdateBreadcrumbs);
1017 }
1018
1019 EditorEvent::BreadcrumbsChanged => {
1020 f(ItemEvent::UpdateBreadcrumbs);
1021 }
1022
1023 EditorEvent::DirtyChanged => {
1024 f(ItemEvent::UpdateTab);
1025 }
1026
1027 EditorEvent::BufferEdited => {
1028 f(ItemEvent::Edit);
1029 f(ItemEvent::UpdateBreadcrumbs);
1030 }
1031
1032 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
1033 f(ItemEvent::Edit);
1034 }
1035
1036 _ => {}
1037 }
1038 }
1039
1040 fn preserve_preview(&self, cx: &App) -> bool {
1041 self.buffer.read(cx).preserve_preview(cx)
1042 }
1043}
1044
1045impl SerializableItem for Editor {
1046 fn serialized_item_kind() -> &'static str {
1047 "Editor"
1048 }
1049
1050 fn cleanup(
1051 workspace_id: WorkspaceId,
1052 alive_items: Vec<ItemId>,
1053 _window: &mut Window,
1054 cx: &mut App,
1055 ) -> Task<Result<()>> {
1056 workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1057 }
1058
1059 fn deserialize(
1060 project: Entity<Project>,
1061 workspace: WeakEntity<Workspace>,
1062 workspace_id: workspace::WorkspaceId,
1063 item_id: ItemId,
1064 window: &mut Window,
1065 cx: &mut App,
1066 ) -> Task<Result<Entity<Self>>> {
1067 let serialized_editor = match DB
1068 .get_serialized_editor(item_id, workspace_id)
1069 .context("Failed to query editor state")
1070 {
1071 Ok(Some(serialized_editor)) => {
1072 if ProjectSettings::get_global(cx)
1073 .session
1074 .restore_unsaved_buffers
1075 {
1076 serialized_editor
1077 } else {
1078 SerializedEditor {
1079 abs_path: serialized_editor.abs_path,
1080 contents: None,
1081 language: None,
1082 mtime: None,
1083 }
1084 }
1085 }
1086 Ok(None) => {
1087 return Task::ready(Err(anyhow!(
1088 "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1089 )));
1090 }
1091 Err(error) => {
1092 return Task::ready(Err(error));
1093 }
1094 };
1095 log::debug!(
1096 "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1097 );
1098
1099 match serialized_editor {
1100 SerializedEditor {
1101 abs_path: None,
1102 contents: Some(contents),
1103 language,
1104 ..
1105 } => window.spawn(cx, {
1106 let project = project.clone();
1107 async move |cx| {
1108 let language_registry =
1109 project.read_with(cx, |project, _| project.languages().clone())?;
1110
1111 let language = if let Some(language_name) = language {
1112 // We don't fail here, because we'd rather not set the language if the name changed
1113 // than fail to restore the buffer.
1114 language_registry
1115 .language_for_name(&language_name)
1116 .await
1117 .ok()
1118 } else {
1119 None
1120 };
1121
1122 // First create the empty buffer
1123 let buffer = project
1124 .update(cx, |project, cx| project.create_buffer(true, cx))?
1125 .await
1126 .context("Failed to create buffer while deserializing editor")?;
1127
1128 // Then set the text so that the dirty bit is set correctly
1129 buffer.update(cx, |buffer, cx| {
1130 buffer.set_language_registry(language_registry);
1131 if let Some(language) = language {
1132 buffer.set_language(Some(language), cx);
1133 }
1134 buffer.set_text(contents, cx);
1135 if let Some(entry) = buffer.peek_undo_stack() {
1136 buffer.forget_transaction(entry.transaction_id());
1137 }
1138 })?;
1139
1140 cx.update(|window, cx| {
1141 cx.new(|cx| {
1142 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1143
1144 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1145 editor
1146 })
1147 })
1148 }
1149 }),
1150 SerializedEditor {
1151 abs_path: Some(abs_path),
1152 contents,
1153 mtime,
1154 ..
1155 } => {
1156 let opened_buffer = project.update(cx, |project, cx| {
1157 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1158 let project_path = ProjectPath {
1159 worktree_id: worktree.read(cx).id(),
1160 path: path,
1161 };
1162 Some(project.open_path(project_path, cx))
1163 });
1164
1165 match opened_buffer {
1166 Some(opened_buffer) => {
1167 window.spawn(cx, async move |cx| {
1168 let (_, buffer) = opened_buffer
1169 .await
1170 .context("Failed to open path in project")?;
1171
1172 // This is a bit wasteful: we're loading the whole buffer from
1173 // disk and then overwrite the content.
1174 // But for now, it keeps the implementation of the content serialization
1175 // simple, because we don't have to persist all of the metadata that we get
1176 // by loading the file (git diff base, ...).
1177 if let Some(buffer_text) = contents {
1178 buffer.update(cx, |buffer, cx| {
1179 // If we did restore an mtime, we want to store it on the buffer
1180 // so that the next edit will mark the buffer as dirty/conflicted.
1181 if mtime.is_some() {
1182 buffer.did_reload(
1183 buffer.version(),
1184 buffer.line_ending(),
1185 mtime,
1186 cx,
1187 );
1188 }
1189 buffer.set_text(buffer_text, cx);
1190 if let Some(entry) = buffer.peek_undo_stack() {
1191 buffer.forget_transaction(entry.transaction_id());
1192 }
1193 })?;
1194 }
1195
1196 cx.update(|window, cx| {
1197 cx.new(|cx| {
1198 let mut editor =
1199 Editor::for_buffer(buffer, Some(project), window, cx);
1200
1201 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1202 editor
1203 })
1204 })
1205 })
1206 }
1207 None => {
1208 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1209 workspace.open_abs_path(
1210 abs_path.clone(),
1211 OpenOptions {
1212 visible: Some(OpenVisible::None),
1213 ..Default::default()
1214 },
1215 window,
1216 cx,
1217 )
1218 });
1219 window.spawn(cx, async move |cx| {
1220 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1221 editor.update_in(cx, |editor, window, cx| {
1222 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1223 })?;
1224 Ok(editor)
1225 })
1226 }
1227 }
1228 }
1229 SerializedEditor {
1230 abs_path: None,
1231 contents: None,
1232 ..
1233 } => window.spawn(cx, async move |cx| {
1234 let buffer = project
1235 .update(cx, |project, cx| project.create_buffer(true, cx))?
1236 .await
1237 .context("Failed to create buffer")?;
1238
1239 cx.update(|window, cx| {
1240 cx.new(|cx| {
1241 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1242
1243 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1244 editor
1245 })
1246 })
1247 }),
1248 }
1249 }
1250
1251 fn serialize(
1252 &mut self,
1253 workspace: &mut Workspace,
1254 item_id: ItemId,
1255 closing: bool,
1256 window: &mut Window,
1257 cx: &mut Context<Self>,
1258 ) -> Option<Task<Result<()>>> {
1259 let buffer_serialization = self.buffer_serialization?;
1260 let project = self.project.clone()?;
1261
1262 let serialize_dirty_buffers = match buffer_serialization {
1263 // If we don't have a worktree, we don't serialize, because
1264 // projects without worktrees aren't deserialized.
1265 BufferSerialization::All => project.read(cx).visible_worktrees(cx).next().is_some(),
1266 BufferSerialization::NonDirtyBuffers => false,
1267 };
1268
1269 if closing && !serialize_dirty_buffers {
1270 return None;
1271 }
1272
1273 let workspace_id = workspace.database_id()?;
1274
1275 let buffer = self.buffer().read(cx).as_singleton()?;
1276
1277 let abs_path = buffer.read(cx).file().and_then(|file| {
1278 let worktree_id = file.worktree_id(cx);
1279 project
1280 .read(cx)
1281 .worktree_for_id(worktree_id, cx)
1282 .map(|worktree| worktree.read(cx).absolutize(file.path()))
1283 .or_else(|| {
1284 let full_path = file.full_path(cx);
1285 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1286 project.read(cx).absolute_path(&project_path, cx)
1287 })
1288 });
1289
1290 let is_dirty = buffer.read(cx).is_dirty();
1291 let mtime = buffer.read(cx).saved_mtime();
1292
1293 let snapshot = buffer.read(cx).snapshot();
1294
1295 Some(cx.spawn_in(window, async move |_this, cx| {
1296 cx.background_spawn(async move {
1297 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1298 let contents = snapshot.text();
1299 let language = snapshot.language().map(|lang| lang.name().to_string());
1300 (Some(contents), language)
1301 } else {
1302 (None, None)
1303 };
1304
1305 let editor = SerializedEditor {
1306 abs_path,
1307 contents,
1308 language,
1309 mtime,
1310 };
1311 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1312 DB.save_serialized_editor(item_id, workspace_id, editor)
1313 .await
1314 .context("failed to save serialized editor")
1315 })
1316 .await
1317 .context("failed to save contents of buffer")?;
1318
1319 Ok(())
1320 }))
1321 }
1322
1323 fn should_serialize(&self, event: &Self::Event) -> bool {
1324 self.should_serialize_buffer()
1325 && matches!(
1326 event,
1327 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1328 )
1329 }
1330}
1331
1332#[derive(Debug, Default)]
1333struct EditorRestorationData {
1334 entries: HashMap<PathBuf, RestorationData>,
1335}
1336
1337#[derive(Default, Debug)]
1338pub struct RestorationData {
1339 pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1340 pub folds: Vec<Range<Point>>,
1341 pub selections: Vec<Range<Point>>,
1342}
1343
1344impl ProjectItem for Editor {
1345 type Item = Buffer;
1346
1347 fn project_item_kind() -> Option<ProjectItemKind> {
1348 Some(ProjectItemKind("Editor"))
1349 }
1350
1351 fn for_project_item(
1352 project: Entity<Project>,
1353 pane: Option<&Pane>,
1354 buffer: Entity<Buffer>,
1355 window: &mut Window,
1356 cx: &mut Context<Self>,
1357 ) -> Self {
1358 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1359 if let Some((excerpt_id, buffer_id, snapshot)) =
1360 editor.buffer().read(cx).snapshot(cx).as_singleton()
1361 && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1362 && let Some(restoration_data) = Self::project_item_kind()
1363 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1364 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1365 .and_then(|data| {
1366 let file = project::File::from_dyn(buffer.read(cx).file())?;
1367 data.entries.get(&file.abs_path(cx))
1368 })
1369 {
1370 editor.fold_ranges(
1371 clip_ranges(&restoration_data.folds, snapshot),
1372 false,
1373 window,
1374 cx,
1375 );
1376 if !restoration_data.selections.is_empty() {
1377 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1378 s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
1379 });
1380 }
1381 let (top_row, offset) = restoration_data.scroll_position;
1382 let anchor = Anchor::in_buffer(
1383 *excerpt_id,
1384 buffer_id,
1385 snapshot.anchor_before(Point::new(top_row, 0)),
1386 );
1387 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1388 }
1389
1390 editor
1391 }
1392
1393 fn for_broken_project_item(
1394 abs_path: &Path,
1395 is_local: bool,
1396 e: &anyhow::Error,
1397 window: &mut Window,
1398 cx: &mut App,
1399 ) -> Option<InvalidItemView> {
1400 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1401 }
1402}
1403
1404fn clip_ranges<'a>(
1405 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1406 snapshot: &'a BufferSnapshot,
1407) -> Vec<Range<Point>> {
1408 original
1409 .into_iter()
1410 .map(|range| {
1411 snapshot.clip_point(range.start, Bias::Left)
1412 ..snapshot.clip_point(range.end, Bias::Right)
1413 })
1414 .collect()
1415}
1416
1417impl EventEmitter<SearchEvent> for Editor {}
1418
1419impl Editor {
1420 pub fn update_restoration_data(
1421 &self,
1422 cx: &mut Context<Self>,
1423 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1424 ) {
1425 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1426 return;
1427 }
1428
1429 let editor = cx.entity();
1430 cx.defer(move |cx| {
1431 editor.update(cx, |editor, cx| {
1432 let kind = Editor::project_item_kind()?;
1433 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1434 let buffer = editor.buffer().read(cx).as_singleton()?;
1435 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1436 pane.update(cx, |pane, _| {
1437 let data = pane
1438 .project_item_restoration_data
1439 .entry(kind)
1440 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1441 let data = match data.downcast_mut::<EditorRestorationData>() {
1442 Some(data) => data,
1443 None => {
1444 *data = Box::new(EditorRestorationData::default());
1445 data.downcast_mut::<EditorRestorationData>()
1446 .expect("just written the type downcasted to")
1447 }
1448 };
1449
1450 let data = data.entries.entry(file_abs_path).or_default();
1451 write(data);
1452 Some(())
1453 })
1454 });
1455 });
1456 }
1457}
1458
1459pub(crate) enum BufferSearchHighlights {}
1460impl SearchableItem for Editor {
1461 type Match = Range<Anchor>;
1462
1463 fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1464 self.background_highlights
1465 .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1466 .map_or(Vec::new(), |(_color, ranges)| {
1467 ranges.iter().cloned().collect()
1468 })
1469 }
1470
1471 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1472 if self
1473 .clear_background_highlights::<BufferSearchHighlights>(cx)
1474 .is_some()
1475 {
1476 cx.emit(SearchEvent::MatchesInvalidated);
1477 }
1478 }
1479
1480 fn update_matches(
1481 &mut self,
1482 matches: &[Range<Anchor>],
1483 _: &mut Window,
1484 cx: &mut Context<Self>,
1485 ) {
1486 let existing_range = self
1487 .background_highlights
1488 .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1489 .map(|(_, range)| range.as_ref());
1490 let updated = existing_range != Some(matches);
1491 self.highlight_background::<BufferSearchHighlights>(
1492 matches,
1493 |theme| theme.colors().search_match_background,
1494 cx,
1495 );
1496 if updated {
1497 cx.emit(SearchEvent::MatchesInvalidated);
1498 }
1499 }
1500
1501 fn has_filtered_search_ranges(&mut self) -> bool {
1502 self.has_background_highlights::<SearchWithinRange>()
1503 }
1504
1505 fn toggle_filtered_search_ranges(
1506 &mut self,
1507 enabled: Option<FilteredSearchRange>,
1508 _: &mut Window,
1509 cx: &mut Context<Self>,
1510 ) {
1511 if self.has_filtered_search_ranges() {
1512 self.previous_search_ranges = self
1513 .clear_background_highlights::<SearchWithinRange>(cx)
1514 .map(|(_, ranges)| ranges)
1515 }
1516
1517 if let Some(range) = enabled {
1518 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1519
1520 if ranges.iter().any(|s| s.start != s.end) {
1521 self.set_search_within_ranges(&ranges, cx);
1522 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1523 && range != FilteredSearchRange::Selection
1524 {
1525 self.set_search_within_ranges(&previous_search_ranges, cx);
1526 }
1527 }
1528 }
1529
1530 fn supported_options(&self) -> SearchOptions {
1531 if self.in_project_search {
1532 SearchOptions {
1533 case: true,
1534 word: true,
1535 regex: true,
1536 replacement: false,
1537 selection: false,
1538 find_in_results: true,
1539 }
1540 } else {
1541 SearchOptions {
1542 case: true,
1543 word: true,
1544 regex: true,
1545 replacement: true,
1546 selection: true,
1547 find_in_results: false,
1548 }
1549 }
1550 }
1551
1552 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1553 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1554 let snapshot = self.snapshot(window, cx);
1555 let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1556 let buffer_snapshot = snapshot.buffer_snapshot();
1557
1558 match setting {
1559 SeedQuerySetting::Never => String::new(),
1560 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1561 let text: String = buffer_snapshot
1562 .text_for_range(selection.start..selection.end)
1563 .collect();
1564 if text.contains('\n') {
1565 String::new()
1566 } else {
1567 text
1568 }
1569 }
1570 SeedQuerySetting::Selection => String::new(),
1571 SeedQuerySetting::Always => {
1572 let (range, kind) = buffer_snapshot
1573 .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1574 if kind == Some(CharKind::Word) {
1575 let text: String = buffer_snapshot.text_for_range(range).collect();
1576 if !text.trim().is_empty() {
1577 return text;
1578 }
1579 }
1580 String::new()
1581 }
1582 }
1583 }
1584
1585 fn activate_match(
1586 &mut self,
1587 index: usize,
1588 matches: &[Range<Anchor>],
1589 collapse: bool,
1590 window: &mut Window,
1591 cx: &mut Context<Self>,
1592 ) {
1593 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1594 let range = self.range_for_match(&matches[index], collapse);
1595 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1596 Autoscroll::center()
1597 } else {
1598 Autoscroll::fit()
1599 };
1600 self.change_selections(SelectionEffects::scroll(autoscroll), window, cx, |s| {
1601 s.select_ranges([range]);
1602 })
1603 }
1604
1605 fn select_matches(
1606 &mut self,
1607 matches: &[Self::Match],
1608 window: &mut Window,
1609 cx: &mut Context<Self>,
1610 ) {
1611 self.unfold_ranges(matches, false, false, cx);
1612 self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1613 s.select_ranges(matches.iter().cloned())
1614 });
1615 }
1616 fn replace(
1617 &mut self,
1618 identifier: &Self::Match,
1619 query: &SearchQuery,
1620 window: &mut Window,
1621 cx: &mut Context<Self>,
1622 ) {
1623 let text = self.buffer.read(cx);
1624 let text = text.snapshot(cx);
1625 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1626 let text: Cow<_> = if text.len() == 1 {
1627 text.first().cloned().unwrap().into()
1628 } else {
1629 let joined_chunks = text.join("");
1630 joined_chunks.into()
1631 };
1632
1633 if let Some(replacement) = query.replacement_for(&text) {
1634 self.transact(window, cx, |this, _, cx| {
1635 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1636 });
1637 }
1638 }
1639 fn replace_all(
1640 &mut self,
1641 matches: &mut dyn Iterator<Item = &Self::Match>,
1642 query: &SearchQuery,
1643 window: &mut Window,
1644 cx: &mut Context<Self>,
1645 ) {
1646 let text = self.buffer.read(cx);
1647 let text = text.snapshot(cx);
1648 let mut edits = vec![];
1649
1650 for m in matches {
1651 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1652
1653 let text: Cow<_> = if text.len() == 1 {
1654 text.first().cloned().unwrap().into()
1655 } else {
1656 let joined_chunks = text.join("");
1657 joined_chunks.into()
1658 };
1659
1660 if let Some(replacement) = query.replacement_for(&text) {
1661 edits.push((m.clone(), Arc::from(&*replacement)));
1662 }
1663 }
1664
1665 if !edits.is_empty() {
1666 self.transact(window, cx, |this, _, cx| {
1667 this.edit(edits, cx);
1668 });
1669 }
1670 }
1671 fn match_index_for_direction(
1672 &mut self,
1673 matches: &[Range<Anchor>],
1674 current_index: usize,
1675 direction: Direction,
1676 count: usize,
1677 _: &mut Window,
1678 cx: &mut Context<Self>,
1679 ) -> usize {
1680 let buffer = self.buffer().read(cx).snapshot(cx);
1681 let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1682 self.selections.newest_anchor().head()
1683 } else {
1684 matches[current_index].start
1685 };
1686
1687 let mut count = count % matches.len();
1688 if count == 0 {
1689 return current_index;
1690 }
1691 match direction {
1692 Direction::Next => {
1693 if matches[current_index]
1694 .start
1695 .cmp(¤t_index_position, &buffer)
1696 .is_gt()
1697 {
1698 count -= 1
1699 }
1700
1701 (current_index + count) % matches.len()
1702 }
1703 Direction::Prev => {
1704 if matches[current_index]
1705 .end
1706 .cmp(¤t_index_position, &buffer)
1707 .is_lt()
1708 {
1709 count -= 1;
1710 }
1711
1712 if current_index >= count {
1713 current_index - count
1714 } else {
1715 matches.len() - (count - current_index)
1716 }
1717 }
1718 }
1719 }
1720
1721 fn find_matches(
1722 &mut self,
1723 query: Arc<project::search::SearchQuery>,
1724 _: &mut Window,
1725 cx: &mut Context<Self>,
1726 ) -> Task<Vec<Range<Anchor>>> {
1727 let buffer = self.buffer().read(cx).snapshot(cx);
1728 let search_within_ranges = self
1729 .background_highlights
1730 .get(&HighlightKey::Type(TypeId::of::<SearchWithinRange>()))
1731 .map_or(vec![], |(_color, ranges)| {
1732 ranges.iter().cloned().collect::<Vec<_>>()
1733 });
1734
1735 cx.background_spawn(async move {
1736 let mut ranges = Vec::new();
1737
1738 let search_within_ranges = if search_within_ranges.is_empty() {
1739 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1740 } else {
1741 search_within_ranges
1742 };
1743
1744 for range in search_within_ranges {
1745 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1746 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1747 {
1748 ranges.extend(
1749 query
1750 .search(search_buffer, Some(search_range.clone()))
1751 .await
1752 .into_iter()
1753 .map(|match_range| {
1754 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1755 let start = search_buffer
1756 .anchor_after(search_range.start + match_range.start);
1757 let end = search_buffer
1758 .anchor_before(search_range.start + match_range.end);
1759 deleted_hunk_anchor.with_diff_base_anchor(start)
1760 ..deleted_hunk_anchor.with_diff_base_anchor(end)
1761 } else {
1762 let start = search_buffer
1763 .anchor_after(search_range.start + match_range.start);
1764 let end = search_buffer
1765 .anchor_before(search_range.start + match_range.end);
1766 Anchor::range_in_buffer(
1767 excerpt_id,
1768 search_buffer.remote_id(),
1769 start..end,
1770 )
1771 }
1772 }),
1773 );
1774 }
1775 }
1776
1777 ranges
1778 })
1779 }
1780
1781 fn active_match_index(
1782 &mut self,
1783 direction: Direction,
1784 matches: &[Range<Anchor>],
1785 _: &mut Window,
1786 cx: &mut Context<Self>,
1787 ) -> Option<usize> {
1788 active_match_index(
1789 direction,
1790 matches,
1791 &self.selections.newest_anchor().head(),
1792 &self.buffer().read(cx).snapshot(cx),
1793 )
1794 }
1795
1796 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1797 self.expect_bounds_change = self.last_bounds;
1798 }
1799
1800 fn set_search_is_case_sensitive(
1801 &mut self,
1802 case_sensitive: Option<bool>,
1803 _cx: &mut Context<Self>,
1804 ) {
1805 self.select_next_is_case_sensitive = case_sensitive;
1806 }
1807}
1808
1809pub fn active_match_index(
1810 direction: Direction,
1811 ranges: &[Range<Anchor>],
1812 cursor: &Anchor,
1813 buffer: &MultiBufferSnapshot,
1814) -> Option<usize> {
1815 if ranges.is_empty() {
1816 None
1817 } else {
1818 let r = ranges.binary_search_by(|probe| {
1819 if probe.end.cmp(cursor, buffer).is_lt() {
1820 Ordering::Less
1821 } else if probe.start.cmp(cursor, buffer).is_gt() {
1822 Ordering::Greater
1823 } else {
1824 Ordering::Equal
1825 }
1826 });
1827 match direction {
1828 Direction::Prev => match r {
1829 Ok(i) => Some(i),
1830 Err(i) => Some(i.saturating_sub(1)),
1831 },
1832 Direction::Next => match r {
1833 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1834 },
1835 }
1836 }
1837}
1838
1839pub fn entry_label_color(selected: bool) -> Color {
1840 if selected {
1841 Color::Default
1842 } else {
1843 Color::Muted
1844 }
1845}
1846
1847pub fn entry_diagnostic_aware_icon_name_and_color(
1848 diagnostic_severity: Option<DiagnosticSeverity>,
1849) -> Option<(IconName, Color)> {
1850 match diagnostic_severity {
1851 Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1852 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1853 _ => None,
1854 }
1855}
1856
1857pub fn entry_diagnostic_aware_icon_decoration_and_color(
1858 diagnostic_severity: Option<DiagnosticSeverity>,
1859) -> Option<(IconDecorationKind, Color)> {
1860 match diagnostic_severity {
1861 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1862 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1863 _ => None,
1864 }
1865}
1866
1867pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1868 let tracked = git_status.index + git_status.worktree;
1869 if ignored {
1870 Color::Ignored
1871 } else if git_status.conflict > 0 {
1872 Color::Conflict
1873 } else if tracked.modified > 0 {
1874 Color::Modified
1875 } else if tracked.added > 0 || git_status.untracked > 0 {
1876 Color::Created
1877 } else {
1878 entry_label_color(selected)
1879 }
1880}
1881
1882fn path_for_buffer<'a>(
1883 buffer: &Entity<MultiBuffer>,
1884 height: usize,
1885 include_filename: bool,
1886 cx: &'a App,
1887) -> Option<Cow<'a, str>> {
1888 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1889 path_for_file(file.as_ref(), height, include_filename, cx)
1890}
1891
1892fn path_for_file<'a>(
1893 file: &'a dyn language::File,
1894 mut height: usize,
1895 include_filename: bool,
1896 cx: &'a App,
1897) -> Option<Cow<'a, str>> {
1898 // Ensure we always render at least the filename.
1899 height += 1;
1900
1901 let mut prefix = file.path().as_ref();
1902 while height > 0 {
1903 if let Some(parent) = prefix.parent() {
1904 prefix = parent;
1905 height -= 1;
1906 } else {
1907 break;
1908 }
1909 }
1910
1911 // The full_path method allocates, so avoid calling it if height is zero.
1912 if height > 0 {
1913 let mut full_path = file.full_path(cx);
1914 if !include_filename {
1915 if !full_path.pop() {
1916 return None;
1917 }
1918 }
1919 Some(full_path.to_string_lossy().into_owned().into())
1920 } else {
1921 let mut path = file.path().strip_prefix(prefix).ok()?;
1922 if !include_filename {
1923 path = path.parent()?;
1924 }
1925 Some(path.display(file.path_style(cx)))
1926 }
1927}
1928
1929#[cfg(test)]
1930mod tests {
1931 use crate::editor_tests::init_test;
1932 use fs::Fs;
1933
1934 use super::*;
1935 use fs::MTime;
1936 use gpui::{App, VisualTestContext};
1937 use language::{LanguageMatcher, TestFile};
1938 use project::FakeFs;
1939 use std::path::{Path, PathBuf};
1940 use util::{path, rel_path::RelPath};
1941
1942 #[gpui::test]
1943 fn test_path_for_file(cx: &mut App) {
1944 let file = TestFile {
1945 path: RelPath::empty().into(),
1946 root_name: String::new(),
1947 local_root: None,
1948 };
1949 assert_eq!(path_for_file(&file, 0, false, cx), None);
1950 }
1951
1952 async fn deserialize_editor(
1953 item_id: ItemId,
1954 workspace_id: WorkspaceId,
1955 workspace: Entity<Workspace>,
1956 project: Entity<Project>,
1957 cx: &mut VisualTestContext,
1958 ) -> Entity<Editor> {
1959 workspace
1960 .update_in(cx, |workspace, window, cx| {
1961 let pane = workspace.active_pane();
1962 pane.update(cx, |_, cx| {
1963 Editor::deserialize(
1964 project.clone(),
1965 workspace.weak_handle(),
1966 workspace_id,
1967 item_id,
1968 window,
1969 cx,
1970 )
1971 })
1972 })
1973 .await
1974 .unwrap()
1975 }
1976
1977 fn rust_language() -> Arc<language::Language> {
1978 Arc::new(language::Language::new(
1979 language::LanguageConfig {
1980 name: "Rust".into(),
1981 matcher: LanguageMatcher {
1982 path_suffixes: vec!["rs".to_string()],
1983 ..Default::default()
1984 },
1985 ..Default::default()
1986 },
1987 Some(tree_sitter_rust::LANGUAGE.into()),
1988 ))
1989 }
1990
1991 #[gpui::test]
1992 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1993 init_test(cx, |_| {});
1994
1995 let fs = FakeFs::new(cx.executor());
1996 fs.insert_file(path!("/file.rs"), Default::default()).await;
1997
1998 // Test case 1: Deserialize with path and contents
1999 {
2000 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2001 let (workspace, cx) =
2002 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2003 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2004 let item_id = 1234 as ItemId;
2005 let mtime = fs
2006 .metadata(Path::new(path!("/file.rs")))
2007 .await
2008 .unwrap()
2009 .unwrap()
2010 .mtime;
2011
2012 let serialized_editor = SerializedEditor {
2013 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2014 contents: Some("fn main() {}".to_string()),
2015 language: Some("Rust".to_string()),
2016 mtime: Some(mtime),
2017 };
2018
2019 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2020 .await
2021 .unwrap();
2022
2023 let deserialized =
2024 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2025
2026 deserialized.update(cx, |editor, cx| {
2027 assert_eq!(editor.text(cx), "fn main() {}");
2028 assert!(editor.is_dirty(cx));
2029 assert!(!editor.has_conflict(cx));
2030 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2031 assert!(buffer.file().is_some());
2032 });
2033 }
2034
2035 // Test case 2: Deserialize with only path
2036 {
2037 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2038 let (workspace, cx) =
2039 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2040
2041 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2042
2043 let item_id = 5678 as ItemId;
2044 let serialized_editor = SerializedEditor {
2045 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2046 contents: None,
2047 language: None,
2048 mtime: None,
2049 };
2050
2051 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2052 .await
2053 .unwrap();
2054
2055 let deserialized =
2056 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2057
2058 deserialized.update(cx, |editor, cx| {
2059 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2060 assert!(!editor.is_dirty(cx));
2061 assert!(!editor.has_conflict(cx));
2062
2063 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2064 assert!(buffer.file().is_some());
2065 });
2066 }
2067
2068 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2069 {
2070 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2071 // Add Rust to the language, so that we can restore the language of the buffer
2072 project.read_with(cx, |project, _| project.languages().add(rust_language()));
2073
2074 let (workspace, cx) =
2075 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2076
2077 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2078
2079 let item_id = 9012 as ItemId;
2080 let serialized_editor = SerializedEditor {
2081 abs_path: None,
2082 contents: Some("hello".to_string()),
2083 language: Some("Rust".to_string()),
2084 mtime: None,
2085 };
2086
2087 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2088 .await
2089 .unwrap();
2090
2091 let deserialized =
2092 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2093
2094 deserialized.update(cx, |editor, cx| {
2095 assert_eq!(editor.text(cx), "hello");
2096 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2097
2098 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2099 assert_eq!(
2100 buffer.language().map(|lang| lang.name()),
2101 Some("Rust".into())
2102 ); // Language should be set to Rust
2103 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2104 });
2105 }
2106
2107 // Test case 4: Deserialize with path, content, and old mtime
2108 {
2109 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2110 let (workspace, cx) =
2111 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2112
2113 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2114
2115 let item_id = 9345 as ItemId;
2116 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2117 let serialized_editor = SerializedEditor {
2118 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2119 contents: Some("fn main() {}".to_string()),
2120 language: Some("Rust".to_string()),
2121 mtime: Some(old_mtime),
2122 };
2123
2124 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2125 .await
2126 .unwrap();
2127
2128 let deserialized =
2129 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2130
2131 deserialized.update(cx, |editor, cx| {
2132 assert_eq!(editor.text(cx), "fn main() {}");
2133 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2134 });
2135 }
2136
2137 // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2138 {
2139 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2140 let (workspace, cx) =
2141 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2142
2143 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2144
2145 let item_id = 10000 as ItemId;
2146 let serialized_editor = SerializedEditor {
2147 abs_path: None,
2148 contents: None,
2149 language: None,
2150 mtime: None,
2151 };
2152
2153 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2154 .await
2155 .unwrap();
2156
2157 let deserialized =
2158 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2159
2160 deserialized.update(cx, |editor, cx| {
2161 assert_eq!(editor.text(cx), "");
2162 assert!(!editor.is_dirty(cx));
2163 assert!(!editor.has_conflict(cx));
2164
2165 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2166 assert!(buffer.file().is_none());
2167 });
2168 }
2169 }
2170}