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 if let Some(entry) = buffer.peek_undo_stack() {
1077 buffer.forget_transaction(entry.transaction_id());
1078 }
1079 })?;
1080
1081 cx.update(|window, cx| {
1082 cx.new(|cx| {
1083 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1084
1085 editor.read_selections_from_db(item_id, workspace_id, window, cx);
1086 editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1087 editor
1088 })
1089 })
1090 }
1091 }),
1092 SerializedEditor {
1093 abs_path: Some(abs_path),
1094 contents,
1095 mtime,
1096 ..
1097 } => {
1098 let project_item = project.update(cx, |project, cx| {
1099 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1100 let project_path = ProjectPath {
1101 worktree_id: worktree.read(cx).id(),
1102 path: path.into(),
1103 };
1104 Some(project.open_path(project_path, cx))
1105 });
1106
1107 match project_item {
1108 Some(project_item) => {
1109 window.spawn(cx, |mut cx| async move {
1110 let (_, project_item) = project_item.await?;
1111 let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1112 anyhow!("Project item at stored path was not a buffer")
1113 })?;
1114
1115 // This is a bit wasteful: we're loading the whole buffer from
1116 // disk and then overwrite the content.
1117 // But for now, it keeps the implementation of the content serialization
1118 // simple, because we don't have to persist all of the metadata that we get
1119 // by loading the file (git diff base, ...).
1120 if let Some(buffer_text) = contents {
1121 buffer.update(&mut cx, |buffer, cx| {
1122 // If we did restore an mtime, we want to store it on the buffer
1123 // so that the next edit will mark the buffer as dirty/conflicted.
1124 if mtime.is_some() {
1125 buffer.did_reload(
1126 buffer.version(),
1127 buffer.line_ending(),
1128 mtime,
1129 cx,
1130 );
1131 }
1132 buffer.set_text(buffer_text, cx);
1133 if let Some(entry) = buffer.peek_undo_stack() {
1134 buffer.forget_transaction(entry.transaction_id());
1135 }
1136 })?;
1137 }
1138
1139 cx.update(|window, cx| {
1140 cx.new(|cx| {
1141 let mut editor =
1142 Editor::for_buffer(buffer, Some(project), window, cx);
1143
1144 editor.read_selections_from_db(
1145 item_id,
1146 workspace_id,
1147 window,
1148 cx,
1149 );
1150 editor.read_scroll_position_from_db(
1151 item_id,
1152 workspace_id,
1153 window,
1154 cx,
1155 );
1156 editor
1157 })
1158 })
1159 })
1160 }
1161 None => {
1162 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1163 workspace.open_abs_path(abs_path.clone(), false, window, cx)
1164 });
1165 window.spawn(cx, |mut cx| async move {
1166 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1167 editor.update_in(&mut cx, |editor, window, cx| {
1168 editor.read_selections_from_db(item_id, workspace_id, window, cx);
1169 editor.read_scroll_position_from_db(item_id, workspace_id, window, cx);
1170 })?;
1171 Ok(editor)
1172 })
1173 }
1174 }
1175 }
1176 SerializedEditor {
1177 abs_path: None,
1178 contents: None,
1179 ..
1180 } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1181 }
1182 }
1183
1184 fn serialize(
1185 &mut self,
1186 workspace: &mut Workspace,
1187 item_id: ItemId,
1188 closing: bool,
1189 window: &mut Window,
1190 cx: &mut Context<Self>,
1191 ) -> Option<Task<Result<()>>> {
1192 let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1193
1194 let project = self.project.clone()?;
1195 if project.read(cx).visible_worktrees(cx).next().is_none() {
1196 // If we don't have a worktree, we don't serialize, because
1197 // projects without worktrees aren't deserialized.
1198 serialize_dirty_buffers = false;
1199 }
1200
1201 if closing && !serialize_dirty_buffers {
1202 return None;
1203 }
1204
1205 let workspace_id = workspace.database_id()?;
1206
1207 let buffer = self.buffer().read(cx).as_singleton()?;
1208
1209 let abs_path = buffer.read(cx).file().and_then(|file| {
1210 let worktree_id = file.worktree_id(cx);
1211 project
1212 .read(cx)
1213 .worktree_for_id(worktree_id, cx)
1214 .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1215 .or_else(|| {
1216 let full_path = file.full_path(cx);
1217 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1218 project.read(cx).absolute_path(&project_path, cx)
1219 })
1220 });
1221
1222 let is_dirty = buffer.read(cx).is_dirty();
1223 let mtime = buffer.read(cx).saved_mtime();
1224
1225 let snapshot = buffer.read(cx).snapshot();
1226
1227 Some(cx.spawn_in(window, |_this, cx| async move {
1228 cx.background_executor()
1229 .spawn(async move {
1230 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1231 let contents = snapshot.text();
1232 let language = snapshot.language().map(|lang| lang.name().to_string());
1233 (Some(contents), language)
1234 } else {
1235 (None, None)
1236 };
1237
1238 let editor = SerializedEditor {
1239 abs_path,
1240 contents,
1241 language,
1242 mtime,
1243 };
1244 DB.save_serialized_editor(item_id, workspace_id, editor)
1245 .await
1246 .context("failed to save serialized editor")
1247 })
1248 .await
1249 .context("failed to save contents of buffer")?;
1250
1251 Ok(())
1252 }))
1253 }
1254
1255 fn should_serialize(&self, event: &Self::Event) -> bool {
1256 matches!(
1257 event,
1258 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1259 )
1260 }
1261}
1262
1263impl ProjectItem for Editor {
1264 type Item = Buffer;
1265
1266 fn for_project_item(
1267 project: Entity<Project>,
1268 buffer: Entity<Buffer>,
1269 window: &mut Window,
1270 cx: &mut Context<Self>,
1271 ) -> Self {
1272 Self::for_buffer(buffer, Some(project), window, cx)
1273 }
1274}
1275
1276impl EventEmitter<SearchEvent> for Editor {}
1277
1278pub(crate) enum BufferSearchHighlights {}
1279impl SearchableItem for Editor {
1280 type Match = Range<Anchor>;
1281
1282 fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1283 self.background_highlights
1284 .get(&TypeId::of::<BufferSearchHighlights>())
1285 .map_or(Vec::new(), |(_color, ranges)| {
1286 ranges.iter().cloned().collect()
1287 })
1288 }
1289
1290 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1291 if self
1292 .clear_background_highlights::<BufferSearchHighlights>(cx)
1293 .is_some()
1294 {
1295 cx.emit(SearchEvent::MatchesInvalidated);
1296 }
1297 }
1298
1299 fn update_matches(
1300 &mut self,
1301 matches: &[Range<Anchor>],
1302 _: &mut Window,
1303 cx: &mut Context<Self>,
1304 ) {
1305 let existing_range = self
1306 .background_highlights
1307 .get(&TypeId::of::<BufferSearchHighlights>())
1308 .map(|(_, range)| range.as_ref());
1309 let updated = existing_range != Some(matches);
1310 self.highlight_background::<BufferSearchHighlights>(
1311 matches,
1312 |theme| theme.search_match_background,
1313 cx,
1314 );
1315 if updated {
1316 cx.emit(SearchEvent::MatchesInvalidated);
1317 }
1318 }
1319
1320 fn has_filtered_search_ranges(&mut self) -> bool {
1321 self.has_background_highlights::<SearchWithinRange>()
1322 }
1323
1324 fn toggle_filtered_search_ranges(
1325 &mut self,
1326 enabled: bool,
1327 _: &mut Window,
1328 cx: &mut Context<Self>,
1329 ) {
1330 if self.has_filtered_search_ranges() {
1331 self.previous_search_ranges = self
1332 .clear_background_highlights::<SearchWithinRange>(cx)
1333 .map(|(_, ranges)| ranges)
1334 }
1335
1336 if !enabled {
1337 return;
1338 }
1339
1340 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1341 if ranges.iter().any(|s| s.start != s.end) {
1342 self.set_search_within_ranges(&ranges, cx);
1343 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1344 self.set_search_within_ranges(&previous_search_ranges, cx)
1345 }
1346 }
1347
1348 fn supported_options(&self) -> SearchOptions {
1349 if self.in_project_search {
1350 SearchOptions {
1351 case: true,
1352 word: true,
1353 regex: true,
1354 replacement: false,
1355 selection: false,
1356 find_in_results: true,
1357 }
1358 } else {
1359 SearchOptions {
1360 case: true,
1361 word: true,
1362 regex: true,
1363 replacement: true,
1364 selection: true,
1365 find_in_results: false,
1366 }
1367 }
1368 }
1369
1370 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1371 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1372 let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1373 let selection = self.selections.newest::<usize>(cx);
1374
1375 match setting {
1376 SeedQuerySetting::Never => String::new(),
1377 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1378 let text: String = snapshot
1379 .text_for_range(selection.start..selection.end)
1380 .collect();
1381 if text.contains('\n') {
1382 String::new()
1383 } else {
1384 text
1385 }
1386 }
1387 SeedQuerySetting::Selection => String::new(),
1388 SeedQuerySetting::Always => {
1389 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1390 if kind == Some(CharKind::Word) {
1391 let text: String = snapshot.text_for_range(range).collect();
1392 if !text.trim().is_empty() {
1393 return text;
1394 }
1395 }
1396 String::new()
1397 }
1398 }
1399 }
1400
1401 fn activate_match(
1402 &mut self,
1403 index: usize,
1404 matches: &[Range<Anchor>],
1405 window: &mut Window,
1406 cx: &mut Context<Self>,
1407 ) {
1408 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1409 let range = self.range_for_match(&matches[index]);
1410 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1411 s.select_ranges([range]);
1412 })
1413 }
1414
1415 fn select_matches(
1416 &mut self,
1417 matches: &[Self::Match],
1418 window: &mut Window,
1419 cx: &mut Context<Self>,
1420 ) {
1421 self.unfold_ranges(matches, false, false, cx);
1422 self.change_selections(None, window, cx, |s| {
1423 s.select_ranges(matches.iter().cloned())
1424 });
1425 }
1426 fn replace(
1427 &mut self,
1428 identifier: &Self::Match,
1429 query: &SearchQuery,
1430 window: &mut Window,
1431 cx: &mut Context<Self>,
1432 ) {
1433 let text = self.buffer.read(cx);
1434 let text = text.snapshot(cx);
1435 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1436 let text: Cow<_> = if text.len() == 1 {
1437 text.first().cloned().unwrap().into()
1438 } else {
1439 let joined_chunks = text.join("");
1440 joined_chunks.into()
1441 };
1442
1443 if let Some(replacement) = query.replacement_for(&text) {
1444 self.transact(window, cx, |this, _, cx| {
1445 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1446 });
1447 }
1448 }
1449 fn replace_all(
1450 &mut self,
1451 matches: &mut dyn Iterator<Item = &Self::Match>,
1452 query: &SearchQuery,
1453 window: &mut Window,
1454 cx: &mut Context<Self>,
1455 ) {
1456 let text = self.buffer.read(cx);
1457 let text = text.snapshot(cx);
1458 let mut edits = vec![];
1459 for m in matches {
1460 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1461 let text: Cow<_> = if text.len() == 1 {
1462 text.first().cloned().unwrap().into()
1463 } else {
1464 let joined_chunks = text.join("");
1465 joined_chunks.into()
1466 };
1467
1468 if let Some(replacement) = query.replacement_for(&text) {
1469 edits.push((m.clone(), Arc::from(&*replacement)));
1470 }
1471 }
1472
1473 if !edits.is_empty() {
1474 self.transact(window, cx, |this, _, cx| {
1475 this.edit(edits, cx);
1476 });
1477 }
1478 }
1479 fn match_index_for_direction(
1480 &mut self,
1481 matches: &[Range<Anchor>],
1482 current_index: usize,
1483 direction: Direction,
1484 count: usize,
1485 _: &mut Window,
1486 cx: &mut Context<Self>,
1487 ) -> usize {
1488 let buffer = self.buffer().read(cx).snapshot(cx);
1489 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1490 self.selections.newest_anchor().head()
1491 } else {
1492 matches[current_index].start
1493 };
1494
1495 let mut count = count % matches.len();
1496 if count == 0 {
1497 return current_index;
1498 }
1499 match direction {
1500 Direction::Next => {
1501 if matches[current_index]
1502 .start
1503 .cmp(¤t_index_position, &buffer)
1504 .is_gt()
1505 {
1506 count -= 1
1507 }
1508
1509 (current_index + count) % matches.len()
1510 }
1511 Direction::Prev => {
1512 if matches[current_index]
1513 .end
1514 .cmp(¤t_index_position, &buffer)
1515 .is_lt()
1516 {
1517 count -= 1;
1518 }
1519
1520 if current_index >= count {
1521 current_index - count
1522 } else {
1523 matches.len() - (count - current_index)
1524 }
1525 }
1526 }
1527 }
1528
1529 fn find_matches(
1530 &mut self,
1531 query: Arc<project::search::SearchQuery>,
1532 _: &mut Window,
1533 cx: &mut Context<Self>,
1534 ) -> Task<Vec<Range<Anchor>>> {
1535 let buffer = self.buffer().read(cx).snapshot(cx);
1536 let search_within_ranges = self
1537 .background_highlights
1538 .get(&TypeId::of::<SearchWithinRange>())
1539 .map_or(vec![], |(_color, ranges)| {
1540 ranges.iter().cloned().collect::<Vec<_>>()
1541 });
1542
1543 cx.background_executor().spawn(async move {
1544 let mut ranges = Vec::new();
1545
1546 let search_within_ranges = if search_within_ranges.is_empty() {
1547 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1548 } else {
1549 search_within_ranges
1550 };
1551
1552 for range in search_within_ranges {
1553 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1554 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1555 {
1556 ranges.extend(
1557 query
1558 .search(search_buffer, Some(search_range.clone()))
1559 .await
1560 .into_iter()
1561 .map(|match_range| {
1562 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1563 let start = search_buffer
1564 .anchor_after(search_range.start + match_range.start);
1565 let end = search_buffer
1566 .anchor_before(search_range.start + match_range.end);
1567 Anchor {
1568 diff_base_anchor: Some(start),
1569 ..deleted_hunk_anchor
1570 }..Anchor {
1571 diff_base_anchor: Some(end),
1572 ..deleted_hunk_anchor
1573 }
1574 } else {
1575 let start = search_buffer
1576 .anchor_after(search_range.start + match_range.start);
1577 let end = search_buffer
1578 .anchor_before(search_range.start + match_range.end);
1579 Anchor::range_in_buffer(
1580 excerpt_id,
1581 search_buffer.remote_id(),
1582 start..end,
1583 )
1584 }
1585 }),
1586 );
1587 }
1588 }
1589
1590 ranges
1591 })
1592 }
1593
1594 fn active_match_index(
1595 &mut self,
1596 matches: &[Range<Anchor>],
1597 _: &mut Window,
1598 cx: &mut Context<Self>,
1599 ) -> Option<usize> {
1600 active_match_index(
1601 matches,
1602 &self.selections.newest_anchor().head(),
1603 &self.buffer().read(cx).snapshot(cx),
1604 )
1605 }
1606
1607 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1608 self.expect_bounds_change = self.last_bounds;
1609 }
1610}
1611
1612pub fn active_match_index(
1613 ranges: &[Range<Anchor>],
1614 cursor: &Anchor,
1615 buffer: &MultiBufferSnapshot,
1616) -> Option<usize> {
1617 if ranges.is_empty() {
1618 None
1619 } else {
1620 match ranges.binary_search_by(|probe| {
1621 if probe.end.cmp(cursor, buffer).is_lt() {
1622 Ordering::Less
1623 } else if probe.start.cmp(cursor, buffer).is_gt() {
1624 Ordering::Greater
1625 } else {
1626 Ordering::Equal
1627 }
1628 }) {
1629 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1630 }
1631 }
1632}
1633
1634pub fn entry_label_color(selected: bool) -> Color {
1635 if selected {
1636 Color::Default
1637 } else {
1638 Color::Muted
1639 }
1640}
1641
1642pub fn entry_diagnostic_aware_icon_name_and_color(
1643 diagnostic_severity: Option<DiagnosticSeverity>,
1644) -> Option<(IconName, Color)> {
1645 match diagnostic_severity {
1646 Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1647 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1648 _ => None,
1649 }
1650}
1651
1652pub fn entry_diagnostic_aware_icon_decoration_and_color(
1653 diagnostic_severity: Option<DiagnosticSeverity>,
1654) -> Option<(IconDecorationKind, Color)> {
1655 match diagnostic_severity {
1656 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1657 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1658 _ => None,
1659 }
1660}
1661
1662pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1663 let tracked = git_status.index + git_status.worktree;
1664 if ignored {
1665 Color::Ignored
1666 } else if git_status.conflict > 0 {
1667 Color::Conflict
1668 } else if tracked.modified > 0 {
1669 Color::Modified
1670 } else if tracked.added > 0 || git_status.untracked > 0 {
1671 Color::Created
1672 } else {
1673 entry_label_color(selected)
1674 }
1675}
1676
1677fn path_for_buffer<'a>(
1678 buffer: &Entity<MultiBuffer>,
1679 height: usize,
1680 include_filename: bool,
1681 cx: &'a App,
1682) -> Option<Cow<'a, Path>> {
1683 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1684 path_for_file(file.as_ref(), height, include_filename, cx)
1685}
1686
1687fn path_for_file<'a>(
1688 file: &'a dyn language::File,
1689 mut height: usize,
1690 include_filename: bool,
1691 cx: &'a App,
1692) -> Option<Cow<'a, Path>> {
1693 // Ensure we always render at least the filename.
1694 height += 1;
1695
1696 let mut prefix = file.path().as_ref();
1697 while height > 0 {
1698 if let Some(parent) = prefix.parent() {
1699 prefix = parent;
1700 height -= 1;
1701 } else {
1702 break;
1703 }
1704 }
1705
1706 // Here we could have just always used `full_path`, but that is very
1707 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1708 // traversed all the way up to the worktree's root.
1709 if height > 0 {
1710 let full_path = file.full_path(cx);
1711 if include_filename {
1712 Some(full_path.into())
1713 } else {
1714 Some(full_path.parent()?.to_path_buf().into())
1715 }
1716 } else {
1717 let mut path = file.path().strip_prefix(prefix).ok()?;
1718 if !include_filename {
1719 path = path.parent()?;
1720 }
1721 Some(path.into())
1722 }
1723}
1724
1725#[cfg(test)]
1726mod tests {
1727 use crate::editor_tests::init_test;
1728 use fs::Fs;
1729
1730 use super::*;
1731 use fs::MTime;
1732 use gpui::{App, VisualTestContext};
1733 use language::{LanguageMatcher, TestFile};
1734 use project::FakeFs;
1735 use std::path::{Path, PathBuf};
1736 use util::path;
1737
1738 #[gpui::test]
1739 fn test_path_for_file(cx: &mut App) {
1740 let file = TestFile {
1741 path: Path::new("").into(),
1742 root_name: String::new(),
1743 };
1744 assert_eq!(path_for_file(&file, 0, false, cx), None);
1745 }
1746
1747 async fn deserialize_editor(
1748 item_id: ItemId,
1749 workspace_id: WorkspaceId,
1750 workspace: Entity<Workspace>,
1751 project: Entity<Project>,
1752 cx: &mut VisualTestContext,
1753 ) -> Entity<Editor> {
1754 workspace
1755 .update_in(cx, |workspace, window, cx| {
1756 let pane = workspace.active_pane();
1757 pane.update(cx, |_, cx| {
1758 Editor::deserialize(
1759 project.clone(),
1760 workspace.weak_handle(),
1761 workspace_id,
1762 item_id,
1763 window,
1764 cx,
1765 )
1766 })
1767 })
1768 .await
1769 .unwrap()
1770 }
1771
1772 fn rust_language() -> Arc<language::Language> {
1773 Arc::new(language::Language::new(
1774 language::LanguageConfig {
1775 name: "Rust".into(),
1776 matcher: LanguageMatcher {
1777 path_suffixes: vec!["rs".to_string()],
1778 ..Default::default()
1779 },
1780 ..Default::default()
1781 },
1782 Some(tree_sitter_rust::LANGUAGE.into()),
1783 ))
1784 }
1785
1786 #[gpui::test]
1787 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1788 init_test(cx, |_| {});
1789
1790 let fs = FakeFs::new(cx.executor());
1791 fs.insert_file(path!("/file.rs"), Default::default()).await;
1792
1793 // Test case 1: Deserialize with path and contents
1794 {
1795 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1796 let (workspace, cx) =
1797 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1798 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1799 let item_id = 1234 as ItemId;
1800 let mtime = fs
1801 .metadata(Path::new(path!("/file.rs")))
1802 .await
1803 .unwrap()
1804 .unwrap()
1805 .mtime;
1806
1807 let serialized_editor = SerializedEditor {
1808 abs_path: Some(PathBuf::from(path!("/file.rs"))),
1809 contents: Some("fn main() {}".to_string()),
1810 language: Some("Rust".to_string()),
1811 mtime: Some(mtime),
1812 };
1813
1814 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1815 .await
1816 .unwrap();
1817
1818 let deserialized =
1819 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1820
1821 deserialized.update(cx, |editor, cx| {
1822 assert_eq!(editor.text(cx), "fn main() {}");
1823 assert!(editor.is_dirty(cx));
1824 assert!(!editor.has_conflict(cx));
1825 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1826 assert!(buffer.file().is_some());
1827 });
1828 }
1829
1830 // Test case 2: Deserialize with only path
1831 {
1832 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1833 let (workspace, cx) =
1834 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1835
1836 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1837
1838 let item_id = 5678 as ItemId;
1839 let serialized_editor = SerializedEditor {
1840 abs_path: Some(PathBuf::from(path!("/file.rs"))),
1841 contents: None,
1842 language: None,
1843 mtime: None,
1844 };
1845
1846 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1847 .await
1848 .unwrap();
1849
1850 let deserialized =
1851 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1852
1853 deserialized.update(cx, |editor, cx| {
1854 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1855 assert!(!editor.is_dirty(cx));
1856 assert!(!editor.has_conflict(cx));
1857
1858 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1859 assert!(buffer.file().is_some());
1860 });
1861 }
1862
1863 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1864 {
1865 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1866 // Add Rust to the language, so that we can restore the language of the buffer
1867 project.update(cx, |project, _| project.languages().add(rust_language()));
1868
1869 let (workspace, cx) =
1870 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1871
1872 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1873
1874 let item_id = 9012 as ItemId;
1875 let serialized_editor = SerializedEditor {
1876 abs_path: None,
1877 contents: Some("hello".to_string()),
1878 language: Some("Rust".to_string()),
1879 mtime: None,
1880 };
1881
1882 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1883 .await
1884 .unwrap();
1885
1886 let deserialized =
1887 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1888
1889 deserialized.update(cx, |editor, cx| {
1890 assert_eq!(editor.text(cx), "hello");
1891 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
1892
1893 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1894 assert_eq!(
1895 buffer.language().map(|lang| lang.name()),
1896 Some("Rust".into())
1897 ); // Language should be set to Rust
1898 assert!(buffer.file().is_none()); // The buffer should not have an associated file
1899 });
1900 }
1901
1902 // Test case 4: Deserialize with path, content, and old mtime
1903 {
1904 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1905 let (workspace, cx) =
1906 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1907
1908 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1909
1910 let item_id = 9345 as ItemId;
1911 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
1912 let serialized_editor = SerializedEditor {
1913 abs_path: Some(PathBuf::from(path!("/file.rs"))),
1914 contents: Some("fn main() {}".to_string()),
1915 language: Some("Rust".to_string()),
1916 mtime: Some(old_mtime),
1917 };
1918
1919 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1920 .await
1921 .unwrap();
1922
1923 let deserialized =
1924 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1925
1926 deserialized.update(cx, |editor, cx| {
1927 assert_eq!(editor.text(cx), "fn main() {}");
1928 assert!(editor.has_conflict(cx)); // The editor should have a conflict
1929 });
1930 }
1931 }
1932}