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