From 73c4e24a8e6c0bb078f5fb497edb484bd5523f12 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jakub=20Vr=C3=A1na?= <jakub@vrana.cz>
Date: Tue, 20 Dec 2016 16:45:20 +0100
Subject: [PATCH] [sublime bindings] Don't sort last line with no selected
 chars

Selecting two full lines including line ends makes a selection from
line 1 to line 3 (ch: 0). This command used to sort three lines (1 to
3) which is not what I expect. This change makes it sort only two
lines if there are no selected characters on the last line.

It also fixes a fatal error if there are more than one selection on
the same line (the code used 'range' instead of 'ranges').

It also selects the trailing newline after sorting the lines so that
the whole lines are selected.
---
 keymap/sublime.js    | 5 +++--
 test/sublime_test.js | 8 ++++----
 2 files changed, 7 insertions(+), 6 deletions(-)

diff --git a/keymap/sublime.js b/keymap/sublime.js
index c5d2906bc..3d112ab96 100644
--- a/keymap/sublime.js
+++ b/keymap/sublime.js
@@ -310,7 +310,8 @@
       if (range.empty()) continue;
       var from = range.from().line, to = range.to().line;
       while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
-        to = range[++i].to().line;
+        to = ranges[++i].to().line;
+      if (!ranges[i].to().ch) to--;
       toSort.push(from, to);
     }
     if (toSort.length) selected = true;
@@ -331,7 +332,7 @@
             return a < b ? -1 : a == b ? 0 : 1;
           });
         cm.replaceRange(lines, start, end);
-        if (selected) ranges.push({anchor: start, head: end});
+        if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
       }
       if (selected) cm.setSelections(ranges, 0);
     });
diff --git a/test/sublime_test.js b/test/sublime_test.js
index c5c19c0a2..57f16485e 100644
--- a/test/sublime_test.js
+++ b/test/sublime_test.js
@@ -249,11 +249,11 @@
          "undo",
          setSel(0, 0, 2, 0,
                 3, 0, 5, 0),
-         "sortLines", val("a\nb\nc\nA\nB\nC"),
-         hasSel(0, 0, 2, 1,
-                3, 0, 5, 1),
+         "sortLines", val("b\nc\na\nB\nC\nA"),
+         hasSel(0, 0, 2, 0,
+                3, 0, 5, 0),
          "undo",
-         setSel(1, 0, 4, 0), "sortLinesInsensitive", val("c\na\nB\nb\nC\nA"));
+         setSel(1, 0, 5, 0), "sortLinesInsensitive", val("c\na\nB\nb\nC\nA"));
 
   stTest("bookmarks", "abc\ndef\nghi\njkl",
          Pos(0, 1), "toggleBookmark",
-- 
GitLab