1use crate::{
2 link_go_to_definition::hide_link_definition, persistence::DB, scroll::ScrollAnchor, Anchor,
3 Autoscroll, Editor, Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
4 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, CharKind, OffsetRangeExt,
17 Point, SelectionGoal,
18};
19use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
20use rpc::proto::{self, update_view, PeerId};
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, ItemHandle};
37use workspace::{
38 item::{FollowableItem, Item, ItemEvent, 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_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
160 self.leader_peer_id = leader_peer_id;
161 if self.leader_peer_id.is_some() {
162 self.buffer.update(cx, |buffer, cx| {
163 buffer.remove_active_selections(cx);
164 });
165 } else {
166 self.buffer.update(cx, |buffer, cx| {
167 if self.focused {
168 buffer.set_active_selections(
169 &self.selections.disjoint_anchors(),
170 self.selections.line_mode,
171 self.cursor_shape,
172 cx,
173 );
174 }
175 });
176 }
177 cx.notify();
178 }
179
180 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
181 let buffer = self.buffer.read(cx);
182 let scroll_anchor = self.scroll_manager.anchor();
183 let excerpts = buffer
184 .read(cx)
185 .excerpts()
186 .map(|(id, buffer, range)| proto::Excerpt {
187 id: id.to_proto(),
188 buffer_id: buffer.remote_id(),
189 context_start: Some(serialize_text_anchor(&range.context.start)),
190 context_end: Some(serialize_text_anchor(&range.context.end)),
191 primary_start: range
192 .primary
193 .as_ref()
194 .map(|range| serialize_text_anchor(&range.start)),
195 primary_end: range
196 .primary
197 .as_ref()
198 .map(|range| serialize_text_anchor(&range.end)),
199 })
200 .collect();
201
202 Some(proto::view::Variant::Editor(proto::view::Editor {
203 singleton: buffer.is_singleton(),
204 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
205 excerpts,
206 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
207 scroll_x: scroll_anchor.offset.x(),
208 scroll_y: scroll_anchor.offset.y(),
209 selections: self
210 .selections
211 .disjoint_anchors()
212 .iter()
213 .map(serialize_selection)
214 .collect(),
215 pending_selection: self
216 .selections
217 .pending_anchor()
218 .as_ref()
219 .map(serialize_selection),
220 }))
221 }
222
223 fn add_event_to_update_proto(
224 &self,
225 event: &Self::Event,
226 update: &mut Option<proto::update_view::Variant>,
227 cx: &AppContext,
228 ) -> bool {
229 let update =
230 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
231
232 match update {
233 proto::update_view::Variant::Editor(update) => match event {
234 Event::ExcerptsAdded {
235 buffer,
236 predecessor,
237 excerpts,
238 } => {
239 let buffer_id = buffer.read(cx).remote_id();
240 let mut excerpts = excerpts.iter();
241 if let Some((id, range)) = excerpts.next() {
242 update.inserted_excerpts.push(proto::ExcerptInsertion {
243 previous_excerpt_id: Some(predecessor.to_proto()),
244 excerpt: serialize_excerpt(buffer_id, id, range),
245 });
246 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
247 proto::ExcerptInsertion {
248 previous_excerpt_id: None,
249 excerpt: serialize_excerpt(buffer_id, id, range),
250 }
251 }))
252 }
253 true
254 }
255 Event::ExcerptsRemoved { ids } => {
256 update
257 .deleted_excerpts
258 .extend(ids.iter().map(ExcerptId::to_proto));
259 true
260 }
261 Event::ScrollPositionChanged { .. } => {
262 let scroll_anchor = self.scroll_manager.anchor();
263 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
264 update.scroll_x = scroll_anchor.offset.x();
265 update.scroll_y = scroll_anchor.offset.y();
266 true
267 }
268 Event::SelectionsChanged { .. } => {
269 update.selections = self
270 .selections
271 .disjoint_anchors()
272 .iter()
273 .map(serialize_selection)
274 .collect();
275 update.pending_selection = self
276 .selections
277 .pending_anchor()
278 .as_ref()
279 .map(serialize_selection);
280 true
281 }
282 _ => false,
283 },
284 }
285 }
286
287 fn apply_update_proto(
288 &mut self,
289 project: &ModelHandle<Project>,
290 message: update_view::Variant,
291 cx: &mut ViewContext<Self>,
292 ) -> Task<Result<()>> {
293 let update_view::Variant::Editor(message) = message;
294 let project = project.clone();
295 cx.spawn(|this, mut cx| async move {
296 update_editor_from_message(this, project, message, &mut cx).await
297 })
298 }
299
300 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
301 match event {
302 Event::Edited => true,
303 Event::SelectionsChanged { local } => *local,
304 Event::ScrollPositionChanged { local, .. } => *local,
305 _ => false,
306 }
307 }
308
309 fn is_project_item(&self, _cx: &AppContext) -> bool {
310 true
311 }
312}
313
314async fn update_editor_from_message(
315 this: WeakViewHandle<Editor>,
316 project: ModelHandle<Project>,
317 message: proto::update_view::Editor,
318 cx: &mut AsyncAppContext,
319) -> Result<()> {
320 // Open all of the buffers of which excerpts were added to the editor.
321 let inserted_excerpt_buffer_ids = message
322 .inserted_excerpts
323 .iter()
324 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
325 .collect::<HashSet<_>>();
326 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
327 inserted_excerpt_buffer_ids
328 .into_iter()
329 .map(|id| project.open_buffer_by_id(id, cx))
330 .collect::<Vec<_>>()
331 });
332 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
333
334 // Update the editor's excerpts.
335 this.update(cx, |editor, cx| {
336 editor.buffer.update(cx, |multibuffer, cx| {
337 let mut removed_excerpt_ids = message
338 .deleted_excerpts
339 .into_iter()
340 .map(ExcerptId::from_proto)
341 .collect::<Vec<_>>();
342 removed_excerpt_ids.sort_by({
343 let multibuffer = multibuffer.read(cx);
344 move |a, b| a.cmp(&b, &multibuffer)
345 });
346
347 let mut insertions = message.inserted_excerpts.into_iter().peekable();
348 while let Some(insertion) = insertions.next() {
349 let Some(excerpt) = insertion.excerpt else {
350 continue;
351 };
352 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
353 continue;
354 };
355 let buffer_id = excerpt.buffer_id;
356 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
357 continue;
358 };
359
360 let adjacent_excerpts = iter::from_fn(|| {
361 let insertion = insertions.peek()?;
362 if insertion.previous_excerpt_id.is_none()
363 && insertion.excerpt.as_ref()?.buffer_id == buffer_id
364 {
365 insertions.next()?.excerpt
366 } else {
367 None
368 }
369 });
370
371 multibuffer.insert_excerpts_with_ids_after(
372 ExcerptId::from_proto(previous_excerpt_id),
373 buffer,
374 [excerpt]
375 .into_iter()
376 .chain(adjacent_excerpts)
377 .filter_map(|excerpt| {
378 Some((
379 ExcerptId::from_proto(excerpt.id),
380 deserialize_excerpt_range(excerpt)?,
381 ))
382 }),
383 cx,
384 );
385 }
386
387 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
388 });
389 })?;
390
391 // Deserialize the editor state.
392 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
393 let buffer = editor.buffer.read(cx).read(cx);
394 let selections = message
395 .selections
396 .into_iter()
397 .filter_map(|selection| deserialize_selection(&buffer, selection))
398 .collect::<Vec<_>>();
399 let pending_selection = message
400 .pending_selection
401 .and_then(|selection| deserialize_selection(&buffer, selection));
402 let scroll_top_anchor = message
403 .scroll_top_anchor
404 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
405 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
406 })??;
407
408 // Wait until the buffer has received all of the operations referenced by
409 // the editor's new state.
410 this.update(cx, |editor, cx| {
411 editor.buffer.update(cx, |buffer, cx| {
412 buffer.wait_for_anchors(
413 selections
414 .iter()
415 .chain(pending_selection.as_ref())
416 .flat_map(|selection| [selection.start, selection.end])
417 .chain(scroll_top_anchor),
418 cx,
419 )
420 })
421 })?
422 .await?;
423
424 // Update the editor's state.
425 this.update(cx, |editor, cx| {
426 if !selections.is_empty() || pending_selection.is_some() {
427 editor.set_selections_from_remote(selections, pending_selection, cx);
428 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
429 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
430 editor.set_scroll_anchor_remote(
431 ScrollAnchor {
432 anchor: scroll_top_anchor,
433 offset: vec2f(message.scroll_x, message.scroll_y),
434 },
435 cx,
436 );
437 }
438 })?;
439 Ok(())
440}
441
442fn serialize_excerpt(
443 buffer_id: u64,
444 id: &ExcerptId,
445 range: &ExcerptRange<language::Anchor>,
446) -> Option<proto::Excerpt> {
447 Some(proto::Excerpt {
448 id: id.to_proto(),
449 buffer_id,
450 context_start: Some(serialize_text_anchor(&range.context.start)),
451 context_end: Some(serialize_text_anchor(&range.context.end)),
452 primary_start: range
453 .primary
454 .as_ref()
455 .map(|r| serialize_text_anchor(&r.start)),
456 primary_end: range
457 .primary
458 .as_ref()
459 .map(|r| serialize_text_anchor(&r.end)),
460 })
461}
462
463fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
464 proto::Selection {
465 id: selection.id as u64,
466 start: Some(serialize_anchor(&selection.start)),
467 end: Some(serialize_anchor(&selection.end)),
468 reversed: selection.reversed,
469 }
470}
471
472fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
473 proto::EditorAnchor {
474 excerpt_id: anchor.excerpt_id.to_proto(),
475 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
476 }
477}
478
479fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
480 let context = {
481 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
482 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
483 start..end
484 };
485 let primary = excerpt
486 .primary_start
487 .zip(excerpt.primary_end)
488 .and_then(|(start, end)| {
489 let start = language::proto::deserialize_anchor(start)?;
490 let end = language::proto::deserialize_anchor(end)?;
491 Some(start..end)
492 });
493 Some(ExcerptRange { context, primary })
494}
495
496fn deserialize_selection(
497 buffer: &MultiBufferSnapshot,
498 selection: proto::Selection,
499) -> Option<Selection<Anchor>> {
500 Some(Selection {
501 id: selection.id as usize,
502 start: deserialize_anchor(buffer, selection.start?)?,
503 end: deserialize_anchor(buffer, selection.end?)?,
504 reversed: selection.reversed,
505 goal: SelectionGoal::None,
506 })
507}
508
509fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
510 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
511 Some(Anchor {
512 excerpt_id,
513 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
514 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
515 })
516}
517
518impl Item for Editor {
519 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
520 if let Ok(data) = data.downcast::<NavigationData>() {
521 let newest_selection = self.selections.newest::<Point>(cx);
522 let buffer = self.buffer.read(cx).read(cx);
523 let offset = if buffer.can_resolve(&data.cursor_anchor) {
524 data.cursor_anchor.to_point(&buffer)
525 } else {
526 buffer.clip_point(data.cursor_position, Bias::Left)
527 };
528
529 let mut scroll_anchor = data.scroll_anchor;
530 if !buffer.can_resolve(&scroll_anchor.anchor) {
531 scroll_anchor.anchor = buffer.anchor_before(
532 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
533 );
534 }
535
536 drop(buffer);
537
538 if newest_selection.head() == offset {
539 false
540 } else {
541 let nav_history = self.nav_history.take();
542 self.set_scroll_anchor(scroll_anchor, cx);
543 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
544 s.select_ranges([offset..offset])
545 });
546 self.nav_history = nav_history;
547 true
548 }
549 } else {
550 false
551 }
552 }
553
554 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
555 let file_path = self
556 .buffer()
557 .read(cx)
558 .as_singleton()?
559 .read(cx)
560 .file()
561 .and_then(|f| f.as_local())?
562 .abs_path(cx);
563
564 let file_path = file_path.compact().to_string_lossy().to_string();
565
566 Some(file_path.into())
567 }
568
569 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<str>> {
570 match path_for_buffer(&self.buffer, detail, true, cx)? {
571 Cow::Borrowed(path) => Some(path.to_string_lossy()),
572 Cow::Owned(path) => Some(path.to_string_lossy().to_string().into()),
573 }
574 }
575
576 fn tab_content<T: 'static>(
577 &self,
578 detail: Option<usize>,
579 style: &theme::Tab,
580 cx: &AppContext,
581 ) -> AnyElement<T> {
582 Flex::row()
583 .with_child(Label::new(self.title(cx).to_string(), style.label.clone()).into_any())
584 .with_children(detail.and_then(|detail| {
585 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
586 let description = path.to_string_lossy();
587 Some(
588 Label::new(
589 util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN),
590 style.description.text.clone(),
591 )
592 .contained()
593 .with_style(style.description.container)
594 .aligned(),
595 )
596 }))
597 .align_children_center()
598 .into_any()
599 }
600
601 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
602 self.buffer
603 .read(cx)
604 .for_each_buffer(|buffer| f(buffer.id(), buffer.read(cx)));
605 }
606
607 fn is_singleton(&self, cx: &AppContext) -> bool {
608 self.buffer.read(cx).is_singleton()
609 }
610
611 fn clone_on_split(&self, _workspace_id: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self>
612 where
613 Self: Sized,
614 {
615 Some(self.clone(cx))
616 }
617
618 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
619 self.nav_history = Some(history);
620 }
621
622 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
623 let selection = self.selections.newest_anchor();
624 self.push_to_nav_history(selection.head(), None, cx);
625 }
626
627 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
628 hide_link_definition(self, cx);
629 self.link_go_to_definition_state.last_trigger_point = None;
630 }
631
632 fn is_dirty(&self, cx: &AppContext) -> bool {
633 self.buffer().read(cx).read(cx).is_dirty()
634 }
635
636 fn has_conflict(&self, cx: &AppContext) -> bool {
637 self.buffer().read(cx).read(cx).has_conflict()
638 }
639
640 fn can_save(&self, cx: &AppContext) -> bool {
641 let buffer = &self.buffer().read(cx);
642 if let Some(buffer) = buffer.as_singleton() {
643 buffer.read(cx).project_path(cx).is_some()
644 } else {
645 true
646 }
647 }
648
649 fn save(
650 &mut self,
651 project: ModelHandle<Project>,
652 cx: &mut ViewContext<Self>,
653 ) -> Task<Result<()>> {
654 self.report_editor_event("save", None, cx);
655 let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
656 let buffers = self.buffer().clone().read(cx).all_buffers();
657 cx.spawn(|_, mut cx| async move {
658 format.await?;
659
660 if buffers.len() == 1 {
661 project
662 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))
663 .await?;
664 } else {
665 // For multi-buffers, only save those ones that contain changes. For clean buffers
666 // we simulate saving by calling `Buffer::did_save`, so that language servers or
667 // other downstream listeners of save events get notified.
668 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
669 buffer.read_with(&cx, |buffer, _| buffer.is_dirty() || buffer.has_conflict())
670 });
671
672 project
673 .update(&mut cx, |project, cx| {
674 project.save_buffers(dirty_buffers, cx)
675 })
676 .await?;
677 for buffer in clean_buffers {
678 buffer.update(&mut cx, |buffer, cx| {
679 let version = buffer.saved_version().clone();
680 let fingerprint = buffer.saved_version_fingerprint();
681 let mtime = buffer.saved_mtime();
682 buffer.did_save(version, fingerprint, mtime, cx);
683 });
684 }
685 }
686
687 Ok(())
688 })
689 }
690
691 fn save_as(
692 &mut self,
693 project: ModelHandle<Project>,
694 abs_path: PathBuf,
695 cx: &mut ViewContext<Self>,
696 ) -> Task<Result<()>> {
697 let buffer = self
698 .buffer()
699 .read(cx)
700 .as_singleton()
701 .expect("cannot call save_as on an excerpt list");
702
703 let file_extension = abs_path
704 .extension()
705 .map(|a| a.to_string_lossy().to_string());
706 self.report_editor_event("save", file_extension, cx);
707
708 project.update(cx, |project, cx| {
709 project.save_buffer_as(buffer, abs_path, cx)
710 })
711 }
712
713 fn reload(
714 &mut self,
715 project: ModelHandle<Project>,
716 cx: &mut ViewContext<Self>,
717 ) -> Task<Result<()>> {
718 let buffer = self.buffer().clone();
719 let buffers = self.buffer.read(cx).all_buffers();
720 let reload_buffers =
721 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
722 cx.spawn(|this, mut cx| async move {
723 let transaction = reload_buffers.log_err().await;
724 this.update(&mut cx, |editor, cx| {
725 editor.request_autoscroll(Autoscroll::fit(), cx)
726 })?;
727 buffer.update(&mut cx, |buffer, cx| {
728 if let Some(transaction) = transaction {
729 if !buffer.is_singleton() {
730 buffer.push_transaction(&transaction.0, cx);
731 }
732 }
733 });
734 Ok(())
735 })
736 }
737
738 fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
739 let mut result = SmallVec::new();
740 match event {
741 Event::Closed => result.push(ItemEvent::CloseItem),
742 Event::Saved | Event::TitleChanged => {
743 result.push(ItemEvent::UpdateTab);
744 result.push(ItemEvent::UpdateBreadcrumbs);
745 }
746 Event::Reparsed => {
747 result.push(ItemEvent::UpdateBreadcrumbs);
748 }
749 Event::SelectionsChanged { local } if *local => {
750 result.push(ItemEvent::UpdateBreadcrumbs);
751 }
752 Event::DirtyChanged => {
753 result.push(ItemEvent::UpdateTab);
754 }
755 Event::BufferEdited => {
756 result.push(ItemEvent::Edit);
757 result.push(ItemEvent::UpdateBreadcrumbs);
758 }
759 _ => {}
760 }
761 result
762 }
763
764 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
765 Some(Box::new(handle.clone()))
766 }
767
768 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Vector2F> {
769 self.pixel_position_of_newest_cursor
770 }
771
772 fn breadcrumb_location(&self) -> ToolbarItemLocation {
773 ToolbarItemLocation::PrimaryLeft { flex: None }
774 }
775
776 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
777 let cursor = self.selections.newest_anchor().head();
778 let multibuffer = &self.buffer().read(cx);
779 let (buffer_id, symbols) =
780 multibuffer.symbols_containing(cursor, Some(&theme.editor.syntax), cx)?;
781 let buffer = multibuffer.buffer(buffer_id)?;
782
783 let buffer = buffer.read(cx);
784 let filename = buffer
785 .snapshot()
786 .resolve_file_path(
787 cx,
788 self.project
789 .as_ref()
790 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
791 .unwrap_or_default(),
792 )
793 .map(|path| path.to_string_lossy().to_string())
794 .unwrap_or_else(|| "untitled".to_string());
795
796 let mut breadcrumbs = vec![BreadcrumbText {
797 text: filename,
798 highlights: None,
799 }];
800 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
801 text: symbol.text,
802 highlights: Some(symbol.highlight_ranges),
803 }));
804 Some(breadcrumbs)
805 }
806
807 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
808 let workspace_id = workspace.database_id();
809 let item_id = cx.view_id();
810 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
811
812 fn serialize(
813 buffer: ModelHandle<Buffer>,
814 workspace_id: WorkspaceId,
815 item_id: ItemId,
816 cx: &mut AppContext,
817 ) {
818 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
819 let path = file.abs_path(cx);
820
821 cx.background()
822 .spawn(async move {
823 DB.save_path(item_id, workspace_id, path.clone())
824 .await
825 .log_err()
826 })
827 .detach();
828 }
829 }
830
831 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
832 serialize(buffer.clone(), workspace_id, item_id, cx);
833
834 cx.subscribe(&buffer, |this, buffer, event, cx| {
835 if let Some((_, workspace_id)) = this.workspace.as_ref() {
836 if let language::Event::FileHandleChanged = event {
837 serialize(buffer, *workspace_id, cx.view_id(), cx);
838 }
839 }
840 })
841 .detach();
842 }
843 }
844
845 fn serialized_item_kind() -> Option<&'static str> {
846 Some("Editor")
847 }
848
849 fn deserialize(
850 project: ModelHandle<Project>,
851 _workspace: WeakViewHandle<Workspace>,
852 workspace_id: workspace::WorkspaceId,
853 item_id: ItemId,
854 cx: &mut ViewContext<Pane>,
855 ) -> Task<Result<ViewHandle<Self>>> {
856 let project_item: Result<_> = project.update(cx, |project, cx| {
857 // Look up the path with this key associated, create a self with that path
858 let path = DB
859 .get_path(item_id, workspace_id)?
860 .context("No path stored for this editor")?;
861
862 let (worktree, path) = project
863 .find_local_worktree(&path, cx)
864 .with_context(|| format!("No worktree for path: {path:?}"))?;
865 let project_path = ProjectPath {
866 worktree_id: worktree.read(cx).id(),
867 path: path.into(),
868 };
869
870 Ok(project.open_path(project_path, cx))
871 });
872
873 project_item
874 .map(|project_item| {
875 cx.spawn(|pane, mut cx| async move {
876 let (_, project_item) = project_item.await?;
877 let buffer = project_item
878 .downcast::<Buffer>()
879 .context("Project item at stored path was not a buffer")?;
880 Ok(pane.update(&mut cx, |_, cx| {
881 cx.add_view(|cx| {
882 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
883 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
884 editor
885 })
886 })?)
887 })
888 })
889 .unwrap_or_else(|error| Task::ready(Err(error)))
890 }
891}
892
893impl ProjectItem for Editor {
894 type Item = Buffer;
895
896 fn for_project_item(
897 project: ModelHandle<Project>,
898 buffer: ModelHandle<Buffer>,
899 cx: &mut ViewContext<Self>,
900 ) -> Self {
901 Self::for_buffer(buffer, Some(project), cx)
902 }
903}
904
905pub(crate) enum BufferSearchHighlights {}
906impl SearchableItem for Editor {
907 type Match = Range<Anchor>;
908
909 fn to_search_event(
910 &mut self,
911 event: &Self::Event,
912 _: &mut ViewContext<Self>,
913 ) -> Option<SearchEvent> {
914 match event {
915 Event::BufferEdited => Some(SearchEvent::MatchesInvalidated),
916 Event::SelectionsChanged { .. } => {
917 if self.selections.disjoint_anchors().len() == 1 {
918 Some(SearchEvent::ActiveMatchChanged)
919 } else {
920 None
921 }
922 }
923 _ => None,
924 }
925 }
926
927 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
928 self.clear_background_highlights::<BufferSearchHighlights>(cx);
929 }
930
931 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
932 self.highlight_background::<BufferSearchHighlights>(
933 matches,
934 |theme| theme.search.match_background,
935 cx,
936 );
937 }
938
939 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
940 let display_map = self.snapshot(cx).display_snapshot;
941 let selection = self.selections.newest::<usize>(cx);
942 if selection.start == selection.end {
943 let (range, kind) = display_map
944 .buffer_snapshot
945 .surrounding_word(selection.start);
946 if kind != Some(CharKind::Word) {
947 return String::new();
948 }
949 let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
950 if text.trim().is_empty() {
951 String::new()
952 } else {
953 text
954 }
955 } else {
956 display_map
957 .buffer_snapshot
958 .text_for_range(selection.start..selection.end)
959 .collect()
960 }
961 }
962
963 fn activate_match(
964 &mut self,
965 index: usize,
966 matches: Vec<Range<Anchor>>,
967 cx: &mut ViewContext<Self>,
968 ) {
969 self.unfold_ranges([matches[index].clone()], false, true, cx);
970 let range = self.range_for_match(&matches[index]);
971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
972 s.select_ranges([range]);
973 })
974 }
975
976 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
977 self.unfold_ranges(matches.clone(), false, false, cx);
978 let mut ranges = Vec::new();
979 for m in &matches {
980 ranges.push(self.range_for_match(&m))
981 }
982 self.change_selections(None, cx, |s| s.select_ranges(ranges));
983 }
984 fn replace(
985 &mut self,
986 identifier: &Self::Match,
987 query: &SearchQuery,
988 cx: &mut ViewContext<Self>,
989 ) {
990 let text = self.buffer.read(cx);
991 let text = text.snapshot(cx);
992 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
993 let text: Cow<_> = if text.len() == 1 {
994 text.first().cloned().unwrap().into()
995 } else {
996 let joined_chunks = text.join("");
997 joined_chunks.into()
998 };
999
1000 if let Some(replacement) = query.replacement_for(&text) {
1001 self.transact(cx, |this, cx| {
1002 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1003 });
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}