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