Skip to repository content3287 lines · 118.9 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T04:29:49.256Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
items.rs
1use crate::{
2 ActiveDebugLine, Anchor, Autoscroll, BufferSerialization, Capability, Editor, EditorEvent,
3 EditorSettings, ExcerptRange, FormatTarget, MultiBuffer, MultiBufferSnapshot, NavigationData,
4 ReportEditorEvent, SelectionEffects, ToPoint as _,
5 display_map::HighlightKey,
6 editor_settings::SeedQuerySetting,
7 persistence::{EditorDb, SerializedEditor},
8 scroll::{ScrollAnchor, ScrollOffset},
9};
10use anyhow::{Context as _, Result, anyhow};
11use collections::{HashMap, HashSet};
12use file_icons::FileIcons;
13use fs::MTime;
14use futures::{channel::oneshot, future::try_join_all};
15use git::status::GitSummary;
16use gpui::{
17 AnyElement, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter, Font,
18 IntoElement, ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window, point,
19};
20use language::{
21 Bias, Buffer, BufferRow, CharKind, CharScopeContext, HighlightedText, LocalFile, PLAIN_TEXT,
22 Point, SelectionGoal,
23 language_settings::{FormatOnSave, LanguageSettings},
24 proto::serialize_anchor as serialize_text_anchor,
25};
26use lsp::DiagnosticSeverity;
27use multi_buffer::{BufferOffset, MultiBufferOffset, PathKey};
28use project::{
29 File, Project, ProjectItem as _, ProjectPath, git_store::GitStore, lsp_store::FormatTrigger,
30 project_settings::ProjectSettings, search::SearchQuery,
31};
32use rope::TextSummary;
33use rpc::proto::{self, update_view};
34use settings::Settings;
35use std::{
36 any::{Any, TypeId},
37 borrow::Cow,
38 cmp::{self, Ordering},
39 num::NonZeroU32,
40 ops::Range,
41 path::{Path, PathBuf},
42 sync::Arc,
43};
44use text::{BufferId, BufferSnapshot, OffsetRangeExt, Selection, ToPoint as _};
45use ui::{IconDecorationKind, prelude::*};
46use util::{ResultExt, TryFutureExt, debug_panic, paths::PathExt, rel_path::RelPath};
47use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
48use workspace::{
49 CollaboratorId, ItemId, ItemNavHistory, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
50 invalid_item_view::InvalidItemView,
51 item::{FollowableItem, Item, ItemBufferKind, ItemEvent, ProjectItem, SaveOptions},
52 searchable::{
53 Direction, FilteredSearchRange, SearchEvent, SearchToken, SearchableItem,
54 SearchableItemHandle,
55 },
56};
57use workspace::{
58 Pane, TabBarSettings, WorkspaceSettings,
59 item::{FollowEvent, ProjectItemKind},
60 searchable::SearchOptions,
61};
62use zed_actions::preview::{
63 markdown::OpenPreview as OpenMarkdownPreview, svg::OpenPreview as OpenSvgPreview,
64};
65
66pub const MAX_TAB_TITLE_LEN: usize = 24;
67
68impl FollowableItem for Editor {
69 fn remote_id(&self) -> Option<ViewId> {
70 self.remote_id
71 }
72
73 fn from_state_proto(
74 workspace: Entity<Workspace>,
75 remote_id: ViewId,
76 state: &mut Option<proto::view::Variant>,
77 window: &mut Window,
78 cx: &mut App,
79 ) -> Option<Task<Result<Entity<Self>>>> {
80 let project = workspace.read(cx).project().to_owned();
81 let Some(proto::view::Variant::Editor(_)) = state else {
82 return None;
83 };
84 let Some(proto::view::Variant::Editor(state)) = state.take() else {
85 unreachable!()
86 };
87
88 let buffer_ids = state
89 .path_excerpts
90 .iter()
91 .map(|excerpt| excerpt.buffer_id)
92 .collect::<HashSet<_>>();
93
94 let buffers = project.update(cx, |project, cx| {
95 buffer_ids
96 .iter()
97 .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
98 .collect::<Result<Vec<_>>>()
99 });
100
101 Some(window.spawn(cx, async move |cx| {
102 let mut buffers = futures::future::try_join_all(buffers?)
103 .await
104 .debug_assert_ok("leaders don't share views for unshared buffers")?;
105
106 let path_excerpts =
107 deserialize_path_excerpts_and_wait_for_anchors(state.path_excerpts, &buffers, cx)
108 .await?;
109
110 let editor = cx.update(|window, cx| {
111 let multibuffer = cx.new(|cx| {
112 let mut multibuffer;
113 if state.singleton && buffers.len() == 1 {
114 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
115 } else {
116 multibuffer = MultiBuffer::new(project.read(cx).capability());
117 for (path_key, buffer_id, ranges) in path_excerpts {
118 let Some(buffer) =
119 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id)
120 else {
121 continue;
122 };
123 let buffer_snapshot = buffer.read(cx).snapshot();
124 multibuffer.update_path_excerpts(
125 path_key,
126 buffer.clone(),
127 &buffer_snapshot,
128 &ranges,
129 cx,
130 );
131 }
132 };
133
134 if let Some(title) = &state.title {
135 multibuffer = multibuffer.with_title(title.clone())
136 }
137
138 multibuffer
139 });
140
141 cx.new(|cx| {
142 let mut editor =
143 Editor::for_multibuffer(multibuffer, Some(project.clone()), window, cx);
144 editor.remote_id = Some(remote_id);
145 editor
146 })
147 })?;
148
149 editor.update(cx, |editor, cx| editor.text(cx));
150 update_editor_from_message(
151 editor.downgrade(),
152 project,
153 proto::update_view::Editor {
154 selections: state.selections,
155 pending_selection: state.pending_selection,
156 scroll_top_anchor: state.scroll_top_anchor,
157 scroll_x: state.scroll_x,
158 scroll_y: state.scroll_y,
159 ..Default::default()
160 },
161 cx,
162 )
163 .await?;
164
165 Ok(editor)
166 }))
167 }
168
169 fn set_leader_id(
170 &mut self,
171 leader_id: Option<CollaboratorId>,
172 window: &mut Window,
173 cx: &mut Context<Self>,
174 ) {
175 self.leader_id = leader_id;
176 if self.leader_id.is_some() {
177 self.buffer.update(cx, |buffer, cx| {
178 buffer.remove_active_selections(cx);
179 });
180 } else if self.focus_handle.is_focused(window) {
181 self.buffer.update(cx, |buffer, cx| {
182 buffer.set_active_selections(
183 &self.selections.disjoint_anchors_arc(),
184 self.selections.line_mode(),
185 self.cursor_shape,
186 cx,
187 );
188 });
189 }
190 cx.notify();
191 }
192
193 fn to_state_proto(&self, _: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
194 let is_private = self
195 .buffer
196 .read(cx)
197 .as_singleton()
198 .and_then(|buffer| buffer.read(cx).file())
199 .is_some_and(|file| file.is_private());
200 if is_private {
201 return None;
202 }
203
204 let display_snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
205 let scroll_anchor = self.scroll_manager.native_anchor(&display_snapshot, cx);
206 let buffer = self.buffer.read(cx);
207 let snapshot = buffer.snapshot(cx);
208 let mut path_excerpts: Vec<proto::PathExcerpts> = Vec::new();
209 for excerpt in snapshot.excerpts() {
210 if let Some(prev_entry) = path_excerpts.last_mut()
211 && prev_entry.buffer_id == excerpt.context.start.buffer_id.to_proto()
212 {
213 prev_entry.ranges.push(serialize_excerpt_range(excerpt));
214 } else if let Some(path_key) = snapshot.path_for_buffer(excerpt.context.start.buffer_id)
215 {
216 path_excerpts.push(proto::PathExcerpts {
217 path_key: Some(serialize_path_key(path_key)),
218 buffer_id: excerpt.context.start.buffer_id.to_proto(),
219 ranges: vec![serialize_excerpt_range(excerpt)],
220 });
221 }
222 }
223
224 Some(proto::view::Variant::Editor(proto::view::Editor {
225 singleton: buffer.is_singleton(),
226 title: buffer.explicit_title().map(ToOwned::to_owned),
227 excerpts: Vec::new(),
228 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
229 scroll_x: scroll_anchor.offset.x,
230 scroll_y: scroll_anchor.offset.y,
231 selections: self
232 .selections
233 .disjoint_anchors_arc()
234 .iter()
235 .map(serialize_selection)
236 .collect(),
237 pending_selection: self
238 .selections
239 .pending_anchor()
240 .as_ref()
241 .copied()
242 .map(serialize_selection),
243 path_excerpts,
244 }))
245 }
246
247 fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
248 match event {
249 EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
250 EditorEvent::SelectionsChanged { local }
251 | EditorEvent::ScrollPositionChanged { local, .. } => {
252 if *local {
253 Some(FollowEvent::Unfollow)
254 } else {
255 None
256 }
257 }
258 _ => None,
259 }
260 }
261
262 fn add_event_to_update_proto(
263 &self,
264 event: &EditorEvent,
265 update: &mut Option<proto::update_view::Variant>,
266 _: &mut Window,
267 cx: &mut App,
268 ) -> bool {
269 let update =
270 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
271
272 match update {
273 proto::update_view::Variant::Editor(update) => match event {
274 EditorEvent::BufferRangesUpdated {
275 buffer,
276 path_key,
277 ranges,
278 } => {
279 let buffer_id = buffer.read(cx).remote_id().to_proto();
280 let path_key = serialize_path_key(path_key);
281 let ranges = ranges
282 .iter()
283 .cloned()
284 .map(serialize_excerpt_range)
285 .collect::<Vec<_>>();
286 update.updated_paths.push(proto::PathExcerpts {
287 path_key: Some(path_key),
288 buffer_id,
289 ranges,
290 });
291 true
292 }
293 EditorEvent::BuffersRemoved { removed_buffer_ids } => {
294 update
295 .deleted_buffers
296 .extend(removed_buffer_ids.iter().copied().map(BufferId::to_proto));
297 true
298 }
299 EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
300 let display_snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
301 let scroll_anchor = self.scroll_manager.native_anchor(&display_snapshot, cx);
302 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
303 update.scroll_x = scroll_anchor.offset.x;
304 update.scroll_y = scroll_anchor.offset.y;
305 true
306 }
307 EditorEvent::SelectionsChanged { .. } => {
308 update.selections = self
309 .selections
310 .disjoint_anchors_arc()
311 .iter()
312 .map(serialize_selection)
313 .collect();
314 update.pending_selection = self
315 .selections
316 .pending_anchor()
317 .as_ref()
318 .copied()
319 .map(serialize_selection);
320 true
321 }
322 _ => false,
323 },
324 }
325 }
326
327 fn apply_update_proto(
328 &mut self,
329 project: &Entity<Project>,
330 message: update_view::Variant,
331 window: &mut Window,
332 cx: &mut Context<Self>,
333 ) -> Task<Result<()>> {
334 let update_view::Variant::Editor(message) = message;
335 let project = project.clone();
336 cx.spawn_in(window, async move |this, cx| {
337 update_editor_from_message(this, project, message, cx).await
338 })
339 }
340
341 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
342 true
343 }
344
345 fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
346 let self_singleton = self.buffer.read(cx).as_singleton()?;
347 let other_singleton = existing.buffer.read(cx).as_singleton()?;
348 if self_singleton == other_singleton {
349 Some(Dedup::KeepExisting)
350 } else {
351 None
352 }
353 }
354
355 fn update_agent_location(
356 &mut self,
357 location: language::Anchor,
358 window: &mut Window,
359 cx: &mut Context<Self>,
360 ) {
361 let buffer = self.buffer.read(cx);
362 let buffer = buffer.read(cx);
363 let Some(position) = buffer.anchor_in_excerpt(location) else {
364 return;
365 };
366 let selection = Selection {
367 id: 0,
368 reversed: false,
369 start: position,
370 end: position,
371 goal: SelectionGoal::None,
372 };
373 drop(buffer);
374 self.set_selections_from_remote(vec![selection], None, window, cx);
375 self.request_autoscroll_remotely(Autoscroll::focused(), cx);
376 }
377}
378
379async fn update_editor_from_message(
380 this: WeakEntity<Editor>,
381 project: Entity<Project>,
382 message: proto::update_view::Editor,
383 cx: &mut AsyncWindowContext,
384) -> Result<()> {
385 // Open all of the buffers of which excerpts were added to the editor.
386 let inserted_excerpt_buffer_ids = message
387 .updated_paths
388 .iter()
389 .map(|insertion| insertion.buffer_id)
390 .collect::<HashSet<_>>();
391 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
392 inserted_excerpt_buffer_ids
393 .into_iter()
394 .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
395 .collect::<Result<Vec<_>>>()
396 })?;
397 let inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
398
399 let updated_paths = deserialize_path_excerpts_and_wait_for_anchors(
400 message.updated_paths,
401 &inserted_excerpt_buffers,
402 cx,
403 )
404 .await?;
405
406 // Update the editor's excerpts.
407 let buffer_snapshot = this.update(cx, |editor, cx| {
408 editor.buffer.update(cx, |multibuffer, cx| {
409 for (path_key, buffer_id, ranges) in updated_paths {
410 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
411 continue;
412 };
413
414 let buffer_snapshot = buffer.read(cx).snapshot();
415 multibuffer.update_path_excerpts(path_key, buffer, &buffer_snapshot, &ranges, cx);
416 }
417
418 for buffer_id in message
419 .deleted_buffers
420 .into_iter()
421 .filter_map(|buffer_id| BufferId::new(buffer_id).ok())
422 {
423 multibuffer.remove_excerpts_for_buffer(buffer_id, cx);
424 }
425
426 multibuffer.snapshot(cx)
427 })
428 })?;
429
430 // Deserialize the editor state.
431 let selections = message
432 .selections
433 .into_iter()
434 .filter_map(|selection| deserialize_selection(selection, &buffer_snapshot))
435 .collect::<Vec<_>>();
436 let pending_selection = message
437 .pending_selection
438 .and_then(|selection| deserialize_selection(selection, &buffer_snapshot));
439 let scroll_top_anchor = message
440 .scroll_top_anchor
441 .and_then(|selection| deserialize_anchor(selection, &buffer_snapshot));
442
443 // Wait until the buffer has received all of the operations referenced by
444 // the editor's new state.
445 this.update(cx, |editor, cx| {
446 editor.buffer.update(cx, |buffer, cx| {
447 buffer.wait_for_anchors(
448 selections
449 .iter()
450 .chain(pending_selection.as_ref())
451 .flat_map(|selection| [selection.start, selection.end])
452 .chain(scroll_top_anchor),
453 cx,
454 )
455 })
456 })?
457 .await?;
458
459 // Update the editor's state.
460 this.update_in(cx, |editor, window, cx| {
461 if !selections.is_empty() || pending_selection.is_some() {
462 editor.set_selections_from_remote(selections, pending_selection, window, cx);
463 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
464 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
465 editor.set_scroll_anchor_remote(
466 ScrollAnchor {
467 anchor: scroll_top_anchor,
468 offset: point(message.scroll_x, message.scroll_y),
469 },
470 window,
471 cx,
472 );
473 }
474 })?;
475 Ok(())
476}
477
478fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
479 proto::Selection {
480 id: selection.id as u64,
481 start: Some(serialize_anchor(&selection.start)),
482 end: Some(serialize_anchor(&selection.end)),
483 reversed: selection.reversed,
484 }
485}
486
487fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
488 match anchor {
489 Anchor::Min => proto::EditorAnchor {
490 excerpt_id: None,
491 anchor: Some(proto::Anchor {
492 replica_id: 0,
493 timestamp: 0,
494 offset: 0,
495 bias: proto::Bias::Left as i32,
496 buffer_id: None,
497 }),
498 },
499 Anchor::Excerpt(_) => proto::EditorAnchor {
500 excerpt_id: None,
501 anchor: anchor.raw_text_anchor().map(|a| serialize_text_anchor(&a)),
502 },
503 Anchor::Max => proto::EditorAnchor {
504 excerpt_id: None,
505 anchor: Some(proto::Anchor {
506 replica_id: u32::MAX,
507 timestamp: u32::MAX,
508 offset: u64::MAX,
509 bias: proto::Bias::Right as i32,
510 buffer_id: None,
511 }),
512 },
513 }
514}
515
516fn serialize_excerpt_range(range: ExcerptRange<language::Anchor>) -> proto::ExcerptRange {
517 let context_start = language::proto::serialize_anchor(&range.context.start);
518 let context_end = language::proto::serialize_anchor(&range.context.end);
519 let primary_start = language::proto::serialize_anchor(&range.primary.start);
520 let primary_end = language::proto::serialize_anchor(&range.primary.end);
521 proto::ExcerptRange {
522 context_start: Some(context_start),
523 context_end: Some(context_end),
524 primary_start: Some(primary_start),
525 primary_end: Some(primary_end),
526 }
527}
528
529async fn deserialize_path_excerpts_and_wait_for_anchors(
530 path_excerpts: Vec<proto::PathExcerpts>,
531 buffers: &[Entity<Buffer>],
532 cx: &mut AsyncWindowContext,
533) -> Result<Vec<(PathKey, BufferId, Vec<ExcerptRange<language::Anchor>>)>> {
534 let path_excerpts = path_excerpts
535 .into_iter()
536 .filter_map(|path_with_ranges| {
537 let path_key = path_with_ranges.path_key.and_then(deserialize_path_key)?;
538 let buffer_id = BufferId::new(path_with_ranges.buffer_id).ok()?;
539 let ranges = path_with_ranges
540 .ranges
541 .into_iter()
542 .filter_map(deserialize_excerpt_range)
543 .collect::<Vec<_>>();
544 Some((path_key, buffer_id, ranges))
545 })
546 .collect::<Vec<_>>();
547
548 let wait_for_anchors = cx.update(|_, cx| {
549 buffers
550 .iter()
551 .map(|buffer| {
552 let buffer_id = buffer.read(cx).remote_id();
553 let anchors = path_excerpts
554 .iter()
555 .filter(|(_, id, _)| *id == buffer_id)
556 .flat_map(|(_, _, ranges)| {
557 ranges.iter().flat_map(|range| {
558 [
559 range.context.start,
560 range.context.end,
561 range.primary.start,
562 range.primary.end,
563 ]
564 })
565 })
566 .collect::<Vec<_>>();
567 buffer.update(cx, |buffer, _| buffer.wait_for_anchors(anchors))
568 })
569 .collect::<Vec<_>>()
570 })?;
571 // Without this wait, resolving these anchors later can race ahead of the
572 // leader's pending buffer ops and trip `panic_bad_anchor` on a stale
573 // snapshot.
574 try_join_all(wait_for_anchors).await?;
575
576 Ok(path_excerpts)
577}
578
579fn deserialize_excerpt_range(
580 excerpt_range: proto::ExcerptRange,
581) -> Option<ExcerptRange<language::Anchor>> {
582 let context = {
583 let start = language::proto::deserialize_anchor(excerpt_range.context_start?)?;
584 let end = language::proto::deserialize_anchor(excerpt_range.context_end?)?;
585 start..end
586 };
587 let primary = excerpt_range
588 .primary_start
589 .zip(excerpt_range.primary_end)
590 .and_then(|(start, end)| {
591 let start = language::proto::deserialize_anchor(start)?;
592 let end = language::proto::deserialize_anchor(end)?;
593 Some(start..end)
594 })
595 .unwrap_or_else(|| context.clone());
596 Some(ExcerptRange { context, primary })
597}
598
599fn deserialize_selection(
600 selection: proto::Selection,
601 buffer: &MultiBufferSnapshot,
602) -> Option<Selection<Anchor>> {
603 Some(Selection {
604 id: selection.id as usize,
605 start: deserialize_anchor(selection.start?, buffer)?,
606 end: deserialize_anchor(selection.end?, buffer)?,
607 reversed: selection.reversed,
608 goal: SelectionGoal::None,
609 })
610}
611
612fn deserialize_anchor(anchor: proto::EditorAnchor, buffer: &MultiBufferSnapshot) -> Option<Anchor> {
613 let anchor = anchor.anchor?;
614 if let Some(buffer_id) = anchor.buffer_id
615 && BufferId::new(buffer_id).is_ok()
616 {
617 let text_anchor = language::proto::deserialize_anchor(anchor)?;
618 buffer.anchor_in_buffer(text_anchor)
619 } else {
620 match proto::Bias::from_i32(anchor.bias)? {
621 proto::Bias::Left => Some(Anchor::Min),
622 proto::Bias::Right => Some(Anchor::Max),
623 }
624 }
625}
626
627impl Item for Editor {
628 type Event = EditorEvent;
629
630 fn act_as_type<'a>(
631 &'a self,
632 type_id: TypeId,
633 self_handle: &'a Entity<Self>,
634 cx: &'a App,
635 ) -> Option<gpui::AnyEntity> {
636 if TypeId::of::<Self>() == type_id {
637 Some(self_handle.clone().into())
638 } else if TypeId::of::<MultiBuffer>() == type_id {
639 Some(self_handle.read(cx).buffer.clone().into())
640 } else {
641 None
642 }
643 }
644
645 fn navigate(
646 &mut self,
647 data: Arc<dyn Any + Send>,
648 window: &mut Window,
649 cx: &mut Context<Self>,
650 ) -> bool {
651 if let Some(data) = data.downcast_ref::<NavigationData>() {
652 let newest_selection = self.selections.newest::<Point>(&self.display_snapshot(cx));
653 let buffer = self.buffer.read(cx).read(cx);
654 let offset = if buffer.can_resolve(&data.cursor_anchor) {
655 data.cursor_anchor.to_point(&buffer)
656 } else {
657 buffer.clip_point(data.cursor_position, Bias::Left)
658 };
659
660 let mut scroll_anchor = data.scroll_anchor;
661 if !buffer.can_resolve(&scroll_anchor.anchor) {
662 scroll_anchor.anchor = buffer.anchor_before(
663 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
664 );
665 }
666
667 drop(buffer);
668
669 if newest_selection.head() == offset {
670 false
671 } else {
672 self.set_scroll_anchor(scroll_anchor, window, cx);
673 self.change_selections(
674 SelectionEffects::default().nav_history(false),
675 window,
676 cx,
677 |s| s.select_ranges([offset..offset]),
678 );
679 true
680 }
681 } else {
682 false
683 }
684 }
685
686 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
687 let multi_buffer = self.buffer().read(cx);
688 if let Some(file) = multi_buffer
689 .as_singleton()
690 .and_then(|buffer| buffer.read(cx).file())
691 .and_then(|file| File::from_dyn(Some(file)))
692 {
693 Some(
694 file.worktree
695 .read(cx)
696 .absolutize(&file.path)
697 .compact()
698 .to_string_lossy()
699 .into_owned()
700 .into(),
701 )
702 } else {
703 let title = multi_buffer.title(cx);
704 (!title.is_empty()).then(|| title.to_string().into())
705 }
706 }
707
708 fn telemetry_event_text(&self) -> Option<&'static str> {
709 None
710 }
711
712 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
713 if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
714 path.to_string().into()
715 } else {
716 // Use the same logic as the displayed title for consistency
717 self.buffer.read(cx).title(cx).to_string().into()
718 }
719 }
720
721 fn suggested_filename(&self, cx: &App) -> SharedString {
722 let multi_buffer = self.buffer.read(cx);
723 let title = multi_buffer.title(cx);
724 if let Some(buffer) = multi_buffer.as_singleton() {
725 let buffer = buffer.read(cx);
726 if buffer.file().is_none()
727 && let Some(language) = buffer.language()
728 && *language != *PLAIN_TEXT
729 && let Some(suffix) = language.path_suffixes().first()
730 && !suffix.is_empty()
731 && !title.ends_with(&format!(".{suffix}"))
732 {
733 return format!("{title}.{suffix}").into();
734 }
735 }
736
737 title.to_string().into()
738 }
739
740 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
741 ItemSettings::get_global(cx)
742 .file_icons
743 .then(|| {
744 path_for_buffer(&self.buffer, 0, true, cx)
745 .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
746 })
747 .flatten()
748 .map(Icon::from_path)
749 }
750
751 fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
752 let label_color = if ItemSettings::get_global(cx).git_status {
753 self.buffer()
754 .read(cx)
755 .as_singleton()
756 .and_then(|buffer| {
757 let buffer = buffer.read(cx);
758 let path = buffer.project_path(cx)?;
759 let buffer_id = buffer.remote_id();
760 let project = self.project()?.read(cx);
761 let entry = project.entry_for_path(&path, cx)?;
762 let (repo, repo_path) = project
763 .git_store()
764 .read(cx)
765 .repository_and_path_for_buffer_id(buffer_id, cx)?;
766 let status = repo.read(cx).status_for_path(&repo_path)?.status;
767
768 Some(entry_git_aware_label_color(
769 status.summary(),
770 entry.is_ignored,
771 params.selected,
772 ))
773 })
774 .unwrap_or_else(|| entry_label_color(params.selected))
775 } else {
776 entry_label_color(params.selected)
777 };
778
779 let description = params.detail.and_then(|detail| {
780 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
781 let description = path.trim();
782
783 if description.is_empty() {
784 return None;
785 }
786
787 Some(util::truncate_and_trailoff(
788 description,
789 params.max_title_len.unwrap_or(MAX_TAB_TITLE_LEN),
790 ))
791 });
792
793 // Whether the file was saved in the past but is now deleted.
794 let was_deleted: bool = self
795 .buffer()
796 .read(cx)
797 .as_singleton()
798 .and_then(|buffer| buffer.read(cx).file())
799 .is_some_and(|file| file.disk_state().is_deleted());
800
801 h_flex()
802 .gap_1()
803 .when(params.truncate_title_middle, |this| {
804 this.w_full().min_w_0().overflow_hidden()
805 })
806 .child(
807 Label::new(if params.truncate_title_middle {
808 self.title(cx).to_string()
809 } else {
810 util::truncate_and_trailoff(
811 &self.title(cx),
812 params.max_title_len.unwrap_or(MAX_TAB_TITLE_LEN),
813 )
814 })
815 .color(label_color)
816 .when(params.truncate_title_middle, |this| {
817 this.truncate_middle().flex_1()
818 })
819 .when(params.preview, |this| this.italic())
820 .when(was_deleted, |this| this.strikethrough()),
821 )
822 .when_some(description, |this, description| {
823 this.child(
824 Label::new(description)
825 .size(LabelSize::XSmall)
826 .when(params.truncate_title_middle, |this| {
827 this.truncate_start().flex_shrink()
828 })
829 .color(Color::Muted),
830 )
831 })
832 .into_any_element()
833 }
834
835 fn for_each_project_item(
836 &self,
837 cx: &App,
838 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
839 ) {
840 self.buffer
841 .read(cx)
842 .for_each_buffer(&mut |buffer| f(buffer.entity_id(), buffer.read(cx)));
843 }
844
845 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
846 match self.buffer.read(cx).is_singleton() {
847 true => ItemBufferKind::Singleton,
848 false => ItemBufferKind::Multibuffer,
849 }
850 }
851
852 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
853 self.active_buffer(cx)?.read(cx).project_path(cx)
854 }
855
856 fn can_save_as(&self, cx: &App) -> bool {
857 self.buffer.read(cx).is_singleton()
858 }
859
860 fn can_split(&self) -> bool {
861 true
862 }
863
864 fn clone_on_split(
865 &self,
866 _workspace_id: Option<WorkspaceId>,
867 window: &mut Window,
868 cx: &mut Context<Self>,
869 ) -> Task<Option<Entity<Editor>>>
870 where
871 Self: Sized,
872 {
873 Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
874 }
875
876 fn set_nav_history(
877 &mut self,
878 history: ItemNavHistory,
879 _window: &mut Window,
880 _: &mut Context<Self>,
881 ) {
882 self.nav_history = Some(history);
883 }
884
885 fn on_removed(&self, cx: &mut Context<Self>) {
886 self.report_editor_event(ReportEditorEvent::Closed, None, cx);
887 }
888
889 fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
890 let selection = self.selections.newest_anchor();
891 self.push_to_nav_history(selection.head(), None, true, false, cx);
892 }
893
894 fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
895 self.hide_hovered_link(cx);
896 }
897
898 fn is_dirty(&self, cx: &App) -> bool {
899 self.buffer().read(cx).read(cx).is_dirty()
900 }
901
902 fn capability(&self, cx: &App) -> Capability {
903 self.capability(cx)
904 }
905
906 // Note: this mirrors the logic in `Editor::toggle_read_only`, but is reachable
907 // without relying on focus-based action dispatch.
908 fn toggle_read_only(&mut self, window: &mut Window, cx: &mut Context<Self>) {
909 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
910 buffer.update(cx, |buffer, cx| {
911 buffer.set_capability(
912 match buffer.capability() {
913 Capability::ReadWrite => Capability::Read,
914 Capability::Read => Capability::ReadWrite,
915 Capability::ReadOnly => Capability::ReadOnly,
916 },
917 cx,
918 );
919 });
920 }
921 cx.notify();
922 window.refresh();
923 }
924
925 fn has_deleted_file(&self, cx: &App) -> bool {
926 self.buffer().read(cx).read(cx).has_deleted_file()
927 }
928
929 fn has_conflict(&self, cx: &App) -> bool {
930 self.buffer().read(cx).read(cx).has_conflict()
931 }
932
933 fn can_save(&self, cx: &App) -> bool {
934 let buffer = &self.buffer().read(cx);
935 if let Some(buffer) = buffer.as_singleton() {
936 buffer.read(cx).project_path(cx).is_some()
937 } else {
938 true
939 }
940 }
941
942 fn save(
943 &mut self,
944 options: SaveOptions,
945 project: Entity<Project>,
946 window: &mut Window,
947 cx: &mut Context<Self>,
948 ) -> Task<Result<()>> {
949 // Add meta data tracking # of auto saves
950 if options.autosave {
951 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
952 } else {
953 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
954 }
955
956 let buffers = self.buffer().clone().read(cx).all_buffers();
957 let buffers = buffers
958 .into_iter()
959 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
960 .collect::<HashSet<_>>();
961
962 let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
963 buffers
964 } else {
965 buffers
966 .into_iter()
967 .filter(|buffer| buffer.read(cx).is_dirty())
968 .collect()
969 };
970
971 let format_trigger = if options.force_format {
972 FormatTrigger::Manual
973 } else {
974 FormatTrigger::Save
975 };
976
977 cx.spawn_in(window, async move |this, cx| {
978 if options.format {
979 let format_task = this.update_in(cx, |editor, window, cx| {
980 let format_target = compute_format_target(
981 &buffers_to_save,
982 format_trigger,
983 editor.buffer(),
984 project.read(cx).git_store(),
985 cx,
986 );
987 format_target.map(|target| {
988 editor.perform_format(project.clone(), format_trigger, target, window, cx)
989 })
990 })?;
991 if let Some(format_task) = format_task {
992 format_task.await?;
993 }
994 }
995
996 if !buffers_to_save.is_empty() {
997 project
998 .update(cx, |project, cx| {
999 project.save_buffers(buffers_to_save.clone(), cx)
1000 })
1001 .await?;
1002 }
1003
1004 Ok(())
1005 })
1006 }
1007
1008 fn save_as(
1009 &mut self,
1010 project: Entity<Project>,
1011 path: ProjectPath,
1012 _: &mut Window,
1013 cx: &mut Context<Self>,
1014 ) -> Task<Result<()>> {
1015 let buffer = self
1016 .buffer()
1017 .read(cx)
1018 .as_singleton()
1019 .expect("cannot call save_as on an excerpt list");
1020
1021 let file_extension = path.path.extension().map(|a| a.to_string());
1022 self.report_editor_event(
1023 ReportEditorEvent::Saved { auto_saved: false },
1024 file_extension,
1025 cx,
1026 );
1027
1028 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
1029 }
1030
1031 fn reload(
1032 &mut self,
1033 project: Entity<Project>,
1034 window: &mut Window,
1035 cx: &mut Context<Self>,
1036 ) -> Task<Result<()>> {
1037 let buffer = self.buffer().clone();
1038 let buffers = self.buffer.read(cx).all_buffers();
1039 let reload_buffers =
1040 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
1041 cx.spawn_in(window, async move |this, cx| {
1042 let transaction = reload_buffers.log_err().await;
1043 this.update(cx, |editor, cx| {
1044 editor.request_autoscroll(Autoscroll::fit(), cx)
1045 })?;
1046 buffer.update(cx, |buffer, cx| {
1047 if let Some(transaction) = transaction
1048 && !buffer.is_singleton()
1049 {
1050 buffer.push_transaction(&transaction.0, cx);
1051 }
1052 });
1053 Ok(())
1054 })
1055 }
1056
1057 fn as_searchable(
1058 &self,
1059 handle: &Entity<Self>,
1060 _: &App,
1061 ) -> Option<Box<dyn SearchableItemHandle>> {
1062 Some(Box::new(handle.clone()))
1063 }
1064
1065 fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
1066 self.pixel_position_of_newest_cursor
1067 }
1068
1069 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1070 if self.breadcrumbs_visible() && self.buffer().read(cx).is_singleton() {
1071 ToolbarItemLocation::PrimaryLeft
1072 } else {
1073 ToolbarItemLocation::Hidden
1074 }
1075 }
1076
1077 // In a non-singleton case, the breadcrumbs are actually shown on sticky file headers of the multibuffer.
1078 fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
1079 if self.buffer.read(cx).is_singleton() {
1080 let font = theme_settings::ThemeSettings::get_global(cx)
1081 .buffer_font
1082 .clone();
1083 Some((self.breadcrumbs_inner(cx)?, Some(font)))
1084 } else {
1085 None
1086 }
1087 }
1088
1089 fn breadcrumb_prefix(
1090 &self,
1091 _window: &mut Window,
1092 cx: &mut Context<Self>,
1093 ) -> Option<gpui::AnyElement> {
1094 (!TabBarSettings::get_global(cx).show && ItemSettings::get_global(cx).file_icons)
1095 .then(|| {
1096 path_for_buffer(&self.buffer, 0, true, cx)
1097 .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
1098 })
1099 .flatten()
1100 .map(|icon_path| Icon::from_path(icon_path).into_any_element())
1101 }
1102
1103 fn added_to_workspace(
1104 &mut self,
1105 workspace: &mut Workspace,
1106 window: &mut Window,
1107 cx: &mut Context<Self>,
1108 ) {
1109 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1110 if let Some(workspace_entity) = &workspace.weak_handle().upgrade() {
1111 cx.subscribe(
1112 workspace_entity,
1113 |editor, _, event: &workspace::Event, cx| {
1114 if let workspace::Event::ModalOpened = event {
1115 editor.mouse_context_menu.take();
1116 editor.hide_blame_popover(true, cx);
1117 }
1118 },
1119 )
1120 .detach();
1121 }
1122
1123 // Load persisted folds if this editor doesn't already have folds.
1124 // This handles manually-opened files (not workspace restoration).
1125 let display_snapshot = self
1126 .display_map
1127 .update(cx, |display_map, cx| display_map.snapshot(cx));
1128 let has_folds = display_snapshot
1129 .folds_in_range(MultiBufferOffset(0)..display_snapshot.buffer_snapshot().len())
1130 .next()
1131 .is_some();
1132
1133 if !has_folds {
1134 if let Some(workspace_id) = workspace.database_id()
1135 && let Some(file_path) = self.buffer().read(cx).as_singleton().and_then(|buffer| {
1136 project::File::from_dyn(buffer.read(cx).file()).map(|file| file.abs_path(cx))
1137 })
1138 {
1139 self.load_folds_from_db(workspace_id, file_path, window, cx);
1140 }
1141 }
1142 }
1143
1144 fn pane_changed(&mut self, new_pane_id: EntityId, cx: &mut Context<Self>) {
1145 if self
1146 .highlighted_rows
1147 .get(&TypeId::of::<ActiveDebugLine>())
1148 .is_some_and(|lines| !lines.is_empty())
1149 && let Some(breakpoint_store) = self.breakpoint_store.as_ref()
1150 {
1151 breakpoint_store.update(cx, |store, _cx| {
1152 store.set_active_debug_pane_id(new_pane_id);
1153 });
1154 }
1155 }
1156
1157 fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
1158 match event {
1159 EditorEvent::Saved | EditorEvent::TitleChanged => {
1160 f(ItemEvent::UpdateTab);
1161 f(ItemEvent::UpdateBreadcrumbs);
1162 }
1163
1164 EditorEvent::Reparsed(_) => {
1165 f(ItemEvent::UpdateBreadcrumbs);
1166 }
1167
1168 EditorEvent::SelectionsChanged { local } if *local => {
1169 f(ItemEvent::UpdateBreadcrumbs);
1170 }
1171
1172 EditorEvent::BreadcrumbsChanged | EditorEvent::OutlineSymbolsChanged => {
1173 f(ItemEvent::UpdateBreadcrumbs);
1174 }
1175
1176 EditorEvent::DirtyChanged => {
1177 f(ItemEvent::UpdateTab);
1178 }
1179
1180 EditorEvent::BufferEdited => {
1181 f(ItemEvent::Edit);
1182 f(ItemEvent::UpdateBreadcrumbs);
1183 }
1184
1185 EditorEvent::BufferRangesUpdated { .. } | EditorEvent::BuffersRemoved { .. } => {
1186 f(ItemEvent::Edit);
1187 }
1188
1189 _ => {}
1190 }
1191 }
1192
1193 fn tab_extra_context_menu_actions(
1194 &self,
1195 _window: &mut Window,
1196 cx: &mut Context<Self>,
1197 ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1198 let mut actions = Vec::new();
1199
1200 let is_markdown = self
1201 .buffer()
1202 .read(cx)
1203 .as_singleton()
1204 .and_then(|buffer| buffer.read(cx).language())
1205 .is_some_and(|language| language.name().as_ref() == "Markdown");
1206
1207 let is_svg = self
1208 .buffer()
1209 .read(cx)
1210 .as_singleton()
1211 .and_then(|buffer| buffer.read(cx).file())
1212 .is_some_and(|file| {
1213 std::path::Path::new(file.file_name(cx))
1214 .extension()
1215 .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))
1216 });
1217
1218 if is_markdown {
1219 actions.push((
1220 "Open Markdown Preview".into(),
1221 Box::new(OpenMarkdownPreview) as Box<dyn gpui::Action>,
1222 ));
1223 }
1224
1225 if is_svg {
1226 actions.push((
1227 "Open SVG Preview".into(),
1228 Box::new(OpenSvgPreview) as Box<dyn gpui::Action>,
1229 ));
1230 }
1231
1232 actions
1233 }
1234
1235 fn preserve_preview(&self, cx: &App) -> bool {
1236 self.buffer.read(cx).preserve_preview(cx)
1237 }
1238}
1239
1240impl SerializableItem for Editor {
1241 fn serialized_item_kind() -> &'static str {
1242 "Editor"
1243 }
1244
1245 fn cleanup(
1246 workspace_id: WorkspaceId,
1247 alive_items: Vec<ItemId>,
1248 _window: &mut Window,
1249 cx: &mut App,
1250 ) -> Task<Result<()>> {
1251 workspace::delete_unloaded_items(
1252 alive_items,
1253 workspace_id,
1254 "editors",
1255 &EditorDb::global(cx),
1256 cx,
1257 )
1258 }
1259
1260 fn deserialize(
1261 project: Entity<Project>,
1262 _workspace: WeakEntity<Workspace>,
1263 workspace_id: workspace::WorkspaceId,
1264 item_id: ItemId,
1265 window: &mut Window,
1266 cx: &mut App,
1267 ) -> Task<Result<Entity<Self>>> {
1268 let serialized_editor = match EditorDb::global(cx)
1269 .get_serialized_editor(item_id, workspace_id)
1270 .context("Failed to query editor state")
1271 {
1272 Ok(Some(serialized_editor)) => {
1273 if ProjectSettings::get_global(cx)
1274 .session
1275 .restore_unsaved_buffers
1276 {
1277 serialized_editor
1278 } else {
1279 SerializedEditor {
1280 abs_path: serialized_editor.abs_path,
1281 contents: None,
1282 language: None,
1283 mtime: None,
1284 }
1285 }
1286 }
1287 Ok(None) => {
1288 return Task::ready(Err(anyhow!(
1289 "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1290 )));
1291 }
1292 Err(error) => {
1293 return Task::ready(Err(error));
1294 }
1295 };
1296 log::debug!(
1297 "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1298 );
1299
1300 match serialized_editor {
1301 SerializedEditor {
1302 abs_path: None,
1303 contents: Some(contents),
1304 language,
1305 ..
1306 } => window.spawn(cx, {
1307 let project = project.clone();
1308 async move |cx| {
1309 let language_registry =
1310 project.read_with(cx, |project, _| project.languages().clone());
1311
1312 let language = if let Some(language_name) = language {
1313 // We don't fail here, because we'd rather not set the language if the name changed
1314 // than fail to restore the buffer.
1315 language_registry
1316 .language_for_name(&language_name)
1317 .await
1318 .ok()
1319 } else {
1320 None
1321 };
1322
1323 // First create the empty buffer
1324 let buffer = project
1325 .update(cx, |project, cx| project.create_buffer(language, true, cx))
1326 .await
1327 .context("Failed to create buffer while deserializing editor")?;
1328
1329 // Then set the text so that the dirty bit is set correctly
1330 buffer.update(cx, |buffer, cx| {
1331 buffer.set_language_registry(language_registry);
1332 buffer.set_text(contents, cx);
1333 if let Some(entry) = buffer.peek_undo_stack() {
1334 buffer.forget_transaction(entry.transaction_id());
1335 }
1336 });
1337
1338 cx.update(|window, cx| {
1339 cx.new(|cx| {
1340 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1341
1342 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1343 editor
1344 })
1345 })
1346 }
1347 }),
1348 SerializedEditor {
1349 abs_path: Some(abs_path),
1350 contents,
1351 mtime,
1352 ..
1353 } => {
1354 let opened_buffer = project.update(cx, |project, cx| {
1355 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1356 let project_path = ProjectPath {
1357 worktree_id: worktree.read(cx).id(),
1358 path: path,
1359 };
1360 Some(project.open_path(project_path, cx))
1361 });
1362
1363 match opened_buffer {
1364 Some(opened_buffer) => window.spawn(cx, async move |cx| {
1365 let (_, buffer) = opened_buffer
1366 .await
1367 .context("Failed to open path in project")?;
1368
1369 if let Some(contents) = contents {
1370 buffer.update(cx, |buffer, cx| {
1371 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1372 });
1373 }
1374
1375 cx.update(|window, cx| {
1376 cx.new(|cx| {
1377 let mut editor =
1378 Editor::for_buffer(buffer, Some(project), window, cx);
1379
1380 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1381 editor
1382 })
1383 })
1384 }),
1385 None => {
1386 // File is not in any worktree (e.g., opened as a standalone file).
1387 // Open the buffer directly via the project rather than through
1388 // workspace.open_abs_path(), which has the side effect of adding
1389 // the item to a pane. The caller (deserialize_to) will add the
1390 // returned item to the correct pane.
1391 window.spawn(cx, async move |cx| {
1392 let buffer = project
1393 .update(cx, |project, cx| project.open_local_buffer(&abs_path, cx))
1394 .await
1395 .with_context(|| {
1396 format!("Failed to open buffer for {abs_path:?}")
1397 })?;
1398
1399 if let Some(contents) = contents {
1400 buffer.update(cx, |buffer, cx| {
1401 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1402 });
1403 }
1404
1405 cx.update(|window, cx| {
1406 cx.new(|cx| {
1407 let mut editor =
1408 Editor::for_buffer(buffer, Some(project), window, cx);
1409 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1410 editor
1411 })
1412 })
1413 })
1414 }
1415 }
1416 }
1417 SerializedEditor {
1418 abs_path: None,
1419 contents: None,
1420 ..
1421 } => window.spawn(cx, async move |cx| {
1422 let buffer = project
1423 .update(cx, |project, cx| project.create_buffer(None, true, cx))
1424 .await
1425 .context("Failed to create buffer")?;
1426
1427 cx.update(|window, cx| {
1428 cx.new(|cx| {
1429 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1430
1431 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1432 editor
1433 })
1434 })
1435 }),
1436 }
1437 }
1438
1439 fn serialize(
1440 &mut self,
1441 workspace: &mut Workspace,
1442 item_id: ItemId,
1443 closing: bool,
1444 window: &mut Window,
1445 cx: &mut Context<Self>,
1446 ) -> Option<Task<Result<()>>> {
1447 let buffer_serialization = self.buffer_serialization?;
1448 let project = self.project.clone()?;
1449
1450 let serialize_dirty_buffers = match buffer_serialization {
1451 // Always serialize dirty buffers, including for worktree-less windows.
1452 // This enables hot-exit functionality for empty windows and single files.
1453 BufferSerialization::All => true,
1454 BufferSerialization::NonDirtyBuffers => false,
1455 };
1456
1457 if closing && !serialize_dirty_buffers {
1458 return None;
1459 }
1460
1461 let workspace_id = workspace.database_id()?;
1462
1463 let buffer = self.buffer().read(cx).as_singleton()?;
1464
1465 let abs_path = buffer.read(cx).file().and_then(|file| {
1466 let worktree_id = file.worktree_id(cx);
1467 project
1468 .read(cx)
1469 .worktree_for_id(worktree_id, cx)
1470 .map(|worktree| worktree.read(cx).absolutize(file.path()))
1471 .or_else(|| {
1472 let full_path = file.full_path(cx);
1473 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1474 project.read(cx).absolute_path(&project_path, cx)
1475 })
1476 });
1477
1478 let is_dirty = buffer.read(cx).is_dirty();
1479 let mtime = buffer.read(cx).saved_mtime();
1480
1481 let snapshot = buffer.read(cx).snapshot();
1482
1483 let db = EditorDb::global(cx);
1484 Some(cx.spawn_in(window, async move |_this, cx| {
1485 cx.background_spawn(async move {
1486 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1487 let contents = snapshot.text();
1488 let language = snapshot.language().map(|lang| lang.name().to_string());
1489 (Some(contents), language)
1490 } else {
1491 (None, None)
1492 };
1493
1494 let editor = SerializedEditor {
1495 abs_path,
1496 contents,
1497 language,
1498 mtime,
1499 };
1500 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1501 db.save_serialized_editor(item_id, workspace_id, editor)
1502 .await
1503 .context("failed to save serialized editor")
1504 })
1505 .await
1506 .context("failed to save contents of buffer")?;
1507
1508 Ok(())
1509 }))
1510 }
1511
1512 fn should_serialize(&self, event: &Self::Event) -> bool {
1513 self.should_serialize_buffer()
1514 && matches!(
1515 event,
1516 EditorEvent::Saved
1517 | EditorEvent::DirtyChanged
1518 | EditorEvent::BufferEdited
1519 | EditorEvent::FileHandleChanged
1520 )
1521 }
1522}
1523
1524#[derive(Debug, Default)]
1525struct EditorRestorationData {
1526 entries: HashMap<PathBuf, RestorationData>,
1527}
1528
1529#[derive(Default, Debug)]
1530pub struct RestorationData {
1531 pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1532 pub folds: Vec<Range<Point>>,
1533 pub selections: Vec<Range<Point>>,
1534}
1535
1536impl ProjectItem for Editor {
1537 type Item = Buffer;
1538
1539 fn project_item_kind() -> Option<ProjectItemKind> {
1540 Some(ProjectItemKind("Editor"))
1541 }
1542
1543 fn for_project_item(
1544 project: Entity<Project>,
1545 pane: Option<&Pane>,
1546 buffer: Entity<Buffer>,
1547 window: &mut Window,
1548 cx: &mut Context<Self>,
1549 ) -> Self {
1550 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1551 let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1552
1553 if let Some(buffer_snapshot) = editor.buffer().read(cx).snapshot(cx).as_singleton()
1554 && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1555 && let Some(restoration_data) = Self::project_item_kind()
1556 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1557 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1558 .and_then(|data| {
1559 let file = project::File::from_dyn(buffer.read(cx).file())?;
1560 data.entries.get(&file.abs_path(cx))
1561 })
1562 {
1563 if !restoration_data.folds.is_empty() {
1564 editor.fold_ranges(
1565 clip_ranges(&restoration_data.folds, buffer_snapshot),
1566 false,
1567 window,
1568 cx,
1569 );
1570 }
1571 if !restoration_data.selections.is_empty() {
1572 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1573 s.select_ranges(clip_ranges(&restoration_data.selections, buffer_snapshot));
1574 });
1575 }
1576 let (top_row, offset) = restoration_data.scroll_position;
1577 let anchor = multibuffer_snapshot.anchor_before(Point::new(top_row, 0));
1578 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1579 }
1580
1581 editor
1582 }
1583
1584 fn for_broken_project_item(
1585 abs_path: &Path,
1586 is_local: bool,
1587 e: &anyhow::Error,
1588 window: &mut Window,
1589 cx: &mut App,
1590 ) -> Option<InvalidItemView> {
1591 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1592 }
1593}
1594
1595fn clip_ranges<'a>(
1596 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1597 snapshot: &'a BufferSnapshot,
1598) -> Vec<Range<Point>> {
1599 original
1600 .into_iter()
1601 .map(|range| {
1602 snapshot.clip_point(range.start, Bias::Left)
1603 ..snapshot.clip_point(range.end, Bias::Right)
1604 })
1605 .collect()
1606}
1607
1608impl EventEmitter<SearchEvent> for Editor {}
1609
1610impl Editor {
1611 pub fn update_restoration_data(
1612 &self,
1613 cx: &mut Context<Self>,
1614 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1615 ) {
1616 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1617 return;
1618 }
1619
1620 let editor = cx.entity();
1621 cx.defer(move |cx| {
1622 editor.update(cx, |editor, cx| {
1623 let kind = Editor::project_item_kind()?;
1624 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1625 let buffer = editor.buffer().read(cx).as_singleton()?;
1626 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1627 pane.update(cx, |pane, _| {
1628 let data = pane
1629 .project_item_restoration_data
1630 .entry(kind)
1631 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1632 let data = match data.downcast_mut::<EditorRestorationData>() {
1633 Some(data) => data,
1634 None => {
1635 *data = Box::new(EditorRestorationData::default());
1636 data.downcast_mut::<EditorRestorationData>()
1637 .expect("just written the type downcasted to")
1638 }
1639 };
1640
1641 let data = data.entries.entry(file_abs_path).or_default();
1642 write(data);
1643 Some(())
1644 })
1645 });
1646 });
1647 }
1648}
1649
1650impl SearchableItem for Editor {
1651 type Match = Range<Anchor>;
1652
1653 fn get_matches(&self, _window: &mut Window, _: &mut App) -> (Vec<Range<Anchor>>, SearchToken) {
1654 (
1655 self.background_highlights
1656 .get(&HighlightKey::BufferSearchHighlights)
1657 .map_or(Vec::new(), |(_color, ranges)| {
1658 ranges.iter().cloned().collect()
1659 }),
1660 SearchToken::default(),
1661 )
1662 }
1663
1664 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1665 if self
1666 .clear_background_highlights(HighlightKey::BufferSearchHighlights, cx)
1667 .is_some()
1668 {
1669 cx.emit(SearchEvent::MatchesInvalidated);
1670 }
1671 }
1672
1673 fn update_matches(
1674 &mut self,
1675 matches: &[Range<Anchor>],
1676 active_match_index: Option<usize>,
1677 _token: SearchToken,
1678 _: &mut Window,
1679 cx: &mut Context<Self>,
1680 ) {
1681 let existing_range = self
1682 .background_highlights
1683 .get(&HighlightKey::BufferSearchHighlights)
1684 .map(|(_, range)| range.as_ref());
1685 let updated = existing_range != Some(matches);
1686 self.highlight_background(
1687 HighlightKey::BufferSearchHighlights,
1688 matches,
1689 move |index, theme| {
1690 if active_match_index == Some(*index) {
1691 theme.colors().search_active_match_background
1692 } else {
1693 theme.colors().search_match_background
1694 }
1695 },
1696 cx,
1697 );
1698 if updated {
1699 cx.emit(SearchEvent::MatchesInvalidated);
1700 }
1701 }
1702
1703 fn has_filtered_search_ranges(&mut self) -> bool {
1704 self.has_background_highlights(HighlightKey::SearchWithinRange)
1705 }
1706
1707 fn toggle_filtered_search_ranges(
1708 &mut self,
1709 enabled: Option<FilteredSearchRange>,
1710 _: &mut Window,
1711 cx: &mut Context<Self>,
1712 ) {
1713 if self.has_filtered_search_ranges() {
1714 self.previous_search_ranges = self
1715 .clear_background_highlights(HighlightKey::SearchWithinRange, cx)
1716 .map(|(_, ranges)| ranges)
1717 }
1718
1719 if let Some(range) = enabled {
1720 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1721
1722 if ranges.iter().any(|s| s.start != s.end) {
1723 self.set_search_within_ranges(&ranges, cx);
1724 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1725 && range != FilteredSearchRange::Selection
1726 {
1727 self.set_search_within_ranges(&previous_search_ranges, cx);
1728 }
1729 }
1730 }
1731
1732 fn supported_options(&self) -> SearchOptions {
1733 if self.in_project_search {
1734 SearchOptions {
1735 case: true,
1736 word: true,
1737 regex: true,
1738 replacement: false,
1739 selection: false,
1740 select_all: true,
1741 find_in_results: true,
1742 }
1743 } else {
1744 SearchOptions {
1745 case: true,
1746 word: true,
1747 regex: true,
1748 replacement: true,
1749 selection: true,
1750 select_all: true,
1751 find_in_results: false,
1752 }
1753 }
1754 }
1755
1756 fn query_suggestion(
1757 &mut self,
1758 seed_query_override: Option<SeedQuerySetting>,
1759 window: &mut Window,
1760 cx: &mut Context<Self>,
1761 ) -> String {
1762 let setting = seed_query_override
1763 .unwrap_or_else(|| EditorSettings::get_global(cx).seed_search_query_from_cursor);
1764 let snapshot = self.snapshot(window, cx);
1765 let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1766 let buffer_snapshot = snapshot.buffer_snapshot();
1767
1768 match setting {
1769 SeedQuerySetting::Never => String::new(),
1770 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1771 buffer_snapshot
1772 .text_for_range(selection.start..selection.end)
1773 .collect()
1774 }
1775 SeedQuerySetting::Selection => String::new(),
1776 SeedQuerySetting::Always => {
1777 let (range, kind) = buffer_snapshot
1778 .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1779 if kind == Some(CharKind::Word) {
1780 let text: String = buffer_snapshot.text_for_range(range).collect();
1781 if !text.trim().is_empty() {
1782 return text;
1783 }
1784 }
1785 String::new()
1786 }
1787 }
1788 }
1789
1790 fn activate_match(
1791 &mut self,
1792 index: usize,
1793 matches: &[Range<Anchor>],
1794 _token: SearchToken,
1795 window: &mut Window,
1796 cx: &mut Context<Self>,
1797 ) {
1798 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1799 let range = self.range_for_match(&matches[index]);
1800 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1801 Autoscroll::center()
1802 } else {
1803 Autoscroll::fit()
1804 };
1805 self.change_selections(
1806 SelectionEffects::scroll(autoscroll).from_search(true),
1807 window,
1808 cx,
1809 |s| {
1810 s.select_ranges([range]);
1811 },
1812 )
1813 }
1814
1815 fn select_matches(
1816 &mut self,
1817 matches: &[Self::Match],
1818 _token: SearchToken,
1819 window: &mut Window,
1820 cx: &mut Context<Self>,
1821 ) {
1822 self.unfold_ranges(matches, false, false, cx);
1823 self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1824 s.select_ranges(matches.iter().cloned())
1825 });
1826 }
1827 fn replace(
1828 &mut self,
1829 identifier: &Self::Match,
1830 query: &SearchQuery,
1831 _token: SearchToken,
1832 window: &mut Window,
1833 cx: &mut Context<Self>,
1834 ) {
1835 let text = self.buffer.read(cx);
1836 let text = text.snapshot(cx);
1837 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1838 let text: Cow<_> = if text.len() == 1 {
1839 text.first().cloned().unwrap().into()
1840 } else {
1841 let joined_chunks = text.concat();
1842 joined_chunks.into()
1843 };
1844
1845 if let Some(replacement) = query.replacement_for(&text) {
1846 self.transact(window, cx, |this, _, cx| {
1847 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1848 });
1849 }
1850 }
1851 fn replace_all(
1852 &mut self,
1853 matches: &mut dyn Iterator<Item = &Self::Match>,
1854 query: &SearchQuery,
1855 _token: SearchToken,
1856 window: &mut Window,
1857 cx: &mut Context<Self>,
1858 ) {
1859 let text = self.buffer.read(cx);
1860 let text = text.snapshot(cx);
1861 let mut edits = vec![];
1862
1863 // A regex might have replacement variables so we cannot apply
1864 // the same replacement to all matches
1865 if query.is_regex() {
1866 edits = matches
1867 .filter_map(|m| {
1868 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1869
1870 let text: Cow<_> = if text.len() == 1 {
1871 text.first().cloned().unwrap().into()
1872 } else {
1873 let joined_chunks = text.concat();
1874 joined_chunks.into()
1875 };
1876
1877 query
1878 .replacement_for(&text)
1879 .map(|replacement| (m.clone(), Arc::from(&*replacement)))
1880 })
1881 .collect();
1882 } else if let Some(replacement) = query.replacement().map(Arc::<str>::from) {
1883 edits = matches.map(|m| (m.clone(), replacement.clone())).collect();
1884 }
1885
1886 if !edits.is_empty() {
1887 self.transact(window, cx, |this, _, cx| {
1888 this.edit(edits, cx);
1889 });
1890 }
1891 }
1892
1893 /// Takes the current cursor position and finds the next match in the
1894 /// provided `direction`, the provide `count` number of times, wrapping
1895 /// around if necessary.
1896 fn match_index_for_direction(
1897 &mut self,
1898 matches: &[Range<Anchor>],
1899 current_index: usize,
1900 direction: Direction,
1901 count: usize,
1902 _token: SearchToken,
1903 _: &mut Window,
1904 cx: &mut Context<Self>,
1905 ) -> usize {
1906 if count == 0 {
1907 return current_index;
1908 }
1909
1910 let cursor = if self.selections.disjoint_anchors_arc().len() == 1 {
1911 self.selections.newest_anchor().head()
1912 } else {
1913 matches[current_index].start
1914 };
1915
1916 let buffer = self.buffer().read(cx).snapshot(cx);
1917 let new_idx = match direction {
1918 Direction::Next => matches
1919 .iter()
1920 .position(|m| m.start.cmp(&cursor, &buffer).is_gt())
1921 .unwrap_or(0),
1922 Direction::Prev => matches
1923 .iter()
1924 .rposition(|m| m.end.cmp(&cursor, &buffer).is_lt())
1925 .unwrap_or(matches.len() - 1),
1926 } as isize;
1927
1928 // We'll use `count - 1` because the first jump to the next or previous
1929 // match already happens in the scenario above, when we find the next or
1930 // previous match starting from the cursor position.
1931 let count = count.saturating_sub(1);
1932 let count = match direction {
1933 Direction::Prev => -(count as isize),
1934 Direction::Next => count as isize,
1935 };
1936
1937 let new_idx = (new_idx + count) % matches.len() as isize;
1938 let new_idx = if new_idx.is_negative() {
1939 // We need a `matches.len() - 1` here in case `next_idx` has now been
1940 // set to `0`, otherwise we'd end up returning `matches.len()`, which
1941 // would be out of bounds.
1942 new_idx + (matches.len() - 1) as isize
1943 } else {
1944 new_idx
1945 };
1946 assert!(new_idx < matches.len() as isize);
1947 new_idx as usize
1948 }
1949
1950 fn find_matches(
1951 &mut self,
1952 query: Arc<project::search::SearchQuery>,
1953 _: &mut Window,
1954 cx: &mut Context<Self>,
1955 ) -> Task<Vec<Range<Anchor>>> {
1956 let buffer = self.buffer().read(cx).snapshot(cx);
1957 let search_within_ranges = self
1958 .background_highlights
1959 .get(&HighlightKey::SearchWithinRange)
1960 .map_or(vec![], |(_color, ranges)| {
1961 ranges.iter().cloned().collect::<Vec<_>>()
1962 });
1963
1964 let executor = cx.background_executor().clone();
1965 cx.background_spawn(async move {
1966 let mut ranges = Vec::new();
1967
1968 let search_within_ranges = if search_within_ranges.is_empty() {
1969 vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1970 } else {
1971 search_within_ranges
1972 };
1973 let num_cpus = executor.num_cpus();
1974 for range in search_within_ranges {
1975 for (search_buffer, search_range, deleted_hunk_anchor) in
1976 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1977 {
1978 let query = query.clone();
1979
1980 let mut results = Vec::new();
1981 executor
1982 .scoped(|scope| {
1983 for search_range in chunk_search_range(
1984 search_buffer.text.clone(),
1985 &query,
1986 num_cpus as u32,
1987 search_range,
1988 ) {
1989 let query = query.clone();
1990 let buffer = buffer.clone();
1991
1992 let (tx, rx) = oneshot::channel();
1993 results.push(rx);
1994 scope.spawn(async move {
1995 let chunk_result = query
1996 .search(
1997 search_buffer,
1998 Some(search_range.start..search_range.end),
1999 )
2000 .await
2001 .into_iter()
2002 .filter_map(|match_range| {
2003 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
2004 let start = search_buffer.anchor_after(
2005 search_range.start + match_range.start,
2006 );
2007 let end = search_buffer.anchor_before(
2008 search_range.start + match_range.end,
2009 );
2010 Some(
2011 deleted_hunk_anchor.with_diff_base_anchor(start)
2012 ..deleted_hunk_anchor
2013 .with_diff_base_anchor(end),
2014 )
2015 } else {
2016 let start = search_buffer.anchor_after(
2017 search_range.start + match_range.start,
2018 );
2019 let end = search_buffer.anchor_before(
2020 search_range.start + match_range.end,
2021 );
2022 buffer.anchor_range_in_buffer(start..end)
2023 }
2024 })
2025 .collect::<Vec<_>>();
2026 _ = tx.send(chunk_result);
2027 });
2028 }
2029 })
2030 .await;
2031
2032 for rx in results {
2033 if let Ok(results) = rx.await {
2034 ranges.extend(results);
2035 }
2036 }
2037 }
2038 }
2039
2040 ranges
2041 })
2042 }
2043
2044 fn active_match_index(
2045 &mut self,
2046 direction: Direction,
2047 matches: &[Range<Anchor>],
2048 _token: SearchToken,
2049 _: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) -> Option<usize> {
2052 active_match_index(
2053 direction,
2054 matches,
2055 &self.selections.newest_anchor().head(),
2056 &self.buffer().read(cx).snapshot(cx),
2057 )
2058 }
2059
2060 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
2061 self.expect_bounds_change = self.last_bounds;
2062 }
2063
2064 fn set_search_is_case_sensitive(
2065 &mut self,
2066 case_sensitive: Option<bool>,
2067 _cx: &mut Context<Self>,
2068 ) {
2069 self.select_next_is_case_sensitive = case_sensitive;
2070 }
2071}
2072
2073pub fn active_match_index(
2074 direction: Direction,
2075 ranges: &[Range<Anchor>],
2076 cursor: &Anchor,
2077 buffer: &MultiBufferSnapshot,
2078) -> Option<usize> {
2079 if ranges.is_empty() {
2080 None
2081 } else {
2082 let r = ranges.binary_search_by(|probe| {
2083 if probe.end.cmp(cursor, buffer).is_lt() {
2084 Ordering::Less
2085 } else if probe.start.cmp(cursor, buffer).is_gt() {
2086 Ordering::Greater
2087 } else {
2088 Ordering::Equal
2089 }
2090 });
2091 match direction {
2092 Direction::Prev => match r {
2093 Ok(i) => Some(i),
2094 Err(i) => Some(i.saturating_sub(1)),
2095 },
2096 Direction::Next => match r {
2097 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
2098 },
2099 }
2100 }
2101}
2102
2103/// Opens a path-like target (e.g. `items.rs:100:5`) in the workspace, moving the cursor
2104/// to the one-based row/column if present. Returns whether the target was opened.
2105pub async fn open_resolved_target(
2106 workspace: &WeakEntity<Workspace>,
2107 open_target: &workspace::path_link::OpenTarget,
2108 cx: &mut AsyncWindowContext,
2109) -> Result<bool> {
2110 let path_to_open = open_target.path();
2111 let mut opened_items = workspace
2112 .update_in(cx, |workspace, window, cx| {
2113 workspace.open_paths(
2114 vec![path_to_open.path.clone()],
2115 workspace::OpenOptions {
2116 visible: Some(workspace::OpenVisible::OnlyDirectories),
2117 ..Default::default()
2118 },
2119 None,
2120 window,
2121 cx,
2122 )
2123 })
2124 .context("workspace update")?
2125 .await;
2126 if opened_items.len() != 1 {
2127 debug_panic!(
2128 "Received {} items for one path {path_to_open:?}",
2129 opened_items.len(),
2130 );
2131 }
2132 let Some(opened_item) = opened_items.pop() else {
2133 return Ok(false);
2134 };
2135
2136 if open_target.is_file() {
2137 let Some(opened_item) = opened_item else {
2138 return Ok(false);
2139 };
2140 let opened_item =
2141 opened_item.with_context(|| format!("opening {:?}", path_to_open.path))?;
2142 if let Some(row) = path_to_open.row
2143 && let Some(editor) = opened_item.downcast::<Editor>()
2144 {
2145 let column = path_to_open.column.unwrap_or(0);
2146 editor
2147 .downgrade()
2148 .update_in(cx, |editor, window, cx| {
2149 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2150 let point = buffer.read(cx).snapshot().point_from_external_input(
2151 row.saturating_sub(1),
2152 column.saturating_sub(1),
2153 );
2154 editor.go_to_singleton_buffer_point(point, window, cx);
2155 }
2156 })
2157 .log_err();
2158 }
2159 Ok(true)
2160 } else if open_target.is_dir() {
2161 workspace.update(cx, |workspace, cx| {
2162 workspace.project().update(cx, |_, cx| {
2163 cx.emit(project::Event::ActivateProjectPanel);
2164 })
2165 })?;
2166 Ok(true)
2167 } else {
2168 Ok(false)
2169 }
2170}
2171
2172pub fn entry_label_color(selected: bool) -> Color {
2173 if selected {
2174 Color::Default
2175 } else {
2176 Color::Muted
2177 }
2178}
2179
2180pub fn entry_diagnostic_aware_icon_name_and_color(
2181 diagnostic_severity: Option<DiagnosticSeverity>,
2182) -> Option<(IconName, Color)> {
2183 match diagnostic_severity {
2184 Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
2185 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
2186 _ => None,
2187 }
2188}
2189
2190pub fn entry_diagnostic_aware_icon_decoration_and_color(
2191 diagnostic_severity: Option<DiagnosticSeverity>,
2192) -> Option<(IconDecorationKind, Color)> {
2193 match diagnostic_severity {
2194 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
2195 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
2196 _ => None,
2197 }
2198}
2199
2200pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
2201 let tracked = git_status.index + git_status.worktree;
2202 if git_status.conflict > 0 {
2203 Color::Conflict
2204 } else if tracked.deleted > 0 {
2205 Color::Deleted
2206 } else if tracked.modified > 0 {
2207 Color::Modified
2208 } else if tracked.added > 0 || git_status.untracked > 0 {
2209 Color::Created
2210 } else if ignored {
2211 Color::Ignored
2212 } else {
2213 entry_label_color(selected)
2214 }
2215}
2216
2217fn path_for_buffer<'a>(
2218 buffer: &Entity<MultiBuffer>,
2219 height: usize,
2220 include_filename: bool,
2221 cx: &'a App,
2222) -> Option<Cow<'a, str>> {
2223 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
2224 path_for_file(file, height, include_filename, cx)
2225}
2226
2227fn path_for_file<'a>(
2228 file: &'a Arc<dyn language::File>,
2229 mut height: usize,
2230 include_filename: bool,
2231 cx: &'a App,
2232) -> Option<Cow<'a, str>> {
2233 if project::File::from_dyn(Some(file)).is_none() {
2234 return None;
2235 }
2236
2237 let file = file.as_ref();
2238 // Ensure we always render at least the filename.
2239 height += 1;
2240
2241 let mut prefix = file.path().as_ref();
2242 while height > 0 {
2243 if let Some(parent) = prefix.parent() {
2244 prefix = parent;
2245 height -= 1;
2246 } else {
2247 break;
2248 }
2249 }
2250
2251 // The full_path method allocates, so avoid calling it if height is zero.
2252 if height > 0 {
2253 let mut full_path = file.full_path(cx);
2254 if !include_filename {
2255 if !full_path.pop() {
2256 return None;
2257 }
2258 }
2259 Some(full_path.to_string_lossy().into_owned().into())
2260 } else {
2261 let mut path = file.path().strip_prefix(prefix).ok()?;
2262 if !include_filename {
2263 path = path.parent()?;
2264 }
2265 Some(path.display(file.path_style(cx)))
2266 }
2267}
2268
2269/// Restores serialized buffer contents by overwriting the buffer with saved text.
2270/// This is somewhat wasteful since we load the whole buffer from disk then overwrite it,
2271/// but keeps implementation simple as we don't need to persist all metadata from loading
2272/// (git diff base, etc.).
2273fn restore_serialized_buffer_contents(
2274 buffer: &mut Buffer,
2275 contents: String,
2276 mtime: Option<MTime>,
2277 cx: &mut Context<Buffer>,
2278) {
2279 // If we did restore an mtime, store it on the buffer so that
2280 // the next edit will mark the buffer as dirty/conflicted.
2281 if mtime.is_some() {
2282 buffer.did_reload(buffer.version(), buffer.line_ending(), mtime, cx);
2283 }
2284 buffer.set_text(contents, cx);
2285 if let Some(entry) = buffer.peek_undo_stack() {
2286 buffer.forget_transaction(entry.transaction_id());
2287 }
2288}
2289
2290fn serialize_path_key(path_key: &PathKey) -> proto::PathKey {
2291 proto::PathKey {
2292 sort_prefix: path_key.sort_prefix,
2293 path: path_key.path.as_unix_str().to_owned(),
2294 }
2295}
2296
2297fn deserialize_path_key(path_key: proto::PathKey) -> Option<PathKey> {
2298 Some(PathKey {
2299 sort_prefix: path_key.sort_prefix,
2300 path: RelPath::from_unix_str(&path_key.path).ok()?.into(),
2301 })
2302}
2303
2304fn chunk_search_range(
2305 buffer: BufferSnapshot,
2306 query: &SearchQuery,
2307 num_cpus: u32,
2308 initial_range: Range<BufferOffset>,
2309) -> Box<dyn Iterator<Item = Range<usize>> + 'static> {
2310 let range = initial_range.to_offset(&buffer);
2311 if range.is_empty() {
2312 return Box::new(std::iter::empty());
2313 }
2314
2315 let summary: TextSummary = buffer.text_summary_for_range(initial_range);
2316 let num_chunks = if !query.is_regex() && !query.as_str().contains('\n') {
2317 NonZeroU32::new(summary.lines.row.saturating_add(1).min(num_cpus.max(1)))
2318 } else {
2319 NonZeroU32::new(1)
2320 };
2321
2322 let Some(num_chunks) = num_chunks else {
2323 return Box::new(std::iter::empty());
2324 };
2325
2326 let mut chunk_start = range.start;
2327 let rope = buffer.as_rope().clone();
2328 let range_end = range.end;
2329 let average_chunk_length = summary.len.div_ceil(num_chunks.get() as usize);
2330 Box::new(std::iter::from_fn(move || {
2331 if chunk_start >= range_end {
2332 return None;
2333 }
2334 let candidate_position = chunk_start + average_chunk_length;
2335 let adjusted = rope.ceil_char_boundary(candidate_position);
2336 let mut as_point = rope.offset_to_point(adjusted);
2337 as_point.row += 1;
2338 as_point.column = 0;
2339 let end_offset = buffer.point_to_offset(as_point).min(range_end);
2340 let ret = chunk_start..end_offset;
2341 chunk_start = end_offset;
2342 Some(ret)
2343 }))
2344}
2345
2346/// Decides what to format based on the `format_on_save` settings of the saved buffers.
2347///
2348/// In the modifications modes, only lines with unstaged changes are formatted.
2349/// When no git diff is available for a buffer, `modifications` skips formatting while `modifications_if_available`
2350/// falls back to formatting entire buffers.
2351/// When a diff is available but empty, nothing is formatted in either mode.
2352fn compute_format_target(
2353 buffers: &HashSet<Entity<Buffer>>,
2354 trigger: FormatTrigger,
2355 multi_buffer: &Entity<MultiBuffer>,
2356 git_store: &Entity<GitStore>,
2357 cx: &App,
2358) -> Option<FormatTarget> {
2359 if trigger == FormatTrigger::Manual {
2360 return Some(FormatTarget::Buffers(buffers.clone()));
2361 }
2362
2363 let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
2364 let git_store = git_store.read(cx);
2365
2366 let mut fall_back_to_full_format = false;
2367 let mut modified_ranges: Vec<Range<Point>> = Vec::new();
2368
2369 for buffer_entity in buffers.iter() {
2370 let buffer = buffer_entity.read(cx);
2371 let settings = LanguageSettings::for_buffer(buffer, cx);
2372 match settings.format_on_save {
2373 FormatOnSave::On | FormatOnSave::Off => {
2374 return Some(FormatTarget::Buffers(buffers.clone()));
2375 }
2376 FormatOnSave::Modifications | FormatOnSave::ModificationsIfAvailable => {}
2377 }
2378
2379 let Some(diff_snapshot) = git_store
2380 .get_unstaged_diff(buffer.remote_id(), cx)
2381 .map(|diff| diff.read(cx).snapshot(cx))
2382 else {
2383 if settings.format_on_save == FormatOnSave::ModificationsIfAvailable {
2384 fall_back_to_full_format = true;
2385 }
2386 continue;
2387 };
2388
2389 let anchor_ranges = compute_modified_ranges(&buffer.snapshot(), &diff_snapshot);
2390 let flat_anchors = anchor_ranges
2391 .iter()
2392 .flat_map(|range| [range.start, range.end])
2393 .collect::<Vec<_>>();
2394 let multi_buffer_anchors =
2395 multi_buffer_snapshot.text_anchors_to_visible_anchors(flat_anchors);
2396 for pair in multi_buffer_anchors.chunks_exact(2) {
2397 let (Some(start), Some(end)) = (&pair[0], &pair[1]) else {
2398 continue;
2399 };
2400 modified_ranges
2401 .push(start.to_point(&multi_buffer_snapshot)..end.to_point(&multi_buffer_snapshot));
2402 }
2403 }
2404
2405 if fall_back_to_full_format {
2406 Some(FormatTarget::Buffers(buffers.clone()))
2407 } else if modified_ranges.is_empty() {
2408 None
2409 } else {
2410 Some(FormatTarget::Ranges(modified_ranges))
2411 }
2412}
2413
2414/// Computes the buffer ranges that have unstaged changes, expanded to full lines and
2415/// with adjacent hunks merged, for use with format-on-save. An empty result means the
2416/// buffer has no formatable modifications.
2417fn compute_modified_ranges(
2418 buffer_snapshot: &language::BufferSnapshot,
2419 diff_snapshot: &buffer_diff::BufferDiffSnapshot,
2420) -> Vec<Range<text::Anchor>> {
2421 let mut merged: Vec<Range<text::Anchor>> = Vec::new();
2422 for hunk in diff_snapshot.hunks(buffer_snapshot) {
2423 let range = hunk.buffer_range;
2424 if range.start.cmp(&range.end, buffer_snapshot).is_eq() {
2425 // Deletion-only hunks produce no buffer content to format.
2426 continue;
2427 }
2428 let start_point = range.start.to_point(buffer_snapshot);
2429 let end_point = range.end.to_point(buffer_snapshot);
2430 let start_row = start_point.row;
2431 let end_row = if end_point.column == 0 && end_point.row > start_point.row {
2432 end_point.row - 1
2433 } else {
2434 end_point.row
2435 };
2436 let line_start = text::Point::new(start_row, 0);
2437 let line_end = text::Point::new(end_row, buffer_snapshot.line_len(end_row));
2438 let expanded =
2439 buffer_snapshot.anchor_before(line_start)..buffer_snapshot.anchor_after(line_end);
2440
2441 if let Some(last) = merged.last_mut() {
2442 let last_end_point = last.end.to_point(buffer_snapshot);
2443 if start_row <= last_end_point.row + 1 {
2444 if expanded.end.to_point(buffer_snapshot) > last_end_point {
2445 last.end = expanded.end;
2446 }
2447 continue;
2448 }
2449 }
2450 merged.push(expanded);
2451 }
2452 merged
2453}
2454
2455#[cfg(test)]
2456mod tests {
2457 use crate::editor_tests::init_test;
2458 use fs::Fs;
2459 use workspace::MultiWorkspace;
2460
2461 use super::*;
2462 use fs::MTime;
2463 use gpui::{App, VisualTestContext};
2464 use language::TestFile;
2465 use project::FakeFs;
2466 use serde_json::json;
2467 use std::path::{Path, PathBuf};
2468 use util::{path, paths::PathWithPosition, rel_path::RelPath};
2469 use workspace::path_link::{OpenTarget, OpenTargetFoundBy};
2470
2471 #[gpui::test]
2472 fn test_path_for_file(cx: &mut App) {
2473 let file: Arc<dyn language::File> = Arc::new(TestFile {
2474 path: RelPath::empty_arc(),
2475 root_name: String::new(),
2476 local_root: None,
2477 });
2478 assert_eq!(path_for_file(&file, 0, false, cx), None);
2479 }
2480
2481 #[gpui::test]
2482 fn test_chunk_search_range_multi_line(cx: &mut App) {
2483 let text = "line one\nline two\nline three\nline four\nline five\nline six\n";
2484 let buffer = cx.new(|cx| Buffer::local(text, cx));
2485 let snapshot = buffer.read(cx).snapshot();
2486
2487 let chunks = chunk_search_range_for_test(&snapshot, "line", 4, 0..text.len());
2488
2489 assert_chunks_are_contiguous(&chunks, 0..text.len());
2490 assert!(
2491 chunks.len() <= 4,
2492 "got {} chunks, expected <= num_cpus (4)",
2493 chunks.len()
2494 );
2495 for chunk in &chunks {
2496 let end = chunk.end;
2497 assert!(
2498 end == text.len() || text.as_bytes()[end - 1] == b'\n',
2499 "chunk ending at {end} is not a line boundary",
2500 );
2501 }
2502 }
2503
2504 #[gpui::test]
2505 fn test_chunk_search_range_single_line(cx: &mut App) {
2506 let text = "hello world hello again";
2507 let buffer = cx.new(|cx| Buffer::local(text, cx));
2508 let snapshot = buffer.read(cx).snapshot();
2509
2510 let chunks = chunk_search_range_for_test(&snapshot, "hello", 4, 0..text.len());
2511 assert_chunks_are_contiguous(&chunks, 0..text.len());
2512 }
2513
2514 #[gpui::test]
2515 fn test_chunk_search_range_empty_range(cx: &mut App) {
2516 let buffer = cx.new(|cx| Buffer::local("hello world", cx));
2517 let snapshot = buffer.read(cx).snapshot();
2518
2519 let chunks = chunk_search_range_for_test(&snapshot, "hello", 4, 5..5);
2520 assert!(chunks.is_empty());
2521 }
2522
2523 #[gpui::test]
2524 fn test_chunk_search_range_does_not_start_at_zero(cx: &mut App) {
2525 let line = "abcdefghij\n";
2526 let text = line.repeat(20);
2527 let buffer = cx.new(|cx| Buffer::local(text.clone(), cx));
2528 let snapshot = buffer.read(cx).snapshot();
2529
2530 let start = line.len() * 7;
2531 let end = line.len() * 14;
2532 let chunks = chunk_search_range_for_test(&snapshot, "abc", 4, start..end);
2533
2534 assert_chunks_are_contiguous(&chunks, start..end);
2535 }
2536
2537 fn chunk_search_range_for_test(
2538 snapshot: &language::BufferSnapshot,
2539 query: &str,
2540 num_cpus: u32,
2541 range: Range<usize>,
2542 ) -> Vec<Range<usize>> {
2543 let query = SearchQuery::text(
2544 query,
2545 false,
2546 false,
2547 false,
2548 Default::default(),
2549 Default::default(),
2550 false,
2551 None,
2552 )
2553 .unwrap();
2554 chunk_search_range(
2555 snapshot.text.clone(),
2556 &query,
2557 num_cpus,
2558 BufferOffset(range.start)..BufferOffset(range.end),
2559 )
2560 .collect()
2561 }
2562
2563 #[track_caller]
2564 fn assert_chunks_are_contiguous(chunks: &[Range<usize>], expected: Range<usize>) {
2565 assert!(!chunks.is_empty(), "expected at least one chunk");
2566 assert_eq!(
2567 chunks.first().unwrap().start,
2568 expected.start,
2569 "first chunk does not start at {}",
2570 expected.start
2571 );
2572 assert_eq!(
2573 chunks.last().unwrap().end,
2574 expected.end,
2575 "last chunk does not end at {}",
2576 expected.end
2577 );
2578 for chunk in chunks {
2579 assert!(chunk.start < chunk.end, "empty chunk: {:?}", chunk);
2580 }
2581 for window in chunks.windows(2) {
2582 assert_eq!(
2583 window[0].end, window[1].start,
2584 "gap or overlap between chunks {:?} and {:?}",
2585 window[0], window[1],
2586 );
2587 }
2588 }
2589
2590 #[gpui::test]
2591 async fn test_suggested_filename_uses_language_extension_for_untitled_buffer(
2592 cx: &mut gpui::TestAppContext,
2593 ) {
2594 init_test(cx, |_| {});
2595
2596 let buffer = cx.update(|cx| {
2597 cx.new(|cx| Buffer::local("", cx).with_language(languages::rust_lang(), cx))
2598 });
2599 let (editor, cx) =
2600 cx.add_window_view(|window, cx| Editor::for_buffer(buffer, None, window, cx));
2601
2602 editor.read_with(cx, |editor, cx| {
2603 assert_eq!(editor.suggested_filename(cx).as_ref(), "untitled.rs");
2604 });
2605 }
2606
2607 #[gpui::test]
2608 async fn test_suggested_filename_appends_extension_to_content_title(
2609 cx: &mut gpui::TestAppContext,
2610 ) {
2611 init_test(cx, |_| {});
2612
2613 let buffer = cx.update(|cx| {
2614 cx.new(|cx| {
2615 Buffer::local("sadsdsads\nmore text", cx).with_language(languages::rust_lang(), cx)
2616 })
2617 });
2618 let (editor, cx) =
2619 cx.add_window_view(|window, cx| Editor::for_buffer(buffer, None, window, cx));
2620
2621 editor.read_with(cx, |editor, cx| {
2622 assert_eq!(editor.tab_content_text(0, cx).as_ref(), "sadsdsads");
2623 assert_eq!(editor.suggested_filename(cx).as_ref(), "sadsdsads.rs");
2624 });
2625 }
2626
2627 #[gpui::test]
2628 async fn test_suggested_filename_does_not_duplicate_extension(cx: &mut gpui::TestAppContext) {
2629 init_test(cx, |_| {});
2630
2631 let buffer = cx.update(|cx| {
2632 cx.new(|cx| {
2633 Buffer::local("main.rs\nfn main() {}", cx).with_language(languages::rust_lang(), cx)
2634 })
2635 });
2636 let (editor, cx) =
2637 cx.add_window_view(|window, cx| Editor::for_buffer(buffer, None, window, cx));
2638
2639 editor.read_with(cx, |editor, cx| {
2640 assert_eq!(editor.suggested_filename(cx).as_ref(), "main.rs");
2641 });
2642 }
2643
2644 #[gpui::test]
2645 async fn test_suggested_filename_keeps_content_title_for_plain_text(
2646 cx: &mut gpui::TestAppContext,
2647 ) {
2648 init_test(cx, |_| {});
2649
2650 let buffer = cx.update(|cx| {
2651 cx.new(|cx| {
2652 Buffer::local("shopping list\nmilk", cx)
2653 .with_language(language::PLAIN_TEXT.clone(), cx)
2654 })
2655 });
2656 let (editor, cx) =
2657 cx.add_window_view(|window, cx| Editor::for_buffer(buffer, None, window, cx));
2658
2659 editor.read_with(cx, |editor, cx| {
2660 assert_eq!(editor.suggested_filename(cx).as_ref(), "shopping list");
2661 });
2662 }
2663
2664 #[gpui::test]
2665 async fn test_suggested_filename_keeps_content_title_without_language(
2666 cx: &mut gpui::TestAppContext,
2667 ) {
2668 init_test(cx, |_| {});
2669
2670 let buffer = cx.update(|cx| cx.new(|cx| Buffer::local("shopping list\nmilk", cx)));
2671 let (editor, cx) =
2672 cx.add_window_view(|window, cx| Editor::for_buffer(buffer, None, window, cx));
2673
2674 editor.read_with(cx, |editor, cx| {
2675 assert_eq!(editor.suggested_filename(cx).as_ref(), "shopping list");
2676 });
2677 }
2678
2679 async fn deserialize_editor(
2680 item_id: ItemId,
2681 workspace_id: WorkspaceId,
2682 workspace: Entity<Workspace>,
2683 project: Entity<Project>,
2684 cx: &mut VisualTestContext,
2685 ) -> Entity<Editor> {
2686 workspace
2687 .update_in(cx, |workspace, window, cx| {
2688 let pane = workspace.active_pane();
2689 pane.update(cx, |_, cx| {
2690 Editor::deserialize(
2691 project.clone(),
2692 workspace.weak_handle(),
2693 workspace_id,
2694 item_id,
2695 window,
2696 cx,
2697 )
2698 })
2699 })
2700 .await
2701 .unwrap()
2702 }
2703
2704 #[gpui::test]
2705 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2706 init_test(cx, |_| {});
2707
2708 let fs = FakeFs::new(cx.executor());
2709 fs.insert_file(path!("/file.rs"), Default::default()).await;
2710
2711 // Test case 1: Deserialize with path and contents
2712 {
2713 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2714 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2715 MultiWorkspace::test_new(project.clone(), window, cx)
2716 });
2717 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2718 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2719 let workspace_id = db.next_id().await.unwrap();
2720 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2721 let item_id = 1234 as ItemId;
2722 let mtime = fs
2723 .metadata(Path::new(path!("/file.rs")))
2724 .await
2725 .unwrap()
2726 .unwrap()
2727 .mtime;
2728
2729 let serialized_editor = SerializedEditor {
2730 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2731 contents: Some("fn main() {}".to_string()),
2732 language: Some("Rust".to_string()),
2733 mtime: Some(mtime),
2734 };
2735
2736 editor_db
2737 .save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2738 .await
2739 .unwrap();
2740
2741 let deserialized =
2742 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2743
2744 deserialized.update(cx, |editor, cx| {
2745 assert_eq!(editor.text(cx), "fn main() {}");
2746 assert!(editor.is_dirty(cx));
2747 assert!(!editor.has_conflict(cx));
2748 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2749 assert!(buffer.file().is_some());
2750 });
2751 }
2752
2753 // Test case 2: Deserialize with only path
2754 {
2755 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2756 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2757 MultiWorkspace::test_new(project.clone(), window, cx)
2758 });
2759 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2760 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2761 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2762
2763 let workspace_id = db.next_id().await.unwrap();
2764
2765 let item_id = 5678 as ItemId;
2766 let serialized_editor = SerializedEditor {
2767 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2768 contents: None,
2769 language: None,
2770 mtime: None,
2771 };
2772
2773 editor_db
2774 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2775 .await
2776 .unwrap();
2777
2778 let deserialized =
2779 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2780
2781 deserialized.update(cx, |editor, cx| {
2782 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2783 assert!(!editor.is_dirty(cx));
2784 assert!(!editor.has_conflict(cx));
2785
2786 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2787 assert!(buffer.file().is_some());
2788 });
2789 }
2790
2791 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2792 {
2793 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2794 // Add Rust to the language, so that we can restore the language of the buffer
2795 project.read_with(cx, |project, _| {
2796 project.languages().add(languages::rust_lang())
2797 });
2798
2799 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2800 MultiWorkspace::test_new(project.clone(), window, cx)
2801 });
2802 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2803 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2804 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2805
2806 let workspace_id = db.next_id().await.unwrap();
2807
2808 let item_id = 9012 as ItemId;
2809 let serialized_editor = SerializedEditor {
2810 abs_path: None,
2811 contents: Some("hello".to_string()),
2812 language: Some("Rust".to_string()),
2813 mtime: None,
2814 };
2815
2816 editor_db
2817 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2818 .await
2819 .unwrap();
2820
2821 let deserialized =
2822 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2823
2824 deserialized.update(cx, |editor, cx| {
2825 assert_eq!(editor.text(cx), "hello");
2826 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2827
2828 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2829 assert_eq!(
2830 buffer.language().map(|lang| lang.name()),
2831 Some("Rust".into())
2832 ); // Language should be set to Rust
2833 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2834 });
2835 }
2836
2837 // Test case 4: Deserialize with path, content, and old mtime
2838 {
2839 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2840 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2841 MultiWorkspace::test_new(project.clone(), window, cx)
2842 });
2843 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2844 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2845 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2846
2847 let workspace_id = db.next_id().await.unwrap();
2848
2849 let item_id = 9345 as ItemId;
2850 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2851 let serialized_editor = SerializedEditor {
2852 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2853 contents: Some("fn main() {}".to_string()),
2854 language: Some("Rust".to_string()),
2855 mtime: Some(old_mtime),
2856 };
2857
2858 editor_db
2859 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2860 .await
2861 .unwrap();
2862
2863 let deserialized =
2864 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2865
2866 deserialized.update(cx, |editor, cx| {
2867 assert_eq!(editor.text(cx), "fn main() {}");
2868 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2869 });
2870 }
2871
2872 // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2873 {
2874 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2875 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2876 MultiWorkspace::test_new(project.clone(), window, cx)
2877 });
2878 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2879 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2880 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2881
2882 let workspace_id = db.next_id().await.unwrap();
2883
2884 let item_id = 10000 as ItemId;
2885 let serialized_editor = SerializedEditor {
2886 abs_path: None,
2887 contents: None,
2888 language: None,
2889 mtime: None,
2890 };
2891
2892 editor_db
2893 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2894 .await
2895 .unwrap();
2896
2897 let deserialized =
2898 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2899
2900 deserialized.update(cx, |editor, cx| {
2901 assert_eq!(editor.text(cx), "");
2902 assert!(!editor.is_dirty(cx));
2903 assert!(!editor.has_conflict(cx));
2904
2905 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2906 assert!(buffer.file().is_none());
2907 });
2908 }
2909
2910 // Test case 6: Deserialize with path and contents in an empty workspace (no worktree)
2911 // This tests the hot-exit scenario where a file is opened in an empty workspace
2912 // and has unsaved changes that should be restored.
2913 {
2914 let fs = FakeFs::new(cx.executor());
2915 fs.insert_file(path!("/standalone.rs"), "original content".into())
2916 .await;
2917
2918 // Create an empty project with no worktrees
2919 let project = Project::test(fs.clone(), [], cx).await;
2920 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2921 MultiWorkspace::test_new(project.clone(), window, cx)
2922 });
2923 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2924 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2925 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2926
2927 let workspace_id = db.next_id().await.unwrap();
2928 let item_id = 11000 as ItemId;
2929
2930 let mtime = fs
2931 .metadata(Path::new(path!("/standalone.rs")))
2932 .await
2933 .unwrap()
2934 .unwrap()
2935 .mtime;
2936
2937 // Simulate serialized state: file with unsaved changes
2938 let serialized_editor = SerializedEditor {
2939 abs_path: Some(PathBuf::from(path!("/standalone.rs"))),
2940 contents: Some("modified content".to_string()),
2941 language: Some("Rust".to_string()),
2942 mtime: Some(mtime),
2943 };
2944
2945 editor_db
2946 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2947 .await
2948 .unwrap();
2949
2950 let deserialized =
2951 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2952
2953 deserialized.update(cx, |editor, cx| {
2954 // The editor should have the serialized contents, not the disk contents
2955 assert_eq!(editor.text(cx), "modified content");
2956 assert!(editor.is_dirty(cx));
2957 assert!(!editor.has_conflict(cx));
2958
2959 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2960 assert!(buffer.file().is_some());
2961 });
2962 }
2963 }
2964
2965 // Verify that renaming an open file emits EditorEvent::FileHandleChanged so that
2966 // the workspace re-serializes the editor with the updated path.
2967 #[gpui::test]
2968 async fn test_file_handle_changed_on_rename(cx: &mut gpui::TestAppContext) {
2969 use serde_json::json;
2970 use std::cell::RefCell;
2971 use std::rc::Rc;
2972 use util::rel_path::rel_path;
2973
2974 init_test(cx, |_| {});
2975
2976 let fs = FakeFs::new(cx.executor());
2977 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}" }))
2978 .await;
2979
2980 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
2981
2982 let buffer = project
2983 .update(cx, |project, cx| {
2984 project.open_local_buffer(path!("/root/file.rs"), cx)
2985 })
2986 .await
2987 .unwrap();
2988
2989 let received_file_handle_changed = Rc::new(RefCell::new(false));
2990 let (editor, cx) = cx.add_window_view({
2991 let project = project.clone();
2992 let received_file_handle_changed = received_file_handle_changed.clone();
2993 move |window, cx| {
2994 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2995 editor.set_should_serialize(true, cx);
2996 let entity = cx.entity();
2997 cx.subscribe_in(&entity, window, move |_, _, event: &EditorEvent, _, _| {
2998 if matches!(event, EditorEvent::FileHandleChanged) {
2999 *received_file_handle_changed.borrow_mut() = true;
3000 }
3001 })
3002 .detach();
3003 editor
3004 }
3005 });
3006
3007 cx.run_until_parked();
3008
3009 let (entry_id, worktree_id) = project.update(cx, |project, cx| {
3010 let worktree = project.worktrees(cx).next().unwrap();
3011 let worktree = worktree.read(cx);
3012 let entry = worktree.entry_for_path(rel_path("file.rs")).unwrap();
3013 (entry.id, worktree.id())
3014 });
3015
3016 project
3017 .update(cx, |project, cx| {
3018 project.rename_entry(entry_id, (worktree_id, rel_path("renamed.rs")).into(), cx)
3019 })
3020 .await
3021 .unwrap();
3022
3023 cx.run_until_parked();
3024
3025 assert!(
3026 *received_file_handle_changed.borrow(),
3027 "EditorEvent::FileHandleChanged must be emitted when the open file is renamed"
3028 );
3029
3030 editor.update(cx, |editor, cx| {
3031 let buffer = editor.buffer().read(cx).as_singleton().unwrap();
3032 let path = buffer.read(cx).file().unwrap().path();
3033 assert!(
3034 path.as_std_path().ends_with("renamed.rs"),
3035 "buffer path must reflect the renamed file, got {path:?}"
3036 );
3037 });
3038 }
3039
3040 // Regression test for https://github.com/zed-industries/zed/issues/35947
3041 // Verifies that deserializing a non-worktree editor does not add the item
3042 // to any pane as a side effect.
3043 #[gpui::test]
3044 async fn test_deserialize_non_worktree_file_does_not_add_to_pane(
3045 cx: &mut gpui::TestAppContext,
3046 ) {
3047 init_test(cx, |_| {});
3048
3049 let fs = FakeFs::new(cx.executor());
3050 fs.insert_tree(path!("/outside"), json!({ "settings.json": "{}" }))
3051 .await;
3052
3053 // Project with a different root — settings.json is NOT in any worktree
3054 let project = Project::test(fs.clone(), [], cx).await;
3055 let (multi_workspace, cx) =
3056 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3057 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3058 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
3059 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
3060
3061 let workspace_id = db.next_id().await.unwrap();
3062 let item_id = 99999 as ItemId;
3063
3064 let serialized_editor = SerializedEditor {
3065 abs_path: Some(PathBuf::from(path!("/outside/settings.json"))),
3066 contents: None,
3067 language: None,
3068 mtime: None,
3069 };
3070
3071 editor_db
3072 .save_serialized_editor(item_id, workspace_id, serialized_editor)
3073 .await
3074 .unwrap();
3075
3076 // Count items in all panes before deserialization
3077 let pane_items_before = workspace.read_with(cx, |workspace, cx| {
3078 workspace
3079 .panes()
3080 .iter()
3081 .map(|pane| pane.read(cx).items_len())
3082 .sum::<usize>()
3083 });
3084
3085 let deserialized =
3086 deserialize_editor(item_id, workspace_id, workspace.clone(), project, cx).await;
3087
3088 cx.run_until_parked();
3089
3090 // The editor should exist and have the file
3091 deserialized.update(cx, |editor, cx| {
3092 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
3093 assert!(buffer.file().is_some());
3094 });
3095
3096 // No items should have been added to any pane as a side effect
3097 let pane_items_after = workspace.read_with(cx, |workspace, cx| {
3098 workspace
3099 .panes()
3100 .iter()
3101 .map(|pane| pane.read(cx).items_len())
3102 .sum::<usize>()
3103 });
3104
3105 assert_eq!(
3106 pane_items_before, pane_items_after,
3107 "Editor::deserialize should not add items to panes as a side effect"
3108 );
3109 }
3110
3111 #[gpui::test]
3112 async fn test_open_resolved_target_at_non_ascii_column(cx: &mut gpui::TestAppContext) {
3113 init_test(cx, |_| {});
3114
3115 let fs = FakeFs::new(cx.executor());
3116 fs.insert_tree(
3117 path!("/root"),
3118 json!({
3119 "src": {
3120 "main.rs": "first\naéøbc\n",
3121 },
3122 }),
3123 )
3124 .await;
3125
3126 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
3127 let (multi_workspace, cx) =
3128 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3129 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3130
3131 let open_target = OpenTarget::Path(
3132 PathWithPosition {
3133 path: PathBuf::from(path!("/root/src/main.rs")),
3134 row: Some(2),
3135 column: Some(4),
3136 },
3137 false,
3138 OpenTargetFoundBy::BackgroundPathResolution,
3139 );
3140
3141 let opened = workspace
3142 .update_in(cx, |_, window, cx| {
3143 cx.spawn_in(window, async move |workspace, cx| {
3144 open_resolved_target(&workspace, &open_target, cx).await
3145 })
3146 })
3147 .await
3148 .expect("opening the target should succeed");
3149 assert!(opened, "target should open as a file");
3150
3151 let editor = workspace.read_with(cx, |workspace, cx| {
3152 workspace
3153 .active_item(cx)
3154 .and_then(|item| item.act_as::<Editor>(cx))
3155 .expect("active item should be an editor")
3156 });
3157 let cursor = editor.update_in(cx, |editor, _, cx| {
3158 editor
3159 .selections
3160 .newest::<language::Point>(&editor.display_snapshot(cx))
3161 .head()
3162 });
3163 // Column 4 is the fourth character of `aéøbc` (the `b`), which starts at byte 5.
3164 assert_eq!(cursor, language::Point::new(1, 5));
3165 }
3166
3167 #[gpui::test]
3168 fn test_compute_modified_ranges_git_diff(cx: &mut gpui::TestAppContext) {
3169 let base_text = "line0\nline1\nline2\nline3\nline4\nline5\nline6\n";
3170 // Modify line1 and line5 to create two non-adjacent hunks.
3171 let buffer_text = "line0\nMOD1\nline2\nline3\nline4\nMOD5\nline6\n";
3172
3173 let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
3174 let diff_snapshot = buffer.update(cx, |buffer, cx| {
3175 let diff = cx.new(|cx| {
3176 buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
3177 });
3178 diff.read(cx).snapshot(cx)
3179 });
3180
3181 let ranges = buffer.update(cx, |buffer, _cx| {
3182 compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
3183 });
3184
3185 assert_eq!(ranges.len(), 2, "expected 2 non-adjacent ranges");
3186
3187 buffer.update(cx, |buffer, _cx| {
3188 let text_snapshot: &text::BufferSnapshot = buffer;
3189 let r0 = ranges[0].start.to_point(text_snapshot)..ranges[0].end.to_point(text_snapshot);
3190 let r1 = ranges[1].start.to_point(text_snapshot)..ranges[1].end.to_point(text_snapshot);
3191 assert_eq!(r0.start.row, 1, "first hunk should start at row 1");
3192 assert_eq!(r0.end.row, 1, "first hunk should end at row 1");
3193 assert_eq!(r1.start.row, 5, "second hunk should start at row 5");
3194 assert_eq!(r1.end.row, 5, "second hunk should end at row 5");
3195 });
3196 }
3197
3198 #[gpui::test]
3199 fn test_compute_modified_ranges_unchanged_buffer(cx: &mut gpui::TestAppContext) {
3200 let buffer_text = "line0\nline1\nline2\n";
3201 let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
3202 let diff_snapshot = buffer.update(cx, |buffer, cx| {
3203 let diff = cx.new(|cx| {
3204 buffer_diff::BufferDiff::new_with_base_text(
3205 buffer_text,
3206 &buffer.text_snapshot(),
3207 cx,
3208 )
3209 });
3210 diff.read(cx).snapshot(cx)
3211 });
3212
3213 let ranges = buffer.update(cx, |buffer, _cx| {
3214 compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
3215 });
3216
3217 assert_eq!(
3218 ranges,
3219 Vec::new(),
3220 "buffer that matches its diff base should produce no modified ranges"
3221 );
3222 }
3223
3224 #[gpui::test]
3225 fn test_compute_modified_ranges_deletion_only(cx: &mut gpui::TestAppContext) {
3226 let base_text = "line0\nline1\nline2\n";
3227 // Buffer has line1 deleted (pure deletion).
3228 let buffer_text = "line0\nline2\n";
3229
3230 let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
3231 let diff_snapshot = buffer.update(cx, |buffer, cx| {
3232 let diff = cx.new(|cx| {
3233 buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
3234 });
3235 diff.read(cx).snapshot(cx)
3236 });
3237
3238 // Verify the diff has a deletion hunk.
3239 let hunk_count = buffer.update(cx, |buffer, _cx| {
3240 let text_snapshot: &text::BufferSnapshot = buffer;
3241 diff_snapshot.hunks(text_snapshot).count()
3242 });
3243 assert!(hunk_count > 0, "diff should have hunks");
3244
3245 let ranges = buffer.update(cx, |buffer, _cx| {
3246 compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
3247 });
3248
3249 assert_eq!(
3250 ranges,
3251 Vec::new(),
3252 "deletion-only hunks should be skipped, leaving no ranges"
3253 );
3254 }
3255
3256 #[gpui::test]
3257 fn test_compute_modified_ranges_adjacent_hunks(cx: &mut gpui::TestAppContext) {
3258 let base_text = "line0\nline1\nline2\nline3\nline4\n";
3259 // Modify lines 2 and 3 which are adjacent; they should merge into one range.
3260 let buffer_text = "line0\nline1\nMOD2\nMOD3\nline4\n";
3261
3262 let buffer = cx.new(|cx| language::Buffer::local(buffer_text, cx));
3263 let diff_snapshot = buffer.update(cx, |buffer, cx| {
3264 let diff = cx.new(|cx| {
3265 buffer_diff::BufferDiff::new_with_base_text(base_text, &buffer.text_snapshot(), cx)
3266 });
3267 diff.read(cx).snapshot(cx)
3268 });
3269
3270 let ranges = buffer.update(cx, |buffer, _cx| {
3271 compute_modified_ranges(&buffer.snapshot(), &diff_snapshot)
3272 });
3273
3274 assert_eq!(
3275 ranges.len(),
3276 1,
3277 "adjacent hunks (rows 2 and 3) should be merged into one range"
3278 );
3279 buffer.update(cx, |buffer, _cx| {
3280 let text_snapshot: &text::BufferSnapshot = buffer;
3281 let r = ranges[0].start.to_point(text_snapshot)..ranges[0].end.to_point(text_snapshot);
3282 assert_eq!(r.start.row, 2, "merged range should start at row 2");
3283 assert_eq!(r.end.row, 3, "merged range should end at row 3");
3284 });
3285 }
3286}
3287