From 8935e7a8791eea391a1de41a78278b4bf5dd241d Mon Sep 17 00:00:00 2001
From: Nathan Vegdahl <cessen@cessen.com>
Date: Wed, 23 Jun 2021 23:53:22 -0700
Subject: [PATCH] Fix open-new-line command for CRLF, as well as other bugs.

Fixes #363.

I set out to fix issue #363, but after fixing it discovered some
other things were wrong with the command while testing.  In
summary:
- #363 was because it was still assuming a line ending width
  of 1 char in its indexing calculations, even when actually
  inserting CRLF.
- Aside from #363, it actually needed to set `line_end_index`
  to zero for *all* calculations that use it when line == 0,
  but it was only doing so for a single calculation.
---
 helix-term/src/commands.rs | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs
index 9e44d256..d176fbca 100644
--- a/helix-term/src/commands.rs
+++ b/helix-term/src/commands.rs
@@ -1825,8 +1825,16 @@ fn open(cx: &mut Context, open: Open) {
             Open::Above => line,
         };
 
-        // insert newlines after this index for both Above and Below variants
-        let line_end_index = line_end_char_index(&doc.text().slice(..), line.saturating_sub(1));
+        // Index to insert newlines after, as well as the char width
+        // to use to compensate for those inserted newlines.
+        let (line_end_index, line_end_offset_width) = if line == 0 {
+            (0, 0)
+        } else {
+            (
+                line_end_char_index(&doc.text().slice(..), line.saturating_sub(1)),
+                doc.line_ending.len_chars(),
+            )
+        };
 
         // TODO: share logic with insert_newline for indentation
         let indent_level = indent::suggested_indent_for_pos(
@@ -1844,11 +1852,7 @@ fn open(cx: &mut Context, open: Open) {
         let text = text.repeat(count);
 
         // calculate new selection ranges
-        let pos = if line == 0 {
-            0 // Required since text will have a min len of 1 (\n)
-        } else {
-            offs + line_end_index + 1
-        };
+        let pos = offs + line_end_index + line_end_offset_width;
         for i in 0..count {
             // pos                    -> beginning of reference line,
             // + (i * (1+indent_len)) -> beginning of i'th line from pos