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