From 2762f323bf6407093dc814591e7c6d08ca82bc6f Mon Sep 17 00:00:00 2001
From: stijn <stijn@ignitron.net>
Date: Thu, 21 Jun 2018 11:54:49 +0200
Subject: [PATCH] windows: Fix line wrapping behaviour on the REPL.

This enables going back to previous wrapped lines using backspace or left
arrow: instead of just sticking to the beginning of a line, the cursor will
move a line up.
---
 ports/windows/windows_mphal.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/ports/windows/windows_mphal.c b/ports/windows/windows_mphal.c
index 153b04423..1e3a09291 100644
--- a/ports/windows/windows_mphal.c
+++ b/ports/windows/windows_mphal.c
@@ -106,12 +106,23 @@ void mp_hal_set_interrupt_char(char c) {
 }
 
 void mp_hal_move_cursor_back(uint pos) {
+    if (!pos) {
+        return;
+    }
     assure_conout_handle();
     CONSOLE_SCREEN_BUFFER_INFO info;
     GetConsoleScreenBufferInfo(con_out, &info);
     info.dwCursorPosition.X -= (short)pos;
-    if (info.dwCursorPosition.X < 0) {
+    // Move up a line if needed.
+    while (info.dwCursorPosition.X < 0) {
+        info.dwCursorPosition.X = info.dwSize.X + info.dwCursorPosition.X;
+        info.dwCursorPosition.Y -= 1;
+    }
+    // Caller requested to move out of the screen. That's not possible so just clip,
+    // it's the caller's responsibility to not let this happen.
+    if (info.dwCursorPosition.Y < 0) {
         info.dwCursorPosition.X = 0;
+        info.dwCursorPosition.Y = 0;
     }
     SetConsoleCursorPosition(con_out, info.dwCursorPosition);
 }
-- 
GitLab