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