1use crate::{
2 editor_settings::SeedQuerySetting,
3 persistence::{SerializedEditor, DB},
4 scroll::ScrollAnchor,
5 Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, FormatTarget,
6 MultiBuffer, MultiBufferSnapshot, NavigationData, SearchWithinRange, ToPoint as _,
7};
8use anyhow::{anyhow, Context as _, Result};
9use collections::HashSet;
10use file_icons::FileIcons;
11use futures::future::try_join_all;
12use git::repository::GitFileStatus;
13use gpui::{
14 point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
15 IntoElement, Model, ParentElement, Pixels, SharedString, Styled, Task, View, ViewContext,
16 VisualContext, WeakView, WindowContext,
17};
18use language::{
19 proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, DiskState, Point,
20 SelectionGoal,
21};
22use lsp::DiagnosticSeverity;
23use multi_buffer::AnchorRangeExt;
24use project::{
25 lsp_store::FormatTrigger, project_settings::ProjectSettings, search::SearchQuery, Project,
26 ProjectItem as _, ProjectPath,
27};
28use rpc::proto::{self, update_view, PeerId};
29use settings::Settings;
30use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
31
32use std::{
33 any::TypeId,
34 borrow::Cow,
35 cmp::{self, Ordering},
36 iter,
37 ops::Range,
38 path::Path,
39 sync::Arc,
40};
41use text::{BufferId, Selection};
42use theme::{Theme, ThemeSettings};
43use ui::{h_flex, prelude::*, IconDecorationKind, Label};
44use util::{paths::PathExt, ResultExt, TryFutureExt};
45use workspace::item::{BreadcrumbText, FollowEvent};
46use workspace::{
47 item::{FollowableItem, Item, ItemEvent, ProjectItem},
48 searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
49 ItemId, ItemNavHistory, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
50};
51
52pub const MAX_TAB_TITLE_LEN: usize = 24;
53
54impl FollowableItem for Editor {
55 fn remote_id(&self) -> Option<ViewId> {
56 self.remote_id
57 }
58
59 fn from_state_proto(
60 workspace: View<Workspace>,
61 remote_id: ViewId,
62 state: &mut Option<proto::view::Variant>,
63 cx: &mut WindowContext,
64 ) -> Option<Task<Result<View<Self>>>> {
65 let project = workspace.read(cx).project().to_owned();
66 let Some(proto::view::Variant::Editor(_)) = state else {
67 return None;
68 };
69 let Some(proto::view::Variant::Editor(state)) = state.take() else {
70 unreachable!()
71 };
72
73 let buffer_ids = state
74 .excerpts
75 .iter()
76 .map(|excerpt| excerpt.buffer_id)
77 .collect::<HashSet<_>>();
78 let buffers = project.update(cx, |project, cx| {
79 buffer_ids
80 .iter()
81 .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
82 .collect::<Result<Vec<_>>>()
83 });
84
85 Some(cx.spawn(|mut cx| async move {
86 let mut buffers = futures::future::try_join_all(buffers?)
87 .await
88 .debug_assert_ok("leaders don't share views for unshared buffers")?;
89
90 let editor = cx.update(|cx| {
91 let multibuffer = cx.new_model(|cx| {
92 let mut multibuffer;
93 if state.singleton && buffers.len() == 1 {
94 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
95 } else {
96 multibuffer = MultiBuffer::new(project.read(cx).capability());
97 let mut excerpts = state.excerpts.into_iter().peekable();
98 while let Some(excerpt) = excerpts.peek() {
99 let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
100 continue;
101 };
102 let buffer_excerpts = iter::from_fn(|| {
103 let excerpt = excerpts.peek()?;
104 (excerpt.buffer_id == u64::from(buffer_id))
105 .then(|| excerpts.next().unwrap())
106 });
107 let buffer =
108 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
109 if let Some(buffer) = buffer {
110 multibuffer.push_excerpts(
111 buffer.clone(),
112 buffer_excerpts.filter_map(deserialize_excerpt_range),
113 cx,
114 );
115 }
116 }
117 };
118
119 if let Some(title) = &state.title {
120 multibuffer = multibuffer.with_title(title.clone())
121 }
122
123 multibuffer
124 });
125
126 cx.new_view(|cx| {
127 let mut editor =
128 Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx);
129 editor.remote_id = Some(remote_id);
130 editor
131 })
132 })?;
133
134 update_editor_from_message(
135 editor.downgrade(),
136 project,
137 proto::update_view::Editor {
138 selections: state.selections,
139 pending_selection: state.pending_selection,
140 scroll_top_anchor: state.scroll_top_anchor,
141 scroll_x: state.scroll_x,
142 scroll_y: state.scroll_y,
143 ..Default::default()
144 },
145 &mut cx,
146 )
147 .await?;
148
149 Ok(editor)
150 }))
151 }
152
153 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
154 self.leader_peer_id = leader_peer_id;
155 if self.leader_peer_id.is_some() {
156 self.buffer.update(cx, |buffer, cx| {
157 buffer.remove_active_selections(cx);
158 });
159 } else if self.focus_handle.is_focused(cx) {
160 self.buffer.update(cx, |buffer, cx| {
161 buffer.set_active_selections(
162 &self.selections.disjoint_anchors(),
163 self.selections.line_mode,
164 self.cursor_shape,
165 cx,
166 );
167 });
168 }
169 cx.notify();
170 }
171
172 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
173 let buffer = self.buffer.read(cx);
174 if buffer
175 .as_singleton()
176 .and_then(|buffer| buffer.read(cx).file())
177 .map_or(false, |file| file.is_private())
178 {
179 return None;
180 }
181
182 let scroll_anchor = self.scroll_manager.anchor();
183 let excerpts = buffer
184 .read(cx)
185 .excerpts()
186 .map(|(id, buffer, range)| proto::Excerpt {
187 id: id.to_proto(),
188 buffer_id: buffer.remote_id().into(),
189 context_start: Some(serialize_text_anchor(&range.context.start)),
190 context_end: Some(serialize_text_anchor(&range.context.end)),
191 primary_start: range
192 .primary
193 .as_ref()
194 .map(|range| serialize_text_anchor(&range.start)),
195 primary_end: range
196 .primary
197 .as_ref()
198 .map(|range| serialize_text_anchor(&range.end)),
199 })
200 .collect();
201
202 Some(proto::view::Variant::Editor(proto::view::Editor {
203 singleton: buffer.is_singleton(),
204 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
205 excerpts,
206 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
207 scroll_x: scroll_anchor.offset.x,
208 scroll_y: scroll_anchor.offset.y,
209 selections: self
210 .selections
211 .disjoint_anchors()
212 .iter()
213 .map(serialize_selection)
214 .collect(),
215 pending_selection: self
216 .selections
217 .pending_anchor()
218 .as_ref()
219 .map(serialize_selection),
220 }))
221 }
222
223 fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
224 match event {
225 EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
226 EditorEvent::SelectionsChanged { local }
227 | EditorEvent::ScrollPositionChanged { local, .. } => {
228 if *local {
229 Some(FollowEvent::Unfollow)
230 } else {
231 None
232 }
233 }
234 _ => None,
235 }
236 }
237
238 fn add_event_to_update_proto(
239 &self,
240 event: &EditorEvent,
241 update: &mut Option<proto::update_view::Variant>,
242 cx: &WindowContext,
243 ) -> bool {
244 let update =
245 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
246
247 match update {
248 proto::update_view::Variant::Editor(update) => match event {
249 EditorEvent::ExcerptsAdded {
250 buffer,
251 predecessor,
252 excerpts,
253 } => {
254 let buffer_id = buffer.read(cx).remote_id();
255 let mut excerpts = excerpts.iter();
256 if let Some((id, range)) = excerpts.next() {
257 update.inserted_excerpts.push(proto::ExcerptInsertion {
258 previous_excerpt_id: Some(predecessor.to_proto()),
259 excerpt: serialize_excerpt(buffer_id, id, range),
260 });
261 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
262 proto::ExcerptInsertion {
263 previous_excerpt_id: None,
264 excerpt: serialize_excerpt(buffer_id, id, range),
265 }
266 }))
267 }
268 true
269 }
270 EditorEvent::ExcerptsRemoved { ids } => {
271 update
272 .deleted_excerpts
273 .extend(ids.iter().map(ExcerptId::to_proto));
274 true
275 }
276 EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
277 let scroll_anchor = self.scroll_manager.anchor();
278 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
279 update.scroll_x = scroll_anchor.offset.x;
280 update.scroll_y = scroll_anchor.offset.y;
281 true
282 }
283 EditorEvent::SelectionsChanged { .. } => {
284 update.selections = self
285 .selections
286 .disjoint_anchors()
287 .iter()
288 .map(serialize_selection)
289 .collect();
290 update.pending_selection = self
291 .selections
292 .pending_anchor()
293 .as_ref()
294 .map(serialize_selection);
295 true
296 }
297 _ => false,
298 },
299 }
300 }
301
302 fn apply_update_proto(
303 &mut self,
304 project: &Model<Project>,
305 message: update_view::Variant,
306 cx: &mut ViewContext<Self>,
307 ) -> Task<Result<()>> {
308 let update_view::Variant::Editor(message) = message;
309 let project = project.clone();
310 cx.spawn(|this, mut cx| async move {
311 update_editor_from_message(this, project, message, &mut cx).await
312 })
313 }
314
315 fn is_project_item(&self, _cx: &WindowContext) -> bool {
316 true
317 }
318
319 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup> {
320 let self_singleton = self.buffer.read(cx).as_singleton()?;
321 let other_singleton = existing.buffer.read(cx).as_singleton()?;
322 if self_singleton == other_singleton {
323 Some(Dedup::KeepExisting)
324 } else {
325 None
326 }
327 }
328}
329
330async fn update_editor_from_message(
331 this: WeakView<Editor>,
332 project: Model<Project>,
333 message: proto::update_view::Editor,
334 cx: &mut AsyncWindowContext,
335) -> Result<()> {
336 // Open all of the buffers of which excerpts were added to the editor.
337 let inserted_excerpt_buffer_ids = message
338 .inserted_excerpts
339 .iter()
340 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
341 .collect::<HashSet<_>>();
342 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
343 inserted_excerpt_buffer_ids
344 .into_iter()
345 .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
346 .collect::<Result<Vec<_>>>()
347 })??;
348 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
349
350 // Update the editor's excerpts.
351 this.update(cx, |editor, cx| {
352 editor.buffer.update(cx, |multibuffer, cx| {
353 let mut removed_excerpt_ids = message
354 .deleted_excerpts
355 .into_iter()
356 .map(ExcerptId::from_proto)
357 .collect::<Vec<_>>();
358 removed_excerpt_ids.sort_by({
359 let multibuffer = multibuffer.read(cx);
360 move |a, b| a.cmp(b, &multibuffer)
361 });
362
363 let mut insertions = message.inserted_excerpts.into_iter().peekable();
364 while let Some(insertion) = insertions.next() {
365 let Some(excerpt) = insertion.excerpt else {
366 continue;
367 };
368 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
369 continue;
370 };
371 let buffer_id = BufferId::new(excerpt.buffer_id)?;
372 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
373 continue;
374 };
375
376 let adjacent_excerpts = iter::from_fn(|| {
377 let insertion = insertions.peek()?;
378 if insertion.previous_excerpt_id.is_none()
379 && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
380 {
381 insertions.next()?.excerpt
382 } else {
383 None
384 }
385 });
386
387 multibuffer.insert_excerpts_with_ids_after(
388 ExcerptId::from_proto(previous_excerpt_id),
389 buffer,
390 [excerpt]
391 .into_iter()
392 .chain(adjacent_excerpts)
393 .filter_map(|excerpt| {
394 Some((
395 ExcerptId::from_proto(excerpt.id),
396 deserialize_excerpt_range(excerpt)?,
397 ))
398 }),
399 cx,
400 );
401 }
402
403 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
404 Result::<(), anyhow::Error>::Ok(())
405 })
406 })??;
407
408 // Deserialize the editor state.
409 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
410 let buffer = editor.buffer.read(cx).read(cx);
411 let selections = message
412 .selections
413 .into_iter()
414 .filter_map(|selection| deserialize_selection(&buffer, selection))
415 .collect::<Vec<_>>();
416 let pending_selection = message
417 .pending_selection
418 .and_then(|selection| deserialize_selection(&buffer, selection));
419 let scroll_top_anchor = message
420 .scroll_top_anchor
421 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
422 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
423 })??;
424
425 // Wait until the buffer has received all of the operations referenced by
426 // the editor's new state.
427 this.update(cx, |editor, cx| {
428 editor.buffer.update(cx, |buffer, cx| {
429 buffer.wait_for_anchors(
430 selections
431 .iter()
432 .chain(pending_selection.as_ref())
433 .flat_map(|selection| [selection.start, selection.end])
434 .chain(scroll_top_anchor),
435 cx,
436 )
437 })
438 })?
439 .await?;
440
441 // Update the editor's state.
442 this.update(cx, |editor, cx| {
443 if !selections.is_empty() || pending_selection.is_some() {
444 editor.set_selections_from_remote(selections, pending_selection, cx);
445 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
446 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
447 editor.set_scroll_anchor_remote(
448 ScrollAnchor {
449 anchor: scroll_top_anchor,
450 offset: point(message.scroll_x, message.scroll_y),
451 },
452 cx,
453 );
454 }
455 })?;
456 Ok(())
457}
458
459fn serialize_excerpt(
460 buffer_id: BufferId,
461 id: &ExcerptId,
462 range: &ExcerptRange<language::Anchor>,
463) -> Option<proto::Excerpt> {
464 Some(proto::Excerpt {
465 id: id.to_proto(),
466 buffer_id: buffer_id.into(),
467 context_start: Some(serialize_text_anchor(&range.context.start)),
468 context_end: Some(serialize_text_anchor(&range.context.end)),
469 primary_start: range
470 .primary
471 .as_ref()
472 .map(|r| serialize_text_anchor(&r.start)),
473 primary_end: range
474 .primary
475 .as_ref()
476 .map(|r| serialize_text_anchor(&r.end)),
477 })
478}
479
480fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
481 proto::Selection {
482 id: selection.id as u64,
483 start: Some(serialize_anchor(&selection.start)),
484 end: Some(serialize_anchor(&selection.end)),
485 reversed: selection.reversed,
486 }
487}
488
489fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
490 proto::EditorAnchor {
491 excerpt_id: anchor.excerpt_id.to_proto(),
492 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
493 }
494}
495
496fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
497 let context = {
498 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
499 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
500 start..end
501 };
502 let primary = excerpt
503 .primary_start
504 .zip(excerpt.primary_end)
505 .and_then(|(start, end)| {
506 let start = language::proto::deserialize_anchor(start)?;
507 let end = language::proto::deserialize_anchor(end)?;
508 Some(start..end)
509 });
510 Some(ExcerptRange { context, primary })
511}
512
513fn deserialize_selection(
514 buffer: &MultiBufferSnapshot,
515 selection: proto::Selection,
516) -> Option<Selection<Anchor>> {
517 Some(Selection {
518 id: selection.id as usize,
519 start: deserialize_anchor(buffer, selection.start?)?,
520 end: deserialize_anchor(buffer, selection.end?)?,
521 reversed: selection.reversed,
522 goal: SelectionGoal::None,
523 })
524}
525
526fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
527 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
528 Some(Anchor {
529 excerpt_id,
530 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
531 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
532 })
533}
534
535impl Item for Editor {
536 type Event = EditorEvent;
537
538 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
539 if let Ok(data) = data.downcast::<NavigationData>() {
540 let newest_selection = self.selections.newest::<Point>(cx);
541 let buffer = self.buffer.read(cx).read(cx);
542 let offset = if buffer.can_resolve(&data.cursor_anchor) {
543 data.cursor_anchor.to_point(&buffer)
544 } else {
545 buffer.clip_point(data.cursor_position, Bias::Left)
546 };
547
548 let mut scroll_anchor = data.scroll_anchor;
549 if !buffer.can_resolve(&scroll_anchor.anchor) {
550 scroll_anchor.anchor = buffer.anchor_before(
551 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
552 );
553 }
554
555 drop(buffer);
556
557 if newest_selection.head() == offset {
558 false
559 } else {
560 let nav_history = self.nav_history.take();
561 self.set_scroll_anchor(scroll_anchor, cx);
562 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
563 s.select_ranges([offset..offset])
564 });
565 self.nav_history = nav_history;
566 true
567 }
568 } else {
569 false
570 }
571 }
572
573 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
574 let file_path = self
575 .buffer()
576 .read(cx)
577 .as_singleton()?
578 .read(cx)
579 .file()
580 .and_then(|f| f.as_local())?
581 .abs_path(cx);
582
583 let file_path = file_path.compact().to_string_lossy().to_string();
584
585 Some(file_path.into())
586 }
587
588 fn telemetry_event_text(&self) -> Option<&'static str> {
589 None
590 }
591
592 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
593 let path = path_for_buffer(&self.buffer, detail, true, cx)?;
594 Some(path.to_string_lossy().to_string().into())
595 }
596
597 fn tab_icon(&self, cx: &WindowContext) -> Option<Icon> {
598 ItemSettings::get_global(cx)
599 .file_icons
600 .then(|| {
601 self.buffer
602 .read(cx)
603 .as_singleton()
604 .and_then(|buffer| buffer.read(cx).project_path(cx))
605 .and_then(|path| FileIcons::get_icon(path.path.as_ref(), cx))
606 })
607 .flatten()
608 .map(Icon::from_path)
609 }
610
611 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
612 let label_color = if ItemSettings::get_global(cx).git_status {
613 self.buffer()
614 .read(cx)
615 .as_singleton()
616 .and_then(|buffer| buffer.read(cx).project_path(cx))
617 .and_then(|path| {
618 let project = self.project.as_ref()?.read(cx);
619 let entry = project.entry_for_path(&path, cx)?;
620 let git_status = project
621 .worktree_for_id(path.worktree_id, cx)?
622 .read(cx)
623 .snapshot()
624 .status_for_file(path.path);
625
626 Some(entry_git_aware_label_color(
627 git_status,
628 entry.is_ignored,
629 params.selected,
630 ))
631 })
632 .unwrap_or_else(|| entry_label_color(params.selected))
633 } else {
634 entry_label_color(params.selected)
635 };
636
637 let description = params.detail.and_then(|detail| {
638 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
639 let description = path.to_string_lossy();
640 let description = description.trim();
641
642 if description.is_empty() {
643 return None;
644 }
645
646 Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
647 });
648
649 // Whether the file was saved in the past but is now deleted.
650 let was_deleted: bool = self
651 .buffer()
652 .read(cx)
653 .as_singleton()
654 .and_then(|buffer| buffer.read(cx).file())
655 .map_or(false, |file| file.disk_state() == DiskState::Deleted);
656
657 h_flex()
658 .gap_2()
659 .child(
660 Label::new(self.title(cx).to_string())
661 .color(label_color)
662 .italic(params.preview)
663 .strikethrough(was_deleted),
664 )
665 .when_some(description, |this, description| {
666 this.child(
667 Label::new(description)
668 .size(LabelSize::XSmall)
669 .color(Color::Muted),
670 )
671 })
672 .into_any_element()
673 }
674
675 fn for_each_project_item(
676 &self,
677 cx: &AppContext,
678 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
679 ) {
680 self.buffer
681 .read(cx)
682 .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
683 }
684
685 fn is_singleton(&self, cx: &AppContext) -> bool {
686 self.buffer.read(cx).is_singleton()
687 }
688
689 fn clone_on_split(
690 &self,
691 _workspace_id: Option<WorkspaceId>,
692 cx: &mut ViewContext<Self>,
693 ) -> Option<View<Editor>>
694 where
695 Self: Sized,
696 {
697 Some(cx.new_view(|cx| self.clone(cx)))
698 }
699
700 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
701 self.nav_history = Some(history);
702 }
703
704 fn discarded(&self, _project: Model<Project>, cx: &mut ViewContext<Self>) {
705 for buffer in self.buffer().clone().read(cx).all_buffers() {
706 buffer.update(cx, |buffer, cx| buffer.discarded(cx))
707 }
708 }
709
710 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
711 let selection = self.selections.newest_anchor();
712 self.push_to_nav_history(selection.head(), None, cx);
713 }
714
715 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
716 self.hide_hovered_link(cx);
717 }
718
719 fn is_dirty(&self, cx: &AppContext) -> bool {
720 self.buffer().read(cx).read(cx).is_dirty()
721 }
722
723 fn has_deleted_file(&self, cx: &AppContext) -> bool {
724 self.buffer().read(cx).read(cx).has_deleted_file()
725 }
726
727 fn has_conflict(&self, cx: &AppContext) -> bool {
728 self.buffer().read(cx).read(cx).has_conflict()
729 }
730
731 fn can_save(&self, cx: &AppContext) -> bool {
732 let buffer = &self.buffer().read(cx);
733 if let Some(buffer) = buffer.as_singleton() {
734 buffer.read(cx).project_path(cx).is_some()
735 } else {
736 true
737 }
738 }
739
740 fn save(
741 &mut self,
742 format: bool,
743 project: Model<Project>,
744 cx: &mut ViewContext<Self>,
745 ) -> Task<Result<()>> {
746 self.report_editor_event("Editor Saved", None, cx);
747 let buffers = self.buffer().clone().read(cx).all_buffers();
748 let buffers = buffers
749 .into_iter()
750 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
751 .collect::<HashSet<_>>();
752 cx.spawn(|this, mut cx| async move {
753 if format {
754 this.update(&mut cx, |editor, cx| {
755 editor.perform_format(
756 project.clone(),
757 FormatTrigger::Save,
758 FormatTarget::Buffers,
759 cx,
760 )
761 })?
762 .await?;
763 }
764
765 if buffers.len() == 1 {
766 // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
767 project
768 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
769 .await?;
770 } else {
771 // For multi-buffers, only format and save the buffers with changes.
772 // For clean buffers, we simulate saving by calling `Buffer::did_save`,
773 // so that language servers or other downstream listeners of save events get notified.
774 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
775 buffer
776 .update(&mut cx, |buffer, _| {
777 buffer.is_dirty() || buffer.has_conflict()
778 })
779 .unwrap_or(false)
780 });
781
782 project
783 .update(&mut cx, |project, cx| {
784 project.save_buffers(dirty_buffers, cx)
785 })?
786 .await?;
787 for buffer in clean_buffers {
788 buffer
789 .update(&mut cx, |buffer, cx| {
790 let version = buffer.saved_version().clone();
791 let mtime = buffer.saved_mtime();
792 buffer.did_save(version, mtime, cx);
793 })
794 .ok();
795 }
796 }
797
798 Ok(())
799 })
800 }
801
802 fn save_as(
803 &mut self,
804 project: Model<Project>,
805 path: ProjectPath,
806 cx: &mut ViewContext<Self>,
807 ) -> Task<Result<()>> {
808 let buffer = self
809 .buffer()
810 .read(cx)
811 .as_singleton()
812 .expect("cannot call save_as on an excerpt list");
813
814 let file_extension = path
815 .path
816 .extension()
817 .map(|a| a.to_string_lossy().to_string());
818 self.report_editor_event("Editor Saved", file_extension, cx);
819
820 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
821 }
822
823 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
824 let buffer = self.buffer().clone();
825 let buffers = self.buffer.read(cx).all_buffers();
826 let reload_buffers =
827 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
828 cx.spawn(|this, mut cx| async move {
829 let transaction = reload_buffers.log_err().await;
830 this.update(&mut cx, |editor, cx| {
831 editor.request_autoscroll(Autoscroll::fit(), cx)
832 })?;
833 buffer
834 .update(&mut cx, |buffer, cx| {
835 if let Some(transaction) = transaction {
836 if !buffer.is_singleton() {
837 buffer.push_transaction(&transaction.0, cx);
838 }
839 }
840 })
841 .ok();
842 Ok(())
843 })
844 }
845
846 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
847 Some(Box::new(handle.clone()))
848 }
849
850 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
851 self.pixel_position_of_newest_cursor
852 }
853
854 fn breadcrumb_location(&self, _: &AppContext) -> ToolbarItemLocation {
855 if self.show_breadcrumbs {
856 ToolbarItemLocation::PrimaryLeft
857 } else {
858 ToolbarItemLocation::Hidden
859 }
860 }
861
862 fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
863 let cursor = self.selections.newest_anchor().head();
864 let multibuffer = &self.buffer().read(cx);
865 let (buffer_id, symbols) =
866 multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
867 let buffer = multibuffer.buffer(buffer_id)?;
868
869 let buffer = buffer.read(cx);
870 let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
871 buffer
872 .snapshot()
873 .resolve_file_path(
874 cx,
875 self.project
876 .as_ref()
877 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
878 .unwrap_or_default(),
879 )
880 .map(|path| path.to_string_lossy().to_string())
881 .unwrap_or_else(|| {
882 if multibuffer.is_singleton() {
883 multibuffer.title(cx).to_string()
884 } else {
885 "untitled".to_string()
886 }
887 })
888 });
889
890 let settings = ThemeSettings::get_global(cx);
891
892 let mut breadcrumbs = vec![BreadcrumbText {
893 text,
894 highlights: None,
895 font: Some(settings.buffer_font.clone()),
896 }];
897
898 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
899 text: symbol.text,
900 highlights: Some(symbol.highlight_ranges),
901 font: Some(settings.buffer_font.clone()),
902 }));
903 Some(breadcrumbs)
904 }
905
906 fn added_to_workspace(&mut self, workspace: &mut Workspace, _: &mut ViewContext<Self>) {
907 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
908 }
909
910 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
911 match event {
912 EditorEvent::Closed => f(ItemEvent::CloseItem),
913
914 EditorEvent::Saved | EditorEvent::TitleChanged => {
915 f(ItemEvent::UpdateTab);
916 f(ItemEvent::UpdateBreadcrumbs);
917 }
918
919 EditorEvent::Reparsed(_) => {
920 f(ItemEvent::UpdateBreadcrumbs);
921 }
922
923 EditorEvent::SelectionsChanged { local } if *local => {
924 f(ItemEvent::UpdateBreadcrumbs);
925 }
926
927 EditorEvent::DirtyChanged => {
928 f(ItemEvent::UpdateTab);
929 }
930
931 EditorEvent::BufferEdited => {
932 f(ItemEvent::Edit);
933 f(ItemEvent::UpdateBreadcrumbs);
934 }
935
936 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
937 f(ItemEvent::Edit);
938 }
939
940 _ => {}
941 }
942 }
943
944 fn preserve_preview(&self, cx: &AppContext) -> bool {
945 self.buffer.read(cx).preserve_preview(cx)
946 }
947}
948
949impl SerializableItem for Editor {
950 fn serialized_item_kind() -> &'static str {
951 "Editor"
952 }
953
954 fn cleanup(
955 workspace_id: WorkspaceId,
956 alive_items: Vec<ItemId>,
957 cx: &mut WindowContext,
958 ) -> Task<Result<()>> {
959 cx.spawn(|_| DB.delete_unloaded_items(workspace_id, alive_items))
960 }
961
962 fn deserialize(
963 project: Model<Project>,
964 workspace: WeakView<Workspace>,
965 workspace_id: workspace::WorkspaceId,
966 item_id: ItemId,
967 cx: &mut WindowContext,
968 ) -> Task<Result<View<Self>>> {
969 let serialized_editor = match DB
970 .get_serialized_editor(item_id, workspace_id)
971 .context("Failed to query editor state")
972 {
973 Ok(Some(serialized_editor)) => {
974 if ProjectSettings::get_global(cx)
975 .session
976 .restore_unsaved_buffers
977 {
978 serialized_editor
979 } else {
980 SerializedEditor {
981 abs_path: serialized_editor.abs_path,
982 contents: None,
983 language: None,
984 mtime: None,
985 }
986 }
987 }
988 Ok(None) => {
989 return Task::ready(Err(anyhow!("No path or contents found for buffer")));
990 }
991 Err(error) => {
992 return Task::ready(Err(error));
993 }
994 };
995
996 match serialized_editor {
997 SerializedEditor {
998 abs_path: None,
999 contents: Some(contents),
1000 language,
1001 ..
1002 } => cx.spawn(|mut cx| {
1003 let project = project.clone();
1004 async move {
1005 let language = if let Some(language_name) = language {
1006 let language_registry =
1007 project.update(&mut cx, |project, _| project.languages().clone())?;
1008
1009 // We don't fail here, because we'd rather not set the language if the name changed
1010 // than fail to restore the buffer.
1011 language_registry
1012 .language_for_name(&language_name)
1013 .await
1014 .ok()
1015 } else {
1016 None
1017 };
1018
1019 // First create the empty buffer
1020 let buffer = project
1021 .update(&mut cx, |project, cx| project.create_buffer(cx))?
1022 .await?;
1023
1024 // Then set the text so that the dirty bit is set correctly
1025 buffer.update(&mut cx, |buffer, cx| {
1026 if let Some(language) = language {
1027 buffer.set_language(Some(language), cx);
1028 }
1029 buffer.set_text(contents, cx);
1030 })?;
1031
1032 cx.update(|cx| {
1033 cx.new_view(|cx| {
1034 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
1035
1036 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1037 editor
1038 })
1039 })
1040 }
1041 }),
1042 SerializedEditor {
1043 abs_path: Some(abs_path),
1044 contents,
1045 mtime,
1046 ..
1047 } => {
1048 let project_item = project.update(cx, |project, cx| {
1049 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1050 let project_path = ProjectPath {
1051 worktree_id: worktree.read(cx).id(),
1052 path: path.into(),
1053 };
1054 Some(project.open_path(project_path, cx))
1055 });
1056
1057 match project_item {
1058 Some(project_item) => {
1059 cx.spawn(|mut cx| async move {
1060 let (_, project_item) = project_item.await?;
1061 let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1062 anyhow!("Project item at stored path was not a buffer")
1063 })?;
1064
1065 // This is a bit wasteful: we're loading the whole buffer from
1066 // disk and then overwrite the content.
1067 // But for now, it keeps the implementation of the content serialization
1068 // simple, because we don't have to persist all of the metadata that we get
1069 // by loading the file (git diff base, ...).
1070 if let Some(buffer_text) = contents {
1071 buffer.update(&mut cx, |buffer, cx| {
1072 // If we did restore an mtime, we want to store it on the buffer
1073 // so that the next edit will mark the buffer as dirty/conflicted.
1074 if mtime.is_some() {
1075 buffer.did_reload(
1076 buffer.version(),
1077 buffer.line_ending(),
1078 mtime,
1079 cx,
1080 );
1081 }
1082 buffer.set_text(buffer_text, cx);
1083 })?;
1084 }
1085
1086 cx.update(|cx| {
1087 cx.new_view(|cx| {
1088 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
1089
1090 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1091 editor
1092 })
1093 })
1094 })
1095 }
1096 None => {
1097 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1098 workspace.open_abs_path(abs_path.clone(), false, cx)
1099 });
1100 cx.spawn(|mut cx| async move {
1101 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1102 editor.update(&mut cx, |editor, cx| {
1103 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1104 })?;
1105 Ok(editor)
1106 })
1107 }
1108 }
1109 }
1110 SerializedEditor {
1111 abs_path: None,
1112 contents: None,
1113 ..
1114 } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1115 }
1116 }
1117
1118 fn serialize(
1119 &mut self,
1120 workspace: &mut Workspace,
1121 item_id: ItemId,
1122 closing: bool,
1123 cx: &mut ViewContext<Self>,
1124 ) -> Option<Task<Result<()>>> {
1125 let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1126
1127 let project = self.project.clone()?;
1128 if project.read(cx).visible_worktrees(cx).next().is_none() {
1129 // If we don't have a worktree, we don't serialize, because
1130 // projects without worktrees aren't deserialized.
1131 serialize_dirty_buffers = false;
1132 }
1133
1134 if closing && !serialize_dirty_buffers {
1135 return None;
1136 }
1137
1138 let workspace_id = workspace.database_id()?;
1139
1140 let buffer = self.buffer().read(cx).as_singleton()?;
1141
1142 let abs_path = buffer.read(cx).file().and_then(|file| {
1143 let worktree_id = file.worktree_id(cx);
1144 project
1145 .read(cx)
1146 .worktree_for_id(worktree_id, cx)
1147 .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1148 .or_else(|| {
1149 let full_path = file.full_path(cx);
1150 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1151 project.read(cx).absolute_path(&project_path, cx)
1152 })
1153 });
1154
1155 let is_dirty = buffer.read(cx).is_dirty();
1156 let mtime = buffer.read(cx).saved_mtime();
1157
1158 let snapshot = buffer.read(cx).snapshot();
1159
1160 Some(cx.spawn(|_this, cx| async move {
1161 cx.background_executor()
1162 .spawn(async move {
1163 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1164 let contents = snapshot.text();
1165 let language = snapshot.language().map(|lang| lang.name().to_string());
1166 (Some(contents), language)
1167 } else {
1168 (None, None)
1169 };
1170
1171 let editor = SerializedEditor {
1172 abs_path,
1173 contents,
1174 language,
1175 mtime,
1176 };
1177
1178 DB.save_serialized_editor(item_id, workspace_id, editor)
1179 .await
1180 .context("failed to save serialized editor")
1181 })
1182 .await
1183 .context("failed to save contents of buffer")?;
1184
1185 Ok(())
1186 }))
1187 }
1188
1189 fn should_serialize(&self, event: &Self::Event) -> bool {
1190 matches!(
1191 event,
1192 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1193 )
1194 }
1195}
1196
1197impl ProjectItem for Editor {
1198 type Item = Buffer;
1199
1200 fn for_project_item(
1201 project: Model<Project>,
1202 buffer: Model<Buffer>,
1203 cx: &mut ViewContext<Self>,
1204 ) -> Self {
1205 Self::for_buffer(buffer, Some(project), cx)
1206 }
1207}
1208
1209impl EventEmitter<SearchEvent> for Editor {}
1210
1211pub(crate) enum BufferSearchHighlights {}
1212impl SearchableItem for Editor {
1213 type Match = Range<Anchor>;
1214
1215 fn get_matches(&self, _: &mut WindowContext) -> Vec<Range<Anchor>> {
1216 self.background_highlights
1217 .get(&TypeId::of::<BufferSearchHighlights>())
1218 .map_or(Vec::new(), |(_color, ranges)| {
1219 ranges.iter().cloned().collect()
1220 })
1221 }
1222
1223 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1224 if self
1225 .clear_background_highlights::<BufferSearchHighlights>(cx)
1226 .is_some()
1227 {
1228 cx.emit(SearchEvent::MatchesInvalidated);
1229 }
1230 }
1231
1232 fn update_matches(&mut self, matches: &[Range<Anchor>], cx: &mut ViewContext<Self>) {
1233 let existing_range = self
1234 .background_highlights
1235 .get(&TypeId::of::<BufferSearchHighlights>())
1236 .map(|(_, range)| range.as_ref());
1237 let updated = existing_range != Some(matches);
1238 self.highlight_background::<BufferSearchHighlights>(
1239 matches,
1240 |theme| theme.search_match_background,
1241 cx,
1242 );
1243 if updated {
1244 cx.emit(SearchEvent::MatchesInvalidated);
1245 }
1246 }
1247
1248 fn has_filtered_search_ranges(&mut self) -> bool {
1249 self.has_background_highlights::<SearchWithinRange>()
1250 }
1251
1252 fn toggle_filtered_search_ranges(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1253 if self.has_filtered_search_ranges() {
1254 self.previous_search_ranges = self
1255 .clear_background_highlights::<SearchWithinRange>(cx)
1256 .map(|(_, ranges)| ranges)
1257 }
1258
1259 if !enabled {
1260 return;
1261 }
1262
1263 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1264 if ranges.iter().any(|s| s.start != s.end) {
1265 self.set_search_within_ranges(&ranges, cx);
1266 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1267 self.set_search_within_ranges(&previous_search_ranges, cx)
1268 }
1269 }
1270
1271 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1272 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1273 let snapshot = &self.snapshot(cx).buffer_snapshot;
1274 let selection = self.selections.newest::<usize>(cx);
1275
1276 match setting {
1277 SeedQuerySetting::Never => String::new(),
1278 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1279 let text: String = snapshot
1280 .text_for_range(selection.start..selection.end)
1281 .collect();
1282 if text.contains('\n') {
1283 String::new()
1284 } else {
1285 text
1286 }
1287 }
1288 SeedQuerySetting::Selection => String::new(),
1289 SeedQuerySetting::Always => {
1290 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1291 if kind == Some(CharKind::Word) {
1292 let text: String = snapshot.text_for_range(range).collect();
1293 if !text.trim().is_empty() {
1294 return text;
1295 }
1296 }
1297 String::new()
1298 }
1299 }
1300 }
1301
1302 fn activate_match(
1303 &mut self,
1304 index: usize,
1305 matches: &[Range<Anchor>],
1306 cx: &mut ViewContext<Self>,
1307 ) {
1308 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1309 let range = self.range_for_match(&matches[index]);
1310 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1311 s.select_ranges([range]);
1312 })
1313 }
1314
1315 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1316 self.unfold_ranges(matches, false, false, cx);
1317 let mut ranges = Vec::new();
1318 for m in matches {
1319 ranges.push(self.range_for_match(m))
1320 }
1321 self.change_selections(None, cx, |s| s.select_ranges(ranges));
1322 }
1323 fn replace(
1324 &mut self,
1325 identifier: &Self::Match,
1326 query: &SearchQuery,
1327 cx: &mut ViewContext<Self>,
1328 ) {
1329 let text = self.buffer.read(cx);
1330 let text = text.snapshot(cx);
1331 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1332 let text: Cow<_> = if text.len() == 1 {
1333 text.first().cloned().unwrap().into()
1334 } else {
1335 let joined_chunks = text.join("");
1336 joined_chunks.into()
1337 };
1338
1339 if let Some(replacement) = query.replacement_for(&text) {
1340 self.transact(cx, |this, cx| {
1341 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1342 });
1343 }
1344 }
1345 fn replace_all(
1346 &mut self,
1347 matches: &mut dyn Iterator<Item = &Self::Match>,
1348 query: &SearchQuery,
1349 cx: &mut ViewContext<Self>,
1350 ) {
1351 let text = self.buffer.read(cx);
1352 let text = text.snapshot(cx);
1353 let mut edits = vec![];
1354 for m in matches {
1355 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1356 let text: Cow<_> = if text.len() == 1 {
1357 text.first().cloned().unwrap().into()
1358 } else {
1359 let joined_chunks = text.join("");
1360 joined_chunks.into()
1361 };
1362
1363 if let Some(replacement) = query.replacement_for(&text) {
1364 edits.push((m.clone(), Arc::from(&*replacement)));
1365 }
1366 }
1367
1368 if !edits.is_empty() {
1369 self.transact(cx, |this, cx| {
1370 this.edit(edits, cx);
1371 });
1372 }
1373 }
1374 fn match_index_for_direction(
1375 &mut self,
1376 matches: &[Range<Anchor>],
1377 current_index: usize,
1378 direction: Direction,
1379 count: usize,
1380 cx: &mut ViewContext<Self>,
1381 ) -> usize {
1382 let buffer = self.buffer().read(cx).snapshot(cx);
1383 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1384 self.selections.newest_anchor().head()
1385 } else {
1386 matches[current_index].start
1387 };
1388
1389 let mut count = count % matches.len();
1390 if count == 0 {
1391 return current_index;
1392 }
1393 match direction {
1394 Direction::Next => {
1395 if matches[current_index]
1396 .start
1397 .cmp(¤t_index_position, &buffer)
1398 .is_gt()
1399 {
1400 count -= 1
1401 }
1402
1403 (current_index + count) % matches.len()
1404 }
1405 Direction::Prev => {
1406 if matches[current_index]
1407 .end
1408 .cmp(¤t_index_position, &buffer)
1409 .is_lt()
1410 {
1411 count -= 1;
1412 }
1413
1414 if current_index >= count {
1415 current_index - count
1416 } else {
1417 matches.len() - (count - current_index)
1418 }
1419 }
1420 }
1421 }
1422
1423 fn find_matches(
1424 &mut self,
1425 query: Arc<project::search::SearchQuery>,
1426 cx: &mut ViewContext<Self>,
1427 ) -> Task<Vec<Range<Anchor>>> {
1428 let buffer = self.buffer().read(cx).snapshot(cx);
1429 let search_within_ranges = self
1430 .background_highlights
1431 .get(&TypeId::of::<SearchWithinRange>())
1432 .map_or(vec![], |(_color, ranges)| {
1433 ranges.iter().cloned().collect::<Vec<_>>()
1434 });
1435
1436 cx.background_executor().spawn(async move {
1437 let mut ranges = Vec::new();
1438
1439 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1440 let search_within_ranges = if search_within_ranges.is_empty() {
1441 vec![None]
1442 } else {
1443 search_within_ranges
1444 .into_iter()
1445 .map(|range| Some(range.to_offset(&buffer)))
1446 .collect::<Vec<_>>()
1447 };
1448
1449 for range in search_within_ranges {
1450 let buffer = &buffer;
1451 ranges.extend(
1452 query
1453 .search(excerpt_buffer, range.clone())
1454 .await
1455 .into_iter()
1456 .map(|matched_range| {
1457 let offset = range.clone().map(|r| r.start).unwrap_or(0);
1458 buffer.anchor_after(matched_range.start + offset)
1459 ..buffer.anchor_before(matched_range.end + offset)
1460 }),
1461 );
1462 }
1463 } else {
1464 let search_within_ranges = if search_within_ranges.is_empty() {
1465 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1466 } else {
1467 search_within_ranges
1468 };
1469
1470 for (excerpt_id, search_buffer, search_range) in
1471 buffer.excerpts_in_ranges(search_within_ranges)
1472 {
1473 if !search_range.is_empty() {
1474 ranges.extend(
1475 query
1476 .search(search_buffer, Some(search_range.clone()))
1477 .await
1478 .into_iter()
1479 .map(|match_range| {
1480 let start = search_buffer
1481 .anchor_after(search_range.start + match_range.start);
1482 let end = search_buffer
1483 .anchor_before(search_range.start + match_range.end);
1484 buffer.anchor_in_excerpt(excerpt_id, start).unwrap()
1485 ..buffer.anchor_in_excerpt(excerpt_id, end).unwrap()
1486 }),
1487 );
1488 }
1489 }
1490 };
1491
1492 ranges
1493 })
1494 }
1495
1496 fn active_match_index(
1497 &mut self,
1498 matches: &[Range<Anchor>],
1499 cx: &mut ViewContext<Self>,
1500 ) -> Option<usize> {
1501 active_match_index(
1502 matches,
1503 &self.selections.newest_anchor().head(),
1504 &self.buffer().read(cx).snapshot(cx),
1505 )
1506 }
1507
1508 fn search_bar_visibility_changed(&mut self, _visible: bool, _cx: &mut ViewContext<Self>) {
1509 self.expect_bounds_change = self.last_bounds;
1510 }
1511}
1512
1513pub fn active_match_index(
1514 ranges: &[Range<Anchor>],
1515 cursor: &Anchor,
1516 buffer: &MultiBufferSnapshot,
1517) -> Option<usize> {
1518 if ranges.is_empty() {
1519 None
1520 } else {
1521 match ranges.binary_search_by(|probe| {
1522 if probe.end.cmp(cursor, buffer).is_lt() {
1523 Ordering::Less
1524 } else if probe.start.cmp(cursor, buffer).is_gt() {
1525 Ordering::Greater
1526 } else {
1527 Ordering::Equal
1528 }
1529 }) {
1530 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1531 }
1532 }
1533}
1534
1535pub fn entry_label_color(selected: bool) -> Color {
1536 if selected {
1537 Color::Default
1538 } else {
1539 Color::Muted
1540 }
1541}
1542
1543pub fn entry_diagnostic_aware_icon_name_and_color(
1544 diagnostic_severity: Option<DiagnosticSeverity>,
1545) -> Option<(IconName, Color)> {
1546 match diagnostic_severity {
1547 Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1548 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1549 _ => None,
1550 }
1551}
1552
1553pub fn entry_diagnostic_aware_icon_decoration_and_color(
1554 diagnostic_severity: Option<DiagnosticSeverity>,
1555) -> Option<(IconDecorationKind, Color)> {
1556 match diagnostic_severity {
1557 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1558 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1559 _ => None,
1560 }
1561}
1562
1563pub fn entry_git_aware_label_color(
1564 git_status: Option<GitFileStatus>,
1565 ignored: bool,
1566 selected: bool,
1567) -> Color {
1568 if ignored {
1569 Color::Ignored
1570 } else {
1571 match git_status {
1572 Some(GitFileStatus::Added) | Some(GitFileStatus::Untracked) => Color::Created,
1573 Some(GitFileStatus::Modified) => Color::Modified,
1574 Some(GitFileStatus::Conflict) => Color::Conflict,
1575 Some(GitFileStatus::Deleted) | None => entry_label_color(selected),
1576 }
1577 }
1578}
1579
1580fn path_for_buffer<'a>(
1581 buffer: &Model<MultiBuffer>,
1582 height: usize,
1583 include_filename: bool,
1584 cx: &'a AppContext,
1585) -> Option<Cow<'a, Path>> {
1586 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1587 path_for_file(file.as_ref(), height, include_filename, cx)
1588}
1589
1590fn path_for_file<'a>(
1591 file: &'a dyn language::File,
1592 mut height: usize,
1593 include_filename: bool,
1594 cx: &'a AppContext,
1595) -> Option<Cow<'a, Path>> {
1596 // Ensure we always render at least the filename.
1597 height += 1;
1598
1599 let mut prefix = file.path().as_ref();
1600 while height > 0 {
1601 if let Some(parent) = prefix.parent() {
1602 prefix = parent;
1603 height -= 1;
1604 } else {
1605 break;
1606 }
1607 }
1608
1609 // Here we could have just always used `full_path`, but that is very
1610 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1611 // traversed all the way up to the worktree's root.
1612 if height > 0 {
1613 let full_path = file.full_path(cx);
1614 if include_filename {
1615 Some(full_path.into())
1616 } else {
1617 Some(full_path.parent()?.to_path_buf().into())
1618 }
1619 } else {
1620 let mut path = file.path().strip_prefix(prefix).ok()?;
1621 if !include_filename {
1622 path = path.parent()?;
1623 }
1624 Some(path.into())
1625 }
1626}
1627
1628#[cfg(test)]
1629mod tests {
1630 use crate::editor_tests::init_test;
1631 use fs::Fs;
1632
1633 use super::*;
1634 use fs::MTime;
1635 use gpui::{AppContext, VisualTestContext};
1636 use language::{LanguageMatcher, TestFile};
1637 use project::FakeFs;
1638 use std::path::{Path, PathBuf};
1639
1640 #[gpui::test]
1641 fn test_path_for_file(cx: &mut AppContext) {
1642 let file = TestFile {
1643 path: Path::new("").into(),
1644 root_name: String::new(),
1645 };
1646 assert_eq!(path_for_file(&file, 0, false, cx), None);
1647 }
1648
1649 async fn deserialize_editor(
1650 item_id: ItemId,
1651 workspace_id: WorkspaceId,
1652 workspace: View<Workspace>,
1653 project: Model<Project>,
1654 cx: &mut VisualTestContext,
1655 ) -> View<Editor> {
1656 workspace
1657 .update(cx, |workspace, cx| {
1658 let pane = workspace.active_pane();
1659 pane.update(cx, |_, cx| {
1660 Editor::deserialize(
1661 project.clone(),
1662 workspace.weak_handle(),
1663 workspace_id,
1664 item_id,
1665 cx,
1666 )
1667 })
1668 })
1669 .await
1670 .unwrap()
1671 }
1672
1673 fn rust_language() -> Arc<language::Language> {
1674 Arc::new(language::Language::new(
1675 language::LanguageConfig {
1676 name: "Rust".into(),
1677 matcher: LanguageMatcher {
1678 path_suffixes: vec!["rs".to_string()],
1679 ..Default::default()
1680 },
1681 ..Default::default()
1682 },
1683 Some(tree_sitter_rust::LANGUAGE.into()),
1684 ))
1685 }
1686
1687 #[gpui::test]
1688 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1689 init_test(cx, |_| {});
1690
1691 let fs = FakeFs::new(cx.executor());
1692 fs.insert_file("/file.rs", Default::default()).await;
1693
1694 // Test case 1: Deserialize with path and contents
1695 {
1696 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1697 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1698 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1699 let item_id = 1234 as ItemId;
1700 let mtime = fs
1701 .metadata(Path::new("/file.rs"))
1702 .await
1703 .unwrap()
1704 .unwrap()
1705 .mtime;
1706
1707 let serialized_editor = SerializedEditor {
1708 abs_path: Some(PathBuf::from("/file.rs")),
1709 contents: Some("fn main() {}".to_string()),
1710 language: Some("Rust".to_string()),
1711 mtime: Some(mtime),
1712 };
1713
1714 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1715 .await
1716 .unwrap();
1717
1718 let deserialized =
1719 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1720
1721 deserialized.update(cx, |editor, cx| {
1722 assert_eq!(editor.text(cx), "fn main() {}");
1723 assert!(editor.is_dirty(cx));
1724 assert!(!editor.has_conflict(cx));
1725 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1726 assert!(buffer.file().is_some());
1727 });
1728 }
1729
1730 // Test case 2: Deserialize with only path
1731 {
1732 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1733 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1734
1735 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1736
1737 let item_id = 5678 as ItemId;
1738 let serialized_editor = SerializedEditor {
1739 abs_path: Some(PathBuf::from("/file.rs")),
1740 contents: None,
1741 language: None,
1742 mtime: None,
1743 };
1744
1745 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1746 .await
1747 .unwrap();
1748
1749 let deserialized =
1750 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1751
1752 deserialized.update(cx, |editor, cx| {
1753 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1754 assert!(!editor.is_dirty(cx));
1755 assert!(!editor.has_conflict(cx));
1756
1757 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1758 assert!(buffer.file().is_some());
1759 });
1760 }
1761
1762 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1763 {
1764 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1765 // Add Rust to the language, so that we can restore the language of the buffer
1766 project.update(cx, |project, _| project.languages().add(rust_language()));
1767
1768 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1769
1770 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1771
1772 let item_id = 9012 as ItemId;
1773 let serialized_editor = SerializedEditor {
1774 abs_path: None,
1775 contents: Some("hello".to_string()),
1776 language: Some("Rust".to_string()),
1777 mtime: None,
1778 };
1779
1780 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1781 .await
1782 .unwrap();
1783
1784 let deserialized =
1785 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1786
1787 deserialized.update(cx, |editor, cx| {
1788 assert_eq!(editor.text(cx), "hello");
1789 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
1790
1791 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1792 assert_eq!(
1793 buffer.language().map(|lang| lang.name()),
1794 Some("Rust".into())
1795 ); // Language should be set to Rust
1796 assert!(buffer.file().is_none()); // The buffer should not have an associated file
1797 });
1798 }
1799
1800 // Test case 4: Deserialize with path, content, and old mtime
1801 {
1802 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1803 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1804
1805 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1806
1807 let item_id = 9345 as ItemId;
1808 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
1809 let serialized_editor = SerializedEditor {
1810 abs_path: Some(PathBuf::from("/file.rs")),
1811 contents: Some("fn main() {}".to_string()),
1812 language: Some("Rust".to_string()),
1813 mtime: Some(old_mtime),
1814 };
1815
1816 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1817 .await
1818 .unwrap();
1819
1820 let deserialized =
1821 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1822
1823 deserialized.update(cx, |editor, cx| {
1824 assert_eq!(editor.text(cx), "fn main() {}");
1825 assert!(editor.has_conflict(cx)); // The editor should have a conflict
1826 });
1827 }
1828 }
1829}