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