From e5b5b4448ce0981a7a89a8c43df77d71bfa9cc96 Mon Sep 17 00:00:00 2001
From: Thomas Munro <tmunro@postgresql.org>
Date: Sun, 10 Jul 2022 16:30:03 +1200
Subject: [PATCH] Fix \watch's interaction with libedit on ^C.

When you hit ^C, the terminal driver in Unix-like systems echoes "^C" as
well as sending an interrupt signal (depending on stty settings).  At
least libedit (but maybe also libreadline) is then confused about the
current cursor location, and corrupts the display if you try to scroll
back.  Fix, by moving to a new line before the next prompt is displayed.

Back-patch to all supported released.

Author: Pavel Stehule <pavel.stehule@gmail.com>
Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/3278793.1626198638%40sss.pgh.pa.us
---
 src/bin/psql/command.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index d66f83d8ba..9e62e15385 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -4899,6 +4899,14 @@ do_watch(PQExpBuffer query_buf, double sleep)
 		sigint_interrupt_enabled = false;
 	}
 
+	/*
+	 * If the terminal driver echoed "^C", libedit/libreadline might be
+	 * confused about the cursor position.  Therefore, inject a newline
+	 * before the next prompt is displayed.
+	 */
+	fprintf(stdout, "\n");
+	fflush(stdout);
+
 	pg_free(title);
 	return (res >= 0);
 }