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