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