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