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