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(&self, detail: usize, cx: &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(
706 &mut self,
707 format: bool,
708 project: Model<Project>,
709 cx: &mut ViewContext<Self>,
710 ) -> Task<Result<()>> {
711 self.report_editor_event("save", None, cx);
712 let buffers = self.buffer().clone().read(cx).all_buffers();
713 cx.spawn(|this, mut cx| async move {
714 if format {
715 this.update(&mut cx, |this, cx| {
716 this.perform_format(project.clone(), FormatTrigger::Save, cx)
717 })?
718 .await?;
719 }
720
721 if buffers.len() == 1 {
722 project
723 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
724 .await?;
725 } else {
726 // For multi-buffers, only save those ones that contain changes. For clean buffers
727 // we simulate saving by calling `Buffer::did_save`, so that language servers or
728 // other downstream listeners of save events get notified.
729 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
730 buffer
731 .update(&mut cx, |buffer, _| {
732 buffer.is_dirty() || buffer.has_conflict()
733 })
734 .unwrap_or(false)
735 });
736
737 project
738 .update(&mut cx, |project, cx| {
739 project.save_buffers(dirty_buffers, cx)
740 })?
741 .await?;
742 for buffer in clean_buffers {
743 buffer
744 .update(&mut cx, |buffer, cx| {
745 let version = buffer.saved_version().clone();
746 let fingerprint = buffer.saved_version_fingerprint();
747 let mtime = buffer.saved_mtime();
748 buffer.did_save(version, fingerprint, mtime, cx);
749 })
750 .ok();
751 }
752 }
753
754 Ok(())
755 })
756 }
757
758 fn save_as(
759 &mut self,
760 project: Model<Project>,
761 abs_path: PathBuf,
762 cx: &mut ViewContext<Self>,
763 ) -> Task<Result<()>> {
764 let buffer = self
765 .buffer()
766 .read(cx)
767 .as_singleton()
768 .expect("cannot call save_as on an excerpt list");
769
770 let file_extension = abs_path
771 .extension()
772 .map(|a| a.to_string_lossy().to_string());
773 self.report_editor_event("save", file_extension, cx);
774
775 project.update(cx, |project, cx| {
776 project.save_buffer_as(buffer, abs_path, cx)
777 })
778 }
779
780 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
781 let buffer = self.buffer().clone();
782 let buffers = self.buffer.read(cx).all_buffers();
783 let reload_buffers =
784 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
785 cx.spawn(|this, mut cx| async move {
786 let transaction = reload_buffers.log_err().await;
787 this.update(&mut cx, |editor, cx| {
788 editor.request_autoscroll(Autoscroll::fit(), cx)
789 })?;
790 buffer
791 .update(&mut cx, |buffer, cx| {
792 if let Some(transaction) = transaction {
793 if !buffer.is_singleton() {
794 buffer.push_transaction(&transaction.0, cx);
795 }
796 }
797 })
798 .ok();
799 Ok(())
800 })
801 }
802
803 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
804 Some(Box::new(handle.clone()))
805 }
806
807 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
808 self.pixel_position_of_newest_cursor
809 }
810
811 fn breadcrumb_location(&self) -> ToolbarItemLocation {
812 if self.show_breadcrumbs {
813 ToolbarItemLocation::PrimaryLeft
814 } else {
815 ToolbarItemLocation::Hidden
816 }
817 }
818
819 fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
820 let cursor = self.selections.newest_anchor().head();
821 let multibuffer = &self.buffer().read(cx);
822 let (buffer_id, symbols) =
823 multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
824 let buffer = multibuffer.buffer(buffer_id)?;
825
826 let buffer = buffer.read(cx);
827 let filename = buffer
828 .snapshot()
829 .resolve_file_path(
830 cx,
831 self.project
832 .as_ref()
833 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
834 .unwrap_or_default(),
835 )
836 .map(|path| path.to_string_lossy().to_string())
837 .unwrap_or_else(|| "untitled".to_string());
838
839 let mut breadcrumbs = vec![BreadcrumbText {
840 text: filename,
841 highlights: None,
842 }];
843 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
844 text: symbol.text,
845 highlights: Some(symbol.highlight_ranges),
846 }));
847 Some(breadcrumbs)
848 }
849
850 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
851 let workspace_id = workspace.database_id();
852 let item_id = cx.view().item_id().as_u64() as ItemId;
853 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
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((_, 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: Vec<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 query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1007 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1008 let snapshot = &self.snapshot(cx).buffer_snapshot;
1009 let selection = self.selections.newest::<usize>(cx);
1010
1011 match setting {
1012 SeedQuerySetting::Never => String::new(),
1013 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1014 snapshot
1015 .text_for_range(selection.start..selection.end)
1016 .collect()
1017 }
1018 SeedQuerySetting::Selection => String::new(),
1019 SeedQuerySetting::Always => {
1020 let (range, kind) = snapshot.surrounding_word(selection.start);
1021 if kind == Some(CharKind::Word) {
1022 let text: String = snapshot.text_for_range(range).collect();
1023 if !text.trim().is_empty() {
1024 return text;
1025 }
1026 }
1027 String::new()
1028 }
1029 }
1030 }
1031
1032 fn activate_match(
1033 &mut self,
1034 index: usize,
1035 matches: Vec<Range<Anchor>>,
1036 cx: &mut ViewContext<Self>,
1037 ) {
1038 self.unfold_ranges([matches[index].clone()], false, true, cx);
1039 let range = self.range_for_match(&matches[index]);
1040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1041 s.select_ranges([range]);
1042 })
1043 }
1044
1045 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
1046 self.unfold_ranges(matches.clone(), false, false, cx);
1047 let mut ranges = Vec::new();
1048 for m in &matches {
1049 ranges.push(self.range_for_match(&m))
1050 }
1051 self.change_selections(None, cx, |s| s.select_ranges(ranges));
1052 }
1053 fn replace(
1054 &mut self,
1055 identifier: &Self::Match,
1056 query: &SearchQuery,
1057 cx: &mut ViewContext<Self>,
1058 ) {
1059 let text = self.buffer.read(cx);
1060 let text = text.snapshot(cx);
1061 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1062 let text: Cow<_> = if text.len() == 1 {
1063 text.first().cloned().unwrap().into()
1064 } else {
1065 let joined_chunks = text.join("");
1066 joined_chunks.into()
1067 };
1068
1069 if let Some(replacement) = query.replacement_for(&text) {
1070 self.transact(cx, |this, cx| {
1071 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1072 });
1073 }
1074 }
1075 fn match_index_for_direction(
1076 &mut self,
1077 matches: &Vec<Range<Anchor>>,
1078 current_index: usize,
1079 direction: Direction,
1080 count: usize,
1081 cx: &mut ViewContext<Self>,
1082 ) -> usize {
1083 let buffer = self.buffer().read(cx).snapshot(cx);
1084 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1085 self.selections.newest_anchor().head()
1086 } else {
1087 matches[current_index].start
1088 };
1089
1090 let mut count = count % matches.len();
1091 if count == 0 {
1092 return current_index;
1093 }
1094 match direction {
1095 Direction::Next => {
1096 if matches[current_index]
1097 .start
1098 .cmp(¤t_index_position, &buffer)
1099 .is_gt()
1100 {
1101 count = count - 1
1102 }
1103
1104 (current_index + count) % matches.len()
1105 }
1106 Direction::Prev => {
1107 if matches[current_index]
1108 .end
1109 .cmp(¤t_index_position, &buffer)
1110 .is_lt()
1111 {
1112 count = count - 1;
1113 }
1114
1115 if current_index >= count {
1116 current_index - count
1117 } else {
1118 matches.len() - (count - current_index)
1119 }
1120 }
1121 }
1122 }
1123
1124 fn find_matches(
1125 &mut self,
1126 query: Arc<project::search::SearchQuery>,
1127 cx: &mut ViewContext<Self>,
1128 ) -> Task<Vec<Range<Anchor>>> {
1129 let buffer = self.buffer().read(cx).snapshot(cx);
1130 cx.background_executor().spawn(async move {
1131 let mut ranges = Vec::new();
1132 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1133 ranges.extend(
1134 query
1135 .search(excerpt_buffer, None)
1136 .await
1137 .into_iter()
1138 .map(|range| {
1139 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1140 }),
1141 );
1142 } else {
1143 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1144 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1145 ranges.extend(
1146 query
1147 .search(&excerpt.buffer, Some(excerpt_range.clone()))
1148 .await
1149 .into_iter()
1150 .map(|range| {
1151 let start = excerpt
1152 .buffer
1153 .anchor_after(excerpt_range.start + range.start);
1154 let end = excerpt
1155 .buffer
1156 .anchor_before(excerpt_range.start + range.end);
1157 buffer.anchor_in_excerpt(excerpt.id, start)
1158 ..buffer.anchor_in_excerpt(excerpt.id, end)
1159 }),
1160 );
1161 }
1162 }
1163 ranges
1164 })
1165 }
1166
1167 fn active_match_index(
1168 &mut self,
1169 matches: Vec<Range<Anchor>>,
1170 cx: &mut ViewContext<Self>,
1171 ) -> Option<usize> {
1172 active_match_index(
1173 &matches,
1174 &self.selections.newest_anchor().head(),
1175 &self.buffer().read(cx).snapshot(cx),
1176 )
1177 }
1178}
1179
1180pub fn active_match_index(
1181 ranges: &[Range<Anchor>],
1182 cursor: &Anchor,
1183 buffer: &MultiBufferSnapshot,
1184) -> Option<usize> {
1185 if ranges.is_empty() {
1186 None
1187 } else {
1188 match ranges.binary_search_by(|probe| {
1189 if probe.end.cmp(cursor, &*buffer).is_lt() {
1190 Ordering::Less
1191 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1192 Ordering::Greater
1193 } else {
1194 Ordering::Equal
1195 }
1196 }) {
1197 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1198 }
1199 }
1200}
1201
1202pub struct CursorPosition {
1203 position: Option<Point>,
1204 selected_count: usize,
1205 _observe_active_editor: Option<Subscription>,
1206}
1207
1208impl Default for CursorPosition {
1209 fn default() -> Self {
1210 Self::new()
1211 }
1212}
1213
1214impl CursorPosition {
1215 pub fn new() -> Self {
1216 Self {
1217 position: None,
1218 selected_count: 0,
1219 _observe_active_editor: None,
1220 }
1221 }
1222
1223 fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1224 let editor = editor.read(cx);
1225 let buffer = editor.buffer().read(cx).snapshot(cx);
1226
1227 self.selected_count = 0;
1228 let mut last_selection: Option<Selection<usize>> = None;
1229 for selection in editor.selections.all::<usize>(cx) {
1230 self.selected_count += selection.end - selection.start;
1231 if last_selection
1232 .as_ref()
1233 .map_or(true, |last_selection| selection.id > last_selection.id)
1234 {
1235 last_selection = Some(selection);
1236 }
1237 }
1238 self.position = last_selection.map(|s| s.head().to_point(&buffer));
1239
1240 cx.notify();
1241 }
1242}
1243
1244impl Render for CursorPosition {
1245 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1246 div().when_some(self.position, |el, position| {
1247 let mut text = format!(
1248 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1249 position.row + 1,
1250 position.column + 1
1251 );
1252 if self.selected_count > 0 {
1253 write!(text, " ({} selected)", self.selected_count).unwrap();
1254 }
1255
1256 el.child(Label::new(text).size(LabelSize::Small))
1257 })
1258 }
1259}
1260
1261impl StatusItemView for CursorPosition {
1262 fn set_active_pane_item(
1263 &mut self,
1264 active_pane_item: Option<&dyn ItemHandle>,
1265 cx: &mut ViewContext<Self>,
1266 ) {
1267 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1268 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1269 self.update_position(editor, cx);
1270 } else {
1271 self.position = None;
1272 self._observe_active_editor = None;
1273 }
1274
1275 cx.notify();
1276 }
1277}
1278
1279fn path_for_buffer<'a>(
1280 buffer: &Model<MultiBuffer>,
1281 height: usize,
1282 include_filename: bool,
1283 cx: &'a AppContext,
1284) -> Option<Cow<'a, Path>> {
1285 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1286 path_for_file(file.as_ref(), height, include_filename, cx)
1287}
1288
1289fn path_for_file<'a>(
1290 file: &'a dyn language::File,
1291 mut height: usize,
1292 include_filename: bool,
1293 cx: &'a AppContext,
1294) -> Option<Cow<'a, Path>> {
1295 // Ensure we always render at least the filename.
1296 height += 1;
1297
1298 let mut prefix = file.path().as_ref();
1299 while height > 0 {
1300 if let Some(parent) = prefix.parent() {
1301 prefix = parent;
1302 height -= 1;
1303 } else {
1304 break;
1305 }
1306 }
1307
1308 // Here we could have just always used `full_path`, but that is very
1309 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1310 // traversed all the way up to the worktree's root.
1311 if height > 0 {
1312 let full_path = file.full_path(cx);
1313 if include_filename {
1314 Some(full_path.into())
1315 } else {
1316 Some(full_path.parent()?.to_path_buf().into())
1317 }
1318 } else {
1319 let mut path = file.path().strip_prefix(prefix).ok()?;
1320 if !include_filename {
1321 path = path.parent()?;
1322 }
1323 Some(path.into())
1324 }
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329 use super::*;
1330 use gpui::AppContext;
1331 use std::{
1332 path::{Path, PathBuf},
1333 sync::Arc,
1334 time::SystemTime,
1335 };
1336
1337 #[gpui::test]
1338 fn test_path_for_file(cx: &mut AppContext) {
1339 let file = TestFile {
1340 path: Path::new("").into(),
1341 full_path: PathBuf::from(""),
1342 };
1343 assert_eq!(path_for_file(&file, 0, false, cx), None);
1344 }
1345
1346 struct TestFile {
1347 path: Arc<Path>,
1348 full_path: PathBuf,
1349 }
1350
1351 impl language::File for TestFile {
1352 fn path(&self) -> &Arc<Path> {
1353 &self.path
1354 }
1355
1356 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1357 self.full_path.clone()
1358 }
1359
1360 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1361 unimplemented!()
1362 }
1363
1364 fn mtime(&self) -> SystemTime {
1365 unimplemented!()
1366 }
1367
1368 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1369 unimplemented!()
1370 }
1371
1372 fn worktree_id(&self) -> usize {
1373 0
1374 }
1375
1376 fn is_deleted(&self) -> bool {
1377 unimplemented!()
1378 }
1379
1380 fn as_any(&self) -> &dyn std::any::Any {
1381 unimplemented!()
1382 }
1383
1384 fn to_proto(&self) -> rpc::proto::File {
1385 unimplemented!()
1386 }
1387
1388 fn is_private(&self) -> bool {
1389 false
1390 }
1391 }
1392}