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 .update(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.update(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 project_item = 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 project_item {
1148 Some(project_item) => {
1149 window.spawn(cx, async move |cx| {
1150 let (_, project_item) = project_item.await?;
1151 let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1152 anyhow!("Project item at stored path was not a buffer")
1153 })?;
1154
1155 // This is a bit wasteful: we're loading the whole buffer from
1156 // disk and then overwrite the content.
1157 // But for now, it keeps the implementation of the content serialization
1158 // simple, because we don't have to persist all of the metadata that we get
1159 // by loading the file (git diff base, ...).
1160 if let Some(buffer_text) = contents {
1161 buffer.update(cx, |buffer, cx| {
1162 // If we did restore an mtime, we want to store it on the buffer
1163 // so that the next edit will mark the buffer as dirty/conflicted.
1164 if mtime.is_some() {
1165 buffer.did_reload(
1166 buffer.version(),
1167 buffer.line_ending(),
1168 mtime,
1169 cx,
1170 );
1171 }
1172 buffer.set_text(buffer_text, cx);
1173 if let Some(entry) = buffer.peek_undo_stack() {
1174 buffer.forget_transaction(entry.transaction_id());
1175 }
1176 })?;
1177 }
1178
1179 cx.update(|window, cx| {
1180 cx.new(|cx| {
1181 let mut editor =
1182 Editor::for_buffer(buffer, Some(project), window, cx);
1183
1184 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1185 editor
1186 })
1187 })
1188 })
1189 }
1190 None => {
1191 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1192 workspace.open_abs_path(
1193 abs_path.clone(),
1194 OpenOptions {
1195 visible: Some(OpenVisible::None),
1196 ..Default::default()
1197 },
1198 window,
1199 cx,
1200 )
1201 });
1202 window.spawn(cx, async move |cx| {
1203 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1204 editor.update_in(cx, |editor, window, cx| {
1205 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1206 })?;
1207 Ok(editor)
1208 })
1209 }
1210 }
1211 }
1212 SerializedEditor {
1213 abs_path: None,
1214 contents: None,
1215 ..
1216 } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1217 }
1218 }
1219
1220 fn serialize(
1221 &mut self,
1222 workspace: &mut Workspace,
1223 item_id: ItemId,
1224 closing: bool,
1225 window: &mut Window,
1226 cx: &mut Context<Self>,
1227 ) -> Option<Task<Result<()>>> {
1228 if self.mode.is_minimap() {
1229 return None;
1230 }
1231 let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1232
1233 let project = self.project.clone()?;
1234 if project.read(cx).visible_worktrees(cx).next().is_none() {
1235 // If we don't have a worktree, we don't serialize, because
1236 // projects without worktrees aren't deserialized.
1237 serialize_dirty_buffers = false;
1238 }
1239
1240 if closing && !serialize_dirty_buffers {
1241 return None;
1242 }
1243
1244 let workspace_id = workspace.database_id()?;
1245
1246 let buffer = self.buffer().read(cx).as_singleton()?;
1247
1248 let abs_path = buffer.read(cx).file().and_then(|file| {
1249 let worktree_id = file.worktree_id(cx);
1250 project
1251 .read(cx)
1252 .worktree_for_id(worktree_id, cx)
1253 .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1254 .or_else(|| {
1255 let full_path = file.full_path(cx);
1256 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1257 project.read(cx).absolute_path(&project_path, cx)
1258 })
1259 });
1260
1261 let is_dirty = buffer.read(cx).is_dirty();
1262 let mtime = buffer.read(cx).saved_mtime();
1263
1264 let snapshot = buffer.read(cx).snapshot();
1265
1266 Some(cx.spawn_in(window, async move |_this, cx| {
1267 cx.background_spawn(async move {
1268 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1269 let contents = snapshot.text();
1270 let language = snapshot.language().map(|lang| lang.name().to_string());
1271 (Some(contents), language)
1272 } else {
1273 (None, None)
1274 };
1275
1276 let editor = SerializedEditor {
1277 abs_path,
1278 contents,
1279 language,
1280 mtime,
1281 };
1282 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1283 DB.save_serialized_editor(item_id, workspace_id, editor)
1284 .await
1285 .context("failed to save serialized editor")
1286 })
1287 .await
1288 .context("failed to save contents of buffer")?;
1289
1290 Ok(())
1291 }))
1292 }
1293
1294 fn should_serialize(&self, event: &Self::Event) -> bool {
1295 matches!(
1296 event,
1297 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1298 )
1299 }
1300}
1301
1302#[derive(Debug, Default)]
1303struct EditorRestorationData {
1304 entries: HashMap<PathBuf, RestorationData>,
1305}
1306
1307#[derive(Default, Debug)]
1308pub struct RestorationData {
1309 pub scroll_position: (BufferRow, gpui::Point<f32>),
1310 pub folds: Vec<Range<Point>>,
1311 pub selections: Vec<Range<Point>>,
1312}
1313
1314impl ProjectItem for Editor {
1315 type Item = Buffer;
1316
1317 fn project_item_kind() -> Option<ProjectItemKind> {
1318 Some(ProjectItemKind("Editor"))
1319 }
1320
1321 fn for_project_item(
1322 project: Entity<Project>,
1323 pane: Option<&Pane>,
1324 buffer: Entity<Buffer>,
1325 window: &mut Window,
1326 cx: &mut Context<Self>,
1327 ) -> Self {
1328 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1329 if let Some((excerpt_id, buffer_id, snapshot)) =
1330 editor.buffer().read(cx).snapshot(cx).as_singleton()
1331 {
1332 if WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1333 if let Some(restoration_data) = Self::project_item_kind()
1334 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1335 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1336 .and_then(|data| {
1337 let file = project::File::from_dyn(buffer.read(cx).file())?;
1338 data.entries.get(&file.abs_path(cx))
1339 })
1340 {
1341 editor.fold_ranges(
1342 clip_ranges(&restoration_data.folds, &snapshot),
1343 false,
1344 window,
1345 cx,
1346 );
1347 if !restoration_data.selections.is_empty() {
1348 editor.change_selections(None, window, cx, |s| {
1349 s.select_ranges(clip_ranges(&restoration_data.selections, &snapshot));
1350 });
1351 }
1352 let (top_row, offset) = restoration_data.scroll_position;
1353 let anchor = Anchor::in_buffer(
1354 *excerpt_id,
1355 buffer_id,
1356 snapshot.anchor_before(Point::new(top_row, 0)),
1357 );
1358 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1359 }
1360 }
1361 }
1362
1363 editor
1364 }
1365}
1366
1367fn clip_ranges<'a>(
1368 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1369 snapshot: &'a BufferSnapshot,
1370) -> Vec<Range<Point>> {
1371 original
1372 .into_iter()
1373 .map(|range| {
1374 snapshot.clip_point(range.start, Bias::Left)
1375 ..snapshot.clip_point(range.end, Bias::Right)
1376 })
1377 .collect()
1378}
1379
1380impl EventEmitter<SearchEvent> for Editor {}
1381
1382impl Editor {
1383 pub fn update_restoration_data(
1384 &self,
1385 cx: &mut Context<Self>,
1386 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1387 ) {
1388 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1389 return;
1390 }
1391
1392 let editor = cx.entity();
1393 cx.defer(move |cx| {
1394 editor.update(cx, |editor, cx| {
1395 let kind = Editor::project_item_kind()?;
1396 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1397 let buffer = editor.buffer().read(cx).as_singleton()?;
1398 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1399 pane.update(cx, |pane, _| {
1400 let data = pane
1401 .project_item_restoration_data
1402 .entry(kind)
1403 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1404 let data = match data.downcast_mut::<EditorRestorationData>() {
1405 Some(data) => data,
1406 None => {
1407 *data = Box::new(EditorRestorationData::default());
1408 data.downcast_mut::<EditorRestorationData>()
1409 .expect("just written the type downcasted to")
1410 }
1411 };
1412
1413 let data = data.entries.entry(file_abs_path).or_default();
1414 write(data);
1415 Some(())
1416 })
1417 });
1418 });
1419 }
1420}
1421
1422pub(crate) enum BufferSearchHighlights {}
1423impl SearchableItem for Editor {
1424 type Match = Range<Anchor>;
1425
1426 fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1427 self.background_highlights
1428 .get(&TypeId::of::<BufferSearchHighlights>())
1429 .map_or(Vec::new(), |(_color, ranges)| {
1430 ranges.iter().cloned().collect()
1431 })
1432 }
1433
1434 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1435 if self
1436 .clear_background_highlights::<BufferSearchHighlights>(cx)
1437 .is_some()
1438 {
1439 cx.emit(SearchEvent::MatchesInvalidated);
1440 }
1441 }
1442
1443 fn update_matches(
1444 &mut self,
1445 matches: &[Range<Anchor>],
1446 _: &mut Window,
1447 cx: &mut Context<Self>,
1448 ) {
1449 let existing_range = self
1450 .background_highlights
1451 .get(&TypeId::of::<BufferSearchHighlights>())
1452 .map(|(_, range)| range.as_ref());
1453 let updated = existing_range != Some(matches);
1454 self.highlight_background::<BufferSearchHighlights>(
1455 matches,
1456 |theme| theme.search_match_background,
1457 cx,
1458 );
1459 if updated {
1460 cx.emit(SearchEvent::MatchesInvalidated);
1461 }
1462 }
1463
1464 fn has_filtered_search_ranges(&mut self) -> bool {
1465 self.has_background_highlights::<SearchWithinRange>()
1466 }
1467
1468 fn toggle_filtered_search_ranges(
1469 &mut self,
1470 enabled: bool,
1471 _: &mut Window,
1472 cx: &mut Context<Self>,
1473 ) {
1474 if self.has_filtered_search_ranges() {
1475 self.previous_search_ranges = self
1476 .clear_background_highlights::<SearchWithinRange>(cx)
1477 .map(|(_, ranges)| ranges)
1478 }
1479
1480 if !enabled {
1481 return;
1482 }
1483
1484 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1485 if ranges.iter().any(|s| s.start != s.end) {
1486 self.set_search_within_ranges(&ranges, cx);
1487 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1488 self.set_search_within_ranges(&previous_search_ranges, cx)
1489 }
1490 }
1491
1492 fn supported_options(&self) -> SearchOptions {
1493 if self.in_project_search {
1494 SearchOptions {
1495 case: true,
1496 word: true,
1497 regex: true,
1498 replacement: false,
1499 selection: false,
1500 find_in_results: true,
1501 }
1502 } else {
1503 SearchOptions {
1504 case: true,
1505 word: true,
1506 regex: true,
1507 replacement: true,
1508 selection: true,
1509 find_in_results: false,
1510 }
1511 }
1512 }
1513
1514 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1515 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1516 let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1517 let selection = self.selections.newest::<usize>(cx);
1518
1519 match setting {
1520 SeedQuerySetting::Never => String::new(),
1521 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1522 let text: String = snapshot
1523 .text_for_range(selection.start..selection.end)
1524 .collect();
1525 if text.contains('\n') {
1526 String::new()
1527 } else {
1528 text
1529 }
1530 }
1531 SeedQuerySetting::Selection => String::new(),
1532 SeedQuerySetting::Always => {
1533 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1534 if kind == Some(CharKind::Word) {
1535 let text: String = snapshot.text_for_range(range).collect();
1536 if !text.trim().is_empty() {
1537 return text;
1538 }
1539 }
1540 String::new()
1541 }
1542 }
1543 }
1544
1545 fn activate_match(
1546 &mut self,
1547 index: usize,
1548 matches: &[Range<Anchor>],
1549 window: &mut Window,
1550 cx: &mut Context<Self>,
1551 ) {
1552 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1553 let range = self.range_for_match(&matches[index]);
1554 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1555 s.select_ranges([range]);
1556 })
1557 }
1558
1559 fn select_matches(
1560 &mut self,
1561 matches: &[Self::Match],
1562 window: &mut Window,
1563 cx: &mut Context<Self>,
1564 ) {
1565 self.unfold_ranges(matches, false, false, cx);
1566 self.change_selections(None, window, cx, |s| {
1567 s.select_ranges(matches.iter().cloned())
1568 });
1569 }
1570 fn replace(
1571 &mut self,
1572 identifier: &Self::Match,
1573 query: &SearchQuery,
1574 window: &mut Window,
1575 cx: &mut Context<Self>,
1576 ) {
1577 let text = self.buffer.read(cx);
1578 let text = text.snapshot(cx);
1579 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1580 let text: Cow<_> = if text.len() == 1 {
1581 text.first().cloned().unwrap().into()
1582 } else {
1583 let joined_chunks = text.join("");
1584 joined_chunks.into()
1585 };
1586
1587 if let Some(replacement) = query.replacement_for(&text) {
1588 self.transact(window, cx, |this, _, cx| {
1589 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1590 });
1591 }
1592 }
1593 fn replace_all(
1594 &mut self,
1595 matches: &mut dyn Iterator<Item = &Self::Match>,
1596 query: &SearchQuery,
1597 window: &mut Window,
1598 cx: &mut Context<Self>,
1599 ) {
1600 let text = self.buffer.read(cx);
1601 let text = text.snapshot(cx);
1602 let mut edits = vec![];
1603 let mut last_point: Option<Point> = None;
1604
1605 for m in matches {
1606 let point = m.start.to_point(&text);
1607 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1608
1609 // Check if the row for the current match is different from the last
1610 // match. If that's not the case and we're still replacing matches
1611 // in the same row/line, skip this match if the `one_match_per_line`
1612 // option is enabled.
1613 if last_point.is_none() {
1614 last_point = Some(point);
1615 } else if last_point.is_some() && point.row != last_point.unwrap().row {
1616 last_point = Some(point);
1617 } else if query.one_match_per_line().is_some_and(|enabled| enabled) {
1618 continue;
1619 }
1620
1621 let text: Cow<_> = if text.len() == 1 {
1622 text.first().cloned().unwrap().into()
1623 } else {
1624 let joined_chunks = text.join("");
1625 joined_chunks.into()
1626 };
1627
1628 if let Some(replacement) = query.replacement_for(&text) {
1629 edits.push((m.clone(), Arc::from(&*replacement)));
1630 }
1631 }
1632
1633 if !edits.is_empty() {
1634 self.transact(window, cx, |this, _, cx| {
1635 this.edit(edits, cx);
1636 });
1637 }
1638 }
1639 fn match_index_for_direction(
1640 &mut self,
1641 matches: &[Range<Anchor>],
1642 current_index: usize,
1643 direction: Direction,
1644 count: usize,
1645 _: &mut Window,
1646 cx: &mut Context<Self>,
1647 ) -> usize {
1648 let buffer = self.buffer().read(cx).snapshot(cx);
1649 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1650 self.selections.newest_anchor().head()
1651 } else {
1652 matches[current_index].start
1653 };
1654
1655 let mut count = count % matches.len();
1656 if count == 0 {
1657 return current_index;
1658 }
1659 match direction {
1660 Direction::Next => {
1661 if matches[current_index]
1662 .start
1663 .cmp(¤t_index_position, &buffer)
1664 .is_gt()
1665 {
1666 count -= 1
1667 }
1668
1669 (current_index + count) % matches.len()
1670 }
1671 Direction::Prev => {
1672 if matches[current_index]
1673 .end
1674 .cmp(¤t_index_position, &buffer)
1675 .is_lt()
1676 {
1677 count -= 1;
1678 }
1679
1680 if current_index >= count {
1681 current_index - count
1682 } else {
1683 matches.len() - (count - current_index)
1684 }
1685 }
1686 }
1687 }
1688
1689 fn find_matches(
1690 &mut self,
1691 query: Arc<project::search::SearchQuery>,
1692 _: &mut Window,
1693 cx: &mut Context<Self>,
1694 ) -> Task<Vec<Range<Anchor>>> {
1695 let buffer = self.buffer().read(cx).snapshot(cx);
1696 let search_within_ranges = self
1697 .background_highlights
1698 .get(&TypeId::of::<SearchWithinRange>())
1699 .map_or(vec![], |(_color, ranges)| {
1700 ranges.iter().cloned().collect::<Vec<_>>()
1701 });
1702
1703 cx.background_spawn(async move {
1704 let mut ranges = Vec::new();
1705
1706 let search_within_ranges = if search_within_ranges.is_empty() {
1707 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1708 } else {
1709 search_within_ranges
1710 };
1711
1712 for range in search_within_ranges {
1713 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1714 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1715 {
1716 ranges.extend(
1717 query
1718 .search(search_buffer, Some(search_range.clone()))
1719 .await
1720 .into_iter()
1721 .map(|match_range| {
1722 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1723 let start = search_buffer
1724 .anchor_after(search_range.start + match_range.start);
1725 let end = search_buffer
1726 .anchor_before(search_range.start + match_range.end);
1727 Anchor {
1728 diff_base_anchor: Some(start),
1729 ..deleted_hunk_anchor
1730 }..Anchor {
1731 diff_base_anchor: Some(end),
1732 ..deleted_hunk_anchor
1733 }
1734 } else {
1735 let start = search_buffer
1736 .anchor_after(search_range.start + match_range.start);
1737 let end = search_buffer
1738 .anchor_before(search_range.start + match_range.end);
1739 Anchor::range_in_buffer(
1740 excerpt_id,
1741 search_buffer.remote_id(),
1742 start..end,
1743 )
1744 }
1745 }),
1746 );
1747 }
1748 }
1749
1750 ranges
1751 })
1752 }
1753
1754 fn active_match_index(
1755 &mut self,
1756 direction: Direction,
1757 matches: &[Range<Anchor>],
1758 _: &mut Window,
1759 cx: &mut Context<Self>,
1760 ) -> Option<usize> {
1761 active_match_index(
1762 direction,
1763 matches,
1764 &self.selections.newest_anchor().head(),
1765 &self.buffer().read(cx).snapshot(cx),
1766 )
1767 }
1768
1769 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1770 self.expect_bounds_change = self.last_bounds;
1771 }
1772}
1773
1774pub fn active_match_index(
1775 direction: Direction,
1776 ranges: &[Range<Anchor>],
1777 cursor: &Anchor,
1778 buffer: &MultiBufferSnapshot,
1779) -> Option<usize> {
1780 if ranges.is_empty() {
1781 None
1782 } else {
1783 let r = ranges.binary_search_by(|probe| {
1784 if probe.end.cmp(cursor, buffer).is_lt() {
1785 Ordering::Less
1786 } else if probe.start.cmp(cursor, buffer).is_gt() {
1787 Ordering::Greater
1788 } else {
1789 Ordering::Equal
1790 }
1791 });
1792 match direction {
1793 Direction::Prev => match r {
1794 Ok(i) => Some(i),
1795 Err(i) => Some(i.saturating_sub(1)),
1796 },
1797 Direction::Next => match r {
1798 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1799 },
1800 }
1801 }
1802}
1803
1804pub fn entry_label_color(selected: bool) -> Color {
1805 if selected {
1806 Color::Default
1807 } else {
1808 Color::Muted
1809 }
1810}
1811
1812pub fn entry_diagnostic_aware_icon_name_and_color(
1813 diagnostic_severity: Option<DiagnosticSeverity>,
1814) -> Option<(IconName, Color)> {
1815 match diagnostic_severity {
1816 Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1817 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1818 _ => None,
1819 }
1820}
1821
1822pub fn entry_diagnostic_aware_icon_decoration_and_color(
1823 diagnostic_severity: Option<DiagnosticSeverity>,
1824) -> Option<(IconDecorationKind, Color)> {
1825 match diagnostic_severity {
1826 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1827 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1828 _ => None,
1829 }
1830}
1831
1832pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1833 let tracked = git_status.index + git_status.worktree;
1834 if ignored {
1835 Color::Ignored
1836 } else if git_status.conflict > 0 {
1837 Color::Conflict
1838 } else if tracked.modified > 0 {
1839 Color::Modified
1840 } else if tracked.added > 0 || git_status.untracked > 0 {
1841 Color::Created
1842 } else {
1843 entry_label_color(selected)
1844 }
1845}
1846
1847fn path_for_buffer<'a>(
1848 buffer: &Entity<MultiBuffer>,
1849 height: usize,
1850 include_filename: bool,
1851 cx: &'a App,
1852) -> Option<Cow<'a, Path>> {
1853 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1854 path_for_file(file.as_ref(), height, include_filename, cx)
1855}
1856
1857fn path_for_file<'a>(
1858 file: &'a dyn language::File,
1859 mut height: usize,
1860 include_filename: bool,
1861 cx: &'a App,
1862) -> Option<Cow<'a, Path>> {
1863 // Ensure we always render at least the filename.
1864 height += 1;
1865
1866 let mut prefix = file.path().as_ref();
1867 while height > 0 {
1868 if let Some(parent) = prefix.parent() {
1869 prefix = parent;
1870 height -= 1;
1871 } else {
1872 break;
1873 }
1874 }
1875
1876 // Here we could have just always used `full_path`, but that is very
1877 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1878 // traversed all the way up to the worktree's root.
1879 if height > 0 {
1880 let full_path = file.full_path(cx);
1881 if include_filename {
1882 Some(full_path.into())
1883 } else {
1884 Some(full_path.parent()?.to_path_buf().into())
1885 }
1886 } else {
1887 let mut path = file.path().strip_prefix(prefix).ok()?;
1888 if !include_filename {
1889 path = path.parent()?;
1890 }
1891 Some(path.into())
1892 }
1893}
1894
1895#[cfg(test)]
1896mod tests {
1897 use crate::editor_tests::init_test;
1898 use fs::Fs;
1899
1900 use super::*;
1901 use fs::MTime;
1902 use gpui::{App, VisualTestContext};
1903 use language::{LanguageMatcher, TestFile};
1904 use project::FakeFs;
1905 use std::path::{Path, PathBuf};
1906 use util::path;
1907
1908 #[gpui::test]
1909 fn test_path_for_file(cx: &mut App) {
1910 let file = TestFile {
1911 path: Path::new("").into(),
1912 root_name: String::new(),
1913 local_root: None,
1914 };
1915 assert_eq!(path_for_file(&file, 0, false, cx), None);
1916 }
1917
1918 async fn deserialize_editor(
1919 item_id: ItemId,
1920 workspace_id: WorkspaceId,
1921 workspace: Entity<Workspace>,
1922 project: Entity<Project>,
1923 cx: &mut VisualTestContext,
1924 ) -> Entity<Editor> {
1925 workspace
1926 .update_in(cx, |workspace, window, cx| {
1927 let pane = workspace.active_pane();
1928 pane.update(cx, |_, cx| {
1929 Editor::deserialize(
1930 project.clone(),
1931 workspace.weak_handle(),
1932 workspace_id,
1933 item_id,
1934 window,
1935 cx,
1936 )
1937 })
1938 })
1939 .await
1940 .unwrap()
1941 }
1942
1943 fn rust_language() -> Arc<language::Language> {
1944 Arc::new(language::Language::new(
1945 language::LanguageConfig {
1946 name: "Rust".into(),
1947 matcher: LanguageMatcher {
1948 path_suffixes: vec!["rs".to_string()],
1949 ..Default::default()
1950 },
1951 ..Default::default()
1952 },
1953 Some(tree_sitter_rust::LANGUAGE.into()),
1954 ))
1955 }
1956
1957 #[gpui::test]
1958 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1959 init_test(cx, |_| {});
1960
1961 let fs = FakeFs::new(cx.executor());
1962 fs.insert_file(path!("/file.rs"), Default::default()).await;
1963
1964 // Test case 1: Deserialize with path and contents
1965 {
1966 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1967 let (workspace, cx) =
1968 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1969 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1970 let item_id = 1234 as ItemId;
1971 let mtime = fs
1972 .metadata(Path::new(path!("/file.rs")))
1973 .await
1974 .unwrap()
1975 .unwrap()
1976 .mtime;
1977
1978 let serialized_editor = SerializedEditor {
1979 abs_path: Some(PathBuf::from(path!("/file.rs"))),
1980 contents: Some("fn main() {}".to_string()),
1981 language: Some("Rust".to_string()),
1982 mtime: Some(mtime),
1983 };
1984
1985 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1986 .await
1987 .unwrap();
1988
1989 let deserialized =
1990 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1991
1992 deserialized.update(cx, |editor, cx| {
1993 assert_eq!(editor.text(cx), "fn main() {}");
1994 assert!(editor.is_dirty(cx));
1995 assert!(!editor.has_conflict(cx));
1996 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1997 assert!(buffer.file().is_some());
1998 });
1999 }
2000
2001 // Test case 2: Deserialize with only path
2002 {
2003 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2004 let (workspace, cx) =
2005 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2006
2007 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2008
2009 let item_id = 5678 as ItemId;
2010 let serialized_editor = SerializedEditor {
2011 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2012 contents: None,
2013 language: None,
2014 mtime: None,
2015 };
2016
2017 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2018 .await
2019 .unwrap();
2020
2021 let deserialized =
2022 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2023
2024 deserialized.update(cx, |editor, cx| {
2025 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2026 assert!(!editor.is_dirty(cx));
2027 assert!(!editor.has_conflict(cx));
2028
2029 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2030 assert!(buffer.file().is_some());
2031 });
2032 }
2033
2034 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2035 {
2036 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2037 // Add Rust to the language, so that we can restore the language of the buffer
2038 project.update(cx, |project, _| project.languages().add(rust_language()));
2039
2040 let (workspace, cx) =
2041 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2042
2043 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2044
2045 let item_id = 9012 as ItemId;
2046 let serialized_editor = SerializedEditor {
2047 abs_path: None,
2048 contents: Some("hello".to_string()),
2049 language: Some("Rust".to_string()),
2050 mtime: None,
2051 };
2052
2053 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2054 .await
2055 .unwrap();
2056
2057 let deserialized =
2058 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2059
2060 deserialized.update(cx, |editor, cx| {
2061 assert_eq!(editor.text(cx), "hello");
2062 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2063
2064 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2065 assert_eq!(
2066 buffer.language().map(|lang| lang.name()),
2067 Some("Rust".into())
2068 ); // Language should be set to Rust
2069 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2070 });
2071 }
2072
2073 // Test case 4: Deserialize with path, content, and old mtime
2074 {
2075 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2076 let (workspace, cx) =
2077 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2078
2079 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2080
2081 let item_id = 9345 as ItemId;
2082 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2083 let serialized_editor = SerializedEditor {
2084 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2085 contents: Some("fn main() {}".to_string()),
2086 language: Some("Rust".to_string()),
2087 mtime: Some(old_mtime),
2088 };
2089
2090 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2091 .await
2092 .unwrap();
2093
2094 let deserialized =
2095 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2096
2097 deserialized.update(cx, |editor, cx| {
2098 assert_eq!(editor.text(cx), "fn main() {}");
2099 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2100 });
2101 }
2102 }
2103}