From 0277876eac340b46a0201fc29b70ccb5e5f83f58 Mon Sep 17 00:00:00 2001
From: Victor Wagner <vitus@wagner.pp.ru>
Date: Fri, 18 Mar 2016 12:46:51 +0300
Subject: [PATCH] Force output codepage to 65001 and restore before quit

---
 charset.c | 14 +++++++++++++-
 main.c    |  3 +++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/charset.c b/charset.c
index 4c62664..69b035f 100644
--- a/charset.c
+++ b/charset.c
@@ -14,6 +14,9 @@
  */
 
 #include "less.h"
+#if MSDOS_COMPILER==WIN32C
+#include <windows.h>
+#endif
 #if HAVE_LOCALE
 #include <locale.h>
 #include <ctype.h>
@@ -319,7 +322,15 @@ set_charset()
 		ichardef(s);
 		return;
 	}
-
+#ifdef WIN32
+	SetConsoleOutputCP(65001);
+    _setmode(_fileno(stdout),_O_U8TEXT);
+    _setmode(_fileno(stderr),_O_U8TEXT);
+	if (isatty(fileno(stdin))) 
+		_setmode(_fileno(stdin),_O_U8TEXT);
+	icharset("UTF-8",0);
+	
+#else 
 #if HAVE_LOCALE
 #ifdef CODESET
 	/*
@@ -364,6 +375,7 @@ set_charset()
 	(void) icharset("latin1", 1);
 #endif
 #endif
+#endif
 }
 
 /*
diff --git a/main.c b/main.c
index 149999c..e4f35b9 100644
--- a/main.c
+++ b/main.c
@@ -51,6 +51,7 @@ extern int	jump_sline;
 
 #ifdef WIN32
 static char consoleTitle[256];
+static int  savedConsoleCodePage;
 #endif
 
 extern int	less_is_more;
@@ -103,6 +104,7 @@ main(argc, argv)
 		}
 	}
 	GetConsoleTitle(consoleTitle, sizeof(consoleTitle)/sizeof(char));
+	savedConsoleCodePage = GetConsoleOutputCP();	
 #endif /* WIN32 */
 
 	/*
@@ -404,6 +406,7 @@ quit(status)
 #endif
 #ifdef WIN32
 	SetConsoleTitle(consoleTitle);
+	SetConsoleOutputCP(savedConsoleCodePage);
 #endif
 	close_getchr();
 	exit(status);
-- 
2.39.5