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