From 12b31a684908a81e40889585a0fb69a5313a7eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20M=C3=ADchal?= Date: Fri, 17 Dec 2021 05:43:58 +0200 Subject: [PATCH] Move cursor to the beginning of the line before erasing (#126) The \033[K escape sequence signifies 'clear from cursor position to the end of the line'. Without moving the cursor to the beggining of the line first it results in no text being deleted. The behaviour of Carriage Return (\r) in terminal emulators is not formally standardized but it is generally interpreted as a move to the beginning of the line. Fixes https://github.com/briandowns/spinner/issues/123 --- spinner.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/spinner.go b/spinner.go index 3462819..5f3a8bc 100644 --- a/spinner.go +++ b/spinner.go @@ -395,7 +395,7 @@ func (s *Spinner) UpdateCharSet(cs []string) { s.mu.Unlock() } -// erase deletes written characters. +// erase deletes written characters on the current line. // Caller must already hold s.lock. func (s *Spinner) erase() { n := utf8.RuneCountInString(s.lastOutput) @@ -405,7 +405,14 @@ func (s *Spinner) erase() { s.lastOutput = "" return } - fmt.Fprintf(s.Writer, "\033[K") // erases to end of line + + // Taken from https://en.wikipedia.org/wiki/ANSI_escape_code: + // \r - Carriage return - Moves the cursor to column zero + // \033[K - Erases part of the line. If n is 0 (or missing), clear from + // cursor to the end of the line. If n is 1, clear from cursor to beginning + // of the line. If n is 2, clear entire line. Cursor position does not + // change. + fmt.Fprintf(s.Writer, "\r\033[K") s.lastOutput = "" }