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