Skip to main content

gpui_component/diff/
document.rs

1use std::{ops::Range, sync::Arc};
2
3use gpui::SharedString;
4
5use super::conflict::DiffConflict;
6use super::parser::{DiffParseError, DiffParseOptions};
7use smallvec::{SmallVec, smallvec};
8use unicode_segmentation::UnicodeSegmentation as _;
9
10/// Which source version a position belongs to.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum DiffSide {
13    Original,
14    Modified,
15}
16
17impl DiffSide {
18    pub(crate) fn other(self) -> Self {
19        match self {
20            Self::Original => Self::Modified,
21            Self::Modified => Self::Original,
22        }
23    }
24}
25
26/// A one-based source line, independent of the visual layout.
27///
28/// The file is identified by its [`DiffFile::path`], which stays stable when a
29/// newer revision of the patch reorders its files.
30#[derive(Clone, Debug, PartialEq, Eq, Hash)]
31pub struct DiffLinePosition {
32    path: SharedString,
33    side: DiffSide,
34    line: usize,
35}
36
37impl DiffLinePosition {
38    /// Creates a position, clamping the line to at least one.
39    pub fn new(path: impl Into<SharedString>, side: DiffSide, line: usize) -> Self {
40        Self {
41            path: path.into(),
42            side,
43            line: line.max(1),
44        }
45    }
46    /// The [`DiffFile::path`] of the file.
47    pub fn path(&self) -> &SharedString {
48        &self.path
49    }
50    pub fn side(&self) -> DiffSide {
51        self.side
52    }
53    pub fn line(&self) -> usize {
54        self.line
55    }
56}
57
58/// One character of a source line, as the pointer finds it.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct DiffTextPosition {
61    position: DiffLinePosition,
62    offset: usize,
63    text: SharedString,
64}
65
66impl DiffTextPosition {
67    pub(crate) fn new(position: DiffLinePosition, offset: usize, text: SharedString) -> Self {
68        Self {
69            position,
70            offset,
71            text,
72        }
73    }
74    /// The line the character is on.
75    pub fn position(&self) -> &DiffLinePosition {
76        &self.position
77    }
78    /// The character's byte offset in the line's content, before tab
79    /// expansion: the unit [`super::DiffSpanHighlight`] spans use.
80    pub fn offset(&self) -> usize {
81        self.offset
82    }
83    /// The line's content, so the handler can read the word around the
84    /// offset without a copy of the patch.
85    pub fn text(&self) -> &SharedString {
86        &self.text
87    }
88}
89
90/// An inclusive range of source lines in one file, identified by its
91/// [`DiffFile::path`].
92///
93/// A range starts at `start` on [`Self::side`] and ends at `end` on
94/// [`Self::end_side`]. When both sides are the same it covers that side's lines
95/// between the two numbers, in either order. A range ending on the other side
96/// covers the patch body between the two lines in patch order, as a Unified
97/// view shows it.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct DiffLineRange {
100    path: SharedString,
101    side: DiffSide,
102    start: usize,
103    end_side: DiffSide,
104    end: usize,
105}
106
107impl DiffLineRange {
108    /// Creates a range on one side, clamping the lines to at least one.
109    pub fn new(path: impl Into<SharedString>, side: DiffSide, start: usize, end: usize) -> Self {
110        Self {
111            path: path.into(),
112            side,
113            start: start.max(1),
114            end_side: side,
115            end: end.max(1),
116        }
117    }
118    /// Ends the range on `side`, keeping `end` as its line on that side.
119    pub fn with_end_side(mut self, side: DiffSide) -> Self {
120        self.end_side = side;
121        self
122    }
123    /// The [`DiffFile::path`] of the file.
124    pub fn path(&self) -> &SharedString {
125        &self.path
126    }
127    /// The side `start` is on.
128    pub fn side(&self) -> DiffSide {
129        self.side
130    }
131    pub fn start(&self) -> usize {
132        self.start
133    }
134    /// The side `end` is on; the same as [`Self::side`] unless set.
135    pub fn end_side(&self) -> DiffSide {
136        self.end_side
137    }
138    pub fn end(&self) -> usize {
139        self.end
140    }
141    pub(crate) fn start_position(&self) -> DiffLinePosition {
142        DiffLinePosition::new(self.path.clone(), self.side, self.start)
143    }
144    pub(crate) fn end_position(&self) -> DiffLinePosition {
145        DiffLinePosition::new(self.path.clone(), self.end_side, self.end)
146    }
147    /// Whether the range covers lines on one side only.
148    pub(crate) fn is_single_side(&self) -> bool {
149        self.side == self.end_side
150    }
151}
152
153/// One supplied source line and its display form.
154#[derive(Debug)]
155pub(crate) struct SourceLine {
156    line_number: usize,
157    text: SharedString,
158    display: SharedString,
159    chunks: SmallVec<[DisplayChunk; 1]>,
160    counterpart: Option<usize>,
161    // Only expanded tabs need an entry; ordinary UTF-8 bytes map by identity
162    // plus the cumulative expansion of earlier tabs.
163    display_tabs: Vec<DisplayTab>,
164    source: Range<usize>,
165    content_end: usize,
166}
167
168#[derive(Debug)]
169struct DisplayChunk {
170    range: Range<usize>,
171    text: SharedString,
172}
173
174#[derive(Debug)]
175struct DisplayTab {
176    source_offset: usize,
177    display_offset: usize,
178    width: usize,
179}
180
181impl SourceLine {
182    /// The one-based line number in the source file.
183    pub(crate) fn line_number(&self) -> usize {
184        self.line_number
185    }
186    /// The source content, without its line ending.
187    pub(crate) fn text(&self) -> &SharedString {
188        &self.text
189    }
190    /// The content with tabs expanded, as painted.
191    pub(crate) fn display(&self) -> &SharedString {
192        &self.display
193    }
194    /// Display ranges painted as separate text runs, bounding shaping cost.
195    pub(crate) fn chunk_ranges(&self) -> impl Iterator<Item = Range<usize>> + '_ {
196        self.chunks.iter().map(|chunk| chunk.range.clone())
197    }
198    /// The index of the paired line on the other side, if any.
199    pub(crate) fn counterpart(&self) -> Option<usize> {
200        self.counterpart
201    }
202    /// The byte range in the side's source, including the line ending.
203    pub(crate) fn source(&self) -> Range<usize> {
204        self.source.clone()
205    }
206    /// The source offset where the line ending begins.
207    pub(crate) fn content_end(&self) -> usize {
208        self.content_end
209    }
210
211    /// Reuses the retained text for a projected chunk. The fallback supports
212    /// valid partial ranges without making ordinary rendering allocate.
213    pub(crate) fn chunk_text(&self, range: &Range<usize>) -> SharedString {
214        if range.start == 0 && range.end == self.display.len() {
215            return self.display.clone();
216        }
217        let ix = self
218            .chunks
219            .partition_point(|chunk| chunk.range.start < range.start);
220        if let Some(chunk) = self.chunks.get(ix)
221            && chunk.range == *range
222        {
223            return chunk.text.clone();
224        }
225        self.display
226            .get(range.clone())
227            .map_or_else(SharedString::default, SharedString::from)
228    }
229
230    pub(crate) fn source_offset(&self, display_offset: usize) -> usize {
231        let display_offset = display_offset.min(self.display.len());
232        let preceding = self
233            .display_tabs
234            .partition_point(|tab| tab.display_offset <= display_offset);
235        let Some(tab) = preceding.checked_sub(1).map(|ix| &self.display_tabs[ix]) else {
236            return display_offset;
237        };
238        if display_offset < tab.display_offset + tab.width {
239            tab.source_offset
240        } else {
241            display_offset - (tab.display_offset + tab.width - tab.source_offset - 1)
242        }
243    }
244    pub(crate) fn display_range(&self, source: Range<usize>) -> Range<usize> {
245        self.display_offset(source.start)..self.display_offset(source.end)
246    }
247
248    fn display_offset(&self, source_offset: usize) -> usize {
249        let source_offset = source_offset.min(self.text.len());
250        let preceding = self
251            .display_tabs
252            .partition_point(|tab| tab.source_offset < source_offset);
253        let expansion = preceding.checked_sub(1).map_or(0, |ix| {
254            let tab = &self.display_tabs[ix];
255            tab.display_offset + tab.width - tab.source_offset - 1
256        });
257        source_offset + expansion
258    }
259}
260
261/// One row of the side-by-side alignment: a line on either or both sides.
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263pub(crate) struct LinePair {
264    original: Option<usize>,
265    modified: Option<usize>,
266    changed: bool,
267}
268
269impl LinePair {
270    pub(crate) fn new(original: Option<usize>, modified: Option<usize>, changed: bool) -> Self {
271        Self {
272            original,
273            modified,
274            changed,
275        }
276    }
277    pub(crate) fn original(&self) -> Option<usize> {
278        self.original
279    }
280    pub(crate) fn modified(&self) -> Option<usize> {
281        self.modified
282    }
283    pub(crate) fn is_changed(&self) -> bool {
284        self.changed
285    }
286}
287
288/// One `@@` hunk: its pairs and the source lines it supplies on each side.
289#[derive(Clone, Debug)]
290pub(crate) struct Hunk {
291    pairs: Range<usize>,
292    original: Range<usize>,
293    modified: Range<usize>,
294    label: SharedString,
295    /// The one-based original lines the hunk supplies.
296    original_lines: Range<usize>,
297    /// Whether the hunk ended before its declared line counts.
298    truncated: bool,
299}
300
301impl Hunk {
302    pub(crate) fn new(
303        pairs: Range<usize>,
304        original: Range<usize>,
305        modified: Range<usize>,
306        label: SharedString,
307        original_lines: Range<usize>,
308        truncated: bool,
309    ) -> Self {
310        Self {
311            pairs,
312            original,
313            modified,
314            label,
315            original_lines,
316            truncated,
317        }
318    }
319    /// Original lines between the previous hunk, or the file start, and this
320    /// one that the patch does not supply.
321    pub(crate) fn hidden_lines_before(&self, previous: Option<&Hunk>) -> usize {
322        let after = previous.map_or(1, |previous| previous.original_lines.end);
323        self.original_lines.start.saturating_sub(after)
324    }
325    pub(crate) fn pairs(&self) -> Range<usize> {
326        self.pairs.clone()
327    }
328    pub(crate) fn lines(&self, side: DiffSide) -> Range<usize> {
329        match side {
330            DiffSide::Original => self.original.clone(),
331            DiffSide::Modified => self.modified.clone(),
332        }
333    }
334    /// The `@@` header line.
335    pub(crate) fn label(&self) -> &SharedString {
336        &self.label
337    }
338    pub(crate) fn is_truncated(&self) -> bool {
339        self.truncated
340    }
341}
342
343/// One side of a file: its path, unless the side is missing such as
344/// `/dev/null`, and the source fragments the patch supplies.
345#[derive(Default)]
346pub(crate) struct FileSide {
347    path: Option<SharedString>,
348    source: SharedString,
349    lines: Vec<SourceLine>,
350}
351
352impl FileSide {
353    /// Builds a side from its concatenated source and each line's number and
354    /// byte range in it.
355    pub(crate) fn new(
356        path: Option<SharedString>,
357        source: String,
358        lines: impl IntoIterator<Item = (usize, Range<usize>)>,
359    ) -> Self {
360        let lines = lines
361            .into_iter()
362            .map(|(line_number, range)| source_line(&source, range, line_number))
363            .collect();
364        Self {
365            path,
366            source: source.into(),
367            lines,
368        }
369    }
370}
371
372/// How a file changed, in Git's status terms.
373#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
374#[non_exhaustive]
375pub enum DiffFileStatus {
376    Added,
377    Deleted,
378    Modified,
379    Renamed,
380    Copied,
381    /// A whole file shown for reference, from [`DiffFile::unchanged`].
382    Unchanged,
383    /// A working file with conflict markers, from [`DiffFile::parse_conflicts`].
384    Conflicted,
385}
386
387/// One line of the patch body in patch order: an unchanged line on both
388/// sides, or a deleted or added line on one side.
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390pub(crate) struct PatchLine {
391    original: Option<usize>,
392    modified: Option<usize>,
393}
394
395impl PatchLine {
396    pub(crate) fn line(&self, side: DiffSide) -> Option<usize> {
397        match side {
398            DiffSide::Original => self.original,
399            DiffSide::Modified => self.modified,
400        }
401    }
402}
403
404struct DocumentInner {
405    path: SharedString,
406    status: DiffFileStatus,
407    original: FileSide,
408    modified: FileSide,
409    pairs: Vec<LinePair>,
410    hunks: Vec<Hunk>,
411    additions: usize,
412    deletions: usize,
413    extended_headers: Vec<SharedString>,
414    binary: bool,
415    /// Width of the widest line number, in digits.
416    line_number_digits: usize,
417    /// The patch body in order; each side's lines map back into it.
418    patch_lines: Vec<PatchLine>,
419    patch_ixs: [Vec<usize>; 2],
420    conflicts: Vec<DiffConflict>,
421}
422
423/// One changed file parsed from a unified or Git diff.
424///
425/// Only source fragments present in the patch are retained; unavailable
426/// context is never reconstructed or compared. Cloning is cheap.
427#[derive(Clone)]
428pub struct DiffFile {
429    inner: Arc<DocumentInner>,
430    language: Option<SharedString>,
431}
432
433impl DiffFile {
434    /// Parses every file in a unified or Git diff, in patch order, without
435    /// computing differences. Syntax emphasis is prepared later by
436    /// [`super::DiffState`] on a background thread.
437    pub fn parse(patch: &str) -> Result<Vec<Self>, DiffParseError> {
438        super::parser::parse(patch, DiffParseOptions::default())
439    }
440
441    /// Parses like [`DiffFile::parse`], applying the relaxations `options`
442    /// enables. Malformed headers, invalid paths and unordered hunks are still
443    /// errors.
444    pub fn parse_with(patch: &str, options: DiffParseOptions) -> Result<Vec<Self>, DiffParseError> {
445        super::parser::parse(patch, options)
446    }
447
448    /// Assembles a parsed file, pairing counterpart lines and deriving its
449    /// display path, change counts and line-number width.
450    pub(crate) fn new(
451        status: DiffFileStatus,
452        mut original: FileSide,
453        mut modified: FileSide,
454        pairs: Vec<LinePair>,
455        hunks: Vec<Hunk>,
456        extended_headers: Vec<SharedString>,
457        binary: bool,
458    ) -> Self {
459        let (mut additions, mut deletions) = (0, 0);
460        for pair in &pairs {
461            // Conflict lines are unresolved alternatives, not additions.
462            if pair.changed && status != DiffFileStatus::Conflicted {
463                additions += usize::from(pair.modified.is_some());
464                deletions += usize::from(pair.original.is_some());
465            }
466            if let (Some(old), Some(new)) = (pair.original, pair.modified) {
467                original.lines[old].counterpart = Some(new);
468                modified.lines[new].counterpart = Some(old);
469            }
470        }
471        let widest = [&original, &modified]
472            .iter()
473            .filter_map(|side| side.lines.last())
474            .map(|line| line.line_number)
475            .max()
476            .unwrap_or(1);
477        let path = modified
478            .path
479            .clone()
480            .or_else(|| original.path.clone())
481            .unwrap_or_default();
482        let (patch_lines, patch_ixs) = patch_order(&pairs, &hunks, &original, &modified);
483        Self {
484            inner: Arc::new(DocumentInner {
485                path,
486                status,
487                original,
488                modified,
489                pairs,
490                hunks,
491                additions,
492                deletions,
493                extended_headers,
494                binary,
495                line_number_digits: widest.max(1).ilog10() as usize + 1,
496                patch_lines,
497                patch_ixs,
498                conflicts: Vec::new(),
499            }),
500            language: None,
501        }
502    }
503
504    /// Overrides the syntax language detected from the path, using a
505    /// highlighter language name such as `rust` or `javascript`.
506    pub fn with_language(mut self, language: impl Into<SharedString>) -> Self {
507        self.language = Some(language.into());
508        self
509    }
510    /// The syntax language: the override, or the one detected from the path.
511    pub fn language(&self) -> SharedString {
512        self.language
513            .clone()
514            .unwrap_or_else(|| super::presentation::detected_language(self.path()))
515    }
516    pub(crate) fn language_override(&self) -> Option<&SharedString> {
517        self.language.as_ref()
518    }
519    /// How the file changed.
520    pub fn status(&self) -> DiffFileStatus {
521        self.inner.status
522    }
523
524    /// The path to show for this file: the modified path, or the original path
525    /// of a deleted file.
526    pub fn path(&self) -> &SharedString {
527        &self.inner.path
528    }
529    /// The original path, or `None` for an added file.
530    pub fn original_path(&self) -> Option<&SharedString> {
531        self.inner.original.path.as_ref()
532    }
533    /// The modified path, or `None` for a deleted file.
534    pub fn modified_path(&self) -> Option<&SharedString> {
535        self.inner.modified.path.as_ref()
536    }
537    /// Git extended header lines, such as file modes, similarity, renames
538    /// and the binary marker, as they appear in the patch.
539    pub fn extended_headers(&self) -> &[SharedString] {
540        &self.inner.extended_headers
541    }
542    /// Whether the patch reports binary contents rather than textual hunks.
543    pub fn is_binary(&self) -> bool {
544        self.inner.binary
545    }
546    /// Whether a hunk ended before its declared line counts, which only
547    /// [`DiffParseOptions::truncated_hunks`] accepts.
548    pub fn is_truncated(&self) -> bool {
549        self.inner.hunks.iter().any(Hunk::is_truncated)
550    }
551    pub fn additions(&self) -> usize {
552        self.inner.additions
553    }
554    pub fn deletions(&self) -> usize {
555        self.inner.deletions
556    }
557    /// Whether the file changes, including an added or deleted empty file and
558    /// metadata-only changes such as a mode change or pure rename.
559    pub fn has_changes(&self) -> bool {
560        self.additions() > 0
561            || self.deletions() > 0
562            || !self.inner.extended_headers.is_empty()
563            || self.inner.binary
564            || self.original_path().is_none()
565            || self.modified_path().is_none()
566            || self.status() == DiffFileStatus::Conflicted
567    }
568
569    /// Whether the file has one column in every display mode.
570    pub(crate) fn is_single_column(&self) -> bool {
571        matches!(
572            self.status(),
573            DiffFileStatus::Unchanged | DiffFileStatus::Conflicted
574        )
575    }
576    /// Merge conflicts in working-file order; slice indices identify resolutions.
577    pub fn conflicts(&self) -> &[DiffConflict] {
578        &self.inner.conflicts
579    }
580    pub(crate) fn with_conflicts(mut self, conflicts: Vec<DiffConflict>) -> Self {
581        Arc::get_mut(&mut self.inner)
582            .expect("a newly built file is not shared")
583            .conflicts = conflicts;
584        self
585    }
586
587    pub(crate) fn lines_count(&self, side: DiffSide) -> usize {
588        self.lines(side).len()
589    }
590
591    /// Copies patch-provided lines. Unavailable context is omitted, without
592    /// inventing source lines.
593    pub(crate) fn text_for_lines(&self, side: DiffSide, start: usize, end: usize) -> String {
594        let lines = self.lines(side);
595        let start_ix = lines.partition_point(|line| line.line_number < start);
596        let end_ix = lines.partition_point(|line| line.line_number <= end);
597        let selected = &lines[start_ix..end_ix];
598        let (Some(first), Some(last)) = (selected.first(), selected.last()) else {
599            return String::new();
600        };
601        self.source(side)[first.source.start..last.source.end].to_owned()
602    }
603
604    /// The one-based line number of the line at `index` on `side`.
605    pub(crate) fn line_number(&self, side: DiffSide, index: usize) -> usize {
606        self.lines(side)[index].line_number
607    }
608    pub(crate) fn line_index(&self, side: DiffSide, line: usize) -> Option<usize> {
609        self.lines(side)
610            .binary_search_by_key(&line, |source| source.line_number)
611            .ok()
612    }
613
614    pub(crate) fn pairs(&self) -> &[LinePair] {
615        &self.inner.pairs
616    }
617    pub(crate) fn hunks(&self) -> &[Hunk] {
618        &self.inner.hunks
619    }
620    /// Width of the widest supplied line number, in digits.
621    pub(crate) fn line_number_digits(&self) -> usize {
622        self.inner.line_number_digits
623    }
624
625    pub(crate) fn patch_lines(&self) -> &[PatchLine] {
626        &self.inner.patch_lines
627    }
628    /// The position of a side's line in [`Self::patch_lines`].
629    pub(crate) fn patch_ix(&self, side: DiffSide, ix: usize) -> usize {
630        self.inner.patch_ixs[side as usize][ix]
631    }
632
633    pub(crate) fn side_path(&self, side: DiffSide) -> Option<&SharedString> {
634        self.side(side).path.as_ref()
635    }
636
637    fn side(&self, side: DiffSide) -> &FileSide {
638        match side {
639            DiffSide::Original => &self.inner.original,
640            DiffSide::Modified => &self.inner.modified,
641        }
642    }
643    pub(crate) fn lines(&self, side: DiffSide) -> &[SourceLine] {
644        &self.side(side).lines
645    }
646    pub(crate) fn source(&self, side: DiffSide) -> &str {
647        &self.side(side).source
648    }
649}
650
651/// Orders the patch body as Git writes it: within each run of changes, every
652/// deletion precedes every addition. Runs never cross hunk boundaries.
653fn patch_order(
654    pairs: &[LinePair],
655    hunks: &[Hunk],
656    original: &FileSide,
657    modified: &FileSide,
658) -> (Vec<PatchLine>, [Vec<usize>; 2]) {
659    let mut lines = Vec::with_capacity(pairs.len());
660    let mut ixs = [vec![0; original.lines.len()], vec![0; modified.lines.len()]];
661    let ranges = if hunks.is_empty() {
662        vec![0..pairs.len()]
663    } else {
664        hunks.iter().map(Hunk::pairs).collect()
665    };
666    for range in ranges {
667        let mut ix = range.start;
668        while ix < range.end {
669            if !pairs[ix].changed {
670                let pair = pairs[ix];
671                lines.push(PatchLine {
672                    original: pair.original,
673                    modified: pair.modified,
674                });
675                ix += 1;
676                continue;
677            }
678            let start = ix;
679            while ix < range.end && pairs[ix].changed {
680                ix += 1;
681            }
682            for pair in &pairs[start..ix] {
683                if let Some(line) = pair.original {
684                    lines.push(PatchLine {
685                        original: Some(line),
686                        modified: None,
687                    });
688                }
689            }
690            for pair in &pairs[start..ix] {
691                if let Some(line) = pair.modified {
692                    lines.push(PatchLine {
693                        original: None,
694                        modified: Some(line),
695                    });
696                }
697            }
698        }
699    }
700    for (patch_ix, line) in lines.iter().enumerate() {
701        if let Some(ix) = line.original {
702            ixs[0][ix] = patch_ix;
703        }
704        if let Some(ix) = line.modified {
705            ixs[1][ix] = patch_ix;
706        }
707    }
708    (lines, ixs)
709}
710
711/// Builds the display form of one source line from its range in `source`.
712fn source_line(source: &str, range: Range<usize>, line_number: usize) -> SourceLine {
713    let raw = &source[range.clone()];
714    let content = match raw.strip_suffix('\n') {
715        Some(content) => content.strip_suffix('\r').unwrap_or(content),
716        None => raw,
717    };
718    let text = SharedString::from(content.to_owned());
719    let (display, display_tabs): (SharedString, Vec<DisplayTab>) = if content.contains('\t') {
720        let mut display = String::with_capacity(content.len());
721        let mut display_tabs = Vec::new();
722        let mut column = 0;
723        for (ix, ch) in content.char_indices() {
724            if ch == '\t' {
725                let spaces = 4 - column % 4;
726                display_tabs.push(DisplayTab {
727                    source_offset: ix,
728                    display_offset: display.len(),
729                    width: spaces,
730                });
731                for _ in 0..spaces {
732                    display.push(' ');
733                }
734                column += spaces;
735            } else {
736                display.push(ch);
737                column += 1;
738            }
739        }
740        (display.into(), display_tabs)
741    } else {
742        (text.clone(), Vec::new())
743    };
744    let chunks = display_chunks(&display)
745        .into_iter()
746        .map(|range| {
747            let text = if range.start == 0 && range.end == display.len() {
748                display.clone()
749            } else {
750                SharedString::from(display[range.clone()].to_owned())
751            };
752            DisplayChunk { range, text }
753        })
754        .collect();
755    SourceLine {
756        line_number,
757        text,
758        display,
759        chunks,
760        counterpart: None,
761        display_tabs,
762        content_end: range.start + content.len(),
763        source: range,
764    }
765}
766
767#[cfg(test)]
768pub(crate) fn source_lines(text: &str) -> Vec<SourceLine> {
769    let mut offset = 0;
770    text.split_inclusive('\n')
771        .enumerate()
772        .map(|(index, line)| {
773            let range = offset..offset + line.len();
774            offset = range.end;
775            source_line(text, range, index + 1)
776        })
777        .collect()
778}
779
780/// Bound native selection projection while preserving grapheme boundaries.
781/// Exceptionally large clusters split only at UTF-8 boundaries.
782pub(crate) fn display_chunks(text: &str) -> SmallVec<[Range<usize>; 1]> {
783    const MAX_BYTES: usize = 512;
784    if text.len() <= MAX_BYTES {
785        return smallvec![0..text.len()];
786    }
787    let mut chunks = SmallVec::new();
788    let mut start = 0;
789    let mut end = 0;
790    for (ix, grapheme) in text.grapheme_indices(true) {
791        if ix + grapheme.len() - start > MAX_BYTES && start < ix {
792            chunks.push(start..ix);
793            start = ix;
794        }
795        if grapheme.len() > MAX_BYTES {
796            for (relative, character) in grapheme.char_indices() {
797                let offset = ix + relative;
798                if offset + character.len_utf8() - start > MAX_BYTES {
799                    chunks.push(start..offset);
800                    start = offset;
801                }
802            }
803        }
804        end = ix + grapheme.len();
805    }
806    if start < end {
807        chunks.push(start..end);
808    }
809    chunks
810}
811
812/// Test fixtures describe complete file versions; they are turned into a
813/// full-context patch and pass through the production parser.
814#[cfg(test)]
815pub(crate) mod fixture {
816    use similar::{ChangeTag, TextDiff};
817
818    use super::DiffFile;
819
820    fn quoted(name: &str) -> String {
821        format!(
822            "\"{}\"",
823            name.replace('\\', "\\\\")
824                .replace('\"', "\\\"")
825                .replace('\n', "\\n")
826                .replace('\r', "\\r")
827                .replace('\t', "\\t")
828        )
829    }
830
831    /// Builds a document from optional complete sources. Hunk rows are
832    /// removed because these fixtures predate hunk navigation.
833    pub(crate) fn document(
834        original: Option<(&str, &str)>,
835        modified: Option<(&str, &str)>,
836    ) -> DiffFile {
837        let old = original.map_or("", |(_, text)| text);
838        let new = modified.map_or("", |(_, text)| text);
839        let old_lines: Vec<&str> = old.split_inclusive('\n').collect();
840        let new_lines: Vec<&str> = new.split_inclusive('\n').collect();
841        let old_name = original.map_or_else(|| "/dev/null".to_owned(), |(name, _)| quoted(name));
842        let new_name = modified.map_or_else(|| "/dev/null".to_owned(), |(name, _)| quoted(name));
843        // Write one full-context hunk directly: `similar`'s unified writer
844        // does not preserve CRLF line endings.
845        let diff = TextDiff::from_slices(&old_lines, &new_lines);
846        let mut patch = format!("--- {old_name}\n+++ {new_name}\n");
847        if !old_lines.is_empty() || !new_lines.is_empty() {
848            patch.push_str(&format!(
849                "@@ -{},{} +{},{} @@\n",
850                usize::from(!old_lines.is_empty()),
851                old_lines.len(),
852                usize::from(!new_lines.is_empty()),
853                new_lines.len()
854            ));
855            for op in diff.ops() {
856                for change in diff.iter_changes(op) {
857                    patch.push(match change.tag() {
858                        ChangeTag::Equal => ' ',
859                        ChangeTag::Delete => '-',
860                        ChangeTag::Insert => '+',
861                    });
862                    patch.push_str(change.value());
863                    if !change.value().ends_with('\n') {
864                        patch.push_str("\n\\ No newline at end of file\n");
865                    }
866                }
867            }
868        }
869        if original.is_none() {
870            patch.insert_str(0, "diff --git a/fixture b/fixture\nnew file mode 100644\n");
871        } else if modified.is_none() {
872            patch.insert_str(
873                0,
874                "diff --git a/fixture b/fixture\ndeleted file mode 100644\n",
875            );
876        }
877        let mut document = DiffFile::parse(&patch)
878            .unwrap_or_else(|error| panic!("invalid fixture patch: {error}\n{patch}"))
879            .remove(0);
880        std::sync::Arc::get_mut(&mut document.inner)
881            .unwrap()
882            .hunks
883            .clear();
884        document
885    }
886
887    pub(crate) fn modified(name: &str, original: &str, modified: &str) -> DiffFile {
888        document(Some((name, original)), Some((name, modified)))
889    }
890}
891
892#[cfg(test)]
893mod tests {
894    use super::{fixture, *};
895
896    #[test]
897    fn comparison_preserves_source_and_alignment() {
898        fn assert_send_sync<T: Send + Sync>() {}
899        assert_send_sync::<DiffFile>();
900        let doc = fixture::modified(
901            "a.rs",
902            "same\r\n旧值\r\nremoved\r\ntail",
903            "same\r\n新值\r\ntail\r\n",
904        );
905        assert_eq!((doc.additions(), doc.deletions()), (2, 3));
906        assert_eq!(
907            doc.inner.pairs.first().unwrap(),
908            &LinePair {
909                original: Some(0),
910                modified: Some(0),
911                changed: false
912            }
913        );
914        for side in [DiffSide::Original, DiffSide::Modified] {
915            assert_eq!(doc.text_for_lines(side, 1, usize::MAX), doc.source(side));
916        }
917        let same = fixture::modified("empty", "", "");
918        assert!(!same.has_changes());
919        assert_eq!(same.lines_count(DiffSide::Original), 0);
920        let added = fixture::document(None, Some(("new", "one\n\n")));
921        assert_eq!((added.additions(), added.deletions()), (2, 0));
922        assert!(added.inner.pairs.iter().all(|p| p.original.is_none()));
923        let deleted = fixture::document(Some(("old", "one\n")), None);
924        assert_eq!((deleted.additions(), deleted.deletions()), (0, 1));
925        assert!(fixture::document(None, Some(("empty", ""))).has_changes());
926    }
927
928    #[test]
929    fn alignment_covers_each_source_line_once() {
930        for (old, new) in [
931            ("one\ntwo\n", "one\ninserted\ntwo\n"),
932            ("one\nremoved\ntwo\n", "one\ntwo\n"),
933            ("old one\nold two\n", "new one\n"),
934            (
935                "repeat\nold\nrepeat\nsame\nold again\n",
936                "repeat\nnew\nrepeat\nsame\nnew again\n",
937            ),
938            ("same\n", "same\r\n"),
939            ("same\n", "same"),
940            ("a\rb", "a\rc"),
941            ("a\rb\nlast\r", "a\rc\nlast\r\n"),
942            ("", "\n"),
943            ("\n", ""),
944        ] {
945            let doc = fixture::modified("a.txt", old, new);
946            assert_eq!(
947                doc.inner
948                    .pairs
949                    .iter()
950                    .filter_map(|pair| pair.original)
951                    .collect::<Vec<_>>(),
952                (0..doc.lines_count(DiffSide::Original)).collect::<Vec<_>>()
953            );
954            assert_eq!(
955                doc.inner
956                    .pairs
957                    .iter()
958                    .filter_map(|pair| pair.modified)
959                    .collect::<Vec<_>>(),
960                (0..doc.lines_count(DiffSide::Modified)).collect::<Vec<_>>()
961            );
962            assert_eq!(
963                doc.deletions(),
964                doc.inner
965                    .pairs
966                    .iter()
967                    .filter(|pair| pair.changed && pair.original.is_some())
968                    .count()
969            );
970            assert_eq!(
971                doc.additions(),
972                doc.inner
973                    .pairs
974                    .iter()
975                    .filter(|pair| pair.changed && pair.modified.is_some())
976                    .count()
977            );
978            assert!(doc.has_changes());
979            for pair in &doc.inner.pairs {
980                if !pair.changed {
981                    let old_line = &doc.lines(DiffSide::Original)[pair.original.unwrap()];
982                    let new_line = &doc.lines(DiffSide::Modified)[pair.modified.unwrap()];
983                    assert_eq!(&old[old_line.source.clone()], &new[new_line.source.clone()]);
984                }
985            }
986        }
987        let doc = fixture::modified("a.txt", "same\nold\ntail\n", "same\nnew\nextra\ntail\n");
988        assert_eq!(
989            doc.inner.pairs[1],
990            LinePair {
991                original: Some(1),
992                modified: Some(1),
993                changed: true
994            }
995        );
996        assert_eq!(
997            doc.inner.pairs[2],
998            LinePair {
999                original: None,
1000                modified: Some(2),
1001                changed: true
1002            }
1003        );
1004        assert_eq!(doc.text_for_lines(DiffSide::Modified, 2, 3), "new\nextra\n");
1005        assert_eq!(doc.text_for_lines(DiffSide::Original, 99, 100), "");
1006        let bare_cr = fixture::modified("a.txt", "a\rb", "a\rb");
1007        assert!(!bare_cr.has_changes());
1008        assert_eq!(bare_cr.lines_count(DiffSide::Original), 1);
1009        assert_eq!(bare_cr.inner.pairs.len(), 1);
1010    }
1011
1012    #[test]
1013    fn source_display_mapping_preserves_tabs_and_unicode() {
1014        let lines = source_lines("é\t中\t\r\nlast\r");
1015        let first = &lines[0];
1016        assert_eq!(first.text.as_str(), "é\t中\t");
1017        assert_eq!(first.display.as_str(), "é   中   ");
1018        assert_eq!(first.source, 0..9);
1019        assert_eq!(first.content_end, 7);
1020        assert_eq!(first.display_tabs.len(), 2);
1021        assert_eq!(first.display_range(2..3), 2..5);
1022        assert_eq!(first.display_range(6..7), 8..11);
1023        assert_eq!(
1024            first.display_range(0..first.text.len()),
1025            0..first.display.len()
1026        );
1027        for offset in 2..5 {
1028            assert_eq!(first.source_offset(offset), 2);
1029        }
1030        assert_eq!(first.source_offset(5), 3);
1031        assert_eq!(first.source_offset(first.display.len()), first.text.len());
1032        assert_eq!(first.source_offset(usize::MAX), first.text.len());
1033        assert_eq!(lines[1].text.as_str(), "last\r");
1034        assert!(lines[1].display_tabs.is_empty());
1035        assert_eq!(lines[1].source_offset(2), 2);
1036        assert_eq!(lines[1].source_offset(usize::MAX), lines[1].text.len());
1037        assert_eq!(lines[1].display_range(1..4), 1..4);
1038        let plain_unicode = source_lines("中é");
1039        assert!(plain_unicode[0].display_tabs.is_empty());
1040        assert_eq!(plain_unicode[0].display_range(3..5), 3..5);
1041        assert_eq!(plain_unicode[0].source_offset(3), 3);
1042        assert!(source_lines("").is_empty());
1043        assert_eq!(source_lines("\n").len(), 1);
1044        // Compare every byte against the former dense mapping, including
1045        // UTF-8 interiors and all spaces belonging to each expanded tab.
1046        for (display_offset, source_offset) in
1047            [0, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 7].into_iter().enumerate()
1048        {
1049            assert_eq!(first.source_offset(display_offset), source_offset);
1050        }
1051        for (source_offset, display_offset) in [0, 1, 2, 5, 6, 7, 8, 11].into_iter().enumerate() {
1052            assert_eq!(
1053                first.display_range(source_offset..source_offset),
1054                display_offset..display_offset
1055            );
1056        }
1057        let adjacent_tabs = source_lines("\t\té\t");
1058        assert_eq!(adjacent_tabs[0].display.as_str(), "        é   ");
1059        assert_eq!(adjacent_tabs[0].display_tabs.len(), 3);
1060        for (source_offset, display_offset) in [0, 4, 8, 9, 10, 13].into_iter().enumerate() {
1061            assert_eq!(
1062                adjacent_tabs[0].display_range(source_offset..source_offset),
1063                display_offset..display_offset
1064            );
1065        }
1066        let long_line = source_lines("a long source line without tabs uses shared heap storage");
1067        assert_eq!(long_line[0].text.as_ptr(), long_line[0].display.as_ptr());
1068        let long_tab_line = source_lines(&format!("{}\t", "a".repeat(100_000)));
1069        assert_eq!(long_tab_line[0].display_tabs.len(), 1);
1070    }
1071
1072    #[test]
1073    fn display_chunks_retain_complete_utf8_source() {
1074        let ordinary = "an ordinary line uses the existing shared display string";
1075        let long_grapheme = format!("a{}", "\u{301}".repeat(600));
1076        for text in [
1077            String::new(),
1078            ordinary.to_owned(),
1079            "é👩‍💻中".repeat(200),
1080            long_grapheme,
1081        ] {
1082            let chunks = display_chunks(&text);
1083            let mut previous_end = 0;
1084            for range in &chunks {
1085                assert_eq!(range.start, previous_end);
1086                assert!(range.len() <= 512);
1087                assert!(text.is_char_boundary(range.start) && text.is_char_boundary(range.end));
1088                previous_end = range.end;
1089            }
1090            assert_eq!(previous_end, text.len());
1091            assert_eq!(
1092                chunks
1093                    .iter()
1094                    .map(|range| &text[range.clone()])
1095                    .collect::<String>(),
1096                text
1097            );
1098            if text.is_empty() {
1099                continue;
1100            }
1101            let lines = source_lines(&text);
1102            let line = &lines[0];
1103            assert_eq!(line.chunks.len(), chunks.len());
1104            assert_eq!(line.chunk_text(&(0..line.display.len())), line.display);
1105            for chunk in &line.chunks {
1106                let retained = line.chunk_text(&chunk.range);
1107                assert_eq!(retained.as_str(), &text[chunk.range.clone()]);
1108                if retained.len() > 23 {
1109                    assert_eq!(retained.as_ptr(), chunk.text.as_ptr());
1110                }
1111            }
1112        }
1113        let normal_graphemes = "é👩‍💻中".repeat(200);
1114        let boundaries = normal_graphemes
1115            .grapheme_indices(true)
1116            .map(|(ix, _)| ix)
1117            .chain([normal_graphemes.len()])
1118            .collect::<Vec<_>>();
1119        for range in display_chunks(&normal_graphemes) {
1120            assert!(boundaries.contains(&range.start) && boundaries.contains(&range.end));
1121        }
1122        let line = &source_lines(ordinary)[0];
1123        assert_eq!(line.display.as_ptr(), line.chunks[0].text.as_ptr());
1124    }
1125}