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