home *** CD-ROM | disk | FTP | other *** search
/ vim.ftp.fu-berlin.de / 2015-02-03.vim.ftp.fu-berlin.de.tar / vim.ftp.fu-berlin.de / amiga / vim46src.lha / vim-4.6 / src / win32.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-02-11  |  73.6 KB  |  3,419 lines

  1. /* vi:set ts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved        by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  */
  8.  
  9. /*
  10.  * win32.c
  11.  *
  12.  * Win32 (Windows NT and Windows 95) system-dependent routines.
  13.  * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
  14.  * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
  15.  *
  16.  * George V. Reilly <gvr@halcyon.com> wrote most of this.
  17.  * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
  18.  */
  19.  
  20. #include <io.h>
  21. #include "vim.h"
  22. #include "globals.h"
  23. #include "option.h"
  24. #include "proto.h"
  25. #ifdef HAVE_FCNTL_H
  26. # include <fcntl.h>
  27. #endif
  28. #include <sys/types.h>
  29. #include <errno.h>
  30. #include <signal.h>
  31. #include <limits.h>
  32. #include <process.h>
  33. #include <time.h>
  34.  
  35. #define STRICT
  36. #define WIN32_LEAN_AND_MEAN
  37. #include <windows.h>
  38.  
  39. #undef chdir
  40. #include <direct.h>
  41.  
  42.  
  43. /* Disgusting hack for getting dead keys to work properly on Windows 95.
  44.  * See below for the gory details.  If you're only running on NT or
  45.  * if you're an English-speaking user, you can comment this out. */
  46.  
  47. /* WARNING: this code is experimental and incomplete and it does not work.
  48.  * Don't use it! */
  49. /* #define WIN95_DEAD_KEYS_HACK */
  50.  
  51.  
  52. /* Force all filenames to lowercase */
  53. /* #define DOWNCASE_FILENAMES */
  54.  
  55.  
  56. /* Record all output and all keyboard & mouse input */
  57. /* #define MCH_WRITE_DUMP */
  58.  
  59. #ifdef MCH_WRITE_DUMP
  60. FILE* fdDump = NULL;
  61. #endif /* MCH_WRITE_DUMP */
  62.  
  63.  
  64. /*
  65.  * When generating prototypes for Win32 on Unix, these lines make the syntax
  66.  * errors disappear.  They do not need to be correct.
  67.  */
  68. #ifdef PROTO
  69. # define HANDLE int
  70. # define SMALL_RECT int
  71. # define COORD int
  72. # define SHORT int
  73. # define WORD int
  74. # define DWORD int
  75. # define BOOL int
  76. # define LPSTR int
  77. # define KEY_EVENT_RECORD int
  78. # define MOUSE_EVENT_RECORD int
  79. # define WINAPI
  80. # define CONSOLE_CURSOR_INFO int
  81. # define LPCSTR char_u *
  82. # define WINBASEAPI 
  83. #endif
  84.  
  85. /* Undocumented API in kernel32.dll needed to work around dead key bug in
  86.  * console-mode applications in NT 4.0.  If you switch keyboard layouts
  87.  * in a console app to a layout that includes dead keys and then hit a
  88.  * dead key, a call to ToAscii will trash the stack.  My thanks to Ian James
  89.  * and Michael Dietrich for helping me figure out this workaround.
  90.  */
  91.  
  92. /* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
  93. typedef WINBASEAPI BOOL (*PFNGCKLN)(LPSTR);
  94. static PFNGCKLN    s_pfnGetConsoleKeyboardLayoutName = NULL;
  95.  
  96.  
  97. /* Win32 Console handles for input and output */
  98. static HANDLE g_hConIn  = INVALID_HANDLE_VALUE;
  99. static HANDLE g_hSavOut = INVALID_HANDLE_VALUE;
  100. static HANDLE g_hCurOut = INVALID_HANDLE_VALUE;
  101. static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
  102.  
  103. /* Win32 Screen buffer,coordinate,console I/O information */
  104. static SMALL_RECT g_srScrollRegion;
  105. static COORD      g_coord;    /* 0-based, but external coords are 1-based */
  106.  
  107. /* The attribute of the screen when the editor was started */
  108. static WORD  g_attrDefault = 7;  /* lightgray text on black background */
  109. static WORD  g_attrCurrent;
  110.  
  111. static int g_fCBrkPressed = FALSE;  /* set by ctrl-break interrupt */
  112. static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
  113.  
  114. static void termcap_mode_start();
  115. static void termcap_mode_end();
  116. static void clear_chars(COORD coord, DWORD n);
  117. static void clear_screen();
  118. static void clear_to_end_of_display();
  119. static void clear_to_end_of_line();
  120. static void scroll(unsigned cLines);
  121. static void set_scroll_region(unsigned left, unsigned top,
  122.                               unsigned right, unsigned bottom);
  123. static void insert_lines(unsigned cLines);
  124. static void delete_lines(unsigned cLines);
  125. static void gotoxy(unsigned x, unsigned y);
  126. static void normvideo();
  127. static void textattr(WORD wAttr);
  128. static void standout();
  129. static void standend();
  130. static void visual_bell();
  131. static void cursor_visible(BOOL fVisible);
  132. static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite, DWORD* pcchWritten);
  133.  
  134.  
  135. /* This symbol is not defined in older versions of the SDK or Visual C++ */
  136.  
  137. #ifndef VER_PLATFORM_WIN32_WINDOWS
  138. # define VER_PLATFORM_WIN32_WINDOWS 1
  139. #endif
  140.  
  141. static DWORD g_PlatformId;
  142.  
  143. /*
  144.  *    Returns VER_PLATFORM_WIN32_NT (NT) or VER_PLATFORM_WIN32_WINDOWS (Win95)
  145.  */
  146.     static DWORD
  147. PlatformId()
  148. {
  149.     OSVERSIONINFO ovi;
  150.  
  151.     ovi.dwOSVersionInfoSize = sizeof(ovi);
  152.     GetVersionEx(&ovi);
  153.  
  154.     g_PlatformId = ovi.dwPlatformId;
  155.  
  156.     return g_PlatformId;
  157. }
  158.  
  159.  
  160.  
  161. #define SHIFT  (SHIFT_PRESSED)
  162. #define CTRL   (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
  163. #define ALT    (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED)
  164. #define ALT_GR (RIGHT_ALT_PRESSED  | LEFT_CTRL_PRESSED) 
  165.  
  166.  
  167.  
  168. #ifdef WIN95_DEAD_KEYS_HACK
  169.  
  170. /* The problem that this code attempts to work around is that the
  171.  * console-mode input routines are broken on Windows 95 if you're
  172.  * using dead keys.  A dead key is an accent key, such as acute,
  173.  * grave, or umlaut, that doesn't produce a character by itself,
  174.  * but when followed by another key, produces an accented character,
  175.  * such as a-acute, e-grave, u-umlaut, n-tilde, and so on.  Very
  176.  * useful for most European languages.  English-language keyboard
  177.  * layouts don't use dead keys, as far as I know.
  178.  *
  179.  * Unfortunately, the KEY_EVENT_RECORD contains the wrong data when
  180.  * I get the keystroke that's supposed to have an accented character.
  181.  * The AsciiChar part contains the unaccented character instead.
  182.  *
  183.  * The following code (unsuccessfully) attempts to fake the dead keys.
  184.  * I rely on the fact that the virtual key code and the scan key code
  185.  * are actually correct for both the dead key and the following letter.
  186.  * I set up a second thread that creates a hidden window and then sits
  187.  * in a little message loop.  I send it all the data from the dead key
  188.  * and the following key (each thread has its own keyboard input state),
  189.  * and it sends its own hidden window a suitable sequence of WM_KEYDOWN
  190.  * and WM_KEYUP messages.  TranslateMessage causes these to be turned
  191.  * into WM_DEADCHAR and WM_CHAR messages.  Almost.  It works as long as
  192.  * neither the dead key nor the following key are shifted, but after
  193.  * happens, that it goes to hell in a handbasket.
  194.  *
  195.  * I have spent many, many hours trying all sorts of approaches to get
  196.  * dead keys to work with Windows 95 and I am completely stumped.
  197.  *
  198.  * So why not just have all the input come directly via WM_CHAR?
  199.  * Because this is a console application and I don't know how to do that.
  200.  *
  201.  * So how do you type dead keys?  Answer: you don't, not if you're using
  202.  * Windows 95, not until either Microsoft fixes the bug (and they haven't
  203.  * as of Service Pack 1) or someone (me?) produces a true Windows GUI
  204.  * version of Vim.
  205.  *
  206.  * If someone can come up with some workaround, please, please, please
  207.  * send it to me.
  208.  *
  209.  * You can, however, use digraphs.  They're not as convenient as dead
  210.  * keys, especially if you're used to typing dead keys, but they do
  211.  * work and they're better than nothing.
  212.  *
  213.  * If you're using NT, the dead keys work fine.  At least they do with
  214.  * NT 3.51, Service Pack 3, US Edition.  I haven't tested it with any
  215.  * other version of NT.  I did hear one report that NT3.51, SP3, UK edition
  216.  * had problems with CTRL-vowels, but I don't know about dead keys.
  217.  *
  218.  * /George V. Reilly, 3/15/1996
  219.  *
  220.  * On 24th March, I was told by a senior developer at Microsoft:
  221.  *   Win95 console support has always been and will always be flaky.
  222.  *   
  223.  *   The flakiness is unavoidable because we are stuck between the world of
  224.  *   MS-DOS keyboard TSRs like KEYB (which wants to cook the data; important
  225.  *   for international) and the world of Win32.
  226.  *   
  227.  *   So keys that don't "exist" in MS-DOS land (like dead keys) have a
  228.  *   very tenuous existence in Win32 console land.  Keys that act
  229.  *   differently between MS-DOS land and Win32 console land (like capslock)
  230.  *   will act flaky.
  231.  *   
  232.  *   Don't even *mention* the problems with multiple language keyboard
  233.  *   layouts...
  234.  */
  235.  
  236. static HWND   g_hwndKbd  = NULL;
  237. static HANDLE g_hthrdKbd = NULL;
  238. static DWORD  g_dwThreadId = 0;
  239.  
  240. #define WM_SENDDEADKEY (WM_USER+31)
  241.  
  242.  
  243. void send_key(UINT uVirtKey, UINT uScanCode, UINT fDown);
  244. void key_down(UINT uVirtKey, UINT uScanCode);
  245. void keystate_down(UINT uCtrlState);
  246. void key_up(UINT uVirtKey, UINT uScanCode);
  247. void keystate_up(UINT uCtrlState);
  248.  
  249.     static LRESULT CALLBACK
  250. keyboard_wndproc(
  251.     HWND hwnd,
  252.     UINT uMsg,
  253.     WPARAM wParam,
  254.     LPARAM lParam)
  255. {
  256.     static int n, vk, sc; 
  257.     char ch, sz[200];
  258.  
  259.     sprintf(sz, "kbd: msg = %04x, w = %08x, l = %08x\n", uMsg, wParam, lParam);
  260.     OutputDebugString(sz);
  261.  
  262.     switch (uMsg)
  263.     {
  264.     case WM_SENDDEADKEY:
  265.         {
  266.             UINT uDeadVirt, uDeadScan, uDeadCtrl, uVirt, uScan, uCtrl;
  267.             BYTE abKeystate[256];
  268.             WORD awAnsiCode[2];
  269.             
  270.             uDeadVirt = LOBYTE(wParam);
  271.             uDeadScan = HIBYTE(wParam);
  272.             uDeadCtrl = HIWORD(wParam);
  273.  
  274.             uVirt = LOBYTE(lParam);
  275.             uScan = HIBYTE(lParam);
  276.             uCtrl = HIWORD(lParam);
  277.  
  278.             GetKeyboardState(abKeystate);
  279.             
  280.             memset(abKeystate, 0, sizeof (abKeystate));
  281.             if (!SetKeyboardState(abKeystate))
  282.             {
  283.                 n = GetLastError();
  284.                 sprintf(sz, "setkeyboardstate failed, error %d\n", n);
  285.                 OutputDebugString(sz);
  286.             }
  287.  
  288.             ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0),
  289.                     abKeystate, awAnsiCode, 0);
  290.     
  291.             if (uDeadCtrl & SHIFT_PRESSED) 
  292.                 abKeystate[VK_SHIFT] = 0x80;
  293.             if (uDeadCtrl & CAPSLOCK_ON) 
  294.                 abKeystate[VK_CAPITAL] = 1;
  295.             
  296.             if ((uDeadCtrl & ALT_GR) == ALT_GR)
  297.             {
  298.                 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
  299.                     abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
  300.             }
  301.             
  302.             if (!SetKeyboardState(abKeystate))
  303.             {
  304.                 n = GetLastError();
  305.                 sprintf(sz, "setkeyboardstate failed, error %d\n", n);
  306.                 OutputDebugString(sz);
  307.             }
  308.  
  309.             //keystate_down(uDeadCtrl);
  310.             key_down(uDeadVirt, uDeadScan);
  311.             key_up(uDeadVirt, uDeadScan);
  312.             //keystate_up(uDeadCtrl);
  313.  
  314.             memset(abKeystate, 0, sizeof (abKeystate));
  315.     
  316.             if (uCtrl & SHIFT_PRESSED) 
  317.                 abKeystate[VK_SHIFT] = 0x80;
  318.             if (uCtrl & CAPSLOCK_ON) 
  319.                 abKeystate[VK_CAPITAL] = 1;
  320.             
  321.             if ((uCtrl & ALT_GR) == ALT_GR)
  322.             {
  323.                 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
  324.                     abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
  325.             }
  326.             
  327.             if (!SetKeyboardState(abKeystate))
  328.             {
  329.                 int n = GetLastError();
  330.             }
  331.  
  332.             //keystate_down(uCtrl);
  333.             key_down(uVirt, uScan);
  334.             Sleep(30);
  335.  
  336.             key_up(uVirt, uScan);
  337.             //keystate_up(uCtrl);
  338.         }
  339.         break;
  340.         
  341.     case WM_CHAR:
  342.     case WM_DEADCHAR:
  343.         ch = wParam;
  344.         CharToOemBuff(&ch, &ch, 1);
  345.         sprintf(sz, "WM_%sCHAR: wParam = 0x%2x, Oem = 0x%2x, '%c'\n",
  346.                 ((uMsg == WM_CHAR) ? "" : "DEAD"),
  347.                 wParam, LOBYTE(ch), isprint(ch) ? ch : '?');
  348.         OutputDebugString(sz);
  349.  
  350.         n = DefWindowProc(hwnd, uMsg, wParam, lParam);
  351.         return n;
  352.  
  353.     case WM_KEYDOWN:
  354.         vk = wParam;
  355.         sc = HIWORD(lParam);
  356.  
  357.     default:
  358.         return DefWindowProc(hwnd, uMsg, wParam, lParam);
  359.     }
  360. }
  361.  
  362.  
  363.  
  364.     static DWORD WINAPI
  365. keyboard_threadproc(
  366.     LPVOID lpvThreadParam)
  367. {
  368.     const char szKbdTrans[] = "VimKbdXlator";
  369.     WNDCLASS wndclass;
  370.     MSG msg;
  371.     int i = 0;
  372.     
  373.     wndclass.style = 0;
  374.     wndclass.lpfnWndProc = keyboard_wndproc;
  375.     wndclass.cbClsExtra = 0;
  376.     wndclass.cbWndExtra = 0;
  377.     wndclass.hInstance = GetModuleHandle(NULL);
  378.     wndclass.hIcon = NULL;
  379.     wndclass.hCursor = NULL;
  380.     wndclass.hbrBackground = NULL;
  381.     wndclass.lpszMenuName = NULL;
  382.     wndclass.lpszClassName = szKbdTrans;
  383.  
  384.     RegisterClass(&wndclass);
  385.     
  386.     g_hwndKbd = CreateWindow(szKbdTrans, "", 0,
  387.                              CW_USEDEFAULT, CW_USEDEFAULT,
  388.                              CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
  389.                              GetModuleHandle(NULL), NULL);
  390.     
  391.     while (GetMessage(&msg, NULL, 0, 0))
  392.     {
  393. #if 0
  394.         char sz[200];
  395.         sprintf(sz, "gm: %2d: hwnd = %x, msg = %x, w = %x, l = %x\n",
  396.                 ++i, msg.hwnd, msg.message, msg.wParam, msg.lParam);
  397.         OutputDebugString(sz);
  398. #endif
  399.  
  400.         TranslateMessage(&msg);
  401.         DispatchMessage(&msg);
  402.     }
  403.  
  404.     return msg.wParam;
  405. }
  406.  
  407.  
  408.  
  409.     static BOOL
  410. keyboard_init()
  411. {
  412.     const char sz[] = "aA\xE0\xE1\xE8\xE9\xF1\xD1";
  413.     const char* psz = sz;
  414.  
  415.     for ( ; *psz; psz++)
  416.     {
  417.         char sz2[100];
  418.         SHORT w = VkKeyScan(*psz);
  419.         
  420.         sprintf(sz2, "%02x: %04x\n", *psz, w);
  421.         OutputDebugString(sz2);
  422.     }
  423.  
  424.     g_hthrdKbd = (HANDLE) _beginthreadex(NULL, 0, keyboard_threadproc,
  425.                                          (LPVOID) NULL, 0, &g_dwThreadId);
  426.  
  427.     return (g_hthrdKbd != NULL);
  428. }
  429.  
  430.  
  431.  
  432.     static void
  433. keyboard_exit()
  434. {
  435.     TerminateThread(g_hthrdKbd, 0);
  436. }
  437.  
  438.  
  439.  
  440.     void
  441. send_key(
  442.     UINT uVirtKey,
  443.     UINT uScanCode,
  444.     UINT fDown)
  445. {
  446.     PostMessage(g_hwndKbd,
  447.                 fDown ? WM_KEYDOWN : WM_KEYUP,
  448.                 uVirtKey,
  449.                 MAKELONG(1, uScanCode | (fDown ? 0 : 0x8000)));
  450.     Sleep(20);
  451. }
  452.  
  453.  
  454.  
  455.     void
  456. key_down(
  457.     UINT uVirtKey,
  458.     UINT uScanCode)
  459. {
  460.     send_key(uVirtKey, uScanCode, TRUE);
  461. }
  462.  
  463.  
  464.  
  465.     void
  466. keystate_down(
  467.     UINT uCtrlState)
  468. {
  469.     if (uCtrlState & SHIFT_PRESSED)
  470.         key_down(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0));
  471.     if ((uCtrlState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) != 0)
  472.         key_down(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0));
  473. }
  474.  
  475.  
  476.  
  477.     void
  478. key_up(
  479.     UINT uVirtKey,
  480.     UINT uScanCode)
  481. {
  482.     send_key(uVirtKey, uScanCode, FALSE);
  483. }
  484.  
  485.  
  486.  
  487.     void
  488. keystate_up(
  489.     UINT uCtrlState)
  490. {
  491.     if ((uCtrlState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) != 0)
  492.         key_up(VK_CONTROL, MapVirtualKey(VK_CONTROL, 0));
  493.     if (uCtrlState & SHIFT_PRESSED)
  494.         key_up(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0));
  495. }
  496.  
  497. #endif /* WIN95_DEAD_KEYS_HACK */
  498.  
  499.  
  500.  
  501. /* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
  502.  * We map function keys to their ANSI terminal equivalents, as produced
  503.  * by ANSI.SYS, for compatibility with the MS-DOS version of Vim.  Any
  504.  * ANSI key with a value >= '\300' is nonstandard, but provided anyway
  505.  * so that the user can have access to all SHIFT-, CTRL-, and ALT-
  506.  * combinations of function/arrow/etc keys.
  507.  */
  508.  
  509. const static struct {
  510.     WORD    wVirtKey;
  511.     BOOL    fAnsiKey;
  512.     int        chAlone;
  513.     int        chShift;
  514.     int        chCtrl;
  515.     int        chAlt;
  516. } VirtKeyMap[] = {
  517.  
  518. /*      Key        ANSI    alone    shift    ctrl        alt */
  519.     { VK_ESCAPE,FALSE,    ESC,    ESC,    ESC,        ESC,    },
  520.  
  521.     { VK_F1,    TRUE,    ';',    'T',    '^',        'h', },
  522.     { VK_F2,    TRUE,    '<',    'U',    '_',        'i', },
  523.     { VK_F3,    TRUE,    '=',    'V',    '`',        'j', },
  524.     { VK_F4,    TRUE,    '>',    'W',    'a',        'k', },
  525.     { VK_F5,    TRUE,    '?',    'X',    'b',        'l', },
  526.     { VK_F6,    TRUE,    '@',    'Y',    'c',        'm', },
  527.     { VK_F7,    TRUE,    'A',    'Z',    'd',        'n', },
  528.     { VK_F8,    TRUE,    'B',    '[',    'e',        'o', },
  529.     { VK_F9,    TRUE,    'C',    '\\',    'f',        'p', },
  530.     { VK_F10,    TRUE,    'D',    ']',    'g',        'q', },
  531.     { VK_F11,    TRUE,    '\205',    '\207',    '\211',        '\213', },
  532.     { VK_F12,    TRUE,    '\206',    '\210',    '\212',        '\214', },
  533.  
  534.     { VK_HOME,    TRUE,    'G',    '\302',    'w',        '\303', },
  535.     { VK_UP,    TRUE,    'H',    '\304',    '\305',        '\306', },
  536.     { VK_PRIOR,    TRUE,    'I',    '\307',    '\204',        '\310', }, /*PgUp*/
  537.     { VK_LEFT,    TRUE,    'K',    '\311',    's',        '\312', },
  538.     { VK_RIGHT,    TRUE,    'M',    '\313',    't',        '\314', },
  539.     { VK_END,    TRUE,    'O',    '\315',    'u',        '\316', },
  540.     { VK_DOWN,    TRUE,    'P',    '\317',    '\320',        '\321', },
  541.     { VK_NEXT,    TRUE,    'Q',    '\322',    'v',        '\323', }, /*PgDn*/
  542.     { VK_INSERT,TRUE,    'R',    '\324',    '\325',        '\326', },
  543.     { VK_DELETE,TRUE,    'S',    '\327',    '\330',        '\331', },
  544.  
  545.     { VK_SNAPSHOT,TRUE,    0,        0,        0,            'r', }, /*PrtScrn*/
  546.  
  547.     /* Most people don't have F13-F20, but what the hell... */
  548.     { VK_F13,    TRUE,    '\332',    '\333',    '\334',        '\335', },
  549.     { VK_F14,    TRUE,    '\336',    '\337',    '\340',        '\341', },
  550.     { VK_F15,    TRUE,    '\342',    '\343',    '\344',        '\345', },
  551.     { VK_F16,    TRUE,    '\346',    '\347',    '\350',        '\351', },
  552.     { VK_F17,    TRUE,    '\352',    '\353',    '\354',        '\355', },
  553.     { VK_F18,    TRUE,    '\356',    '\357',    '\360',        '\361', },
  554.     { VK_F19,    TRUE,    '\362',    '\363',    '\364',        '\365', },
  555.     { VK_F20,    TRUE,    '\366',    '\367',    '\370',        '\371', },
  556. };
  557.  
  558.  
  559. // The ToAscii bug destroys several registers.  Need to turn off optimization
  560. // or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
  561.  
  562. #pragma optimize("", off)
  563.  
  564.  
  565. /* The return code indicates key code size. */
  566.     static int
  567. win32_kbd_patch_key(
  568.     KEY_EVENT_RECORD* pker)
  569. {
  570.     static int s_iIsDead = 0;
  571.     static WORD awAnsiCode[2];
  572.     UINT uMods = pker->dwControlKeyState;
  573.     BYTE abKeystate[256];
  574.  
  575.     if (s_iIsDead == 2)
  576.     {
  577.         pker->uChar.AsciiChar = (CHAR) awAnsiCode[1];
  578.         s_iIsDead = 0;
  579.         return 1;
  580.     }
  581.  
  582.     if (pker->uChar.AsciiChar != 0) 
  583.         return 1;
  584.     
  585.     memset(abKeystate, 0, sizeof (abKeystate));
  586.  
  587.     // Should only be non-NULL on NT 4.0
  588.     if (s_pfnGetConsoleKeyboardLayoutName != NULL)
  589.     {
  590.         CHAR szKLID[KL_NAMELENGTH];
  591.         
  592.         if (s_pfnGetConsoleKeyboardLayoutName(szKLID))
  593.         {
  594.             HKL hkl = LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
  595.         }
  596.     }
  597.  
  598.     /* Clear any pending dead keys */
  599.     ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
  600.  
  601.     if (uMods & SHIFT_PRESSED) 
  602.         abKeystate[VK_SHIFT] = 0x80;
  603.     if (uMods & CAPSLOCK_ON) 
  604.         abKeystate[VK_CAPITAL] = 1;
  605.  
  606.     if ((uMods & ALT_GR) == ALT_GR)
  607.     {
  608.         abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
  609.             abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
  610.     }
  611.  
  612.     s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
  613.                         abKeystate, awAnsiCode, 0);
  614.  
  615.     if (s_iIsDead > 0)
  616.         pker->uChar.AsciiChar = (CHAR) awAnsiCode[0];
  617.  
  618.     return s_iIsDead;
  619. }
  620.  
  621.  
  622. static BOOL g_fJustGotFocus = FALSE;
  623.   
  624. /*
  625.  * Decode a KEY_EVENT into one or two keystrokes
  626.  */
  627.     static BOOL
  628. decode_key_event(
  629.     KEY_EVENT_RECORD* pker,
  630.     char_u* pch,
  631.     char_u* pchPending,
  632.     BOOL fDoPost)
  633. {
  634.     int i;
  635.     const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
  636.  
  637. #ifdef WIN95_DEAD_KEYS_HACK
  638.     static UINT uDeadVirtKey = 0, uDeadScan = 0, uDeadCtrlState = 0;
  639.     char sz[200];
  640.  
  641.     sprintf(sz, "Vk = 0x%02x, `%c'; Scan = 0x%02x; "
  642.             "Char = %3d, 0x%02x, `%c'; Ctrl = 0x%02x, Post = %d\n",
  643.             pker->wVirtualKeyCode,
  644.             isprint(pker->wVirtualKeyCode) ? pker->wVirtualKeyCode :'?',
  645.             pker->wVirtualScanCode,
  646.             LOBYTE(pker->uChar.AsciiChar), LOBYTE(pker->uChar.AsciiChar),
  647.             isprint(pker->uChar.AsciiChar) ? pker->uChar.AsciiChar :'?',
  648.             pker->dwControlKeyState, fDoPost);
  649.     OutputDebugString(sz);
  650. #endif /* WIN95_DEAD_KEYS_HACK */
  651.  
  652.     *pch = *pchPending = NUL;
  653.     g_fJustGotFocus = FALSE;
  654.     
  655.     /* ignore key up events */
  656.     if (!pker->bKeyDown)
  657.         return FALSE;
  658.  
  659.     /* ignore some keystrokes */
  660.     switch (pker->wVirtualKeyCode)
  661.     {
  662.     /* modifiers */
  663.     case VK_SHIFT:
  664.     case VK_CONTROL:
  665.     case VK_MENU:    /* Alt key */
  666.         return FALSE;
  667.  
  668.     default:
  669.         break;
  670.     }
  671.  
  672. #ifdef WIN95_DEAD_KEYS_HACK
  673.     if (fDoPost  &&  uDeadVirtKey != 0)
  674.     {
  675.         sprintf(sz, "sending vk = 0x%2x, sc = 0x%2x\n", 
  676.                 pker->wVirtualKeyCode, pker->wVirtualScanCode);
  677.         OutputDebugString(sz);
  678.  
  679.         PostMessage(g_hwndKbd, WM_SENDDEADKEY,
  680.                     MAKELONG(MAKEWORD(uDeadVirtKey, uDeadScan), uDeadCtrlState),
  681.                     MAKELONG(MAKEWORD(pker->wVirtualKeyCode,
  682.                                       pker->wVirtualScanCode),
  683.                              pker->dwControlKeyState));
  684.     }
  685. #endif /* WIN95_DEAD_KEYS_HACK */
  686.  
  687. #if 0
  688.     /* If AltGr has been pressed, remove it.  */
  689.     if ((pker->dwControlKeyState & ALT_GR) == ALT_GR)
  690.         pker->dwControlKeyState &= ~ ALT_GR;
  691. #endif
  692.  
  693. #if 0
  694.     /* If CapsLock is on on Win95, digits will be shifted by default;
  695.      * e.g., pressing '1' will give '!'.  Feh. */
  696.     if ((pker->dwControlKeyState & CAPSLOCK_ON) &&
  697.         !(pker->dwControlKeyState & SHIFT_PRESSED) &&
  698.         ('0' <= pker->wVirtualKeyCode  &&  pker->wVirtualKeyCode <= '9'))
  699.     {
  700.         pker->uChar.AsciiChar = NUL;
  701.     }
  702. #endif
  703.  
  704. #if 0
  705.     if ((*pch = pker->uChar.AsciiChar) != NUL)
  706.         return TRUE;
  707. #endif
  708.  
  709.     /* special cases */
  710.     if ((nModifs & CTRL) != 0  &&  (nModifs & ~CTRL) == 0
  711.         &&  pker->uChar.AsciiChar == NUL)
  712.     {
  713.         /* Ctrl-6 is Ctrl-^ */
  714.         if (pker->wVirtualKeyCode == '6')
  715.         {
  716.             *pch = Ctrl('^');
  717.             return TRUE;
  718.         }
  719.         /* Ctrl-2 is Ctrl-@ */
  720.         else if (pker->wVirtualKeyCode == '2')
  721.         {
  722.             *pch = NUL;
  723.             return TRUE;
  724.         }
  725.     }
  726.     
  727.     /* Shift-TAB */
  728.     if (pker->wVirtualKeyCode == VK_TAB  &&  (nModifs & SHIFT_PRESSED))
  729.     {
  730.         *pch = K_NUL;
  731.         *pchPending = '\017';
  732.         return TRUE;
  733.     }
  734.     
  735.     for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]);  --i >= 0;  )
  736.     {
  737.         if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
  738.         {
  739.             if (nModifs == 0)
  740.                 *pch = VirtKeyMap[i].chAlone;
  741.             else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
  742.                 *pch = VirtKeyMap[i].chShift;
  743.             else if ((nModifs & CTRL) != 0  &&  (nModifs & ~CTRL) == 0)
  744.                 *pch = VirtKeyMap[i].chCtrl;
  745.             else if ((nModifs & ALT) != 0  &&  (nModifs & ~ALT) == 0)
  746.                 *pch = VirtKeyMap[i].chAlt;
  747.  
  748.             if (*pch != 0)
  749.             {
  750.                 if (VirtKeyMap[i].fAnsiKey)
  751.                 {
  752.                     *pchPending = *pch;
  753.                     *pch = K_NUL;
  754.                 }
  755.  
  756.                 return TRUE;
  757.             }
  758.         }
  759.     }
  760.  
  761.     i = win32_kbd_patch_key(pker);
  762.  
  763.     if (i < 0)
  764.     {
  765.         *pch = NUL;
  766.  
  767. #ifdef WIN95_DEAD_KEYS_HACK
  768.         if (fDoPost)
  769.         {
  770.             uDeadVirtKey = pker->wVirtualKeyCode;
  771.             uDeadScan = pker->wVirtualScanCode;
  772.             uDeadCtrlState = pker->dwControlKeyState;
  773.         }
  774. #endif /* WIN95_DEAD_KEYS_HACK */
  775.     }
  776.     else
  777.     {
  778. #ifdef WIN95_DEAD_KEYS_HACK
  779.         uDeadVirtKey = uDeadScan = uDeadCtrlState = 0;
  780. #endif /* WIN95_DEAD_KEYS_HACK */
  781.         *pch = (i > 0)  ?  pker->uChar.AsciiChar  :  NUL;
  782.     }
  783.  
  784.     return (*pch != NUL);
  785. }
  786.  
  787. #pragma optimize("", on)
  788.  
  789.  
  790. #ifdef USE_MOUSE
  791.  
  792. static int g_fMouseAvail = FALSE;    /* mouse present */
  793. static int g_fMouseActive = FALSE;    /* mouse enabled */
  794. static int g_nMouseClick = -1;        /* mouse status */
  795. static int g_xMouse;                /* mouse x coordinate */
  796. static int g_yMouse;                /* mouse y coordinate */
  797.  
  798. /*
  799.  * Enable or disable mouse input
  800.  */
  801.     void
  802. mch_setmouse(
  803.     int on)
  804. {
  805.     DWORD cmodein;
  806.  
  807.     if (! g_fMouseAvail)
  808.         return;
  809.     
  810.     g_fMouseActive = on;
  811.     GetConsoleMode(g_hConIn, &cmodein);
  812.  
  813.     if (g_fMouseActive)
  814.         cmodein |= ENABLE_MOUSE_INPUT;
  815.     else
  816.         cmodein &= ~ENABLE_MOUSE_INPUT;
  817.  
  818.     SetConsoleMode(g_hConIn, cmodein);
  819. }
  820.  
  821.  
  822. /*
  823.  * Decode a MOUSE_EVENT.  If it's a valid event, return MOUSE_LEFT,
  824.  * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
  825.  * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
  826.  * or a MOUSE_LEFT, _MIDDLE, or _RIGHT.  We encode the button type,
  827.  * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
  828.  * and we return the mouse position in g_xMouse and g_yMouse.
  829.  *
  830.  * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
  831.  * MOUSE_DRAGs and one MOUSE_RELEASE.  MOUSE_RELEASE will be followed only
  832.  * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
  833.  *
  834.  * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
  835.  * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
  836.  *
  837.  * Windows will send us MOUSE_MOVED notifications whenever the mouse
  838.  * moves, even if it stays within the same character cell.  We ignore
  839.  * all MOUSE_MOVED messages if the position hasn't really changed, and
  840.  * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
  841.  * we're only interested in MOUSE_DRAG).
  842.  *
  843.  * All of this is complicated by the code that fakes MOUSE_MIDDLE on
  844.  * 2-button mouses by pressing the left & right buttons simultaneously.
  845.  * In practice, it's almost impossible to click both at the same time,
  846.  * so we need to delay a little.  Also, we tend not to get MOUSE_RELEASE
  847.  * in such cases, if the user is clicking quickly.
  848.  */
  849.     static BOOL
  850. decode_mouse_event(
  851.     MOUSE_EVENT_RECORD* pmer)
  852. {
  853.     static int s_nOldButton = -1;
  854.     static int s_nOldMouseClick = -1;
  855.     static int s_xOldMouse = -1;
  856.     static int s_yOldMouse = -1;
  857.     static linenr_t s_old_topline = 0;
  858.     static int s_cClicks = 1;
  859.     static BOOL s_fReleased = TRUE;
  860.     static s_dwLastClickTime = 0;
  861.     static BOOL s_fNextIsMiddle = FALSE;
  862.  
  863.     const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
  864.     const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
  865.     const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
  866.     const DWORD LEFT_RIGHT = LEFT | RIGHT;
  867.  
  868.     int nButton;
  869.  
  870.     if (! g_fMouseAvail  ||  ! g_fMouseActive)
  871.     {
  872.         g_nMouseClick = -1;
  873.         return FALSE;
  874.     }
  875.  
  876.     /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
  877.     if (g_fJustGotFocus)
  878.     {
  879.         g_fJustGotFocus = FALSE;
  880.         return FALSE;
  881.     }
  882.     
  883.     /* unprocessed mouse click? */
  884.     if (g_nMouseClick != -1)
  885.         return TRUE;
  886.  
  887.     nButton = -1;
  888.     g_xMouse = pmer->dwMousePosition.X;
  889.     g_yMouse = pmer->dwMousePosition.Y;
  890.  
  891.     if (pmer->dwEventFlags == MOUSE_MOVED)
  892.     {
  893.         /* ignore MOUSE_MOVED events if (x, y) hasn't changed.  (We get these
  894.          * events even when the mouse moves only within a char cell.) */
  895.         if (s_xOldMouse == g_xMouse  &&  s_yOldMouse == g_yMouse)
  896.             return FALSE;
  897.     }
  898.  
  899.     /* If no buttons are pressed... */
  900.     if (pmer->dwButtonState == 0)
  901.     {
  902.         /* If the last thing returned was MOUSE_RELEASE, ignore this */
  903.         if (s_fReleased)
  904.             return FALSE;
  905.  
  906.         nButton = MOUSE_RELEASE;
  907.         s_fReleased = TRUE;
  908.     }
  909.     else    /* one or more buttons pressed */
  910.     {
  911.         const int cButtons = GetSystemMetrics(SM_CMOUSEBUTTONS);
  912.  
  913.         /* on a 2-button mouse, hold down left and right buttons
  914.          * simultaneously to get MIDDLE. */
  915.  
  916.         if (cButtons == 2  &&  s_nOldButton != MOUSE_DRAG)
  917.         {
  918.             DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
  919.             
  920.             /* if either left or right button only is pressed, see if the
  921.              * the next mouse event has both of them pressed */
  922.             if (dwLR == LEFT  ||  dwLR  == RIGHT)
  923.             {
  924.                 for (;;)
  925.                 {
  926.                     /* wait a short time for next input event */
  927.                     if (WaitForSingleObject(g_hConIn, p_mouset / 3)
  928.                         != WAIT_OBJECT_0)
  929.                         break;
  930.                     else
  931.                     {
  932.                         DWORD cRecords = 0;
  933.                         INPUT_RECORD ir;
  934.                         MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
  935.                         
  936.                         PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
  937.                     
  938.                         if (cRecords == 0  ||  ir.EventType != MOUSE_EVENT
  939.                             ||  !(pmer2->dwButtonState & LEFT_RIGHT))
  940.                             break;
  941.                         else
  942.                         {
  943.                             if (pmer2->dwEventFlags != MOUSE_MOVED)
  944.                             {
  945.                                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  946.                                 
  947.                                 return decode_mouse_event(pmer2);
  948.                             }
  949.                             else if (s_xOldMouse == pmer2->dwMousePosition.X &&
  950.                                      s_yOldMouse == pmer2->dwMousePosition.Y)
  951.                             {
  952.                                 /* throw away spurious mouse move */
  953.                                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  954.  
  955.                                 /* are there any more mouse events in queue? */
  956.                                 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
  957.  
  958.                                 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
  959.                                     break;
  960.                             }
  961.                             else
  962.                                 break;
  963.                         }
  964.                     }
  965.                 }
  966.             }
  967.         }
  968.  
  969.         if (s_fNextIsMiddle)
  970.         {
  971.             nButton = (pmer->dwEventFlags == MOUSE_MOVED)
  972.                 ? MOUSE_DRAG : MOUSE_MIDDLE;
  973.             s_fNextIsMiddle = FALSE;
  974.         }
  975.         else if (cButtons == 2  &&
  976.             ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
  977.         {
  978.             nButton = MOUSE_MIDDLE;
  979.  
  980.             if (! s_fReleased  &&  pmer->dwEventFlags != MOUSE_MOVED)
  981.             {
  982.                 s_fNextIsMiddle = TRUE;
  983.                 nButton = MOUSE_RELEASE;
  984.             }
  985.         }
  986.         else if ((pmer->dwButtonState & LEFT) == LEFT)
  987.             nButton = MOUSE_LEFT;
  988.         else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
  989.             nButton = MOUSE_MIDDLE;
  990.         else if ((pmer->dwButtonState & RIGHT) == RIGHT)
  991.             nButton = MOUSE_RIGHT;
  992.  
  993.         if (! s_fReleased  && ! s_fNextIsMiddle
  994.             &&  nButton != s_nOldButton  &&  s_nOldButton != MOUSE_DRAG)
  995.             return FALSE;
  996.         
  997.         s_fReleased = s_fNextIsMiddle;
  998.     }
  999.  
  1000.     if (pmer->dwEventFlags == 0  ||  pmer->dwEventFlags == DOUBLE_CLICK)
  1001.     {
  1002.         /* button pressed or released, without mouse moving */
  1003.         if (nButton != -1  &&  nButton != MOUSE_RELEASE)
  1004.         {
  1005.             DWORD dwCurrentTime = GetTickCount();
  1006.  
  1007.             if (s_xOldMouse != g_xMouse  ||  s_yOldMouse != g_yMouse
  1008.                 ||  s_nOldButton != nButton
  1009.                 ||  s_old_topline != curwin->w_topline
  1010.                 ||  (int) (dwCurrentTime - s_dwLastClickTime) > p_mouset)
  1011.             {
  1012.                 s_cClicks = 1;
  1013.             }
  1014.             else if (++s_cClicks > 4)
  1015.             {
  1016.                 s_cClicks = 1;
  1017.             }
  1018.  
  1019.             s_dwLastClickTime = dwCurrentTime;
  1020.         }
  1021.     }
  1022.     else if (pmer->dwEventFlags == MOUSE_MOVED)
  1023.     {
  1024.         if (nButton != -1  &&  nButton != MOUSE_RELEASE)
  1025.             nButton = MOUSE_DRAG;
  1026.  
  1027.         s_cClicks = 1;
  1028.     }
  1029.  
  1030.     if (nButton == -1)
  1031.         return FALSE;
  1032.     
  1033.     if (nButton != MOUSE_RELEASE)
  1034.         s_nOldButton = nButton;
  1035.     
  1036.     g_nMouseClick = nButton;
  1037.  
  1038.     if (pmer->dwControlKeyState & SHIFT_PRESSED)
  1039.         g_nMouseClick |= MOUSE_SHIFT;
  1040.     if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
  1041.         g_nMouseClick |= MOUSE_CTRL;
  1042.     if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED))
  1043.         g_nMouseClick |= MOUSE_ALT;
  1044.  
  1045.     /* only pass on interesting (i.e., different) mouse events */
  1046.     if (s_xOldMouse == g_xMouse  &&  s_yOldMouse == g_yMouse
  1047.         &&  s_nOldMouseClick == g_nMouseClick)
  1048.     {
  1049.         g_nMouseClick = -1;
  1050.         return FALSE;
  1051.     }
  1052.  
  1053.     g_nMouseClick |= 0x20;
  1054.  
  1055.     s_xOldMouse = g_xMouse;
  1056.     s_yOldMouse = g_yMouse;
  1057.     s_old_topline = curwin->w_topline;
  1058.     s_nOldMouseClick = g_nMouseClick;
  1059.     
  1060.     if (nButton != MOUSE_DRAG  &&  nButton != MOUSE_RELEASE)
  1061.         SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
  1062.     
  1063.     return TRUE;
  1064. }
  1065.  
  1066.  
  1067. #endif /* USE_MOUSE */
  1068.  
  1069.  
  1070. /*
  1071.  * Wait until console input from keyboard or mouse is available,
  1072.  * or the time is up
  1073.  */
  1074.     static int
  1075. WaitForChar(
  1076.     long msec)
  1077. {
  1078.     DWORD dwNow, dwEndTime;
  1079.  
  1080.     if (msec <= 0)
  1081.         msec = 2;    /* very short time */
  1082.  
  1083.     dwEndTime = GetTickCount() + msec;
  1084.  
  1085.     /* We need to loop until the end of the time period, because
  1086.      * we might get multiple unusable mouse events in that time.
  1087.      */
  1088.     while ((dwNow = GetTickCount())  <  dwEndTime)
  1089.     {
  1090.         if (WaitForSingleObject(g_hConIn, dwEndTime - dwNow) == WAIT_OBJECT_0)
  1091.         {
  1092.             INPUT_RECORD ir;
  1093.             DWORD cRecords = 0;
  1094.             
  1095.             PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1096.             
  1097.             if (cRecords > 0)
  1098.             {
  1099.                 if (ir.EventType == KEY_EVENT  &&  ir.Event.KeyEvent.bKeyDown)
  1100.                 {
  1101.                     char_u ch, ch2;
  1102.  
  1103.                     return decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
  1104.                                             FALSE);
  1105.                 }
  1106.                 else if (ir.EventType == FOCUS_EVENT)
  1107.                 {
  1108.                     ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1109.                     
  1110.                     g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
  1111.                 }
  1112.                 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
  1113.                 {
  1114.                     ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1115.                     
  1116.                     set_winsize(Rows, Columns, FALSE);
  1117.                 }
  1118. #ifdef USE_MOUSE
  1119.                 else if (ir.EventType == MOUSE_EVENT) 
  1120.                 {
  1121.                     ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1122.                     
  1123.                     if (decode_mouse_event(&ir.Event.MouseEvent))
  1124.                         return TRUE;
  1125.                 }
  1126. #endif /* USE_MOUSE */
  1127.                 else
  1128.                 {
  1129.                     /* Discard it, it's an insignificant event */
  1130.                     ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1131.                 }
  1132.             }
  1133.         }
  1134.     }
  1135.         
  1136.     return FALSE;
  1137. }
  1138.  
  1139.  
  1140. static char_u g_chPending = NUL;
  1141.  
  1142.  
  1143. /*
  1144.  * Is there a pending keystroke or mouse event?
  1145.  */
  1146.     static BOOL
  1147. kbhit()
  1148. {
  1149.     if (g_chPending != NUL
  1150. #ifdef USE_MOUSE
  1151.         || g_nMouseClick != -1
  1152. #endif /* USE_MOUSE */
  1153.         )
  1154.         return TRUE;
  1155.  
  1156.     for ( ; ; )
  1157.     {
  1158.         INPUT_RECORD ir;
  1159.         DWORD cRecords = 0;
  1160.  
  1161.         PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1162.  
  1163.         if (cRecords == 0)
  1164.             return FALSE;
  1165.         else
  1166.         {
  1167.             if (ir.EventType == KEY_EVENT  &&  ir.Event.KeyEvent.bKeyDown)
  1168.             {
  1169.                 char_u ch, ch2;
  1170.  
  1171.                 return decode_key_event(&ir.Event.KeyEvent, &ch, &ch2, FALSE);
  1172.             }
  1173.             else if (ir.EventType == FOCUS_EVENT)
  1174.             {
  1175.                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1176.                 
  1177.                 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
  1178.             }
  1179.             else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
  1180.             {
  1181.                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1182.                 
  1183.                 set_winsize(Rows, Columns, FALSE);
  1184.             }
  1185. #ifdef USE_MOUSE
  1186.             else if (ir.EventType == MOUSE_EVENT) 
  1187.             {
  1188.                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1189.  
  1190.                 if (decode_mouse_event(&ir.Event.MouseEvent))
  1191.                     return TRUE;
  1192.             }
  1193. #endif /* USE_MOUSE */
  1194.             else
  1195.             {
  1196.                 /* Discard it, it's an insignificant event */
  1197.                 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1198.             }
  1199.         }
  1200.     }
  1201. }
  1202.  
  1203.  
  1204. /*
  1205.  * Get a keystroke or a mouse event
  1206.  */
  1207.     static char_u
  1208. tgetch()
  1209. {
  1210.     char_u ch;
  1211.  
  1212.     if (g_chPending != NUL)
  1213.     {
  1214.         ch = g_chPending;
  1215.         g_chPending = NUL;
  1216.         return ch;
  1217.     }
  1218.  
  1219.     for ( ; ; )
  1220.     {
  1221.         INPUT_RECORD ir;
  1222.         DWORD cRecords = 0;
  1223.         
  1224.         ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
  1225.         
  1226.         if (ir.EventType == KEY_EVENT)
  1227.         {
  1228.             if (decode_key_event(&ir.Event.KeyEvent, &ch, &g_chPending, TRUE))
  1229.                 return ch;
  1230.         }
  1231.         else if (ir.EventType == FOCUS_EVENT)
  1232.         {
  1233.             g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
  1234.         }
  1235.         else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
  1236.         {
  1237.             set_winsize(Rows, Columns, FALSE);
  1238.         } 
  1239. #ifdef USE_MOUSE
  1240.         else if (ir.EventType == MOUSE_EVENT) 
  1241.         {
  1242.             if (decode_mouse_event(&ir.Event.MouseEvent))
  1243.                 return 0;
  1244.         }
  1245. #endif /* USE_MOUSE */
  1246.     }
  1247. }
  1248.  
  1249.  
  1250. /*
  1251.  * mch_inchar(): low-level input funcion.
  1252.  * Get one or more characters from the keyboard or the mouse.
  1253.  * If time == 0, do not wait for characters.
  1254.  * If time == n, wait a short time for characters.
  1255.  * If time == -1, wait forever for characters.
  1256.  * Returns the number of characters read into buf.
  1257.  */
  1258.     int
  1259. mch_inchar(
  1260.     char_u *buf,
  1261.     int maxlen,
  1262.     long time)
  1263. {
  1264.     int len = 0;
  1265.     int c;
  1266.  
  1267.     if (time >= 0)
  1268.     {
  1269.         if (! WaitForChar(time))     /* no character available */
  1270.             return 0;
  1271.     }
  1272.     else    /* time == -1, wait forever */
  1273.     {
  1274.     
  1275.         /* If there is no character available within 2 seconds (default),
  1276.          * write the autoscript file to disk */
  1277.         if (WaitForChar(p_ut) == 0)
  1278.             updatescript(0);
  1279.     }
  1280.  
  1281.     /*
  1282.      * Try to read as many characters as there are.
  1283.      */
  1284.  
  1285.     --maxlen;                   /* may get two chars at once */
  1286.  
  1287.     /* we will get at least one key. Get more if they are available. */
  1288.     g_fCBrkPressed = FALSE;
  1289.  
  1290. #ifdef MCH_WRITE_DUMP
  1291.     if (fdDump)
  1292.         fputc('[', fdDump);
  1293. #endif /* MCH_WRITE_DUMP */
  1294.  
  1295.     while ((len == 0 || kbhit())  &&  len < maxlen)
  1296.     {
  1297. #ifdef USE_MOUSE
  1298.         if (g_nMouseClick != -1  &&  maxlen >= 5-1)
  1299.         {
  1300. # ifdef MCH_WRITE_DUMP
  1301.             if (fdDump)
  1302.                 fprintf(fdDump, "{%02x @ %d, %d}",
  1303.                         g_nMouseClick, g_xMouse, g_yMouse);
  1304. # endif /* MCH_WRITE_DUMP */
  1305.  
  1306.             len = 5;
  1307.             *buf++ = ESC + 128;
  1308.             *buf++ = 'M';
  1309.             *buf++ = g_nMouseClick;
  1310.             *buf++ = g_xMouse + '!';
  1311.             *buf++ = g_yMouse + '!';
  1312.             g_nMouseClick = -1;
  1313.             
  1314.         }
  1315.         else
  1316. #endif /* USE_MOUSE */
  1317.         {
  1318.             if ((c = tgetch()) == Ctrl('C'))
  1319.                 g_fCBrkPressed = TRUE;
  1320.             
  1321. #ifdef USE_MOUSE
  1322.             if (g_nMouseClick == -1)
  1323. #endif /* USE_MOUSE */
  1324.             {
  1325.                 *buf++ = c;
  1326.                 len++;
  1327.                 
  1328. #ifdef MCH_WRITE_DUMP
  1329.                 if (fdDump)
  1330.                     fputc(c, fdDump);
  1331. #endif /* MCH_WRITE_DUMP */
  1332.                 
  1333.             }
  1334.         }
  1335.     }
  1336.  
  1337. #ifdef MCH_WRITE_DUMP
  1338.     if (fdDump)
  1339.     {
  1340.         fputs("]\n", fdDump);
  1341.         fflush(fdDump);
  1342.     }
  1343. #endif /* MCH_WRITE_DUMP */
  1344.  
  1345.     beep_count = 0;            /* may beep again now that we got some chars */
  1346.     return len;
  1347. }
  1348.  
  1349.  
  1350. static char g_szOrigTitle[256];
  1351. static int  g_fWindInitCalled = FALSE;
  1352. static CONSOLE_CURSOR_INFO g_cci;
  1353. static DWORD g_cmodein = 0;
  1354. static DWORD g_cmodeout = 0;
  1355.  
  1356. /*
  1357.  * Because of a bug in the Windows 95 Console, we need to set the screen size
  1358.  * back when switching screens.
  1359.  */
  1360. static int g_nOldRows = 0;
  1361. static int g_nOldColumns = 0;
  1362.  
  1363. /*
  1364.  * platform-specific initialization
  1365.  */
  1366.     void
  1367. mch_windinit()
  1368. {
  1369.     CONSOLE_SCREEN_BUFFER_INFO csbi;
  1370.     extern int _fmode;
  1371.  
  1372.     PlatformId();
  1373.  
  1374.     _fmode = O_BINARY;          /* we do our own CR-LF translation */
  1375.     flushbuf();
  1376.  
  1377.     /* Obtain handles for the standard Console I/O devices */
  1378.     g_hConIn =  GetStdHandle(STD_INPUT_HANDLE);
  1379.     g_hSavOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1380.     g_hCurOut = g_hSavOut;
  1381.  
  1382.     /* Get current text attributes */
  1383.     GetConsoleScreenBufferInfo(g_hSavOut, &csbi);
  1384.     g_attrCurrent = g_attrDefault = csbi.wAttributes;
  1385.     GetConsoleCursorInfo(g_hSavOut, &g_cci);
  1386.  
  1387.     GetConsoleMode(g_hConIn,  &g_cmodein);
  1388.     GetConsoleMode(g_hSavOut, &g_cmodeout);
  1389.  
  1390.     GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle));
  1391.     mch_get_winsize();
  1392.  
  1393.     g_nOldRows = Rows;
  1394.     g_nOldColumns = Columns;
  1395.  
  1396. #ifdef MCH_WRITE_DUMP
  1397.     fdDump = fopen("dump", "wt");
  1398.  
  1399.     if (fdDump)
  1400.     {
  1401.         time_t t;
  1402.  
  1403.         time(&t);
  1404.         fputs(ctime(&t), fdDump);
  1405.         fflush(fdDump);
  1406.     }
  1407. #endif /* MCH_WRITE_DUMP */
  1408.  
  1409.     g_fWindInitCalled = TRUE;
  1410.  
  1411. #ifdef USE_MOUSE
  1412.     g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
  1413. #endif
  1414.  
  1415. #ifdef WIN95_DEAD_KEYS_HACK
  1416.     keyboard_init();
  1417. #endif
  1418.  
  1419.     /* This will be NULL on anything but NT 4.0 */
  1420.     s_pfnGetConsoleKeyboardLayoutName =
  1421.         (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
  1422.                                   "GetConsoleKeyboardLayoutNameA");
  1423.     /*
  1424.      * We don't really want to jump to our own screen yet; do that after
  1425.      * starttermcap().  This flashes the window, sorry about that, but
  1426.      * otherwise "vim -r" doesn't work.
  1427.      */
  1428.     g_hCurOut = g_hSavOut;
  1429.     SetConsoleActiveScreenBuffer(g_hCurOut);
  1430. }
  1431.  
  1432.  
  1433. /*
  1434.  * Shut down and exit with status `r'
  1435.  * Careful: mch_windexit() may be called before mch_windinit()!
  1436.  */
  1437.     void
  1438. mch_windexit(
  1439.     int r)
  1440. {
  1441.     stoptermcap();
  1442.     outchar('\r');
  1443.     outchar('\n');
  1444.     flushbuf();
  1445.  
  1446.     if (g_fWindInitCalled)
  1447.         settmode(0);
  1448.  
  1449.     if (g_hConOut != INVALID_HANDLE_VALUE)
  1450.     {
  1451.         (void) CloseHandle(g_hConOut);
  1452.  
  1453.         if (g_hSavOut != INVALID_HANDLE_VALUE)
  1454.         {
  1455.             SetConsoleTextAttribute(g_hSavOut, g_attrDefault);
  1456.             SetConsoleCursorInfo(g_hSavOut, &g_cci);
  1457.         }
  1458.     }
  1459.  
  1460.     ml_close_all(TRUE);             /* remove all memfiles */
  1461.  
  1462.     if (g_fWindInitCalled)
  1463.     {
  1464. #ifdef WIN95_DEAD_KEYS_HACK
  1465.         keyboard_exit();
  1466. #endif
  1467.  
  1468.         mch_restore_title(3);
  1469.  
  1470. #ifdef MCH_WRITE_DUMP
  1471.         if (fdDump)
  1472.         {
  1473.             time_t t;
  1474.             
  1475.             time(&t);
  1476.             fputs(ctime(&t), fdDump);
  1477.             fclose(fdDump);
  1478.         }
  1479.         fdDump = NULL;
  1480. #endif /* MCH_WRITE_DUMP */
  1481.     }
  1482.  
  1483.     exit(r);
  1484. }
  1485.  
  1486.  
  1487. /*
  1488.  * Do we have an interactive window?
  1489.  */
  1490.     int
  1491. mch_check_win(
  1492.     int argc,
  1493.     char **argv)
  1494. {
  1495.     if (isatty(1))
  1496.         return OK;
  1497.     return FAIL;
  1498. }
  1499.  
  1500.  
  1501. /*
  1502.  * Is input interactive?  (From a keyboard)
  1503.  */
  1504.     int
  1505. mch_check_input()
  1506. {
  1507.     if (isatty(0))
  1508.         return OK;
  1509.     return FAIL;
  1510. }
  1511.  
  1512.  
  1513. /*
  1514.  * Turn a filename into its canonical form.  Replace slashes with backslashes.
  1515.  * This used to replace backslashes with slashes, but that caused problems
  1516.  * when using the file name as a command.  We can't have a mix of slashes and
  1517.  * backslashes, because comparing file names will not work correctly.  The
  1518.  * commands that use file names should be prepared to handle the backslashes.
  1519.  */
  1520.     static void
  1521. canonicalize_filename(
  1522.     char* pszName)
  1523. {
  1524.     if (pszName == NULL)
  1525.         return;
  1526.     
  1527.     for ( ; *pszName;  pszName++)
  1528.     {
  1529.         if (*pszName == '/')
  1530.             *pszName = '\\';
  1531. #ifdef DOWNCASE_FILENAMES
  1532.         else
  1533.             *pszName = tolower(*pszName);
  1534. #endif /* DOWNCASE_FILENAMES */
  1535.     }
  1536. }
  1537.  
  1538.  
  1539. /*
  1540.  * fname_case(): Set the case of the filename, if it already exists.
  1541.  */
  1542.     void
  1543. fname_case(
  1544.     char_u *name)
  1545. {
  1546. #ifdef DOWNCASE_FILENAMES
  1547.     canonicalize_filename(name);
  1548. #else /* !DOWNCASE_FILENAMES */
  1549.     char szTrueName[_MAX_PATH + 1];
  1550.     char *psz, *pszPrev;
  1551.     const int len = (name != NULL)  ?  STRLEN(name)  :  0;
  1552.     
  1553.     if (len == 0)
  1554.         return;
  1555.     
  1556.     STRCPY(szTrueName, name);
  1557.     STRCAT(szTrueName, "\\");    /* sentinel */
  1558.  
  1559.     for (psz = szTrueName;  *psz != NUL;  psz++)
  1560.         if (*psz == '/')
  1561.             *psz = '\\';
  1562.  
  1563.     psz = pszPrev = szTrueName;
  1564.  
  1565.     /* Skip leading \\ in UNC name or drive letter */
  1566.     if (len > 2   &&  ((psz[0] == '\\'  &&  psz[1] == '\\')
  1567.                        || (isalpha(psz[0])  &&  psz[1] == ':')))
  1568.     {
  1569.         psz = pszPrev = szTrueName + 2;
  1570.     }
  1571.     
  1572.     while (*psz != NUL)
  1573.     {
  1574.         WIN32_FIND_DATA fb;
  1575.         HANDLE          hFind;
  1576.  
  1577.         while (*psz != '\\')
  1578.             psz++;
  1579.         *psz = NUL;
  1580.         
  1581.         if ((hFind = FindFirstFile(szTrueName, &fb)) != INVALID_HANDLE_VALUE)
  1582.         {
  1583.             /* avoid ".." and ".", etc */
  1584.             if (_stricoll(pszPrev, fb.cFileName) == 0)
  1585.                 STRCPY(pszPrev, fb.cFileName);
  1586.             FindClose(hFind);
  1587.         }
  1588.         
  1589.         *psz++ = '\\';
  1590.         pszPrev = psz;
  1591.     }
  1592.  
  1593.     *--psz = NUL;    /* remove sentinel */
  1594.  
  1595.     STRCPY(name, szTrueName);
  1596. #endif /* !DOWNCASE_FILENAMES */
  1597. }
  1598.  
  1599.  
  1600. /*
  1601.  * mch_settitle(): set titlebar of our window
  1602.  * Can the icon also be set?
  1603.  */
  1604.     void
  1605. mch_settitle(
  1606.     char_u *title,
  1607.     char_u *icon)
  1608. {
  1609.     if (title != NULL)
  1610.         SetConsoleTitle(title);
  1611. }
  1612.  
  1613.  
  1614. /*
  1615.  * Restore the window/icon title.
  1616.  * which is one of:
  1617.  *    1: Just restore title
  1618.  *  2: Just restore icon (which we don't have)
  1619.  *    3: Restore title and icon (which we don't have)
  1620.  */
  1621.     void
  1622. mch_restore_title(
  1623.     int which)
  1624. {
  1625.     mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
  1626. }
  1627.  
  1628.  
  1629. /*
  1630.  * Return TRUE if we can restore the title (we can)
  1631.  */
  1632.     int
  1633. mch_can_restore_title()
  1634. {
  1635.     return TRUE;
  1636. }
  1637.  
  1638.  
  1639. /*
  1640.  * Return TRUE if we can restore the icon (we can't)
  1641.  */
  1642.     int
  1643. mch_can_restore_icon()
  1644. {
  1645.     return FALSE;
  1646. }
  1647.  
  1648.  
  1649. /*
  1650.  * Insert user name in s[len].
  1651.  */
  1652.     int
  1653. mch_get_user_name(
  1654.     char_u *s,
  1655.     int len)
  1656. {
  1657.     char szUserName[MAX_COMPUTERNAME_LENGTH + 1];
  1658.     DWORD cch = sizeof szUserName;
  1659.  
  1660.     if (GetUserName(szUserName, &cch))
  1661.     {
  1662.         STRNCPY(s, szUserName, len);
  1663.         return OK;
  1664.     }
  1665.     s[0] = NUL;
  1666.     return FAIL;
  1667. }
  1668.  
  1669.  
  1670. /*
  1671.  * Insert host name in s[len].
  1672.  */
  1673.     void
  1674. mch_get_host_name(
  1675.     char_u *s,
  1676.     int len)
  1677. {
  1678.     char szHostName[MAX_COMPUTERNAME_LENGTH + 1];
  1679.     DWORD cch = sizeof szHostName;
  1680.  
  1681.     if (GetComputerName(szHostName, &cch))
  1682.     {
  1683.         STRCPY(s, "PC ");
  1684.         STRNCPY(s + 3, szHostName, len - 3);
  1685.     }
  1686.     else
  1687.         STRNCPY(s, "PC (Win32 Vim)", len);
  1688. }
  1689.  
  1690.  
  1691. /*
  1692.  * return process ID
  1693.  */
  1694.     long
  1695. mch_get_pid()
  1696. {
  1697.     return (long) GetCurrentProcessId();
  1698. }
  1699.  
  1700.  
  1701. /*
  1702.  * Get name of current directory into buffer 'buf' of length 'len' bytes.
  1703.  * Return OK for success, FAIL for failure.
  1704.  */
  1705.     int
  1706. mch_dirname(
  1707.     char_u *buf,
  1708.     int len)
  1709. {
  1710.     return (getcwd(buf, len) != NULL ? OK : FAIL);
  1711. }
  1712.  
  1713.  
  1714. /*
  1715.  * Get absolute filename into buffer 'buf' of length 'len' bytes,
  1716.  * turning all '/'s into '\\'s and getting the correct case of each
  1717.  * component of the filename.  Return OK or FAIL.
  1718.  */
  1719.     int
  1720. FullName(
  1721.     char_u *fname,
  1722.     char_u *buf,
  1723.     int len,
  1724.     int force)
  1725. {
  1726.     int nResult = FAIL;
  1727.     
  1728.     if (fname == NULL)          /* always fail */
  1729.         return FAIL;
  1730.  
  1731.     if (_fullpath(buf, fname, len) == NULL)
  1732.     {
  1733.         /* failed, use the relative path name */
  1734.         STRNCPY(buf, fname, len);
  1735.     }
  1736.     else
  1737.         nResult = OK;
  1738.  
  1739.     fname_case(buf);
  1740.  
  1741.     return nResult;
  1742. }
  1743.  
  1744.  
  1745. /*
  1746.  * return TRUE if `fname' is an absolute path name
  1747.  */
  1748.     int
  1749. isFullName(
  1750.     char_u *fname)
  1751. {
  1752.     char szName[_MAX_PATH];
  1753.  
  1754.     FullName(fname, szName, _MAX_PATH, FALSE);
  1755.  
  1756. #ifdef DOWNCASE_FILENAMES
  1757.     return _stricoll(fname, szName) == 0;
  1758. #else /* !DOWNCASE_FILENAMES */
  1759.     return strcoll(fname, szName) == 0;
  1760. #endif /* !DOWNCASE_FILENAMES */
  1761. }
  1762.  
  1763.  
  1764. /*
  1765.  * get file permissions for `name'
  1766.  * -1 : error
  1767.  * else FILE_ATTRIBUTE_* defined in winnt.h
  1768.  */
  1769.     long
  1770. getperm(
  1771.     char_u *name)
  1772. {
  1773.     return GetFileAttributes(name);
  1774. }
  1775.  
  1776.  
  1777. /*
  1778.  * set file permission for `name' to `perm'
  1779.  */
  1780.     int
  1781. setperm(
  1782.     char_u *name,
  1783.     long perm)
  1784. {
  1785.     perm |= FILE_ATTRIBUTE_ARCHIVE;        /* file has changed, set archive bit */
  1786.     return SetFileAttributes(name, perm) ? OK : FAIL;
  1787. }
  1788.  
  1789.  
  1790. /*
  1791.  * return TRUE if "name" is a directory
  1792.  * return FALSE if "name" is not a directory or upon error
  1793.  */
  1794.     int
  1795. mch_isdir(
  1796.     char_u *name)
  1797. {
  1798.     int f = getperm(name);
  1799.  
  1800.     if (f == -1)
  1801.         return FALSE;              /* file does not exist at all */
  1802.  
  1803.     return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
  1804. }
  1805.  
  1806.  
  1807. /*
  1808.  * handler for ctrl-break, ctrl-c interrupts, and fatal events. 
  1809.  */
  1810.     static BOOL WINAPI
  1811. handler_routine(
  1812.     DWORD dwCtrlType)
  1813. {
  1814.     switch (dwCtrlType)
  1815.     {
  1816.     case CTRL_C_EVENT:
  1817.         g_fCtrlCPressed = TRUE;
  1818.         return TRUE;
  1819.  
  1820.     case CTRL_BREAK_EVENT:
  1821.         g_fCBrkPressed  = TRUE;
  1822.         return TRUE;
  1823.  
  1824.     /* fatal events: shut down gracefully */
  1825.     case CTRL_CLOSE_EVENT:
  1826.     case CTRL_LOGOFF_EVENT:
  1827.     case CTRL_SHUTDOWN_EVENT:
  1828.         windgoto((int)Rows - 1, 0);
  1829.         sprintf((char *)IObuff, "Vim: Caught %s event\n",
  1830.                 (dwCtrlType == CTRL_CLOSE_EVENT ? "close"
  1831.                  : dwCtrlType == CTRL_LOGOFF_EVENT ? "logoff" : "shutdown"));
  1832.  
  1833. #ifdef DEBUG
  1834.         OutputDebugString(IObuff);
  1835. #endif /* DEBUG */
  1836.  
  1837.         preserve_exit();        /* output IObuff, preserve files and exit */
  1838.  
  1839.         return TRUE;            /* not reached */
  1840.  
  1841.     default:
  1842.         return FALSE;
  1843.     }
  1844. }
  1845.  
  1846.  
  1847. /*
  1848.  * set the tty in (raw) ? "raw" : "cooked" mode
  1849.  */
  1850.     void
  1851. mch_settmode(
  1852.     int raw)
  1853. {
  1854.     DWORD cmodein;
  1855.     DWORD cmodeout;
  1856.  
  1857.     GetConsoleMode(g_hConIn,  &cmodein);
  1858.     GetConsoleMode(g_hCurOut, &cmodeout);
  1859.  
  1860.     if (raw)
  1861.     {
  1862.         cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
  1863.                      ENABLE_ECHO_INPUT);
  1864.         cmodein |= (
  1865. #ifdef USE_MOUSE
  1866.             (g_fMouseActive ? ENABLE_MOUSE_INPUT : 0) |
  1867. #endif /* USE_MOUSE */
  1868.             ENABLE_WINDOW_INPUT);
  1869.  
  1870.         SetConsoleMode(g_hConIn, cmodein);
  1871.  
  1872.         cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
  1873.         SetConsoleMode(g_hCurOut, cmodeout);
  1874.         SetConsoleCtrlHandler(handler_routine, TRUE);
  1875.     }
  1876.     else /* cooked */
  1877.     {
  1878.         cmodein =  g_cmodein;
  1879.         cmodeout = g_cmodeout;
  1880.         SetConsoleMode(g_hConIn,  g_cmodein);
  1881.         SetConsoleMode(g_hCurOut, g_cmodeout);
  1882.  
  1883.         SetConsoleCtrlHandler(handler_routine, FALSE);
  1884.     }
  1885.  
  1886. #ifdef MCH_WRITE_DUMP
  1887.     if (fdDump)
  1888.     {
  1889.         fprintf(fdDump, "mch_settmode(%s, CurOut = %s, in = %x, out = %x)\n",
  1890.                 raw ? "raw" : "cooked",
  1891.                 (g_hCurOut == g_hSavOut ? "Sav" : "Con"),
  1892.                 cmodein, cmodeout);
  1893.         fflush(fdDump);
  1894.     }
  1895. #endif /* MCH_WRITE_DUMP */
  1896. }
  1897.  
  1898.  
  1899. /*
  1900.  * Get the size of the current window in `Rows' and `Columns'
  1901.  */
  1902.     int
  1903. mch_get_winsize()
  1904. {
  1905.     CONSOLE_SCREEN_BUFFER_INFO csbi;
  1906.  
  1907.     if (GetConsoleScreenBufferInfo(g_hCurOut, &csbi))
  1908.     {
  1909.         Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
  1910.         Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
  1911.     }
  1912.     else
  1913.     {
  1914.         Rows = 25;
  1915.         Columns = 80;
  1916.     }
  1917.  
  1918.     if (Columns < MIN_COLUMNS  ||  Rows < MIN_ROWS + 1)
  1919.     {
  1920.         /* these values are overwritten by termcap size or default */
  1921.         Rows = 25;
  1922.         Columns = 80;
  1923.     }
  1924.  
  1925.     check_winsize();
  1926.     set_scroll_region(0, 0, Columns - 1, Rows - 1);
  1927.  
  1928.     return OK;
  1929. }
  1930.  
  1931.  
  1932. /*
  1933.  * Set a console window to `xSize' * `ySize'
  1934.  */
  1935.     static void
  1936. ResizeConBufAndWindow(
  1937.     HANDLE hConsole,
  1938.     int xSize,
  1939.     int ySize)
  1940. {
  1941.     CONSOLE_SCREEN_BUFFER_INFO csbi;    /* hold current console buffer info */
  1942.     SMALL_RECT      srWindowRect;       /* hold the new console size */
  1943.     COORD           coordScreen;
  1944.     DWORD            dwErr = 0;
  1945.  
  1946. #ifdef MCH_WRITE_DUMP
  1947.     if (fdDump)
  1948.     {
  1949.         fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
  1950.         fflush(fdDump);
  1951.     }
  1952. #endif /* MCH_WRITE_DUMP */
  1953.  
  1954.     GetConsoleScreenBufferInfo(hConsole, &csbi);
  1955.  
  1956.     /* get the largest size we can size the console window to */
  1957.     coordScreen = GetLargestConsoleWindowSize(hConsole);
  1958.  
  1959.     /* define the new console window size and scroll position */
  1960.     srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
  1961.     srWindowRect.Right =  (SHORT) (min(xSize, coordScreen.X) - 1);
  1962.     srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
  1963.  
  1964.     /* define the new console buffer size */
  1965.     coordScreen.X = xSize;
  1966.     coordScreen.Y = ySize;
  1967.  
  1968.     if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
  1969.     {
  1970. #ifdef MCH_WRITE_DUMP
  1971.         if (fdDump)
  1972.         {
  1973.             fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
  1974.                     GetLastError());
  1975.             fflush(fdDump);
  1976.         }
  1977. #endif /* MCH_WRITE_DUMP */
  1978.     }
  1979.  
  1980.     if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
  1981.     {
  1982. #ifdef MCH_WRITE_DUMP
  1983.         if (fdDump)
  1984.         {
  1985.             fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
  1986.                     GetLastError());
  1987.             fflush(fdDump);
  1988.         }
  1989. #endif /* MCH_WRITE_DUMP */
  1990.     }
  1991.  
  1992. }
  1993.  
  1994.  
  1995. /*
  1996.  * Set the console window to `Rows' * `Columns'
  1997.  */
  1998.     void
  1999. mch_set_winsize()
  2000. {
  2001.     COORD coordScreen = GetLargestConsoleWindowSize(g_hCurOut);
  2002.  
  2003.     /* Clamp Rows and Columns to reasonable values */
  2004.     if (Rows > coordScreen.Y)
  2005.         Rows = coordScreen.Y;
  2006.     if (Columns > coordScreen.X)
  2007.         Columns = coordScreen.X;
  2008.  
  2009.     ResizeConBufAndWindow(g_hCurOut, Columns, Rows);
  2010.     set_scroll_region(0, 0, Columns - 1, Rows - 1);
  2011. }
  2012.  
  2013.  
  2014. /*
  2015.  * We have no job control, so fake it by starting a new shell.
  2016.  */
  2017.     void
  2018. mch_suspend()
  2019. {
  2020.     MSG_OUTSTR("new shell started\n");
  2021.     call_shell(NULL, SHELL_COOKED);
  2022.     need_check_timestamps = TRUE;
  2023. }
  2024.  
  2025.  
  2026. /*
  2027.  * Either execute a command by calling the shell or start a new shell
  2028.  */
  2029.     int
  2030. call_shell(
  2031.     char_u *cmd,
  2032.     int options)            /* SHELL_FILTER if called by do_filter() */
  2033.                             /* SHELL_COOKED if term needs cooked mode */
  2034.                             /* SHELL_EXPAND if called by ExpandWildCards() */
  2035. {
  2036.     int        x;
  2037.     int        stopped_termcap_mode = FALSE;
  2038.  
  2039.     flushbuf();
  2040.  
  2041.     /*
  2042.      * ALWAYS switch to non-termcap mode, otherwise ":r !ls" may crash.
  2043.      */
  2044.     if (g_hCurOut == g_hConOut)
  2045.     {
  2046.         termcap_mode_end();
  2047.         stopped_termcap_mode = TRUE;
  2048.     }
  2049.  
  2050. #ifdef MCH_WRITE_DUMP
  2051.     if (fdDump)
  2052.     {
  2053.         fprintf(fdDump, "call_shell(\"%s\", %d)\n", cmd, options);
  2054.         fflush(fdDump);
  2055.     }
  2056. #endif /* MCH_WRITE_DUMP */
  2057.  
  2058.     signal(SIGINT, SIG_IGN);    /* we don't want to be killed here by Ctrl-C*/
  2059.     signal(SIGBREAK, SIG_IGN);    /* Nor by Ctrl-Break */
  2060.  
  2061.     if (options & SHELL_COOKED)
  2062.         settmode(0);            /* set to cooked mode */
  2063.  
  2064.     if (cmd == NULL)
  2065.     {
  2066.         x = system(p_sh);
  2067.     }
  2068.     else
  2069.     {
  2070.         /* we use "command" or "cmd" to start the shell; slow but easy */
  2071.         char newcmd[CMDBUFFSIZE + 100];
  2072.  
  2073.         sprintf(newcmd, "%s %s %s", p_sh, p_shcf, cmd);
  2074.         x = system(newcmd);
  2075.     }
  2076.  
  2077.     settmode(1);                /* set to raw mode */
  2078.  
  2079.     if (x && !expand_interactively)
  2080.     {
  2081.         smsg("%d returned", x);
  2082.         msg_outchar('\n');
  2083.     }
  2084.     resettitle();
  2085.  
  2086.     signal(SIGINT, SIG_DFL);
  2087.     signal(SIGBREAK, SIG_DFL);
  2088.  
  2089.     if (stopped_termcap_mode)
  2090.         termcap_mode_start();
  2091.  
  2092.     return (x ? FAIL : OK);
  2093. }
  2094.  
  2095.  
  2096. #define FL_CHUNK 32
  2097.  
  2098. typedef struct filelist {
  2099.     char_u** file;
  2100.     int      nfiles;
  2101.     int      maxfiles;
  2102. } FileList;
  2103.  
  2104.  
  2105. /*
  2106.  * Add filename `f' to the list of files in `fl'
  2107.  */
  2108.     static void
  2109. addfile(
  2110.     FileList *fl,
  2111.     char *f,
  2112.     int isdir)
  2113. {
  2114.     char           *p, *pp;
  2115.  
  2116.     if (!fl->file)
  2117.     {
  2118.         fl->file = (char **) alloc(sizeof(char *) * FL_CHUNK);
  2119.         if (!fl->file)
  2120.             return;
  2121.         fl->nfiles = 0;
  2122.         fl->maxfiles = FL_CHUNK;
  2123.     }
  2124.     if (fl->nfiles >= fl->maxfiles)
  2125.     {
  2126.         char          **t;
  2127.         int             i;
  2128.  
  2129.         t = (char **) lalloc(sizeof(char *) * (fl->maxfiles + FL_CHUNK), TRUE);
  2130.         if (!t)
  2131.             return;
  2132.         for (i = fl->nfiles - 1; i >= 0; i--)
  2133.             t[i] = fl->file[i];
  2134.         vim_free(fl->file);
  2135.         fl->file = t;
  2136.         fl->maxfiles += FL_CHUNK;
  2137.     }
  2138.     p = alloc((unsigned) (strlen(f) + 1 + isdir));
  2139.     if (p)
  2140.     {
  2141.         /* replace slashes with backslashes while copying */
  2142.         for (pp = p; *f; ++f, ++pp)
  2143.         {
  2144.             if (*f == '/')
  2145.                 *pp = '\\';
  2146.             else
  2147.                 *pp = *f;
  2148.         }
  2149.         if (isdir)
  2150.             *pp++ = '\\';
  2151.         *pp = NUL;
  2152.     }
  2153.     fl->file[fl->nfiles++] = p;
  2154. }
  2155.  
  2156.  
  2157. /*
  2158.  * Does `s' contain a wildcard?
  2159.  */
  2160.     int
  2161. mch_has_wildcard(
  2162.     char_u *s)
  2163. {
  2164.     for ( ;  *s;  ++s)
  2165.         if (*s == '?' || *s == '*' || *s == '$')
  2166.             return TRUE;
  2167.     return FALSE;
  2168. }
  2169.  
  2170.  
  2171. /*
  2172.  * Copy a string, forcing it to lowercase if DOWNCASE_FILENAMES is defined
  2173.  */
  2174. #ifdef DOWNCASE_FILENAMES
  2175.     static void
  2176. strlowcpy(
  2177.     char *d,
  2178.     char *s)
  2179. {
  2180.     while (*s)
  2181.         *d++ = tolower(*s++);
  2182.     *d = NUL;
  2183. }
  2184. #else /* !DOWNCASE_FILENAMES */
  2185. # define strlowcpy(d, s) STRCPY(d, s)
  2186. #endif /* !DOWNCASE_FILENAMES */
  2187.  
  2188.  
  2189. /*
  2190.  * comparison function for qsort in expandpath
  2191.  */
  2192.     static int
  2193. pstrcmp(
  2194.     const void *a,
  2195.     const void *b)
  2196. {
  2197. #ifdef DOWNCASE_FILENAMES
  2198.     return (_stricoll(* (const char **) a, * (const char **) b));
  2199. #else /* !DOWNCASE_FILENAMES */
  2200.     return (strcoll(* (const char **) a, * (const char **) b));
  2201. #endif /* !DOWNCASE_FILENAMES */
  2202. }
  2203.  
  2204.  
  2205. /*
  2206.  * recursively build up a list of files in `fl' matching the first wildcard
  2207.  * in `path'.  `fonly' and `donly' are not used (files only and directories
  2208.  * only flags?).  If `notf' is set, we add `path' to `fl' even when no such
  2209.  * file exists.
  2210.  */
  2211.     static int
  2212. expandpath(
  2213.     FileList *fl,
  2214.     char *path,
  2215.     int fonly,
  2216.     int donly,
  2217.     int notf)
  2218. {
  2219.     char            buf[_MAX_PATH];
  2220.     char           *p,
  2221.                    *s,
  2222.                    *e;
  2223.     int             lastn,
  2224.                     c = 1,
  2225.                     r;
  2226.     WIN32_FIND_DATA fb;
  2227.     HANDLE          hFind;
  2228.     int                found_one = FALSE;
  2229.  
  2230.     lastn = fl->nfiles;
  2231.  
  2232.     /*
  2233.      * Find the first part in the path name that contains a wildcard.
  2234.      * Copy it into `buf', including the preceding characters.
  2235.      */
  2236.     p = buf;
  2237.     s = NULL;
  2238.     e = NULL;
  2239.     while (*path)
  2240.     {
  2241.         if (*path == '\\' || *path == ':' || *path == '/')
  2242.         {
  2243.             if (e)
  2244.                 break;
  2245.             else
  2246.                 s = p;
  2247.         }
  2248.         if (*path == '*' || *path == '?')
  2249.             e = p;
  2250.         *p++ = *path++;
  2251.     }
  2252.     e = p;
  2253.     if (s)
  2254.         s++;
  2255.     else
  2256.         s = buf;
  2257.  
  2258.     /* now we have one wildcard component between `s' and `e' */
  2259.     *e = NUL;
  2260.     r = 0;
  2261.  
  2262.     /* If we are expanding wildcards, we try both files and directories */
  2263.     if ((hFind = FindFirstFile(buf, &fb)) != INVALID_HANDLE_VALUE)
  2264.         while (c)
  2265.         {
  2266.             strlowcpy(s, fb.cFileName);
  2267.  
  2268.             /*
  2269.              * Ignore "." and "..".
  2270.              * When more follows, this must be a directory.
  2271.              */
  2272.             if ((s[0] != '.'  ||
  2273.                     (s[1] != NUL  &&  (s[1] != '.' || s[2] != NUL))) &&
  2274.                     (*path == NUL || mch_isdir(buf)))
  2275.             {
  2276.                 strcat(buf, path);
  2277.                 if (!mch_has_wildcard(path))
  2278.                     addfile(fl, buf, mch_isdir(buf));
  2279.                 else
  2280.                     r |= expandpath(fl, buf, fonly, donly, notf);
  2281.                 found_one = TRUE;
  2282.             }
  2283.  
  2284.             c = FindNextFile(hFind, &fb);
  2285.         }
  2286.  
  2287.     if (!found_one)
  2288.     {
  2289.         /* not found */
  2290.         STRCPY(e, path);
  2291.  
  2292.         if (notf)
  2293.             addfile(fl, buf, FALSE);
  2294.  
  2295.         return 1;               /* unexpanded or empty */
  2296.     }
  2297.  
  2298.     qsort(fl->file + lastn, fl->nfiles - lastn, sizeof(char *), pstrcmp);
  2299.     FindClose(hFind);
  2300.  
  2301.     return r;
  2302. }
  2303.  
  2304.  
  2305. /*
  2306.  * MSDOS rebuild of Scott Ballantyne's ExpandWildCards for amiga/arp. -- jw
  2307.  *
  2308.  * return OK for success, FAIL for error (you may lose some memory) and
  2309.  *       put an error message in *file.
  2310.  *
  2311.  * `num_pat' is number of input patterns
  2312.  * `pat' is array of pointers to input patterns
  2313.  * `num_file' is pointer to number of matched file names
  2314.  * `file' is pointer to array of pointers to matched file names
  2315.  * On Unix/Win32, we do not check for `files_only' yet
  2316.  * `list_notfound' is ignored
  2317.  */
  2318.     int
  2319. ExpandWildCards(
  2320.     int num_pat,
  2321.     char_u **pat,
  2322.     int *num_file,
  2323.     char_u ***file,
  2324.     int files_only,
  2325.     int list_notfound)
  2326. {
  2327.     int                i,
  2328.                     r = 0;
  2329.     FileList        f;
  2330.     char_u            *p;
  2331.  
  2332.     f.file = NULL;
  2333.     f.nfiles = 0;
  2334.  
  2335.     for (i = 0; i < num_pat; i++)
  2336.     {
  2337.         /*
  2338.          * First expand environment variables.
  2339.          */
  2340.         if (vim_strchr(pat[i], '$') != NULL)
  2341.         {
  2342.             p = alloc(MAXPATHL);
  2343.             if (p != NULL)
  2344.                 expand_env(pat[i], p, MAXPATHL);
  2345.             else
  2346.                 p = pat[i];
  2347.         }
  2348.         else
  2349.             p = pat[i];
  2350.  
  2351.         if (!mch_has_wildcard(p))
  2352.             addfile(&f, p, files_only ? FALSE : mch_isdir(p));
  2353.         else
  2354.             r |= expandpath(&f, p, files_only, 0, list_notfound);
  2355.  
  2356.         if (p != pat[i])
  2357.             vim_free(p);
  2358.     }
  2359.  
  2360.     *num_file = f.nfiles;
  2361.     *file = (*num_file > 0) ? f.file : (char_u **)"";
  2362.  
  2363.     return (*num_file > 0) ? OK : FAIL;
  2364. }
  2365.  
  2366.  
  2367. #ifdef vim_chdir
  2368. # undef vim_chdir
  2369. #endif
  2370.  
  2371. /*
  2372.  * The normal _chdir() does not change the default drive.  This one does.
  2373.  * Returning 0 implies success; -1 implies failure.
  2374.  */
  2375.     int
  2376. vim_chdir(
  2377.     char *path)
  2378. {
  2379.     if (path[0] == NUL)         /* just checking... */
  2380.         return -1;
  2381.  
  2382.     if (isalpha(path[0])  &&  path[1] == ':')    /* has a drive name */
  2383.     {
  2384.         if (_chdrive(toupper(path[0]) - 'A' + 1) != 0)
  2385.             return -1;          /* invalid drive name */
  2386.         path += 2;
  2387.     }
  2388.  
  2389.     if (*path == NUL)           /* drive name only */
  2390.         return 0;
  2391.  
  2392.     return chdir(path);        /* let the normal chdir() do the rest */
  2393. }
  2394.  
  2395.  
  2396. /*
  2397.  * Copy the contents of screen buffer hSrc to the bottom-left corner
  2398.  * of screen buffer hDst.
  2399.  */
  2400.     static void
  2401. copy_screen_buffer_text(
  2402.     HANDLE hSrc,
  2403.     HANDLE hDst)
  2404. {
  2405.     int     i, j, nSrcWidth, nSrcHeight, nDstWidth, nDstHeight;
  2406.     COORD   coordOrigin;
  2407.     DWORD   dwDummy;
  2408.     LPSTR   pszOldText;
  2409.     CONSOLE_SCREEN_BUFFER_INFO csbiSrc, csbiDst;
  2410.  
  2411. #ifdef MCH_WRITE_DUMP
  2412.     if (fdDump)
  2413.     {
  2414.         fprintf(fdDump, "copy_screen_buffer_text(%s, %s)\n",
  2415.                 (hSrc == g_hSavOut ? "Sav" : "Con"),
  2416.                 (hDst == g_hSavOut ? "Sav" : "Con"));
  2417.         fflush(fdDump);
  2418.     }
  2419. #endif /* MCH_WRITE_DUMP */
  2420.  
  2421.     GetConsoleScreenBufferInfo(hSrc, &csbiSrc);
  2422.     nSrcWidth =  csbiSrc.srWindow.Right  - csbiSrc.srWindow.Left + 1;
  2423.     nSrcHeight = csbiSrc.srWindow.Bottom - csbiSrc.srWindow.Top  + 1;
  2424.  
  2425.     GetConsoleScreenBufferInfo(hDst, &csbiDst);
  2426.     nDstWidth =  csbiDst.srWindow.Right  - csbiDst.srWindow.Left + 1;
  2427.     nDstHeight = csbiDst.srWindow.Bottom - csbiDst.srWindow.Top  + 1;
  2428.  
  2429.     pszOldText = (LPSTR) alloc(nDstHeight * nDstWidth);
  2430.         
  2431.     /* clear the top few lines if Src shorter than Dst */
  2432.     for (i = 0;  i < nDstHeight - nSrcHeight;  i++)
  2433.     {
  2434.         for (j = 0;  j < nDstWidth;  j++)
  2435.             pszOldText[i * nDstWidth + j] = ' ';
  2436.     }
  2437.     
  2438.     /* Grab text off source screen. */
  2439.     coordOrigin.X = 0;
  2440.     coordOrigin.Y = (SHORT) max(0, csbiSrc.srWindow.Bottom + 1 - nDstHeight);
  2441.  
  2442.     for (i = 0;  i < min(nSrcHeight, nDstHeight);  i++)
  2443.     {
  2444.         LPSTR psz = pszOldText
  2445.                      + (i + max(0, nDstHeight - nSrcHeight)) * nDstWidth;
  2446.         
  2447.         ReadConsoleOutputCharacter(hSrc, psz, min(nDstWidth, nSrcWidth),
  2448.                                    coordOrigin, &dwDummy);
  2449.         coordOrigin.Y++;
  2450.         
  2451.         /* clear the last few columns if Src narrower than Dst */
  2452.         for (j = nSrcWidth;  j < nDstWidth;  j++)
  2453.             psz[j] = ' ';
  2454.     }
  2455.  
  2456.     /* paste Src's text onto Dst */
  2457.     coordOrigin.Y = csbiDst.srWindow.Top;
  2458.     WriteConsoleOutputCharacter(hDst, pszOldText, nDstHeight * nDstWidth,
  2459.                                 coordOrigin, &dwDummy);
  2460.     vim_free(pszOldText);
  2461. }
  2462.  
  2463.  
  2464. /* keep track of state of original console window */
  2465. static SMALL_RECT g_srOrigWindowRect;
  2466. static COORD      g_coordOrig;
  2467. static WORD       g_attrSave = 0;
  2468.  
  2469.  
  2470. /*
  2471.  * Start termcap mode by switching to our allocated screen buffer
  2472.  */
  2473.     static void
  2474. termcap_mode_start()
  2475. {
  2476.     CONSOLE_SCREEN_BUFFER_INFO csbi;
  2477.     DWORD dwDummy;
  2478.     COORD coord;
  2479.     WORD wAttr = (WORD) (g_attrSave ? g_attrSave : g_attrCurrent);
  2480.  
  2481.     GetConsoleScreenBufferInfo(g_hSavOut, &csbi);
  2482.     g_srOrigWindowRect = csbi.srWindow;
  2483.  
  2484.     g_coordOrig.X = 0;
  2485.     g_coordOrig.Y = csbi.dwCursorPosition.Y;
  2486.  
  2487.     if (g_hConOut == INVALID_HANDLE_VALUE)
  2488.     {
  2489.         /* Create a new screen buffer in which we do all of our editing.
  2490.          * This means we can restore the original screen when we finish. */
  2491.         g_hConOut = CreateConsoleScreenBuffer(GENERIC_WRITE | GENERIC_READ, 
  2492.                                               0, (LPSECURITY_ATTRIBUTES) NULL,
  2493.                                               CONSOLE_TEXTMODE_BUFFER,
  2494.                                               (LPVOID) NULL);
  2495.     }
  2496.  
  2497.     coord.X = coord.Y = 0;
  2498.     FillConsoleOutputCharacter(g_hConOut, ' ', Rows * Columns, coord, &dwDummy);
  2499.     FillConsoleOutputAttribute(g_hConOut, wAttr, Rows*Columns, coord, &dwDummy);
  2500.  
  2501.     copy_screen_buffer_text(g_hSavOut, g_hConOut);
  2502.     
  2503.     g_hCurOut = g_hConOut;
  2504.     SetConsoleActiveScreenBuffer(g_hCurOut);
  2505.  
  2506.     ResizeConBufAndWindow(g_hCurOut, Columns, Rows);
  2507.     set_scroll_region(0, 0, Columns - 1, Rows - 1);
  2508.     check_winsize();
  2509.  
  2510.     resettitle();
  2511.  
  2512.     textattr(wAttr);
  2513. }
  2514.  
  2515.  
  2516. /*
  2517.  * Turn off termcap mode by restoring the screen buffer we had upon startup
  2518.  */
  2519.     static void
  2520. termcap_mode_end()
  2521. {
  2522.     g_attrSave = g_attrCurrent;
  2523.  
  2524.     ResizeConBufAndWindow(g_hCurOut, g_nOldColumns, g_nOldRows);
  2525.     check_winsize();
  2526.  
  2527.     g_hCurOut = g_hSavOut;
  2528.     SetConsoleActiveScreenBuffer(g_hCurOut);
  2529.     SetConsoleCursorInfo(g_hCurOut, &g_cci);
  2530.  
  2531.     normvideo();
  2532.  
  2533.     if (!p_rs)
  2534.         g_coordOrig.Y = g_srOrigWindowRect.Bottom;
  2535.     
  2536.     SetConsoleCursorPosition(g_hCurOut, g_coordOrig);
  2537.  
  2538.     if (!p_rs)
  2539.         copy_screen_buffer_text(g_hConOut, g_hSavOut);
  2540.  
  2541.     clear_chars(g_coordOrig,
  2542.                 g_srOrigWindowRect.Right - g_srOrigWindowRect.Left + 1);
  2543.     
  2544.     mch_restore_title(3);
  2545.  
  2546.     SetConsoleMode(g_hConIn,  g_cmodein);
  2547.     SetConsoleMode(g_hSavOut, g_cmodeout);
  2548. }
  2549.  
  2550. /*
  2551.  * Switching off termcap mode is only allowed when Columns is 80, otherwise a
  2552.  * crash may result.  It's always allowed on NT.
  2553.  */
  2554.     int
  2555. can_end_termcap_mode(
  2556.     int give_msg)
  2557. {
  2558.     if (g_PlatformId == VER_PLATFORM_WIN32_NT  ||  Columns == 80)
  2559.         return TRUE;
  2560.     if (give_msg)
  2561.         msg("'columns' is not 80, cannot execute external commands");
  2562.     return FALSE;
  2563. }
  2564.  
  2565. /*
  2566.  * clear `n' chars, starting from `coord'
  2567.  */
  2568.     static void
  2569. clear_chars(
  2570.     COORD coord,
  2571.     DWORD n)
  2572. {
  2573.     DWORD dwDummy;
  2574.  
  2575.     FillConsoleOutputCharacter(g_hCurOut, ' ', n, coord, &dwDummy);
  2576.     FillConsoleOutputAttribute(g_hCurOut, g_attrCurrent, n, coord, &dwDummy);
  2577. }
  2578.  
  2579.  
  2580. /*
  2581.  * Clear the screen
  2582.  */
  2583.     static void
  2584. clear_screen()
  2585. {
  2586.     g_coord.X = g_coord.Y = 0;
  2587.     clear_chars(g_coord, Rows * Columns);
  2588. }
  2589.  
  2590.  
  2591. /*
  2592.  * Clear to end of display
  2593.  */
  2594.     static void
  2595. clear_to_end_of_display()
  2596. {
  2597.     clear_chars(g_coord, (Rows-g_coord.Y-1) * Columns + (Columns-g_coord.X));
  2598. }
  2599.  
  2600.  
  2601. /*
  2602.  * Clear to end of line
  2603.  */
  2604.     static void
  2605. clear_to_end_of_line()
  2606. {
  2607.     clear_chars(g_coord, Columns - g_coord.X);
  2608. }
  2609.  
  2610.  
  2611. /*
  2612.  * Scroll the scroll region up by `cLines' lines
  2613.  */
  2614.     static void
  2615. scroll(
  2616.     unsigned cLines)
  2617. {
  2618.     COORD oldcoord = g_coord;
  2619.     
  2620.     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
  2621.     delete_lines(cLines);
  2622.  
  2623.     g_coord = oldcoord;
  2624. }
  2625.  
  2626.  
  2627. /*
  2628.  * Set the scroll region
  2629.  */
  2630.     static void
  2631. set_scroll_region(
  2632.     unsigned left,
  2633.     unsigned top,
  2634.     unsigned right,
  2635.     unsigned bottom)
  2636. {
  2637.     if (left >= right  ||  top >= bottom
  2638.         ||  right > (unsigned) Columns - 1
  2639.         ||  bottom > (unsigned) Rows - 1)
  2640.         return;
  2641.     
  2642.     g_srScrollRegion.Left =   left;
  2643.     g_srScrollRegion.Top =    top;
  2644.     g_srScrollRegion.Right =  right;
  2645.     g_srScrollRegion.Bottom = bottom;
  2646. }
  2647.  
  2648.  
  2649. /*
  2650.  * Insert `cLines' lines at the current cursor position
  2651.  */
  2652.     static void
  2653. insert_lines(
  2654.     unsigned cLines)
  2655. {
  2656.     SMALL_RECT      source;
  2657.     COORD           dest;
  2658.     CHAR_INFO       fill;
  2659.  
  2660.     dest.X = 0;
  2661.     dest.Y = g_coord.Y + cLines;
  2662.  
  2663.     source.Left   = 0;
  2664.     source.Top    = g_coord.Y;
  2665.     source.Right  = g_srScrollRegion.Right;
  2666.     source.Bottom = g_srScrollRegion.Bottom - cLines;
  2667.  
  2668.     fill.Char.AsciiChar = ' ';
  2669.     fill.Attributes = g_attrCurrent;
  2670.  
  2671.     ScrollConsoleScreenBuffer(g_hCurOut, &source, NULL, dest, &fill);
  2672.  
  2673.     /* Here we have to deal with a win32 console flake: If the scroll
  2674.      * region looks like abc and we scroll c to a and fill with d we get
  2675.      * cbd... if we scroll block c one line at a time to a, we get cdd...
  2676.      * vim expects cdd consistently... So we have to deal with that
  2677.      * here... (this also occurs scrolling the same way in the other
  2678.      * direction).  */
  2679.  
  2680.     if (source.Bottom < dest.Y)
  2681.     {
  2682.         COORD coord;
  2683.  
  2684.         coord.X = 0;
  2685.         coord.Y = source.Bottom;
  2686.         clear_chars(coord, Columns * (dest.Y - source.Bottom));
  2687.     }
  2688. }
  2689.  
  2690.  
  2691. /*
  2692.  * Delete `cLines' lines at the current cursor position
  2693.  */
  2694.     static void
  2695. delete_lines(
  2696.     unsigned cLines)
  2697. {
  2698.     SMALL_RECT      source;
  2699.     COORD           dest;
  2700.     CHAR_INFO       fill;
  2701.     int                nb;
  2702.  
  2703.     dest.X = 0;
  2704.     dest.Y = g_coord.Y;
  2705.  
  2706.     source.Left   = 0;
  2707.     source.Top    = g_coord.Y + cLines;
  2708.     source.Right  = g_srScrollRegion.Right;
  2709.     source.Bottom = g_srScrollRegion.Bottom;
  2710.  
  2711.     fill.Char.AsciiChar = ' ';
  2712.     fill.Attributes = g_attrCurrent;
  2713.  
  2714.     ScrollConsoleScreenBuffer(g_hCurOut, &source, NULL, dest, &fill);
  2715.  
  2716.     /* Here we have to deal with a win32 console flake: If the scroll
  2717.      * region looks like abc and we scroll c to a and fill with d we get
  2718.      * cbd... if we scroll block c one line at a time to a, we get cdd...
  2719.      * vim expects cdd consistently... So we have to deal with that
  2720.      * here... (this also occurs scrolling the same way in the other
  2721.      * direction).  */
  2722.  
  2723.     nb = dest.Y + (source.Bottom - source.Top) + 1;
  2724.  
  2725.     if (nb < source.Top)
  2726.     {
  2727.         COORD coord;
  2728.  
  2729.         coord.X = 0;
  2730.         coord.Y = nb;
  2731.         clear_chars(coord, Columns * (source.Top - nb));
  2732.     }
  2733. }
  2734.  
  2735.  
  2736. /*
  2737.  * Set the cursor position
  2738.  */
  2739.     static void
  2740. gotoxy(
  2741.     unsigned x,
  2742.     unsigned y)
  2743. {
  2744.     COORD coord2;
  2745.     
  2746.     if (x < 1  ||  x > (unsigned) Columns  ||  y < 1  ||  y > (unsigned) Rows)
  2747.         return;
  2748.  
  2749.     /* Should we check against g_srScrollRegion? */
  2750.  
  2751.     /* external cursor coords are 1-based; internal are 0-based */
  2752.     g_coord.X = coord2.X = x - 1;
  2753.     g_coord.Y = coord2.Y = y - 1;
  2754.  
  2755.     /* If we are using the window buffer that we had upon startup, make
  2756.      * sure to position cursor relative to the window upon that buffer */
  2757.     if (g_hCurOut == g_hSavOut)
  2758.     {
  2759.         CONSOLE_SCREEN_BUFFER_INFO csbi;
  2760.  
  2761.         GetConsoleScreenBufferInfo(g_hCurOut, &csbi);
  2762.         g_srOrigWindowRect = csbi.srWindow;
  2763.  
  2764.         coord2.X += (SHORT) (g_srOrigWindowRect.Left);
  2765.         coord2.Y += (SHORT) (g_srOrigWindowRect.Bottom + 1 - Rows);
  2766.     }
  2767.  
  2768.     SetConsoleCursorPosition(g_hCurOut, coord2);
  2769. }
  2770.  
  2771.  
  2772. /*
  2773.  * Set the current text attribute = (foreground | background)
  2774.  *
  2775.  * COLOR        FOREGROUND    BACKGROUND
  2776.  *  black            0            0
  2777.  *  blue            1           16
  2778.  *  green            2           32
  2779.  *  cyan            3           48
  2780.  *  red                4           64
  2781.  *  magenta            5           80
  2782.  *  brown            6           96
  2783.  *  lightgray        7          112
  2784.  *  darkgray        8          128
  2785.  *  lightblue        9          144
  2786.  *  lightgreen       10          160
  2787.  *  lightcyan       11          176
  2788.  *  lightred       12          192
  2789.  *  lightmagenta   13          208
  2790.  *  yellow           14          224
  2791.  *  white           15          240
  2792.  */
  2793.     static void
  2794. textattr(
  2795.     WORD wAttr)
  2796. {
  2797.     g_attrCurrent = wAttr;
  2798.  
  2799.     SetConsoleTextAttribute(g_hCurOut, wAttr);
  2800. }
  2801.  
  2802.  
  2803. /*
  2804.  * restore the default text attribute (whatever we started with)
  2805.  */
  2806.     static void
  2807. normvideo()
  2808. {
  2809.     textattr(g_attrDefault);
  2810. }
  2811.  
  2812.  
  2813. static WORD g_attrPreStandout = 0;
  2814.  
  2815. /*
  2816.  * Make the text standout, by brightening it
  2817.  */
  2818.     static void
  2819. standout()
  2820. {
  2821.     g_attrPreStandout = g_attrCurrent;
  2822.     textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
  2823. }
  2824.  
  2825.  
  2826. /*
  2827.  * Turn off standout mode
  2828.  */
  2829.     static void
  2830. standend()
  2831. {
  2832.     if (g_attrPreStandout)
  2833.     {
  2834.         textattr(g_attrPreStandout);
  2835.         g_attrPreStandout = 0;
  2836.     }
  2837. }
  2838.  
  2839.  
  2840. /*
  2841.  * visual bell: flash the screen
  2842.  */
  2843.     static void
  2844. visual_bell()
  2845. {
  2846.     COORD   coordOrigin = {0, 0};
  2847.     WORD    attrFlash = ~g_attrCurrent & 0xff;
  2848.     
  2849.     DWORD   dwDummy;
  2850.     LPWORD  oldattrs = (LPWORD) alloc(Rows * Columns * sizeof(WORD));
  2851.     
  2852.     ReadConsoleOutputAttribute(g_hCurOut, oldattrs, Rows * Columns,
  2853.                                coordOrigin, &dwDummy);
  2854.     FillConsoleOutputAttribute(g_hCurOut, attrFlash, Rows * Columns,
  2855.                                coordOrigin, &dwDummy);
  2856.  
  2857.     Sleep(15);        /* wait for 15 msec */
  2858.     WriteConsoleOutputAttribute(g_hCurOut, oldattrs, Rows * Columns,
  2859.                                  coordOrigin, &dwDummy);
  2860.     vim_free(oldattrs);
  2861. }
  2862.  
  2863.  
  2864. /*
  2865.  * Make the cursor visible or invisible
  2866.  */
  2867.     static void
  2868. cursor_visible(
  2869.     BOOL fVisible)
  2870. {
  2871.     CONSOLE_CURSOR_INFO cci;
  2872.  
  2873.     cci.bVisible = fVisible;
  2874.     /* make cursor big and visible (100 on Win95 makes it disappear)  */
  2875.     cci.dwSize = 99;           /* 100 percent cursor */
  2876.     SetConsoleCursorInfo(g_hCurOut, &cci);
  2877. }
  2878.  
  2879.  
  2880. /*
  2881.  * write `cchToWrite' characters in `pchBuf' to the screen
  2882.  */
  2883.     static BOOL
  2884. write_chars(
  2885.     LPCSTR pchBuf,
  2886.     DWORD  cchToWrite,
  2887.     DWORD* pcchWritten)
  2888. {
  2889.     BOOL f;
  2890.     COORD coord2 = g_coord;
  2891.  
  2892.     if (g_hCurOut == g_hSavOut)
  2893.     {
  2894.         CONSOLE_SCREEN_BUFFER_INFO csbi;
  2895.  
  2896.         GetConsoleScreenBufferInfo(g_hCurOut, &csbi);
  2897.  
  2898.         coord2.X += (SHORT) (csbi.srWindow.Left);
  2899.         coord2.Y += (SHORT) (csbi.srWindow.Bottom + 1 - Rows);
  2900.     }
  2901.  
  2902.     FillConsoleOutputAttribute(g_hCurOut, g_attrCurrent, cchToWrite,
  2903.                                coord2, pcchWritten);
  2904.     f = WriteConsoleOutputCharacter(g_hCurOut, pchBuf, cchToWrite,
  2905.                                     coord2, pcchWritten);
  2906.  
  2907.     g_coord.X += (SHORT) *pcchWritten;
  2908.  
  2909.     while (g_coord.X > g_srScrollRegion.Right)
  2910.     {
  2911.         g_coord.X -= (SHORT) Columns;
  2912.         if (g_coord.Y < g_srScrollRegion.Bottom)
  2913.             g_coord.Y++;
  2914.     }
  2915.  
  2916.     gotoxy(g_coord.X + 1, g_coord.Y + 1);
  2917.  
  2918.     return f;
  2919. }
  2920.  
  2921.  
  2922. /*
  2923.  * mch_write(): write the output buffer to the screen, translating ESC
  2924.  * sequences into calls to console output routines.
  2925.  */
  2926.     void
  2927. mch_write(
  2928.     char_u *s,
  2929.     int len)
  2930. {
  2931.     s[len] = NUL;
  2932.     
  2933.     if (! term_console)
  2934.     {
  2935.         write(1, s, (unsigned) len);
  2936.         return;
  2937.     }
  2938.  
  2939.     /* translate ESC | sequences into faked bios calls */
  2940.     while (len--)
  2941.     {
  2942.         /* optimization: use one single write_chars for runs of text,
  2943.          * rather than once per character  It ain't curses, but it helps. */
  2944.         
  2945.         DWORD  prefix = strcspn(s, "\n\r\b\a\033");
  2946.         
  2947.         if (p_wd)
  2948.         {
  2949.             WaitForChar(p_wd);
  2950.             if (prefix)
  2951.                 prefix = 1;
  2952.         }
  2953.  
  2954.         if (prefix)
  2955.         {
  2956.             DWORD nWritten;
  2957.             
  2958.             if (write_chars(s, prefix, &nWritten))
  2959.             {
  2960. #ifdef MCH_WRITE_DUMP
  2961.                 if (fdDump)
  2962.                 {
  2963.                     fputc('>', fdDump);
  2964.                     fwrite(s, sizeof(char_u), nWritten, fdDump);
  2965.                     fputs("<\n", fdDump);
  2966.                 }
  2967. #endif /* MCH_WRITE_DUMP */
  2968.                 len -= (nWritten - 1);
  2969.                 s += nWritten;
  2970.             }
  2971.         }
  2972.         else if (s[0] == '\n')
  2973.         {
  2974.             /* \n, newline: go to the beginning of the next line or scroll */
  2975.             if (g_coord.Y == g_srScrollRegion.Bottom)
  2976.             {
  2977.                 scroll(1);
  2978.                 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
  2979.             }
  2980.             else
  2981.             {
  2982.                 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
  2983.             }
  2984. #ifdef MCH_WRITE_DUMP
  2985.             if (fdDump)
  2986.                 fputs("\\n\n", fdDump);
  2987. #endif /* MCH_WRITE_DUMP */
  2988.             s++;
  2989.         }
  2990.         else if (s[0] == '\r')
  2991.         {
  2992.             /* \r, carriage return: go to beginning of line */
  2993.             gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
  2994. #ifdef MCH_WRITE_DUMP
  2995.             if (fdDump)
  2996.                 fputs("\\r\n", fdDump);
  2997. #endif /* MCH_WRITE_DUMP */
  2998.             s++;
  2999.         }
  3000.         else if (s[0] == '\b')
  3001.         {
  3002.             /* \b, backspace: move cursor one position left */
  3003.             if (g_coord.X > g_srScrollRegion.Left)
  3004.                 g_coord.X--;
  3005.             else if (g_coord.Y > g_srScrollRegion.Top)
  3006.             {
  3007.                 g_coord.X = g_srScrollRegion.Right;
  3008.                 g_coord.Y--;
  3009.             }
  3010.             gotoxy(g_coord.X + 1, g_coord.Y + 1);
  3011. #ifdef MCH_WRITE_DUMP
  3012.             if (fdDump)
  3013.                 fputs("\\b\n", fdDump);
  3014. #endif /* MCH_WRITE_DUMP */
  3015.             s++;
  3016.         }
  3017.         else if (s[0] == '\a')
  3018.         {
  3019.             /* \a, bell */
  3020.             MessageBeep(0xFFFFFFFF);
  3021. #ifdef MCH_WRITE_DUMP
  3022.             if (fdDump)
  3023.                 fputs("\\a\n", fdDump);
  3024. #endif /* MCH_WRITE_DUMP */
  3025.             s++;
  3026.         }
  3027.         else if (s[0] == ESC  &&  len >= 3-1  &&  s[1] == '|')
  3028.         {
  3029. #ifdef MCH_WRITE_DUMP
  3030.             char_u* old_s = s;
  3031. #endif /* MCH_WRITE_DUMP */
  3032.             char_u* p;
  3033.             int arg1 = 0, arg2 = 0;
  3034.             
  3035.             switch (s[2])
  3036.             {
  3037.             /* one or two numeric arguments, separated by ';' */
  3038.  
  3039.             case '0': case '1': case '2': case '3': case '4':
  3040.             case '5': case '6': case '7': case '8': case '9':
  3041.                 p = s + 2;
  3042.                 arg1 = getdigits(&p);        /* no check for length! */
  3043.                 if (p > s + len)
  3044.                     break;
  3045.                 
  3046.                 if (*p == ';')
  3047.                 {
  3048.                     ++p;
  3049.                     arg2 = getdigits(&p);    /* no check for length! */
  3050.                     if (p > s + len)
  3051.                         break;
  3052.                     
  3053.                     if (*p == 'H')
  3054.                         gotoxy(arg2, arg1);
  3055.                     else if (*p == 'r')
  3056.                         set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
  3057.                 }
  3058.                 else if (*p == 'A')
  3059.                 {
  3060.                     /* move cursor up arg1 lines in same column */
  3061.                     gotoxy(g_coord.X + 1,
  3062.                            max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
  3063.                 }
  3064.                 else if (*p == 'C')
  3065.                 {
  3066.                     /* move cursor right arg1 columns in same line */
  3067.                     gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
  3068.                            g_coord.Y + 1);
  3069.                 }
  3070.                 else if (*p == 'H')
  3071.                 {
  3072.                     gotoxy(1, arg1);
  3073.                 }
  3074.                 else if (*p == 'L')
  3075.                 {
  3076.                     insert_lines(arg1);
  3077.                 }
  3078.                 else if (*p == 'm')
  3079.                 {
  3080.                     if (arg1 == 0)
  3081.                         normvideo();
  3082.                     else
  3083.                         textattr((WORD) arg1);
  3084.                 }
  3085.                 else if (*p == 'M')
  3086.                 {
  3087.                     delete_lines(arg1);
  3088.                 }
  3089.                 
  3090.                 len -= p - s;
  3091.                 s = p + 1;
  3092.                 break;
  3093.                 
  3094.  
  3095.             /* Three-character escape sequences */
  3096.                 
  3097.             case 'A':
  3098.                 /* move cursor up one line in same column */
  3099.                 gotoxy(g_coord.X + 1,
  3100.                        max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
  3101.                 goto got3;
  3102.  
  3103.             case 'B':
  3104.                 visual_bell();
  3105.                 goto got3;
  3106.                 
  3107.             case 'C':
  3108.                 /* move cursor right one column in same line */
  3109.                 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
  3110.                        g_coord.Y + 1);
  3111.                 goto got3;
  3112.  
  3113.             case 'E':
  3114.                 termcap_mode_end();
  3115.                 goto got3;
  3116.                 
  3117.             case 'F':
  3118.                 standout();
  3119.                 goto got3;
  3120.  
  3121.             case 'f':
  3122.                 standend();
  3123.                 goto got3;
  3124.  
  3125.             case 'H':
  3126.                 gotoxy(1, 1);
  3127.                 goto got3;
  3128.                 
  3129.             case 'j':
  3130.                 clear_to_end_of_display();
  3131.                 goto got3;
  3132.                 
  3133.             case 'J':
  3134.                 clear_screen();
  3135.                 goto got3;
  3136.                 
  3137.             case 'K':
  3138.                 clear_to_end_of_line();
  3139.                 goto got3;
  3140.                 
  3141.             case 'L':
  3142.                 insert_lines(1);
  3143.                 goto got3;
  3144.                 
  3145.             case 'M':
  3146.                 delete_lines(1);
  3147.                 goto got3;
  3148.                 
  3149.             case 'S':
  3150.                 termcap_mode_start();
  3151.                 goto got3;
  3152.                 
  3153.             case 'V':
  3154.                 cursor_visible(TRUE);
  3155.                 goto got3;
  3156.                 
  3157.             case 'v':
  3158.                 cursor_visible(FALSE);
  3159.                 goto got3;
  3160.  
  3161.             got3:
  3162.                 s += 3;
  3163.                 len -= 2;
  3164.             }
  3165.  
  3166. #ifdef MCH_WRITE_DUMP
  3167.             if (fdDump)
  3168.             {
  3169.                 fputs("ESC | ", fdDump);
  3170.                 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
  3171.                 fputc('\n', fdDump);
  3172.             }
  3173. #endif /* MCH_WRITE_DUMP */
  3174.         }
  3175.         else
  3176.         {
  3177.             /* Write a single character */
  3178.             DWORD nWritten;
  3179.  
  3180.             if (write_chars(s, 1, &nWritten))
  3181.             {
  3182. #ifdef MCH_WRITE_DUMP
  3183.                 if (fdDump)
  3184.                 {
  3185.                     fputc('>', fdDump);
  3186.                     fwrite(s, sizeof(char_u), nWritten, fdDump);
  3187.                     fputs("<\n", fdDump);
  3188.                 }
  3189. #endif /* MCH_WRITE_DUMP */
  3190.  
  3191.                 len -= (nWritten - 1);
  3192.                 s += nWritten;
  3193.             }
  3194.         }
  3195.     }
  3196.  
  3197. #ifdef MCH_WRITE_DUMP
  3198.     if (fdDump)
  3199.         fflush(fdDump);
  3200. #endif /* MCH_WRITE_DUMP */
  3201. }
  3202.  
  3203.  
  3204. /*
  3205.  * Delay for half a second.
  3206.  */
  3207.     void
  3208. mch_delay(
  3209.     long    msec,
  3210.     int        ignoreinput)
  3211. {
  3212.     if (ignoreinput)
  3213.         Sleep((int)msec);
  3214.     else
  3215.         WaitForChar(msec);
  3216. }
  3217.  
  3218.  
  3219. #ifdef vim_remove
  3220. # undef vim_remove
  3221. #endif
  3222.  
  3223. /*
  3224.  * this version of remove is not scared by a readonly (backup) file
  3225.  */
  3226.     int
  3227. vim_remove(
  3228.     char_u *name)
  3229. {
  3230.     SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
  3231.     return DeleteFile(name) ? 0 : -1;
  3232. }
  3233.  
  3234.  
  3235. /*
  3236.  * check for an "interrupt signal": CTRL-break or CTRL-C
  3237.  */
  3238.     void
  3239. mch_breakcheck()
  3240. {
  3241.     if (g_fCtrlCPressed || g_fCBrkPressed)
  3242.     {
  3243.         g_fCtrlCPressed = g_fCBrkPressed = FALSE;
  3244.         got_int = TRUE;
  3245.     }
  3246. }
  3247.  
  3248.  
  3249. /*
  3250.  * How much memory is available?
  3251.  */
  3252.     long
  3253. mch_avail_mem(
  3254.     int special)
  3255. {
  3256.     return LONG_MAX;        /* virtual memory, eh? */
  3257. }
  3258.  
  3259.  
  3260. /*
  3261.  * return non-zero if a character is available
  3262.  */
  3263.     int
  3264. mch_char_avail()
  3265. {
  3266.     return WaitForChar(0L);
  3267. }
  3268.  
  3269.  
  3270. /*
  3271.  * set screen mode, always fails.
  3272.  */
  3273.     int
  3274. mch_screenmode(
  3275.     char_u *arg)
  3276. {
  3277.     EMSG("Screen mode setting not supported");
  3278.     return FAIL;
  3279. }
  3280.  
  3281.  
  3282. /*
  3283.  * win95rename works around a bug in rename (aka MoveFile) in
  3284.  * Windows 95: rename("foo.bar", "foo.bar~") will generate a
  3285.  * file whose shortfilename is "FOO.BAR" (its longfilename will
  3286.  * be correct: "foo.bar~").  Because a file can be accessed by
  3287.  * either its SFN or its LFN, "foo.bar" has effectively been
  3288.  * renamed to "foo.bar", which is not at all what was wanted.  This
  3289.  * seems to happen only when renaming files with three-character
  3290.  * extensions by appending a suffix that does not include ".".
  3291.  * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
  3292.  *
  3293.  * Like rename(), returns 0 upon success, non-zero upon failure.
  3294.  * Should probably set errno appropriately when errors occur.
  3295.  */
  3296.     int
  3297. win95rename(
  3298.     const char* pszOldFile,
  3299.     const char* pszNewFile)
  3300. {
  3301.     char szTempFile[_MAX_PATH];
  3302.     char szNewPath[_MAX_PATH];
  3303.     char* pszFilePart;
  3304.     HANDLE hf;
  3305.  
  3306. #undef rename
  3307.  
  3308.     /* get base path of new filename */
  3309.     if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0)
  3310.         return -1;
  3311.     else
  3312.         *pszFilePart = NUL;
  3313.     
  3314.     /* Get (and create) a unique temporary filename in directory of new file */
  3315.     if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
  3316.         return -2;
  3317.  
  3318.     /* blow the temp file away */
  3319.     if (! DeleteFile(szTempFile))
  3320.         return -3;
  3321.  
  3322.     /* rename old file to the temp file */
  3323.     if (! MoveFile(pszOldFile, szTempFile))
  3324.         return -4;
  3325.  
  3326.     /* now create an empty file called pszOldFile; this prevents
  3327.      * the operating system using pszOldFile as an alias (SFN)
  3328.      * if we're renaming within the same directory.  For example,
  3329.      * we're editing a file called filename.asc.txt by its SFN,
  3330.      * filena~1.txt.  If we rename filena~1.txt to filena~1.txt~
  3331.      * (i.e., we're making a backup while writing it), the SFN
  3332.      * for filena~1.txt~ will be filena~1.txt, by default, which
  3333.      * will cause all sorts of problems later in buf_write.  So, we
  3334.      * create an empty file called filena~1.txt and the system will have
  3335.      * to find some other SFN for filena~1.txt~, such as filena~2.txt
  3336.      */
  3337.     if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
  3338.                          FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
  3339.         return -5;
  3340.     if (! CloseHandle(hf))
  3341.         return -6;
  3342.     
  3343.     /* rename the temp file to the new file */
  3344.     if (! MoveFile(szTempFile, pszNewFile))
  3345.         return -7;
  3346.  
  3347.     /* Seems to be left around on Novell filesystems */
  3348.     DeleteFile(szTempFile);
  3349.     
  3350.     /* finally, remove the empty old file */
  3351.     if (! DeleteFile(pszOldFile))
  3352.         return -8;
  3353.  
  3354.     return 0;    /* success */
  3355. }
  3356.  
  3357. /*
  3358.  * Special version of getenv(): use $HOME when $VIM not defined.
  3359.  */
  3360.     char_u *
  3361. vim_getenv(
  3362.     char_u *var)
  3363. {
  3364.     char_u    *retval;
  3365.  
  3366.     retval = (char_u *)getenv((char *)var);
  3367.  
  3368.     if (retval == NULL && STRCMP(var, "VIM") == 0)
  3369.         retval = (char_u *)getenv("HOME");
  3370.  
  3371. #ifdef MCH_WRITE_DUMP
  3372.     if (fdDump)
  3373.     {
  3374.         fprintf(fdDump, "$%s = \"%s\"\n", var, retval);
  3375.         fflush(fdDump);
  3376.     }
  3377. #endif
  3378.  
  3379.     return retval;
  3380. }
  3381.  
  3382.  
  3383. /*
  3384.  * Get the default shell for the current hardware platform
  3385.  */
  3386.     char*
  3387. default_shell()
  3388. {
  3389.     char* psz = NULL;
  3390.  
  3391.     PlatformId();
  3392.  
  3393.     if (g_PlatformId == VER_PLATFORM_WIN32_NT)            /* Windows NT */
  3394.         psz = "cmd.exe";
  3395.     else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)  /* Windows 95 */
  3396.         psz = "command.com";
  3397.  
  3398.     return psz;
  3399. }
  3400.  
  3401.  
  3402. /*
  3403.  * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
  3404.  */
  3405.     void
  3406. DumpPutS(
  3407.     const char* psz)
  3408. {
  3409. # ifdef MCH_WRITE_DUMP
  3410.     if (fdDump)
  3411.     {
  3412.         fputs(psz, fdDump);
  3413.         if (psz[strlen(psz) - 1] != '\n')
  3414.             fputc('\n', fdDump);
  3415.         fflush(fdDump);
  3416.     }
  3417. # endif /* MCH_WRITE_DUMP */
  3418. }
  3419.