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