LoginSignup
3
4

More than 5 years have passed since last update.

カラー表示でも画面が崩れないUTF-8対応のless.exe

Posted at

Windowsのコマンドプロンプトで使えるUTF-8に対応したless.exeはいくつかあるのですが、私の周囲では@mattnさんのパッチを適用したバージョンが有名です。

しかし、このless.exeを試しに使ってみたところ、日本語をカラー表示した時に画面が崩れてしまうことが分かりました。

気になったので調べてみたところ、lessの-Rオプションを指定した時に、NUL終端されていない文字列を渡されるケースが漏れていたのが原因でしたので、そこを修正してみたのが下記のパッチです。

less-458.utf-8.patch
diff -Naur less-458.orig/Makefile.wnm less-458/Makefile.wnm
--- less-458.orig/Makefile.wnm  Fri Apr  5 01:55:07 2013
+++ less-458/Makefile.wnm   Thu Sep  5 21:27:07 2013
@@ -6,7 +6,7 @@
 CC = cl

 # Normal flags
-CFLAGS = /nologo /ML /W3 /GX /O2 /I "." /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /c
+CFLAGS = /nologo /W3 /EHsc /O2 /I "." /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D"_CRT_SECURE_NO_WARNINGS" /c
 LDFLAGS = /nologo /subsystem:console /incremental:no /machine:I386

 # Debugging flags
@@ -14,7 +14,7 @@
 #LDFLAGS = /nologo /subsystem:console /incremental:yes /debug /machine:I386

 LD = link
-LIBS = user32.lib
+LIBS = user32.lib /nodefaultlib:libc.lib

 #### End of system configuration section. ####

diff -Naur less-458.orig/screen.c less-458/screen.c
--- less-458.orig/screen.c  Fri Apr  5 01:55:05 2013
+++ less-458/screen.c   Thu Sep  5 21:27:07 2013
@@ -2490,7 +2490,29 @@
 {
 #if MSDOS_COMPILER==WIN32C
    DWORD written;
-   WriteConsole(con_out, text, len, &written, NULL);
+   extern int utf_mode;
+   if (utf_mode)
+   {
+       DWORD wlen = 0;
+       char *text_prev = text;
+       char *text_end = text + len;
+       wchar_t *wtext = (wchar_t*) malloc(len * sizeof(wchar_t));
+       while (text < text_end && *text)
+       {
+           wtext[wlen++] =  (wchar_t) step_char(&text, TRUE, text_end);
+           if (text == text_prev)
+               break;
+           else
+               text_prev = text;
+       }
+
+       if (wlen > 0)
+           WriteConsoleW(con_out, wtext, wlen, &written, NULL);
+       free(wtext);
+   } else
+   {
+       WriteConsole(con_out, text, len, &written, NULL);
+   }
 #else
    char c = text[len];
    text[len] = '\0';

本家からソースを落として上記のパッチを当ててビルドしてください。

set LESSCHARSET=utf-8 することで、文字エンコーディングがUTF-8なファイルを閲覧できます。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4