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