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::{h_stack, Color, Label};
36use util::{paths::PathExt, paths::FILE_ROW_COLUMN_DELIMITER, ResultExt, TryFutureExt};
37use workspace::{
38 item::{BreadcrumbText, FollowEvent, FollowableEvents, 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 FollowableEvents for EditorEvent {
50 fn to_follow_event(&self) -> Option<workspace::item::FollowEvent> {
51 match self {
52 EditorEvent::Edited => Some(FollowEvent::Unfollow),
53 EditorEvent::SelectionsChanged { local }
54 | EditorEvent::ScrollPositionChanged { local, .. } => {
55 if *local {
56 Some(FollowEvent::Unfollow)
57 } else {
58 None
59 }
60 }
61 _ => None,
62 }
63 }
64}
65
66impl EventEmitter<ItemEvent> for Editor {}
67
68impl FollowableItem for Editor {
69 type FollowableEvent = EditorEvent;
70 fn remote_id(&self) -> Option<ViewId> {
71 self.remote_id
72 }
73
74 fn from_state_proto(
75 pane: View<workspace::Pane>,
76 workspace: View<Workspace>,
77 remote_id: ViewId,
78 state: &mut Option<proto::view::Variant>,
79 cx: &mut WindowContext,
80 ) -> Option<Task<Result<View<Self>>>> {
81 let project = workspace.read(cx).project().to_owned();
82 let Some(proto::view::Variant::Editor(_)) = state else {
83 return None;
84 };
85 let Some(proto::view::Variant::Editor(state)) = state.take() else {
86 unreachable!()
87 };
88
89 let client = project.read(cx).client();
90 let replica_id = project.read(cx).replica_id();
91 let buffer_ids = state
92 .excerpts
93 .iter()
94 .map(|excerpt| excerpt.buffer_id)
95 .collect::<HashSet<_>>();
96 let buffers = project.update(cx, |project, cx| {
97 buffer_ids
98 .iter()
99 .map(|id| project.open_buffer_by_id(*id, cx))
100 .collect::<Vec<_>>()
101 });
102
103 let pane = pane.downgrade();
104 Some(cx.spawn(|mut cx| async move {
105 let mut buffers = futures::future::try_join_all(buffers).await?;
106 let editor = pane.update(&mut cx, |pane, cx| {
107 let mut editors = pane.items_of_type::<Self>();
108 editors.find(|editor| {
109 let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
110 let singleton_buffer_matches = state.singleton
111 && buffers.first()
112 == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
113 ids_match || singleton_buffer_matches
114 })
115 })?;
116
117 let editor = if let Some(editor) = editor {
118 editor
119 } else {
120 pane.update(&mut cx, |_, cx| {
121 let multibuffer = cx.build_model(|cx| {
122 let mut multibuffer;
123 if state.singleton && buffers.len() == 1 {
124 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
125 } else {
126 multibuffer = MultiBuffer::new(replica_id);
127 let mut excerpts = state.excerpts.into_iter().peekable();
128 while let Some(excerpt) = excerpts.peek() {
129 let buffer_id = excerpt.buffer_id;
130 let buffer_excerpts = iter::from_fn(|| {
131 let excerpt = excerpts.peek()?;
132 (excerpt.buffer_id == buffer_id)
133 .then(|| excerpts.next().unwrap())
134 });
135 let buffer =
136 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
137 if let Some(buffer) = buffer {
138 multibuffer.push_excerpts(
139 buffer.clone(),
140 buffer_excerpts.filter_map(deserialize_excerpt_range),
141 cx,
142 );
143 }
144 }
145 };
146
147 if let Some(title) = &state.title {
148 multibuffer = multibuffer.with_title(title.clone())
149 }
150
151 multibuffer
152 });
153
154 cx.build_view(|cx| {
155 let mut editor =
156 Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
157 editor.remote_id = Some(remote_id);
158 editor
159 })
160 })?
161 };
162
163 update_editor_from_message(
164 editor.downgrade(),
165 project,
166 proto::update_view::Editor {
167 selections: state.selections,
168 pending_selection: state.pending_selection,
169 scroll_top_anchor: state.scroll_top_anchor,
170 scroll_x: state.scroll_x,
171 scroll_y: state.scroll_y,
172 ..Default::default()
173 },
174 &mut cx,
175 )
176 .await?;
177
178 Ok(editor)
179 }))
180 }
181
182 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
183 self.leader_peer_id = leader_peer_id;
184 if self.leader_peer_id.is_some() {
185 self.buffer.update(cx, |buffer, cx| {
186 buffer.remove_active_selections(cx);
187 });
188 } else if self.focus_handle.is_focused(cx) {
189 self.buffer.update(cx, |buffer, cx| {
190 buffer.set_active_selections(
191 &self.selections.disjoint_anchors(),
192 self.selections.line_mode,
193 self.cursor_shape,
194 cx,
195 );
196 });
197 }
198 cx.notify();
199 }
200
201 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
202 let buffer = self.buffer.read(cx);
203 let scroll_anchor = self.scroll_manager.anchor();
204 let excerpts = buffer
205 .read(cx)
206 .excerpts()
207 .map(|(id, buffer, range)| proto::Excerpt {
208 id: id.to_proto(),
209 buffer_id: buffer.remote_id(),
210 context_start: Some(serialize_text_anchor(&range.context.start)),
211 context_end: Some(serialize_text_anchor(&range.context.end)),
212 primary_start: range
213 .primary
214 .as_ref()
215 .map(|range| serialize_text_anchor(&range.start)),
216 primary_end: range
217 .primary
218 .as_ref()
219 .map(|range| serialize_text_anchor(&range.end)),
220 })
221 .collect();
222
223 Some(proto::view::Variant::Editor(proto::view::Editor {
224 singleton: buffer.is_singleton(),
225 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
226 excerpts,
227 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
228 scroll_x: scroll_anchor.offset.x,
229 scroll_y: scroll_anchor.offset.y,
230 selections: self
231 .selections
232 .disjoint_anchors()
233 .iter()
234 .map(serialize_selection)
235 .collect(),
236 pending_selection: self
237 .selections
238 .pending_anchor()
239 .as_ref()
240 .map(serialize_selection),
241 }))
242 }
243
244 fn add_event_to_update_proto(
245 &self,
246 event: &Self::FollowableEvent,
247 update: &mut Option<proto::update_view::Variant>,
248 cx: &WindowContext,
249 ) -> bool {
250 let update =
251 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
252
253 match update {
254 proto::update_view::Variant::Editor(update) => match event {
255 EditorEvent::ExcerptsAdded {
256 buffer,
257 predecessor,
258 excerpts,
259 } => {
260 let buffer_id = buffer.read(cx).remote_id();
261 let mut excerpts = excerpts.iter();
262 if let Some((id, range)) = excerpts.next() {
263 update.inserted_excerpts.push(proto::ExcerptInsertion {
264 previous_excerpt_id: Some(predecessor.to_proto()),
265 excerpt: serialize_excerpt(buffer_id, id, range),
266 });
267 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
268 proto::ExcerptInsertion {
269 previous_excerpt_id: None,
270 excerpt: serialize_excerpt(buffer_id, id, range),
271 }
272 }))
273 }
274 true
275 }
276 EditorEvent::ExcerptsRemoved { ids } => {
277 update
278 .deleted_excerpts
279 .extend(ids.iter().map(ExcerptId::to_proto));
280 true
281 }
282 EditorEvent::ScrollPositionChanged { .. } => {
283 let scroll_anchor = self.scroll_manager.anchor();
284 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
285 update.scroll_x = scroll_anchor.offset.x;
286 update.scroll_y = scroll_anchor.offset.y;
287 true
288 }
289 EditorEvent::SelectionsChanged { .. } => {
290 update.selections = self
291 .selections
292 .disjoint_anchors()
293 .iter()
294 .map(serialize_selection)
295 .collect();
296 update.pending_selection = self
297 .selections
298 .pending_anchor()
299 .as_ref()
300 .map(serialize_selection);
301 true
302 }
303 _ => false,
304 },
305 }
306 }
307
308 fn apply_update_proto(
309 &mut self,
310 project: &Model<Project>,
311 message: update_view::Variant,
312 cx: &mut ViewContext<Self>,
313 ) -> Task<Result<()>> {
314 let update_view::Variant::Editor(message) = message;
315 let project = project.clone();
316 cx.spawn(|this, mut cx| async move {
317 update_editor_from_message(this, project, message, &mut cx).await
318 })
319 }
320
321 fn is_project_item(&self, _cx: &WindowContext) -> bool {
322 true
323 }
324}
325
326async fn update_editor_from_message(
327 this: WeakView<Editor>,
328 project: Model<Project>,
329 message: proto::update_view::Editor,
330 cx: &mut AsyncWindowContext,
331) -> Result<()> {
332 // Open all of the buffers of which excerpts were added to the editor.
333 let inserted_excerpt_buffer_ids = message
334 .inserted_excerpts
335 .iter()
336 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
337 .collect::<HashSet<_>>();
338 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
339 inserted_excerpt_buffer_ids
340 .into_iter()
341 .map(|id| project.open_buffer_by_id(id, cx))
342 .collect::<Vec<_>>()
343 })?;
344 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
345
346 // Update the editor's excerpts.
347 this.update(cx, |editor, cx| {
348 editor.buffer.update(cx, |multibuffer, cx| {
349 let mut removed_excerpt_ids = message
350 .deleted_excerpts
351 .into_iter()
352 .map(ExcerptId::from_proto)
353 .collect::<Vec<_>>();
354 removed_excerpt_ids.sort_by({
355 let multibuffer = multibuffer.read(cx);
356 move |a, b| a.cmp(&b, &multibuffer)
357 });
358
359 let mut insertions = message.inserted_excerpts.into_iter().peekable();
360 while let Some(insertion) = insertions.next() {
361 let Some(excerpt) = insertion.excerpt else {
362 continue;
363 };
364 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
365 continue;
366 };
367 let buffer_id = excerpt.buffer_id;
368 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id) else {
369 continue;
370 };
371
372 let adjacent_excerpts = iter::from_fn(|| {
373 let insertion = insertions.peek()?;
374 if insertion.previous_excerpt_id.is_none()
375 && insertion.excerpt.as_ref()?.buffer_id == buffer_id
376 {
377 insertions.next()?.excerpt
378 } else {
379 None
380 }
381 });
382
383 multibuffer.insert_excerpts_with_ids_after(
384 ExcerptId::from_proto(previous_excerpt_id),
385 buffer,
386 [excerpt]
387 .into_iter()
388 .chain(adjacent_excerpts)
389 .filter_map(|excerpt| {
390 Some((
391 ExcerptId::from_proto(excerpt.id),
392 deserialize_excerpt_range(excerpt)?,
393 ))
394 }),
395 cx,
396 );
397 }
398
399 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
400 });
401 })?;
402
403 // Deserialize the editor state.
404 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
405 let buffer = editor.buffer.read(cx).read(cx);
406 let selections = message
407 .selections
408 .into_iter()
409 .filter_map(|selection| deserialize_selection(&buffer, selection))
410 .collect::<Vec<_>>();
411 let pending_selection = message
412 .pending_selection
413 .and_then(|selection| deserialize_selection(&buffer, selection));
414 let scroll_top_anchor = message
415 .scroll_top_anchor
416 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
417 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
418 })??;
419
420 // Wait until the buffer has received all of the operations referenced by
421 // the editor's new state.
422 this.update(cx, |editor, cx| {
423 editor.buffer.update(cx, |buffer, cx| {
424 buffer.wait_for_anchors(
425 selections
426 .iter()
427 .chain(pending_selection.as_ref())
428 .flat_map(|selection| [selection.start, selection.end])
429 .chain(scroll_top_anchor),
430 cx,
431 )
432 })
433 })?
434 .await?;
435
436 // Update the editor's state.
437 this.update(cx, |editor, cx| {
438 if !selections.is_empty() || pending_selection.is_some() {
439 editor.set_selections_from_remote(selections, pending_selection, cx);
440 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
441 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
442 editor.set_scroll_anchor_remote(
443 ScrollAnchor {
444 anchor: scroll_top_anchor,
445 offset: point(message.scroll_x, message.scroll_y),
446 },
447 cx,
448 );
449 }
450 })?;
451 Ok(())
452}
453
454fn serialize_excerpt(
455 buffer_id: u64,
456 id: &ExcerptId,
457 range: &ExcerptRange<language::Anchor>,
458) -> Option<proto::Excerpt> {
459 Some(proto::Excerpt {
460 id: id.to_proto(),
461 buffer_id,
462 context_start: Some(serialize_text_anchor(&range.context.start)),
463 context_end: Some(serialize_text_anchor(&range.context.end)),
464 primary_start: range
465 .primary
466 .as_ref()
467 .map(|r| serialize_text_anchor(&r.start)),
468 primary_end: range
469 .primary
470 .as_ref()
471 .map(|r| serialize_text_anchor(&r.end)),
472 })
473}
474
475fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
476 proto::Selection {
477 id: selection.id as u64,
478 start: Some(serialize_anchor(&selection.start)),
479 end: Some(serialize_anchor(&selection.end)),
480 reversed: selection.reversed,
481 }
482}
483
484fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
485 proto::EditorAnchor {
486 excerpt_id: anchor.excerpt_id.to_proto(),
487 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
488 }
489}
490
491fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
492 let context = {
493 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
494 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
495 start..end
496 };
497 let primary = excerpt
498 .primary_start
499 .zip(excerpt.primary_end)
500 .and_then(|(start, end)| {
501 let start = language::proto::deserialize_anchor(start)?;
502 let end = language::proto::deserialize_anchor(end)?;
503 Some(start..end)
504 });
505 Some(ExcerptRange { context, primary })
506}
507
508fn deserialize_selection(
509 buffer: &MultiBufferSnapshot,
510 selection: proto::Selection,
511) -> Option<Selection<Anchor>> {
512 Some(Selection {
513 id: selection.id as usize,
514 start: deserialize_anchor(buffer, selection.start?)?,
515 end: deserialize_anchor(buffer, selection.end?)?,
516 reversed: selection.reversed,
517 goal: SelectionGoal::None,
518 })
519}
520
521fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
522 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
523 Some(Anchor {
524 excerpt_id,
525 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
526 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
527 })
528}
529
530impl Item for Editor {
531 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
532 if let Ok(data) = data.downcast::<NavigationData>() {
533 let newest_selection = self.selections.newest::<Point>(cx);
534 let buffer = self.buffer.read(cx).read(cx);
535 let offset = if buffer.can_resolve(&data.cursor_anchor) {
536 data.cursor_anchor.to_point(&buffer)
537 } else {
538 buffer.clip_point(data.cursor_position, Bias::Left)
539 };
540
541 let mut scroll_anchor = data.scroll_anchor;
542 if !buffer.can_resolve(&scroll_anchor.anchor) {
543 scroll_anchor.anchor = buffer.anchor_before(
544 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
545 );
546 }
547
548 drop(buffer);
549
550 if newest_selection.head() == offset {
551 false
552 } else {
553 let nav_history = self.nav_history.take();
554 self.set_scroll_anchor(scroll_anchor, cx);
555 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
556 s.select_ranges([offset..offset])
557 });
558 self.nav_history = nav_history;
559 true
560 }
561 } else {
562 false
563 }
564 }
565
566 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
567 let file_path = self
568 .buffer()
569 .read(cx)
570 .as_singleton()?
571 .read(cx)
572 .file()
573 .and_then(|f| f.as_local())?
574 .abs_path(cx);
575
576 let file_path = file_path.compact().to_string_lossy().to_string();
577
578 Some(file_path.into())
579 }
580
581 fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
582 let path = path_for_buffer(&self.buffer, detail, true, cx)?;
583 Some(path.to_string_lossy().to_string().into())
584 }
585
586 fn tab_content(&self, detail: Option<usize>, cx: &WindowContext) -> AnyElement {
587 let theme = cx.theme();
588
589 let description = detail.and_then(|detail| {
590 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
591 let description = path.to_string_lossy();
592 let description = description.trim();
593
594 if description.is_empty() {
595 return None;
596 }
597
598 Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
599 });
600
601 h_stack()
602 .gap_2()
603 .child(Label::new(self.title(cx).to_string()))
604 .when_some(description, |this, description| {
605 this.child(Label::new(description).color(Color::Muted))
606 })
607 .into_any_element()
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 deserialize(
842 project: Model<Project>,
843 _workspace: WeakView<Workspace>,
844 workspace_id: workspace::WorkspaceId,
845 item_id: ItemId,
846 cx: &mut ViewContext<Pane>,
847 ) -> Task<Result<View<Self>>> {
848 let project_item: Result<_> = project.update(cx, |project, cx| {
849 // Look up the path with this key associated, create a self with that path
850 let path = DB
851 .get_path(item_id, workspace_id)?
852 .context("No path stored for this editor")?;
853
854 let (worktree, path) = project
855 .find_local_worktree(&path, cx)
856 .with_context(|| format!("No worktree for path: {path:?}"))?;
857 let project_path = ProjectPath {
858 worktree_id: worktree.read(cx).id(),
859 path: path.into(),
860 };
861
862 Ok(project.open_path(project_path, cx))
863 });
864
865 project_item
866 .map(|project_item| {
867 cx.spawn(|pane, mut cx| async move {
868 let (_, project_item) = project_item.await?;
869 let buffer = project_item
870 .downcast::<Buffer>()
871 .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
872 Ok(pane.update(&mut cx, |_, cx| {
873 cx.build_view(|cx| {
874 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
875
876 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
877 editor
878 })
879 })?)
880 })
881 })
882 .unwrap_or_else(|error| Task::ready(Err(error)))
883 }
884}
885
886impl ProjectItem for Editor {
887 type Item = Buffer;
888
889 fn for_project_item(
890 project: Model<Project>,
891 buffer: Model<Buffer>,
892 cx: &mut ViewContext<Self>,
893 ) -> Self {
894 Self::for_buffer(buffer, Some(project), cx)
895 }
896}
897
898impl EventEmitter<SearchEvent> for Editor {}
899
900pub(crate) enum BufferSearchHighlights {}
901impl SearchableItem for Editor {
902 type Match = Range<Anchor>;
903
904 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
905 self.clear_background_highlights::<BufferSearchHighlights>(cx);
906 }
907
908 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
909 self.highlight_background::<BufferSearchHighlights>(
910 matches,
911 |theme| theme.title_bar_background, // todo: update theme
912 cx,
913 );
914 }
915
916 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
917 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
918 let snapshot = &self.snapshot(cx).buffer_snapshot;
919 let selection = self.selections.newest::<usize>(cx);
920
921 match setting {
922 SeedQuerySetting::Never => String::new(),
923 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
924 snapshot
925 .text_for_range(selection.start..selection.end)
926 .collect()
927 }
928 SeedQuerySetting::Selection => String::new(),
929 SeedQuerySetting::Always => {
930 let (range, kind) = snapshot.surrounding_word(selection.start);
931 if kind == Some(CharKind::Word) {
932 let text: String = snapshot.text_for_range(range).collect();
933 if !text.trim().is_empty() {
934 return text;
935 }
936 }
937 String::new()
938 }
939 }
940 }
941
942 fn activate_match(
943 &mut self,
944 index: usize,
945 matches: Vec<Range<Anchor>>,
946 cx: &mut ViewContext<Self>,
947 ) {
948 self.unfold_ranges([matches[index].clone()], false, true, cx);
949 let range = self.range_for_match(&matches[index]);
950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
951 s.select_ranges([range]);
952 })
953 }
954
955 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
956 self.unfold_ranges(matches.clone(), false, false, cx);
957 let mut ranges = Vec::new();
958 for m in &matches {
959 ranges.push(self.range_for_match(&m))
960 }
961 self.change_selections(None, cx, |s| s.select_ranges(ranges));
962 }
963 fn replace(
964 &mut self,
965 identifier: &Self::Match,
966 query: &SearchQuery,
967 cx: &mut ViewContext<Self>,
968 ) {
969 let text = self.buffer.read(cx);
970 let text = text.snapshot(cx);
971 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
972 let text: Cow<_> = if text.len() == 1 {
973 text.first().cloned().unwrap().into()
974 } else {
975 let joined_chunks = text.join("");
976 joined_chunks.into()
977 };
978
979 if let Some(replacement) = query.replacement_for(&text) {
980 self.transact(cx, |this, cx| {
981 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
982 });
983 }
984 }
985 fn match_index_for_direction(
986 &mut self,
987 matches: &Vec<Range<Anchor>>,
988 current_index: usize,
989 direction: Direction,
990 count: usize,
991 cx: &mut ViewContext<Self>,
992 ) -> usize {
993 let buffer = self.buffer().read(cx).snapshot(cx);
994 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
995 self.selections.newest_anchor().head()
996 } else {
997 matches[current_index].start
998 };
999
1000 let mut count = count % matches.len();
1001 if count == 0 {
1002 return current_index;
1003 }
1004 match direction {
1005 Direction::Next => {
1006 if matches[current_index]
1007 .start
1008 .cmp(¤t_index_position, &buffer)
1009 .is_gt()
1010 {
1011 count = count - 1
1012 }
1013
1014 (current_index + count) % matches.len()
1015 }
1016 Direction::Prev => {
1017 if matches[current_index]
1018 .end
1019 .cmp(¤t_index_position, &buffer)
1020 .is_lt()
1021 {
1022 count = count - 1;
1023 }
1024
1025 if current_index >= count {
1026 current_index - count
1027 } else {
1028 matches.len() - (count - current_index)
1029 }
1030 }
1031 }
1032 }
1033
1034 fn find_matches(
1035 &mut self,
1036 query: Arc<project::search::SearchQuery>,
1037 cx: &mut ViewContext<Self>,
1038 ) -> Task<Vec<Range<Anchor>>> {
1039 let buffer = self.buffer().read(cx).snapshot(cx);
1040 cx.background_executor().spawn(async move {
1041 let mut ranges = Vec::new();
1042 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1043 ranges.extend(
1044 query
1045 .search(excerpt_buffer, None)
1046 .await
1047 .into_iter()
1048 .map(|range| {
1049 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1050 }),
1051 );
1052 } else {
1053 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1054 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1055 ranges.extend(
1056 query
1057 .search(&excerpt.buffer, Some(excerpt_range.clone()))
1058 .await
1059 .into_iter()
1060 .map(|range| {
1061 let start = excerpt
1062 .buffer
1063 .anchor_after(excerpt_range.start + range.start);
1064 let end = excerpt
1065 .buffer
1066 .anchor_before(excerpt_range.start + range.end);
1067 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1068 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1069 }),
1070 );
1071 }
1072 }
1073 ranges
1074 })
1075 }
1076
1077 fn active_match_index(
1078 &mut self,
1079 matches: Vec<Range<Anchor>>,
1080 cx: &mut ViewContext<Self>,
1081 ) -> Option<usize> {
1082 active_match_index(
1083 &matches,
1084 &self.selections.newest_anchor().head(),
1085 &self.buffer().read(cx).snapshot(cx),
1086 )
1087 }
1088}
1089
1090pub fn active_match_index(
1091 ranges: &[Range<Anchor>],
1092 cursor: &Anchor,
1093 buffer: &MultiBufferSnapshot,
1094) -> Option<usize> {
1095 if ranges.is_empty() {
1096 None
1097 } else {
1098 match ranges.binary_search_by(|probe| {
1099 if probe.end.cmp(cursor, &*buffer).is_lt() {
1100 Ordering::Less
1101 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1102 Ordering::Greater
1103 } else {
1104 Ordering::Equal
1105 }
1106 }) {
1107 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1108 }
1109 }
1110}
1111
1112pub struct CursorPosition {
1113 position: Option<Point>,
1114 selected_count: usize,
1115 _observe_active_editor: Option<Subscription>,
1116}
1117
1118impl Default for CursorPosition {
1119 fn default() -> Self {
1120 Self::new()
1121 }
1122}
1123
1124impl CursorPosition {
1125 pub fn new() -> Self {
1126 Self {
1127 position: None,
1128 selected_count: 0,
1129 _observe_active_editor: None,
1130 }
1131 }
1132
1133 fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1134 let editor = editor.read(cx);
1135 let buffer = editor.buffer().read(cx).snapshot(cx);
1136
1137 self.selected_count = 0;
1138 let mut last_selection: Option<Selection<usize>> = None;
1139 for selection in editor.selections.all::<usize>(cx) {
1140 self.selected_count += selection.end - selection.start;
1141 if last_selection
1142 .as_ref()
1143 .map_or(true, |last_selection| selection.id > last_selection.id)
1144 {
1145 last_selection = Some(selection);
1146 }
1147 }
1148 self.position = last_selection.map(|s| s.head().to_point(&buffer));
1149
1150 cx.notify();
1151 }
1152}
1153
1154impl Render for CursorPosition {
1155 type Element = Div;
1156
1157 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1158 div().when_some(self.position, |el, position| {
1159 let mut text = format!(
1160 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1161 position.row + 1,
1162 position.column + 1
1163 );
1164 if self.selected_count > 0 {
1165 write!(text, " ({} selected)", self.selected_count).unwrap();
1166 }
1167
1168 el.child(Label::new(text))
1169 })
1170 }
1171}
1172
1173impl StatusItemView for CursorPosition {
1174 fn set_active_pane_item(
1175 &mut self,
1176 active_pane_item: Option<&dyn ItemHandle>,
1177 cx: &mut ViewContext<Self>,
1178 ) {
1179 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1180 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1181 self.update_position(editor, cx);
1182 } else {
1183 self.position = None;
1184 self._observe_active_editor = None;
1185 }
1186
1187 cx.notify();
1188 }
1189}
1190
1191fn path_for_buffer<'a>(
1192 buffer: &Model<MultiBuffer>,
1193 height: usize,
1194 include_filename: bool,
1195 cx: &'a AppContext,
1196) -> Option<Cow<'a, Path>> {
1197 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1198 path_for_file(file.as_ref(), height, include_filename, cx)
1199}
1200
1201fn path_for_file<'a>(
1202 file: &'a dyn language::File,
1203 mut height: usize,
1204 include_filename: bool,
1205 cx: &'a AppContext,
1206) -> Option<Cow<'a, Path>> {
1207 // Ensure we always render at least the filename.
1208 height += 1;
1209
1210 let mut prefix = file.path().as_ref();
1211 while height > 0 {
1212 if let Some(parent) = prefix.parent() {
1213 prefix = parent;
1214 height -= 1;
1215 } else {
1216 break;
1217 }
1218 }
1219
1220 // Here we could have just always used `full_path`, but that is very
1221 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1222 // traversed all the way up to the worktree's root.
1223 if height > 0 {
1224 let full_path = file.full_path(cx);
1225 if include_filename {
1226 Some(full_path.into())
1227 } else {
1228 Some(full_path.parent()?.to_path_buf().into())
1229 }
1230 } else {
1231 let mut path = file.path().strip_prefix(prefix).ok()?;
1232 if !include_filename {
1233 path = path.parent()?;
1234 }
1235 Some(path.into())
1236 }
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241 use super::*;
1242 use gpui::AppContext;
1243 use std::{
1244 path::{Path, PathBuf},
1245 sync::Arc,
1246 time::SystemTime,
1247 };
1248
1249 #[gpui::test]
1250 fn test_path_for_file(cx: &mut AppContext) {
1251 let file = TestFile {
1252 path: Path::new("").into(),
1253 full_path: PathBuf::from(""),
1254 };
1255 assert_eq!(path_for_file(&file, 0, false, cx), None);
1256 }
1257
1258 struct TestFile {
1259 path: Arc<Path>,
1260 full_path: PathBuf,
1261 }
1262
1263 impl language::File for TestFile {
1264 fn path(&self) -> &Arc<Path> {
1265 &self.path
1266 }
1267
1268 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1269 self.full_path.clone()
1270 }
1271
1272 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1273 unimplemented!()
1274 }
1275
1276 fn mtime(&self) -> SystemTime {
1277 unimplemented!()
1278 }
1279
1280 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1281 unimplemented!()
1282 }
1283
1284 fn worktree_id(&self) -> usize {
1285 0
1286 }
1287
1288 fn is_deleted(&self) -> bool {
1289 unimplemented!()
1290 }
1291
1292 fn as_any(&self) -> &dyn std::any::Any {
1293 unimplemented!()
1294 }
1295
1296 fn to_proto(&self) -> rpc::proto::File {
1297 unimplemented!()
1298 }
1299 }
1300}