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