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