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