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