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