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