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