dprint 0.60.0

Binary for dprint code formatter—a pluggable and configurable code formatting platform.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.

// The following code is lifted from Deno's codebase.
// https://github.com/denoland/deno/blob/35f028daf27bb40e86829e7b7cc19aa72a62c0a0/cli/lsp/text.rs

use anyhow::Result;
use anyhow::bail;
use deno_tower_lsp::lsp_types as lsp;
use deno_tower_lsp::lsp_types::TextEdit;
use similar::ChangeTag;
use similar::TextDiff;
use std::collections::HashMap;
use std::time::Duration;
use std::time::Instant;
use text_size::TextRange;
use text_size::TextSize;

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Utf16Char {
  pub start: TextSize,
  pub end: TextSize,
}

impl Utf16Char {
  fn len(&self) -> TextSize {
    self.end - self.start
  }

  fn len_utf16(&self) -> usize {
    if self.len() == TextSize::from(4) { 2 } else { 1 }
  }
}

#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub struct LineIndex {
  utf8_offsets: Vec<TextSize>,
  /// The u8 offset of the end of each line excluding its line ending.
  utf8_line_ends: Vec<TextSize>,
  utf16_lines: HashMap<u32, Vec<Utf16Char>>,
  utf16_offsets: Vec<TextSize>,
}

impl LineIndex {
  pub fn new(text: &str) -> LineIndex {
    let mut utf16_lines = HashMap::new();
    let mut utf16_chars = Vec::new();

    let mut utf8_offsets = vec![0.into()];
    let mut utf8_line_ends = Vec::new();
    let mut utf16_offsets = vec![0.into()];
    let mut was_last_cr = false;
    let mut curr_row = 0.into();
    let mut curr_col = 0.into();
    let mut curr_offset_u16 = 0.into();
    let mut line = 0;
    for c in text.chars() {
      let c_len = TextSize::of(c);
      curr_row += c_len;
      curr_offset_u16 += TextSize::from(c.len_utf16() as u32);
      if c == '\n' {
        let line_ending_len = if was_last_cr { 2 } else { 1 };
        utf8_line_ends.push(curr_row - TextSize::from(line_ending_len));
        was_last_cr = false;
        utf8_offsets.push(curr_row);
        utf16_offsets.push(curr_offset_u16);

        if !utf16_chars.is_empty() {
          utf16_lines.insert(line, utf16_chars);
          utf16_chars = Vec::new();
        }

        curr_col = 0.into();
        line += 1;
        continue;
      }
      was_last_cr = c == '\r';

      if !c.is_ascii() {
        utf16_chars.push(Utf16Char {
          start: curr_col,
          end: curr_col + c_len,
        });
      }
      curr_col += c_len;
    }

    // utf8_offsets and utf16_offsets length is equal to (# of lines + 1)
    utf8_offsets.push(curr_row);
    utf8_line_ends.push(curr_row);
    utf16_offsets.push(curr_offset_u16);

    if !utf16_chars.is_empty() {
      utf16_lines.insert(line, utf16_chars);
    }

    LineIndex {
      utf8_offsets,
      utf8_line_ends,
      utf16_lines,
      utf16_offsets,
    }
  }

  /// Convert a u16 based range to a u8 TextRange.
  pub fn get_text_range(&self, range: lsp::Range) -> Result<TextRange> {
    let start = self.offset(range.start);
    let end = self.offset(range.end);
    if start > end {
      bail!("The start of the range was after its end.")
    }
    Ok(TextRange::new(start, end))
  }

  /// Return a u8 offset based on a u16 position.
  ///
  /// A position past the end of a line is the end of that line, which is how
  /// the language server protocol defines it, and a position past the last
  /// line is the end of the text.
  pub fn offset(&self, position: lsp::Position) -> TextSize {
    let line = position.line as usize;
    let Some(line_end) = self.utf8_line_ends.get(line).copied() else {
      return self.utf8_line_ends.last().copied().unwrap_or_default();
    };
    let line_start = u32::from(self.utf8_offsets[line]);
    let col = u32::from(self.utf16_to_utf8_col(position.line, position.character));
    std::cmp::min(TextSize::from(line_start.saturating_add(col)), line_end)
  }

  /// Returns a u16 position based on a u16 offset.
  pub fn position_utf16(&self, offset: TextSize) -> lsp::Position {
    let line = partition_point(&self.utf16_offsets, |&it| it <= offset) - 1;
    let line_start_offset = self.utf16_offsets[line];
    let col = offset - line_start_offset;

    lsp::Position {
      line: line as u32,
      character: col.into(),
    }
  }

  /// Returns a u16 position based on a u8 offset.
  ///
  /// An offset in the middle of a character is the character's start.
  pub fn position_utf16_from_utf8_offset(&self, offset: TextSize) -> lsp::Position {
    let line = partition_point(&self.utf8_offsets, |&it| it <= offset) - 1;
    let col = offset - self.utf8_offsets[line];

    lsp::Position {
      line: line as u32,
      character: self.utf8_to_utf16_col(line as u32, col),
    }
  }

  /// Returns the zero based number of the last line, which is the line
  /// that the end of the text is on.
  pub fn last_line(&self) -> u32 {
    // only a default index has no lines
    self.utf8_line_ends.len().saturating_sub(1) as u32
  }

  fn utf16_to_utf8_col(&self, line: u32, mut col: u32) -> TextSize {
    if let Some(utf16_chars) = self.utf16_lines.get(&line) {
      for c in utf16_chars {
        if col > u32::from(c.start) {
          col = col.saturating_add(u32::from(c.len()) - c.len_utf16() as u32);
          // a position in the middle of a character (between the two
          // utf-16 code units of a surrogate pair) is the character's start
          if col < u32::from(c.end) {
            col = c.start.into();
            break;
          }
        } else {
          break;
        }
      }
    }

    col.into()
  }

  fn utf8_to_utf16_col(&self, line: u32, col: TextSize) -> u32 {
    let mut utf16_col = u32::from(col);
    if let Some(utf16_chars) = self.utf16_lines.get(&line) {
      for c in utf16_chars {
        if col >= c.end {
          utf16_col -= u32::from(c.len()) - c.len_utf16() as u32;
        } else {
          if col > c.start {
            utf16_col -= u32::from(col - c.start);
          }
          break;
        }
      }
    }
    utf16_col
  }
}

/// Normalizes the line endings of the formatted text to match those of the
/// source text.
///
/// Editors own the line endings of a document, so the language server should
/// not change them based on the plugin's configured newline kind. Doing so
/// produced spurious edits that some editors mishandled, resulting in doubled
/// or garbled newlines (see https://github.com/dprint/dprint/issues/965).
pub fn normalize_to_source_line_endings(source: &str, formatted: String) -> String {
  let Some(source_uses_crlf) = detect_crlf(source) else {
    return formatted; // can't tell what the source uses, so leave it alone
  };
  if Some(source_uses_crlf) == detect_crlf(&formatted) {
    return formatted;
  }
  if source_uses_crlf {
    formatted.replace("\r\n", "\n").replace('\n', "\r\n")
  } else {
    formatted.replace("\r\n", "\n")
  }
}

/// Determines whether the text uses `\r\n` line endings based on the first line
/// ending found. Returns `None` when there are no line endings.
fn detect_crlf(text: &str) -> Option<bool> {
  match text.find('\n') {
    None => None,
    Some(0) => Some(false),
    Some(index) => Some(text.as_bytes()[index - 1] == b'\r'),
  }
}

/// Compare two strings and return a vector of text edit records which are
/// supported by the Language Server Protocol.
pub fn get_edits(a: &str, b: &str, line_index: &LineIndex) -> Vec<TextEdit> {
  if a == b {
    return vec![];
  }
  // Heuristic to detect things like minified files. Diffing is expensive.
  if b.chars().filter(|c| *c == '\n').count() > line_index.utf8_offsets.len() * 3 {
    return vec![replace_whole_file(a, b, line_index)];
  }
  // diff at the character level, coalescing consecutive changes of the same
  // kind into runs so the edit construction below can work a chunk at a time.
  // Within a replacement similar always yields the deletions before the insertions.
  //
  // A deadline bounds pathological inputs. similar bails out and returns a valid
  // (but non-minimal) diff when it's hit, which would produce a large pile of
  // scattered edits, so in that case fall back to replacing the whole file.
  let deadline = Instant::now() + Duration::from_millis(500);
  let diff = TextDiff::configure().deadline(deadline).diff_chars(a, b);
  if Instant::now() >= deadline {
    return vec![replace_whole_file(a, b, line_index)];
  }
  let mut chunks: Vec<(ChangeTag, String)> = Vec::new();
  for change in diff.iter_all_changes() {
    match chunks.last_mut() {
      Some((tag, text)) if *tag == change.tag() => text.push_str(change.value()),
      _ => chunks.push((change.tag(), change.value().to_string())),
    }
  }

  let mut text_edits = Vec::<TextEdit>::new();
  let mut iter = chunks.iter().peekable();
  let mut a_pos = TextSize::from(0);
  loop {
    let chunk = iter.next();
    match chunk {
      None => break,
      Some((ChangeTag::Equal, e)) => {
        a_pos += TextSize::from(e.encode_utf16().count() as u32);
      }
      Some((ChangeTag::Delete, d)) => {
        let start = line_index.position_utf16(a_pos);
        a_pos += TextSize::from(d.encode_utf16().count() as u32);
        let end = line_index.position_utf16(a_pos);
        let range = lsp::Range { start, end };
        match iter.peek() {
          Some((ChangeTag::Insert, i)) => {
            iter.next();
            text_edits.push(TextEdit {
              range,
              new_text: i.to_string(),
            });
          }
          _ => text_edits.push(TextEdit {
            range,
            new_text: "".to_string(),
          }),
        }
      }
      Some((ChangeTag::Insert, i)) => {
        let pos = line_index.position_utf16(a_pos);
        let range = lsp::Range { start: pos, end: pos };
        text_edits.push(TextEdit {
          range,
          new_text: i.to_string(),
        });
      }
    }
  }

  text_edits
}

/// A single edit that replaces the entire document with `new_text`.
fn replace_whole_file(old_text: &str, new_text: &str, line_index: &LineIndex) -> TextEdit {
  TextEdit {
    range: lsp::Range {
      start: lsp::Position::new(0, 0),
      end: line_index.position_utf16_from_utf8_offset(TextSize::of(old_text)),
    },
    new_text: new_text.to_string(),
  }
}

fn partition_point<T, P>(slice: &[T], mut predicate: P) -> usize
where
  P: FnMut(&T) -> bool,
{
  let mut left = 0;
  let mut right = slice.len() - 1;

  while left != right {
    let mid = left + (right - left) / 2;
    // SAFETY:
    // When left < right, left <= mid < right.
    // Therefore left always increases and right always decreases,
    // and either of them is selected.
    // In both cases left <= right is satisfied.
    // Therefore if left < right in a step,
    // left <= right is satisfied in the next step.
    // Therefore as long as left != right, 0 <= left < right < len is satisfied
    // and if this case 0 <= mid < len is satisfied too.
    let value = unsafe { slice.get_unchecked(mid) };
    if predicate(value) {
      left = mid + 1;
    } else {
      right = mid;
    }
  }

  left
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_line_index() {
    let text = "hello\nworld";
    let index = LineIndex::new(text);
    assert_eq!(index.position_utf16(0.into()), lsp::Position { line: 0, character: 0 });
    assert_eq!(index.position_utf16(1.into()), lsp::Position { line: 0, character: 1 });
    assert_eq!(index.position_utf16(5.into()), lsp::Position { line: 0, character: 5 });
    assert_eq!(index.position_utf16(6.into()), lsp::Position { line: 1, character: 0 });
    assert_eq!(index.position_utf16(7.into()), lsp::Position { line: 1, character: 1 });
    assert_eq!(index.position_utf16(8.into()), lsp::Position { line: 1, character: 2 });
    assert_eq!(index.position_utf16(10.into()), lsp::Position { line: 1, character: 4 });
    assert_eq!(index.position_utf16(11.into()), lsp::Position { line: 1, character: 5 });
    assert_eq!(index.position_utf16(12.into()), lsp::Position { line: 1, character: 6 });

    let text = "\nhello\nworld";
    let index = LineIndex::new(text);
    assert_eq!(index.position_utf16(0.into()), lsp::Position { line: 0, character: 0 });
    assert_eq!(index.position_utf16(1.into()), lsp::Position { line: 1, character: 0 });
    assert_eq!(index.position_utf16(2.into()), lsp::Position { line: 1, character: 1 });
    assert_eq!(index.position_utf16(6.into()), lsp::Position { line: 1, character: 5 });
    assert_eq!(index.position_utf16(7.into()), lsp::Position { line: 2, character: 0 });
  }

  #[test]
  fn test_position_utf16_from_utf8_offset() {
    fn position(index: &LineIndex, offset: u32) -> (u32, u32) {
      let position = index.position_utf16_from_utf8_offset(offset.into());
      (position.line, position.character)
    }

    let index = LineIndex::new("hello\nworld");
    assert_eq!(position(&index, 0), (0, 0));
    assert_eq!(position(&index, 5), (0, 5));
    assert_eq!(position(&index, 6), (1, 0));
    assert_eq!(position(&index, 11), (1, 5));

    // é is two utf-8 bytes and one utf-16 code unit, 🦕 is four and two
    let index = LineIndex::new("a\u{e9}b\u{1F995}c\r\n\u{1F995}\u{e9}\n");
    assert_eq!(position(&index, 0), (0, 0));
    assert_eq!(position(&index, 1), (0, 1));
    assert_eq!(position(&index, 3), (0, 2));
    assert_eq!(position(&index, 4), (0, 3));
    assert_eq!(position(&index, 8), (0, 5));
    assert_eq!(position(&index, 9), (0, 6));
    assert_eq!(position(&index, 10), (0, 7));
    assert_eq!(position(&index, 11), (1, 0));
    assert_eq!(position(&index, 15), (1, 2));
    assert_eq!(position(&index, 17), (1, 3));
    assert_eq!(position(&index, 18), (2, 0));
    // in the middle of a character is the start of the character
    assert_eq!(position(&index, 2), (0, 1));
    assert_eq!(position(&index, 5), (0, 3));
    assert_eq!(position(&index, 7), (0, 3));
    assert_eq!(position(&index, 13), (1, 0));

    // round trips with the conversion in the other direction
    let text = "a\u{e9}b\u{1F995}c\n\u{1F995}\u{e9}\n\u{30e1} \u{30e1}";
    let index = LineIndex::new(text);
    for (offset, _) in text.char_indices().chain([(text.len(), ' ')]) {
      let offset = TextSize::from(offset as u32);
      assert_eq!(index.offset(index.position_utf16_from_utf8_offset(offset)), offset);
    }

    assert_eq!(position(&LineIndex::new(""), 0), (0, 0));
  }

  #[test]
  fn test_offset_out_of_range() {
    fn offset(index: &LineIndex, line: u32, character: u32) -> u32 {
      index.offset(lsp::Position { line, character }).into()
    }

    let index = LineIndex::new("ab\ncd");
    assert_eq!(offset(&index, 0, 2), 2);
    // past the end of a line is the end of the line
    assert_eq!(offset(&index, 0, 3), 2);
    assert_eq!(offset(&index, 0, 100), 2);
    assert_eq!(offset(&index, 0, u32::MAX), 2);
    assert_eq!(offset(&index, 1, 100), 5);
    // past the last line is the end of the text
    assert_eq!(offset(&index, 2, 0), 5);
    assert_eq!(offset(&index, 100, 100), 5);

    // excludes the line ending
    let index = LineIndex::new("ab\r\ncd\n");
    assert_eq!(offset(&index, 0, 100), 2);
    assert_eq!(offset(&index, 1, 100), 6);
    assert_eq!(offset(&index, 2, 0), 7);
    assert_eq!(offset(&index, 2, 100), 7);
    assert_eq!(offset(&index, 3, 0), 7);

    // empty text
    let index = LineIndex::new("");
    assert_eq!(offset(&index, 0, 0), 0);
    assert_eq!(offset(&index, 0, 5), 0);
    assert_eq!(offset(&index, 5, 5), 0);

    // multi-byte characters
    let index = LineIndex::new("a\u{1F995}b\n\u{e9}");
    assert_eq!(offset(&index, 0, 1), 1);
    // in the middle of the surrogate pair is the start of the character
    assert_eq!(offset(&index, 0, 2), 1);
    assert_eq!(offset(&index, 0, 3), 5);
    assert_eq!(offset(&index, 0, 4), 6);
    assert_eq!(offset(&index, 0, 100), 6);
    assert_eq!(offset(&index, 1, 1), 9);
    assert_eq!(offset(&index, 1, 100), 9);
  }

  #[test]
  fn test_last_line() {
    assert_eq!(LineIndex::new("").last_line(), 0);
    assert_eq!(LineIndex::new("ab").last_line(), 0);
    assert_eq!(LineIndex::new("ab\ncd").last_line(), 1);
    assert_eq!(LineIndex::new("ab\r\ncd\n").last_line(), 2);
    assert_eq!(LineIndex::default().last_line(), 0);
  }

  #[test]
  fn test_get_text_range_out_of_range() {
    fn range(index: &LineIndex, start: (u32, u32), end: (u32, u32)) -> Result<(u32, u32)> {
      let range = index.get_text_range(lsp::Range {
        start: lsp::Position {
          line: start.0,
          character: start.1,
        },
        end: lsp::Position { line: end.0, character: end.1 },
      })?;
      Ok((range.start().into(), range.end().into()))
    }

    let index = LineIndex::new("ab\ncd");
    // the start is past the end of its line, which was previously after the end
    assert_eq!(range(&index, (0, 100), (1, 0)).unwrap(), (2, 3));
    assert_eq!(range(&index, (0, 0), (0, 10)).unwrap(), (0, 2));
    assert_eq!(range(&index, (0, 0), (100, 0)).unwrap(), (0, 5));
    // start after the end
    assert!(range(&index, (0, 2), (0, 1)).is_err());
    assert!(range(&index, (1, 0), (0, 0)).is_err());
  }

  #[test]
  fn test_char_len() {
    assert_eq!('メ'.len_utf8(), 3);
    assert_eq!('メ'.len_utf16(), 1);
    assert_eq!('编'.len_utf8(), 3);
    assert_eq!('编'.len_utf16(), 1);
    assert_eq!('🦕'.len_utf8(), 4);
    assert_eq!('🦕'.len_utf16(), 2);
  }

  #[test]
  fn test_empty_index() {
    let col_index = LineIndex::new(
      "
const C: char = 'x';
",
    );
    assert_eq!(col_index.utf16_lines.len(), 0);
  }

  #[test]
  fn test_single_char() {
    let col_index = LineIndex::new(
      "
const C: char = 'メ';
",
    );

    assert_eq!(col_index.utf16_lines.len(), 1);
    assert_eq!(col_index.utf16_lines[&1].len(), 1);
    assert_eq!(
      col_index.utf16_lines[&1][0],
      Utf16Char {
        start: 17.into(),
        end: 20.into()
      }
    );

    // UTF-16 to UTF-8, no changes
    assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15));

    // UTF-16 to UTF-8
    assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21));

    let col_index = LineIndex::new("a𐐏b");
    assert_eq!(col_index.utf16_to_utf8_col(0, 3), TextSize::from(5));
  }

  #[test]
  fn test_string() {
    let col_index = LineIndex::new(
      "
const C: char = \"メ メ\";
",
    );

    assert_eq!(col_index.utf16_lines.len(), 1);
    assert_eq!(col_index.utf16_lines[&1].len(), 2);
    assert_eq!(
      col_index.utf16_lines[&1][0],
      Utf16Char {
        start: 17.into(),
        end: 20.into()
      }
    );
    assert_eq!(
      col_index.utf16_lines[&1][1],
      Utf16Char {
        start: 21.into(),
        end: 24.into()
      }
    );

    // UTF-16 to UTF-8
    assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15));

    // メ UTF-8: 0xE3 0x83 0xA1, UTF-16: 0x30E1
    assert_eq!(col_index.utf16_to_utf8_col(1, 17), TextSize::from(17)); // first メ at 17..20
    assert_eq!(col_index.utf16_to_utf8_col(1, 18), TextSize::from(20)); // space
    assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21)); // second メ at 21..24

    assert_eq!(col_index.utf16_to_utf8_col(2, 15), TextSize::from(15));
  }

  #[test]
  fn test_get_edits() {
    let a = "abcdefg";
    let b = "a\nb\nchije\nfg\n";
    let actual = get_edits(a, b, &LineIndex::new(a));
    assert_eq!(
      actual,
      vec![
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 0, character: 1 },
            end: lsp::Position { line: 0, character: 1 }
          },
          new_text: "\n".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 0, character: 2 },
            end: lsp::Position { line: 0, character: 2 }
          },
          new_text: "\n".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 0, character: 3 },
            end: lsp::Position { line: 0, character: 4 }
          },
          new_text: "hij".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 0, character: 5 },
            end: lsp::Position { line: 0, character: 5 }
          },
          new_text: "\n".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 0, character: 7 },
            end: lsp::Position { line: 0, character: 7 }
          },
          new_text: "\n".to_string()
        },
      ]
    );
  }

  #[test]
  fn test_replace_whole_file_non_ascii() {
    fn end(old_text: &str) -> lsp::Position {
      let edit = replace_whole_file(old_text, "new", &LineIndex::new(old_text));
      assert_eq!(edit.range.start, lsp::Position { line: 0, character: 0 });
      assert_eq!(edit.new_text, "new");
      edit.range.end
    }

    assert_eq!(end("ab\ncd"), lsp::Position { line: 1, character: 2 });
    assert_eq!(end("ab\ncd\n"), lsp::Position { line: 2, character: 0 });
    // é is two utf-8 bytes and one utf-16 code unit, 🦕 is four and two
    assert_eq!(end("\u{e9}\nab"), lsp::Position { line: 1, character: 2 });
    assert_eq!(end("a\u{e9}\u{1F995}"), lsp::Position { line: 0, character: 4 });
    assert_eq!(end("\u{e9}\u{e9}\u{e9}\n"), lsp::Position { line: 1, character: 0 });
    assert_eq!(end("\u{1F995}\r\n\u{e9}b\u{1F995}"), lsp::Position { line: 1, character: 4 });
  }

  #[test]
  fn test_normalize_to_source_line_endings() {
    // source LF, formatted CRLF -> formatted becomes LF
    assert_eq!(normalize_to_source_line_endings("a\nb\n", "a\r\nb\r\nc\r\n".to_string()), "a\nb\nc\n");
    // source CRLF, formatted LF -> formatted becomes CRLF
    assert_eq!(normalize_to_source_line_endings("a\r\nb\r\n", "a\nb\nc\n".to_string()), "a\r\nb\r\nc\r\n");
    // matching line endings are left untouched (no allocation churn issues)
    assert_eq!(normalize_to_source_line_endings("a\nb\n", "a\nb\n".to_string()), "a\nb\n");
    assert_eq!(normalize_to_source_line_endings("a\r\nb\r\n", "a\r\nb\r\n".to_string()), "a\r\nb\r\n");
    // no line endings in source -> leave formatted as-is
    assert_eq!(normalize_to_source_line_endings("abc", "abc\r\n".to_string()), "abc\r\n");
    // leading newline still detects the source kind
    assert_eq!(normalize_to_source_line_endings("\nabc", "\r\nabc".to_string()), "\nabc");
  }

  #[test]
  fn test_get_edits_after_normalizing_line_endings() {
    // when only the line endings differ, normalizing should produce no edits (#965)
    let a = "line1\nline2\nline3\n";
    let formatted = "line1\r\nline2\r\nline3\r\n".to_string();
    let new_text = normalize_to_source_line_endings(a, formatted);
    assert_eq!(get_edits(a, &new_text, &LineIndex::new(a)), vec![]);
  }

  #[test]
  fn test_get_edits_mbc() {
    let a = "const bar = \"👍🇺🇸😃\";\nconsole.log('hello deno')\n";
    let b = "const bar = \"👍🇺🇸😃\";\nconsole.log(\"hello deno\");\n";
    let actual = get_edits(a, b, &LineIndex::new(a));
    assert_eq!(
      actual,
      vec![
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 1, character: 12 },
            end: lsp::Position { line: 1, character: 13 }
          },
          new_text: "\"".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 1, character: 23 },
            end: lsp::Position { line: 1, character: 24 }
          },
          new_text: "\"".to_string()
        },
        TextEdit {
          range: lsp::Range {
            start: lsp::Position { line: 1, character: 25 },
            end: lsp::Position { line: 1, character: 25 }
          },
          new_text: ";".to_string()
        },
      ]
    )
  }
}