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, async move |cx| {
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 =
133 Editor::for_multibuffer(multibuffer, Some(project.clone()), window, cx);
134 editor.remote_id = Some(remote_id);
135 editor
136 })
137 })?;
138
139 update_editor_from_message(
140 editor.downgrade(),
141 project,
142 proto::update_view::Editor {
143 selections: state.selections,
144 pending_selection: state.pending_selection,
145 scroll_top_anchor: state.scroll_top_anchor,
146 scroll_x: state.scroll_x,
147 scroll_y: state.scroll_y,
148 ..Default::default()
149 },
150 cx,
151 )
152 .await?;
153
154 Ok(editor)
155 }))
156 }
157
158 fn set_leader_peer_id(
159 &mut self,
160 leader_peer_id: Option<PeerId>,
161 window: &mut Window,
162 cx: &mut Context<Self>,
163 ) {
164 self.leader_peer_id = leader_peer_id;
165 if self.leader_peer_id.is_some() {
166 self.buffer.update(cx, |buffer, cx| {
167 buffer.remove_active_selections(cx);
168 });
169 } else if self.focus_handle.is_focused(window) {
170 self.buffer.update(cx, |buffer, cx| {
171 buffer.set_active_selections(
172 &self.selections.disjoint_anchors(),
173 self.selections.line_mode,
174 self.cursor_shape,
175 cx,
176 );
177 });
178 }
179 cx.notify();
180 }
181
182 fn to_state_proto(&self, _: &Window, cx: &App) -> Option<proto::view::Variant> {
183 let buffer = self.buffer.read(cx);
184 if buffer
185 .as_singleton()
186 .and_then(|buffer| buffer.read(cx).file())
187 .map_or(false, |file| file.is_private())
188 {
189 return None;
190 }
191
192 let scroll_anchor = self.scroll_manager.anchor();
193 let excerpts = buffer
194 .read(cx)
195 .excerpts()
196 .map(|(id, buffer, range)| proto::Excerpt {
197 id: id.to_proto(),
198 buffer_id: buffer.remote_id().into(),
199 context_start: Some(serialize_text_anchor(&range.context.start)),
200 context_end: Some(serialize_text_anchor(&range.context.end)),
201 primary_start: range
202 .primary
203 .as_ref()
204 .map(|range| serialize_text_anchor(&range.start)),
205 primary_end: range
206 .primary
207 .as_ref()
208 .map(|range| serialize_text_anchor(&range.end)),
209 })
210 .collect();
211
212 Some(proto::view::Variant::Editor(proto::view::Editor {
213 singleton: buffer.is_singleton(),
214 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
215 excerpts,
216 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
217 scroll_x: scroll_anchor.offset.x,
218 scroll_y: scroll_anchor.offset.y,
219 selections: self
220 .selections
221 .disjoint_anchors()
222 .iter()
223 .map(serialize_selection)
224 .collect(),
225 pending_selection: self
226 .selections
227 .pending_anchor()
228 .as_ref()
229 .map(serialize_selection),
230 }))
231 }
232
233 fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
234 match event {
235 EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
236 EditorEvent::SelectionsChanged { local }
237 | EditorEvent::ScrollPositionChanged { local, .. } => {
238 if *local {
239 Some(FollowEvent::Unfollow)
240 } else {
241 None
242 }
243 }
244 _ => None,
245 }
246 }
247
248 fn add_event_to_update_proto(
249 &self,
250 event: &EditorEvent,
251 update: &mut Option<proto::update_view::Variant>,
252 _: &Window,
253 cx: &App,
254 ) -> bool {
255 let update =
256 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
257
258 match update {
259 proto::update_view::Variant::Editor(update) => match event {
260 EditorEvent::ExcerptsAdded {
261 buffer,
262 predecessor,
263 excerpts,
264 } => {
265 let buffer_id = buffer.read(cx).remote_id();
266 let mut excerpts = excerpts.iter();
267 if let Some((id, range)) = excerpts.next() {
268 update.inserted_excerpts.push(proto::ExcerptInsertion {
269 previous_excerpt_id: Some(predecessor.to_proto()),
270 excerpt: serialize_excerpt(buffer_id, id, range),
271 });
272 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
273 proto::ExcerptInsertion {
274 previous_excerpt_id: None,
275 excerpt: serialize_excerpt(buffer_id, id, range),
276 }
277 }))
278 }
279 true
280 }
281 EditorEvent::ExcerptsRemoved { ids } => {
282 update
283 .deleted_excerpts
284 .extend(ids.iter().map(ExcerptId::to_proto));
285 true
286 }
287 EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
288 let scroll_anchor = self.scroll_manager.anchor();
289 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
290 update.scroll_x = scroll_anchor.offset.x;
291 update.scroll_y = scroll_anchor.offset.y;
292 true
293 }
294 EditorEvent::SelectionsChanged { .. } => {
295 update.selections = self
296 .selections
297 .disjoint_anchors()
298 .iter()
299 .map(serialize_selection)
300 .collect();
301 update.pending_selection = self
302 .selections
303 .pending_anchor()
304 .as_ref()
305 .map(serialize_selection);
306 true
307 }
308 _ => false,
309 },
310 }
311 }
312
313 fn apply_update_proto(
314 &mut self,
315 project: &Entity<Project>,
316 message: update_view::Variant,
317 window: &mut Window,
318 cx: &mut Context<Self>,
319 ) -> Task<Result<()>> {
320 let update_view::Variant::Editor(message) = message;
321 let project = project.clone();
322 cx.spawn_in(window, async move |this, cx| {
323 update_editor_from_message(this, project, message, cx).await
324 })
325 }
326
327 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
328 true
329 }
330
331 fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
332 let self_singleton = self.buffer.read(cx).as_singleton()?;
333 let other_singleton = existing.buffer.read(cx).as_singleton()?;
334 if self_singleton == other_singleton {
335 Some(Dedup::KeepExisting)
336 } else {
337 None
338 }
339 }
340}
341
342async fn update_editor_from_message(
343 this: WeakEntity<Editor>,
344 project: Entity<Project>,
345 message: proto::update_view::Editor,
346 cx: &mut AsyncWindowContext,
347) -> Result<()> {
348 // Open all of the buffers of which excerpts were added to the editor.
349 let inserted_excerpt_buffer_ids = message
350 .inserted_excerpts
351 .iter()
352 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
353 .collect::<HashSet<_>>();
354 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
355 inserted_excerpt_buffer_ids
356 .into_iter()
357 .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
358 .collect::<Result<Vec<_>>>()
359 })??;
360 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
361
362 // Update the editor's excerpts.
363 this.update(cx, |editor, cx| {
364 editor.buffer.update(cx, |multibuffer, cx| {
365 let mut removed_excerpt_ids = message
366 .deleted_excerpts
367 .into_iter()
368 .map(ExcerptId::from_proto)
369 .collect::<Vec<_>>();
370 removed_excerpt_ids.sort_by({
371 let multibuffer = multibuffer.read(cx);
372 move |a, b| a.cmp(b, &multibuffer)
373 });
374
375 let mut insertions = message.inserted_excerpts.into_iter().peekable();
376 while let Some(insertion) = insertions.next() {
377 let Some(excerpt) = insertion.excerpt else {
378 continue;
379 };
380 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
381 continue;
382 };
383 let buffer_id = BufferId::new(excerpt.buffer_id)?;
384 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
385 continue;
386 };
387
388 let adjacent_excerpts = iter::from_fn(|| {
389 let insertion = insertions.peek()?;
390 if insertion.previous_excerpt_id.is_none()
391 && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
392 {
393 insertions.next()?.excerpt
394 } else {
395 None
396 }
397 });
398
399 multibuffer.insert_excerpts_with_ids_after(
400 ExcerptId::from_proto(previous_excerpt_id),
401 buffer,
402 [excerpt]
403 .into_iter()
404 .chain(adjacent_excerpts)
405 .filter_map(|excerpt| {
406 Some((
407 ExcerptId::from_proto(excerpt.id),
408 deserialize_excerpt_range(excerpt)?,
409 ))
410 }),
411 cx,
412 );
413 }
414
415 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
416 Result::<(), anyhow::Error>::Ok(())
417 })
418 })??;
419
420 // Deserialize the editor state.
421 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
422 let buffer = editor.buffer.read(cx).read(cx);
423 let selections = message
424 .selections
425 .into_iter()
426 .filter_map(|selection| deserialize_selection(&buffer, selection))
427 .collect::<Vec<_>>();
428 let pending_selection = message
429 .pending_selection
430 .and_then(|selection| deserialize_selection(&buffer, selection));
431 let scroll_top_anchor = message
432 .scroll_top_anchor
433 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
434 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
435 })??;
436
437 // Wait until the buffer has received all of the operations referenced by
438 // the editor's new state.
439 this.update(cx, |editor, cx| {
440 editor.buffer.update(cx, |buffer, cx| {
441 buffer.wait_for_anchors(
442 selections
443 .iter()
444 .chain(pending_selection.as_ref())
445 .flat_map(|selection| [selection.start, selection.end])
446 .chain(scroll_top_anchor),
447 cx,
448 )
449 })
450 })?
451 .await?;
452
453 // Update the editor's state.
454 this.update_in(cx, |editor, window, cx| {
455 if !selections.is_empty() || pending_selection.is_some() {
456 editor.set_selections_from_remote(selections, pending_selection, window, cx);
457 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
458 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
459 editor.set_scroll_anchor_remote(
460 ScrollAnchor {
461 anchor: scroll_top_anchor,
462 offset: point(message.scroll_x, message.scroll_y),
463 },
464 window,
465 cx,
466 );
467 }
468 })?;
469 Ok(())
470}
471
472fn serialize_excerpt(
473 buffer_id: BufferId,
474 id: &ExcerptId,
475 range: &ExcerptRange<language::Anchor>,
476) -> Option<proto::Excerpt> {
477 Some(proto::Excerpt {
478 id: id.to_proto(),
479 buffer_id: buffer_id.into(),
480 context_start: Some(serialize_text_anchor(&range.context.start)),
481 context_end: Some(serialize_text_anchor(&range.context.end)),
482 primary_start: range
483 .primary
484 .as_ref()
485 .map(|r| serialize_text_anchor(&r.start)),
486 primary_end: range
487 .primary
488 .as_ref()
489 .map(|r| serialize_text_anchor(&r.end)),
490 })
491}
492
493fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
494 proto::Selection {
495 id: selection.id as u64,
496 start: Some(serialize_anchor(&selection.start)),
497 end: Some(serialize_anchor(&selection.end)),
498 reversed: selection.reversed,
499 }
500}
501
502fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
503 proto::EditorAnchor {
504 excerpt_id: anchor.excerpt_id.to_proto(),
505 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
506 }
507}
508
509fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
510 let context = {
511 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
512 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
513 start..end
514 };
515 let primary = excerpt
516 .primary_start
517 .zip(excerpt.primary_end)
518 .and_then(|(start, end)| {
519 let start = language::proto::deserialize_anchor(start)?;
520 let end = language::proto::deserialize_anchor(end)?;
521 Some(start..end)
522 });
523 Some(ExcerptRange { context, primary })
524}
525
526fn deserialize_selection(
527 buffer: &MultiBufferSnapshot,
528 selection: proto::Selection,
529) -> Option<Selection<Anchor>> {
530 Some(Selection {
531 id: selection.id as usize,
532 start: deserialize_anchor(buffer, selection.start?)?,
533 end: deserialize_anchor(buffer, selection.end?)?,
534 reversed: selection.reversed,
535 goal: SelectionGoal::None,
536 })
537}
538
539fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
540 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
541 Some(Anchor {
542 excerpt_id,
543 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
544 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
545 diff_base_anchor: None,
546 })
547}
548
549impl Item for Editor {
550 type Event = EditorEvent;
551
552 fn navigate(
553 &mut self,
554 data: Box<dyn std::any::Any>,
555 window: &mut Window,
556 cx: &mut Context<Self>,
557 ) -> bool {
558 if let Ok(data) = data.downcast::<NavigationData>() {
559 let newest_selection = self.selections.newest::<Point>(cx);
560 let buffer = self.buffer.read(cx).read(cx);
561 let offset = if buffer.can_resolve(&data.cursor_anchor) {
562 data.cursor_anchor.to_point(&buffer)
563 } else {
564 buffer.clip_point(data.cursor_position, Bias::Left)
565 };
566
567 let mut scroll_anchor = data.scroll_anchor;
568 if !buffer.can_resolve(&scroll_anchor.anchor) {
569 scroll_anchor.anchor = buffer.anchor_before(
570 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
571 );
572 }
573
574 drop(buffer);
575
576 if newest_selection.head() == offset {
577 false
578 } else {
579 let nav_history = self.nav_history.take();
580 self.set_scroll_anchor(scroll_anchor, window, cx);
581 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
582 s.select_ranges([offset..offset])
583 });
584 self.nav_history = nav_history;
585 true
586 }
587 } else {
588 false
589 }
590 }
591
592 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
593 let file_path = self
594 .buffer()
595 .read(cx)
596 .as_singleton()?
597 .read(cx)
598 .file()
599 .and_then(|f| f.as_local())?
600 .abs_path(cx);
601
602 let file_path = file_path.compact().to_string_lossy().to_string();
603
604 Some(file_path.into())
605 }
606
607 fn telemetry_event_text(&self) -> Option<&'static str> {
608 None
609 }
610
611 fn tab_description(&self, detail: usize, cx: &App) -> Option<SharedString> {
612 let path = path_for_buffer(&self.buffer, detail, true, cx)?;
613 Some(path.to_string_lossy().to_string().into())
614 }
615
616 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
617 ItemSettings::get_global(cx)
618 .file_icons
619 .then(|| {
620 path_for_buffer(&self.buffer, 0, true, cx)
621 .and_then(|path| FileIcons::get_icon(path.as_ref(), cx))
622 })
623 .flatten()
624 .map(Icon::from_path)
625 }
626
627 fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
628 let label_color = if ItemSettings::get_global(cx).git_status {
629 self.buffer()
630 .read(cx)
631 .as_singleton()
632 .and_then(|buffer| buffer.read(cx).project_path(cx))
633 .and_then(|path| {
634 let project = self.project.as_ref()?.read(cx);
635 let entry = project.entry_for_path(&path, cx)?;
636 let git_status = project
637 .worktree_for_id(path.worktree_id, cx)?
638 .read(cx)
639 .snapshot()
640 .status_for_file(path.path)?;
641
642 Some(entry_git_aware_label_color(
643 git_status.summary(),
644 entry.is_ignored,
645 params.selected,
646 ))
647 })
648 .unwrap_or_else(|| entry_label_color(params.selected))
649 } else {
650 entry_label_color(params.selected)
651 };
652
653 let description = params.detail.and_then(|detail| {
654 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
655 let description = path.to_string_lossy();
656 let description = description.trim();
657
658 if description.is_empty() {
659 return None;
660 }
661
662 Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
663 });
664
665 // Whether the file was saved in the past but is now deleted.
666 let was_deleted: bool = self
667 .buffer()
668 .read(cx)
669 .as_singleton()
670 .and_then(|buffer| buffer.read(cx).file())
671 .map_or(false, |file| file.disk_state() == DiskState::Deleted);
672
673 h_flex()
674 .gap_2()
675 .child(
676 Label::new(self.title(cx).to_string())
677 .color(label_color)
678 .when(params.preview, |this| this.italic())
679 .when(was_deleted, |this| this.strikethrough()),
680 )
681 .when_some(description, |this, description| {
682 this.child(
683 Label::new(description)
684 .size(LabelSize::XSmall)
685 .color(Color::Muted),
686 )
687 })
688 .into_any_element()
689 }
690
691 fn for_each_project_item(
692 &self,
693 cx: &App,
694 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
695 ) {
696 self.buffer
697 .read(cx)
698 .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
699 }
700
701 fn is_singleton(&self, cx: &App) -> bool {
702 self.buffer.read(cx).is_singleton()
703 }
704
705 fn can_save_as(&self, cx: &App) -> bool {
706 self.buffer.read(cx).is_singleton()
707 }
708
709 fn clone_on_split(
710 &self,
711 _workspace_id: Option<WorkspaceId>,
712 window: &mut Window,
713 cx: &mut Context<Self>,
714 ) -> Option<Entity<Editor>>
715 where
716 Self: Sized,
717 {
718 Some(cx.new(|cx| self.clone(window, cx)))
719 }
720
721 fn set_nav_history(
722 &mut self,
723 history: ItemNavHistory,
724 _window: &mut Window,
725 _: &mut Context<Self>,
726 ) {
727 self.nav_history = Some(history);
728 }
729
730 fn discarded(&self, _project: Entity<Project>, _: &mut Window, cx: &mut Context<Self>) {
731 for buffer in self.buffer().clone().read(cx).all_buffers() {
732 buffer.update(cx, |buffer, cx| buffer.discarded(cx))
733 }
734 }
735
736 fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
737 let selection = self.selections.newest_anchor();
738 self.push_to_nav_history(selection.head(), None, cx);
739 }
740
741 fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
742 self.hide_hovered_link(cx);
743 }
744
745 fn is_dirty(&self, cx: &App) -> bool {
746 self.buffer().read(cx).read(cx).is_dirty()
747 }
748
749 fn has_deleted_file(&self, cx: &App) -> bool {
750 self.buffer().read(cx).read(cx).has_deleted_file()
751 }
752
753 fn has_conflict(&self, cx: &App) -> bool {
754 self.buffer().read(cx).read(cx).has_conflict()
755 }
756
757 fn can_save(&self, cx: &App) -> bool {
758 let buffer = &self.buffer().read(cx);
759 if let Some(buffer) = buffer.as_singleton() {
760 buffer.read(cx).project_path(cx).is_some()
761 } else {
762 true
763 }
764 }
765
766 fn save(
767 &mut self,
768 format: bool,
769 project: Entity<Project>,
770 window: &mut Window,
771 cx: &mut Context<Self>,
772 ) -> Task<Result<()>> {
773 self.report_editor_event("Editor Saved", None, cx);
774 let buffers = self.buffer().clone().read(cx).all_buffers();
775 let buffers = buffers
776 .into_iter()
777 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
778 .collect::<HashSet<_>>();
779 cx.spawn_in(window, async move |this, cx| {
780 if format {
781 this.update_in(cx, |editor, window, cx| {
782 editor.perform_format(
783 project.clone(),
784 FormatTrigger::Save,
785 FormatTarget::Buffers,
786 window,
787 cx,
788 )
789 })?
790 .await?;
791 }
792
793 if buffers.len() == 1 {
794 // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
795 project
796 .update(cx, |project, cx| project.save_buffers(buffers, cx))?
797 .await?;
798 } else {
799 // For multi-buffers, only format and save the buffers with changes.
800 // For clean buffers, we simulate saving by calling `Buffer::did_save`,
801 // so that language servers or other downstream listeners of save events get notified.
802 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
803 buffer
804 .update(cx, |buffer, _| buffer.is_dirty() || buffer.has_conflict())
805 .unwrap_or(false)
806 });
807
808 project
809 .update(cx, |project, cx| project.save_buffers(dirty_buffers, cx))?
810 .await?;
811 for buffer in clean_buffers {
812 buffer
813 .update(cx, |buffer, cx| {
814 let version = buffer.saved_version().clone();
815 let mtime = buffer.saved_mtime();
816 buffer.did_save(version, mtime, cx);
817 })
818 .ok();
819 }
820 }
821
822 Ok(())
823 })
824 }
825
826 fn save_as(
827 &mut self,
828 project: Entity<Project>,
829 path: ProjectPath,
830 _: &mut Window,
831 cx: &mut Context<Self>,
832 ) -> Task<Result<()>> {
833 let buffer = self
834 .buffer()
835 .read(cx)
836 .as_singleton()
837 .expect("cannot call save_as on an excerpt list");
838
839 let file_extension = path
840 .path
841 .extension()
842 .map(|a| a.to_string_lossy().to_string());
843 self.report_editor_event("Editor Saved", file_extension, cx);
844
845 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
846 }
847
848 fn reload(
849 &mut self,
850 project: Entity<Project>,
851 window: &mut Window,
852 cx: &mut Context<Self>,
853 ) -> Task<Result<()>> {
854 let buffer = self.buffer().clone();
855 let buffers = self.buffer.read(cx).all_buffers();
856 let reload_buffers =
857 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
858 cx.spawn_in(window, async move |this, cx| {
859 let transaction = reload_buffers.log_err().await;
860 this.update(cx, |editor, cx| {
861 editor.request_autoscroll(Autoscroll::fit(), cx)
862 })?;
863 buffer
864 .update(cx, |buffer, cx| {
865 if let Some(transaction) = transaction {
866 if !buffer.is_singleton() {
867 buffer.push_transaction(&transaction.0, cx);
868 }
869 }
870 })
871 .ok();
872 Ok(())
873 })
874 }
875
876 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
877 Some(Box::new(handle.clone()))
878 }
879
880 fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
881 self.pixel_position_of_newest_cursor
882 }
883
884 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
885 if self.show_breadcrumbs {
886 ToolbarItemLocation::PrimaryLeft
887 } else {
888 ToolbarItemLocation::Hidden
889 }
890 }
891
892 fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
893 let cursor = self.selections.newest_anchor().head();
894 let multibuffer = &self.buffer().read(cx);
895 let (buffer_id, symbols) =
896 multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
897 let buffer = multibuffer.buffer(buffer_id)?;
898
899 let buffer = buffer.read(cx);
900 let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
901 buffer
902 .snapshot()
903 .resolve_file_path(
904 cx,
905 self.project
906 .as_ref()
907 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
908 .unwrap_or_default(),
909 )
910 .map(|path| path.to_string_lossy().to_string())
911 .unwrap_or_else(|| {
912 if multibuffer.is_singleton() {
913 multibuffer.title(cx).to_string()
914 } else {
915 "untitled".to_string()
916 }
917 })
918 });
919
920 let settings = ThemeSettings::get_global(cx);
921
922 let mut breadcrumbs = vec![BreadcrumbText {
923 text,
924 highlights: None,
925 font: Some(settings.buffer_font.clone()),
926 }];
927
928 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
929 text: symbol.text,
930 highlights: Some(symbol.highlight_ranges),
931 font: Some(settings.buffer_font.clone()),
932 }));
933 Some(breadcrumbs)
934 }
935
936 fn added_to_workspace(
937 &mut self,
938 workspace: &mut Workspace,
939 _window: &mut Window,
940 _: &mut Context<Self>,
941 ) {
942 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
943 }
944
945 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
946 match event {
947 EditorEvent::Closed => f(ItemEvent::CloseItem),
948
949 EditorEvent::Saved | EditorEvent::TitleChanged => {
950 f(ItemEvent::UpdateTab);
951 f(ItemEvent::UpdateBreadcrumbs);
952 }
953
954 EditorEvent::Reparsed(_) => {
955 f(ItemEvent::UpdateBreadcrumbs);
956 }
957
958 EditorEvent::SelectionsChanged { local } if *local => {
959 f(ItemEvent::UpdateBreadcrumbs);
960 }
961
962 EditorEvent::DirtyChanged => {
963 f(ItemEvent::UpdateTab);
964 }
965
966 EditorEvent::BufferEdited => {
967 f(ItemEvent::Edit);
968 f(ItemEvent::UpdateBreadcrumbs);
969 }
970
971 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
972 f(ItemEvent::Edit);
973 }
974
975 _ => {}
976 }
977 }
978
979 fn preserve_preview(&self, cx: &App) -> bool {
980 self.buffer.read(cx).preserve_preview(cx)
981 }
982}
983
984impl SerializableItem for Editor {
985 fn serialized_item_kind() -> &'static str {
986 "Editor"
987 }
988
989 fn cleanup(
990 workspace_id: WorkspaceId,
991 alive_items: Vec<ItemId>,
992 window: &mut Window,
993 cx: &mut App,
994 ) -> Task<Result<()>> {
995 window.spawn(cx, async move |_| {
996 DB.delete_unloaded_items(workspace_id, alive_items).await
997 })
998 }
999
1000 fn deserialize(
1001 project: Entity<Project>,
1002 workspace: WeakEntity<Workspace>,
1003 workspace_id: workspace::WorkspaceId,
1004 item_id: ItemId,
1005 window: &mut Window,
1006 cx: &mut App,
1007 ) -> Task<Result<Entity<Self>>> {
1008 let serialized_editor = match DB
1009 .get_serialized_editor(item_id, workspace_id)
1010 .context("Failed to query editor state")
1011 {
1012 Ok(Some(serialized_editor)) => {
1013 if ProjectSettings::get_global(cx)
1014 .session
1015 .restore_unsaved_buffers
1016 {
1017 serialized_editor
1018 } else {
1019 SerializedEditor {
1020 abs_path: serialized_editor.abs_path,
1021 contents: None,
1022 language: None,
1023 mtime: None,
1024 }
1025 }
1026 }
1027 Ok(None) => {
1028 return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1029 }
1030 Err(error) => {
1031 return Task::ready(Err(error));
1032 }
1033 };
1034
1035 match serialized_editor {
1036 SerializedEditor {
1037 abs_path: None,
1038 contents: Some(contents),
1039 language,
1040 ..
1041 } => window.spawn(cx, {
1042 let project = project.clone();
1043 async move |cx| {
1044 let language_registry =
1045 project.update(cx, |project, _| project.languages().clone())?;
1046
1047 let language = if let Some(language_name) = language {
1048 // We don't fail here, because we'd rather not set the language if the name changed
1049 // than fail to restore the buffer.
1050 language_registry
1051 .language_for_name(&language_name)
1052 .await
1053 .ok()
1054 } else {
1055 None
1056 };
1057
1058 // First create the empty buffer
1059 let buffer = project
1060 .update(cx, |project, cx| project.create_buffer(cx))?
1061 .await?;
1062
1063 // Then set the text so that the dirty bit is set correctly
1064 buffer.update(cx, |buffer, cx| {
1065 buffer.set_language_registry(language_registry);
1066 if let Some(language) = language {
1067 buffer.set_language(Some(language), cx);
1068 }
1069 buffer.set_text(contents, cx);
1070 if let Some(entry) = buffer.peek_undo_stack() {
1071 buffer.forget_transaction(entry.transaction_id());
1072 }
1073 })?;
1074
1075 cx.update(|window, cx| {
1076 cx.new(|cx| {
1077 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1078
1079 editor.read_selections_from_db(item_id, workspace_id, window, cx);
1080 editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1081 editor
1082 })
1083 })
1084 }
1085 }),
1086 SerializedEditor {
1087 abs_path: Some(abs_path),
1088 contents,
1089 mtime,
1090 ..
1091 } => {
1092 let project_item = project.update(cx, |project, cx| {
1093 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1094 let project_path = ProjectPath {
1095 worktree_id: worktree.read(cx).id(),
1096 path: path.into(),
1097 };
1098 Some(project.open_path(project_path, cx))
1099 });
1100
1101 match project_item {
1102 Some(project_item) => {
1103 window.spawn(cx, async move |cx| {
1104 let (_, project_item) = project_item.await?;
1105 let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1106 anyhow!("Project item at stored path was not a buffer")
1107 })?;
1108
1109 // This is a bit wasteful: we're loading the whole buffer from
1110 // disk and then overwrite the content.
1111 // But for now, it keeps the implementation of the content serialization
1112 // simple, because we don't have to persist all of the metadata that we get
1113 // by loading the file (git diff base, ...).
1114 if let Some(buffer_text) = contents {
1115 buffer.update(cx, |buffer, cx| {
1116 // If we did restore an mtime, we want to store it on the buffer
1117 // so that the next edit will mark the buffer as dirty/conflicted.
1118 if mtime.is_some() {
1119 buffer.did_reload(
1120 buffer.version(),
1121 buffer.line_ending(),
1122 mtime,
1123 cx,
1124 );
1125 }
1126 buffer.set_text(buffer_text, cx);
1127 if let Some(entry) = buffer.peek_undo_stack() {
1128 buffer.forget_transaction(entry.transaction_id());
1129 }
1130 })?;
1131 }
1132
1133 cx.update(|window, cx| {
1134 cx.new(|cx| {
1135 let mut editor =
1136 Editor::for_buffer(buffer, Some(project), window, cx);
1137
1138 editor.read_selections_from_db(
1139 item_id,
1140 workspace_id,
1141 window,
1142 cx,
1143 );
1144 editor.read_scroll_position_from_db(
1145 item_id,
1146 workspace_id,
1147 window,
1148 cx,
1149 );
1150 editor
1151 })
1152 })
1153 })
1154 }
1155 None => {
1156 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1157 workspace.open_abs_path(
1158 abs_path.clone(),
1159 OpenOptions {
1160 visible: Some(OpenVisible::None),
1161 ..Default::default()
1162 },
1163 window,
1164 cx,
1165 )
1166 });
1167 window.spawn(cx, async move |cx| {
1168 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1169 editor.update_in(cx, |editor, window, cx| {
1170 editor.read_selections_from_db(item_id, workspace_id, window, cx);
1171 editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1172 })?;
1173 Ok(editor)
1174 })
1175 }
1176 }
1177 }
1178 SerializedEditor {
1179 abs_path: None,
1180 contents: None,
1181 ..
1182 } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1183 }
1184 }
1185
1186 fn serialize(
1187 &mut self,
1188 workspace: &mut Workspace,
1189 item_id: ItemId,
1190 closing: bool,
1191 window: &mut Window,
1192 cx: &mut Context<Self>,
1193 ) -> Option<Task<Result<()>>> {
1194 let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1195
1196 let project = self.project.clone()?;
1197 if project.read(cx).visible_worktrees(cx).next().is_none() {
1198 // If we don't have a worktree, we don't serialize, because
1199 // projects without worktrees aren't deserialized.
1200 serialize_dirty_buffers = false;
1201 }
1202
1203 if closing && !serialize_dirty_buffers {
1204 return None;
1205 }
1206
1207 let workspace_id = workspace.database_id()?;
1208
1209 let buffer = self.buffer().read(cx).as_singleton()?;
1210
1211 let abs_path = buffer.read(cx).file().and_then(|file| {
1212 let worktree_id = file.worktree_id(cx);
1213 project
1214 .read(cx)
1215 .worktree_for_id(worktree_id, cx)
1216 .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1217 .or_else(|| {
1218 let full_path = file.full_path(cx);
1219 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1220 project.read(cx).absolute_path(&project_path, cx)
1221 })
1222 });
1223
1224 let is_dirty = buffer.read(cx).is_dirty();
1225 let mtime = buffer.read(cx).saved_mtime();
1226
1227 let snapshot = buffer.read(cx).snapshot();
1228
1229 Some(cx.spawn_in(window, async move |_this, cx| {
1230 cx.background_spawn(async move {
1231 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1232 let contents = snapshot.text();
1233 let language = snapshot.language().map(|lang| lang.name().to_string());
1234 (Some(contents), language)
1235 } else {
1236 (None, None)
1237 };
1238
1239 let editor = SerializedEditor {
1240 abs_path,
1241 contents,
1242 language,
1243 mtime,
1244 };
1245 DB.save_serialized_editor(item_id, workspace_id, editor)
1246 .await
1247 .context("failed to save serialized editor")
1248 })
1249 .await
1250 .context("failed to save contents of buffer")?;
1251
1252 Ok(())
1253 }))
1254 }
1255
1256 fn should_serialize(&self, event: &Self::Event) -> bool {
1257 matches!(
1258 event,
1259 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1260 )
1261 }
1262}
1263
1264impl ProjectItem for Editor {
1265 type Item = Buffer;
1266
1267 fn for_project_item(
1268 project: Entity<Project>,
1269 buffer: Entity<Buffer>,
1270 window: &mut Window,
1271 cx: &mut Context<Self>,
1272 ) -> Self {
1273 Self::for_buffer(buffer, Some(project), window, cx)
1274 }
1275}
1276
1277impl EventEmitter<SearchEvent> for Editor {}
1278
1279pub(crate) enum BufferSearchHighlights {}
1280impl SearchableItem for Editor {
1281 type Match = Range<Anchor>;
1282
1283 fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1284 self.background_highlights
1285 .get(&TypeId::of::<BufferSearchHighlights>())
1286 .map_or(Vec::new(), |(_color, ranges)| {
1287 ranges.iter().cloned().collect()
1288 })
1289 }
1290
1291 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1292 if self
1293 .clear_background_highlights::<BufferSearchHighlights>(cx)
1294 .is_some()
1295 {
1296 cx.emit(SearchEvent::MatchesInvalidated);
1297 }
1298 }
1299
1300 fn update_matches(
1301 &mut self,
1302 matches: &[Range<Anchor>],
1303 _: &mut Window,
1304 cx: &mut Context<Self>,
1305 ) {
1306 let existing_range = self
1307 .background_highlights
1308 .get(&TypeId::of::<BufferSearchHighlights>())
1309 .map(|(_, range)| range.as_ref());
1310 let updated = existing_range != Some(matches);
1311 self.highlight_background::<BufferSearchHighlights>(
1312 matches,
1313 |theme| theme.search_match_background,
1314 cx,
1315 );
1316 if updated {
1317 cx.emit(SearchEvent::MatchesInvalidated);
1318 }
1319 }
1320
1321 fn has_filtered_search_ranges(&mut self) -> bool {
1322 self.has_background_highlights::<SearchWithinRange>()
1323 }
1324
1325 fn toggle_filtered_search_ranges(
1326 &mut self,
1327 enabled: bool,
1328 _: &mut Window,
1329 cx: &mut Context<Self>,
1330 ) {
1331 if self.has_filtered_search_ranges() {
1332 self.previous_search_ranges = self
1333 .clear_background_highlights::<SearchWithinRange>(cx)
1334 .map(|(_, ranges)| ranges)
1335 }
1336
1337 if !enabled {
1338 return;
1339 }
1340
1341 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1342 if ranges.iter().any(|s| s.start != s.end) {
1343 self.set_search_within_ranges(&ranges, cx);
1344 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1345 self.set_search_within_ranges(&previous_search_ranges, cx)
1346 }
1347 }
1348
1349 fn supported_options(&self) -> SearchOptions {
1350 if self.in_project_search {
1351 SearchOptions {
1352 case: true,
1353 word: true,
1354 regex: true,
1355 replacement: false,
1356 selection: false,
1357 find_in_results: true,
1358 }
1359 } else {
1360 SearchOptions {
1361 case: true,
1362 word: true,
1363 regex: true,
1364 replacement: true,
1365 selection: true,
1366 find_in_results: false,
1367 }
1368 }
1369 }
1370
1371 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1372 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1373 let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1374 let selection = self.selections.newest::<usize>(cx);
1375
1376 match setting {
1377 SeedQuerySetting::Never => String::new(),
1378 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1379 let text: String = snapshot
1380 .text_for_range(selection.start..selection.end)
1381 .collect();
1382 if text.contains('\n') {
1383 String::new()
1384 } else {
1385 text
1386 }
1387 }
1388 SeedQuerySetting::Selection => String::new(),
1389 SeedQuerySetting::Always => {
1390 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1391 if kind == Some(CharKind::Word) {
1392 let text: String = snapshot.text_for_range(range).collect();
1393 if !text.trim().is_empty() {
1394 return text;
1395 }
1396 }
1397 String::new()
1398 }
1399 }
1400 }
1401
1402 fn activate_match(
1403 &mut self,
1404 index: usize,
1405 matches: &[Range<Anchor>],
1406 window: &mut Window,
1407 cx: &mut Context<Self>,
1408 ) {
1409 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1410 let range = self.range_for_match(&matches[index]);
1411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1412 s.select_ranges([range]);
1413 })
1414 }
1415
1416 fn select_matches(
1417 &mut self,
1418 matches: &[Self::Match],
1419 window: &mut Window,
1420 cx: &mut Context<Self>,
1421 ) {
1422 self.unfold_ranges(matches, false, false, cx);
1423 self.change_selections(None, window, cx, |s| {
1424 s.select_ranges(matches.iter().cloned())
1425 });
1426 }
1427 fn replace(
1428 &mut self,
1429 identifier: &Self::Match,
1430 query: &SearchQuery,
1431 window: &mut Window,
1432 cx: &mut Context<Self>,
1433 ) {
1434 let text = self.buffer.read(cx);
1435 let text = text.snapshot(cx);
1436 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1437 let text: Cow<_> = if text.len() == 1 {
1438 text.first().cloned().unwrap().into()
1439 } else {
1440 let joined_chunks = text.join("");
1441 joined_chunks.into()
1442 };
1443
1444 if let Some(replacement) = query.replacement_for(&text) {
1445 self.transact(window, cx, |this, _, cx| {
1446 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1447 });
1448 }
1449 }
1450 fn replace_all(
1451 &mut self,
1452 matches: &mut dyn Iterator<Item = &Self::Match>,
1453 query: &SearchQuery,
1454 window: &mut Window,
1455 cx: &mut Context<Self>,
1456 ) {
1457 let text = self.buffer.read(cx);
1458 let text = text.snapshot(cx);
1459 let mut edits = vec![];
1460 for m in matches {
1461 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1462 let text: Cow<_> = if text.len() == 1 {
1463 text.first().cloned().unwrap().into()
1464 } else {
1465 let joined_chunks = text.join("");
1466 joined_chunks.into()
1467 };
1468
1469 if let Some(replacement) = query.replacement_for(&text) {
1470 edits.push((m.clone(), Arc::from(&*replacement)));
1471 }
1472 }
1473
1474 if !edits.is_empty() {
1475 self.transact(window, cx, |this, _, cx| {
1476 this.edit(edits, cx);
1477 });
1478 }
1479 }
1480 fn match_index_for_direction(
1481 &mut self,
1482 matches: &[Range<Anchor>],
1483 current_index: usize,
1484 direction: Direction,
1485 count: usize,
1486 _: &mut Window,
1487 cx: &mut Context<Self>,
1488 ) -> usize {
1489 let buffer = self.buffer().read(cx).snapshot(cx);
1490 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1491 self.selections.newest_anchor().head()
1492 } else {
1493 matches[current_index].start
1494 };
1495
1496 let mut count = count % matches.len();
1497 if count == 0 {
1498 return current_index;
1499 }
1500 match direction {
1501 Direction::Next => {
1502 if matches[current_index]
1503 .start
1504 .cmp(¤t_index_position, &buffer)
1505 .is_gt()
1506 {
1507 count -= 1
1508 }
1509
1510 (current_index + count) % matches.len()
1511 }
1512 Direction::Prev => {
1513 if matches[current_index]
1514 .end
1515 .cmp(¤t_index_position, &buffer)
1516 .is_lt()
1517 {
1518 count -= 1;
1519 }
1520
1521 if current_index >= count {
1522 current_index - count
1523 } else {
1524 matches.len() - (count - current_index)
1525 }
1526 }
1527 }
1528 }
1529
1530 fn find_matches(
1531 &mut self,
1532 query: Arc<project::search::SearchQuery>,
1533 _: &mut Window,
1534 cx: &mut Context<Self>,
1535 ) -> Task<Vec<Range<Anchor>>> {
1536 let buffer = self.buffer().read(cx).snapshot(cx);
1537 let search_within_ranges = self
1538 .background_highlights
1539 .get(&TypeId::of::<SearchWithinRange>())
1540 .map_or(vec![], |(_color, ranges)| {
1541 ranges.iter().cloned().collect::<Vec<_>>()
1542 });
1543
1544 cx.background_spawn(async move {
1545 let mut ranges = Vec::new();
1546
1547 let search_within_ranges = if search_within_ranges.is_empty() {
1548 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1549 } else {
1550 search_within_ranges
1551 };
1552
1553 for range in search_within_ranges {
1554 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1555 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1556 {
1557 ranges.extend(
1558 query
1559 .search(search_buffer, Some(search_range.clone()))
1560 .await
1561 .into_iter()
1562 .map(|match_range| {
1563 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1564 let start = search_buffer
1565 .anchor_after(search_range.start + match_range.start);
1566 let end = search_buffer
1567 .anchor_before(search_range.start + match_range.end);
1568 Anchor {
1569 diff_base_anchor: Some(start),
1570 ..deleted_hunk_anchor
1571 }..Anchor {
1572 diff_base_anchor: Some(end),
1573 ..deleted_hunk_anchor
1574 }
1575 } else {
1576 let start = search_buffer
1577 .anchor_after(search_range.start + match_range.start);
1578 let end = search_buffer
1579 .anchor_before(search_range.start + match_range.end);
1580 Anchor::range_in_buffer(
1581 excerpt_id,
1582 search_buffer.remote_id(),
1583 start..end,
1584 )
1585 }
1586 }),
1587 );
1588 }
1589 }
1590
1591 ranges
1592 })
1593 }
1594
1595 fn active_match_index(
1596 &mut self,
1597 direction: Direction,
1598 matches: &[Range<Anchor>],
1599 _: &mut Window,
1600 cx: &mut Context<Self>,
1601 ) -> Option<usize> {
1602 active_match_index(
1603 direction,
1604 matches,
1605 &self.selections.newest_anchor().head(),
1606 &self.buffer().read(cx).snapshot(cx),
1607 )
1608 }
1609
1610 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1611 self.expect_bounds_change = self.last_bounds;
1612 }
1613}
1614
1615pub fn active_match_index(
1616 direction: Direction,
1617 ranges: &[Range<Anchor>],
1618 cursor: &Anchor,
1619 buffer: &MultiBufferSnapshot,
1620) -> Option<usize> {
1621 if ranges.is_empty() {
1622 None
1623 } else {
1624 let r = ranges.binary_search_by(|probe| {
1625 if probe.end.cmp(cursor, buffer).is_lt() {
1626 Ordering::Less
1627 } else if probe.start.cmp(cursor, buffer).is_gt() {
1628 Ordering::Greater
1629 } else {
1630 Ordering::Equal
1631 }
1632 });
1633 match direction {
1634 Direction::Prev => match r {
1635 Ok(i) => Some(i),
1636 Err(i) => Some(i.saturating_sub(1)),
1637 },
1638 Direction::Next => match r {
1639 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1640 },
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::VersionControlIgnored
1677 } else if git_status.conflict > 0 {
1678 Color::VersionControlConflict
1679 } else if tracked.modified > 0 {
1680 Color::VersionControlModified
1681 } else if tracked.added > 0 || git_status.untracked > 0 {
1682 Color::VersionControlAdded
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}