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