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