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