hunk_diff.rs

   1use collections::{hash_map, HashMap, HashSet};
   2use git::diff::DiffHunkStatus;
   3use gpui::{Action, AnchorCorner, AppContext, CursorStyle, Hsla, Model, MouseButton, Task, View};
   4use language::{Buffer, BufferId, Point};
   5use multi_buffer::{
   6    Anchor, AnchorRangeExt, ExcerptRange, MultiBuffer, MultiBufferDiffHunk, MultiBufferRow,
   7    MultiBufferSnapshot, ToPoint,
   8};
   9use std::{ops::Range, sync::Arc};
  10use text::OffsetRangeExt;
  11use ui::{
  12    prelude::*, ActiveTheme, ContextMenu, IconButtonShape, InteractiveElement, IntoElement,
  13    ParentElement, PopoverMenu, Styled, Tooltip, ViewContext, VisualContext,
  14};
  15use util::RangeExt;
  16use workspace::Item;
  17
  18use crate::{
  19    editor_settings::CurrentLineHighlight, hunk_status, hunks_for_selections, ApplyDiffHunk,
  20    BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, DiffRowHighlight, DisplayRow,
  21    DisplaySnapshot, Editor, EditorElement, ExpandAllHunkDiffs, GoToHunk, GoToPrevHunk, RevertFile,
  22    RevertSelectedHunks, ToDisplayPoint, ToggleHunkDiff,
  23};
  24
  25#[derive(Debug, Clone)]
  26pub(super) struct HoveredHunk {
  27    pub multi_buffer_range: Range<Anchor>,
  28    pub status: DiffHunkStatus,
  29    pub diff_base_byte_range: Range<usize>,
  30}
  31
  32#[derive(Debug, Default)]
  33pub(super) struct ExpandedHunks {
  34    pub(crate) hunks: Vec<ExpandedHunk>,
  35    diff_base: HashMap<BufferId, DiffBaseBuffer>,
  36    hunk_update_tasks: HashMap<Option<BufferId>, Task<()>>,
  37    expand_all: bool,
  38}
  39
  40#[derive(Debug, Clone)]
  41pub(super) struct ExpandedHunk {
  42    pub blocks: Vec<CustomBlockId>,
  43    pub hunk_range: Range<Anchor>,
  44    pub diff_base_byte_range: Range<usize>,
  45    pub status: DiffHunkStatus,
  46    pub folded: bool,
  47}
  48
  49#[derive(Debug)]
  50struct DiffBaseBuffer {
  51    buffer: Model<Buffer>,
  52    diff_base_version: usize,
  53}
  54
  55#[derive(Debug, Clone, PartialEq, Eq)]
  56pub enum DisplayDiffHunk {
  57    Folded {
  58        display_row: DisplayRow,
  59    },
  60
  61    Unfolded {
  62        diff_base_byte_range: Range<usize>,
  63        display_row_range: Range<DisplayRow>,
  64        multi_buffer_range: Range<Anchor>,
  65        status: DiffHunkStatus,
  66    },
  67}
  68
  69impl ExpandedHunks {
  70    pub fn hunks(&self, include_folded: bool) -> impl Iterator<Item = &ExpandedHunk> {
  71        self.hunks
  72            .iter()
  73            .filter(move |hunk| include_folded || !hunk.folded)
  74    }
  75}
  76
  77impl Editor {
  78    pub fn set_expand_all_diff_hunks(&mut self) {
  79        self.expanded_hunks.expand_all = true;
  80    }
  81
  82    pub(super) fn toggle_hovered_hunk(
  83        &mut self,
  84        hovered_hunk: &HoveredHunk,
  85        cx: &mut ViewContext<Editor>,
  86    ) {
  87        let editor_snapshot = self.snapshot(cx);
  88        if let Some(diff_hunk) = to_diff_hunk(hovered_hunk, &editor_snapshot.buffer_snapshot) {
  89            self.toggle_hunks_expanded(vec![diff_hunk], cx);
  90            self.change_selections(None, cx, |selections| selections.refresh());
  91        }
  92    }
  93
  94    pub fn toggle_hunk_diff(&mut self, _: &ToggleHunkDiff, cx: &mut ViewContext<Self>) {
  95        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
  96        let selections = self.selections.disjoint_anchors();
  97        self.toggle_hunks_expanded(
  98            hunks_for_selections(&multi_buffer_snapshot, &selections),
  99            cx,
 100        );
 101    }
 102
 103    pub fn expand_all_hunk_diffs(&mut self, _: &ExpandAllHunkDiffs, cx: &mut ViewContext<Self>) {
 104        let snapshot = self.snapshot(cx);
 105        let display_rows_with_expanded_hunks = self
 106            .expanded_hunks
 107            .hunks(false)
 108            .map(|hunk| &hunk.hunk_range)
 109            .map(|anchor_range| {
 110                (
 111                    anchor_range
 112                        .start
 113                        .to_display_point(&snapshot.display_snapshot)
 114                        .row(),
 115                    anchor_range
 116                        .end
 117                        .to_display_point(&snapshot.display_snapshot)
 118                        .row(),
 119                )
 120            })
 121            .collect::<HashMap<_, _>>();
 122        let hunks = snapshot
 123            .display_snapshot
 124            .buffer_snapshot
 125            .git_diff_hunks_in_range(MultiBufferRow::MIN..MultiBufferRow::MAX)
 126            .filter(|hunk| {
 127                let hunk_display_row_range = Point::new(hunk.row_range.start.0, 0)
 128                    .to_display_point(&snapshot.display_snapshot)
 129                    ..Point::new(hunk.row_range.end.0, 0)
 130                        .to_display_point(&snapshot.display_snapshot);
 131                let row_range_end =
 132                    display_rows_with_expanded_hunks.get(&hunk_display_row_range.start.row());
 133                row_range_end.is_none() || row_range_end != Some(&hunk_display_row_range.end.row())
 134            });
 135        self.toggle_hunks_expanded(hunks.collect(), cx);
 136    }
 137
 138    fn toggle_hunks_expanded(
 139        &mut self,
 140        hunks_to_toggle: Vec<MultiBufferDiffHunk>,
 141        cx: &mut ViewContext<Self>,
 142    ) {
 143        if self.expanded_hunks.expand_all {
 144            return;
 145        }
 146
 147        let previous_toggle_task = self.expanded_hunks.hunk_update_tasks.remove(&None);
 148        let new_toggle_task = cx.spawn(move |editor, mut cx| async move {
 149            if let Some(task) = previous_toggle_task {
 150                task.await;
 151            }
 152
 153            editor
 154                .update(&mut cx, |editor, cx| {
 155                    let snapshot = editor.snapshot(cx);
 156                    let mut hunks_to_toggle = hunks_to_toggle.into_iter().fuse().peekable();
 157                    let mut highlights_to_remove =
 158                        Vec::with_capacity(editor.expanded_hunks.hunks.len());
 159                    let mut blocks_to_remove = HashSet::default();
 160                    let mut hunks_to_expand = Vec::new();
 161                    editor.expanded_hunks.hunks.retain(|expanded_hunk| {
 162                        if expanded_hunk.folded {
 163                            return true;
 164                        }
 165                        let expanded_hunk_row_range = expanded_hunk
 166                            .hunk_range
 167                            .start
 168                            .to_display_point(&snapshot)
 169                            .row()
 170                            ..expanded_hunk
 171                                .hunk_range
 172                                .end
 173                                .to_display_point(&snapshot)
 174                                .row();
 175                        let mut retain = true;
 176                        while let Some(hunk_to_toggle) = hunks_to_toggle.peek() {
 177                            match diff_hunk_to_display(hunk_to_toggle, &snapshot) {
 178                                DisplayDiffHunk::Folded { .. } => {
 179                                    hunks_to_toggle.next();
 180                                    continue;
 181                                }
 182                                DisplayDiffHunk::Unfolded {
 183                                    diff_base_byte_range,
 184                                    display_row_range,
 185                                    multi_buffer_range,
 186                                    status,
 187                                } => {
 188                                    let hunk_to_toggle_row_range = display_row_range;
 189                                    if hunk_to_toggle_row_range.start > expanded_hunk_row_range.end
 190                                    {
 191                                        break;
 192                                    } else if expanded_hunk_row_range == hunk_to_toggle_row_range {
 193                                        highlights_to_remove.push(expanded_hunk.hunk_range.clone());
 194                                        blocks_to_remove
 195                                            .extend(expanded_hunk.blocks.iter().copied());
 196                                        hunks_to_toggle.next();
 197                                        retain = false;
 198                                        break;
 199                                    } else {
 200                                        hunks_to_expand.push(HoveredHunk {
 201                                            status,
 202                                            multi_buffer_range,
 203                                            diff_base_byte_range,
 204                                        });
 205                                        hunks_to_toggle.next();
 206                                        continue;
 207                                    }
 208                                }
 209                            }
 210                        }
 211
 212                        retain
 213                    });
 214                    for hunk in hunks_to_toggle {
 215                        let remaining_hunk_point_range = Point::new(hunk.row_range.start.0, 0)
 216                            ..Point::new(hunk.row_range.end.0, 0);
 217                        let hunk_start = snapshot
 218                            .buffer_snapshot
 219                            .anchor_before(remaining_hunk_point_range.start);
 220                        let hunk_end = snapshot
 221                            .buffer_snapshot
 222                            .anchor_in_excerpt(hunk_start.excerpt_id, hunk.buffer_range.end)
 223                            .unwrap();
 224                        hunks_to_expand.push(HoveredHunk {
 225                            status: hunk_status(&hunk),
 226                            multi_buffer_range: hunk_start..hunk_end,
 227                            diff_base_byte_range: hunk.diff_base_byte_range.clone(),
 228                        });
 229                    }
 230
 231                    editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
 232                    editor.remove_blocks(blocks_to_remove, None, cx);
 233                    for hunk in hunks_to_expand {
 234                        editor.expand_diff_hunk(None, &hunk, cx);
 235                    }
 236                    cx.notify();
 237                })
 238                .ok();
 239        });
 240
 241        self.expanded_hunks
 242            .hunk_update_tasks
 243            .insert(None, cx.background_executor().spawn(new_toggle_task));
 244    }
 245
 246    pub(super) fn expand_diff_hunk(
 247        &mut self,
 248        diff_base_buffer: Option<Model<Buffer>>,
 249        hunk: &HoveredHunk,
 250        cx: &mut ViewContext<'_, Editor>,
 251    ) -> Option<()> {
 252        let buffer = self.buffer.clone();
 253        let multi_buffer_snapshot = buffer.read(cx).snapshot(cx);
 254        let hunk_range = hunk.multi_buffer_range.clone();
 255        let (diff_base_buffer, deleted_text_lines) = buffer.update(cx, |buffer, cx| {
 256            let buffer = buffer.buffer(hunk_range.start.buffer_id?)?;
 257            let diff_base_buffer = diff_base_buffer
 258                .or_else(|| self.current_diff_base_buffer(&buffer, cx))
 259                .or_else(|| create_diff_base_buffer(&buffer, cx))?;
 260            let deleted_text_lines = buffer.read(cx).diff_base().map(|diff_base| {
 261                let diff_start_row = diff_base
 262                    .offset_to_point(hunk.diff_base_byte_range.start)
 263                    .row;
 264                let diff_end_row = diff_base.offset_to_point(hunk.diff_base_byte_range.end).row;
 265                diff_end_row - diff_start_row
 266            })?;
 267            Some((diff_base_buffer, deleted_text_lines))
 268        })?;
 269
 270        let block_insert_index = match self.expanded_hunks.hunks.binary_search_by(|probe| {
 271            probe
 272                .hunk_range
 273                .start
 274                .cmp(&hunk_range.start, &multi_buffer_snapshot)
 275        }) {
 276            Ok(_already_present) => return None,
 277            Err(ix) => ix,
 278        };
 279
 280        let blocks;
 281        match hunk.status {
 282            DiffHunkStatus::Removed => {
 283                blocks = self.insert_blocks(
 284                    [
 285                        self.hunk_header_block(&hunk, cx),
 286                        Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
 287                    ],
 288                    None,
 289                    cx,
 290                );
 291            }
 292            DiffHunkStatus::Added => {
 293                self.highlight_rows::<DiffRowHighlight>(
 294                    hunk_range.clone(),
 295                    added_hunk_color(cx),
 296                    false,
 297                    cx,
 298                );
 299                blocks = self.insert_blocks([self.hunk_header_block(&hunk, cx)], None, cx);
 300            }
 301            DiffHunkStatus::Modified => {
 302                self.highlight_rows::<DiffRowHighlight>(
 303                    hunk_range.clone(),
 304                    added_hunk_color(cx),
 305                    false,
 306                    cx,
 307                );
 308                blocks = self.insert_blocks(
 309                    [
 310                        self.hunk_header_block(&hunk, cx),
 311                        Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
 312                    ],
 313                    None,
 314                    cx,
 315                );
 316            }
 317        };
 318        self.expanded_hunks.hunks.insert(
 319            block_insert_index,
 320            ExpandedHunk {
 321                blocks,
 322                hunk_range,
 323                status: hunk.status,
 324                folded: false,
 325                diff_base_byte_range: hunk.diff_base_byte_range.clone(),
 326            },
 327        );
 328
 329        Some(())
 330    }
 331
 332    fn apply_diff_hunks_in_range(
 333        &mut self,
 334        range: Range<Anchor>,
 335        cx: &mut ViewContext<'_, Editor>,
 336    ) -> Option<()> {
 337        let (buffer, range, _) = self
 338            .buffer
 339            .read(cx)
 340            .range_to_buffer_ranges(range, cx)
 341            .into_iter()
 342            .next()?;
 343
 344        buffer.update(cx, |branch_buffer, cx| {
 345            branch_buffer.merge_into_base(vec![range], cx);
 346        });
 347
 348        if let Some(project) = self.project.clone() {
 349            self.save(true, project, cx).detach_and_log_err(cx);
 350        }
 351
 352        None
 353    }
 354
 355    pub(crate) fn apply_all_diff_hunks(&mut self, cx: &mut ViewContext<Self>) {
 356        let buffers = self.buffer.read(cx).all_buffers();
 357        for branch_buffer in buffers {
 358            branch_buffer.update(cx, |branch_buffer, cx| {
 359                branch_buffer.merge_into_base(Vec::new(), cx);
 360            });
 361        }
 362
 363        if let Some(project) = self.project.clone() {
 364            self.save(true, project, cx).detach_and_log_err(cx);
 365        }
 366    }
 367
 368    pub(crate) fn apply_selected_diff_hunks(
 369        &mut self,
 370        _: &ApplyDiffHunk,
 371        cx: &mut ViewContext<Self>,
 372    ) {
 373        let snapshot = self.buffer.read(cx).snapshot(cx);
 374        let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
 375        let mut ranges_by_buffer = HashMap::default();
 376        self.transact(cx, |editor, cx| {
 377            for hunk in hunks {
 378                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
 379                    ranges_by_buffer
 380                        .entry(buffer.clone())
 381                        .or_insert_with(Vec::new)
 382                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
 383                }
 384            }
 385
 386            for (buffer, ranges) in ranges_by_buffer {
 387                buffer.update(cx, |buffer, cx| {
 388                    buffer.merge_into_base(ranges, cx);
 389                });
 390            }
 391        });
 392
 393        if let Some(project) = self.project.clone() {
 394            self.save(true, project, cx).detach_and_log_err(cx);
 395        }
 396    }
 397
 398    fn hunk_header_block(
 399        &self,
 400        hunk: &HoveredHunk,
 401        cx: &mut ViewContext<'_, Editor>,
 402    ) -> BlockProperties<Anchor> {
 403        let is_branch_buffer = self
 404            .buffer
 405            .read(cx)
 406            .point_to_buffer_offset(hunk.multi_buffer_range.start, cx)
 407            .map_or(false, |(buffer, _, _)| {
 408                buffer.read(cx).diff_base_buffer().is_some()
 409            });
 410
 411        let border_color = cx.theme().colors().border_variant;
 412        let bg_color = cx.theme().colors().editor_background;
 413        let gutter_color = match hunk.status {
 414            DiffHunkStatus::Added => cx.theme().status().created,
 415            DiffHunkStatus::Modified => cx.theme().status().modified,
 416            DiffHunkStatus::Removed => cx.theme().status().deleted,
 417        };
 418
 419        BlockProperties {
 420            placement: BlockPlacement::Above(hunk.multi_buffer_range.start),
 421            height: 1,
 422            style: BlockStyle::Sticky,
 423            priority: 0,
 424            render: Box::new({
 425                let editor = cx.view().clone();
 426                let hunk = hunk.clone();
 427
 428                move |cx| {
 429                    let hunk_controls_menu_handle =
 430                        editor.read(cx).hunk_controls_menu_handle.clone();
 431
 432                    h_flex()
 433                        .id(cx.block_id)
 434                        .h(cx.line_height())
 435                        .w_full()
 436                        .border_t_1()
 437                        .border_color(border_color)
 438                        .bg(bg_color)
 439                        .child(
 440                            div()
 441                                .id("gutter-strip")
 442                                .w(EditorElement::diff_hunk_strip_width(cx.line_height()))
 443                                .h_full()
 444                                .bg(gutter_color)
 445                                .cursor(CursorStyle::PointingHand)
 446                                .on_click({
 447                                    let editor = editor.clone();
 448                                    let hunk = hunk.clone();
 449                                    move |_event, cx| {
 450                                        editor.update(cx, |editor, cx| {
 451                                            editor.toggle_hovered_hunk(&hunk, cx);
 452                                        });
 453                                    }
 454                                }),
 455                        )
 456                        .child(
 457                            h_flex()
 458                                .px_6()
 459                                .size_full()
 460                                .justify_end()
 461                                .child(
 462                                    h_flex()
 463                                        .gap_1()
 464                                        .when(!is_branch_buffer, |row| {
 465                                            row.child(
 466                                                IconButton::new("next-hunk", IconName::ArrowDown)
 467                                                    .shape(IconButtonShape::Square)
 468                                                    .icon_size(IconSize::Small)
 469                                                    .tooltip({
 470                                                        let focus_handle = editor.focus_handle(cx);
 471                                                        move |cx| {
 472                                                            Tooltip::for_action_in(
 473                                                                "Next Hunk",
 474                                                                &GoToHunk,
 475                                                                &focus_handle,
 476                                                                cx,
 477                                                            )
 478                                                        }
 479                                                    })
 480                                                    .on_click({
 481                                                        let editor = editor.clone();
 482                                                        let hunk = hunk.clone();
 483                                                        move |_event, cx| {
 484                                                            editor.update(cx, |editor, cx| {
 485                                                                editor.go_to_subsequent_hunk(
 486                                                                    hunk.multi_buffer_range.end,
 487                                                                    cx,
 488                                                                );
 489                                                            });
 490                                                        }
 491                                                    }),
 492                                            )
 493                                            .child(
 494                                                IconButton::new("prev-hunk", IconName::ArrowUp)
 495                                                    .shape(IconButtonShape::Square)
 496                                                    .icon_size(IconSize::Small)
 497                                                    .tooltip({
 498                                                        let focus_handle = editor.focus_handle(cx);
 499                                                        move |cx| {
 500                                                            Tooltip::for_action_in(
 501                                                                "Previous Hunk",
 502                                                                &GoToPrevHunk,
 503                                                                &focus_handle,
 504                                                                cx,
 505                                                            )
 506                                                        }
 507                                                    })
 508                                                    .on_click({
 509                                                        let editor = editor.clone();
 510                                                        let hunk = hunk.clone();
 511                                                        move |_event, cx| {
 512                                                            editor.update(cx, |editor, cx| {
 513                                                                editor.go_to_preceding_hunk(
 514                                                                    hunk.multi_buffer_range.start,
 515                                                                    cx,
 516                                                                );
 517                                                            });
 518                                                        }
 519                                                    }),
 520                                            )
 521                                        })
 522                                        .child(
 523                                            IconButton::new("discard", IconName::Undo)
 524                                                .shape(IconButtonShape::Square)
 525                                                .icon_size(IconSize::Small)
 526                                                .tooltip({
 527                                                    let focus_handle = editor.focus_handle(cx);
 528                                                    move |cx| {
 529                                                        Tooltip::for_action_in(
 530                                                            "Discard Hunk",
 531                                                            &RevertSelectedHunks,
 532                                                            &focus_handle,
 533                                                            cx,
 534                                                        )
 535                                                    }
 536                                                })
 537                                                .on_click({
 538                                                    let editor = editor.clone();
 539                                                    let hunk = hunk.clone();
 540                                                    move |_event, cx| {
 541                                                        let multi_buffer =
 542                                                            editor.read(cx).buffer().clone();
 543                                                        let multi_buffer_snapshot =
 544                                                            multi_buffer.read(cx).snapshot(cx);
 545                                                        let mut revert_changes = HashMap::default();
 546                                                        if let Some(hunk) =
 547                                                            crate::hunk_diff::to_diff_hunk(
 548                                                                &hunk,
 549                                                                &multi_buffer_snapshot,
 550                                                            )
 551                                                        {
 552                                                            Editor::prepare_revert_change(
 553                                                                &mut revert_changes,
 554                                                                &multi_buffer,
 555                                                                &hunk,
 556                                                                cx,
 557                                                            );
 558                                                        }
 559                                                        if !revert_changes.is_empty() {
 560                                                            editor.update(cx, |editor, cx| {
 561                                                                editor.revert(revert_changes, cx)
 562                                                            });
 563                                                        }
 564                                                    }
 565                                                }),
 566                                        )
 567                                        .map(|this| {
 568                                            if is_branch_buffer {
 569                                                this.child(
 570                                                    IconButton::new("apply", IconName::Check)
 571                                                        .shape(IconButtonShape::Square)
 572                                                        .icon_size(IconSize::Small)
 573                                                        .tooltip({
 574                                                            let focus_handle =
 575                                                                editor.focus_handle(cx);
 576                                                            move |cx| {
 577                                                                Tooltip::for_action_in(
 578                                                                    "Apply Hunk",
 579                                                                    &ApplyDiffHunk,
 580                                                                    &focus_handle,
 581                                                                    cx,
 582                                                                )
 583                                                            }
 584                                                        })
 585                                                        .on_click({
 586                                                            let editor = editor.clone();
 587                                                            let hunk = hunk.clone();
 588                                                            move |_event, cx| {
 589                                                                editor.update(cx, |editor, cx| {
 590                                                                    editor
 591                                                                        .apply_diff_hunks_in_range(
 592                                                                            hunk.multi_buffer_range
 593                                                                                .clone(),
 594                                                                            cx,
 595                                                                        );
 596                                                                });
 597                                                            }
 598                                                        }),
 599                                                )
 600                                            } else {
 601                                                this.child({
 602                                                    let focus = editor.focus_handle(cx);
 603                                                    PopoverMenu::new("hunk-controls-dropdown")
 604                                                        .trigger(
 605                                                            IconButton::new(
 606                                                                "toggle_editor_selections_icon",
 607                                                                IconName::EllipsisVertical,
 608                                                            )
 609                                                            .shape(IconButtonShape::Square)
 610                                                            .icon_size(IconSize::Small)
 611                                                            .style(ButtonStyle::Subtle)
 612                                                            .selected(
 613                                                                hunk_controls_menu_handle
 614                                                                    .is_deployed(),
 615                                                            )
 616                                                            .when(
 617                                                                !hunk_controls_menu_handle
 618                                                                    .is_deployed(),
 619                                                                |this| {
 620                                                                    this.tooltip(|cx| {
 621                                                                        Tooltip::text(
 622                                                                            "Hunk Controls",
 623                                                                            cx,
 624                                                                        )
 625                                                                    })
 626                                                                },
 627                                                            ),
 628                                                        )
 629                                                        .anchor(AnchorCorner::TopRight)
 630                                                        .with_handle(hunk_controls_menu_handle)
 631                                                        .menu(move |cx| {
 632                                                            let focus = focus.clone();
 633                                                            let menu = ContextMenu::build(
 634                                                                cx,
 635                                                                move |menu, _| {
 636                                                                    menu.context(focus.clone())
 637                                                                        .action(
 638                                                                            "Discard All Hunks",
 639                                                                            RevertFile
 640                                                                                .boxed_clone(),
 641                                                                        )
 642                                                                },
 643                                                            );
 644                                                            Some(menu)
 645                                                        })
 646                                                })
 647                                            }
 648                                        }),
 649                                )
 650                                .when(!is_branch_buffer, |div| {
 651                                    div.child(
 652                                        IconButton::new("collapse", IconName::Close)
 653                                            .shape(IconButtonShape::Square)
 654                                            .icon_size(IconSize::Small)
 655                                            .tooltip({
 656                                                let focus_handle = editor.focus_handle(cx);
 657                                                move |cx| {
 658                                                    Tooltip::for_action_in(
 659                                                        "Collapse Hunk",
 660                                                        &ToggleHunkDiff,
 661                                                        &focus_handle,
 662                                                        cx,
 663                                                    )
 664                                                }
 665                                            })
 666                                            .on_click({
 667                                                let editor = editor.clone();
 668                                                let hunk = hunk.clone();
 669                                                move |_event, cx| {
 670                                                    editor.update(cx, |editor, cx| {
 671                                                        editor.toggle_hovered_hunk(&hunk, cx);
 672                                                    });
 673                                                }
 674                                            }),
 675                                    )
 676                                }),
 677                        )
 678                        .into_any_element()
 679                }
 680            }),
 681        }
 682    }
 683
 684    fn deleted_text_block(
 685        hunk: &HoveredHunk,
 686        diff_base_buffer: Model<Buffer>,
 687        deleted_text_height: u32,
 688        cx: &mut ViewContext<'_, Editor>,
 689    ) -> BlockProperties<Anchor> {
 690        let gutter_color = match hunk.status {
 691            DiffHunkStatus::Added => unreachable!(),
 692            DiffHunkStatus::Modified => cx.theme().status().modified,
 693            DiffHunkStatus::Removed => cx.theme().status().deleted,
 694        };
 695        let deleted_hunk_color = deleted_hunk_color(cx);
 696        let (editor_height, editor_with_deleted_text) =
 697            editor_with_deleted_text(diff_base_buffer, deleted_hunk_color, hunk, cx);
 698        let editor = cx.view().clone();
 699        let hunk = hunk.clone();
 700        let height = editor_height.max(deleted_text_height);
 701        BlockProperties {
 702            placement: BlockPlacement::Above(hunk.multi_buffer_range.start),
 703            height,
 704            style: BlockStyle::Flex,
 705            priority: 0,
 706            render: Box::new(move |cx| {
 707                let width = EditorElement::diff_hunk_strip_width(cx.line_height());
 708                let gutter_dimensions = editor.read(cx.context).gutter_dimensions;
 709
 710                h_flex()
 711                    .id(cx.block_id)
 712                    .bg(deleted_hunk_color)
 713                    .h(height as f32 * cx.line_height())
 714                    .w_full()
 715                    .child(
 716                        h_flex()
 717                            .id("gutter")
 718                            .max_w(gutter_dimensions.full_width())
 719                            .min_w(gutter_dimensions.full_width())
 720                            .size_full()
 721                            .child(
 722                                h_flex()
 723                                    .id("gutter hunk")
 724                                    .bg(gutter_color)
 725                                    .pl(gutter_dimensions.margin
 726                                        + gutter_dimensions
 727                                            .git_blame_entries_width
 728                                            .unwrap_or_default())
 729                                    .max_w(width)
 730                                    .min_w(width)
 731                                    .size_full()
 732                                    .cursor(CursorStyle::PointingHand)
 733                                    .on_mouse_down(MouseButton::Left, {
 734                                        let editor = editor.clone();
 735                                        let hunk = hunk.clone();
 736                                        move |_event, cx| {
 737                                            editor.update(cx, |editor, cx| {
 738                                                editor.toggle_hovered_hunk(&hunk, cx);
 739                                            });
 740                                        }
 741                                    }),
 742                            ),
 743                    )
 744                    .child(editor_with_deleted_text.clone())
 745                    .into_any_element()
 746            }),
 747        }
 748    }
 749
 750    pub(super) fn clear_expanded_diff_hunks(&mut self, cx: &mut ViewContext<'_, Editor>) -> bool {
 751        if self.expanded_hunks.expand_all {
 752            return false;
 753        }
 754        self.expanded_hunks.hunk_update_tasks.clear();
 755        self.clear_row_highlights::<DiffRowHighlight>();
 756        let to_remove = self
 757            .expanded_hunks
 758            .hunks
 759            .drain(..)
 760            .flat_map(|expanded_hunk| expanded_hunk.blocks.into_iter())
 761            .collect::<HashSet<_>>();
 762        if to_remove.is_empty() {
 763            false
 764        } else {
 765            self.remove_blocks(to_remove, None, cx);
 766            true
 767        }
 768    }
 769
 770    pub(super) fn sync_expanded_diff_hunks(
 771        &mut self,
 772        buffer: Model<Buffer>,
 773        cx: &mut ViewContext<'_, Self>,
 774    ) {
 775        let buffer_id = buffer.read(cx).remote_id();
 776        let buffer_diff_base_version = buffer.read(cx).diff_base_version();
 777        self.expanded_hunks
 778            .hunk_update_tasks
 779            .remove(&Some(buffer_id));
 780        let diff_base_buffer = self.current_diff_base_buffer(&buffer, cx);
 781        let new_sync_task = cx.spawn(move |editor, mut cx| async move {
 782            let diff_base_buffer_unchanged = diff_base_buffer.is_some();
 783            let Ok(diff_base_buffer) =
 784                cx.update(|cx| diff_base_buffer.or_else(|| create_diff_base_buffer(&buffer, cx)))
 785            else {
 786                return;
 787            };
 788            editor
 789                .update(&mut cx, |editor, cx| {
 790                    if let Some(diff_base_buffer) = &diff_base_buffer {
 791                        editor.expanded_hunks.diff_base.insert(
 792                            buffer_id,
 793                            DiffBaseBuffer {
 794                                buffer: diff_base_buffer.clone(),
 795                                diff_base_version: buffer_diff_base_version,
 796                            },
 797                        );
 798                    }
 799
 800                    let snapshot = editor.snapshot(cx);
 801                    let mut recalculated_hunks = snapshot
 802                        .buffer_snapshot
 803                        .git_diff_hunks_in_range(MultiBufferRow::MIN..MultiBufferRow::MAX)
 804                        .filter(|hunk| hunk.buffer_id == buffer_id)
 805                        .fuse()
 806                        .peekable();
 807                    let mut highlights_to_remove =
 808                        Vec::with_capacity(editor.expanded_hunks.hunks.len());
 809                    let mut blocks_to_remove = HashSet::default();
 810                    let mut hunks_to_reexpand =
 811                        Vec::with_capacity(editor.expanded_hunks.hunks.len());
 812                    editor.expanded_hunks.hunks.retain_mut(|expanded_hunk| {
 813                        if expanded_hunk.hunk_range.start.buffer_id != Some(buffer_id) {
 814                            return true;
 815                        };
 816
 817                        let mut retain = false;
 818                        if diff_base_buffer_unchanged {
 819                            let expanded_hunk_display_range = expanded_hunk
 820                                .hunk_range
 821                                .start
 822                                .to_display_point(&snapshot)
 823                                .row()
 824                                ..expanded_hunk
 825                                    .hunk_range
 826                                    .end
 827                                    .to_display_point(&snapshot)
 828                                    .row();
 829                            while let Some(buffer_hunk) = recalculated_hunks.peek() {
 830                                match diff_hunk_to_display(buffer_hunk, &snapshot) {
 831                                    DisplayDiffHunk::Folded { display_row } => {
 832                                        recalculated_hunks.next();
 833                                        if !expanded_hunk.folded
 834                                            && expanded_hunk_display_range
 835                                                .to_inclusive()
 836                                                .contains(&display_row)
 837                                        {
 838                                            retain = true;
 839                                            expanded_hunk.folded = true;
 840                                            highlights_to_remove
 841                                                .push(expanded_hunk.hunk_range.clone());
 842                                            for block in expanded_hunk.blocks.drain(..) {
 843                                                blocks_to_remove.insert(block);
 844                                            }
 845                                            break;
 846                                        } else {
 847                                            continue;
 848                                        }
 849                                    }
 850                                    DisplayDiffHunk::Unfolded {
 851                                        diff_base_byte_range,
 852                                        display_row_range,
 853                                        multi_buffer_range,
 854                                        status,
 855                                    } => {
 856                                        let hunk_display_range = display_row_range;
 857
 858                                        if expanded_hunk_display_range.start
 859                                            > hunk_display_range.end
 860                                        {
 861                                            recalculated_hunks.next();
 862                                            if editor.expanded_hunks.expand_all {
 863                                                hunks_to_reexpand.push(HoveredHunk {
 864                                                    status,
 865                                                    multi_buffer_range,
 866                                                    diff_base_byte_range,
 867                                                });
 868                                            }
 869                                            continue;
 870                                        }
 871
 872                                        if expanded_hunk_display_range.end
 873                                            < hunk_display_range.start
 874                                        {
 875                                            break;
 876                                        }
 877
 878                                        if !expanded_hunk.folded
 879                                            && expanded_hunk_display_range == hunk_display_range
 880                                            && expanded_hunk.status == hunk_status(buffer_hunk)
 881                                            && expanded_hunk.diff_base_byte_range
 882                                                == buffer_hunk.diff_base_byte_range
 883                                        {
 884                                            recalculated_hunks.next();
 885                                            retain = true;
 886                                        } else {
 887                                            hunks_to_reexpand.push(HoveredHunk {
 888                                                status,
 889                                                multi_buffer_range,
 890                                                diff_base_byte_range,
 891                                            });
 892                                        }
 893                                        break;
 894                                    }
 895                                }
 896                            }
 897                        }
 898                        if !retain {
 899                            blocks_to_remove.extend(expanded_hunk.blocks.drain(..));
 900                            highlights_to_remove.push(expanded_hunk.hunk_range.clone());
 901                        }
 902                        retain
 903                    });
 904
 905                    if editor.expanded_hunks.expand_all {
 906                        for hunk in recalculated_hunks {
 907                            match diff_hunk_to_display(&hunk, &snapshot) {
 908                                DisplayDiffHunk::Folded { .. } => {}
 909                                DisplayDiffHunk::Unfolded {
 910                                    diff_base_byte_range,
 911                                    multi_buffer_range,
 912                                    status,
 913                                    ..
 914                                } => {
 915                                    hunks_to_reexpand.push(HoveredHunk {
 916                                        status,
 917                                        multi_buffer_range,
 918                                        diff_base_byte_range,
 919                                    });
 920                                }
 921                            }
 922                        }
 923                    }
 924
 925                    editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
 926                    editor.remove_blocks(blocks_to_remove, None, cx);
 927
 928                    if let Some(diff_base_buffer) = &diff_base_buffer {
 929                        for hunk in hunks_to_reexpand {
 930                            editor.expand_diff_hunk(Some(diff_base_buffer.clone()), &hunk, cx);
 931                        }
 932                    }
 933                })
 934                .ok();
 935        });
 936
 937        self.expanded_hunks.hunk_update_tasks.insert(
 938            Some(buffer_id),
 939            cx.background_executor().spawn(new_sync_task),
 940        );
 941    }
 942
 943    fn current_diff_base_buffer(
 944        &mut self,
 945        buffer: &Model<Buffer>,
 946        cx: &mut AppContext,
 947    ) -> Option<Model<Buffer>> {
 948        buffer.update(cx, |buffer, _| {
 949            match self.expanded_hunks.diff_base.entry(buffer.remote_id()) {
 950                hash_map::Entry::Occupied(o) => {
 951                    if o.get().diff_base_version != buffer.diff_base_version() {
 952                        o.remove();
 953                        None
 954                    } else {
 955                        Some(o.get().buffer.clone())
 956                    }
 957                }
 958                hash_map::Entry::Vacant(_) => None,
 959            }
 960        })
 961    }
 962
 963    fn go_to_subsequent_hunk(&mut self, position: Anchor, cx: &mut ViewContext<Self>) {
 964        let snapshot = self.snapshot(cx);
 965        let position = position.to_point(&snapshot.buffer_snapshot);
 966        if let Some(hunk) = self.go_to_hunk_after_position(&snapshot, position, cx) {
 967            let multi_buffer_start = snapshot
 968                .buffer_snapshot
 969                .anchor_before(Point::new(hunk.row_range.start.0, 0));
 970            let multi_buffer_end = snapshot
 971                .buffer_snapshot
 972                .anchor_after(Point::new(hunk.row_range.end.0, 0));
 973            self.expand_diff_hunk(
 974                None,
 975                &HoveredHunk {
 976                    multi_buffer_range: multi_buffer_start..multi_buffer_end,
 977                    status: hunk_status(&hunk),
 978                    diff_base_byte_range: hunk.diff_base_byte_range,
 979                },
 980                cx,
 981            );
 982        }
 983    }
 984
 985    fn go_to_preceding_hunk(&mut self, position: Anchor, cx: &mut ViewContext<Self>) {
 986        let snapshot = self.snapshot(cx);
 987        let position = position.to_point(&snapshot.buffer_snapshot);
 988        let hunk = self.go_to_hunk_before_position(&snapshot, position, cx);
 989        if let Some(hunk) = hunk {
 990            let multi_buffer_start = snapshot
 991                .buffer_snapshot
 992                .anchor_before(Point::new(hunk.row_range.start.0, 0));
 993            let multi_buffer_end = snapshot
 994                .buffer_snapshot
 995                .anchor_after(Point::new(hunk.row_range.end.0, 0));
 996            self.expand_diff_hunk(
 997                None,
 998                &HoveredHunk {
 999                    multi_buffer_range: multi_buffer_start..multi_buffer_end,
1000                    status: hunk_status(&hunk),
1001                    diff_base_byte_range: hunk.diff_base_byte_range,
1002                },
1003                cx,
1004            );
1005        }
1006    }
1007}
1008
1009fn to_diff_hunk(
1010    hovered_hunk: &HoveredHunk,
1011    multi_buffer_snapshot: &MultiBufferSnapshot,
1012) -> Option<MultiBufferDiffHunk> {
1013    let buffer_id = hovered_hunk
1014        .multi_buffer_range
1015        .start
1016        .buffer_id
1017        .or(hovered_hunk.multi_buffer_range.end.buffer_id)?;
1018    let buffer_range = hovered_hunk.multi_buffer_range.start.text_anchor
1019        ..hovered_hunk.multi_buffer_range.end.text_anchor;
1020    let point_range = hovered_hunk
1021        .multi_buffer_range
1022        .to_point(multi_buffer_snapshot);
1023    Some(MultiBufferDiffHunk {
1024        row_range: MultiBufferRow(point_range.start.row)..MultiBufferRow(point_range.end.row),
1025        buffer_id,
1026        buffer_range,
1027        diff_base_byte_range: hovered_hunk.diff_base_byte_range.clone(),
1028    })
1029}
1030
1031fn create_diff_base_buffer(buffer: &Model<Buffer>, cx: &mut AppContext) -> Option<Model<Buffer>> {
1032    buffer
1033        .update(cx, |buffer, _| {
1034            let language = buffer.language().cloned();
1035            let diff_base = buffer.diff_base()?.clone();
1036            Some((buffer.line_ending(), diff_base, language))
1037        })
1038        .map(|(line_ending, diff_base, language)| {
1039            cx.new_model(|cx| {
1040                let buffer = Buffer::local_normalized(diff_base, line_ending, cx);
1041                match language {
1042                    Some(language) => buffer.with_language(language, cx),
1043                    None => buffer,
1044                }
1045            })
1046        })
1047}
1048
1049fn added_hunk_color(cx: &AppContext) -> Hsla {
1050    let mut created_color = cx.theme().status().git().created;
1051    created_color.fade_out(0.7);
1052    created_color
1053}
1054
1055fn deleted_hunk_color(cx: &AppContext) -> Hsla {
1056    let mut deleted_color = cx.theme().status().deleted;
1057    deleted_color.fade_out(0.7);
1058    deleted_color
1059}
1060
1061fn editor_with_deleted_text(
1062    diff_base_buffer: Model<Buffer>,
1063    deleted_color: Hsla,
1064    hunk: &HoveredHunk,
1065    cx: &mut ViewContext<'_, Editor>,
1066) -> (u32, View<Editor>) {
1067    let parent_editor = cx.view().downgrade();
1068    let editor = cx.new_view(|cx| {
1069        let multi_buffer =
1070            cx.new_model(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1071        multi_buffer.update(cx, |multi_buffer, cx| {
1072            multi_buffer.push_excerpts(
1073                diff_base_buffer,
1074                Some(ExcerptRange {
1075                    context: hunk.diff_base_byte_range.clone(),
1076                    primary: None,
1077                }),
1078                cx,
1079            );
1080        });
1081
1082        let mut editor = Editor::for_multibuffer(multi_buffer, None, true, cx);
1083        editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1084        editor.set_show_wrap_guides(false, cx);
1085        editor.set_show_gutter(false, cx);
1086        editor.scroll_manager.set_forbid_vertical_scroll(true);
1087        editor.set_read_only(true);
1088        editor.set_show_inline_completions(Some(false), cx);
1089
1090        enum DeletedBlockRowHighlight {}
1091        editor.highlight_rows::<DeletedBlockRowHighlight>(
1092            Anchor::min()..Anchor::max(),
1093            deleted_color,
1094            false,
1095            cx,
1096        );
1097        editor.set_current_line_highlight(Some(CurrentLineHighlight::None)); //
1098        editor
1099            ._subscriptions
1100            .extend([cx.on_blur(&editor.focus_handle, |editor, cx| {
1101                editor.change_selections(None, cx, |s| {
1102                    s.try_cancel();
1103                });
1104            })]);
1105
1106        let original_multi_buffer_range = hunk.multi_buffer_range.clone();
1107        let diff_base_range = hunk.diff_base_byte_range.clone();
1108        editor
1109            .register_action::<RevertSelectedHunks>({
1110                let parent_editor = parent_editor.clone();
1111                move |_, cx| {
1112                    parent_editor
1113                        .update(cx, |editor, cx| {
1114                            let Some((buffer, original_text)) =
1115                                editor.buffer().update(cx, |buffer, cx| {
1116                                    let (_, buffer, _) = buffer.excerpt_containing(
1117                                        original_multi_buffer_range.start,
1118                                        cx,
1119                                    )?;
1120                                    let original_text =
1121                                        buffer.read(cx).diff_base()?.slice(diff_base_range.clone());
1122                                    Some((buffer, Arc::from(original_text.to_string())))
1123                                })
1124                            else {
1125                                return;
1126                            };
1127                            buffer.update(cx, |buffer, cx| {
1128                                buffer.edit(
1129                                    Some((
1130                                        original_multi_buffer_range.start.text_anchor
1131                                            ..original_multi_buffer_range.end.text_anchor,
1132                                        original_text,
1133                                    )),
1134                                    None,
1135                                    cx,
1136                                )
1137                            });
1138                        })
1139                        .ok();
1140                }
1141            })
1142            .detach();
1143        let hunk = hunk.clone();
1144        editor
1145            .register_action::<ToggleHunkDiff>(move |_, cx| {
1146                parent_editor
1147                    .update(cx, |editor, cx| {
1148                        editor.toggle_hovered_hunk(&hunk, cx);
1149                    })
1150                    .ok();
1151            })
1152            .detach();
1153        editor
1154    });
1155
1156    let editor_height = editor.update(cx, |editor, cx| editor.max_point(cx).row().0);
1157    (editor_height, editor)
1158}
1159
1160impl DisplayDiffHunk {
1161    pub fn start_display_row(&self) -> DisplayRow {
1162        match self {
1163            &DisplayDiffHunk::Folded { display_row } => display_row,
1164            DisplayDiffHunk::Unfolded {
1165                display_row_range, ..
1166            } => display_row_range.start,
1167        }
1168    }
1169
1170    pub fn contains_display_row(&self, display_row: DisplayRow) -> bool {
1171        let range = match self {
1172            &DisplayDiffHunk::Folded { display_row } => display_row..=display_row,
1173
1174            DisplayDiffHunk::Unfolded {
1175                display_row_range, ..
1176            } => display_row_range.start..=display_row_range.end,
1177        };
1178
1179        range.contains(&display_row)
1180    }
1181}
1182
1183pub fn diff_hunk_to_display(
1184    hunk: &MultiBufferDiffHunk,
1185    snapshot: &DisplaySnapshot,
1186) -> DisplayDiffHunk {
1187    let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
1188    let hunk_start_point_sub = Point::new(hunk.row_range.start.0.saturating_sub(1), 0);
1189    let hunk_end_point_sub = Point::new(
1190        hunk.row_range
1191            .end
1192            .0
1193            .saturating_sub(1)
1194            .max(hunk.row_range.start.0),
1195        0,
1196    );
1197
1198    let status = hunk_status(hunk);
1199    let is_removal = status == DiffHunkStatus::Removed;
1200
1201    let folds_start = Point::new(hunk.row_range.start.0.saturating_sub(2), 0);
1202    let folds_end = Point::new(hunk.row_range.end.0 + 2, 0);
1203    let folds_range = folds_start..folds_end;
1204
1205    let containing_fold = snapshot.folds_in_range(folds_range).find(|fold| {
1206        let fold_point_range = fold.range.to_point(&snapshot.buffer_snapshot);
1207        let fold_point_range = fold_point_range.start..=fold_point_range.end;
1208
1209        let folded_start = fold_point_range.contains(&hunk_start_point);
1210        let folded_end = fold_point_range.contains(&hunk_end_point_sub);
1211        let folded_start_sub = fold_point_range.contains(&hunk_start_point_sub);
1212
1213        (folded_start && folded_end) || (is_removal && folded_start_sub)
1214    });
1215
1216    if let Some(fold) = containing_fold {
1217        let row = fold.range.start.to_display_point(snapshot).row();
1218        DisplayDiffHunk::Folded { display_row: row }
1219    } else {
1220        let start = hunk_start_point.to_display_point(snapshot).row();
1221
1222        let hunk_end_row = hunk.row_range.end.max(hunk.row_range.start);
1223        let hunk_end_point = Point::new(hunk_end_row.0, 0);
1224
1225        let multi_buffer_start = snapshot.buffer_snapshot.anchor_before(hunk_start_point);
1226        let multi_buffer_end = snapshot
1227            .buffer_snapshot
1228            .anchor_in_excerpt(multi_buffer_start.excerpt_id, hunk.buffer_range.end)
1229            .unwrap();
1230        let end = hunk_end_point.to_display_point(snapshot).row();
1231
1232        DisplayDiffHunk::Unfolded {
1233            display_row_range: start..end,
1234            multi_buffer_range: multi_buffer_start..multi_buffer_end,
1235            status,
1236            diff_base_byte_range: hunk.diff_base_byte_range.clone(),
1237        }
1238    }
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243    use super::*;
1244    use crate::{editor_tests::init_test, hunk_status};
1245    use gpui::{Context, TestAppContext};
1246    use language::Capability::ReadWrite;
1247    use multi_buffer::{ExcerptRange, MultiBuffer, MultiBufferRow};
1248    use project::{FakeFs, Project};
1249    use unindent::Unindent as _;
1250
1251    #[gpui::test]
1252    async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
1253        use git::diff::DiffHunkStatus;
1254        init_test(cx, |_| {});
1255
1256        let fs = FakeFs::new(cx.background_executor.clone());
1257        let project = Project::test(fs, [], cx).await;
1258
1259        // buffer has two modified hunks with two rows each
1260        let buffer_1 = project.update(cx, |project, cx| {
1261            project.create_local_buffer(
1262                "
1263                        1.zero
1264                        1.ONE
1265                        1.TWO
1266                        1.three
1267                        1.FOUR
1268                        1.FIVE
1269                        1.six
1270                    "
1271                .unindent()
1272                .as_str(),
1273                None,
1274                cx,
1275            )
1276        });
1277        buffer_1.update(cx, |buffer, cx| {
1278            buffer.set_diff_base(
1279                Some(
1280                    "
1281                        1.zero
1282                        1.one
1283                        1.two
1284                        1.three
1285                        1.four
1286                        1.five
1287                        1.six
1288                    "
1289                    .unindent(),
1290                ),
1291                cx,
1292            );
1293        });
1294
1295        // buffer has a deletion hunk and an insertion hunk
1296        let buffer_2 = project.update(cx, |project, cx| {
1297            project.create_local_buffer(
1298                "
1299                        2.zero
1300                        2.one
1301                        2.two
1302                        2.three
1303                        2.four
1304                        2.five
1305                        2.six
1306                    "
1307                .unindent()
1308                .as_str(),
1309                None,
1310                cx,
1311            )
1312        });
1313        buffer_2.update(cx, |buffer, cx| {
1314            buffer.set_diff_base(
1315                Some(
1316                    "
1317                        2.zero
1318                        2.one
1319                        2.one-and-a-half
1320                        2.two
1321                        2.three
1322                        2.four
1323                        2.six
1324                    "
1325                    .unindent(),
1326                ),
1327                cx,
1328            );
1329        });
1330
1331        cx.background_executor.run_until_parked();
1332
1333        let multibuffer = cx.new_model(|cx| {
1334            let mut multibuffer = MultiBuffer::new(ReadWrite);
1335            multibuffer.push_excerpts(
1336                buffer_1.clone(),
1337                [
1338                    // excerpt ends in the middle of a modified hunk
1339                    ExcerptRange {
1340                        context: Point::new(0, 0)..Point::new(1, 5),
1341                        primary: Default::default(),
1342                    },
1343                    // excerpt begins in the middle of a modified hunk
1344                    ExcerptRange {
1345                        context: Point::new(5, 0)..Point::new(6, 5),
1346                        primary: Default::default(),
1347                    },
1348                ],
1349                cx,
1350            );
1351            multibuffer.push_excerpts(
1352                buffer_2.clone(),
1353                [
1354                    // excerpt ends at a deletion
1355                    ExcerptRange {
1356                        context: Point::new(0, 0)..Point::new(1, 5),
1357                        primary: Default::default(),
1358                    },
1359                    // excerpt starts at a deletion
1360                    ExcerptRange {
1361                        context: Point::new(2, 0)..Point::new(2, 5),
1362                        primary: Default::default(),
1363                    },
1364                    // excerpt fully contains a deletion hunk
1365                    ExcerptRange {
1366                        context: Point::new(1, 0)..Point::new(2, 5),
1367                        primary: Default::default(),
1368                    },
1369                    // excerpt fully contains an insertion hunk
1370                    ExcerptRange {
1371                        context: Point::new(4, 0)..Point::new(6, 5),
1372                        primary: Default::default(),
1373                    },
1374                ],
1375                cx,
1376            );
1377            multibuffer
1378        });
1379
1380        let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
1381
1382        assert_eq!(
1383            snapshot.text(),
1384            "
1385                1.zero
1386                1.ONE
1387                1.FIVE
1388                1.six
1389                2.zero
1390                2.one
1391                2.two
1392                2.one
1393                2.two
1394                2.four
1395                2.five
1396                2.six"
1397                .unindent()
1398        );
1399
1400        let expected = [
1401            (
1402                DiffHunkStatus::Modified,
1403                MultiBufferRow(1)..MultiBufferRow(2),
1404            ),
1405            (
1406                DiffHunkStatus::Modified,
1407                MultiBufferRow(2)..MultiBufferRow(3),
1408            ),
1409            //TODO: Define better when and where removed hunks show up at range extremities
1410            (
1411                DiffHunkStatus::Removed,
1412                MultiBufferRow(6)..MultiBufferRow(6),
1413            ),
1414            (
1415                DiffHunkStatus::Removed,
1416                MultiBufferRow(8)..MultiBufferRow(8),
1417            ),
1418            (
1419                DiffHunkStatus::Added,
1420                MultiBufferRow(10)..MultiBufferRow(11),
1421            ),
1422        ];
1423
1424        assert_eq!(
1425            snapshot
1426                .git_diff_hunks_in_range(MultiBufferRow(0)..MultiBufferRow(12))
1427                .map(|hunk| (hunk_status(&hunk), hunk.row_range))
1428                .collect::<Vec<_>>(),
1429            &expected,
1430        );
1431
1432        assert_eq!(
1433            snapshot
1434                .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(12))
1435                .map(|hunk| (hunk_status(&hunk), hunk.row_range))
1436                .collect::<Vec<_>>(),
1437            expected
1438                .iter()
1439                .rev()
1440                .cloned()
1441                .collect::<Vec<_>>()
1442                .as_slice(),
1443        );
1444    }
1445}