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)
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 { .. } => {
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 tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
582 let path = path_for_buffer(&self.buffer, detail, true, cx)?;
583 Some(path.to_string_lossy().to_string().into())
584 }
585
586 fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement {
587 let git_status = if ItemSettings::get_global(cx).git_status {
588 self.buffer()
589 .read(cx)
590 .as_singleton()
591 .and_then(|buffer| buffer.read(cx).project_path(cx))
592 .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
593 .and_then(|entry| entry.git_status())
594 } else {
595 None
596 };
597 let label_color = match git_status {
598 Some(GitFileStatus::Added) => Color::Created,
599 Some(GitFileStatus::Modified) => Color::Modified,
600 Some(GitFileStatus::Conflict) => Color::Conflict,
601 None => {
602 if selected {
603 Color::Default
604 } else {
605 Color::Muted
606 }
607 }
608 };
609
610 let description = detail.and_then(|detail| {
611 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
612 let description = path.to_string_lossy();
613 let description = description.trim();
614
615 if description.is_empty() {
616 return None;
617 }
618
619 Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
620 });
621
622 h_stack()
623 .gap_2()
624 .child(Label::new(self.title(cx).to_string()).color(label_color))
625 .when_some(description, |this, description| {
626 this.child(
627 Label::new(description)
628 .size(LabelSize::XSmall)
629 .color(Color::Muted),
630 )
631 })
632 .into_any_element()
633 }
634
635 fn for_each_project_item(
636 &self,
637 cx: &AppContext,
638 f: &mut dyn FnMut(EntityId, &dyn project::Item),
639 ) {
640 self.buffer
641 .read(cx)
642 .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
643 }
644
645 fn is_singleton(&self, cx: &AppContext) -> bool {
646 self.buffer.read(cx).is_singleton()
647 }
648
649 fn clone_on_split(
650 &self,
651 _workspace_id: WorkspaceId,
652 cx: &mut ViewContext<Self>,
653 ) -> Option<View<Editor>>
654 where
655 Self: Sized,
656 {
657 Some(cx.new_view(|cx| self.clone(cx)))
658 }
659
660 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
661 self.nav_history = Some(history);
662 }
663
664 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
665 let selection = self.selections.newest_anchor();
666 self.push_to_nav_history(selection.head(), None, cx);
667 }
668
669 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
670 hide_link_definition(self, cx);
671 self.link_go_to_definition_state.last_trigger_point = None;
672 }
673
674 fn is_dirty(&self, cx: &AppContext) -> bool {
675 self.buffer().read(cx).read(cx).is_dirty()
676 }
677
678 fn has_conflict(&self, cx: &AppContext) -> bool {
679 self.buffer().read(cx).read(cx).has_conflict()
680 }
681
682 fn can_save(&self, cx: &AppContext) -> bool {
683 let buffer = &self.buffer().read(cx);
684 if let Some(buffer) = buffer.as_singleton() {
685 buffer.read(cx).project_path(cx).is_some()
686 } else {
687 true
688 }
689 }
690
691 fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
692 self.report_editor_event("save", None, cx);
693 let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
694 let buffers = self.buffer().clone().read(cx).all_buffers();
695 cx.spawn(|_, mut cx| async move {
696 format.await?;
697
698 if buffers.len() == 1 {
699 project
700 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
701 .await?;
702 } else {
703 // For multi-buffers, only save those ones that contain changes. For clean buffers
704 // we simulate saving by calling `Buffer::did_save`, so that language servers or
705 // other downstream listeners of save events get notified.
706 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
707 buffer
708 .update(&mut cx, |buffer, _| {
709 buffer.is_dirty() || buffer.has_conflict()
710 })
711 .unwrap_or(false)
712 });
713
714 project
715 .update(&mut cx, |project, cx| {
716 project.save_buffers(dirty_buffers, cx)
717 })?
718 .await?;
719 for buffer in clean_buffers {
720 buffer
721 .update(&mut cx, |buffer, cx| {
722 let version = buffer.saved_version().clone();
723 let fingerprint = buffer.saved_version_fingerprint();
724 let mtime = buffer.saved_mtime();
725 buffer.did_save(version, fingerprint, mtime, cx);
726 })
727 .ok();
728 }
729 }
730
731 Ok(())
732 })
733 }
734
735 fn save_as(
736 &mut self,
737 project: Model<Project>,
738 abs_path: PathBuf,
739 cx: &mut ViewContext<Self>,
740 ) -> Task<Result<()>> {
741 let buffer = self
742 .buffer()
743 .read(cx)
744 .as_singleton()
745 .expect("cannot call save_as on an excerpt list");
746
747 let file_extension = abs_path
748 .extension()
749 .map(|a| a.to_string_lossy().to_string());
750 self.report_editor_event("save", file_extension, cx);
751
752 project.update(cx, |project, cx| {
753 project.save_buffer_as(buffer, abs_path, cx)
754 })
755 }
756
757 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
758 let buffer = self.buffer().clone();
759 let buffers = self.buffer.read(cx).all_buffers();
760 let reload_buffers =
761 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
762 cx.spawn(|this, mut cx| async move {
763 let transaction = reload_buffers.log_err().await;
764 this.update(&mut cx, |editor, cx| {
765 editor.request_autoscroll(Autoscroll::fit(), cx)
766 })?;
767 buffer
768 .update(&mut cx, |buffer, cx| {
769 if let Some(transaction) = transaction {
770 if !buffer.is_singleton() {
771 buffer.push_transaction(&transaction.0, cx);
772 }
773 }
774 })
775 .ok();
776 Ok(())
777 })
778 }
779
780 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
781 Some(Box::new(handle.clone()))
782 }
783
784 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
785 self.pixel_position_of_newest_cursor
786 }
787
788 fn breadcrumb_location(&self) -> ToolbarItemLocation {
789 ToolbarItemLocation::PrimaryLeft
790 }
791
792 fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
793 let cursor = self.selections.newest_anchor().head();
794 let multibuffer = &self.buffer().read(cx);
795 let (buffer_id, symbols) =
796 multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
797 let buffer = multibuffer.buffer(buffer_id)?;
798
799 let buffer = buffer.read(cx);
800 let filename = buffer
801 .snapshot()
802 .resolve_file_path(
803 cx,
804 self.project
805 .as_ref()
806 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
807 .unwrap_or_default(),
808 )
809 .map(|path| path.to_string_lossy().to_string())
810 .unwrap_or_else(|| "untitled".to_string());
811
812 let mut breadcrumbs = vec![BreadcrumbText {
813 text: filename,
814 highlights: None,
815 }];
816 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
817 text: symbol.text,
818 highlights: Some(symbol.highlight_ranges),
819 }));
820 Some(breadcrumbs)
821 }
822
823 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
824 let workspace_id = workspace.database_id();
825 let item_id = cx.view().item_id().as_u64() as ItemId;
826 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
827
828 fn serialize(
829 buffer: Model<Buffer>,
830 workspace_id: WorkspaceId,
831 item_id: ItemId,
832 cx: &mut AppContext,
833 ) {
834 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
835 let path = file.abs_path(cx);
836
837 cx.background_executor()
838 .spawn(async move {
839 DB.save_path(item_id, workspace_id, path.clone())
840 .await
841 .log_err()
842 })
843 .detach();
844 }
845 }
846
847 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
848 serialize(buffer.clone(), workspace_id, item_id, cx);
849
850 cx.subscribe(&buffer, |this, buffer, event, cx| {
851 if let Some((_, workspace_id)) = this.workspace.as_ref() {
852 if let language::Event::FileHandleChanged = event {
853 serialize(
854 buffer,
855 *workspace_id,
856 cx.view().item_id().as_u64() as ItemId,
857 cx,
858 );
859 }
860 }
861 })
862 .detach();
863 }
864 }
865
866 fn serialized_item_kind() -> Option<&'static str> {
867 Some("Editor")
868 }
869
870 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
871 match event {
872 EditorEvent::Closed => f(ItemEvent::CloseItem),
873
874 EditorEvent::Saved | EditorEvent::TitleChanged => {
875 f(ItemEvent::UpdateTab);
876 f(ItemEvent::UpdateBreadcrumbs);
877 }
878
879 EditorEvent::Reparsed => {
880 f(ItemEvent::UpdateBreadcrumbs);
881 }
882
883 EditorEvent::SelectionsChanged { local } if *local => {
884 f(ItemEvent::UpdateBreadcrumbs);
885 }
886
887 EditorEvent::DirtyChanged => {
888 f(ItemEvent::UpdateTab);
889 }
890
891 EditorEvent::BufferEdited => {
892 f(ItemEvent::Edit);
893 f(ItemEvent::UpdateBreadcrumbs);
894 }
895
896 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
897 f(ItemEvent::Edit);
898 }
899
900 _ => {}
901 }
902 }
903
904 fn deserialize(
905 project: Model<Project>,
906 _workspace: WeakView<Workspace>,
907 workspace_id: workspace::WorkspaceId,
908 item_id: ItemId,
909 cx: &mut ViewContext<Pane>,
910 ) -> Task<Result<View<Self>>> {
911 let project_item: Result<_> = project.update(cx, |project, cx| {
912 // Look up the path with this key associated, create a self with that path
913 let path = DB
914 .get_path(item_id, workspace_id)?
915 .context("No path stored for this editor")?;
916
917 let (worktree, path) = project
918 .find_local_worktree(&path, cx)
919 .with_context(|| format!("No worktree for path: {path:?}"))?;
920 let project_path = ProjectPath {
921 worktree_id: worktree.read(cx).id(),
922 path: path.into(),
923 };
924
925 Ok(project.open_path(project_path, cx))
926 });
927
928 project_item
929 .map(|project_item| {
930 cx.spawn(|pane, mut cx| async move {
931 let (_, project_item) = project_item.await?;
932 let buffer = project_item
933 .downcast::<Buffer>()
934 .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
935 Ok(pane.update(&mut cx, |_, cx| {
936 cx.new_view(|cx| {
937 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
938
939 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
940 editor
941 })
942 })?)
943 })
944 })
945 .unwrap_or_else(|error| Task::ready(Err(error)))
946 }
947}
948
949impl ProjectItem for Editor {
950 type Item = Buffer;
951
952 fn for_project_item(
953 project: Model<Project>,
954 buffer: Model<Buffer>,
955 cx: &mut ViewContext<Self>,
956 ) -> Self {
957 Self::for_buffer(buffer, Some(project), cx)
958 }
959}
960
961impl EventEmitter<SearchEvent> for Editor {}
962
963pub(crate) enum BufferSearchHighlights {}
964impl SearchableItem for Editor {
965 type Match = Range<Anchor>;
966
967 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
968 self.clear_background_highlights::<BufferSearchHighlights>(cx);
969 }
970
971 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
972 self.highlight_background::<BufferSearchHighlights>(
973 matches,
974 |theme| theme.search_match_background,
975 cx,
976 );
977 }
978
979 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
980 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
981 let snapshot = &self.snapshot(cx).buffer_snapshot;
982 let selection = self.selections.newest::<usize>(cx);
983
984 match setting {
985 SeedQuerySetting::Never => String::new(),
986 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
987 snapshot
988 .text_for_range(selection.start..selection.end)
989 .collect()
990 }
991 SeedQuerySetting::Selection => String::new(),
992 SeedQuerySetting::Always => {
993 let (range, kind) = snapshot.surrounding_word(selection.start);
994 if kind == Some(CharKind::Word) {
995 let text: String = snapshot.text_for_range(range).collect();
996 if !text.trim().is_empty() {
997 return text;
998 }
999 }
1000 String::new()
1001 }
1002 }
1003 }
1004
1005 fn activate_match(
1006 &mut self,
1007 index: usize,
1008 matches: Vec<Range<Anchor>>,
1009 cx: &mut ViewContext<Self>,
1010 ) {
1011 self.unfold_ranges([matches[index].clone()], false, true, cx);
1012 let range = self.range_for_match(&matches[index]);
1013 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1014 s.select_ranges([range]);
1015 })
1016 }
1017
1018 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
1019 self.unfold_ranges(matches.clone(), false, false, cx);
1020 let mut ranges = Vec::new();
1021 for m in &matches {
1022 ranges.push(self.range_for_match(&m))
1023 }
1024 self.change_selections(None, cx, |s| s.select_ranges(ranges));
1025 }
1026 fn replace(
1027 &mut self,
1028 identifier: &Self::Match,
1029 query: &SearchQuery,
1030 cx: &mut ViewContext<Self>,
1031 ) {
1032 let text = self.buffer.read(cx);
1033 let text = text.snapshot(cx);
1034 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1035 let text: Cow<_> = if text.len() == 1 {
1036 text.first().cloned().unwrap().into()
1037 } else {
1038 let joined_chunks = text.join("");
1039 joined_chunks.into()
1040 };
1041
1042 if let Some(replacement) = query.replacement_for(&text) {
1043 self.transact(cx, |this, cx| {
1044 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1045 });
1046 }
1047 }
1048 fn match_index_for_direction(
1049 &mut self,
1050 matches: &Vec<Range<Anchor>>,
1051 current_index: usize,
1052 direction: Direction,
1053 count: usize,
1054 cx: &mut ViewContext<Self>,
1055 ) -> usize {
1056 let buffer = self.buffer().read(cx).snapshot(cx);
1057 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1058 self.selections.newest_anchor().head()
1059 } else {
1060 matches[current_index].start
1061 };
1062
1063 let mut count = count % matches.len();
1064 if count == 0 {
1065 return current_index;
1066 }
1067 match direction {
1068 Direction::Next => {
1069 if matches[current_index]
1070 .start
1071 .cmp(¤t_index_position, &buffer)
1072 .is_gt()
1073 {
1074 count = count - 1
1075 }
1076
1077 (current_index + count) % matches.len()
1078 }
1079 Direction::Prev => {
1080 if matches[current_index]
1081 .end
1082 .cmp(¤t_index_position, &buffer)
1083 .is_lt()
1084 {
1085 count = count - 1;
1086 }
1087
1088 if current_index >= count {
1089 current_index - count
1090 } else {
1091 matches.len() - (count - current_index)
1092 }
1093 }
1094 }
1095 }
1096
1097 fn find_matches(
1098 &mut self,
1099 query: Arc<project::search::SearchQuery>,
1100 cx: &mut ViewContext<Self>,
1101 ) -> Task<Vec<Range<Anchor>>> {
1102 let buffer = self.buffer().read(cx).snapshot(cx);
1103 cx.background_executor().spawn(async move {
1104 let mut ranges = Vec::new();
1105 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1106 ranges.extend(
1107 query
1108 .search(excerpt_buffer, None)
1109 .await
1110 .into_iter()
1111 .map(|range| {
1112 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1113 }),
1114 );
1115 } else {
1116 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1117 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1118 ranges.extend(
1119 query
1120 .search(&excerpt.buffer, Some(excerpt_range.clone()))
1121 .await
1122 .into_iter()
1123 .map(|range| {
1124 let start = excerpt
1125 .buffer
1126 .anchor_after(excerpt_range.start + range.start);
1127 let end = excerpt
1128 .buffer
1129 .anchor_before(excerpt_range.start + range.end);
1130 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1131 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1132 }),
1133 );
1134 }
1135 }
1136 ranges
1137 })
1138 }
1139
1140 fn active_match_index(
1141 &mut self,
1142 matches: Vec<Range<Anchor>>,
1143 cx: &mut ViewContext<Self>,
1144 ) -> Option<usize> {
1145 active_match_index(
1146 &matches,
1147 &self.selections.newest_anchor().head(),
1148 &self.buffer().read(cx).snapshot(cx),
1149 )
1150 }
1151}
1152
1153pub fn active_match_index(
1154 ranges: &[Range<Anchor>],
1155 cursor: &Anchor,
1156 buffer: &MultiBufferSnapshot,
1157) -> Option<usize> {
1158 if ranges.is_empty() {
1159 None
1160 } else {
1161 match ranges.binary_search_by(|probe| {
1162 if probe.end.cmp(cursor, &*buffer).is_lt() {
1163 Ordering::Less
1164 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1165 Ordering::Greater
1166 } else {
1167 Ordering::Equal
1168 }
1169 }) {
1170 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1171 }
1172 }
1173}
1174
1175pub struct CursorPosition {
1176 position: Option<Point>,
1177 selected_count: usize,
1178 _observe_active_editor: Option<Subscription>,
1179}
1180
1181impl Default for CursorPosition {
1182 fn default() -> Self {
1183 Self::new()
1184 }
1185}
1186
1187impl CursorPosition {
1188 pub fn new() -> Self {
1189 Self {
1190 position: None,
1191 selected_count: 0,
1192 _observe_active_editor: None,
1193 }
1194 }
1195
1196 fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1197 let editor = editor.read(cx);
1198 let buffer = editor.buffer().read(cx).snapshot(cx);
1199
1200 self.selected_count = 0;
1201 let mut last_selection: Option<Selection<usize>> = None;
1202 for selection in editor.selections.all::<usize>(cx) {
1203 self.selected_count += selection.end - selection.start;
1204 if last_selection
1205 .as_ref()
1206 .map_or(true, |last_selection| selection.id > last_selection.id)
1207 {
1208 last_selection = Some(selection);
1209 }
1210 }
1211 self.position = last_selection.map(|s| s.head().to_point(&buffer));
1212
1213 cx.notify();
1214 }
1215}
1216
1217impl Render for CursorPosition {
1218 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1219 div().when_some(self.position, |el, position| {
1220 let mut text = format!(
1221 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1222 position.row + 1,
1223 position.column + 1
1224 );
1225 if self.selected_count > 0 {
1226 write!(text, " ({} selected)", self.selected_count).unwrap();
1227 }
1228
1229 el.child(Label::new(text).size(LabelSize::Small))
1230 })
1231 }
1232}
1233
1234impl StatusItemView for CursorPosition {
1235 fn set_active_pane_item(
1236 &mut self,
1237 active_pane_item: Option<&dyn ItemHandle>,
1238 cx: &mut ViewContext<Self>,
1239 ) {
1240 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1241 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1242 self.update_position(editor, cx);
1243 } else {
1244 self.position = None;
1245 self._observe_active_editor = None;
1246 }
1247
1248 cx.notify();
1249 }
1250}
1251
1252fn path_for_buffer<'a>(
1253 buffer: &Model<MultiBuffer>,
1254 height: usize,
1255 include_filename: bool,
1256 cx: &'a AppContext,
1257) -> Option<Cow<'a, Path>> {
1258 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1259 path_for_file(file.as_ref(), height, include_filename, cx)
1260}
1261
1262fn path_for_file<'a>(
1263 file: &'a dyn language::File,
1264 mut height: usize,
1265 include_filename: bool,
1266 cx: &'a AppContext,
1267) -> Option<Cow<'a, Path>> {
1268 // Ensure we always render at least the filename.
1269 height += 1;
1270
1271 let mut prefix = file.path().as_ref();
1272 while height > 0 {
1273 if let Some(parent) = prefix.parent() {
1274 prefix = parent;
1275 height -= 1;
1276 } else {
1277 break;
1278 }
1279 }
1280
1281 // Here we could have just always used `full_path`, but that is very
1282 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1283 // traversed all the way up to the worktree's root.
1284 if height > 0 {
1285 let full_path = file.full_path(cx);
1286 if include_filename {
1287 Some(full_path.into())
1288 } else {
1289 Some(full_path.parent()?.to_path_buf().into())
1290 }
1291 } else {
1292 let mut path = file.path().strip_prefix(prefix).ok()?;
1293 if !include_filename {
1294 path = path.parent()?;
1295 }
1296 Some(path.into())
1297 }
1298}
1299
1300#[cfg(test)]
1301mod tests {
1302 use super::*;
1303 use gpui::AppContext;
1304 use std::{
1305 path::{Path, PathBuf},
1306 sync::Arc,
1307 time::SystemTime,
1308 };
1309
1310 #[gpui::test]
1311 fn test_path_for_file(cx: &mut AppContext) {
1312 let file = TestFile {
1313 path: Path::new("").into(),
1314 full_path: PathBuf::from(""),
1315 };
1316 assert_eq!(path_for_file(&file, 0, false, cx), None);
1317 }
1318
1319 struct TestFile {
1320 path: Arc<Path>,
1321 full_path: PathBuf,
1322 }
1323
1324 impl language::File for TestFile {
1325 fn path(&self) -> &Arc<Path> {
1326 &self.path
1327 }
1328
1329 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1330 self.full_path.clone()
1331 }
1332
1333 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1334 unimplemented!()
1335 }
1336
1337 fn mtime(&self) -> SystemTime {
1338 unimplemented!()
1339 }
1340
1341 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1342 unimplemented!()
1343 }
1344
1345 fn worktree_id(&self) -> usize {
1346 0
1347 }
1348
1349 fn is_deleted(&self) -> bool {
1350 unimplemented!()
1351 }
1352
1353 fn as_any(&self) -> &dyn std::any::Any {
1354 unimplemented!()
1355 }
1356
1357 fn to_proto(&self) -> rpc::proto::File {
1358 unimplemented!()
1359 }
1360 }
1361}