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