xref: /vim-8.2.3635/src/os_win32.c (revision 4eb1914e)
1 /* vi:set ts=8 sts=4 sw=4 noet:
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  * See README.txt for an overview of the Vim source code.
8  */
9 /*
10  * os_win32.c
11  *
12  * Used for both the console version and the Win32 GUI.  A lot of code is for
13  * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
14  *
15  * Win32 (Windows NT and Windows 95) system-dependent routines.
16  * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17  * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18  *
19  * George V. Reilly <[email protected]> wrote most of this.
20  * Roger Knobbe <[email protected]> did the initial port of Vim 3.0.
21  */
22 
23 #include "vim.h"
24 
25 #ifdef FEAT_MZSCHEME
26 # include "if_mzsch.h"
27 #endif
28 
29 #include <sys/types.h>
30 #include <signal.h>
31 #include <limits.h>
32 
33 // cproto fails on missing include files
34 #ifndef PROTO
35 # include <process.h>
36 # include <winternl.h>
37 #endif
38 
39 #undef chdir
40 #ifdef __GNUC__
41 # ifndef __MINGW32__
42 #  include <dirent.h>
43 # endif
44 #else
45 # include <direct.h>
46 #endif
47 
48 #ifndef PROTO
49 # if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
50 #  include <shellapi.h>
51 # endif
52 #endif
53 
54 #ifdef FEAT_JOB_CHANNEL
55 # include <tlhelp32.h>
56 #endif
57 
58 #ifdef __MINGW32__
59 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60 #  define FROM_LEFT_1ST_BUTTON_PRESSED    0x0001
61 # endif
62 # ifndef RIGHTMOST_BUTTON_PRESSED
63 #  define RIGHTMOST_BUTTON_PRESSED	  0x0002
64 # endif
65 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66 #  define FROM_LEFT_2ND_BUTTON_PRESSED    0x0004
67 # endif
68 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69 #  define FROM_LEFT_3RD_BUTTON_PRESSED    0x0008
70 # endif
71 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72 #  define FROM_LEFT_4TH_BUTTON_PRESSED    0x0010
73 # endif
74 
75 /*
76  * EventFlags
77  */
78 # ifndef MOUSE_MOVED
79 #  define MOUSE_MOVED   0x0001
80 # endif
81 # ifndef DOUBLE_CLICK
82 #  define DOUBLE_CLICK  0x0002
83 # endif
84 #endif
85 
86 // Record all output and all keyboard & mouse input
87 // #define MCH_WRITE_DUMP
88 
89 #ifdef MCH_WRITE_DUMP
90 FILE* fdDump = NULL;
91 #endif
92 
93 /*
94  * When generating prototypes for Win32 on Unix, these lines make the syntax
95  * errors disappear.  They do not need to be correct.
96  */
97 #ifdef PROTO
98 # define WINAPI
99 typedef char * LPCSTR;
100 typedef char * LPWSTR;
101 typedef int ACCESS_MASK;
102 typedef int BOOL;
103 typedef int COLORREF;
104 typedef int CONSOLE_CURSOR_INFO;
105 typedef int COORD;
106 typedef int DWORD;
107 typedef int HANDLE;
108 typedef int LPHANDLE;
109 typedef int HDC;
110 typedef int HFONT;
111 typedef int HICON;
112 typedef int HINSTANCE;
113 typedef int HWND;
114 typedef int INPUT_RECORD;
115 typedef int INT;
116 typedef int KEY_EVENT_RECORD;
117 typedef int LOGFONT;
118 typedef int LPBOOL;
119 typedef int LPCTSTR;
120 typedef int LPDWORD;
121 typedef int LPSTR;
122 typedef int LPTSTR;
123 typedef int LPVOID;
124 typedef int MOUSE_EVENT_RECORD;
125 typedef int PACL;
126 typedef int PDWORD;
127 typedef int PHANDLE;
128 typedef int PRINTDLG;
129 typedef int PSECURITY_DESCRIPTOR;
130 typedef int PSID;
131 typedef int SECURITY_INFORMATION;
132 typedef int SHORT;
133 typedef int SMALL_RECT;
134 typedef int TEXTMETRIC;
135 typedef int TOKEN_INFORMATION_CLASS;
136 typedef int TRUSTEE;
137 typedef int WORD;
138 typedef int WCHAR;
139 typedef void VOID;
140 typedef int BY_HANDLE_FILE_INFORMATION;
141 typedef int SE_OBJECT_TYPE;
142 typedef int PSNSECINFO;
143 typedef int PSNSECINFOW;
144 typedef int STARTUPINFO;
145 typedef int PROCESS_INFORMATION;
146 typedef int LPSECURITY_ATTRIBUTES;
147 # define __stdcall // empty
148 #endif
149 
150 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
151 // Win32 Console handles for input and output
152 static HANDLE g_hConIn  = INVALID_HANDLE_VALUE;
153 static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154 
155 // Win32 Screen buffer,coordinate,console I/O information
156 static SMALL_RECT g_srScrollRegion;
157 static COORD	  g_coord;  // 0-based, but external coords are 1-based
158 
159 // The attribute of the screen when the editor was started
160 static WORD  g_attrDefault = 7;  // lightgray text on black background
161 static WORD  g_attrCurrent;
162 
163 static int g_fCBrkPressed = FALSE;  // set by ctrl-break interrupt
164 static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165 static int g_fForceExit = FALSE;    // set when forcefully exiting
166 
167 static void scroll(unsigned cLines);
168 static void set_scroll_region(unsigned left, unsigned top,
169 			      unsigned right, unsigned bottom);
170 static void set_scroll_region_tb(unsigned top, unsigned bottom);
171 static void set_scroll_region_lr(unsigned left, unsigned right);
172 static void insert_lines(unsigned cLines);
173 static void delete_lines(unsigned cLines);
174 static void gotoxy(unsigned x, unsigned y);
175 static void standout(void);
176 static int s_cursor_visible = TRUE;
177 static int did_create_conin = FALSE;
178 #endif
179 #ifdef FEAT_GUI_MSWIN
180 static int s_dont_use_vimrun = TRUE;
181 static int need_vimrun_warning = FALSE;
182 static char *vimrun_path = "vimrun ";
183 #endif
184 
185 static int win32_getattrs(char_u *name);
186 static int win32_setattrs(char_u *name, int attrs);
187 static int win32_set_archive(char_u *name);
188 
189 static int conpty_working = 0;
190 static int conpty_type = 0;
191 static int conpty_stable = 0;
192 static int conpty_fix_type = 0;
193 static void vtp_flag_init();
194 
195 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
196 static int vtp_working = 0;
197 static void vtp_init();
198 static void vtp_exit();
199 static void vtp_sgr_bulk(int arg);
200 static void vtp_sgr_bulks(int argc, int *argv);
201 
202 static int wt_working = 0;
203 static void wt_init();
204 
205 static guicolor_T save_console_bg_rgb;
206 static guicolor_T save_console_fg_rgb;
207 static guicolor_T store_console_bg_rgb;
208 static guicolor_T store_console_fg_rgb;
209 
210 static int g_color_index_bg = 0;
211 static int g_color_index_fg = 7;
212 
213 # ifdef FEAT_TERMGUICOLORS
214 static int default_console_color_bg = 0x000000; // black
215 static int default_console_color_fg = 0xc0c0c0; // white
216 # endif
217 
218 # ifdef FEAT_TERMGUICOLORS
219 #  define USE_VTP		(vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
220 #  define USE_WT		(wt_working)
221 # else
222 #  define USE_VTP		0
223 #  define USE_WT		0
224 # endif
225 
226 static void set_console_color_rgb(void);
227 static void reset_console_color_rgb(void);
228 static void restore_console_color_rgb(void);
229 #endif
230 
231 // This flag is newly created from Windows 10
232 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233 # define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234 #endif
235 
236 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
237 static int suppress_winsize = 1;	// don't fiddle with console
238 #endif
239 
240 static char_u *exe_path = NULL;
241 
242 static BOOL win8_or_later = FALSE;
243 
244 # if defined(__GNUC__) && !defined(__MINGW32__)  && !defined(__CYGWIN__)
245 #  define UChar UnicodeChar
246 # else
247 #  define UChar uChar.UnicodeChar
248 # endif
249 
250 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
251 // Dynamic loading for portability
252 typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
253 {
254     ULONG cbSize;
255     COORD dwSize;
256     COORD dwCursorPosition;
257     WORD wAttributes;
258     SMALL_RECT srWindow;
259     COORD dwMaximumWindowSize;
260     WORD wPopupAttributes;
261     BOOL bFullscreenSupported;
262     COLORREF ColorTable[16];
263 } DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
264 typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
265 static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
266 typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
267 static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
268 static BOOL has_csbiex = FALSE;
269 #endif
270 
271 /*
272  * Get version number including build number
273  */
274 typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
275 #define MAKE_VER(major, minor, build) \
276     (((major) << 24) | ((minor) << 16) | (build))
277 
278     static DWORD
279 get_build_number(void)
280 {
281     OSVERSIONINFOW	osver = {sizeof(OSVERSIONINFOW)};
282     HMODULE		hNtdll;
283     PfnRtlGetVersion	pRtlGetVersion;
284     DWORD		ver = MAKE_VER(0, 0, 0);
285 
286     hNtdll = GetModuleHandle("ntdll.dll");
287     if (hNtdll != NULL)
288     {
289 	pRtlGetVersion =
290 	    (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
291 	pRtlGetVersion(&osver);
292 	ver = MAKE_VER(min(osver.dwMajorVersion, 255),
293 		       min(osver.dwMinorVersion, 255),
294 		       min(osver.dwBuildNumber, 32767));
295     }
296     return ver;
297 }
298 
299 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
300     static BOOL
301 is_ambiwidth_event(
302     INPUT_RECORD *ir)
303 {
304     return ir->EventType == KEY_EVENT
305 		&& ir->Event.KeyEvent.bKeyDown
306 		&& ir->Event.KeyEvent.wRepeatCount == 1
307 		&& ir->Event.KeyEvent.wVirtualKeyCode == 0x12
308 		&& ir->Event.KeyEvent.wVirtualScanCode == 0x38
309 		&& ir->Event.KeyEvent.UChar == 0
310 		&& ir->Event.KeyEvent.dwControlKeyState == 2;
311 }
312 
313     static void
314 make_ambiwidth_event(
315     INPUT_RECORD *down,
316     INPUT_RECORD *up)
317 {
318     down->Event.KeyEvent.wVirtualKeyCode = 0;
319     down->Event.KeyEvent.wVirtualScanCode = 0;
320     down->Event.KeyEvent.UChar = up->Event.KeyEvent.UChar;
321     down->Event.KeyEvent.dwControlKeyState = 0;
322 }
323 
324 /*
325  * Version of ReadConsoleInput() that works with IME.
326  * Works around problems on Windows 8.
327  */
328     static BOOL
329 read_console_input(
330     HANDLE	    hInput,
331     INPUT_RECORD    *lpBuffer,
332     DWORD	    nLength,
333     LPDWORD	    lpEvents)
334 {
335     enum
336     {
337 	IRSIZE = 10
338     };
339     static INPUT_RECORD s_irCache[IRSIZE];
340     static DWORD s_dwIndex = 0;
341     static DWORD s_dwMax = 0;
342     DWORD dwEvents;
343     int head;
344     int tail;
345     int i;
346     static INPUT_RECORD s_irPseudo;
347 
348     if (nLength == -2)
349 	return (s_dwMax > 0) ? TRUE : FALSE;
350 
351     if (!win8_or_later)
352     {
353 	if (nLength == -1)
354 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
355 	return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
356     }
357 
358     if (s_dwMax == 0)
359     {
360 	if (!USE_WT && nLength == -1)
361 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
362 	GetNumberOfConsoleInputEvents(hInput, &dwEvents);
363 	if (dwEvents == 0 && nLength == -1)
364 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
365 	ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
366 	s_dwIndex = 0;
367 	s_dwMax = dwEvents;
368 	if (dwEvents == 0)
369 	{
370 	    *lpEvents = 0;
371 	    return TRUE;
372 	}
373 
374 	for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
375 	    if (is_ambiwidth_event(&s_irCache[i]))
376 		make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
377 
378 	if (s_dwMax > 1)
379 	{
380 	    head = 0;
381 	    tail = s_dwMax - 1;
382 	    while (head != tail)
383 	    {
384 		if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
385 			&& s_irCache[head + 1].EventType
386 						  == WINDOW_BUFFER_SIZE_EVENT)
387 		{
388 		    // Remove duplicate event to avoid flicker.
389 		    for (i = head; i < tail; ++i)
390 			s_irCache[i] = s_irCache[i + 1];
391 		    --tail;
392 		    continue;
393 		}
394 		head++;
395 	    }
396 	    s_dwMax = tail + 1;
397 	}
398     }
399 
400     if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
401     {
402 	if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
403 	{
404 	    s_irPseudo = s_irCache[s_dwIndex];
405 	    s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
406 	    s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
407 	    *lpBuffer = s_irPseudo;
408 	    *lpEvents = 1;
409 	    return TRUE;
410 	}
411     }
412 
413     *lpBuffer = s_irCache[s_dwIndex];
414     if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
415 	s_dwMax = 0;
416     *lpEvents = 1;
417     return TRUE;
418 }
419 
420 /*
421  * Version of PeekConsoleInput() that works with IME.
422  */
423     static BOOL
424 peek_console_input(
425     HANDLE	    hInput,
426     INPUT_RECORD    *lpBuffer,
427     DWORD	    nLength UNUSED,
428     LPDWORD	    lpEvents)
429 {
430     return read_console_input(hInput, lpBuffer, -1, lpEvents);
431 }
432 
433 # ifdef FEAT_CLIENTSERVER
434     static DWORD
435 msg_wait_for_multiple_objects(
436     DWORD    nCount,
437     LPHANDLE pHandles,
438     BOOL     fWaitAll,
439     DWORD    dwMilliseconds,
440     DWORD    dwWakeMask)
441 {
442     if (read_console_input(NULL, NULL, -2, NULL))
443 	return WAIT_OBJECT_0;
444     return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
445 				     dwMilliseconds, dwWakeMask);
446 }
447 # endif
448 
449 # ifndef FEAT_CLIENTSERVER
450     static DWORD
451 wait_for_single_object(
452     HANDLE hHandle,
453     DWORD dwMilliseconds)
454 {
455     if (read_console_input(NULL, NULL, -2, NULL))
456 	return WAIT_OBJECT_0;
457     return WaitForSingleObject(hHandle, dwMilliseconds);
458 }
459 # endif
460 #endif
461 
462     static void
463 get_exe_name(void)
464 {
465     // Maximum length of $PATH is more than MAXPATHL.  8191 is often mentioned
466     // as the maximum length that works (plus a NUL byte).
467 #define MAX_ENV_PATH_LEN 8192
468     char	temp[MAX_ENV_PATH_LEN];
469     char_u	*p;
470 
471     if (exe_name == NULL)
472     {
473 	// store the name of the executable, may be used for $VIM
474 	GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
475 	if (*temp != NUL)
476 	    exe_name = FullName_save((char_u *)temp, FALSE);
477     }
478 
479     if (exe_path == NULL && exe_name != NULL)
480     {
481 	exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
482 	if (exe_path != NULL)
483 	{
484 	    // Append our starting directory to $PATH, so that when doing
485 	    // "!xxd" it's found in our starting directory.  Needed because
486 	    // SearchPath() also looks there.
487 	    p = mch_getenv("PATH");
488 	    if (p == NULL
489 		       || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
490 	    {
491 		if (p == NULL || *p == NUL)
492 		    temp[0] = NUL;
493 		else
494 		{
495 		    STRCPY(temp, p);
496 		    STRCAT(temp, ";");
497 		}
498 		STRCAT(temp, exe_path);
499 		vim_setenv((char_u *)"PATH", (char_u *)temp);
500 	    }
501 	}
502     }
503 }
504 
505 /*
506  * Unescape characters in "p" that appear in "escaped".
507  */
508     static void
509 unescape_shellxquote(char_u *p, char_u *escaped)
510 {
511     int	    l = (int)STRLEN(p);
512     int	    n;
513 
514     while (*p != NUL)
515     {
516 	if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
517 	    mch_memmove(p, p + 1, l--);
518 	n = (*mb_ptr2len)(p);
519 	p += n;
520 	l -= n;
521     }
522 }
523 
524 /*
525  * Load library "name".
526  */
527     HINSTANCE
528 vimLoadLib(char *name)
529 {
530     HINSTANCE	dll = NULL;
531 
532     // No need to load any library when registering OLE.
533     if (found_register_arg)
534 	return dll;
535 
536     // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
537     // vimLoadLib() recursively, which causes a stack overflow.
538     if (exe_path == NULL)
539 	get_exe_name();
540     if (exe_path != NULL)
541     {
542 	WCHAR old_dirw[MAXPATHL];
543 
544 	if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
545 	{
546 	    // Change directory to where the executable is, both to make
547 	    // sure we find a .dll there and to avoid looking for a .dll
548 	    // in the current directory.
549 	    SetCurrentDirectory((LPCSTR)exe_path);
550 	    dll = LoadLibrary(name);
551 	    SetCurrentDirectoryW(old_dirw);
552 	    return dll;
553 	}
554     }
555     return dll;
556 }
557 
558 #if defined(VIMDLL) || defined(PROTO)
559 /*
560  * Check if the current executable file is for the GUI subsystem.
561  */
562     int
563 mch_is_gui_executable(void)
564 {
565     PBYTE		pImage = (PBYTE)GetModuleHandle(NULL);
566     PIMAGE_DOS_HEADER	pDOS = (PIMAGE_DOS_HEADER)pImage;
567     PIMAGE_NT_HEADERS	pPE;
568 
569     if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
570 	return FALSE;
571     pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
572     if (pPE->Signature != IMAGE_NT_SIGNATURE)
573 	return FALSE;
574     if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
575 	return TRUE;
576     return FALSE;
577 }
578 #endif
579 
580 #if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
581 /*
582  * Get related information about 'funcname' which is imported by 'hInst'.
583  * If 'info' is 0, return the function address.
584  * If 'info' is 1, return the module name which the function is imported from.
585  */
586     static void *
587 get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
588 {
589     PBYTE			pImage = (PBYTE)hInst;
590     PIMAGE_DOS_HEADER		pDOS = (PIMAGE_DOS_HEADER)hInst;
591     PIMAGE_NT_HEADERS		pPE;
592     PIMAGE_IMPORT_DESCRIPTOR	pImpDesc;
593     PIMAGE_THUNK_DATA		pIAT;	    // Import Address Table
594     PIMAGE_THUNK_DATA		pINT;	    // Import Name Table
595     PIMAGE_IMPORT_BY_NAME	pImpName;
596 
597     if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 	return NULL;
599     pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600     if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 	return NULL;
602     pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 	    + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 							    .VirtualAddress);
605     for (; pImpDesc->FirstThunk; ++pImpDesc)
606     {
607 	if (!pImpDesc->OriginalFirstThunk)
608 	    continue;
609 	pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 	pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 	for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 	{
613 	    if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 		continue;
615 	    pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 					+ (UINT_PTR)(pINT->u1.AddressOfData));
617 	    if (strcmp((char *)pImpName->Name, funcname) == 0)
618 	    {
619 		switch (info)
620 		{
621 		    case 0:
622 			return (void *)pIAT->u1.Function;
623 		    case 1:
624 			return (void *)(pImage + pImpDesc->Name);
625 		    default:
626 			return NULL;
627 		}
628 	    }
629 	}
630     }
631     return NULL;
632 }
633 
634 /*
635  * Get the module handle which 'funcname' in 'hInst' is imported from.
636  */
637     HINSTANCE
638 find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
639 {
640     char    *modulename;
641 
642     modulename = (char *)get_imported_func_info(hInst, funcname, 1);
643     if (modulename != NULL)
644 	return GetModuleHandleA(modulename);
645     return NULL;
646 }
647 
648 /*
649  * Get the address of 'funcname' which is imported by 'hInst' DLL.
650  */
651     void *
652 get_dll_import_func(HINSTANCE hInst, const char *funcname)
653 {
654     return get_imported_func_info(hInst, funcname, 0);
655 }
656 #endif
657 
658 #if defined(DYNAMIC_GETTEXT) || defined(PROTO)
659 # ifndef GETTEXT_DLL
660 #  define GETTEXT_DLL "libintl.dll"
661 #  define GETTEXT_DLL_ALT1 "libintl-8.dll"
662 #  define GETTEXT_DLL_ALT2 "intl.dll"
663 # endif
664 // Dummy functions
665 static char *null_libintl_gettext(const char *);
666 static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
667 static char *null_libintl_textdomain(const char *);
668 static char *null_libintl_bindtextdomain(const char *, const char *);
669 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
670 static int null_libintl_wputenv(const wchar_t *);
671 
672 static HINSTANCE hLibintlDLL = NULL;
673 char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
674 char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
675 						= null_libintl_ngettext;
676 char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
677 char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
678 						= null_libintl_bindtextdomain;
679 char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
680 				       = null_libintl_bind_textdomain_codeset;
681 int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
682 
683     int
684 dyn_libintl_init(void)
685 {
686     int i;
687     static struct
688     {
689 	char	    *name;
690 	FARPROC	    *ptr;
691     } libintl_entry[] =
692     {
693 	{"gettext", (FARPROC*)&dyn_libintl_gettext},
694 	{"ngettext", (FARPROC*)&dyn_libintl_ngettext},
695 	{"textdomain", (FARPROC*)&dyn_libintl_textdomain},
696 	{"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
697 	{NULL, NULL}
698     };
699     HINSTANCE hmsvcrt;
700 
701     // No need to initialize twice.
702     if (hLibintlDLL != NULL)
703 	return 1;
704     // Load gettext library (libintl.dll and other names).
705     hLibintlDLL = vimLoadLib(GETTEXT_DLL);
706 # ifdef GETTEXT_DLL_ALT1
707     if (!hLibintlDLL)
708 	hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
709 # endif
710 # ifdef GETTEXT_DLL_ALT2
711     if (!hLibintlDLL)
712 	hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
713 # endif
714     if (!hLibintlDLL)
715     {
716 	if (p_verbose > 0)
717 	{
718 	    verbose_enter();
719 	    semsg(_(e_loadlib), GETTEXT_DLL);
720 	    verbose_leave();
721 	}
722 	return 0;
723     }
724     for (i = 0; libintl_entry[i].name != NULL
725 					 && libintl_entry[i].ptr != NULL; ++i)
726     {
727 	if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
728 					      libintl_entry[i].name)) == NULL)
729 	{
730 	    dyn_libintl_end();
731 	    if (p_verbose > 0)
732 	    {
733 		verbose_enter();
734 		semsg(_(e_loadfunc), libintl_entry[i].name);
735 		verbose_leave();
736 	    }
737 	    return 0;
738 	}
739     }
740 
741     // The bind_textdomain_codeset() function is optional.
742     dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
743 						   "bind_textdomain_codeset");
744     if (dyn_libintl_bind_textdomain_codeset == NULL)
745 	dyn_libintl_bind_textdomain_codeset =
746 					 null_libintl_bind_textdomain_codeset;
747 
748     // _wputenv() function for the libintl.dll is optional.
749     hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
750     if (hmsvcrt != NULL)
751 	dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
752     if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 	dyn_libintl_wputenv = null_libintl_wputenv;
754 
755     return 1;
756 }
757 
758     void
759 dyn_libintl_end(void)
760 {
761     if (hLibintlDLL)
762 	FreeLibrary(hLibintlDLL);
763     hLibintlDLL			= NULL;
764     dyn_libintl_gettext		= null_libintl_gettext;
765     dyn_libintl_ngettext	= null_libintl_ngettext;
766     dyn_libintl_textdomain	= null_libintl_textdomain;
767     dyn_libintl_bindtextdomain	= null_libintl_bindtextdomain;
768     dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
769     dyn_libintl_wputenv		= null_libintl_wputenv;
770 }
771 
772     static char *
773 null_libintl_gettext(const char *msgid)
774 {
775     return (char*)msgid;
776 }
777 
778     static char *
779 null_libintl_ngettext(
780 	const char *msgid,
781 	const char *msgid_plural,
782 	unsigned long n)
783 {
784     return (char *)(n == 1 ? msgid : msgid_plural);
785 }
786 
787     static char *
788 null_libintl_bindtextdomain(
789 	const char *domainname UNUSED,
790 	const char *dirname UNUSED)
791 {
792     return NULL;
793 }
794 
795     static char *
796 null_libintl_bind_textdomain_codeset(
797 	const char *domainname UNUSED,
798 	const char *codeset UNUSED)
799 {
800     return NULL;
801 }
802 
803     static char *
804 null_libintl_textdomain(const char *domainname UNUSED)
805 {
806     return NULL;
807 }
808 
809     static int
810 null_libintl_wputenv(const wchar_t *envstring UNUSED)
811 {
812     return 0;
813 }
814 
815 #endif // DYNAMIC_GETTEXT
816 
817 // This symbol is not defined in older versions of the SDK or Visual C++
818 
819 #ifndef VER_PLATFORM_WIN32_WINDOWS
820 # define VER_PLATFORM_WIN32_WINDOWS 1
821 #endif
822 
823 #ifdef HAVE_ACL
824 # ifndef PROTO
825 #  include <aclapi.h>
826 # endif
827 # ifndef PROTECTED_DACL_SECURITY_INFORMATION
828 #  define PROTECTED_DACL_SECURITY_INFORMATION	0x80000000L
829 # endif
830 #endif
831 
832 #ifdef HAVE_ACL
833 /*
834  * Enables or disables the specified privilege.
835  */
836     static BOOL
837 win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838 {
839     BOOL		bResult;
840     LUID		luid;
841     HANDLE		hToken;
842     TOKEN_PRIVILEGES	tokenPrivileges;
843 
844     if (!OpenProcessToken(GetCurrentProcess(),
845 		TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 	return FALSE;
847 
848     if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849     {
850 	CloseHandle(hToken);
851 	return FALSE;
852     }
853 
854     tokenPrivileges.PrivilegeCount	     = 1;
855     tokenPrivileges.Privileges[0].Luid       = luid;
856     tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 						    SE_PRIVILEGE_ENABLED : 0;
858 
859     bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 	    sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861 
862     CloseHandle(hToken);
863 
864     return bResult && GetLastError() == ERROR_SUCCESS;
865 }
866 #endif
867 
868 #ifdef _MSC_VER
869 // Suppress the deprecation warning for using GetVersionEx().
870 // It is needed for implementing "windowsversion()".
871 # pragma warning(push)
872 # pragma warning(disable: 4996)
873 #endif
874 /*
875  * Set "win8_or_later" and fill in "windowsVersion" if possible.
876  */
877     void
878 PlatformId(void)
879 {
880     static int done = FALSE;
881 
882     if (!done)
883     {
884 	OSVERSIONINFO ovi;
885 
886 	ovi.dwOSVersionInfoSize = sizeof(ovi);
887 	GetVersionEx(&ovi);
888 
889 #ifdef FEAT_EVAL
890 	vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 		(int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
892 #endif
893 	if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 		|| ovi.dwMajorVersion > 6)
895 	    win8_or_later = TRUE;
896 
897 #ifdef HAVE_ACL
898 	// Enable privilege for getting or setting SACLs.
899 	win32_enable_privilege(SE_SECURITY_NAME, TRUE);
900 #endif
901 	done = TRUE;
902     }
903 }
904 #ifdef _MSC_VER
905 # pragma warning(pop)
906 #endif
907 
908 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
909 
910 # define SHIFT  (SHIFT_PRESSED)
911 # define CTRL   (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
912 # define ALT    (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED)
913 # define ALT_GR (RIGHT_ALT_PRESSED  | LEFT_CTRL_PRESSED)
914 
915 
916 // When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
917 // We map function keys to their ANSI terminal equivalents, as produced
918 // by ANSI.SYS, for compatibility with the MS-DOS version of Vim.  Any
919 // ANSI key with a value >= '\300' is nonstandard, but provided anyway
920 // so that the user can have access to all SHIFT-, CTRL-, and ALT-
921 // combinations of function/arrow/etc keys.
922 
923 static const struct
924 {
925     WORD    wVirtKey;
926     BOOL    fAnsiKey;
927     int	    chAlone;
928     int	    chShift;
929     int	    chCtrl;
930     int	    chAlt;
931 } VirtKeyMap[] =
932 {
933 //    Key	ANSI	alone	shift	ctrl	    alt
934     { VK_ESCAPE,FALSE,	ESC,	ESC,	ESC,	    ESC,    },
935 
936     { VK_F1,	TRUE,	';',	'T',	'^',	    'h', },
937     { VK_F2,	TRUE,	'<',	'U',	'_',	    'i', },
938     { VK_F3,	TRUE,	'=',	'V',	'`',	    'j', },
939     { VK_F4,	TRUE,	'>',	'W',	'a',	    'k', },
940     { VK_F5,	TRUE,	'?',	'X',	'b',	    'l', },
941     { VK_F6,	TRUE,	'@',	'Y',	'c',	    'm', },
942     { VK_F7,	TRUE,	'A',	'Z',	'd',	    'n', },
943     { VK_F8,	TRUE,	'B',	'[',	'e',	    'o', },
944     { VK_F9,	TRUE,	'C',	'\\',	'f',	    'p', },
945     { VK_F10,	TRUE,	'D',	']',	'g',	    'q', },
946     { VK_F11,	TRUE,	'\205',	'\207',	'\211',	    '\213', },
947     { VK_F12,	TRUE,	'\206',	'\210',	'\212',	    '\214', },
948 
949     { VK_HOME,	TRUE,	'G',	'\302',	'w',	    '\303', },
950     { VK_UP,	TRUE,	'H',	'\304',	'\305',	    '\306', },
951     { VK_PRIOR,	TRUE,	'I',	'\307',	'\204',	    '\310', }, // PgUp
952     { VK_LEFT,	TRUE,	'K',	'\311',	's',	    '\312', },
953     { VK_RIGHT,	TRUE,	'M',	'\313',	't',	    '\314', },
954     { VK_END,	TRUE,	'O',	'\315',	'u',	    '\316', },
955     { VK_DOWN,	TRUE,	'P',	'\317',	'\320',	    '\321', },
956     { VK_NEXT,	TRUE,	'Q',	'\322',	'v',	    '\323', }, // PgDn
957     { VK_INSERT,TRUE,	'R',	'\324',	'\325',	    '\326', },
958     { VK_DELETE,TRUE,	'S',	'\327',	'\330',	    '\331', },
959     { VK_BACK,	TRUE,	'x',	'y',	'z',	    '{', }, // Backspace
960 
961     { VK_SNAPSHOT,TRUE,	0,	0,	0,	    'r', }, // PrtScrn
962 
963 # if 0
964     // Most people don't have F13-F20, but what the hell...
965     { VK_F13,	TRUE,	'\332',	'\333',	'\334',	    '\335', },
966     { VK_F14,	TRUE,	'\336',	'\337',	'\340',	    '\341', },
967     { VK_F15,	TRUE,	'\342',	'\343',	'\344',	    '\345', },
968     { VK_F16,	TRUE,	'\346',	'\347',	'\350',	    '\351', },
969     { VK_F17,	TRUE,	'\352',	'\353',	'\354',	    '\355', },
970     { VK_F18,	TRUE,	'\356',	'\357',	'\360',	    '\361', },
971     { VK_F19,	TRUE,	'\362',	'\363',	'\364',	    '\365', },
972     { VK_F20,	TRUE,	'\366',	'\367',	'\370',	    '\371', },
973 # endif
974     { VK_ADD,	TRUE,   'N',    'N',    'N',	'N',	}, // keyp '+'
975     { VK_SUBTRACT, TRUE,'J',	'J',    'J',	'J',	}, // keyp '-'
976  // { VK_DIVIDE,   TRUE,'N',	'N',    'N',	'N',	}, // keyp '/'
977     { VK_MULTIPLY, TRUE,'7',	'7',    '7',	'7',	}, // keyp '*'
978 
979     { VK_NUMPAD0,TRUE,  '\332',	'\333',	'\334',	    '\335', },
980     { VK_NUMPAD1,TRUE,  '\336',	'\337',	'\340',	    '\341', },
981     { VK_NUMPAD2,TRUE,  '\342',	'\343',	'\344',	    '\345', },
982     { VK_NUMPAD3,TRUE,  '\346',	'\347',	'\350',	    '\351', },
983     { VK_NUMPAD4,TRUE,  '\352',	'\353',	'\354',	    '\355', },
984     { VK_NUMPAD5,TRUE,  '\356',	'\357',	'\360',	    '\361', },
985     { VK_NUMPAD6,TRUE,  '\362',	'\363',	'\364',	    '\365', },
986     { VK_NUMPAD7,TRUE,  '\366',	'\367',	'\370',	    '\371', },
987     { VK_NUMPAD8,TRUE,  '\372',	'\373',	'\374',	    '\375', },
988     // Sorry, out of number space! <negri>
989     { VK_NUMPAD9,TRUE,  '\376',	'\377',	'|',	    '}', },
990 };
991 
992 
993 /*
994  * The return code indicates key code size.
995  */
996     static int
997 win32_kbd_patch_key(
998     KEY_EVENT_RECORD *pker)
999 {
1000     UINT uMods = pker->dwControlKeyState;
1001     static int s_iIsDead = 0;
1002     static WORD awAnsiCode[2];
1003     static BYTE abKeystate[256];
1004 
1005 
1006     if (s_iIsDead == 2)
1007     {
1008 	pker->UChar = (WCHAR) awAnsiCode[1];
1009 	s_iIsDead = 0;
1010 	return 1;
1011     }
1012 
1013     if (pker->UChar != 0)
1014 	return 1;
1015 
1016     CLEAR_FIELD(abKeystate);
1017 
1018     // Clear any pending dead keys
1019     ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
1020 
1021     if (uMods & SHIFT_PRESSED)
1022 	abKeystate[VK_SHIFT] = 0x80;
1023     if (uMods & CAPSLOCK_ON)
1024 	abKeystate[VK_CAPITAL] = 1;
1025 
1026     if ((uMods & ALT_GR) == ALT_GR)
1027     {
1028 	abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1029 	    abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1030     }
1031 
1032     s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1033 			abKeystate, awAnsiCode, 2, 0);
1034 
1035     if (s_iIsDead > 0)
1036 	pker->UChar = (WCHAR) awAnsiCode[0];
1037 
1038     return s_iIsDead;
1039 }
1040 
1041 static BOOL g_fJustGotFocus = FALSE;
1042 
1043 /*
1044  * Decode a KEY_EVENT into one or two keystrokes
1045  */
1046     static BOOL
1047 decode_key_event(
1048     KEY_EVENT_RECORD	*pker,
1049     WCHAR		*pch,
1050     WCHAR		*pch2,
1051     int			*pmodifiers,
1052     BOOL		fDoPost UNUSED)
1053 {
1054     int i;
1055     const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1056 
1057     *pch = *pch2 = NUL;
1058     g_fJustGotFocus = FALSE;
1059 
1060     // ignore key up events
1061     if (!pker->bKeyDown)
1062 	return FALSE;
1063 
1064     // ignore some keystrokes
1065     switch (pker->wVirtualKeyCode)
1066     {
1067     // modifiers
1068     case VK_SHIFT:
1069     case VK_CONTROL:
1070     case VK_MENU:   // Alt key
1071 	return FALSE;
1072 
1073     default:
1074 	break;
1075     }
1076 
1077     // special cases
1078     if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
1079     {
1080 	// Ctrl-6 is Ctrl-^
1081 	if (pker->wVirtualKeyCode == '6')
1082 	{
1083 	    *pch = Ctrl_HAT;
1084 	    return TRUE;
1085 	}
1086 	// Ctrl-2 is Ctrl-@
1087 	else if (pker->wVirtualKeyCode == '2')
1088 	{
1089 	    *pch = NUL;
1090 	    return TRUE;
1091 	}
1092 	// Ctrl-- is Ctrl-_
1093 	else if (pker->wVirtualKeyCode == 0xBD)
1094 	{
1095 	    *pch = Ctrl__;
1096 	    return TRUE;
1097 	}
1098     }
1099 
1100     // Shift-TAB
1101     if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1102     {
1103 	*pch = K_NUL;
1104 	*pch2 = '\017';
1105 	return TRUE;
1106     }
1107 
1108     for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]);  --i >= 0;  )
1109     {
1110 	if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1111 	{
1112 	    if (nModifs == 0)
1113 		*pch = VirtKeyMap[i].chAlone;
1114 	    else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1115 		*pch = VirtKeyMap[i].chShift;
1116 	    else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1117 		*pch = VirtKeyMap[i].chCtrl;
1118 	    else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1119 		*pch = VirtKeyMap[i].chAlt;
1120 
1121 	    if (*pch != 0)
1122 	    {
1123 		if (VirtKeyMap[i].fAnsiKey)
1124 		{
1125 		    *pch2 = *pch;
1126 		    *pch = K_NUL;
1127 		}
1128 
1129 		return TRUE;
1130 	    }
1131 	}
1132     }
1133 
1134     i = win32_kbd_patch_key(pker);
1135 
1136     if (i < 0)
1137 	*pch = NUL;
1138     else
1139     {
1140 	*pch = (i > 0) ? pker->UChar : NUL;
1141 
1142 	if (pmodifiers != NULL)
1143 	{
1144 	    // Pass on the ALT key as a modifier, but only when not combined
1145 	    // with CTRL (which is ALTGR).
1146 	    if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1147 		*pmodifiers |= MOD_MASK_ALT;
1148 
1149 	    // Pass on SHIFT only for special keys, because we don't know when
1150 	    // it's already included with the character.
1151 	    if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1152 		*pmodifiers |= MOD_MASK_SHIFT;
1153 
1154 	    // Pass on CTRL only for non-special keys, because we don't know
1155 	    // when it's already included with the character.  And not when
1156 	    // combined with ALT (which is ALTGR).
1157 	    if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1158 					       && *pch >= 0x20 && *pch < 0x80)
1159 		*pmodifiers |= MOD_MASK_CTRL;
1160 	}
1161     }
1162 
1163     return (*pch != NUL);
1164 }
1165 
1166 #endif // FEAT_GUI_MSWIN
1167 
1168 
1169 /*
1170  * For the GUI the mouse handling is in gui_w32.c.
1171  */
1172 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
1173     void
1174 mch_setmouse(int on UNUSED)
1175 {
1176 }
1177 #else
1178 static int g_fMouseAvail = FALSE;   // mouse present
1179 static int g_fMouseActive = FALSE;  // mouse enabled
1180 static int g_nMouseClick = -1;	    // mouse status
1181 static int g_xMouse;		    // mouse x coordinate
1182 static int g_yMouse;		    // mouse y coordinate
1183 
1184 /*
1185  * Enable or disable mouse input
1186  */
1187     void
1188 mch_setmouse(int on)
1189 {
1190     DWORD cmodein;
1191 
1192 # ifdef VIMDLL
1193     if (gui.in_use)
1194 	return;
1195 # endif
1196     if (!g_fMouseAvail)
1197 	return;
1198 
1199     g_fMouseActive = on;
1200     GetConsoleMode(g_hConIn, &cmodein);
1201 
1202     if (g_fMouseActive)
1203 	cmodein |= ENABLE_MOUSE_INPUT;
1204     else
1205 	cmodein &= ~ENABLE_MOUSE_INPUT;
1206 
1207     SetConsoleMode(g_hConIn, cmodein);
1208 }
1209 
1210 
1211 # if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1212 /*
1213  * Called when 'balloonevalterm' changed.
1214  */
1215     void
1216 mch_bevalterm_changed(void)
1217 {
1218     mch_setmouse(g_fMouseActive);
1219 }
1220 # endif
1221 
1222 /*
1223  * Decode a MOUSE_EVENT.  If it's a valid event, return MOUSE_LEFT,
1224  * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1225  * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1226  * or a MOUSE_LEFT, _MIDDLE, or _RIGHT.  We encode the button type,
1227  * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1228  * and we return the mouse position in g_xMouse and g_yMouse.
1229  *
1230  * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1231  * MOUSE_DRAGs and one MOUSE_RELEASE.  MOUSE_RELEASE will be followed only
1232  * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1233  *
1234  * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1235  * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1236  *
1237  * Windows will send us MOUSE_MOVED notifications whenever the mouse
1238  * moves, even if it stays within the same character cell.  We ignore
1239  * all MOUSE_MOVED messages if the position hasn't really changed, and
1240  * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1241  * we're only interested in MOUSE_DRAG).
1242  *
1243  * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1244  * 2-button mouses by pressing the left & right buttons simultaneously.
1245  * In practice, it's almost impossible to click both at the same time,
1246  * so we need to delay a little.  Also, we tend not to get MOUSE_RELEASE
1247  * in such cases, if the user is clicking quickly.
1248  */
1249     static BOOL
1250 decode_mouse_event(
1251     MOUSE_EVENT_RECORD *pmer)
1252 {
1253     static int s_nOldButton = -1;
1254     static int s_nOldMouseClick = -1;
1255     static int s_xOldMouse = -1;
1256     static int s_yOldMouse = -1;
1257     static linenr_T s_old_topline = 0;
1258 # ifdef FEAT_DIFF
1259     static int s_old_topfill = 0;
1260 # endif
1261     static int s_cClicks = 1;
1262     static BOOL s_fReleased = TRUE;
1263     static DWORD s_dwLastClickTime = 0;
1264     static BOOL s_fNextIsMiddle = FALSE;
1265 
1266     static DWORD cButtons = 0;	// number of buttons supported
1267 
1268     const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1269     const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1270     const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1271     const DWORD LEFT_RIGHT = LEFT | RIGHT;
1272 
1273     int nButton;
1274 
1275     if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1276 	cButtons = 2;
1277 
1278     if (!g_fMouseAvail || !g_fMouseActive)
1279     {
1280 	g_nMouseClick = -1;
1281 	return FALSE;
1282     }
1283 
1284     // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
1285     if (g_fJustGotFocus)
1286     {
1287 	g_fJustGotFocus = FALSE;
1288 	return FALSE;
1289     }
1290 
1291     // unprocessed mouse click?
1292     if (g_nMouseClick != -1)
1293 	return TRUE;
1294 
1295     nButton = -1;
1296     g_xMouse = pmer->dwMousePosition.X;
1297     g_yMouse = pmer->dwMousePosition.Y;
1298 
1299     if (pmer->dwEventFlags == MOUSE_MOVED)
1300     {
1301 	// Ignore MOUSE_MOVED events if (x, y) hasn't changed.	(We get these
1302 	// events even when the mouse moves only within a char cell.)
1303 	if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1304 	    return FALSE;
1305     }
1306 
1307     // If no buttons are pressed...
1308     if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1309     {
1310 	nButton = MOUSE_RELEASE;
1311 
1312 	// If the last thing returned was MOUSE_RELEASE, ignore this
1313 	if (s_fReleased)
1314 	{
1315 # ifdef FEAT_BEVAL_TERM
1316 	    // do return mouse move events when we want them
1317 	    if (p_bevalterm)
1318 		nButton = MOUSE_DRAG;
1319 	    else
1320 # endif
1321 		return FALSE;
1322 	}
1323 
1324 	s_fReleased = TRUE;
1325     }
1326     else    // one or more buttons pressed
1327     {
1328 	// on a 2-button mouse, hold down left and right buttons
1329 	// simultaneously to get MIDDLE.
1330 
1331 	if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1332 	{
1333 	    DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1334 
1335 	    // if either left or right button only is pressed, see if the
1336 	    // next mouse event has both of them pressed
1337 	    if (dwLR == LEFT || dwLR == RIGHT)
1338 	    {
1339 		for (;;)
1340 		{
1341 		    // wait a short time for next input event
1342 		    if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1343 							     != WAIT_OBJECT_0)
1344 			break;
1345 		    else
1346 		    {
1347 			DWORD cRecords = 0;
1348 			INPUT_RECORD ir;
1349 			MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1350 
1351 			peek_console_input(g_hConIn, &ir, 1, &cRecords);
1352 
1353 			if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1354 				|| !(pmer2->dwButtonState & LEFT_RIGHT))
1355 			    break;
1356 			else
1357 			{
1358 			    if (pmer2->dwEventFlags != MOUSE_MOVED)
1359 			    {
1360 				read_console_input(g_hConIn, &ir, 1, &cRecords);
1361 
1362 				return decode_mouse_event(pmer2);
1363 			    }
1364 			    else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1365 				     s_yOldMouse == pmer2->dwMousePosition.Y)
1366 			    {
1367 				// throw away spurious mouse move
1368 				read_console_input(g_hConIn, &ir, 1, &cRecords);
1369 
1370 				// are there any more mouse events in queue?
1371 				peek_console_input(g_hConIn, &ir, 1, &cRecords);
1372 
1373 				if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1374 				    break;
1375 			    }
1376 			    else
1377 				break;
1378 			}
1379 		    }
1380 		}
1381 	    }
1382 	}
1383 
1384 	if (s_fNextIsMiddle)
1385 	{
1386 	    nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1387 		? MOUSE_DRAG : MOUSE_MIDDLE;
1388 	    s_fNextIsMiddle = FALSE;
1389 	}
1390 	else if (cButtons == 2	&&
1391 	    ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1392 	{
1393 	    nButton = MOUSE_MIDDLE;
1394 
1395 	    if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1396 	    {
1397 		s_fNextIsMiddle = TRUE;
1398 		nButton = MOUSE_RELEASE;
1399 	    }
1400 	}
1401 	else if ((pmer->dwButtonState & LEFT) == LEFT)
1402 	    nButton = MOUSE_LEFT;
1403 	else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1404 	    nButton = MOUSE_MIDDLE;
1405 	else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1406 	    nButton = MOUSE_RIGHT;
1407 
1408 	if (! s_fReleased && ! s_fNextIsMiddle
1409 		&& nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1410 	    return FALSE;
1411 
1412 	s_fReleased = s_fNextIsMiddle;
1413     }
1414 
1415     if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1416     {
1417 	// button pressed or released, without mouse moving
1418 	if (nButton != -1 && nButton != MOUSE_RELEASE)
1419 	{
1420 	    DWORD dwCurrentTime = GetTickCount();
1421 
1422 	    if (s_xOldMouse != g_xMouse
1423 		    || s_yOldMouse != g_yMouse
1424 		    || s_nOldButton != nButton
1425 		    || s_old_topline != curwin->w_topline
1426 # ifdef FEAT_DIFF
1427 		    || s_old_topfill != curwin->w_topfill
1428 # endif
1429 		    || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1430 	    {
1431 		s_cClicks = 1;
1432 	    }
1433 	    else if (++s_cClicks > 4)
1434 	    {
1435 		s_cClicks = 1;
1436 	    }
1437 
1438 	    s_dwLastClickTime = dwCurrentTime;
1439 	}
1440     }
1441     else if (pmer->dwEventFlags == MOUSE_MOVED)
1442     {
1443 	if (nButton != -1 && nButton != MOUSE_RELEASE)
1444 	    nButton = MOUSE_DRAG;
1445 
1446 	s_cClicks = 1;
1447     }
1448 
1449     if (nButton == -1)
1450 	return FALSE;
1451 
1452     if (nButton != MOUSE_RELEASE)
1453 	s_nOldButton = nButton;
1454 
1455     g_nMouseClick = nButton;
1456 
1457     if (pmer->dwControlKeyState & SHIFT_PRESSED)
1458 	g_nMouseClick |= MOUSE_SHIFT;
1459     if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1460 	g_nMouseClick |= MOUSE_CTRL;
1461     if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED))
1462 	g_nMouseClick |= MOUSE_ALT;
1463 
1464     if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1465 	SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1466 
1467     // only pass on interesting (i.e., different) mouse events
1468     if (s_xOldMouse == g_xMouse
1469 	    && s_yOldMouse == g_yMouse
1470 	    && s_nOldMouseClick == g_nMouseClick)
1471     {
1472 	g_nMouseClick = -1;
1473 	return FALSE;
1474     }
1475 
1476     s_xOldMouse = g_xMouse;
1477     s_yOldMouse = g_yMouse;
1478     s_old_topline = curwin->w_topline;
1479 # ifdef FEAT_DIFF
1480     s_old_topfill = curwin->w_topfill;
1481 # endif
1482     s_nOldMouseClick = g_nMouseClick;
1483 
1484     return TRUE;
1485 }
1486 
1487 #endif // FEAT_GUI_MSWIN
1488 
1489 
1490 #ifdef MCH_CURSOR_SHAPE
1491 /*
1492  * Set the shape of the cursor.
1493  * 'thickness' can be from 1 (thin) to 99 (block)
1494  */
1495     static void
1496 mch_set_cursor_shape(int thickness)
1497 {
1498     CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1499     ConsoleCursorInfo.dwSize = thickness;
1500     ConsoleCursorInfo.bVisible = s_cursor_visible;
1501 
1502     SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1503     if (s_cursor_visible)
1504 	SetConsoleCursorPosition(g_hConOut, g_coord);
1505 }
1506 
1507     void
1508 mch_update_cursor(void)
1509 {
1510     int		idx;
1511     int		thickness;
1512 
1513 # ifdef VIMDLL
1514     if (gui.in_use)
1515 	return;
1516 # endif
1517 
1518     /*
1519      * How the cursor is drawn depends on the current mode.
1520      */
1521     idx = get_shape_idx(FALSE);
1522 
1523     if (shape_table[idx].shape == SHAPE_BLOCK)
1524 	thickness = 99;	// 100 doesn't work on W95
1525     else
1526 	thickness = shape_table[idx].percentage;
1527     mch_set_cursor_shape(thickness);
1528 }
1529 #endif
1530 
1531 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1532 /*
1533  * Handle FOCUS_EVENT.
1534  */
1535     static void
1536 handle_focus_event(INPUT_RECORD ir)
1537 {
1538     g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1539     ui_focus_change((int)g_fJustGotFocus);
1540 }
1541 
1542 static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1543 
1544 /*
1545  * Wait until console input from keyboard or mouse is available,
1546  * or the time is up.
1547  * When "ignore_input" is TRUE even wait when input is available.
1548  * Return TRUE if something is available FALSE if not.
1549  */
1550     static int
1551 WaitForChar(long msec, int ignore_input)
1552 {
1553     DWORD	    dwNow = 0, dwEndTime = 0;
1554     INPUT_RECORD    ir;
1555     DWORD	    cRecords;
1556     WCHAR	    ch, ch2;
1557 # ifdef FEAT_TIMERS
1558     int		    tb_change_cnt = typebuf.tb_change_cnt;
1559 # endif
1560 
1561     if (msec > 0)
1562 	// Wait until the specified time has elapsed.
1563 	dwEndTime = GetTickCount() + msec;
1564     else if (msec < 0)
1565 	// Wait forever.
1566 	dwEndTime = INFINITE;
1567 
1568     // We need to loop until the end of the time period, because
1569     // we might get multiple unusable mouse events in that time.
1570     for (;;)
1571     {
1572 	// Only process messages when waiting.
1573 	if (msec != 0)
1574 	{
1575 # ifdef MESSAGE_QUEUE
1576 	    parse_queued_messages();
1577 # endif
1578 # ifdef FEAT_MZSCHEME
1579 	    mzvim_check_threads();
1580 # endif
1581 # ifdef FEAT_CLIENTSERVER
1582 	    serverProcessPendingMessages();
1583 # endif
1584 	}
1585 
1586 	if (g_nMouseClick != -1
1587 # ifdef FEAT_CLIENTSERVER
1588 		|| (!ignore_input && input_available())
1589 # endif
1590 	   )
1591 	    return TRUE;
1592 
1593 	if (msec > 0)
1594 	{
1595 	    // If the specified wait time has passed, return.  Beware that
1596 	    // GetTickCount() may wrap around (overflow).
1597 	    dwNow = GetTickCount();
1598 	    if ((int)(dwNow - dwEndTime) >= 0)
1599 		break;
1600 	}
1601 	if (msec != 0)
1602 	{
1603 	    DWORD dwWaitTime = dwEndTime - dwNow;
1604 
1605 	    // Don't wait for more than 11 msec to avoid dropping characters,
1606 	    // check channel while waiting for input and handle a callback from
1607 	    // 'balloonexpr'.
1608 	    if (dwWaitTime > 11)
1609 		dwWaitTime = 11;
1610 
1611 # ifdef FEAT_MZSCHEME
1612 	    if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
1613 		dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
1614 # endif
1615 # ifdef FEAT_TIMERS
1616 	    // When waiting very briefly don't trigger timers.
1617 	    if (dwWaitTime > 10)
1618 	    {
1619 		long	due_time;
1620 
1621 		// Trigger timers and then get the time in msec until the next
1622 		// one is due.  Wait up to that time.
1623 		due_time = check_due_timer();
1624 		if (typebuf.tb_change_cnt != tb_change_cnt)
1625 		{
1626 		    // timer may have used feedkeys().
1627 		    return FALSE;
1628 		}
1629 		if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1630 		    dwWaitTime = due_time;
1631 	    }
1632 # endif
1633 	    if (
1634 # ifdef FEAT_CLIENTSERVER
1635 		    // Wait for either an event on the console input or a
1636 		    // message in the client-server window.
1637 		    msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1638 				  dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
1639 # else
1640 		    wait_for_single_object(g_hConIn, dwWaitTime)
1641 							      != WAIT_OBJECT_0
1642 # endif
1643 		    )
1644 		continue;
1645 	}
1646 
1647 	cRecords = 0;
1648 	peek_console_input(g_hConIn, &ir, 1, &cRecords);
1649 
1650 # ifdef FEAT_MBYTE_IME
1651 	// May have to redraw if the cursor ends up in the wrong place.
1652 	// Only when not peeking.
1653 	if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
1654 	{
1655 	    CONSOLE_SCREEN_BUFFER_INFO csbi;
1656 
1657 	    if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1658 	    {
1659 		if (csbi.dwCursorPosition.Y != msg_row)
1660 		{
1661 		    // The screen is now messed up, must redraw the command
1662 		    // line and later all the windows.
1663 		    redraw_all_later(CLEAR);
1664 		    compute_cmdrow();
1665 		    redrawcmd();
1666 		}
1667 	    }
1668 	}
1669 # endif
1670 
1671 	if (cRecords > 0)
1672 	{
1673 	    if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1674 	    {
1675 # ifdef FEAT_MBYTE_IME
1676 		// Windows IME sends two '\n's with only one 'ENTER'.  First:
1677 		// wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
1678 		if (ir.Event.KeyEvent.UChar == 0
1679 			&& ir.Event.KeyEvent.wVirtualKeyCode == 13)
1680 		{
1681 		    read_console_input(g_hConIn, &ir, 1, &cRecords);
1682 		    continue;
1683 		}
1684 # endif
1685 		if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1686 								 NULL, FALSE))
1687 		    return TRUE;
1688 	    }
1689 
1690 	    read_console_input(g_hConIn, &ir, 1, &cRecords);
1691 
1692 	    if (ir.EventType == FOCUS_EVENT)
1693 		handle_focus_event(ir);
1694 	    else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1695 	    {
1696 		COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1697 
1698 		// Only call shell_resized() when the size actually changed to
1699 		// avoid the screen is cleared.
1700 		if (dwSize.X != Columns || dwSize.Y != Rows)
1701 		{
1702 		    CONSOLE_SCREEN_BUFFER_INFO csbi;
1703 		    GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1704 		    dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1705 		    dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1706 		    if (dwSize.X != Columns || dwSize.Y != Rows)
1707 		    {
1708 			ResizeConBuf(g_hConOut, dwSize);
1709 			shell_resized();
1710 		    }
1711 		}
1712 	    }
1713 	    else if (ir.EventType == MOUSE_EVENT
1714 		    && decode_mouse_event(&ir.Event.MouseEvent))
1715 		return TRUE;
1716 	}
1717 	else if (msec == 0)
1718 	    break;
1719     }
1720 
1721 # ifdef FEAT_CLIENTSERVER
1722     // Something might have been received while we were waiting.
1723     if (input_available())
1724 	return TRUE;
1725 # endif
1726 
1727     return FALSE;
1728 }
1729 
1730 /*
1731  * return non-zero if a character is available
1732  */
1733     int
1734 mch_char_avail(void)
1735 {
1736 # ifdef VIMDLL
1737     if (gui.in_use)
1738 	return TRUE;
1739 # endif
1740     return WaitForChar(0L, FALSE);
1741 }
1742 
1743 # if defined(FEAT_TERMINAL) || defined(PROTO)
1744 /*
1745  * Check for any pending input or messages.
1746  */
1747     int
1748 mch_check_messages(void)
1749 {
1750 #  ifdef VIMDLL
1751     if (gui.in_use)
1752 	return TRUE;
1753 #  endif
1754     return WaitForChar(0L, TRUE);
1755 }
1756 # endif
1757 
1758 /*
1759  * Create the console input.  Used when reading stdin doesn't work.
1760  */
1761     static void
1762 create_conin(void)
1763 {
1764     g_hConIn =	CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1765 			FILE_SHARE_READ|FILE_SHARE_WRITE,
1766 			(LPSECURITY_ATTRIBUTES) NULL,
1767 			OPEN_EXISTING, 0, (HANDLE)NULL);
1768     did_create_conin = TRUE;
1769 }
1770 
1771 /*
1772  * Get a keystroke or a mouse event, use a blocking wait.
1773  */
1774     static WCHAR
1775 tgetch(int *pmodifiers, WCHAR *pch2)
1776 {
1777     WCHAR ch;
1778 
1779     for (;;)
1780     {
1781 	INPUT_RECORD ir;
1782 	DWORD cRecords = 0;
1783 
1784 # ifdef FEAT_CLIENTSERVER
1785 	(void)WaitForChar(-1L, FALSE);
1786 	if (input_available())
1787 	    return 0;
1788 	if (g_nMouseClick != -1)
1789 	    return 0;
1790 # endif
1791 	if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
1792 	{
1793 	    if (did_create_conin)
1794 		read_error_exit();
1795 	    create_conin();
1796 	    continue;
1797 	}
1798 
1799 	if (ir.EventType == KEY_EVENT)
1800 	{
1801 	    if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1802 							    pmodifiers, TRUE))
1803 		return ch;
1804 	}
1805 	else if (ir.EventType == FOCUS_EVENT)
1806 	    handle_focus_event(ir);
1807 	else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1808 	    shell_resized();
1809 	else if (ir.EventType == MOUSE_EVENT)
1810 	{
1811 	    if (decode_mouse_event(&ir.Event.MouseEvent))
1812 		return 0;
1813 	}
1814     }
1815 }
1816 #endif // !FEAT_GUI_MSWIN
1817 
1818 
1819 /*
1820  * mch_inchar(): low-level input function.
1821  * Get one or more characters from the keyboard or the mouse.
1822  * If time == 0, do not wait for characters.
1823  * If time == n, wait a short time for characters.
1824  * If time == -1, wait forever for characters.
1825  * Returns the number of characters read into buf.
1826  */
1827     int
1828 mch_inchar(
1829     char_u	*buf UNUSED,
1830     int		maxlen UNUSED,
1831     long	time UNUSED,
1832     int		tb_change_cnt UNUSED)
1833 {
1834 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1835 
1836     int		len;
1837     int		c;
1838 # ifdef VIMDLL
1839 // Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1840 #  define TYPEAHEADSPACE    6
1841 # else
1842 #  define TYPEAHEADSPACE    0
1843 # endif
1844 # define TYPEAHEADLEN	    (20 + TYPEAHEADSPACE)
1845     static char_u   typeahead[TYPEAHEADLEN];	// previously typed bytes.
1846     static int	    typeaheadlen = 0;
1847 
1848 # ifdef VIMDLL
1849     if (gui.in_use)
1850 	return 0;
1851 # endif
1852 
1853     // First use any typeahead that was kept because "buf" was too small.
1854     if (typeaheadlen > 0)
1855 	goto theend;
1856 
1857     if (time >= 0)
1858     {
1859 	if (!WaitForChar(time, FALSE))     // no character available
1860 	    return 0;
1861     }
1862     else    // time == -1, wait forever
1863     {
1864 	mch_set_winsize_now();	// Allow winsize changes from now on
1865 
1866 	/*
1867 	 * If there is no character available within 2 seconds (default)
1868 	 * write the autoscript file to disk.  Or cause the CursorHold event
1869 	 * to be triggered.
1870 	 */
1871 	if (!WaitForChar(p_ut, FALSE))
1872 	{
1873 	    if (trigger_cursorhold() && maxlen >= 3)
1874 	    {
1875 		buf[0] = K_SPECIAL;
1876 		buf[1] = KS_EXTRA;
1877 		buf[2] = (int)KE_CURSORHOLD;
1878 		return 3;
1879 	    }
1880 	    before_blocking();
1881 	}
1882     }
1883 
1884     /*
1885      * Try to read as many characters as there are, until the buffer is full.
1886      */
1887 
1888     // we will get at least one key. Get more if they are available.
1889     g_fCBrkPressed = FALSE;
1890 
1891 # ifdef MCH_WRITE_DUMP
1892     if (fdDump)
1893 	fputc('[', fdDump);
1894 # endif
1895 
1896     // Keep looping until there is something in the typeahead buffer and more
1897     // to get and still room in the buffer (up to two bytes for a char and
1898     // three bytes for a modifier).
1899     while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
1900 		         && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
1901     {
1902 	if (typebuf_changed(tb_change_cnt))
1903 	{
1904 	    // "buf" may be invalid now if a client put something in the
1905 	    // typeahead buffer and "buf" is in the typeahead buffer.
1906 	    typeaheadlen = 0;
1907 	    break;
1908 	}
1909 	if (g_nMouseClick != -1)
1910 	{
1911 # ifdef MCH_WRITE_DUMP
1912 	    if (fdDump)
1913 		fprintf(fdDump, "{%02x @ %d, %d}",
1914 			g_nMouseClick, g_xMouse, g_yMouse);
1915 # endif
1916 	    typeahead[typeaheadlen++] = ESC + 128;
1917 	    typeahead[typeaheadlen++] = 'M';
1918 	    typeahead[typeaheadlen++] = g_nMouseClick;
1919 	    typeahead[typeaheadlen++] = g_xMouse + '!';
1920 	    typeahead[typeaheadlen++] = g_yMouse + '!';
1921 	    g_nMouseClick = -1;
1922 	}
1923 	else
1924 	{
1925 	    WCHAR	ch2 = NUL;
1926 	    int		modifiers = 0;
1927 
1928 	    c = tgetch(&modifiers, &ch2);
1929 
1930 	    if (typebuf_changed(tb_change_cnt))
1931 	    {
1932 		// "buf" may be invalid now if a client put something in the
1933 		// typeahead buffer and "buf" is in the typeahead buffer.
1934 		typeaheadlen = 0;
1935 		break;
1936 	    }
1937 
1938 	    if (c == Ctrl_C && ctrl_c_interrupts)
1939 	    {
1940 # if defined(FEAT_CLIENTSERVER)
1941 		trash_input_buf();
1942 # endif
1943 		got_int = TRUE;
1944 	    }
1945 
1946 	    if (g_nMouseClick == -1)
1947 	    {
1948 		int	n = 1;
1949 
1950 		if (ch2 == NUL)
1951 		{
1952 		    int	    i, j;
1953 		    char_u  *p;
1954 		    WCHAR   ch[2];
1955 
1956 		    ch[0] = c;
1957 		    if (c >= 0xD800 && c <= 0xDBFF)	// High surrogate
1958 		    {
1959 			ch[1] = tgetch(&modifiers, &ch2);
1960 			n++;
1961 		    }
1962 		    p = utf16_to_enc(ch, &n);
1963 		    if (p != NULL)
1964 		    {
1965 			for (i = 0, j = 0; i < n; i++)
1966 			{
1967 			    typeahead[typeaheadlen + j++] = p[i];
1968 # ifdef VIMDLL
1969 			    if (p[i] == CSI)
1970 			    {
1971 				typeahead[typeaheadlen + j++] = KS_EXTRA;
1972 				typeahead[typeaheadlen + j++] = KE_CSI;
1973 			    }
1974 # endif
1975 			}
1976 			n = j;
1977 			vim_free(p);
1978 		    }
1979 		}
1980 		else
1981 		{
1982 		    typeahead[typeaheadlen] = c;
1983 # ifdef VIMDLL
1984 		    if (c == CSI)
1985 		    {
1986 			typeahead[typeaheadlen + 1] = KS_EXTRA;
1987 			typeahead[typeaheadlen + 2] = KE_CSI;
1988 			n = 3;
1989 		    }
1990 # endif
1991 		}
1992 		if (ch2 != NUL)
1993 		{
1994 		    if (c == K_NUL)
1995 		    {
1996 			switch (ch2)
1997 			{
1998 			case (WCHAR)'\324': // SHIFT+Insert
1999 			case (WCHAR)'\325': // CTRL+Insert
2000 			case (WCHAR)'\327': // SHIFT+Delete
2001 			case (WCHAR)'\330': // CTRL+Delete
2002 			    typeahead[typeaheadlen + n] = (char_u)ch2;
2003 			    n++;
2004 			    break;
2005 
2006 			default:
2007 			    typeahead[typeaheadlen + n] = 3;
2008 			    typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2009 			    n += 2;
2010 			    break;
2011 			}
2012 		    }
2013 		    else
2014 		    {
2015 			typeahead[typeaheadlen + n] = 3;
2016 			typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2017 			n += 2;
2018 		    }
2019 		}
2020 
2021 		// Use the ALT key to set the 8th bit of the character
2022 		// when it's one byte, the 8th bit isn't set yet and not
2023 		// using a double-byte encoding (would become a lead
2024 		// byte).
2025 		if ((modifiers & MOD_MASK_ALT)
2026 			&& n == 1
2027 			&& (typeahead[typeaheadlen] & 0x80) == 0
2028 			&& !enc_dbcs
2029 		   )
2030 		{
2031 		    n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2032 						    typeahead + typeaheadlen);
2033 		    modifiers &= ~MOD_MASK_ALT;
2034 		}
2035 
2036 		if (modifiers != 0)
2037 		{
2038 		    // Prepend modifiers to the character.
2039 		    mch_memmove(typeahead + typeaheadlen + 3,
2040 						 typeahead + typeaheadlen, n);
2041 		    typeahead[typeaheadlen++] = K_SPECIAL;
2042 		    typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2043 		    typeahead[typeaheadlen++] =  modifiers;
2044 		}
2045 
2046 		typeaheadlen += n;
2047 
2048 # ifdef MCH_WRITE_DUMP
2049 		if (fdDump)
2050 		    fputc(c, fdDump);
2051 # endif
2052 	    }
2053 	}
2054     }
2055 
2056 # ifdef MCH_WRITE_DUMP
2057     if (fdDump)
2058     {
2059 	fputs("]\n", fdDump);
2060 	fflush(fdDump);
2061     }
2062 # endif
2063 
2064 theend:
2065     // Move typeahead to "buf", as much as fits.
2066     len = 0;
2067     while (len < maxlen && typeaheadlen > 0)
2068     {
2069 	buf[len++] = typeahead[0];
2070 	mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2071     }
2072 #  ifdef FEAT_JOB_CHANNEL
2073     if (len > 0)
2074     {
2075 	buf[len] = NUL;
2076 	ch_log(NULL, "raw key input: \"%s\"", buf);
2077     }
2078 #  endif
2079     return len;
2080 
2081 #else // FEAT_GUI_MSWIN
2082     return 0;
2083 #endif // FEAT_GUI_MSWIN
2084 }
2085 
2086 #ifndef PROTO
2087 # ifndef __MINGW32__
2088 #  include <shellapi.h>	// required for FindExecutable()
2089 # endif
2090 #endif
2091 
2092 /*
2093  * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
2094  * When returning TRUE and "path" is not NULL save the path and set "*path" to
2095  * the allocated memory.
2096  * TODO: Should somehow check if it's really executable.
2097  */
2098     static int
2099 executable_file(char *name, char_u **path)
2100 {
2101     if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
2102     {
2103 	if (path != NULL)
2104 	    *path = FullName_save((char_u *)name, FALSE);
2105 	return TRUE;
2106     }
2107     return FALSE;
2108 }
2109 
2110 /*
2111  * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2112  * If "use_path" is FALSE: Return TRUE if "name" exists.
2113  * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2114  * When returning TRUE and "path" is not NULL save the path and set "*path" to
2115  * the allocated memory.
2116  */
2117     static int
2118 executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2119 {
2120     // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2121     // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2122     // UTF-8.
2123     char_u	buf[_MAX_PATH * 3];
2124     size_t	len = STRLEN(name);
2125     size_t	tmplen;
2126     char_u	*p, *e, *e2;
2127     char_u	*pathbuf = NULL;
2128     char_u	*pathext = NULL;
2129     char_u	*pathextbuf = NULL;
2130     int		noext = FALSE;
2131     int		retval = FALSE;
2132 
2133     if (len >= sizeof(buf))	// safety check
2134 	return FALSE;
2135 
2136     // Using the name directly when a Unix-shell like 'shell'.
2137     if (strstr((char *)gettail(p_sh), "sh") != NULL)
2138 	noext = TRUE;
2139 
2140     if (use_pathext)
2141     {
2142 	pathext = mch_getenv("PATHEXT");
2143 	if (pathext == NULL)
2144 	    pathext = (char_u *)".com;.exe;.bat;.cmd";
2145 
2146 	if (noext == FALSE)
2147 	{
2148 	    /*
2149 	     * Loop over all extensions in $PATHEXT.
2150 	     * Check "name" ends with extension.
2151 	     */
2152 	    p = pathext;
2153 	    while (*p)
2154 	    {
2155 		if (p[0] == ';'
2156 			    || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2157 		{
2158 		    // Skip empty or single ".".
2159 		    ++p;
2160 		    continue;
2161 		}
2162 		e = vim_strchr(p, ';');
2163 		if (e == NULL)
2164 		    e = p + STRLEN(p);
2165 		tmplen = e - p;
2166 
2167 		if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2168 		{
2169 		    noext = TRUE;
2170 		    break;
2171 		}
2172 
2173 		p = e;
2174 	    }
2175 	}
2176     }
2177 
2178     // Prepend single "." to pathext, it's means no extension added.
2179     if (pathext == NULL)
2180 	pathext = (char_u *)".";
2181     else if (noext == TRUE)
2182     {
2183 	if (pathextbuf == NULL)
2184 	    pathextbuf = alloc(STRLEN(pathext) + 3);
2185 	if (pathextbuf == NULL)
2186 	{
2187 	    retval = FALSE;
2188 	    goto theend;
2189 	}
2190 	STRCPY(pathextbuf, ".;");
2191 	STRCAT(pathextbuf, pathext);
2192 	pathext = pathextbuf;
2193     }
2194 
2195     // Use $PATH when "use_path" is TRUE and "name" is basename.
2196     if (use_path && gettail((char_u *)name) == (char_u *)name)
2197     {
2198 	p = mch_getenv("PATH");
2199 	if (p != NULL)
2200 	{
2201 	    pathbuf = alloc(STRLEN(p) + 3);
2202 	    if (pathbuf == NULL)
2203 	    {
2204 		retval = FALSE;
2205 		goto theend;
2206 	    }
2207 	    STRCPY(pathbuf, ".;");
2208 	    STRCAT(pathbuf, p);
2209 	}
2210     }
2211 
2212     /*
2213      * Walk through all entries in $PATH to check if "name" exists there and
2214      * is an executable file.
2215      */
2216     p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2217     while (*p)
2218     {
2219 	if (*p == ';') // Skip empty entry
2220 	{
2221 	    ++p;
2222 	    continue;
2223 	}
2224 	e = vim_strchr(p, ';');
2225 	if (e == NULL)
2226 	    e = p + STRLEN(p);
2227 
2228 	if (e - p + len + 2 > sizeof(buf))
2229 	{
2230 	    retval = FALSE;
2231 	    goto theend;
2232 	}
2233 	// A single "." that means current dir.
2234 	if (e - p == 1 && *p == '.')
2235 	    STRCPY(buf, name);
2236 	else
2237 	{
2238 	    vim_strncpy(buf, p, e - p);
2239 	    add_pathsep(buf);
2240 	    STRCAT(buf, name);
2241 	}
2242 	tmplen = STRLEN(buf);
2243 
2244 	/*
2245 	 * Loop over all extensions in $PATHEXT.
2246 	 * Check "name" with extension added.
2247 	 */
2248 	p = pathext;
2249 	while (*p)
2250 	{
2251 	    if (*p == ';')
2252 	    {
2253 		// Skip empty entry
2254 		++p;
2255 		continue;
2256 	    }
2257 	    e2 = vim_strchr(p, (int)';');
2258 	    if (e2 == NULL)
2259 		e2 = p + STRLEN(p);
2260 
2261 	    if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2262 	    {
2263 		// Not a single "." that means no extension is added.
2264 		if (e2 - p + tmplen + 1 > sizeof(buf))
2265 		{
2266 		    retval = FALSE;
2267 		    goto theend;
2268 		}
2269 		vim_strncpy(buf + tmplen, p, e2 - p);
2270 	    }
2271 	    if (executable_file((char *)buf, path))
2272 	    {
2273 		retval = TRUE;
2274 		goto theend;
2275 	    }
2276 
2277 	    p = e2;
2278 	}
2279 
2280 	p = e;
2281     }
2282 
2283 theend:
2284     free(pathextbuf);
2285     free(pathbuf);
2286     return retval;
2287 }
2288 
2289 #if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2290 	(defined(_MSC_VER) && _MSC_VER >= 1400)
2291 /*
2292  * Bad parameter handler.
2293  *
2294  * Certain MS CRT functions will intentionally crash when passed invalid
2295  * parameters to highlight possible security holes.  Setting this function as
2296  * the bad parameter handler will prevent the crash.
2297  *
2298  * In debug builds the parameters contain CRT information that might help track
2299  * down the source of a problem, but in non-debug builds the arguments are all
2300  * NULL/0.  Debug builds will also produce assert dialogs from the CRT, it is
2301  * worth allowing these to make debugging of issues easier.
2302  */
2303     static void
2304 bad_param_handler(const wchar_t *expression,
2305     const wchar_t *function,
2306     const wchar_t *file,
2307     unsigned int line,
2308     uintptr_t pReserved)
2309 {
2310 }
2311 
2312 # define SET_INVALID_PARAM_HANDLER \
2313 	((void)_set_invalid_parameter_handler(bad_param_handler))
2314 #else
2315 # define SET_INVALID_PARAM_HANDLER
2316 #endif
2317 
2318 #ifdef FEAT_GUI_MSWIN
2319 
2320 /*
2321  * GUI version of mch_init().
2322  */
2323     static void
2324 mch_init_g(void)
2325 {
2326 # ifndef __MINGW32__
2327     extern int _fmode;
2328 # endif
2329 
2330     // Silently handle invalid parameters to CRT functions
2331     SET_INVALID_PARAM_HANDLER;
2332 
2333     // Let critical errors result in a failure, not in a dialog box.  Required
2334     // for the timestamp test to work on removed floppies.
2335     SetErrorMode(SEM_FAILCRITICALERRORS);
2336 
2337     _fmode = O_BINARY;		// we do our own CR-LF translation
2338 
2339     // Specify window size.  Is there a place to get the default from?
2340     Rows = 25;
2341     Columns = 80;
2342 
2343     // Look for 'vimrun'
2344     {
2345 	char_u vimrun_location[_MAX_PATH + 4];
2346 
2347 	// First try in same directory as gvim.exe
2348 	STRCPY(vimrun_location, exe_name);
2349 	STRCPY(gettail(vimrun_location), "vimrun.exe");
2350 	if (mch_getperm(vimrun_location) >= 0)
2351 	{
2352 	    if (*skiptowhite(vimrun_location) != NUL)
2353 	    {
2354 		// Enclose path with white space in double quotes.
2355 		mch_memmove(vimrun_location + 1, vimrun_location,
2356 						 STRLEN(vimrun_location) + 1);
2357 		*vimrun_location = '"';
2358 		STRCPY(gettail(vimrun_location), "vimrun\" ");
2359 	    }
2360 	    else
2361 		STRCPY(gettail(vimrun_location), "vimrun ");
2362 
2363 	    vimrun_path = (char *)vim_strsave(vimrun_location);
2364 	    s_dont_use_vimrun = FALSE;
2365 	}
2366 	else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
2367 	    s_dont_use_vimrun = FALSE;
2368 
2369 	// Don't give the warning for a missing vimrun.exe right now, but only
2370 	// when vimrun was supposed to be used.  Don't bother people that do
2371 	// not need vimrun.exe.
2372 	if (s_dont_use_vimrun)
2373 	    need_vimrun_warning = TRUE;
2374     }
2375 
2376     /*
2377      * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2378      * Otherwise the default "findstr /n" is used.
2379      */
2380     if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
2381 	set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2382 
2383 # ifdef FEAT_CLIPBOARD
2384     win_clip_init();
2385 # endif
2386 
2387     vtp_flag_init();
2388 }
2389 
2390 
2391 #endif // FEAT_GUI_MSWIN
2392 
2393 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
2394 
2395 # define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2396 # define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2397 
2398 /*
2399  * ClearConsoleBuffer()
2400  * Description:
2401  *  Clears the entire contents of the console screen buffer, using the
2402  *  specified attribute.
2403  * Returns:
2404  *  TRUE on success
2405  */
2406     static BOOL
2407 ClearConsoleBuffer(WORD wAttribute)
2408 {
2409     CONSOLE_SCREEN_BUFFER_INFO csbi;
2410     COORD coord;
2411     DWORD NumCells, dummy;
2412 
2413     if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2414 	return FALSE;
2415 
2416     NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2417     coord.X = 0;
2418     coord.Y = 0;
2419     if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2420 	    coord, &dummy))
2421 	return FALSE;
2422     if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2423 	    coord, &dummy))
2424 	return FALSE;
2425 
2426     return TRUE;
2427 }
2428 
2429 /*
2430  * FitConsoleWindow()
2431  * Description:
2432  *  Checks if the console window will fit within given buffer dimensions.
2433  *  Also, if requested, will shrink the window to fit.
2434  * Returns:
2435  *  TRUE on success
2436  */
2437     static BOOL
2438 FitConsoleWindow(
2439     COORD dwBufferSize,
2440     BOOL WantAdjust)
2441 {
2442     CONSOLE_SCREEN_BUFFER_INFO csbi;
2443     COORD dwWindowSize;
2444     BOOL NeedAdjust = FALSE;
2445 
2446     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2447     {
2448 	/*
2449 	 * A buffer resize will fail if the current console window does
2450 	 * not lie completely within that buffer.  To avoid this, we might
2451 	 * have to move and possibly shrink the window.
2452 	 */
2453 	if (csbi.srWindow.Right >= dwBufferSize.X)
2454 	{
2455 	    dwWindowSize.X = SRWIDTH(csbi.srWindow);
2456 	    if (dwWindowSize.X > dwBufferSize.X)
2457 		dwWindowSize.X = dwBufferSize.X;
2458 	    csbi.srWindow.Right = dwBufferSize.X - 1;
2459 	    csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2460 	    NeedAdjust = TRUE;
2461 	}
2462 	if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2463 	{
2464 	    dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2465 	    if (dwWindowSize.Y > dwBufferSize.Y)
2466 		dwWindowSize.Y = dwBufferSize.Y;
2467 	    csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2468 	    csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2469 	    NeedAdjust = TRUE;
2470 	}
2471 	if (NeedAdjust && WantAdjust)
2472 	{
2473 	    if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2474 		return FALSE;
2475 	}
2476 	return TRUE;
2477     }
2478 
2479     return FALSE;
2480 }
2481 
2482 typedef struct ConsoleBufferStruct
2483 {
2484     BOOL			IsValid;
2485     CONSOLE_SCREEN_BUFFER_INFO	Info;
2486     PCHAR_INFO			Buffer;
2487     COORD			BufferSize;
2488     PSMALL_RECT			Regions;
2489     int				NumRegions;
2490 } ConsoleBuffer;
2491 
2492 /*
2493  * SaveConsoleBuffer()
2494  * Description:
2495  *  Saves important information about the console buffer, including the
2496  *  actual buffer contents.  The saved information is suitable for later
2497  *  restoration by RestoreConsoleBuffer().
2498  * Returns:
2499  *  TRUE if all information was saved; FALSE otherwise
2500  *  If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2501  */
2502     static BOOL
2503 SaveConsoleBuffer(
2504     ConsoleBuffer *cb)
2505 {
2506     DWORD NumCells;
2507     COORD BufferCoord;
2508     SMALL_RECT ReadRegion;
2509     WORD Y, Y_incr;
2510     int i, numregions;
2511 
2512     if (cb == NULL)
2513 	return FALSE;
2514 
2515     if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2516     {
2517 	cb->IsValid = FALSE;
2518 	return FALSE;
2519     }
2520     cb->IsValid = TRUE;
2521 
2522     /*
2523      * Allocate a buffer large enough to hold the entire console screen
2524      * buffer.  If this ConsoleBuffer structure has already been initialized
2525      * with a buffer of the correct size, then just use that one.
2526      */
2527     if (!cb->IsValid || cb->Buffer == NULL ||
2528 	    cb->BufferSize.X != cb->Info.dwSize.X ||
2529 	    cb->BufferSize.Y != cb->Info.dwSize.Y)
2530     {
2531 	cb->BufferSize.X = cb->Info.dwSize.X;
2532 	cb->BufferSize.Y = cb->Info.dwSize.Y;
2533 	NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2534 	vim_free(cb->Buffer);
2535 	cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
2536 	if (cb->Buffer == NULL)
2537 	    return FALSE;
2538     }
2539 
2540     /*
2541      * We will now copy the console screen buffer into our buffer.
2542      * ReadConsoleOutput() seems to be limited as far as how much you
2543      * can read at a time.  Empirically, this number seems to be about
2544      * 12000 cells (rows * columns).  Start at position (0, 0) and copy
2545      * in chunks until it is all copied.  The chunks will all have the
2546      * same horizontal characteristics, so initialize them now.  The
2547      * height of each chunk will be (12000 / width).
2548      */
2549     BufferCoord.X = 0;
2550     ReadRegion.Left = 0;
2551     ReadRegion.Right = cb->Info.dwSize.X - 1;
2552     Y_incr = 12000 / cb->Info.dwSize.X;
2553 
2554     numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2555     if (cb->Regions == NULL || numregions != cb->NumRegions)
2556     {
2557 	cb->NumRegions = numregions;
2558 	vim_free(cb->Regions);
2559 	cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
2560 	if (cb->Regions == NULL)
2561 	{
2562 	    VIM_CLEAR(cb->Buffer);
2563 	    return FALSE;
2564 	}
2565     }
2566 
2567     for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
2568     {
2569 	/*
2570 	 * Read into position (0, Y) in our buffer.
2571 	 */
2572 	BufferCoord.Y = Y;
2573 	/*
2574 	 * Read the region whose top left corner is (0, Y) and whose bottom
2575 	 * right corner is (width - 1, Y + Y_incr - 1).  This should define
2576 	 * a region of size width by Y_incr.  Don't worry if this region is
2577 	 * too large for the remaining buffer; it will be cropped.
2578 	 */
2579 	ReadRegion.Top = Y;
2580 	ReadRegion.Bottom = Y + Y_incr - 1;
2581 	if (!ReadConsoleOutputW(g_hConOut,	// output handle
2582 		cb->Buffer,			// our buffer
2583 		cb->BufferSize,			// dimensions of our buffer
2584 		BufferCoord,			// offset in our buffer
2585 		&ReadRegion))			// region to save
2586 	{
2587 	    VIM_CLEAR(cb->Buffer);
2588 	    VIM_CLEAR(cb->Regions);
2589 	    return FALSE;
2590 	}
2591 	cb->Regions[i] = ReadRegion;
2592     }
2593 
2594     return TRUE;
2595 }
2596 
2597 /*
2598  * RestoreConsoleBuffer()
2599  * Description:
2600  *  Restores important information about the console buffer, including the
2601  *  actual buffer contents, if desired.  The information to restore is in
2602  *  the same format used by SaveConsoleBuffer().
2603  * Returns:
2604  *  TRUE on success
2605  */
2606     static BOOL
2607 RestoreConsoleBuffer(
2608     ConsoleBuffer   *cb,
2609     BOOL	    RestoreScreen)
2610 {
2611     COORD BufferCoord;
2612     SMALL_RECT WriteRegion;
2613     int i;
2614 
2615     if (cb == NULL || !cb->IsValid)
2616 	return FALSE;
2617 
2618     /*
2619      * Before restoring the buffer contents, clear the current buffer, and
2620      * restore the cursor position and window information.  Doing this now
2621      * prevents old buffer contents from "flashing" onto the screen.
2622      */
2623     if (RestoreScreen)
2624 	ClearConsoleBuffer(cb->Info.wAttributes);
2625 
2626     FitConsoleWindow(cb->Info.dwSize, TRUE);
2627     if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2628 	return FALSE;
2629     if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2630 	return FALSE;
2631 
2632     if (!RestoreScreen)
2633     {
2634 	/*
2635 	 * No need to restore the screen buffer contents, so we're done.
2636 	 */
2637 	return TRUE;
2638     }
2639 
2640     if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2641 	return FALSE;
2642     if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2643 	return FALSE;
2644 
2645     /*
2646      * Restore the screen buffer contents.
2647      */
2648     if (cb->Buffer != NULL)
2649     {
2650 	for (i = 0; i < cb->NumRegions; i++)
2651 	{
2652 	    BufferCoord.X = cb->Regions[i].Left;
2653 	    BufferCoord.Y = cb->Regions[i].Top;
2654 	    WriteRegion = cb->Regions[i];
2655 	    if (!WriteConsoleOutputW(g_hConOut,	// output handle
2656 			cb->Buffer,		// our buffer
2657 			cb->BufferSize,		// dimensions of our buffer
2658 			BufferCoord,		// offset in our buffer
2659 			&WriteRegion))		// region to restore
2660 		return FALSE;
2661 	}
2662     }
2663 
2664     return TRUE;
2665 }
2666 
2667 # define FEAT_RESTORE_ORIG_SCREEN
2668 # ifdef FEAT_RESTORE_ORIG_SCREEN
2669 static ConsoleBuffer g_cbOrig = { 0 };
2670 # endif
2671 static ConsoleBuffer g_cbNonTermcap = { 0 };
2672 static ConsoleBuffer g_cbTermcap = { 0 };
2673 
2674 # ifdef FEAT_TITLE
2675 char g_szOrigTitle[256] = { 0 };
2676 HWND g_hWnd = NULL;	// also used in os_mswin.c
2677 static HICON g_hOrigIconSmall = NULL;
2678 static HICON g_hOrigIcon = NULL;
2679 static HICON g_hVimIcon = NULL;
2680 static BOOL g_fCanChangeIcon = FALSE;
2681 
2682 // ICON* are not defined in VC++ 4.0
2683 #  ifndef ICON_SMALL
2684 #   define ICON_SMALL 0
2685 #  endif
2686 #  ifndef ICON_BIG
2687 #   define ICON_BIG 1
2688 #  endif
2689 /*
2690  * GetConsoleIcon()
2691  * Description:
2692  *  Attempts to retrieve the small icon and/or the big icon currently in
2693  *  use by a given window.
2694  * Returns:
2695  *  TRUE on success
2696  */
2697     static BOOL
2698 GetConsoleIcon(
2699     HWND	hWnd,
2700     HICON	*phIconSmall,
2701     HICON	*phIcon)
2702 {
2703     if (hWnd == NULL)
2704 	return FALSE;
2705 
2706     if (phIconSmall != NULL)
2707 	*phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2708 					       (WPARAM)ICON_SMALL, (LPARAM)0);
2709     if (phIcon != NULL)
2710 	*phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2711 						 (WPARAM)ICON_BIG, (LPARAM)0);
2712     return TRUE;
2713 }
2714 
2715 /*
2716  * SetConsoleIcon()
2717  * Description:
2718  *  Attempts to change the small icon and/or the big icon currently in
2719  *  use by a given window.
2720  * Returns:
2721  *  TRUE on success
2722  */
2723     static BOOL
2724 SetConsoleIcon(
2725     HWND    hWnd,
2726     HICON   hIconSmall,
2727     HICON   hIcon)
2728 {
2729     if (hWnd == NULL)
2730 	return FALSE;
2731 
2732     if (hIconSmall != NULL)
2733 	SendMessage(hWnd, WM_SETICON,
2734 			    (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
2735     if (hIcon != NULL)
2736 	SendMessage(hWnd, WM_SETICON,
2737 			    (WPARAM)ICON_BIG, (LPARAM) hIcon);
2738     return TRUE;
2739 }
2740 
2741 /*
2742  * SaveConsoleTitleAndIcon()
2743  * Description:
2744  *  Saves the current console window title in g_szOrigTitle, for later
2745  *  restoration.  Also, attempts to obtain a handle to the console window,
2746  *  and use it to save the small and big icons currently in use by the
2747  *  console window.  This is not always possible on some versions of Windows;
2748  *  nor is it possible when running Vim remotely using Telnet (since the
2749  *  console window the user sees is owned by a remote process).
2750  */
2751     static void
2752 SaveConsoleTitleAndIcon(void)
2753 {
2754     // Save the original title.
2755     if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2756 	return;
2757 
2758     /*
2759      * Obtain a handle to the console window using GetConsoleWindow() from
2760      * KERNEL32.DLL; we need to handle in order to change the window icon.
2761      * This function only exists on NT-based Windows, starting with Windows
2762      * 2000.  On older operating systems, we can't change the window icon
2763      * anyway.
2764      */
2765     g_hWnd = GetConsoleWindow();
2766     if (g_hWnd == NULL)
2767 	return;
2768 
2769     // Save the original console window icon.
2770     GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2771     if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2772 	return;
2773 
2774     // Extract the first icon contained in the Vim executable.
2775     if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2776 	g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
2777     if (g_hVimIcon != NULL)
2778 	g_fCanChangeIcon = TRUE;
2779 }
2780 # endif
2781 
2782 static int g_fWindInitCalled = FALSE;
2783 static int g_fTermcapMode = FALSE;
2784 static CONSOLE_CURSOR_INFO g_cci;
2785 static DWORD g_cmodein = 0;
2786 static DWORD g_cmodeout = 0;
2787 
2788 /*
2789  * non-GUI version of mch_init().
2790  */
2791     static void
2792 mch_init_c(void)
2793 {
2794 # ifndef FEAT_RESTORE_ORIG_SCREEN
2795     CONSOLE_SCREEN_BUFFER_INFO csbi;
2796 # endif
2797 # ifndef __MINGW32__
2798     extern int _fmode;
2799 # endif
2800 
2801     // Silently handle invalid parameters to CRT functions
2802     SET_INVALID_PARAM_HANDLER;
2803 
2804     // Let critical errors result in a failure, not in a dialog box.  Required
2805     // for the timestamp test to work on removed floppies.
2806     SetErrorMode(SEM_FAILCRITICALERRORS);
2807 
2808     _fmode = O_BINARY;		// we do our own CR-LF translation
2809     out_flush();
2810 
2811     // Obtain handles for the standard Console I/O devices
2812     if (read_cmd_fd == 0)
2813 	g_hConIn =  GetStdHandle(STD_INPUT_HANDLE);
2814     else
2815 	create_conin();
2816     g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2817 
2818 # ifdef FEAT_RESTORE_ORIG_SCREEN
2819     // Save the initial console buffer for later restoration
2820     SaveConsoleBuffer(&g_cbOrig);
2821     g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2822 # else
2823     // Get current text attributes
2824     GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2825     g_attrCurrent = g_attrDefault = csbi.wAttributes;
2826 # endif
2827     if (cterm_normal_fg_color == 0)
2828 	cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2829     if (cterm_normal_bg_color == 0)
2830 	cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2831 
2832     // Fg and Bg color index number at startup
2833     g_color_index_fg = g_attrDefault & 0xf;
2834     g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2835 
2836     // set termcap codes to current text attributes
2837     update_tcap(g_attrCurrent);
2838 
2839     GetConsoleCursorInfo(g_hConOut, &g_cci);
2840     GetConsoleMode(g_hConIn,  &g_cmodein);
2841     GetConsoleMode(g_hConOut, &g_cmodeout);
2842 
2843 # ifdef FEAT_TITLE
2844     SaveConsoleTitleAndIcon();
2845     /*
2846      * Set both the small and big icons of the console window to Vim's icon.
2847      * Note that Vim presently only has one size of icon (32x32), but it
2848      * automatically gets scaled down to 16x16 when setting the small icon.
2849      */
2850     if (g_fCanChangeIcon)
2851 	SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2852 # endif
2853 
2854     ui_get_shellsize();
2855 
2856 # ifdef MCH_WRITE_DUMP
2857     fdDump = fopen("dump", "wt");
2858 
2859     if (fdDump)
2860     {
2861 	time_t t;
2862 
2863 	time(&t);
2864 	fputs(ctime(&t), fdDump);
2865 	fflush(fdDump);
2866     }
2867 # endif
2868 
2869     g_fWindInitCalled = TRUE;
2870 
2871     g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2872 
2873 # ifdef FEAT_CLIPBOARD
2874     win_clip_init();
2875 # endif
2876 
2877     vtp_flag_init();
2878     vtp_init();
2879     wt_init();
2880 }
2881 
2882 /*
2883  * non-GUI version of mch_exit().
2884  * Shut down and exit with status `r'
2885  * Careful: mch_exit() may be called before mch_init()!
2886  */
2887     static void
2888 mch_exit_c(int r)
2889 {
2890     exiting = TRUE;
2891 
2892     vtp_exit();
2893 
2894     stoptermcap();
2895     if (g_fWindInitCalled)
2896 	settmode(TMODE_COOK);
2897 
2898     ml_close_all(TRUE);		// remove all memfiles
2899 
2900     if (g_fWindInitCalled)
2901     {
2902 # ifdef FEAT_TITLE
2903 	mch_restore_title(SAVE_RESTORE_BOTH);
2904 	/*
2905 	 * Restore both the small and big icons of the console window to
2906 	 * what they were at startup.  Don't do this when the window is
2907 	 * closed, Vim would hang here.
2908 	 */
2909 	if (g_fCanChangeIcon && !g_fForceExit)
2910 	    SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2911 # endif
2912 
2913 # ifdef MCH_WRITE_DUMP
2914 	if (fdDump)
2915 	{
2916 	    time_t t;
2917 
2918 	    time(&t);
2919 	    fputs(ctime(&t), fdDump);
2920 	    fclose(fdDump);
2921 	}
2922 	fdDump = NULL;
2923 # endif
2924     }
2925 
2926     SetConsoleCursorInfo(g_hConOut, &g_cci);
2927     SetConsoleMode(g_hConIn,  g_cmodein);
2928     SetConsoleMode(g_hConOut, g_cmodeout);
2929 
2930 # ifdef DYNAMIC_GETTEXT
2931     dyn_libintl_end();
2932 # endif
2933 
2934     exit(r);
2935 }
2936 #endif // !FEAT_GUI_MSWIN
2937 
2938     void
2939 mch_init(void)
2940 {
2941 #ifdef VIMDLL
2942     if (gui.starting)
2943 	mch_init_g();
2944     else
2945 	mch_init_c();
2946 #elif defined(FEAT_GUI_MSWIN)
2947     mch_init_g();
2948 #else
2949     mch_init_c();
2950 #endif
2951 }
2952 
2953     void
2954 mch_exit(int r)
2955 {
2956 #ifdef FEAT_NETBEANS_INTG
2957     netbeans_send_disconnect();
2958 #endif
2959 
2960 #ifdef VIMDLL
2961     if (gui.in_use || gui.starting)
2962 	mch_exit_g(r);
2963     else
2964 	mch_exit_c(r);
2965 #elif defined(FEAT_GUI_MSWIN)
2966     mch_exit_g(r);
2967 #else
2968     mch_exit_c(r);
2969 #endif
2970 }
2971 
2972 /*
2973  * Do we have an interactive window?
2974  */
2975     int
2976 mch_check_win(
2977     int argc UNUSED,
2978     char **argv UNUSED)
2979 {
2980     get_exe_name();
2981 
2982 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
2983     return OK;	    // GUI always has a tty
2984 #else
2985 # ifdef VIMDLL
2986     if (gui.in_use)
2987 	return OK;
2988 # endif
2989     if (isatty(1))
2990 	return OK;
2991     return FAIL;
2992 #endif
2993 }
2994 
2995 /*
2996  * Set the case of the file name, if it already exists.
2997  * When "len" is > 0, also expand short to long filenames.
2998  */
2999     void
3000 fname_case(
3001     char_u	*name,
3002     int		len)
3003 {
3004     int	    flen;
3005     WCHAR   *p;
3006     WCHAR   buf[_MAX_PATH + 1];
3007 
3008     flen = (int)STRLEN(name);
3009     if (flen == 0)
3010 	return;
3011 
3012     slash_adjust(name);
3013 
3014     p = enc_to_utf16(name, NULL);
3015     if (p == NULL)
3016 	return;
3017 
3018     if (GetLongPathNameW(p, buf, _MAX_PATH))
3019     {
3020 	char_u	*q = utf16_to_enc(buf, NULL);
3021 
3022 	if (q != NULL)
3023 	{
3024 	    if (len > 0 || flen >= (int)STRLEN(q))
3025 		vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3026 	    vim_free(q);
3027 	}
3028     }
3029     vim_free(p);
3030 }
3031 
3032 
3033 /*
3034  * Insert user name in s[len].
3035  */
3036     int
3037 mch_get_user_name(
3038     char_u  *s,
3039     int	    len)
3040 {
3041     WCHAR wszUserName[256 + 1];	// UNLEN is 256
3042     DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3043 
3044     if (GetUserNameW(wszUserName, &wcch))
3045     {
3046 	char_u  *p = utf16_to_enc(wszUserName, NULL);
3047 
3048 	if (p != NULL)
3049 	{
3050 	    vim_strncpy(s, p, len - 1);
3051 	    vim_free(p);
3052 	    return OK;
3053 	}
3054     }
3055     s[0] = NUL;
3056     return FAIL;
3057 }
3058 
3059 
3060 /*
3061  * Insert host name in s[len].
3062  */
3063     void
3064 mch_get_host_name(
3065     char_u	*s,
3066     int		len)
3067 {
3068     WCHAR wszHostName[256 + 1];
3069     DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3070 
3071     if (GetComputerNameW(wszHostName, &wcch))
3072     {
3073 	char_u  *p = utf16_to_enc(wszHostName, NULL);
3074 
3075 	if (p != NULL)
3076 	{
3077 	    vim_strncpy(s, p, len - 1);
3078 	    vim_free(p);
3079 	    return;
3080 	}
3081     }
3082 }
3083 
3084 
3085 /*
3086  * return process ID
3087  */
3088     long
3089 mch_get_pid(void)
3090 {
3091     return (long)GetCurrentProcessId();
3092 }
3093 
3094 /*
3095  * return TRUE if process "pid" is still running
3096  */
3097     int
3098 mch_process_running(long pid)
3099 {
3100     HANDLE  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3101     DWORD   status = 0;
3102     int	    ret = FALSE;
3103 
3104     if (hProcess == NULL)
3105 	return FALSE;  // might not have access
3106     if (GetExitCodeProcess(hProcess, &status) )
3107 	ret = status == STILL_ACTIVE;
3108     CloseHandle(hProcess);
3109     return ret;
3110 }
3111 
3112 /*
3113  * Get name of current directory into buffer 'buf' of length 'len' bytes.
3114  * Return OK for success, FAIL for failure.
3115  */
3116     int
3117 mch_dirname(
3118     char_u	*buf,
3119     int		len)
3120 {
3121     WCHAR   wbuf[_MAX_PATH + 1];
3122 
3123     /*
3124      * Originally this was:
3125      *    return (getcwd(buf, len) != NULL ? OK : FAIL);
3126      * But the Win32s known bug list says that getcwd() doesn't work
3127      * so use the Win32 system call instead. <Negri>
3128      */
3129     if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3130     {
3131 	WCHAR   wcbuf[_MAX_PATH + 1];
3132 	char_u  *p = NULL;
3133 
3134 	if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
3135 	{
3136 	    p = utf16_to_enc(wcbuf, NULL);
3137 	    if (STRLEN(p) >= (size_t)len)
3138 	    {
3139 		// long path name is too long, fall back to short one
3140 		vim_free(p);
3141 		p = NULL;
3142 	    }
3143 	}
3144 	if (p == NULL)
3145 	    p = utf16_to_enc(wbuf, NULL);
3146 
3147 	if (p != NULL)
3148 	{
3149 	    vim_strncpy(buf, p, len - 1);
3150 	    vim_free(p);
3151 	    return OK;
3152 	}
3153     }
3154     return FAIL;
3155 }
3156 
3157 /*
3158  * Get file permissions for "name".
3159  * Return mode_t or -1 for error.
3160  */
3161     long
3162 mch_getperm(char_u *name)
3163 {
3164     stat_T	st;
3165     int		n;
3166 
3167     n = mch_stat((char *)name, &st);
3168     return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
3169 }
3170 
3171 
3172 /*
3173  * Set file permission for "name" to "perm".
3174  *
3175  * Return FAIL for failure, OK otherwise.
3176  */
3177     int
3178 mch_setperm(char_u *name, long perm)
3179 {
3180     long	n;
3181     WCHAR	*p;
3182 
3183     p = enc_to_utf16(name, NULL);
3184     if (p == NULL)
3185 	return FAIL;
3186 
3187     n = _wchmod(p, perm);
3188     vim_free(p);
3189     if (n == -1)
3190 	return FAIL;
3191 
3192     win32_set_archive(name);
3193 
3194     return OK;
3195 }
3196 
3197 /*
3198  * Set hidden flag for "name".
3199  */
3200     void
3201 mch_hide(char_u *name)
3202 {
3203     int attrs = win32_getattrs(name);
3204     if (attrs == -1)
3205 	return;
3206 
3207     attrs |= FILE_ATTRIBUTE_HIDDEN;
3208     win32_setattrs(name, attrs);
3209 }
3210 
3211 /*
3212  * Return TRUE if file "name" exists and is hidden.
3213  */
3214     int
3215 mch_ishidden(char_u *name)
3216 {
3217     int f = win32_getattrs(name);
3218 
3219     if (f == -1)
3220 	return FALSE;		    // file does not exist at all
3221 
3222     return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3223 }
3224 
3225 /*
3226  * return TRUE if "name" is a directory
3227  * return FALSE if "name" is not a directory or upon error
3228  */
3229     int
3230 mch_isdir(char_u *name)
3231 {
3232     int f = win32_getattrs(name);
3233 
3234     if (f == -1)
3235 	return FALSE;		    // file does not exist at all
3236 
3237     return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3238 }
3239 
3240 /*
3241  * return TRUE if "name" is a directory, NOT a symlink to a directory
3242  * return FALSE if "name" is not a directory
3243  * return FALSE for error
3244  */
3245     int
3246 mch_isrealdir(char_u *name)
3247 {
3248     return mch_isdir(name) && !mch_is_symbolic_link(name);
3249 }
3250 
3251 /*
3252  * Create directory "name".
3253  * Return 0 on success, -1 on error.
3254  */
3255     int
3256 mch_mkdir(char_u *name)
3257 {
3258     WCHAR   *p;
3259     int	    retval;
3260 
3261     p = enc_to_utf16(name, NULL);
3262     if (p == NULL)
3263 	return -1;
3264     retval = _wmkdir(p);
3265     vim_free(p);
3266     return retval;
3267 }
3268 
3269 /*
3270  * Delete directory "name".
3271  * Return 0 on success, -1 on error.
3272  */
3273     int
3274 mch_rmdir(char_u *name)
3275 {
3276     WCHAR   *p;
3277     int	    retval;
3278 
3279     p = enc_to_utf16(name, NULL);
3280     if (p == NULL)
3281 	return -1;
3282     retval = _wrmdir(p);
3283     vim_free(p);
3284     return retval;
3285 }
3286 
3287 /*
3288  * Return TRUE if file "fname" has more than one link.
3289  */
3290     int
3291 mch_is_hard_link(char_u *fname)
3292 {
3293     BY_HANDLE_FILE_INFORMATION info;
3294 
3295     return win32_fileinfo(fname, &info) == FILEINFO_OK
3296 						   && info.nNumberOfLinks > 1;
3297 }
3298 
3299 /*
3300  * Return TRUE if "name" is a symbolic link (or a junction).
3301  */
3302     int
3303 mch_is_symbolic_link(char_u *name)
3304 {
3305     HANDLE		hFind;
3306     int			res = FALSE;
3307     DWORD		fileFlags = 0, reparseTag = 0;
3308     WCHAR		*wn;
3309     WIN32_FIND_DATAW	findDataW;
3310 
3311     wn = enc_to_utf16(name, NULL);
3312     if (wn == NULL)
3313 	return FALSE;
3314 
3315     hFind = FindFirstFileW(wn, &findDataW);
3316     vim_free(wn);
3317     if (hFind != INVALID_HANDLE_VALUE)
3318     {
3319 	fileFlags = findDataW.dwFileAttributes;
3320 	reparseTag = findDataW.dwReserved0;
3321 	FindClose(hFind);
3322     }
3323 
3324     if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3325 	    && (reparseTag == IO_REPARSE_TAG_SYMLINK
3326 		|| reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
3327 	res = TRUE;
3328 
3329     return res;
3330 }
3331 
3332 /*
3333  * Return TRUE if file "fname" has more than one link or if it is a symbolic
3334  * link.
3335  */
3336     int
3337 mch_is_linked(char_u *fname)
3338 {
3339     if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3340 	return TRUE;
3341     return FALSE;
3342 }
3343 
3344 /*
3345  * Get the by-handle-file-information for "fname".
3346  * Returns FILEINFO_OK when OK.
3347  * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3348  * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3349  * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3350  */
3351     int
3352 win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3353 {
3354     HANDLE	hFile;
3355     int		res = FILEINFO_READ_FAIL;
3356     WCHAR	*wn;
3357 
3358     wn = enc_to_utf16(fname, NULL);
3359     if (wn == NULL)
3360 	return FILEINFO_ENC_FAIL;
3361 
3362     hFile = CreateFileW(wn,	// file name
3363 	    GENERIC_READ,	// access mode
3364 	    FILE_SHARE_READ | FILE_SHARE_WRITE,	// share mode
3365 	    NULL,		// security descriptor
3366 	    OPEN_EXISTING,	// creation disposition
3367 	    FILE_FLAG_BACKUP_SEMANTICS,	// file attributes
3368 	    NULL);		// handle to template file
3369     vim_free(wn);
3370 
3371     if (hFile != INVALID_HANDLE_VALUE)
3372     {
3373 	if (GetFileInformationByHandle(hFile, info) != 0)
3374 	    res = FILEINFO_OK;
3375 	else
3376 	    res = FILEINFO_INFO_FAIL;
3377 	CloseHandle(hFile);
3378     }
3379 
3380     return res;
3381 }
3382 
3383 /*
3384  * get file attributes for `name'
3385  * -1 : error
3386  * else FILE_ATTRIBUTE_* defined in winnt.h
3387  */
3388     static int
3389 win32_getattrs(char_u *name)
3390 {
3391     int		attr;
3392     WCHAR	*p;
3393 
3394     p = enc_to_utf16(name, NULL);
3395     if (p == NULL)
3396 	return INVALID_FILE_ATTRIBUTES;
3397 
3398     attr = GetFileAttributesW(p);
3399     vim_free(p);
3400 
3401     return attr;
3402 }
3403 
3404 /*
3405  * set file attributes for `name' to `attrs'
3406  *
3407  * return -1 for failure, 0 otherwise
3408  */
3409     static int
3410 win32_setattrs(char_u *name, int attrs)
3411 {
3412     int	    res;
3413     WCHAR   *p;
3414 
3415     p = enc_to_utf16(name, NULL);
3416     if (p == NULL)
3417 	return -1;
3418 
3419     res = SetFileAttributesW(p, attrs);
3420     vim_free(p);
3421 
3422     return res ? 0 : -1;
3423 }
3424 
3425 /*
3426  * Set archive flag for "name".
3427  */
3428     static int
3429 win32_set_archive(char_u *name)
3430 {
3431     int attrs = win32_getattrs(name);
3432     if (attrs == -1)
3433 	return -1;
3434 
3435     attrs |= FILE_ATTRIBUTE_ARCHIVE;
3436     return win32_setattrs(name, attrs);
3437 }
3438 
3439 /*
3440  * Return TRUE if file or directory "name" is writable (not readonly).
3441  * Strange semantics of Win32: a readonly directory is writable, but you can't
3442  * delete a file.  Let's say this means it is writable.
3443  */
3444     int
3445 mch_writable(char_u *name)
3446 {
3447     int attrs = win32_getattrs(name);
3448 
3449     return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3450 			  || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
3451 }
3452 
3453 /*
3454  * Return TRUE if "name" can be executed, FALSE if not.
3455  * If "use_path" is FALSE only check if "name" is executable.
3456  * When returning TRUE and "path" is not NULL save the path and set "*path" to
3457  * the allocated memory.
3458  */
3459     int
3460 mch_can_exe(char_u *name, char_u **path, int use_path)
3461 {
3462     return executable_exists((char *)name, path, TRUE, TRUE);
3463 }
3464 
3465 /*
3466  * Check what "name" is:
3467  * NODE_NORMAL: file or directory (or doesn't exist)
3468  * NODE_WRITABLE: writable device, socket, fifo, etc.
3469  * NODE_OTHER: non-writable things
3470  */
3471     int
3472 mch_nodetype(char_u *name)
3473 {
3474     HANDLE	hFile;
3475     int		type;
3476     WCHAR	*wn;
3477 
3478     // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3479     // read from it later will cause Vim to hang.  Thus return NODE_WRITABLE
3480     // here.
3481     if (STRNCMP(name, "\\\\.\\", 4) == 0)
3482 	return NODE_WRITABLE;
3483 
3484     wn = enc_to_utf16(name, NULL);
3485     if (wn == NULL)
3486 	return NODE_NORMAL;
3487 
3488     hFile = CreateFileW(wn,	    // file name
3489 	    GENERIC_WRITE,	    // access mode
3490 	    0,			    // share mode
3491 	    NULL,		    // security descriptor
3492 	    OPEN_EXISTING,	    // creation disposition
3493 	    0,			    // file attributes
3494 	    NULL);		    // handle to template file
3495     vim_free(wn);
3496     if (hFile == INVALID_HANDLE_VALUE)
3497 	return NODE_NORMAL;
3498 
3499     type = GetFileType(hFile);
3500     CloseHandle(hFile);
3501     if (type == FILE_TYPE_CHAR)
3502 	return NODE_WRITABLE;
3503     if (type == FILE_TYPE_DISK)
3504 	return NODE_NORMAL;
3505     return NODE_OTHER;
3506 }
3507 
3508 #ifdef HAVE_ACL
3509 struct my_acl
3510 {
3511     PSECURITY_DESCRIPTOR    pSecurityDescriptor;
3512     PSID		    pSidOwner;
3513     PSID		    pSidGroup;
3514     PACL		    pDacl;
3515     PACL		    pSacl;
3516 };
3517 #endif
3518 
3519 /*
3520  * Return a pointer to the ACL of file "fname" in allocated memory.
3521  * Return NULL if the ACL is not available for whatever reason.
3522  */
3523     vim_acl_T
3524 mch_get_acl(char_u *fname)
3525 {
3526 #ifndef HAVE_ACL
3527     return (vim_acl_T)NULL;
3528 #else
3529     struct my_acl   *p = NULL;
3530     DWORD   err;
3531 
3532     p = ALLOC_CLEAR_ONE(struct my_acl);
3533     if (p != NULL)
3534     {
3535 	WCHAR	*wn;
3536 
3537 	wn = enc_to_utf16(fname, NULL);
3538 	if (wn == NULL)
3539 	{
3540 	    vim_free(p);
3541 	    return NULL;
3542 	}
3543 
3544 	// Try to retrieve the entire security descriptor.
3545 	err = GetNamedSecurityInfoW(
3546 		wn,			// Abstract filename
3547 		SE_FILE_OBJECT,		// File Object
3548 		OWNER_SECURITY_INFORMATION |
3549 		GROUP_SECURITY_INFORMATION |
3550 		DACL_SECURITY_INFORMATION |
3551 		SACL_SECURITY_INFORMATION,
3552 		&p->pSidOwner,		// Ownership information.
3553 		&p->pSidGroup,		// Group membership.
3554 		&p->pDacl,		// Discretionary information.
3555 		&p->pSacl,		// For auditing purposes.
3556 		&p->pSecurityDescriptor);
3557 	if (err == ERROR_ACCESS_DENIED ||
3558 		err == ERROR_PRIVILEGE_NOT_HELD)
3559 	{
3560 	    // Retrieve only DACL.
3561 	    (void)GetNamedSecurityInfoW(
3562 		    wn,
3563 		    SE_FILE_OBJECT,
3564 		    DACL_SECURITY_INFORMATION,
3565 		    NULL,
3566 		    NULL,
3567 		    &p->pDacl,
3568 		    NULL,
3569 		    &p->pSecurityDescriptor);
3570 	}
3571 	if (p->pSecurityDescriptor == NULL)
3572 	{
3573 	    mch_free_acl((vim_acl_T)p);
3574 	    p = NULL;
3575 	}
3576 	vim_free(wn);
3577     }
3578 
3579     return (vim_acl_T)p;
3580 #endif
3581 }
3582 
3583 #ifdef HAVE_ACL
3584 /*
3585  * Check if "acl" contains inherited ACE.
3586  */
3587     static BOOL
3588 is_acl_inherited(PACL acl)
3589 {
3590     DWORD   i;
3591     ACL_SIZE_INFORMATION    acl_info;
3592     PACCESS_ALLOWED_ACE	    ace;
3593 
3594     acl_info.AceCount = 0;
3595     GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3596     for (i = 0; i < acl_info.AceCount; i++)
3597     {
3598 	GetAce(acl, i, (LPVOID *)&ace);
3599 	if (ace->Header.AceFlags & INHERITED_ACE)
3600 	    return TRUE;
3601     }
3602     return FALSE;
3603 }
3604 #endif
3605 
3606 /*
3607  * Set the ACL of file "fname" to "acl" (unless it's NULL).
3608  * Errors are ignored.
3609  * This must only be called with "acl" equal to what mch_get_acl() returned.
3610  */
3611     void
3612 mch_set_acl(char_u *fname, vim_acl_T acl)
3613 {
3614 #ifdef HAVE_ACL
3615     struct my_acl   *p = (struct my_acl *)acl;
3616     SECURITY_INFORMATION    sec_info = 0;
3617     WCHAR	    *wn;
3618 
3619     if (p == NULL)
3620 	return;
3621 
3622     wn = enc_to_utf16(fname, NULL);
3623     if (wn == NULL)
3624 	return;
3625 
3626     // Set security flags
3627     if (p->pSidOwner)
3628 	sec_info |= OWNER_SECURITY_INFORMATION;
3629     if (p->pSidGroup)
3630 	sec_info |= GROUP_SECURITY_INFORMATION;
3631     if (p->pDacl)
3632     {
3633 	sec_info |= DACL_SECURITY_INFORMATION;
3634 	// Do not inherit its parent's DACL.
3635 	// If the DACL is inherited, Cygwin permissions would be changed.
3636 	if (!is_acl_inherited(p->pDacl))
3637 	    sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3638     }
3639     if (p->pSacl)
3640 	sec_info |= SACL_SECURITY_INFORMATION;
3641 
3642     (void)SetNamedSecurityInfoW(
3643 	    wn,			// Abstract filename
3644 	    SE_FILE_OBJECT,	// File Object
3645 	    sec_info,
3646 	    p->pSidOwner,	// Ownership information.
3647 	    p->pSidGroup,	// Group membership.
3648 	    p->pDacl,		// Discretionary information.
3649 	    p->pSacl		// For auditing purposes.
3650 	    );
3651     vim_free(wn);
3652 #endif
3653 }
3654 
3655     void
3656 mch_free_acl(vim_acl_T acl)
3657 {
3658 #ifdef HAVE_ACL
3659     struct my_acl   *p = (struct my_acl *)acl;
3660 
3661     if (p != NULL)
3662     {
3663 	LocalFree(p->pSecurityDescriptor);	// Free the memory just in case
3664 	vim_free(p);
3665     }
3666 #endif
3667 }
3668 
3669 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
3670 
3671 /*
3672  * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3673  */
3674     static BOOL WINAPI
3675 handler_routine(
3676     DWORD dwCtrlType)
3677 {
3678     INPUT_RECORD ir;
3679     DWORD out;
3680 
3681     switch (dwCtrlType)
3682     {
3683     case CTRL_C_EVENT:
3684 	if (ctrl_c_interrupts)
3685 	    g_fCtrlCPressed = TRUE;
3686 	return TRUE;
3687 
3688     case CTRL_BREAK_EVENT:
3689 	g_fCBrkPressed	= TRUE;
3690 	ctrl_break_was_pressed = TRUE;
3691 	// ReadConsoleInput is blocking, send a key event to continue.
3692 	ir.EventType = KEY_EVENT;
3693 	ir.Event.KeyEvent.bKeyDown = TRUE;
3694 	ir.Event.KeyEvent.wRepeatCount = 1;
3695 	ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3696 	ir.Event.KeyEvent.wVirtualScanCode = 0;
3697 	ir.Event.KeyEvent.dwControlKeyState = 0;
3698 	ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3699 	WriteConsoleInput(g_hConIn, &ir, 1, &out);
3700 	return TRUE;
3701 
3702     // fatal events: shut down gracefully
3703     case CTRL_CLOSE_EVENT:
3704     case CTRL_LOGOFF_EVENT:
3705     case CTRL_SHUTDOWN_EVENT:
3706 	windgoto((int)Rows - 1, 0);
3707 	g_fForceExit = TRUE;
3708 
3709 	vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
3710 		(dwCtrlType == CTRL_CLOSE_EVENT
3711 		     ? _("close")
3712 		     : dwCtrlType == CTRL_LOGOFF_EVENT
3713 			 ? _("logoff")
3714 			 : _("shutdown")));
3715 # ifdef DEBUG
3716 	OutputDebugString(IObuff);
3717 # endif
3718 
3719 	preserve_exit();	// output IObuff, preserve files and exit
3720 
3721 	return TRUE;		// not reached
3722 
3723     default:
3724 	return FALSE;
3725     }
3726 }
3727 
3728 
3729 /*
3730  * set the tty in (raw) ? "raw" : "cooked" mode
3731  */
3732     void
3733 mch_settmode(tmode_T tmode)
3734 {
3735     DWORD cmodein;
3736     DWORD cmodeout;
3737     BOOL bEnableHandler;
3738 
3739 # ifdef VIMDLL
3740     if (gui.in_use)
3741 	return;
3742 # endif
3743     GetConsoleMode(g_hConIn, &cmodein);
3744     GetConsoleMode(g_hConOut, &cmodeout);
3745     if (tmode == TMODE_RAW)
3746     {
3747 	cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3748 		     ENABLE_ECHO_INPUT);
3749 	if (g_fMouseActive)
3750 	    cmodein |= ENABLE_MOUSE_INPUT;
3751 	cmodeout &= ~(
3752 # ifdef FEAT_TERMGUICOLORS
3753 	    // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3754 	    // VTP.
3755 	    ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3756 # else
3757 	    ENABLE_PROCESSED_OUTPUT |
3758 # endif
3759 	    ENABLE_WRAP_AT_EOL_OUTPUT);
3760 	bEnableHandler = TRUE;
3761     }
3762     else // cooked
3763     {
3764 	cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3765 		    ENABLE_ECHO_INPUT);
3766 	cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3767 	bEnableHandler = FALSE;
3768     }
3769     SetConsoleMode(g_hConIn, cmodein);
3770     SetConsoleMode(g_hConOut, cmodeout);
3771     SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3772 
3773 # ifdef MCH_WRITE_DUMP
3774     if (fdDump)
3775     {
3776 	fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3777 		tmode == TMODE_RAW ? "raw" :
3778 				    tmode == TMODE_COOK ? "cooked" : "normal",
3779 		cmodein, cmodeout);
3780 	fflush(fdDump);
3781     }
3782 # endif
3783 }
3784 
3785 
3786 /*
3787  * Get the size of the current window in `Rows' and `Columns'
3788  * Return OK when size could be determined, FAIL otherwise.
3789  */
3790     int
3791 mch_get_shellsize(void)
3792 {
3793     CONSOLE_SCREEN_BUFFER_INFO csbi;
3794 
3795 # ifdef VIMDLL
3796     if (gui.in_use)
3797 	return OK;
3798 # endif
3799     if (!g_fTermcapMode && g_cbTermcap.IsValid)
3800     {
3801 	/*
3802 	 * For some reason, we are trying to get the screen dimensions
3803 	 * even though we are not in termcap mode.  The 'Rows' and 'Columns'
3804 	 * variables are really intended to mean the size of Vim screen
3805 	 * while in termcap mode.
3806 	 */
3807 	Rows = g_cbTermcap.Info.dwSize.Y;
3808 	Columns = g_cbTermcap.Info.dwSize.X;
3809     }
3810     else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3811     {
3812 	Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3813 	Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3814     }
3815     else
3816     {
3817 	Rows = 25;
3818 	Columns = 80;
3819     }
3820     return OK;
3821 }
3822 
3823 /*
3824  * Resize console buffer to 'COORD'
3825  */
3826     static void
3827 ResizeConBuf(
3828     HANDLE  hConsole,
3829     COORD   coordScreen)
3830 {
3831     if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3832     {
3833 # ifdef MCH_WRITE_DUMP
3834 	if (fdDump)
3835 	{
3836 	    fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3837 		    GetLastError());
3838 	    fflush(fdDump);
3839 	}
3840 # endif
3841     }
3842 }
3843 
3844 /*
3845  * Resize console window size to 'srWindowRect'
3846  */
3847     static void
3848 ResizeWindow(
3849     HANDLE     hConsole,
3850     SMALL_RECT srWindowRect)
3851 {
3852     if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3853     {
3854 # ifdef MCH_WRITE_DUMP
3855 	if (fdDump)
3856 	{
3857 	    fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3858 		    GetLastError());
3859 	    fflush(fdDump);
3860 	}
3861 # endif
3862     }
3863 }
3864 
3865 /*
3866  * Set a console window to `xSize' * `ySize'
3867  */
3868     static void
3869 ResizeConBufAndWindow(
3870     HANDLE  hConsole,
3871     int	    xSize,
3872     int	    ySize)
3873 {
3874     CONSOLE_SCREEN_BUFFER_INFO csbi;	// hold current console buffer info
3875     SMALL_RECT	    srWindowRect;	// hold the new console size
3876     COORD	    coordScreen;
3877     COORD	    cursor;
3878     static int	    resized = FALSE;
3879 
3880 # ifdef MCH_WRITE_DUMP
3881     if (fdDump)
3882     {
3883 	fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3884 	fflush(fdDump);
3885     }
3886 # endif
3887 
3888     // get the largest size we can size the console window to
3889     coordScreen = GetLargestConsoleWindowSize(hConsole);
3890 
3891     // define the new console window size and scroll position
3892     srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3893     srWindowRect.Right =  (SHORT) (min(xSize, coordScreen.X) - 1);
3894     srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3895 
3896     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3897     {
3898 	int sx, sy;
3899 
3900 	sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3901 	sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3902 	if (sy < ySize || sx < xSize)
3903 	{
3904 	    /*
3905 	     * Increasing number of lines/columns, do buffer first.
3906 	     * Use the maximal size in x and y direction.
3907 	     */
3908 	    if (sy < ySize)
3909 		coordScreen.Y = ySize;
3910 	    else
3911 		coordScreen.Y = sy;
3912 	    if (sx < xSize)
3913 		coordScreen.X = xSize;
3914 	    else
3915 		coordScreen.X = sx;
3916 	    SetConsoleScreenBufferSize(hConsole, coordScreen);
3917 	}
3918     }
3919 
3920     // define the new console buffer size
3921     coordScreen.X = xSize;
3922     coordScreen.Y = ySize;
3923 
3924     // In the new console call API, only the first time in reverse order
3925     if (!vtp_working || resized)
3926     {
3927 	ResizeWindow(hConsole, srWindowRect);
3928 	ResizeConBuf(hConsole, coordScreen);
3929     }
3930     else
3931     {
3932 	// Workaround for a Windows 10 bug
3933 	cursor.X = srWindowRect.Left;
3934 	cursor.Y = srWindowRect.Top;
3935 	SetConsoleCursorPosition(hConsole, cursor);
3936 
3937 	ResizeConBuf(hConsole, coordScreen);
3938 	ResizeWindow(hConsole, srWindowRect);
3939 	resized = TRUE;
3940     }
3941 }
3942 
3943 
3944 /*
3945  * Set the console window to `Rows' * `Columns'
3946  */
3947     void
3948 mch_set_shellsize(void)
3949 {
3950     COORD coordScreen;
3951 
3952 # ifdef VIMDLL
3953     if (gui.in_use)
3954 	return;
3955 # endif
3956     // Don't change window size while still starting up
3957     if (suppress_winsize != 0)
3958     {
3959 	suppress_winsize = 2;
3960 	return;
3961     }
3962 
3963     if (term_console)
3964     {
3965 	coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3966 
3967 	// Clamp Rows and Columns to reasonable values
3968 	if (Rows > coordScreen.Y)
3969 	    Rows = coordScreen.Y;
3970 	if (Columns > coordScreen.X)
3971 	    Columns = coordScreen.X;
3972 
3973 	ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3974     }
3975 }
3976 
3977 /*
3978  * Rows and/or Columns has changed.
3979  */
3980     void
3981 mch_new_shellsize(void)
3982 {
3983 # ifdef VIMDLL
3984     if (gui.in_use)
3985 	return;
3986 # endif
3987     set_scroll_region(0, 0, Columns - 1, Rows - 1);
3988 }
3989 
3990 
3991 /*
3992  * Called when started up, to set the winsize that was delayed.
3993  */
3994     void
3995 mch_set_winsize_now(void)
3996 {
3997     if (suppress_winsize == 2)
3998     {
3999 	suppress_winsize = 0;
4000 	mch_set_shellsize();
4001 	shell_resized();
4002     }
4003     suppress_winsize = 0;
4004 }
4005 #endif // FEAT_GUI_MSWIN
4006 
4007     static BOOL
4008 vim_create_process(
4009     char		*cmd,
4010     BOOL		inherit_handles,
4011     DWORD		flags,
4012     STARTUPINFO		*si,
4013     PROCESS_INFORMATION *pi,
4014     LPVOID		*env,
4015     char		*cwd)
4016 {
4017     BOOL	ret = FALSE;
4018     WCHAR	*wcmd, *wcwd = NULL;
4019 
4020     wcmd = enc_to_utf16((char_u *)cmd, NULL);
4021     if (wcmd == NULL)
4022 	return FALSE;
4023     if (cwd != NULL)
4024     {
4025 	wcwd = enc_to_utf16((char_u *)cwd, NULL);
4026 	if (wcwd == NULL)
4027 	    goto theend;
4028     }
4029 
4030     ret = CreateProcessW(
4031 	    NULL,		// Executable name
4032 	    wcmd,		// Command to execute
4033 	    NULL,		// Process security attributes
4034 	    NULL,		// Thread security attributes
4035 	    inherit_handles,	// Inherit handles
4036 	    flags,		// Creation flags
4037 	    env,		// Environment
4038 	    wcwd,		// Current directory
4039 	    (LPSTARTUPINFOW)si,	// Startup information
4040 	    pi);		// Process information
4041 theend:
4042     vim_free(wcmd);
4043     vim_free(wcwd);
4044     return ret;
4045 }
4046 
4047 
4048     static HINSTANCE
4049 vim_shell_execute(
4050     char *cmd,
4051     INT	 n_show_cmd)
4052 {
4053     HINSTANCE	ret;
4054     WCHAR	*wcmd;
4055 
4056     wcmd = enc_to_utf16((char_u *)cmd, NULL);
4057     if (wcmd == NULL)
4058 	return (HINSTANCE) 0;
4059 
4060     ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4061     vim_free(wcmd);
4062     return ret;
4063 }
4064 
4065 
4066 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
4067 
4068 /*
4069  * Specialised version of system() for Win32 GUI mode.
4070  * This version proceeds as follows:
4071  *    1. Create a console window for use by the subprocess
4072  *    2. Run the subprocess (it gets the allocated console by default)
4073  *    3. Wait for the subprocess to terminate and get its exit code
4074  *    4. Prompt the user to press a key to close the console window
4075  */
4076     static int
4077 mch_system_classic(char *cmd, int options)
4078 {
4079     STARTUPINFO		si;
4080     PROCESS_INFORMATION pi;
4081     DWORD		ret = 0;
4082     HWND		hwnd = GetFocus();
4083 
4084     si.cb = sizeof(si);
4085     si.lpReserved = NULL;
4086     si.lpDesktop = NULL;
4087     si.lpTitle = NULL;
4088     si.dwFlags = STARTF_USESHOWWINDOW;
4089     /*
4090      * It's nicer to run a filter command in a minimized window.
4091      * Don't activate the window to keep focus on Vim.
4092      */
4093     if (options & SHELL_DOOUT)
4094 	si.wShowWindow = SW_SHOWMINNOACTIVE;
4095     else
4096 	si.wShowWindow = SW_SHOWNORMAL;
4097     si.cbReserved2 = 0;
4098     si.lpReserved2 = NULL;
4099 
4100     // Now, run the command
4101     vim_create_process(cmd, FALSE,
4102 	    CREATE_DEFAULT_ERROR_MODE |	CREATE_NEW_CONSOLE,
4103 	    &si, &pi, NULL, NULL);
4104 
4105     // Wait for the command to terminate before continuing
4106     {
4107 # ifdef FEAT_GUI
4108 	int	    delay = 1;
4109 
4110 	// Keep updating the window while waiting for the shell to finish.
4111 	for (;;)
4112 	{
4113 	    MSG	msg;
4114 
4115 	    if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4116 	    {
4117 		TranslateMessage(&msg);
4118 		pDispatchMessage(&msg);
4119 		delay = 1;
4120 		continue;
4121 	    }
4122 	    if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4123 		break;
4124 
4125 	    // We start waiting for a very short time and then increase it, so
4126 	    // that we respond quickly when the process is quick, and don't
4127 	    // consume too much overhead when it's slow.
4128 	    if (delay < 50)
4129 		delay += 10;
4130 	}
4131 # else
4132 	WaitForSingleObject(pi.hProcess, INFINITE);
4133 # endif
4134 
4135 	// Get the command exit code
4136 	GetExitCodeProcess(pi.hProcess, &ret);
4137     }
4138 
4139     // Close the handles to the subprocess, so that it goes away
4140     CloseHandle(pi.hThread);
4141     CloseHandle(pi.hProcess);
4142 
4143     // Try to get input focus back.  Doesn't always work though.
4144     PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4145 
4146     return ret;
4147 }
4148 
4149 /*
4150  * Thread launched by the gui to send the current buffer data to the
4151  * process. This way avoid to hang up vim totally if the children
4152  * process take a long time to process the lines.
4153  */
4154     static unsigned int __stdcall
4155 sub_process_writer(LPVOID param)
4156 {
4157     HANDLE	    g_hChildStd_IN_Wr = param;
4158     linenr_T	    lnum = curbuf->b_op_start.lnum;
4159     DWORD	    len = 0;
4160     DWORD	    l;
4161     char_u	    *lp = ml_get(lnum);
4162     char_u	    *s;
4163     int		    written = 0;
4164 
4165     for (;;)
4166     {
4167 	l = (DWORD)STRLEN(lp + written);
4168 	if (l == 0)
4169 	    len = 0;
4170 	else if (lp[written] == NL)
4171 	{
4172 	    // NL -> NUL translation
4173 	    WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4174 	}
4175 	else
4176 	{
4177 	    s = vim_strchr(lp + written, NL);
4178 	    WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4179 		      s == NULL ? l : (DWORD)(s - (lp + written)),
4180 		      &len, NULL);
4181 	}
4182 	if (len == (int)l)
4183 	{
4184 	    // Finished a line, add a NL, unless this line should not have
4185 	    // one.
4186 	    if (lnum != curbuf->b_op_end.lnum
4187 		|| (!curbuf->b_p_bin
4188 		    && curbuf->b_p_fixeol)
4189 		|| (lnum != curbuf->b_no_eol_lnum
4190 		    && (lnum != curbuf->b_ml.ml_line_count
4191 			|| curbuf->b_p_eol)))
4192 	    {
4193 		WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4194 						  (LPDWORD)&vim_ignored, NULL);
4195 	    }
4196 
4197 	    ++lnum;
4198 	    if (lnum > curbuf->b_op_end.lnum)
4199 		break;
4200 
4201 	    lp = ml_get(lnum);
4202 	    written = 0;
4203 	}
4204 	else if (len > 0)
4205 	    written += len;
4206     }
4207 
4208     // finished all the lines, close pipe
4209     CloseHandle(g_hChildStd_IN_Wr);
4210     return 0;
4211 }
4212 
4213 
4214 # define BUFLEN 100	// length for buffer, stolen from unix version
4215 
4216 /*
4217  * This function read from the children's stdout and write the
4218  * data on screen or in the buffer accordingly.
4219  */
4220     static void
4221 dump_pipe(int	    options,
4222 	  HANDLE    g_hChildStd_OUT_Rd,
4223 	  garray_T  *ga,
4224 	  char_u    buffer[],
4225 	  DWORD	    *buffer_off)
4226 {
4227     DWORD	availableBytes = 0;
4228     DWORD	i;
4229     int		ret;
4230     DWORD	len;
4231     DWORD	toRead;
4232     int		repeatCount;
4233 
4234     // we query the pipe to see if there is any data to read
4235     // to avoid to perform a blocking read
4236     ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4237 			NULL,		    // optional buffer
4238 			0,		    // buffer size
4239 			NULL,		    // number of read bytes
4240 			&availableBytes,    // available bytes total
4241 			NULL);		    // byteLeft
4242 
4243     repeatCount = 0;
4244     // We got real data in the pipe, read it
4245     while (ret != 0 && availableBytes > 0)
4246     {
4247 	repeatCount++;
4248 	toRead = (DWORD)(BUFLEN - *buffer_off);
4249 	toRead = availableBytes < toRead ? availableBytes : toRead;
4250 	ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
4251 
4252 	// If we haven't read anything, there is a problem
4253 	if (len == 0)
4254 	    break;
4255 
4256 	availableBytes -= len;
4257 
4258 	if (options & SHELL_READ)
4259 	{
4260 	    // Do NUL -> NL translation, append NL separated
4261 	    // lines to the current buffer.
4262 	    for (i = 0; i < len; ++i)
4263 	    {
4264 		if (buffer[i] == NL)
4265 		    append_ga_line(ga);
4266 		else if (buffer[i] == NUL)
4267 		    ga_append(ga, NL);
4268 		else
4269 		    ga_append(ga, buffer[i]);
4270 	    }
4271 	}
4272 	else if (has_mbyte)
4273 	{
4274 	    int		l;
4275 	    int		c;
4276 	    char_u	*p;
4277 
4278 	    len += *buffer_off;
4279 	    buffer[len] = NUL;
4280 
4281 	    // Check if the last character in buffer[] is
4282 	    // incomplete, keep these bytes for the next
4283 	    // round.
4284 	    for (p = buffer; p < buffer + len; p += l)
4285 	    {
4286 		l = MB_CPTR2LEN(p);
4287 		if (l == 0)
4288 		    l = 1;  // NUL byte?
4289 		else if (MB_BYTE2LEN(*p) != l)
4290 		    break;
4291 	    }
4292 	    if (p == buffer)	// no complete character
4293 	    {
4294 		// avoid getting stuck at an illegal byte
4295 		if (len >= 12)
4296 		    ++p;
4297 		else
4298 		{
4299 		    *buffer_off = len;
4300 		    return;
4301 		}
4302 	    }
4303 	    c = *p;
4304 	    *p = NUL;
4305 	    msg_puts((char *)buffer);
4306 	    if (p < buffer + len)
4307 	    {
4308 		*p = c;
4309 		*buffer_off = (DWORD)((buffer + len) - p);
4310 		mch_memmove(buffer, p, *buffer_off);
4311 		return;
4312 	    }
4313 	    *buffer_off = 0;
4314 	}
4315 	else
4316 	{
4317 	    buffer[len] = NUL;
4318 	    msg_puts((char *)buffer);
4319 	}
4320 
4321 	windgoto(msg_row, msg_col);
4322 	cursor_on();
4323 	out_flush();
4324     }
4325 }
4326 
4327 /*
4328  * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4329  * for communication and doesn't open any new window.
4330  */
4331     static int
4332 mch_system_piped(char *cmd, int options)
4333 {
4334     STARTUPINFO		si;
4335     PROCESS_INFORMATION pi;
4336     DWORD		ret = 0;
4337 
4338     HANDLE g_hChildStd_IN_Rd = NULL;
4339     HANDLE g_hChildStd_IN_Wr = NULL;
4340     HANDLE g_hChildStd_OUT_Rd = NULL;
4341     HANDLE g_hChildStd_OUT_Wr = NULL;
4342 
4343     char_u	buffer[BUFLEN + 1]; // reading buffer + size
4344     DWORD	len;
4345 
4346     // buffer used to receive keys
4347     char_u	ta_buf[BUFLEN + 1];	// TypeAHead
4348     int		ta_len = 0;		// valid bytes in ta_buf[]
4349 
4350     DWORD	i;
4351     int		noread_cnt = 0;
4352     garray_T	ga;
4353     int		delay = 1;
4354     DWORD	buffer_off = 0;	// valid bytes in buffer[]
4355     char	*p = NULL;
4356 
4357     SECURITY_ATTRIBUTES saAttr;
4358 
4359     // Set the bInheritHandle flag so pipe handles are inherited.
4360     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4361     saAttr.bInheritHandle = TRUE;
4362     saAttr.lpSecurityDescriptor = NULL;
4363 
4364     if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4365 	// Ensure the read handle to the pipe for STDOUT is not inherited.
4366        || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4367 	// Create a pipe for the child process's STDIN.
4368        || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4369 	// Ensure the write handle to the pipe for STDIN is not inherited.
4370        || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4371     {
4372 	CloseHandle(g_hChildStd_IN_Rd);
4373 	CloseHandle(g_hChildStd_IN_Wr);
4374 	CloseHandle(g_hChildStd_OUT_Rd);
4375 	CloseHandle(g_hChildStd_OUT_Wr);
4376 	msg_puts(_("\nCannot create pipes\n"));
4377     }
4378 
4379     si.cb = sizeof(si);
4380     si.lpReserved = NULL;
4381     si.lpDesktop = NULL;
4382     si.lpTitle = NULL;
4383     si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4384 
4385     // set-up our file redirection
4386     si.hStdError = g_hChildStd_OUT_Wr;
4387     si.hStdOutput = g_hChildStd_OUT_Wr;
4388     si.hStdInput = g_hChildStd_IN_Rd;
4389     si.wShowWindow = SW_HIDE;
4390     si.cbReserved2 = 0;
4391     si.lpReserved2 = NULL;
4392 
4393     if (options & SHELL_READ)
4394 	ga_init2(&ga, 1, BUFLEN);
4395 
4396     if (cmd != NULL)
4397     {
4398 	p = (char *)vim_strsave((char_u *)cmd);
4399 	if (p != NULL)
4400 	    unescape_shellxquote((char_u *)p, p_sxe);
4401 	else
4402 	    p = cmd;
4403     }
4404 
4405     // Now, run the command.
4406     // About "Inherit handles" being TRUE: this command can be litigious,
4407     // handle inheritance was deactivated for pending temp file, but, if we
4408     // deactivate it, the pipes don't work for some reason.
4409      vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4410 	     &si, &pi, NULL, NULL);
4411 
4412     if (p != cmd)
4413 	vim_free(p);
4414 
4415     // Close our unused side of the pipes
4416     CloseHandle(g_hChildStd_IN_Rd);
4417     CloseHandle(g_hChildStd_OUT_Wr);
4418 
4419     if (options & SHELL_WRITE)
4420     {
4421 	HANDLE thread = (HANDLE)
4422 	 _beginthreadex(NULL,  // security attributes
4423 			0,     // default stack size
4424 			sub_process_writer, // function to be executed
4425 			g_hChildStd_IN_Wr,  // parameter
4426 			0,		 // creation flag, start immediately
4427 			NULL);		    // we don't care about thread id
4428 	CloseHandle(thread);
4429 	g_hChildStd_IN_Wr = NULL;
4430     }
4431 
4432     // Keep updating the window while waiting for the shell to finish.
4433     for (;;)
4434     {
4435 	MSG	msg;
4436 
4437 	if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4438 	{
4439 	    TranslateMessage(&msg);
4440 	    pDispatchMessage(&msg);
4441 	}
4442 
4443 	// write pipe information in the window
4444 	if ((options & (SHELL_READ|SHELL_WRITE))
4445 # ifdef FEAT_GUI
4446 		|| gui.in_use
4447 # endif
4448 	    )
4449 	{
4450 	    len = 0;
4451 	    if (!(options & SHELL_EXPAND)
4452 		&& ((options &
4453 			(SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4454 		    != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4455 # ifdef FEAT_GUI
4456 		    || gui.in_use
4457 # endif
4458 		    )
4459 		&& (ta_len > 0 || noread_cnt > 4))
4460 	    {
4461 		if (ta_len == 0)
4462 		{
4463 		    // Get extra characters when we don't have any.  Reset the
4464 		    // counter and timer.
4465 		    noread_cnt = 0;
4466 		    len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4467 		}
4468 		if (ta_len > 0 || len > 0)
4469 		{
4470 		    /*
4471 		     * For pipes: Check for CTRL-C: send interrupt signal to
4472 		     * child.  Check for CTRL-D: EOF, close pipe to child.
4473 		     */
4474 		    if (len == 1 && cmd != NULL)
4475 		    {
4476 			if (ta_buf[ta_len] == Ctrl_C)
4477 			{
4478 			    // Learn what exit code is expected, for
4479 			// now put 9 as SIGKILL
4480 			    TerminateProcess(pi.hProcess, 9);
4481 			}
4482 			if (ta_buf[ta_len] == Ctrl_D)
4483 			{
4484 			    CloseHandle(g_hChildStd_IN_Wr);
4485 			    g_hChildStd_IN_Wr = NULL;
4486 			}
4487 		    }
4488 
4489 		    term_replace_bs_del_keycode(ta_buf, ta_len, len);
4490 
4491 		    /*
4492 		     * For pipes: echo the typed characters.  For a pty this
4493 		     * does not seem to work.
4494 		     */
4495 		    for (i = ta_len; i < ta_len + len; ++i)
4496 		    {
4497 			if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4498 			    msg_putchar(ta_buf[i]);
4499 			else if (has_mbyte)
4500 			{
4501 			    int l = (*mb_ptr2len)(ta_buf + i);
4502 
4503 			    msg_outtrans_len(ta_buf + i, l);
4504 			    i += l - 1;
4505 			}
4506 			else
4507 			    msg_outtrans_len(ta_buf + i, 1);
4508 		    }
4509 		    windgoto(msg_row, msg_col);
4510 		    out_flush();
4511 
4512 		    ta_len += len;
4513 
4514 		    /*
4515 		     * Write the characters to the child, unless EOF has been
4516 		     * typed for pipes.  Write one character at a time, to
4517 		     * avoid losing too much typeahead.  When writing buffer
4518 		     * lines, drop the typed characters (only check for
4519 		     * CTRL-C).
4520 		     */
4521 		    if (options & SHELL_WRITE)
4522 			ta_len = 0;
4523 		    else if (g_hChildStd_IN_Wr != NULL)
4524 		    {
4525 			WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4526 				    1, &len, NULL);
4527 			// if we are typing in, we want to keep things reactive
4528 			delay = 1;
4529 			if (len > 0)
4530 			{
4531 			    ta_len -= len;
4532 			    mch_memmove(ta_buf, ta_buf + len, ta_len);
4533 			}
4534 		    }
4535 		}
4536 	    }
4537 	}
4538 
4539 	if (ta_len)
4540 	    ui_inchar_undo(ta_buf, ta_len);
4541 
4542 	if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4543 	{
4544 	    dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
4545 	    break;
4546 	}
4547 
4548 	++noread_cnt;
4549 	dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
4550 
4551 	// We start waiting for a very short time and then increase it, so
4552 	// that we respond quickly when the process is quick, and don't
4553 	// consume too much overhead when it's slow.
4554 	if (delay < 50)
4555 	    delay += 10;
4556     }
4557 
4558     // Close the pipe
4559     CloseHandle(g_hChildStd_OUT_Rd);
4560     if (g_hChildStd_IN_Wr != NULL)
4561 	CloseHandle(g_hChildStd_IN_Wr);
4562 
4563     WaitForSingleObject(pi.hProcess, INFINITE);
4564 
4565     // Get the command exit code
4566     GetExitCodeProcess(pi.hProcess, &ret);
4567 
4568     if (options & SHELL_READ)
4569     {
4570 	if (ga.ga_len > 0)
4571 	{
4572 	    append_ga_line(&ga);
4573 	    // remember that the NL was missing
4574 	    curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4575 	}
4576 	else
4577 	    curbuf->b_no_eol_lnum = 0;
4578 	ga_clear(&ga);
4579     }
4580 
4581     // Close the handles to the subprocess, so that it goes away
4582     CloseHandle(pi.hThread);
4583     CloseHandle(pi.hProcess);
4584 
4585     return ret;
4586 }
4587 
4588     static int
4589 mch_system_g(char *cmd, int options)
4590 {
4591     // if we can pipe and the shelltemp option is off
4592     if (!p_stmp)
4593 	return mch_system_piped(cmd, options);
4594     else
4595 	return mch_system_classic(cmd, options);
4596 }
4597 #endif
4598 
4599 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
4600     static int
4601 mch_system_c(char *cmd, int options UNUSED)
4602 {
4603     int		ret;
4604     WCHAR	*wcmd;
4605     char_u	*buf;
4606     size_t	len;
4607 
4608     // If the command starts and ends with double quotes, enclose the command
4609     // in parentheses.
4610     len = STRLEN(cmd);
4611     if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4612     {
4613 	len += 3;
4614 	buf = alloc(len);
4615 	if (buf == NULL)
4616 	    return -1;
4617 	vim_snprintf((char *)buf, len, "(%s)", cmd);
4618 	wcmd = enc_to_utf16(buf, NULL);
4619 	free(buf);
4620     }
4621     else
4622 	wcmd = enc_to_utf16((char_u *)cmd, NULL);
4623 
4624     if (wcmd == NULL)
4625 	return -1;
4626 
4627     ret = _wsystem(wcmd);
4628     vim_free(wcmd);
4629     return ret;
4630 }
4631 
4632 #endif
4633 
4634     static int
4635 mch_system(char *cmd, int options)
4636 {
4637 #ifdef VIMDLL
4638     if (gui.in_use || gui.starting)
4639 	return mch_system_g(cmd, options);
4640     else
4641 	return mch_system_c(cmd, options);
4642 #elif defined(FEAT_GUI_MSWIN)
4643     return mch_system_g(cmd, options);
4644 #else
4645     return mch_system_c(cmd, options);
4646 #endif
4647 }
4648 
4649 #if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4650 /*
4651  * Use a terminal window to run a shell command in.
4652  */
4653     static int
4654 mch_call_shell_terminal(
4655     char_u	*cmd,
4656     int		options UNUSED)	// SHELL_*, see vim.h
4657 {
4658     jobopt_T	opt;
4659     char_u	*newcmd = NULL;
4660     typval_T	argvar[2];
4661     long_u	cmdlen;
4662     int		retval = -1;
4663     buf_T	*buf;
4664     job_T	*job;
4665     aco_save_T	aco;
4666     oparg_T	oa;		// operator arguments
4667 
4668     if (cmd == NULL)
4669 	cmdlen = STRLEN(p_sh) + 1;
4670     else
4671 	cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
4672     newcmd = alloc(cmdlen);
4673     if (newcmd == NULL)
4674 	return 255;
4675     if (cmd == NULL)
4676     {
4677 	STRCPY(newcmd, p_sh);
4678 	ch_log(NULL, "starting terminal to run a shell");
4679     }
4680     else
4681     {
4682 	vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4683 	ch_log(NULL, "starting terminal for system command '%s'", cmd);
4684     }
4685 
4686     init_job_options(&opt);
4687 
4688     argvar[0].v_type = VAR_STRING;
4689     argvar[0].vval.v_string = newcmd;
4690     argvar[1].v_type = VAR_UNKNOWN;
4691     buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
4692     if (buf == NULL)
4693     {
4694 	vim_free(newcmd);
4695 	return 255;
4696     }
4697 
4698     job = term_getjob(buf->b_term);
4699     ++job->jv_refcount;
4700 
4701     // Find a window to make "buf" curbuf.
4702     aucmd_prepbuf(&aco, buf);
4703 
4704     clear_oparg(&oa);
4705     while (term_use_loop())
4706     {
4707 	if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4708 	{
4709 	    // If terminal_loop() returns OK we got a key that is handled
4710 	    // in Normal model. We don't do redrawing anyway.
4711 	    if (terminal_loop(TRUE) == OK)
4712 		normal_cmd(&oa, TRUE);
4713 	}
4714 	else
4715 	    normal_cmd(&oa, TRUE);
4716     }
4717     retval = job->jv_exitval;
4718     ch_log(NULL, "system command finished");
4719 
4720     job_unref(job);
4721 
4722     // restore curwin/curbuf and a few other things
4723     aucmd_restbuf(&aco);
4724 
4725     wait_return(TRUE);
4726     do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4727 
4728     vim_free(newcmd);
4729     return retval;
4730 }
4731 #endif
4732 
4733 /*
4734  * Either execute a command by calling the shell or start a new shell
4735  */
4736     int
4737 mch_call_shell(
4738     char_u  *cmd,
4739     int	    options)	// SHELL_*, see vim.h
4740 {
4741     int		x = 0;
4742     int		tmode = cur_tmode;
4743 #ifdef FEAT_TITLE
4744     WCHAR	szShellTitle[512];
4745 
4746     // Change the title to reflect that we are in a subshell.
4747     if (GetConsoleTitleW(szShellTitle,
4748 		sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4749     {
4750 	if (cmd == NULL)
4751 	    wcscat(szShellTitle, L" :sh");
4752 	else
4753 	{
4754 	    WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
4755 
4756 	    if (wn != NULL)
4757 	    {
4758 		wcscat(szShellTitle, L" - !");
4759 		if ((wcslen(szShellTitle) + wcslen(wn) <
4760 			    sizeof(szShellTitle)/sizeof(WCHAR)))
4761 		    wcscat(szShellTitle, wn);
4762 		SetConsoleTitleW(szShellTitle);
4763 		vim_free(wn);
4764 	    }
4765 	}
4766     }
4767 #endif
4768 
4769     out_flush();
4770 
4771 #ifdef MCH_WRITE_DUMP
4772     if (fdDump)
4773     {
4774 	fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4775 	fflush(fdDump);
4776     }
4777 #endif
4778 #if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4779     // TODO: make the terminal window work with input or output redirected.
4780     if (
4781 # ifdef VIMDLL
4782 	    gui.in_use &&
4783 # endif
4784 	    vim_strchr(p_go, GO_TERMINAL) != NULL
4785 	 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4786     {
4787 	char_u	*cmdbase = cmd;
4788 
4789 	if (cmdbase != NULL)
4790 	    // Skip a leading quote and (.
4791 	    while (*cmdbase == '"' || *cmdbase == '(')
4792 		++cmdbase;
4793 
4794 	// Check the command does not begin with "start "
4795 	if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4796 						   || !VIM_ISWHITE(cmdbase[5]))
4797 	{
4798 	    // Use a terminal window to run the command in.
4799 	    x = mch_call_shell_terminal(cmd, options);
4800 # ifdef FEAT_TITLE
4801 	    resettitle();
4802 # endif
4803 	    return x;
4804 	}
4805     }
4806 #endif
4807 
4808     /*
4809      * Catch all deadly signals while running the external command, because a
4810      * CTRL-C, Ctrl-Break or illegal instruction  might otherwise kill us.
4811      */
4812     signal(SIGINT, SIG_IGN);
4813 #if defined(__GNUC__) && !defined(__MINGW32__)
4814     signal(SIGKILL, SIG_IGN);
4815 #else
4816     signal(SIGBREAK, SIG_IGN);
4817 #endif
4818     signal(SIGILL, SIG_IGN);
4819     signal(SIGFPE, SIG_IGN);
4820     signal(SIGSEGV, SIG_IGN);
4821     signal(SIGTERM, SIG_IGN);
4822     signal(SIGABRT, SIG_IGN);
4823 
4824     if (options & SHELL_COOKED)
4825 	settmode(TMODE_COOK);	// set to normal mode
4826 
4827     if (cmd == NULL)
4828     {
4829 	x = mch_system((char *)p_sh, options);
4830     }
4831     else
4832     {
4833 	// we use "command" or "cmd" to start the shell; slow but easy
4834 	char_u	*newcmd = NULL;
4835 	char_u	*cmdbase = cmd;
4836 	long_u	cmdlen;
4837 
4838 	// Skip a leading ", ( and "(.
4839 	if (*cmdbase == '"' )
4840 	    ++cmdbase;
4841 	if (*cmdbase == '(')
4842 	    ++cmdbase;
4843 
4844 	if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
4845 	{
4846 	    STARTUPINFO		si;
4847 	    PROCESS_INFORMATION	pi;
4848 	    DWORD		flags = CREATE_NEW_CONSOLE;
4849 	    INT			n_show_cmd = SW_SHOWNORMAL;
4850 	    char_u		*p;
4851 
4852 	    ZeroMemory(&si, sizeof(si));
4853 	    si.cb = sizeof(si);
4854 	    si.lpReserved = NULL;
4855 	    si.lpDesktop = NULL;
4856 	    si.lpTitle = NULL;
4857 	    si.dwFlags = 0;
4858 	    si.cbReserved2 = 0;
4859 	    si.lpReserved2 = NULL;
4860 
4861 	    cmdbase = skipwhite(cmdbase + 5);
4862 	    if ((STRNICMP(cmdbase, "/min", 4) == 0)
4863 		    && VIM_ISWHITE(cmdbase[4]))
4864 	    {
4865 		cmdbase = skipwhite(cmdbase + 4);
4866 		si.dwFlags = STARTF_USESHOWWINDOW;
4867 		si.wShowWindow = SW_SHOWMINNOACTIVE;
4868 		n_show_cmd = SW_SHOWMINNOACTIVE;
4869 	    }
4870 	    else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4871 		    && VIM_ISWHITE(cmdbase[2]))
4872 	    {
4873 		cmdbase = skipwhite(cmdbase + 2);
4874 		flags = CREATE_NO_WINDOW;
4875 		si.dwFlags = STARTF_USESTDHANDLES;
4876 		si.hStdInput = CreateFile("\\\\.\\NUL",	// File name
4877 		    GENERIC_READ,			// Access flags
4878 		    0,					// Share flags
4879 		    NULL,				// Security att.
4880 		    OPEN_EXISTING,			// Open flags
4881 		    FILE_ATTRIBUTE_NORMAL,		// File att.
4882 		    NULL);				// Temp file
4883 		si.hStdOutput = si.hStdInput;
4884 		si.hStdError = si.hStdInput;
4885 	    }
4886 
4887 	    // Remove a trailing ", ) and )" if they have a match
4888 	    // at the start of the command.
4889 	    if (cmdbase > cmd)
4890 	    {
4891 		p = cmdbase + STRLEN(cmdbase);
4892 		if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4893 		    *--p = NUL;
4894 		if (p > cmdbase && p[-1] == ')'
4895 			&& (*cmd =='(' || cmd[1] == '('))
4896 		    *--p = NUL;
4897 	    }
4898 
4899 	    newcmd = cmdbase;
4900 	    unescape_shellxquote(cmdbase, p_sxe);
4901 
4902 	    /*
4903 	     * If creating new console, arguments are passed to the
4904 	     * 'cmd.exe' as-is. If it's not, arguments are not treated
4905 	     * correctly for current 'cmd.exe'. So unescape characters in
4906 	     * shellxescape except '|' for avoiding to be treated as
4907 	     * argument to them. Pass the arguments to sub-shell.
4908 	     */
4909 	    if (flags != CREATE_NEW_CONSOLE)
4910 	    {
4911 		char_u	*subcmd;
4912 		char_u	*cmd_shell = mch_getenv("COMSPEC");
4913 
4914 		if (cmd_shell == NULL || *cmd_shell == NUL)
4915 		    cmd_shell = (char_u *)default_shell();
4916 
4917 		subcmd = vim_strsave_escaped_ext(cmdbase,
4918 			(char_u *)"|", '^', FALSE);
4919 		if (subcmd != NULL)
4920 		{
4921 		    // make "cmd.exe /c arguments"
4922 		    cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
4923 		    newcmd = alloc(cmdlen);
4924 		    if (newcmd != NULL)
4925 			vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
4926 						       cmd_shell, subcmd);
4927 		    else
4928 			newcmd = cmdbase;
4929 		    vim_free(subcmd);
4930 		}
4931 	    }
4932 
4933 	    /*
4934 	     * Now, start the command as a process, so that it doesn't
4935 	     * inherit our handles which causes unpleasant dangling swap
4936 	     * files if we exit before the spawned process
4937 	     */
4938 	    if (vim_create_process((char *)newcmd, FALSE, flags,
4939 			&si, &pi, NULL, NULL))
4940 		x = 0;
4941 	    else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4942 							       > (HINSTANCE)32)
4943 		x = 0;
4944 	    else
4945 	    {
4946 		x = -1;
4947 #ifdef FEAT_GUI_MSWIN
4948 # ifdef VIMDLL
4949 		if (gui.in_use)
4950 # endif
4951 		    emsg(_("E371: Command not found"));
4952 #endif
4953 	    }
4954 
4955 	    if (newcmd != cmdbase)
4956 		vim_free(newcmd);
4957 
4958 	    if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
4959 	    {
4960 		// Close the handle to \\.\NUL created above.
4961 		CloseHandle(si.hStdInput);
4962 	    }
4963 	    // Close the handles to the subprocess, so that it goes away
4964 	    CloseHandle(pi.hThread);
4965 	    CloseHandle(pi.hProcess);
4966 	}
4967 	else
4968 	{
4969 	    cmdlen =
4970 #ifdef FEAT_GUI_MSWIN
4971 		((gui.in_use || gui.starting) ?
4972 		    (!s_dont_use_vimrun && p_stmp ?
4973 			STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4974 		    : 0) +
4975 #endif
4976 		STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
4977 
4978 	    newcmd = alloc(cmdlen);
4979 	    if (newcmd != NULL)
4980 	    {
4981 #if defined(FEAT_GUI_MSWIN)
4982 		if (
4983 # ifdef VIMDLL
4984 		    (gui.in_use || gui.starting) &&
4985 # endif
4986 		    need_vimrun_warning)
4987 		{
4988 		    char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4989 			"External commands will not pause after completion.\n"
4990 			"See  :help win32-vimrun  for more information.");
4991 		    char *title = _("Vim Warning");
4992 		    WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4993 		    WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4994 
4995 		    if (wmsg != NULL && wtitle != NULL)
4996 			MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4997 		    vim_free(wmsg);
4998 		    vim_free(wtitle);
4999 		    need_vimrun_warning = FALSE;
5000 		}
5001 		if (
5002 # ifdef VIMDLL
5003 		    (gui.in_use || gui.starting) &&
5004 # endif
5005 		    !s_dont_use_vimrun && p_stmp)
5006 		    // Use vimrun to execute the command.  It opens a console
5007 		    // window, which can be closed without killing Vim.
5008 		    vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
5009 			    vimrun_path,
5010 			    (msg_silent != 0 || (options & SHELL_DOOUT))
5011 								 ? "-s " : "",
5012 			    p_sh, p_shcf, cmd);
5013 		else if (
5014 # ifdef VIMDLL
5015 			(gui.in_use || gui.starting) &&
5016 # endif
5017 			s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
5018 		    // workaround for the case that "vimrun" does not exist
5019 		    vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5020 					   p_sh, p_shcf, p_sh, p_shcf, cmd);
5021 		else
5022 #endif
5023 		    vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
5024 							   p_sh, p_shcf, cmd);
5025 		x = mch_system((char *)newcmd, options);
5026 		vim_free(newcmd);
5027 	    }
5028 	}
5029     }
5030 
5031     if (tmode == TMODE_RAW)
5032     {
5033 	// The shell may have messed with the mode, always set it.
5034 	cur_tmode = TMODE_UNKNOWN;
5035 	settmode(TMODE_RAW);	// set to raw mode
5036     }
5037 
5038     // Print the return value, unless "vimrun" was used.
5039     if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5040 #if defined(FEAT_GUI_MSWIN)
5041 	    && ((gui.in_use || gui.starting) ?
5042 		((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
5043 #endif
5044 	    )
5045     {
5046 	smsg(_("shell returned %d"), x);
5047 	msg_putchar('\n');
5048     }
5049 #ifdef FEAT_TITLE
5050     resettitle();
5051 #endif
5052 
5053     signal(SIGINT, SIG_DFL);
5054 #if defined(__GNUC__) && !defined(__MINGW32__)
5055     signal(SIGKILL, SIG_DFL);
5056 #else
5057     signal(SIGBREAK, SIG_DFL);
5058 #endif
5059     signal(SIGILL, SIG_DFL);
5060     signal(SIGFPE, SIG_DFL);
5061     signal(SIGSEGV, SIG_DFL);
5062     signal(SIGTERM, SIG_DFL);
5063     signal(SIGABRT, SIG_DFL);
5064 
5065     return x;
5066 }
5067 
5068 #if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
5069     static HANDLE
5070 job_io_file_open(
5071 	char_u *fname,
5072 	DWORD dwDesiredAccess,
5073 	DWORD dwShareMode,
5074 	LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5075 	DWORD dwCreationDisposition,
5076 	DWORD dwFlagsAndAttributes)
5077 {
5078     HANDLE h;
5079     WCHAR *wn;
5080 
5081     wn = enc_to_utf16(fname, NULL);
5082     if (wn == NULL)
5083 	return INVALID_HANDLE_VALUE;
5084 
5085     h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5086 	    lpSecurityAttributes, dwCreationDisposition,
5087 	    dwFlagsAndAttributes, NULL);
5088     vim_free(wn);
5089     return h;
5090 }
5091 
5092 /*
5093  * Turn the dictionary "env" into a NUL separated list that can be used as the
5094  * environment argument of vim_create_process().
5095  */
5096     void
5097 win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
5098 {
5099     hashitem_T	*hi;
5100     long_u	todo = env != NULL ? env->dv_hashtab.ht_used : 0;
5101     LPVOID	base = GetEnvironmentStringsW();
5102 
5103     // for last \0
5104     if (ga_grow(gap, 1) == FAIL)
5105 	return;
5106 
5107     if (env != NULL)
5108     {
5109 	for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
5110 	{
5111 	    if (!HASHITEM_EMPTY(hi))
5112 	    {
5113 		typval_T *item = &dict_lookup(hi)->di_tv;
5114 		WCHAR   *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5115 		WCHAR   *wval = enc_to_utf16(tv_get_string(item), NULL);
5116 		--todo;
5117 		if (wkey != NULL && wval != NULL)
5118 		{
5119 		    size_t	n;
5120 		    size_t	lkey = wcslen(wkey);
5121 		    size_t	lval = wcslen(wval);
5122 
5123 		    if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5124 			continue;
5125 		    for (n = 0; n < lkey; n++)
5126 			*((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5127 		    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5128 		    for (n = 0; n < lval; n++)
5129 			*((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5130 		    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5131 		}
5132 		vim_free(wkey);
5133 		vim_free(wval);
5134 	    }
5135 	}
5136     }
5137 
5138     if (base)
5139     {
5140 	WCHAR	*p = (WCHAR*) base;
5141 
5142 	// for last \0
5143 	if (ga_grow(gap, 1) == FAIL)
5144 	    return;
5145 
5146 	while (*p != 0 || *(p + 1) != 0)
5147 	{
5148 	    if (ga_grow(gap, 1) == OK)
5149 		*((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5150 	    p++;
5151 	}
5152 	FreeEnvironmentStrings(base);
5153 	*((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5154     }
5155 
5156 # if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
5157     {
5158 #  ifdef FEAT_CLIENTSERVER
5159 	char_u	*servername = get_vim_var_str(VV_SEND_SERVER);
5160 	size_t	servername_len = STRLEN(servername);
5161 #  endif
5162 #  ifdef FEAT_TERMINAL
5163 	char_u	*version = get_vim_var_str(VV_VERSION);
5164 	size_t	version_len = STRLEN(version);
5165 #  endif
5166 	// size of "VIM_SERVERNAME=" and value,
5167 	// plus "VIM_TERMINAL=" and value,
5168 	// plus two terminating NULs
5169 	size_t	n = 0
5170 #  ifdef FEAT_CLIENTSERVER
5171 		    + 15 + servername_len
5172 #  endif
5173 #  ifdef FEAT_TERMINAL
5174 		    + 13 + version_len + 2
5175 #  endif
5176 		    ;
5177 
5178 	if (ga_grow(gap, (int)n) == OK)
5179 	{
5180 #  ifdef FEAT_CLIENTSERVER
5181 	    for (n = 0; n < 15; n++)
5182 		*((WCHAR*)gap->ga_data + gap->ga_len++) =
5183 		    (WCHAR)"VIM_SERVERNAME="[n];
5184 	    for (n = 0; n < servername_len; n++)
5185 		*((WCHAR*)gap->ga_data + gap->ga_len++) =
5186 		    (WCHAR)servername[n];
5187 	    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5188 #  endif
5189 #  ifdef FEAT_TERMINAL
5190 	    if (is_terminal)
5191 	    {
5192 		for (n = 0; n < 13; n++)
5193 		    *((WCHAR*)gap->ga_data + gap->ga_len++) =
5194 			(WCHAR)"VIM_TERMINAL="[n];
5195 		for (n = 0; n < version_len; n++)
5196 		    *((WCHAR*)gap->ga_data + gap->ga_len++) =
5197 			(WCHAR)version[n];
5198 		*((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5199 	    }
5200 #  endif
5201 	}
5202     }
5203 # endif
5204 }
5205 
5206 /*
5207  * Create a pair of pipes.
5208  * Return TRUE for success, FALSE for failure.
5209  */
5210     static BOOL
5211 create_pipe_pair(HANDLE handles[2])
5212 {
5213     static LONG		s;
5214     char		name[64];
5215     SECURITY_ATTRIBUTES sa;
5216 
5217     sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5218 	    GetCurrentProcessId(),
5219 	    InterlockedIncrement(&s));
5220 
5221     // Create named pipe. Max size of named pipe is 65535.
5222     handles[1] = CreateNamedPipe(
5223 	    name,
5224 	    PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5225 	    PIPE_TYPE_BYTE | PIPE_NOWAIT,
5226 	    1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
5227 
5228     if (handles[1] == INVALID_HANDLE_VALUE)
5229 	return FALSE;
5230 
5231     sa.nLength = sizeof(sa);
5232     sa.bInheritHandle = TRUE;
5233     sa.lpSecurityDescriptor = NULL;
5234 
5235     handles[0] = CreateFile(name,
5236 	    FILE_GENERIC_READ,
5237 	    FILE_SHARE_READ, &sa,
5238 	    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5239 
5240     if (handles[0] == INVALID_HANDLE_VALUE)
5241     {
5242 	CloseHandle(handles[1]);
5243 	return FALSE;
5244     }
5245 
5246     return TRUE;
5247 }
5248 
5249     void
5250 mch_job_start(char *cmd, job_T *job, jobopt_T *options)
5251 {
5252     STARTUPINFO		si;
5253     PROCESS_INFORMATION	pi;
5254     HANDLE		jo;
5255     SECURITY_ATTRIBUTES saAttr;
5256     channel_T		*channel = NULL;
5257     HANDLE		ifd[2];
5258     HANDLE		ofd[2];
5259     HANDLE		efd[2];
5260     garray_T		ga;
5261 
5262     int		use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5263     int		use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5264     int		use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5265     int		use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5266     int		use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5267     int		use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5268     int		use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5269 
5270     if (use_out_for_err && use_null_for_out)
5271 	use_null_for_err = TRUE;
5272 
5273     ifd[0] = INVALID_HANDLE_VALUE;
5274     ifd[1] = INVALID_HANDLE_VALUE;
5275     ofd[0] = INVALID_HANDLE_VALUE;
5276     ofd[1] = INVALID_HANDLE_VALUE;
5277     efd[0] = INVALID_HANDLE_VALUE;
5278     efd[1] = INVALID_HANDLE_VALUE;
5279     ga_init2(&ga, (int)sizeof(wchar_t), 500);
5280 
5281     jo = CreateJobObject(NULL, NULL);
5282     if (jo == NULL)
5283     {
5284 	job->jv_status = JOB_FAILED;
5285 	goto failed;
5286     }
5287 
5288     if (options->jo_env != NULL)
5289 	win32_build_env(options->jo_env, &ga, FALSE);
5290 
5291     ZeroMemory(&pi, sizeof(pi));
5292     ZeroMemory(&si, sizeof(si));
5293     si.cb = sizeof(si);
5294     si.dwFlags |= STARTF_USESHOWWINDOW;
5295     si.wShowWindow = SW_HIDE;
5296 
5297     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5298     saAttr.bInheritHandle = TRUE;
5299     saAttr.lpSecurityDescriptor = NULL;
5300 
5301     if (use_file_for_in)
5302     {
5303 	char_u *fname = options->jo_io_name[PART_IN];
5304 
5305 	ifd[0] = job_io_file_open(fname, GENERIC_READ,
5306 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5307 		&saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5308 	if (ifd[0] == INVALID_HANDLE_VALUE)
5309 	{
5310 	    semsg(_(e_notopen), fname);
5311 	    goto failed;
5312 	}
5313     }
5314     else if (!use_null_for_in
5315 	    && (!create_pipe_pair(ifd)
5316 		|| !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
5317 	goto failed;
5318 
5319     if (use_file_for_out)
5320     {
5321 	char_u *fname = options->jo_io_name[PART_OUT];
5322 
5323 	ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5324 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5325 		&saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5326 	if (ofd[1] == INVALID_HANDLE_VALUE)
5327 	{
5328 	    semsg(_(e_notopen), fname);
5329 	    goto failed;
5330 	}
5331     }
5332     else if (!use_null_for_out &&
5333 	    (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5334 	    || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
5335 	goto failed;
5336 
5337     if (use_file_for_err)
5338     {
5339 	char_u *fname = options->jo_io_name[PART_ERR];
5340 
5341 	efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5342 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5343 		&saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5344 	if (efd[1] == INVALID_HANDLE_VALUE)
5345 	{
5346 	    semsg(_(e_notopen), fname);
5347 	    goto failed;
5348 	}
5349     }
5350     else if (!use_out_for_err && !use_null_for_err &&
5351 	    (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5352 	    || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
5353 	goto failed;
5354 
5355     si.dwFlags |= STARTF_USESTDHANDLES;
5356     si.hStdInput = ifd[0];
5357     si.hStdOutput = ofd[1];
5358     si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5359 
5360     if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5361     {
5362 	if (options->jo_set & JO_CHANNEL)
5363 	{
5364 	    channel = options->jo_channel;
5365 	    if (channel != NULL)
5366 		++channel->ch_refcount;
5367 	}
5368 	else
5369 	    channel = add_channel();
5370 	if (channel == NULL)
5371 	    goto failed;
5372     }
5373 
5374     if (!vim_create_process(cmd, TRUE,
5375 	    CREATE_SUSPENDED |
5376 	    CREATE_DEFAULT_ERROR_MODE |
5377 	    CREATE_NEW_PROCESS_GROUP |
5378 	    CREATE_UNICODE_ENVIRONMENT |
5379 	    CREATE_NEW_CONSOLE,
5380 	    &si, &pi,
5381 	    ga.ga_data,
5382 	    (char *)options->jo_cwd))
5383     {
5384 	CloseHandle(jo);
5385 	job->jv_status = JOB_FAILED;
5386 	goto failed;
5387     }
5388 
5389     ga_clear(&ga);
5390 
5391     if (!AssignProcessToJobObject(jo, pi.hProcess))
5392     {
5393 	// if failing, switch the way to terminate
5394 	// process with TerminateProcess.
5395 	CloseHandle(jo);
5396 	jo = NULL;
5397     }
5398     ResumeThread(pi.hThread);
5399     CloseHandle(pi.hThread);
5400     job->jv_proc_info = pi;
5401     job->jv_job_object = jo;
5402     job->jv_status = JOB_STARTED;
5403 
5404     CloseHandle(ifd[0]);
5405     CloseHandle(ofd[1]);
5406     if (!use_out_for_err && !use_null_for_err)
5407 	CloseHandle(efd[1]);
5408 
5409     job->jv_channel = channel;
5410     if (channel != NULL)
5411     {
5412 	channel_set_pipes(channel,
5413 		      use_file_for_in || use_null_for_in
5414 					      ? INVALID_FD : (sock_T)ifd[1],
5415 		      use_file_for_out || use_null_for_out
5416 					     ? INVALID_FD : (sock_T)ofd[0],
5417 		      use_out_for_err || use_file_for_err || use_null_for_err
5418 					    ? INVALID_FD : (sock_T)efd[0]);
5419 	channel_set_job(channel, job, options);
5420     }
5421     return;
5422 
5423 failed:
5424     CloseHandle(ifd[0]);
5425     CloseHandle(ofd[0]);
5426     CloseHandle(efd[0]);
5427     CloseHandle(ifd[1]);
5428     CloseHandle(ofd[1]);
5429     CloseHandle(efd[1]);
5430     channel_unref(channel);
5431     ga_clear(&ga);
5432 }
5433 
5434     char *
5435 mch_job_status(job_T *job)
5436 {
5437     DWORD dwExitCode = 0;
5438 
5439     if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5440 	    || dwExitCode != STILL_ACTIVE)
5441     {
5442 	job->jv_exitval = (int)dwExitCode;
5443 	if (job->jv_status < JOB_ENDED)
5444 	{
5445 	    ch_log(job->jv_channel, "Job ended");
5446 	    job->jv_status = JOB_ENDED;
5447 	}
5448 	return "dead";
5449     }
5450     return "run";
5451 }
5452 
5453     job_T *
5454 mch_detect_ended_job(job_T *job_list)
5455 {
5456     HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5457     job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5458     job_T *job = job_list;
5459 
5460     while (job != NULL)
5461     {
5462 	DWORD n;
5463 	DWORD result;
5464 
5465 	for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5466 				       && job != NULL; job = job->jv_next)
5467 	{
5468 	    if (job->jv_status == JOB_STARTED)
5469 	    {
5470 		jobHandles[n] = job->jv_proc_info.hProcess;
5471 		jobArray[n] = job;
5472 		++n;
5473 	    }
5474 	}
5475 	if (n == 0)
5476 	    continue;
5477 	result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5478 	if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5479 	{
5480 	    job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5481 
5482 	    if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5483 		return wait_job;
5484 	}
5485     }
5486     return NULL;
5487 }
5488 
5489     static BOOL
5490 terminate_all(HANDLE process, int code)
5491 {
5492     PROCESSENTRY32  pe;
5493     HANDLE	    h = INVALID_HANDLE_VALUE;
5494     DWORD	    pid = GetProcessId(process);
5495 
5496     if (pid != 0)
5497     {
5498 	h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5499 	if (h != INVALID_HANDLE_VALUE)
5500 	{
5501 	    pe.dwSize = sizeof(PROCESSENTRY32);
5502 	    if (!Process32First(h, &pe))
5503 		goto theend;
5504 
5505 	    do
5506 	    {
5507 		if (pe.th32ParentProcessID == pid)
5508 		{
5509 		    HANDLE ph = OpenProcess(
5510 				  PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5511 		    if (ph != NULL)
5512 		    {
5513 			terminate_all(ph, code);
5514 			CloseHandle(ph);
5515 		    }
5516 		}
5517 	    } while (Process32Next(h, &pe));
5518 
5519 	    CloseHandle(h);
5520 	}
5521     }
5522 
5523 theend:
5524     return TerminateProcess(process, code);
5525 }
5526 
5527 /*
5528  * Send a (deadly) signal to "job".
5529  * Return FAIL if it didn't work.
5530  */
5531     int
5532 mch_signal_job(job_T *job, char_u *how)
5533 {
5534     int ret;
5535 
5536     if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
5537     {
5538 	// deadly signal
5539 	if (job->jv_job_object != NULL)
5540 	{
5541 	    if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5542 		job->jv_channel->ch_killing = TRUE;
5543 	    return TerminateJobObject(job->jv_job_object, -1) ? OK : FAIL;
5544 	}
5545 	return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
5546     }
5547 
5548     if (!AttachConsole(job->jv_proc_info.dwProcessId))
5549 	return FAIL;
5550     ret = GenerateConsoleCtrlEvent(
5551 		STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5552 		job->jv_proc_info.dwProcessId)
5553 	    ? OK : FAIL;
5554     FreeConsole();
5555     return ret;
5556 }
5557 
5558 /*
5559  * Clear the data related to "job".
5560  */
5561     void
5562 mch_clear_job(job_T *job)
5563 {
5564     if (job->jv_status != JOB_FAILED)
5565     {
5566 	if (job->jv_job_object != NULL)
5567 	    CloseHandle(job->jv_job_object);
5568 	CloseHandle(job->jv_proc_info.hProcess);
5569     }
5570 }
5571 #endif
5572 
5573 
5574 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
5575 
5576 /*
5577  * Start termcap mode
5578  */
5579     static void
5580 termcap_mode_start(void)
5581 {
5582     DWORD cmodein;
5583 
5584     if (g_fTermcapMode)
5585 	return;
5586 
5587     if (!p_rs && USE_VTP)
5588 	vtp_printf("\033[?1049h");
5589 
5590     SaveConsoleBuffer(&g_cbNonTermcap);
5591 
5592     if (g_cbTermcap.IsValid)
5593     {
5594 	/*
5595 	 * We've been in termcap mode before.  Restore certain screen
5596 	 * characteristics, including the buffer size and the window
5597 	 * size.  Since we will be redrawing the screen, we don't need
5598 	 * to restore the actual contents of the buffer.
5599 	 */
5600 	RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5601 	reset_console_color_rgb();
5602 	SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5603 	Rows = g_cbTermcap.Info.dwSize.Y;
5604 	Columns = g_cbTermcap.Info.dwSize.X;
5605     }
5606     else
5607     {
5608 	/*
5609 	 * This is our first time entering termcap mode.  Clear the console
5610 	 * screen buffer, and resize the buffer to match the current window
5611 	 * size.  We will use this as the size of our editing environment.
5612 	 */
5613 	ClearConsoleBuffer(g_attrCurrent);
5614 	set_console_color_rgb();
5615 	ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5616     }
5617 
5618 # ifdef FEAT_TITLE
5619     resettitle();
5620 # endif
5621 
5622     GetConsoleMode(g_hConIn, &cmodein);
5623     if (g_fMouseActive)
5624 	cmodein |= ENABLE_MOUSE_INPUT;
5625     else
5626 	cmodein &= ~ENABLE_MOUSE_INPUT;
5627     cmodein |= ENABLE_WINDOW_INPUT;
5628     SetConsoleMode(g_hConIn, cmodein);
5629 
5630     redraw_later_clear();
5631     g_fTermcapMode = TRUE;
5632 }
5633 
5634 
5635 /*
5636  * End termcap mode
5637  */
5638     static void
5639 termcap_mode_end(void)
5640 {
5641     DWORD cmodein;
5642     ConsoleBuffer *cb;
5643     COORD coord;
5644     DWORD dwDummy;
5645 
5646     if (!g_fTermcapMode)
5647 	return;
5648 
5649     SaveConsoleBuffer(&g_cbTermcap);
5650 
5651     GetConsoleMode(g_hConIn, &cmodein);
5652     cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5653     SetConsoleMode(g_hConIn, cmodein);
5654 
5655 # ifdef FEAT_RESTORE_ORIG_SCREEN
5656     cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5657 # else
5658     cb = &g_cbNonTermcap;
5659 # endif
5660     RestoreConsoleBuffer(cb, p_rs);
5661     restore_console_color_rgb();
5662     SetConsoleCursorInfo(g_hConOut, &g_cci);
5663 
5664     if (p_rs || exiting)
5665     {
5666 	/*
5667 	 * Clear anything that happens to be on the current line.
5668 	 */
5669 	coord.X = 0;
5670 	coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5671 	FillConsoleOutputCharacter(g_hConOut, ' ',
5672 		cb->Info.dwSize.X, coord, &dwDummy);
5673 	/*
5674 	 * The following is just for aesthetics.  If we are exiting without
5675 	 * restoring the screen, then we want to have a prompt string
5676 	 * appear at the bottom line.  However, the command interpreter
5677 	 * seems to always advance the cursor one line before displaying
5678 	 * the prompt string, which causes the screen to scroll.  To
5679 	 * counter this, move the cursor up one line before exiting.
5680 	 */
5681 	if (exiting && !p_rs)
5682 	    coord.Y--;
5683 	/*
5684 	 * Position the cursor at the leftmost column of the desired row.
5685 	 */
5686 	SetConsoleCursorPosition(g_hConOut, coord);
5687     }
5688 
5689     if (!p_rs && USE_VTP)
5690 	vtp_printf("\033[?1049l");
5691 
5692     g_fTermcapMode = FALSE;
5693 }
5694 #endif // FEAT_GUI_MSWIN
5695 
5696 
5697 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
5698     void
5699 mch_write(
5700     char_u  *s UNUSED,
5701     int	    len UNUSED)
5702 {
5703     // never used
5704 }
5705 
5706 #else
5707 
5708 /*
5709  * clear `n' chars, starting from `coord'
5710  */
5711     static void
5712 clear_chars(
5713     COORD coord,
5714     DWORD n)
5715 {
5716     if (!USE_VTP)
5717     {
5718 	DWORD dwDummy;
5719 
5720 	FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5721 	FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5722 								     &dwDummy);
5723     }
5724     else
5725     {
5726 	set_console_color_rgb();
5727 	gotoxy(coord.X + 1, coord.Y + 1);
5728 	vtp_printf("\033[%dX", n);
5729     }
5730 }
5731 
5732 
5733 /*
5734  * Clear the screen
5735  */
5736     static void
5737 clear_screen(void)
5738 {
5739     g_coord.X = g_coord.Y = 0;
5740 
5741     if (!USE_VTP)
5742 	clear_chars(g_coord, Rows * Columns);
5743     else
5744     {
5745 	set_console_color_rgb();
5746 	gotoxy(1, 1);
5747 	vtp_printf("\033[2J");
5748     }
5749 }
5750 
5751 
5752 /*
5753  * Clear to end of display
5754  */
5755     static void
5756 clear_to_end_of_display(void)
5757 {
5758     COORD save = g_coord;
5759 
5760     if (!USE_VTP)
5761 	clear_chars(g_coord, (Rows - g_coord.Y - 1)
5762 					   * Columns + (Columns - g_coord.X));
5763     else
5764     {
5765 	set_console_color_rgb();
5766 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
5767 	vtp_printf("\033[0J");
5768 
5769 	gotoxy(save.X + 1, save.Y + 1);
5770 	g_coord = save;
5771     }
5772 }
5773 
5774 
5775 /*
5776  * Clear to end of line
5777  */
5778     static void
5779 clear_to_end_of_line(void)
5780 {
5781     COORD save = g_coord;
5782 
5783     if (!USE_VTP)
5784 	clear_chars(g_coord, Columns - g_coord.X);
5785     else
5786     {
5787 	set_console_color_rgb();
5788 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
5789 	vtp_printf("\033[0K");
5790 
5791 	gotoxy(save.X + 1, save.Y + 1);
5792 	g_coord = save;
5793     }
5794 }
5795 
5796 
5797 /*
5798  * Scroll the scroll region up by `cLines' lines
5799  */
5800     static void
5801 scroll(unsigned cLines)
5802 {
5803     COORD oldcoord = g_coord;
5804 
5805     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5806     delete_lines(cLines);
5807 
5808     g_coord = oldcoord;
5809 }
5810 
5811 
5812 /*
5813  * Set the scroll region
5814  */
5815     static void
5816 set_scroll_region(
5817     unsigned left,
5818     unsigned top,
5819     unsigned right,
5820     unsigned bottom)
5821 {
5822     if (left >= right
5823 	    || top >= bottom
5824 	    || right > (unsigned) Columns - 1
5825 	    || bottom > (unsigned) Rows - 1)
5826 	return;
5827 
5828     g_srScrollRegion.Left =   left;
5829     g_srScrollRegion.Top =    top;
5830     g_srScrollRegion.Right =  right;
5831     g_srScrollRegion.Bottom = bottom;
5832 }
5833 
5834     static void
5835 set_scroll_region_tb(
5836     unsigned top,
5837     unsigned bottom)
5838 {
5839     if (top >= bottom || bottom > (unsigned)Rows - 1)
5840 	return;
5841 
5842     g_srScrollRegion.Top = top;
5843     g_srScrollRegion.Bottom = bottom;
5844 }
5845 
5846     static void
5847 set_scroll_region_lr(
5848     unsigned left,
5849     unsigned right)
5850 {
5851     if (left >= right || right > (unsigned)Columns - 1)
5852 	return;
5853 
5854     g_srScrollRegion.Left = left;
5855     g_srScrollRegion.Right = right;
5856 }
5857 
5858 
5859 /*
5860  * Insert `cLines' lines at the current cursor position
5861  */
5862     static void
5863 insert_lines(unsigned cLines)
5864 {
5865     SMALL_RECT	    source, clip;
5866     COORD	    dest;
5867     CHAR_INFO	    fill;
5868 
5869     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5870 
5871     dest.X = g_srScrollRegion.Left;
5872     dest.Y = g_coord.Y + cLines;
5873 
5874     source.Left   = g_srScrollRegion.Left;
5875     source.Top	  = g_coord.Y;
5876     source.Right  = g_srScrollRegion.Right;
5877     source.Bottom = g_srScrollRegion.Bottom - cLines;
5878 
5879     clip.Left   = g_srScrollRegion.Left;
5880     clip.Top    = g_coord.Y;
5881     clip.Right  = g_srScrollRegion.Right;
5882     clip.Bottom = g_srScrollRegion.Bottom;
5883 
5884     fill.Char.AsciiChar = ' ';
5885     if (!USE_VTP)
5886 	fill.Attributes = g_attrCurrent;
5887     else
5888 	fill.Attributes = g_attrDefault;
5889 
5890     set_console_color_rgb();
5891 
5892     ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5893 
5894     // Here we have to deal with a win32 console flake: If the scroll
5895     // region looks like abc and we scroll c to a and fill with d we get
5896     // cbd... if we scroll block c one line at a time to a, we get cdd...
5897     // vim expects cdd consistently... So we have to deal with that
5898     // here... (this also occurs scrolling the same way in the other
5899     // direction).
5900 
5901     if (source.Bottom < dest.Y)
5902     {
5903 	COORD coord;
5904 	int   i;
5905 
5906 	coord.X = source.Left;
5907 	for (i = clip.Top; i < dest.Y; ++i)
5908 	{
5909 	    coord.Y = i;
5910 	    clear_chars(coord, source.Right - source.Left + 1);
5911 	}
5912     }
5913 
5914     if (USE_WT)
5915     {
5916 	COORD coord;
5917 	int i;
5918 
5919 	coord.X = source.Left;
5920 	for (i = source.Top; i < dest.Y; ++i)
5921 	{
5922 	    coord.Y = i;
5923 	    clear_chars(coord, source.Right - source.Left + 1);
5924 	}
5925     }
5926 }
5927 
5928 
5929 /*
5930  * Delete `cLines' lines at the current cursor position
5931  */
5932     static void
5933 delete_lines(unsigned cLines)
5934 {
5935     SMALL_RECT	    source, clip;
5936     COORD	    dest;
5937     CHAR_INFO	    fill;
5938     int		    nb;
5939 
5940     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5941 
5942     dest.X = g_srScrollRegion.Left;
5943     dest.Y = g_coord.Y;
5944 
5945     source.Left   = g_srScrollRegion.Left;
5946     source.Top	  = g_coord.Y + cLines;
5947     source.Right  = g_srScrollRegion.Right;
5948     source.Bottom = g_srScrollRegion.Bottom;
5949 
5950     clip.Left   = g_srScrollRegion.Left;
5951     clip.Top    = g_coord.Y;
5952     clip.Right  = g_srScrollRegion.Right;
5953     clip.Bottom = g_srScrollRegion.Bottom;
5954 
5955     fill.Char.AsciiChar = ' ';
5956     if (!USE_VTP)
5957 	fill.Attributes = g_attrCurrent;
5958     else
5959 	fill.Attributes = g_attrDefault;
5960 
5961     set_console_color_rgb();
5962 
5963     ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5964 
5965     // Here we have to deal with a win32 console flake; See insert_lines()
5966     // above.
5967 
5968     nb = dest.Y + (source.Bottom - source.Top) + 1;
5969 
5970     if (nb < source.Top)
5971     {
5972 	COORD coord;
5973 	int   i;
5974 
5975 	coord.X = source.Left;
5976 	for (i = nb; i < clip.Bottom; ++i)
5977 	{
5978 	    coord.Y = i;
5979 	    clear_chars(coord, source.Right - source.Left + 1);
5980 	}
5981     }
5982 
5983     if (USE_WT)
5984     {
5985 	COORD coord;
5986 	int i;
5987 
5988 	coord.X = source.Left;
5989 	for (i = nb; i <= source.Bottom; ++i)
5990 	{
5991 	    coord.Y = i;
5992 	    clear_chars(coord, source.Right - source.Left + 1);
5993 	}
5994     }
5995 }
5996 
5997 
5998 /*
5999  * Set the cursor position to (x,y) (1-based).
6000  */
6001     static void
6002 gotoxy(
6003     unsigned x,
6004     unsigned y)
6005 {
6006     if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6007 	return;
6008 
6009     if (!USE_VTP)
6010     {
6011 	// There are reports of double-width characters not displayed
6012 	// correctly.  This workaround should fix it, similar to how it's done
6013 	// for VTP.
6014 	g_coord.X = 0;
6015 	SetConsoleCursorPosition(g_hConOut, g_coord);
6016 
6017 	// external cursor coords are 1-based; internal are 0-based
6018 	g_coord.X = x - 1;
6019 	g_coord.Y = y - 1;
6020 	SetConsoleCursorPosition(g_hConOut, g_coord);
6021     }
6022     else
6023     {
6024 	// Move the cursor to the left edge of the screen to prevent screen
6025 	// destruction.  Insider build bug.  Always enabled because it's cheap
6026 	// and avoids mistakes with recognizing the build.
6027 	vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
6028 
6029 	vtp_printf("\033[%d;%dH", y, x);
6030 
6031 	g_coord.X = x - 1;
6032 	g_coord.Y = y - 1;
6033     }
6034 }
6035 
6036 
6037 /*
6038  * Set the current text attribute = (foreground | background)
6039  * See ../runtime/doc/os_win32.txt for the numbers.
6040  */
6041     static void
6042 textattr(WORD wAttr)
6043 {
6044     g_attrCurrent = wAttr & 0xff;
6045 
6046     SetConsoleTextAttribute(g_hConOut, wAttr);
6047 }
6048 
6049 
6050     static void
6051 textcolor(WORD wAttr)
6052 {
6053     g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
6054 
6055     if (!USE_VTP)
6056 	SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6057     else
6058 	vtp_sgr_bulk(wAttr);
6059 }
6060 
6061 
6062     static void
6063 textbackground(WORD wAttr)
6064 {
6065     g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
6066 
6067     if (!USE_VTP)
6068 	SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6069     else
6070 	vtp_sgr_bulk(wAttr);
6071 }
6072 
6073 
6074 /*
6075  * restore the default text attribute (whatever we started with)
6076  */
6077     static void
6078 normvideo(void)
6079 {
6080     if (!USE_VTP)
6081 	textattr(g_attrDefault);
6082     else
6083 	vtp_sgr_bulk(0);
6084 }
6085 
6086 
6087 static WORD g_attrPreStandout = 0;
6088 
6089 /*
6090  * Make the text standout, by brightening it
6091  */
6092     static void
6093 standout(void)
6094 {
6095     g_attrPreStandout = g_attrCurrent;
6096 
6097     textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6098 }
6099 
6100 
6101 /*
6102  * Turn off standout mode
6103  */
6104     static void
6105 standend(void)
6106 {
6107     if (g_attrPreStandout)
6108 	textattr(g_attrPreStandout);
6109 
6110     g_attrPreStandout = 0;
6111 }
6112 
6113 
6114 /*
6115  * Set normal fg/bg color, based on T_ME.  Called when t_me has been set.
6116  */
6117     void
6118 mch_set_normal_colors(void)
6119 {
6120     char_u	*p;
6121     int		n;
6122 
6123     cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6124     cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
6125     if (
6126 # ifdef FEAT_TERMGUICOLORS
6127 	!p_tgc &&
6128 # endif
6129 	T_ME[0] == ESC && T_ME[1] == '|')
6130     {
6131 	p = T_ME + 2;
6132 	n = getdigits(&p);
6133 	if (*p == 'm' && n > 0)
6134 	{
6135 	    cterm_normal_fg_color = (n & 0xf) + 1;
6136 	    cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6137 	}
6138     }
6139 # ifdef FEAT_TERMGUICOLORS
6140     cterm_normal_fg_gui_color = INVALCOLOR;
6141     cterm_normal_bg_gui_color = INVALCOLOR;
6142 # endif
6143 }
6144 
6145 
6146 /*
6147  * visual bell: flash the screen
6148  */
6149     static void
6150 visual_bell(void)
6151 {
6152     COORD   coordOrigin = {0, 0};
6153     WORD    attrFlash = ~g_attrCurrent & 0xff;
6154 
6155     DWORD   dwDummy;
6156     LPWORD  oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6157 
6158     if (oldattrs == NULL)
6159 	return;
6160     ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6161 			       coordOrigin, &dwDummy);
6162     FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6163 			       coordOrigin, &dwDummy);
6164 
6165     Sleep(15);	    // wait for 15 msec
6166     if (!USE_VTP)
6167 	WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6168 				coordOrigin, &dwDummy);
6169     vim_free(oldattrs);
6170 }
6171 
6172 
6173 /*
6174  * Make the cursor visible or invisible
6175  */
6176     static void
6177 cursor_visible(BOOL fVisible)
6178 {
6179     s_cursor_visible = fVisible;
6180 
6181     if (USE_VTP)
6182 	vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6183 
6184 # ifdef MCH_CURSOR_SHAPE
6185     mch_update_cursor();
6186 # endif
6187 }
6188 
6189 
6190 /*
6191  * Write "cbToWrite" bytes in `pchBuf' to the screen.
6192  * Returns the number of bytes actually written (at least one).
6193  */
6194     static DWORD
6195 write_chars(
6196     char_u *pchBuf,
6197     DWORD  cbToWrite)
6198 {
6199     COORD	    coord = g_coord;
6200     DWORD	    written;
6201     DWORD	    n, cchwritten;
6202     static DWORD    cells;
6203     static WCHAR    *unicodebuf = NULL;
6204     static int	    unibuflen = 0;
6205     static int	    length;
6206     int		    cp = enc_utf8 ? CP_UTF8 : enc_codepage;
6207     static WCHAR    *utf8spbuf = NULL;
6208     static int	    utf8splength;
6209     static DWORD    utf8spcells;
6210     static WCHAR    **utf8usingbuf = &unicodebuf;
6211 
6212     if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
6213     {
6214 	utf8usingbuf = &unicodebuf;
6215 	do
6216 	{
6217 	    length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6218 							unicodebuf, unibuflen);
6219 	    if (length && length <= unibuflen)
6220 		break;
6221 	    vim_free(unicodebuf);
6222 	    unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6223 	    unibuflen = unibuflen ? 0 : length;
6224 	} while(1);
6225 	cells = mb_string2cells(pchBuf, cbToWrite);
6226     }
6227     else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6228     {
6229 	if (utf8usingbuf != &utf8spbuf)
6230 	{
6231 	    if (utf8spbuf == NULL)
6232 	    {
6233 		cells = mb_string2cells((char_u *)" ", 1);
6234 		length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6235 		utf8spbuf = LALLOC_MULT(WCHAR, length);
6236 		if (utf8spbuf != NULL)
6237 		{
6238 		    MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6239 		    utf8usingbuf = &utf8spbuf;
6240 		    utf8splength = length;
6241 		    utf8spcells = cells;
6242 		}
6243 	    }
6244 	    else
6245 	    {
6246 		utf8usingbuf = &utf8spbuf;
6247 		length = utf8splength;
6248 		cells = utf8spcells;
6249 	    }
6250 	}
6251     }
6252 
6253     if (!USE_VTP)
6254     {
6255 	FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6256 				    coord, &written);
6257 	// When writing fails or didn't write a single character, pretend one
6258 	// character was written, otherwise we get stuck.
6259 	if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
6260 		    coord, &cchwritten) == 0
6261 		|| cchwritten == 0 || cchwritten == (DWORD)-1)
6262 	    cchwritten = 1;
6263     }
6264     else
6265     {
6266 	if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
6267 		    NULL) == 0 || cchwritten == 0)
6268 	    cchwritten = 1;
6269     }
6270 
6271     if (cchwritten == length)
6272     {
6273 	written = cbToWrite;
6274 	g_coord.X += (SHORT)cells;
6275     }
6276     else
6277     {
6278 	char_u *p = pchBuf;
6279 	for (n = 0; n < cchwritten; n++)
6280 	    MB_CPTR_ADV(p);
6281 	written = p - pchBuf;
6282 	g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6283     }
6284 
6285     while (g_coord.X > g_srScrollRegion.Right)
6286     {
6287 	g_coord.X -= (SHORT) Columns;
6288 	if (g_coord.Y < g_srScrollRegion.Bottom)
6289 	    g_coord.Y++;
6290     }
6291 
6292     // Cursor under VTP is always in the correct position, no need to reset.
6293     if (!USE_VTP)
6294 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
6295 
6296     return written;
6297 }
6298 
6299     static char_u *
6300 get_seq(
6301     int *args,
6302     int *count,
6303     char_u *head)
6304 {
6305     int argc;
6306     char_u *p;
6307 
6308     if (head == NULL || *head != '\033')
6309 	return NULL;
6310 
6311     argc = 0;
6312     p = head;
6313     ++p;
6314     do
6315     {
6316 	++p;
6317 	args[argc] = getdigits(&p);
6318 	argc += (argc < 15) ? 1 : 0;
6319     } while (*p == ';');
6320     *count = argc;
6321 
6322     return p;
6323 }
6324 
6325     static char_u *
6326 get_sgr(
6327     int *args,
6328     int *count,
6329     char_u *head)
6330 {
6331     char_u *p = get_seq(args, count, head);
6332 
6333     return (p && *p == 'm') ? ++p : NULL;
6334 }
6335 
6336 /*
6337  * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6338  */
6339     static char_u *
6340 sgrn2(
6341     char_u *head,
6342     int	   n)
6343 {
6344     int argc;
6345     int args[16];
6346     char_u *p = get_sgr(args, &argc, head);
6347 
6348     return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6349 }
6350 
6351 /*
6352  * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6353  */
6354     static char_u *
6355 sgrnc(
6356     char_u *head,
6357     int	   n)
6358 {
6359     int argc;
6360     int args[16];
6361     char_u *p = get_sgr(args, &argc, head);
6362 
6363     return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6364 								    ? p : NULL;
6365 }
6366 
6367     static char_u *
6368 skipblank(char_u *q)
6369 {
6370     char_u *p = q;
6371 
6372     while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6373 	++p;
6374     return p;
6375 }
6376 
6377 /*
6378  * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6379  * NULL.
6380  */
6381     static char_u *
6382 sgrn2c(
6383     char_u *head,
6384     int	   n)
6385 {
6386     char_u *p = sgrn2(head, n);
6387 
6388     return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6389 }
6390 
6391 /*
6392  * If there is only a newline between the sequence immediately following it,
6393  * a pointer to the character following the newline is returned.
6394  * Otherwise NULL.
6395  */
6396     static char_u *
6397 sgrn2cn(
6398     char_u *head,
6399     int n)
6400 {
6401     char_u *p = sgrn2(head, n);
6402 
6403     return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6404 }
6405 
6406 /*
6407  * mch_write(): write the output buffer to the screen, translating ESC
6408  * sequences into calls to console output routines.
6409  */
6410     void
6411 mch_write(
6412     char_u  *s,
6413     int	    len)
6414 {
6415     char_u  *end = s + len;
6416 
6417 # ifdef VIMDLL
6418     if (gui.in_use)
6419 	return;
6420 # endif
6421 
6422     if (!term_console)
6423     {
6424 	write(1, s, (unsigned)len);
6425 	return;
6426     }
6427 
6428     // translate ESC | sequences into faked bios calls
6429     while (len--)
6430     {
6431 	int prefix = -1;
6432 	char_u ch;
6433 
6434 	// While processing a sequence, on rare occasions it seems that another
6435 	// sequence may be inserted asynchronously.
6436 	if (len < 0)
6437 	{
6438 	    redraw_all_later(CLEAR);
6439 	    return;
6440 	}
6441 
6442 	while (s + ++prefix < end)
6443 	{
6444 	    ch = s[prefix];
6445 	    if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6446 						&& ch != '\a' && ch != '\033'))
6447 		break;
6448 	}
6449 
6450 	if (p_wd)
6451 	{
6452 	    WaitForChar(p_wd, FALSE);
6453 	    if (prefix != 0)
6454 		prefix = 1;
6455 	}
6456 
6457 	if (prefix != 0)
6458 	{
6459 	    DWORD nWritten;
6460 
6461 	    nWritten = write_chars(s, prefix);
6462 # ifdef MCH_WRITE_DUMP
6463 	    if (fdDump)
6464 	    {
6465 		fputc('>', fdDump);
6466 		fwrite(s, sizeof(char_u), nWritten, fdDump);
6467 		fputs("<\n", fdDump);
6468 	    }
6469 # endif
6470 	    len -= (nWritten - 1);
6471 	    s += nWritten;
6472 	}
6473 	else if (s[0] == '\n')
6474 	{
6475 	    // \n, newline: go to the beginning of the next line or scroll
6476 	    if (g_coord.Y == g_srScrollRegion.Bottom)
6477 	    {
6478 		scroll(1);
6479 		gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6480 	    }
6481 	    else
6482 	    {
6483 		gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6484 	    }
6485 # ifdef MCH_WRITE_DUMP
6486 	    if (fdDump)
6487 		fputs("\\n\n", fdDump);
6488 # endif
6489 	    s++;
6490 	}
6491 	else if (s[0] == '\r')
6492 	{
6493 	    // \r, carriage return: go to beginning of line
6494 	    gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6495 # ifdef MCH_WRITE_DUMP
6496 	    if (fdDump)
6497 		fputs("\\r\n", fdDump);
6498 # endif
6499 	    s++;
6500 	}
6501 	else if (s[0] == '\b')
6502 	{
6503 	    // \b, backspace: move cursor one position left
6504 	    if (g_coord.X > g_srScrollRegion.Left)
6505 		g_coord.X--;
6506 	    else if (g_coord.Y > g_srScrollRegion.Top)
6507 	    {
6508 		g_coord.X = g_srScrollRegion.Right;
6509 		g_coord.Y--;
6510 	    }
6511 	    gotoxy(g_coord.X + 1, g_coord.Y + 1);
6512 # ifdef MCH_WRITE_DUMP
6513 	    if (fdDump)
6514 		fputs("\\b\n", fdDump);
6515 # endif
6516 	    s++;
6517 	}
6518 	else if (s[0] == '\a')
6519 	{
6520 	    // \a, bell
6521 	    MessageBeep(0xFFFFFFFF);
6522 # ifdef MCH_WRITE_DUMP
6523 	    if (fdDump)
6524 		fputs("\\a\n", fdDump);
6525 # endif
6526 	    s++;
6527 	}
6528 	else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6529 	{
6530 # ifdef MCH_WRITE_DUMP
6531 	    char_u  *old_s = s;
6532 # endif
6533 	    char_u  *p;
6534 	    int	    arg1 = 0, arg2 = 0, argc = 0, args[16];
6535 	    char_u  *sp;
6536 
6537 	    switch (s[2])
6538 	    {
6539 	    case '0': case '1': case '2': case '3': case '4':
6540 	    case '5': case '6': case '7': case '8': case '9':
6541 		if (*(p = get_seq(args, &argc, s)) != 'm')
6542 		    goto notsgr;
6543 
6544 		p = s;
6545 
6546 		// Handling frequent optional sequences.  Output to the screen
6547 		// takes too long, so do not output as much as possible.
6548 
6549 		// If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6550 		// resetFG,FG,BG are omitted.
6551 		if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
6552 		{
6553 		    p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6554 		    len = len + 1 - (int)(p - s);
6555 		    s = p;
6556 		    break;
6557 		}
6558 
6559 		// If FG,BG,BG,FG of SGR are connected, the first FG can be
6560 		// omitted.
6561 		if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6562 		    p = sp;
6563 
6564 		// If FG,BG,FG,BG of SGR are connected, the first FG can be
6565 		// omitted.
6566 		if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6567 		    p = sp;
6568 
6569 		// If BG,BG of SGR are connected, the first BG can be omitted.
6570 		if (sgrn2((sp = sgrn2(p, 48)), 48))
6571 		    p = sp;
6572 
6573 		// If restoreFG and FG are connected, the restoreFG can be
6574 	        // omitted.
6575 		if (sgrn2((sp = sgrnc(p, 39)), 38))
6576 		    p = sp;
6577 
6578 		p = get_seq(args, &argc, p);
6579 
6580 notsgr:
6581 		arg1 = args[0];
6582 		arg2 = args[1];
6583 		if (*p == 'm')
6584 		{
6585 		    if (argc == 1 && args[0] == 0)
6586 			normvideo();
6587 		    else if (argc == 1)
6588 		    {
6589 			if (USE_VTP)
6590 			    textcolor((WORD) arg1);
6591 			else
6592 			    textattr((WORD) arg1);
6593 		    }
6594 		    else if (USE_VTP)
6595 			vtp_sgr_bulks(argc, args);
6596 		}
6597 		else if (argc == 2 && *p == 'H')
6598 		{
6599 		    gotoxy(arg2, arg1);
6600 		}
6601 		else if (argc == 2 && *p == 'r')
6602 		{
6603 		    set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6604 		}
6605 		else if (argc == 2 && *p == 'R')
6606 		{
6607 		    set_scroll_region_tb(arg1, arg2);
6608 		}
6609 		else if (argc == 2 && *p == 'V')
6610 		{
6611 		    set_scroll_region_lr(arg1, arg2);
6612 		}
6613 		else if (argc == 1 && *p == 'A')
6614 		{
6615 		    gotoxy(g_coord.X + 1,
6616 			   max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6617 		}
6618 		else if (argc == 1 && *p == 'b')
6619 		{
6620 		    textbackground((WORD) arg1);
6621 		}
6622 		else if (argc == 1 && *p == 'C')
6623 		{
6624 		    gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6625 			   g_coord.Y + 1);
6626 		}
6627 		else if (argc == 1 && *p == 'f')
6628 		{
6629 		    textcolor((WORD) arg1);
6630 		}
6631 		else if (argc == 1 && *p == 'H')
6632 		{
6633 		    gotoxy(1, arg1);
6634 		}
6635 		else if (argc == 1 && *p == 'L')
6636 		{
6637 		    insert_lines(arg1);
6638 		}
6639 		else if (argc == 1 && *p == 'M')
6640 		{
6641 		    delete_lines(arg1);
6642 		}
6643 
6644 		len -= (int)(p - s);
6645 		s = p + 1;
6646 		break;
6647 
6648 	    case 'A':
6649 		gotoxy(g_coord.X + 1,
6650 		       max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6651 		goto got3;
6652 
6653 	    case 'B':
6654 		visual_bell();
6655 		goto got3;
6656 
6657 	    case 'C':
6658 		gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6659 		       g_coord.Y + 1);
6660 		goto got3;
6661 
6662 	    case 'E':
6663 		termcap_mode_end();
6664 		goto got3;
6665 
6666 	    case 'F':
6667 		standout();
6668 		goto got3;
6669 
6670 	    case 'f':
6671 		standend();
6672 		goto got3;
6673 
6674 	    case 'H':
6675 		gotoxy(1, 1);
6676 		goto got3;
6677 
6678 	    case 'j':
6679 		clear_to_end_of_display();
6680 		goto got3;
6681 
6682 	    case 'J':
6683 		clear_screen();
6684 		goto got3;
6685 
6686 	    case 'K':
6687 		clear_to_end_of_line();
6688 		goto got3;
6689 
6690 	    case 'L':
6691 		insert_lines(1);
6692 		goto got3;
6693 
6694 	    case 'M':
6695 		delete_lines(1);
6696 		goto got3;
6697 
6698 	    case 'S':
6699 		termcap_mode_start();
6700 		goto got3;
6701 
6702 	    case 'V':
6703 		cursor_visible(TRUE);
6704 		goto got3;
6705 
6706 	    case 'v':
6707 		cursor_visible(FALSE);
6708 		goto got3;
6709 
6710 	    got3:
6711 		s += 3;
6712 		len -= 2;
6713 	    }
6714 
6715 # ifdef MCH_WRITE_DUMP
6716 	    if (fdDump)
6717 	    {
6718 		fputs("ESC | ", fdDump);
6719 		fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6720 		fputc('\n', fdDump);
6721 	    }
6722 # endif
6723 	}
6724 	else
6725 	{
6726 	    // Write a single character
6727 	    DWORD nWritten;
6728 
6729 	    nWritten = write_chars(s, 1);
6730 # ifdef MCH_WRITE_DUMP
6731 	    if (fdDump)
6732 	    {
6733 		fputc('>', fdDump);
6734 		fwrite(s, sizeof(char_u), nWritten, fdDump);
6735 		fputs("<\n", fdDump);
6736 	    }
6737 # endif
6738 
6739 	    len -= (nWritten - 1);
6740 	    s += nWritten;
6741 	}
6742     }
6743 
6744 # ifdef MCH_WRITE_DUMP
6745     if (fdDump)
6746 	fflush(fdDump);
6747 # endif
6748 }
6749 
6750 #endif // FEAT_GUI_MSWIN
6751 
6752 
6753 /*
6754  * Delay for "msec" milliseconds.
6755  */
6756     void
6757 mch_delay(
6758     long    msec,
6759     int	    flags UNUSED)
6760 {
6761 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
6762     Sleep((int)msec);	    // never wait for input
6763 #else // Console
6764 # ifdef VIMDLL
6765     if (gui.in_use)
6766     {
6767 	Sleep((int)msec);	    // never wait for input
6768 	return;
6769     }
6770 # endif
6771     if (flags & MCH_DELAY_IGNOREINPUT)
6772 # ifdef FEAT_MZSCHEME
6773 	if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6774 	{
6775 	    int towait = p_mzq;
6776 
6777 	    // if msec is large enough, wait by portions in p_mzq
6778 	    while (msec > 0)
6779 	    {
6780 		mzvim_check_threads();
6781 		if (msec < towait)
6782 		    towait = msec;
6783 		Sleep(towait);
6784 		msec -= towait;
6785 	    }
6786 	}
6787 	else
6788 # endif
6789 	    Sleep((int)msec);
6790     else
6791 	WaitForChar(msec, FALSE);
6792 #endif
6793 }
6794 
6795 
6796 /*
6797  * This version of remove is not scared by a readonly (backup) file.
6798  * This can also remove a symbolic link like Unix.
6799  * Return 0 for success, -1 for failure.
6800  */
6801     int
6802 mch_remove(char_u *name)
6803 {
6804     WCHAR	*wn;
6805     int		n;
6806 
6807     /*
6808      * On Windows, deleting a directory's symbolic link is done by
6809      * RemoveDirectory(): mch_rmdir.  It seems unnatural, but it is fact.
6810      */
6811     if (mch_isdir(name) && mch_is_symbolic_link(name))
6812 	return mch_rmdir(name);
6813 
6814     win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6815 
6816     wn = enc_to_utf16(name, NULL);
6817     if (wn == NULL)
6818 	return -1;
6819 
6820     n = DeleteFileW(wn) ? 0 : -1;
6821     vim_free(wn);
6822     return n;
6823 }
6824 
6825 
6826 /*
6827  * Check for an "interrupt signal": CTRL-break or CTRL-C.
6828  */
6829     void
6830 mch_breakcheck(int force UNUSED)
6831 {
6832 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6833 # ifdef VIMDLL
6834     if (!gui.in_use)
6835 # endif
6836 	if (g_fCtrlCPressed || g_fCBrkPressed)
6837 	{
6838 	    ctrl_break_was_pressed = g_fCBrkPressed;
6839 	    g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6840 	    got_int = TRUE;
6841 	}
6842 #endif
6843 }
6844 
6845 // physical RAM to leave for the OS
6846 #define WINNT_RESERVE_BYTES     (256*1024*1024)
6847 
6848 /*
6849  * How much main memory in KiB that can be used by VIM.
6850  */
6851     long_u
6852 mch_total_mem(int special UNUSED)
6853 {
6854     MEMORYSTATUSEX  ms;
6855 
6856     // Need to use GlobalMemoryStatusEx() when there is more memory than
6857     // what fits in 32 bits.
6858     ms.dwLength = sizeof(MEMORYSTATUSEX);
6859     GlobalMemoryStatusEx(&ms);
6860     if (ms.ullAvailVirtual < ms.ullTotalPhys)
6861     {
6862 	// Process address space fits in physical RAM, use all of it.
6863 	return (long_u)(ms.ullAvailVirtual / 1024);
6864     }
6865     if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6866     {
6867 	// Catch old NT box or perverse hardware setup.
6868 	return (long_u)((ms.ullTotalPhys / 2) / 1024);
6869     }
6870     // Use physical RAM less reserve for OS + data.
6871     return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6872 }
6873 
6874 /*
6875  * mch_wrename() works around a bug in rename (aka MoveFile) in
6876  * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6877  * file whose short file name is "FOO.BAR" (its long file name will
6878  * be correct: "foo.bar~").  Because a file can be accessed by
6879  * either its SFN or its LFN, "foo.bar" has effectively been
6880  * renamed to "foo.bar", which is not at all what was wanted.  This
6881  * seems to happen only when renaming files with three-character
6882  * extensions by appending a suffix that does not include ".".
6883  * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6884  *
6885  * There is another problem, which isn't really a bug but isn't right either:
6886  * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6887  * "abcdef~1.txt" again.  This has been reported on Windows NT 4.0 with
6888  * service pack 6.  Doesn't seem to happen on Windows 98.
6889  *
6890  * Like rename(), returns 0 upon success, non-zero upon failure.
6891  * Should probably set errno appropriately when errors occur.
6892  */
6893     int
6894 mch_wrename(WCHAR *wold, WCHAR *wnew)
6895 {
6896     WCHAR	*p;
6897     int		i;
6898     WCHAR	szTempFile[_MAX_PATH + 1];
6899     WCHAR	szNewPath[_MAX_PATH + 1];
6900     HANDLE	hf;
6901 
6902     // No need to play tricks unless the file name contains a "~" as the
6903     // seventh character.
6904     p = wold;
6905     for (i = 0; wold[i] != NUL; ++i)
6906 	if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6907 		&& wold[i + 1] != 0)
6908 	    p = wold + i + 1;
6909     if ((int)(wold + i - p) < 8 || p[6] != '~')
6910 	return (MoveFileW(wold, wnew) == 0);
6911 
6912     // Get base path of new file name.  Undocumented feature: If pszNewFile is
6913     // a directory, no error is returned and pszFilePart will be NULL.
6914     if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6915 	return -1;
6916     *p = NUL;
6917 
6918     // Get (and create) a unique temporary file name in directory of new file
6919     if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6920 	return -2;
6921 
6922     // blow the temp file away
6923     if (!DeleteFileW(szTempFile))
6924 	return -3;
6925 
6926     // rename old file to the temp file
6927     if (!MoveFileW(wold, szTempFile))
6928 	return -4;
6929 
6930     // now create an empty file called pszOldFile; this prevents the operating
6931     // system using pszOldFile as an alias (SFN) if we're renaming within the
6932     // same directory.  For example, we're editing a file called
6933     // filename.asc.txt by its SFN, filena~1.txt.  If we rename filena~1.txt
6934     // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6935     // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6936     // cause all sorts of problems later in buf_write().  So, we create an
6937     // empty file called filena~1.txt and the system will have to find some
6938     // other SFN for filena~1.txt~, such as filena~2.txt
6939     if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6940 		    FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6941 	return -5;
6942     if (!CloseHandle(hf))
6943 	return -6;
6944 
6945     // rename the temp file to the new file
6946     if (!MoveFileW(szTempFile, wnew))
6947     {
6948 	// Renaming failed.  Rename the file back to its old name, so that it
6949 	// looks like nothing happened.
6950 	(void)MoveFileW(szTempFile, wold);
6951 	return -7;
6952     }
6953 
6954     // Seems to be left around on Novell filesystems
6955     DeleteFileW(szTempFile);
6956 
6957     // finally, remove the empty old file
6958     if (!DeleteFileW(wold))
6959 	return -8;
6960 
6961     return 0;
6962 }
6963 
6964 
6965 /*
6966  * Converts the filenames to UTF-16, then call mch_wrename().
6967  * Like rename(), returns 0 upon success, non-zero upon failure.
6968  */
6969     int
6970 mch_rename(
6971     const char	*pszOldFile,
6972     const char	*pszNewFile)
6973 {
6974     WCHAR	*wold = NULL;
6975     WCHAR	*wnew = NULL;
6976     int		retval = -1;
6977 
6978     wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6979     wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6980     if (wold != NULL && wnew != NULL)
6981 	retval = mch_wrename(wold, wnew);
6982     vim_free(wold);
6983     vim_free(wnew);
6984     return retval;
6985 }
6986 
6987 /*
6988  * Get the default shell for the current hardware platform
6989  */
6990     char *
6991 default_shell(void)
6992 {
6993     return "cmd.exe";
6994 }
6995 
6996 /*
6997  * mch_access() extends access() to do more detailed check on network drives.
6998  * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6999  */
7000     int
7001 mch_access(char *n, int p)
7002 {
7003     HANDLE	hFile;
7004     int		retval = -1;	    // default: fail
7005     WCHAR	*wn;
7006 
7007     wn = enc_to_utf16((char_u *)n, NULL);
7008     if (wn == NULL)
7009 	return -1;
7010 
7011     if (mch_isdir((char_u *)n))
7012     {
7013 	WCHAR TempNameW[_MAX_PATH + 16] = L"";
7014 
7015 	if (p & R_OK)
7016 	{
7017 	    // Read check is performed by seeing if we can do a find file on
7018 	    // the directory for any file.
7019 	    int			i;
7020 	    WIN32_FIND_DATAW    d;
7021 
7022 	    for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7023 		TempNameW[i] = wn[i];
7024 	    if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7025 		TempNameW[i++] = '\\';
7026 	    TempNameW[i++] = '*';
7027 	    TempNameW[i++] = 0;
7028 
7029 	    hFile = FindFirstFileW(TempNameW, &d);
7030 	    if (hFile == INVALID_HANDLE_VALUE)
7031 		goto getout;
7032 	    else
7033 		(void)FindClose(hFile);
7034 	}
7035 
7036 	if (p & W_OK)
7037 	{
7038 	    // Trying to create a temporary file in the directory should catch
7039 	    // directories on read-only network shares.  However, in
7040 	    // directories whose ACL allows writes but denies deletes will end
7041 	    // up keeping the temporary file :-(.
7042 	    if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7043 		goto getout;
7044 	    else
7045 		DeleteFileW(TempNameW);
7046 	}
7047     }
7048     else
7049     {
7050 	// Don't consider a file read-only if another process has opened it.
7051 	DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7052 
7053 	// Trying to open the file for the required access does ACL, read-only
7054 	// network share, and file attribute checks.
7055 	DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7056 					     | ((p & R_OK) ? GENERIC_READ : 0);
7057 
7058 	hFile = CreateFileW(wn, access_mode, share_mode,
7059 					     NULL, OPEN_EXISTING, 0, NULL);
7060 	if (hFile == INVALID_HANDLE_VALUE)
7061 	    goto getout;
7062 	CloseHandle(hFile);
7063     }
7064 
7065     retval = 0;	    // success
7066 getout:
7067     vim_free(wn);
7068     return retval;
7069 }
7070 
7071 /*
7072  * Version of open() that may use UTF-16 file name.
7073  */
7074     int
7075 mch_open(const char *name, int flags, int mode)
7076 {
7077     WCHAR	*wn;
7078     int		f;
7079 
7080     wn = enc_to_utf16((char_u *)name, NULL);
7081     if (wn == NULL)
7082 	return -1;
7083 
7084     f = _wopen(wn, flags, mode);
7085     vim_free(wn);
7086     return f;
7087 }
7088 
7089 /*
7090  * Version of fopen() that uses UTF-16 file name.
7091  */
7092     FILE *
7093 mch_fopen(const char *name, const char *mode)
7094 {
7095     WCHAR	*wn, *wm;
7096     FILE	*f = NULL;
7097 
7098 #if defined(DEBUG) && _MSC_VER >= 1400
7099     // Work around an annoying assertion in the Microsoft debug CRT
7100     // when mode's text/binary setting doesn't match _get_fmode().
7101     char newMode = mode[strlen(mode) - 1];
7102     int oldMode = 0;
7103 
7104     _get_fmode(&oldMode);
7105     if (newMode == 't')
7106 	_set_fmode(_O_TEXT);
7107     else if (newMode == 'b')
7108 	_set_fmode(_O_BINARY);
7109 #endif
7110     wn = enc_to_utf16((char_u *)name, NULL);
7111     wm = enc_to_utf16((char_u *)mode, NULL);
7112     if (wn != NULL && wm != NULL)
7113 	f = _wfopen(wn, wm);
7114     vim_free(wn);
7115     vim_free(wm);
7116 
7117 #if defined(DEBUG) && _MSC_VER >= 1400
7118     _set_fmode(oldMode);
7119 #endif
7120     return f;
7121 }
7122 
7123 /*
7124  * SUB STREAM (aka info stream) handling:
7125  *
7126  * NTFS can have sub streams for each file.  The normal contents of a file is
7127  * stored in the main stream, and extra contents (author information, title and
7128  * so on) can be stored in a sub stream.  After Windows 2000, the user can
7129  * access and store this information in sub streams via an explorer's property
7130  * menu item in the right click menu.  This information in sub streams was lost
7131  * when copying only the main stream.  Therefore we have to copy sub streams.
7132  *
7133  * Incomplete explanation:
7134  *	http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7135  * More useful info and an example:
7136  *	http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7137  */
7138 
7139 /*
7140  * Copy info stream data "substream".  Read from the file with BackupRead(sh)
7141  * and write to stream "substream" of file "to".
7142  * Errors are ignored.
7143  */
7144     static void
7145 copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7146 {
7147     HANDLE  hTo;
7148     WCHAR   *to_name;
7149 
7150     to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7151     wcscpy(to_name, to);
7152     wcscat(to_name, substream);
7153 
7154     hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7155 						 FILE_ATTRIBUTE_NORMAL, NULL);
7156     if (hTo != INVALID_HANDLE_VALUE)
7157     {
7158 	long	done;
7159 	DWORD	todo;
7160 	DWORD	readcnt, written;
7161 	char	buf[4096];
7162 
7163 	// Copy block of bytes at a time.  Abort when something goes wrong.
7164 	for (done = 0; done < len; done += written)
7165 	{
7166 	    // (size_t) cast for Borland C 5.5
7167 	    todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7168 						       : (size_t)(len - done));
7169 	    if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7170 						       FALSE, FALSE, context)
7171 		    || readcnt != todo
7172 		    || !WriteFile(hTo, buf, todo, &written, NULL)
7173 		    || written != todo)
7174 		break;
7175 	}
7176 	CloseHandle(hTo);
7177     }
7178 
7179     free(to_name);
7180 }
7181 
7182 /*
7183  * Copy info streams from file "from" to file "to".
7184  */
7185     static void
7186 copy_infostreams(char_u *from, char_u *to)
7187 {
7188     WCHAR		*fromw;
7189     WCHAR		*tow;
7190     HANDLE		sh;
7191     WIN32_STREAM_ID	sid;
7192     int			headersize;
7193     WCHAR		streamname[_MAX_PATH];
7194     DWORD		readcount;
7195     void		*context = NULL;
7196     DWORD		lo, hi;
7197     int			len;
7198 
7199     // Convert the file names to wide characters.
7200     fromw = enc_to_utf16(from, NULL);
7201     tow = enc_to_utf16(to, NULL);
7202     if (fromw != NULL && tow != NULL)
7203     {
7204 	// Open the file for reading.
7205 	sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7206 			     OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7207 	if (sh != INVALID_HANDLE_VALUE)
7208 	{
7209 	    // Use BackupRead() to find the info streams.  Repeat until we
7210 	    // have done them all.
7211 	    for (;;)
7212 	    {
7213 		// Get the header to find the length of the stream name.  If
7214 		// the "readcount" is zero we have done all info streams.
7215 		ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
7216 		headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
7217 		if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7218 					   &readcount, FALSE, FALSE, &context)
7219 			|| readcount == 0)
7220 		    break;
7221 
7222 		// We only deal with streams that have a name.  The normal
7223 		// file data appears to be without a name, even though docs
7224 		// suggest it is called "::$DATA".
7225 		if (sid.dwStreamNameSize > 0)
7226 		{
7227 		    // Read the stream name.
7228 		    if (!BackupRead(sh, (LPBYTE)streamname,
7229 							 sid.dwStreamNameSize,
7230 					  &readcount, FALSE, FALSE, &context))
7231 			break;
7232 
7233 		    // Copy an info stream with a name ":anything:$DATA".
7234 		    // Skip "::$DATA", it has no stream name (examples suggest
7235 		    // it might be used for the normal file contents).
7236 		    // Note that BackupRead() counts bytes, but the name is in
7237 		    // wide characters.
7238 		    len = readcount / sizeof(WCHAR);
7239 		    streamname[len] = 0;
7240 		    if (len > 7 && wcsicmp(streamname + len - 6,
7241 							      L":$DATA") == 0)
7242 		    {
7243 			streamname[len - 6] = 0;
7244 			copy_substream(sh, &context, tow, streamname,
7245 						    (long)sid.Size.u.LowPart);
7246 		    }
7247 		}
7248 
7249 		// Advance to the next stream.  We might try seeking too far,
7250 		// but BackupSeek() doesn't skip over stream borders, thus
7251 		// that's OK.
7252 		(void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
7253 							  &lo, &hi, &context);
7254 	    }
7255 
7256 	    // Clear the context.
7257 	    (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7258 
7259 	    CloseHandle(sh);
7260 	}
7261     }
7262     vim_free(fromw);
7263     vim_free(tow);
7264 }
7265 
7266 /*
7267  * ntdll.dll definitions
7268  */
7269 #define FileEaInformation   7
7270 #ifndef STATUS_SUCCESS
7271 # define STATUS_SUCCESS	    ((NTSTATUS) 0x00000000L)
7272 #endif
7273 
7274 typedef struct _FILE_FULL_EA_INFORMATION_ {
7275     ULONG  NextEntryOffset;
7276     UCHAR  Flags;
7277     UCHAR  EaNameLength;
7278     USHORT EaValueLength;
7279     CHAR   EaName[1];
7280 } FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7281 
7282 typedef struct _FILE_EA_INFORMATION_ {
7283     ULONG EaSize;
7284 } FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7285 
7286 typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7287 	PHANDLE FileHandle,
7288 	ACCESS_MASK DesiredAccess,
7289 	POBJECT_ATTRIBUTES ObjectAttributes,
7290 	PIO_STATUS_BLOCK IoStatusBlock,
7291 	ULONG ShareAccess,
7292 	ULONG OpenOptions);
7293 typedef NTSTATUS (NTAPI *PfnNtClose)(
7294 	HANDLE Handle);
7295 typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7296 	HANDLE           FileHandle,
7297 	PIO_STATUS_BLOCK IoStatusBlock,
7298 	PVOID            Buffer,
7299 	ULONG            Length);
7300 typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7301 	HANDLE FileHandle,
7302 	PIO_STATUS_BLOCK IoStatusBlock,
7303 	PVOID Buffer,
7304 	ULONG Length,
7305 	BOOLEAN ReturnSingleEntry,
7306 	PVOID EaList,
7307 	ULONG EaListLength,
7308 	PULONG EaIndex,
7309 	BOOLEAN RestartScan);
7310 typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7311 	HANDLE                 FileHandle,
7312 	PIO_STATUS_BLOCK       IoStatusBlock,
7313 	PVOID                  FileInformation,
7314 	ULONG                  Length,
7315 	FILE_INFORMATION_CLASS FileInformationClass);
7316 typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7317 	PUNICODE_STRING DestinationString,
7318 	PCWSTR SourceString);
7319 
7320 PfnNtOpenFile pNtOpenFile = NULL;
7321 PfnNtClose pNtClose = NULL;
7322 PfnNtSetEaFile pNtSetEaFile = NULL;
7323 PfnNtQueryEaFile pNtQueryEaFile = NULL;
7324 PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7325 PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7326 
7327 /*
7328  * Load ntdll.dll functions.
7329  */
7330     static BOOL
7331 load_ntdll(void)
7332 {
7333     static int	loaded = -1;
7334 
7335     if (loaded == -1)
7336     {
7337 	HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7338 	if (hNtdll != NULL)
7339 	{
7340 	    pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7341 	    pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7342 	    pNtSetEaFile = (PfnNtSetEaFile)
7343 		GetProcAddress(hNtdll, "NtSetEaFile");
7344 	    pNtQueryEaFile = (PfnNtQueryEaFile)
7345 		GetProcAddress(hNtdll, "NtQueryEaFile");
7346 	    pNtQueryInformationFile = (PfnNtQueryInformationFile)
7347 		GetProcAddress(hNtdll, "NtQueryInformationFile");
7348 	    pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7349 		GetProcAddress(hNtdll, "RtlInitUnicodeString");
7350 	}
7351 	if (pNtOpenFile == NULL
7352 		|| pNtClose == NULL
7353 		|| pNtSetEaFile == NULL
7354 		|| pNtQueryEaFile == NULL
7355 		|| pNtQueryInformationFile == NULL
7356 		|| pRtlInitUnicodeString == NULL)
7357 	    loaded = FALSE;
7358 	else
7359 	    loaded = TRUE;
7360     }
7361     return (BOOL) loaded;
7362 }
7363 
7364 /*
7365  * Copy extended attributes (EA) from file "from" to file "to".
7366  */
7367     static void
7368 copy_extattr(char_u *from, char_u *to)
7369 {
7370     char_u		    *fromf = NULL;
7371     char_u		    *tof = NULL;
7372     WCHAR		    *fromw = NULL;
7373     WCHAR		    *tow = NULL;
7374     UNICODE_STRING	    u;
7375     HANDLE		    h;
7376     OBJECT_ATTRIBUTES	    oa;
7377     IO_STATUS_BLOCK	    iosb;
7378     FILE_EA_INFORMATION_    eainfo = {0};
7379     void		    *ea = NULL;
7380 
7381     if (!load_ntdll())
7382 	return;
7383 
7384     // Convert the file names to the fully qualified object names.
7385     fromf = alloc(STRLEN(from) + 5);
7386     tof = alloc(STRLEN(to) + 5);
7387     if (fromf == NULL || tof == NULL)
7388 	goto theend;
7389     STRCPY(fromf, "\\??\\");
7390     STRCAT(fromf, from);
7391     STRCPY(tof, "\\??\\");
7392     STRCAT(tof, to);
7393 
7394     // Convert the names to wide characters.
7395     fromw = enc_to_utf16(fromf, NULL);
7396     tow = enc_to_utf16(tof, NULL);
7397     if (fromw == NULL || tow == NULL)
7398 	goto theend;
7399 
7400     // Get the EA.
7401     pRtlInitUnicodeString(&u, fromw);
7402     InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7403     if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7404 		FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7405 	goto theend;
7406     pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7407 	    FileEaInformation);
7408     if (eainfo.EaSize != 0)
7409     {
7410 	ea = alloc(eainfo.EaSize);
7411 	if (ea != NULL)
7412 	{
7413 	    if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7414 			NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7415 	    {
7416 		vim_free(ea);
7417 		ea = NULL;
7418 	    }
7419 	}
7420     }
7421     pNtClose(h);
7422 
7423     // Set the EA.
7424     if (ea != NULL)
7425     {
7426 	pRtlInitUnicodeString(&u, tow);
7427 	InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7428 	if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7429 		    FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7430 	    goto theend;
7431 
7432 	pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7433 	pNtClose(h);
7434     }
7435 
7436 theend:
7437     vim_free(fromf);
7438     vim_free(tof);
7439     vim_free(fromw);
7440     vim_free(tow);
7441     vim_free(ea);
7442 }
7443 
7444 /*
7445  * Copy file attributes from file "from" to file "to".
7446  * For Windows NT and later we copy info streams.
7447  * Always returns zero, errors are ignored.
7448  */
7449     int
7450 mch_copy_file_attribute(char_u *from, char_u *to)
7451 {
7452     // File streams only work on Windows NT and later.
7453     copy_infostreams(from, to);
7454     copy_extattr(from, to);
7455     return 0;
7456 }
7457 
7458 #if defined(MYRESETSTKOFLW) || defined(PROTO)
7459 /*
7460  * Recreate a destroyed stack guard page in win32.
7461  * Written by Benjamin Peterson.
7462  */
7463 
7464 // These magic numbers are from the MS header files
7465 # define MIN_STACK_WINNT 2
7466 
7467 /*
7468  * This function does the same thing as _resetstkoflw(), which is only
7469  * available in DevStudio .net and later.
7470  * Returns 0 for failure, 1 for success.
7471  */
7472     int
7473 myresetstkoflw(void)
7474 {
7475     BYTE	*pStackPtr;
7476     BYTE	*pGuardPage;
7477     BYTE	*pStackBase;
7478     BYTE	*pLowestPossiblePage;
7479     MEMORY_BASIC_INFORMATION mbi;
7480     SYSTEM_INFO si;
7481     DWORD	nPageSize;
7482     DWORD	dummy;
7483 
7484     // We need to know the system page size.
7485     GetSystemInfo(&si);
7486     nPageSize = si.dwPageSize;
7487 
7488     // ...and the current stack pointer
7489     pStackPtr = (BYTE*)_alloca(1);
7490 
7491     // ...and the base of the stack.
7492     if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7493 	return 0;
7494     pStackBase = (BYTE*)mbi.AllocationBase;
7495 
7496     // ...and the page that's min_stack_req pages away from stack base; this is
7497     // the lowest page we could use.
7498     pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
7499 
7500     {
7501 	// We want the first committed page in the stack Start at the stack
7502 	// base and move forward through memory until we find a committed block.
7503 	BYTE *pBlock = pStackBase;
7504 
7505 	for (;;)
7506 	{
7507 	    if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7508 		return 0;
7509 
7510 	    pBlock += mbi.RegionSize;
7511 
7512 	    if (mbi.State & MEM_COMMIT)
7513 		break;
7514 	}
7515 
7516 	// mbi now describes the first committed block in the stack.
7517 	if (mbi.Protect & PAGE_GUARD)
7518 	    return 1;
7519 
7520 	// decide where the guard page should start
7521 	if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7522 	    pGuardPage = pLowestPossiblePage;
7523 	else
7524 	    pGuardPage = (BYTE*)mbi.BaseAddress;
7525 
7526 	// allocate the guard page
7527 	if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7528 	    return 0;
7529 
7530 	// apply the guard attribute to the page
7531 	if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7532 								      &dummy))
7533 	    return 0;
7534     }
7535 
7536     return 1;
7537 }
7538 #endif
7539 
7540 
7541 /*
7542  * The command line arguments in UCS2
7543  */
7544 static int	nArgsW = 0;
7545 static LPWSTR	*ArglistW = NULL;
7546 static int	global_argc = 0;
7547 static char	**global_argv;
7548 
7549 static int	used_file_argc = 0;	// last argument in global_argv[] used
7550 					// for the argument list.
7551 static int	*used_file_indexes = NULL; // indexes in global_argv[] for
7552 					   // command line arguments added to
7553 					   // the argument list
7554 static int	used_file_count = 0;	// nr of entries in used_file_indexes
7555 static int	used_file_literal = FALSE;  // take file names literally
7556 static int	used_file_full_path = FALSE;  // file name was full path
7557 static int	used_file_diff_mode = FALSE;  // file name was with diff mode
7558 static int	used_alist_count = 0;
7559 
7560 
7561 /*
7562  * Get the command line arguments.  Unicode version.
7563  * Returns argc.  Zero when something fails.
7564  */
7565     int
7566 get_cmd_argsW(char ***argvp)
7567 {
7568     char	**argv = NULL;
7569     int		argc = 0;
7570     int		i;
7571 
7572     free_cmd_argsW();
7573     ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7574     if (ArglistW != NULL)
7575     {
7576 	argv = malloc((nArgsW + 1) * sizeof(char *));
7577 	if (argv != NULL)
7578 	{
7579 	    argc = nArgsW;
7580 	    argv[argc] = NULL;
7581 	    for (i = 0; i < argc; ++i)
7582 	    {
7583 		int	len;
7584 
7585 		// Convert each Unicode argument to the current codepage.
7586 		WideCharToMultiByte_alloc(GetACP(), 0,
7587 				ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
7588 				(LPSTR *)&argv[i], &len, 0, 0);
7589 		if (argv[i] == NULL)
7590 		{
7591 		    // Out of memory, clear everything.
7592 		    while (i > 0)
7593 			free(argv[--i]);
7594 		    free(argv);
7595 		    argv = NULL;
7596 		    argc = 0;
7597 		}
7598 	    }
7599 	}
7600     }
7601 
7602     global_argc = argc;
7603     global_argv = argv;
7604     if (argc > 0)
7605     {
7606 	if (used_file_indexes != NULL)
7607 	    free(used_file_indexes);
7608 	used_file_indexes = malloc(argc * sizeof(int));
7609     }
7610 
7611     if (argvp != NULL)
7612 	*argvp = argv;
7613     return argc;
7614 }
7615 
7616     void
7617 free_cmd_argsW(void)
7618 {
7619     if (ArglistW != NULL)
7620     {
7621 	GlobalFree(ArglistW);
7622 	ArglistW = NULL;
7623     }
7624 }
7625 
7626 /*
7627  * Remember "name" is an argument that was added to the argument list.
7628  * This avoids that we have to re-parse the argument list when fix_arg_enc()
7629  * is called.
7630  */
7631     void
7632 used_file_arg(char *name, int literal, int full_path, int diff_mode)
7633 {
7634     int		i;
7635 
7636     if (used_file_indexes == NULL)
7637 	return;
7638     for (i = used_file_argc + 1; i < global_argc; ++i)
7639 	if (STRCMP(global_argv[i], name) == 0)
7640 	{
7641 	    used_file_argc = i;
7642 	    used_file_indexes[used_file_count++] = i;
7643 	    break;
7644 	}
7645     used_file_literal = literal;
7646     used_file_full_path = full_path;
7647     used_file_diff_mode = diff_mode;
7648 }
7649 
7650 /*
7651  * Remember the length of the argument list as it was.  If it changes then we
7652  * leave it alone when 'encoding' is set.
7653  */
7654     void
7655 set_alist_count(void)
7656 {
7657     used_alist_count = GARGCOUNT;
7658 }
7659 
7660 /*
7661  * Fix the encoding of the command line arguments.  Invoked when 'encoding'
7662  * has been changed while starting up.  Use the UCS-2 command line arguments
7663  * and convert them to 'encoding'.
7664  */
7665     void
7666 fix_arg_enc(void)
7667 {
7668     int		i;
7669     int		idx;
7670     char_u	*str;
7671     int		*fnum_list;
7672 
7673     // Safety checks:
7674     // - if argument count differs between the wide and non-wide argument
7675     //   list, something must be wrong.
7676     // - the file name arguments must have been located.
7677     // - the length of the argument list wasn't changed by the user.
7678     if (global_argc != nArgsW
7679 	    || ArglistW == NULL
7680 	    || used_file_indexes == NULL
7681 	    || used_file_count == 0
7682 	    || used_alist_count != GARGCOUNT)
7683 	return;
7684 
7685     // Remember the buffer numbers for the arguments.
7686     fnum_list = ALLOC_MULT(int, GARGCOUNT);
7687     if (fnum_list == NULL)
7688 	return;		// out of memory
7689     for (i = 0; i < GARGCOUNT; ++i)
7690 	fnum_list[i] = GARGLIST[i].ae_fnum;
7691 
7692     // Clear the argument list.  Make room for the new arguments.
7693     alist_clear(&global_alist);
7694     if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
7695 	return;		// out of memory
7696 
7697     for (i = 0; i < used_file_count; ++i)
7698     {
7699 	idx = used_file_indexes[i];
7700 	str = utf16_to_enc(ArglistW[idx], NULL);
7701 	if (str != NULL)
7702 	{
7703 	    int literal = used_file_literal;
7704 
7705 #ifdef FEAT_DIFF
7706 	    // When using diff mode may need to concatenate file name to
7707 	    // directory name.  Just like it's done in main().
7708 	    if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7709 				      && !mch_isdir(alist_name(&GARGLIST[0])))
7710 	    {
7711 		char_u	    *r;
7712 
7713 		r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7714 		if (r != NULL)
7715 		{
7716 		    vim_free(str);
7717 		    str = r;
7718 		}
7719 	    }
7720 #endif
7721 	    // Re-use the old buffer by renaming it.  When not using literal
7722 	    // names it's done by alist_expand() below.
7723 	    if (used_file_literal)
7724 		buf_set_name(fnum_list[i], str);
7725 
7726 	    // Check backtick literal. backtick literal is already expanded in
7727 	    // main.c, so this part add str as literal.
7728 	    if (literal == FALSE)
7729 	    {
7730 		size_t len = STRLEN(str);
7731 
7732 		if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7733 		    literal = TRUE;
7734 	    }
7735 	    alist_add(&global_alist, str, literal ? 2 : 0);
7736 	}
7737     }
7738 
7739     if (!used_file_literal)
7740     {
7741 	// Now expand wildcards in the arguments.
7742 	// Temporarily add '(' and ')' to 'isfname'.  These are valid
7743 	// filename characters but are excluded from 'isfname' to make
7744 	// "gf" work on a file name in parenthesis (e.g.: see vim.h).
7745 	// Also, unset wildignore to not be influenced by this option.
7746 	// The arguments specified in command-line should be kept even if
7747 	// encoding options were changed.
7748 	do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
7749 	do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
7750 	alist_expand(fnum_list, used_alist_count);
7751 	do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7752 	do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
7753     }
7754 
7755     // If wildcard expansion failed, we are editing the first file of the
7756     // arglist and there is no file name: Edit the first argument now.
7757     if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7758     {
7759 	do_cmdline_cmd((char_u *)":rewind");
7760 	if (GARGCOUNT == 1 && used_file_full_path)
7761 	    (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
7762     }
7763 
7764     set_alist_count();
7765 }
7766 
7767     int
7768 mch_setenv(char *var, char *value, int x UNUSED)
7769 {
7770     char_u	*envbuf;
7771     WCHAR	*p;
7772 
7773     envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
7774     if (envbuf == NULL)
7775 	return -1;
7776 
7777     sprintf((char *)envbuf, "%s=%s", var, value);
7778 
7779     p = enc_to_utf16(envbuf, NULL);
7780 
7781     vim_free(envbuf);
7782     if (p == NULL)
7783 	return -1;
7784     _wputenv(p);
7785 #ifdef libintl_wputenv
7786     libintl_wputenv(p);
7787 #endif
7788     // Unlike Un*x systems, we can free the string for _wputenv().
7789     vim_free(p);
7790 
7791     return 0;
7792 }
7793 
7794 /*
7795  * Support for 256 colors and 24-bit colors was added in Windows 10
7796  * version 1703 (Creators update).
7797  */
7798 #define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7799 
7800 /*
7801  * Support for pseudo-console (ConPTY) was added in windows 10
7802  * version 1809 (October 2018 update).
7803  */
7804 #define CONPTY_FIRST_SUPPORT_BUILD  MAKE_VER(10, 0, 17763)
7805 
7806 /*
7807  * ConPTY differences between versions, need different logic.
7808  * version 1903 (May 2019 update).
7809  */
7810 #define CONPTY_1903_BUILD	    MAKE_VER(10, 0, 18362)
7811 
7812 /*
7813  * version 1909 (November 2019 update).
7814  */
7815 #define CONPTY_1909_BUILD	    MAKE_VER(10, 0, 18363)
7816 
7817 /*
7818  * Stay ahead of the next update, and when it's done, fix this.
7819  * version ? (2020 update, temporarily use the build number of insider preview)
7820  */
7821 #define CONPTY_NEXT_UPDATE_BUILD    MAKE_VER(10, 0, 19587)
7822 
7823 /*
7824  * Confirm until this version.  Also the logic changes.
7825  * insider preview.
7826  */
7827 #define CONPTY_INSIDER_BUILD	    MAKE_VER(10, 0, 18995)
7828 
7829 /*
7830  * Not stable now.
7831  */
7832 #define CONPTY_STABLE_BUILD	    MAKE_VER(10, 0, 32767)  // T.B.D.
7833 
7834     static void
7835 vtp_flag_init(void)
7836 {
7837     DWORD   ver = get_build_number();
7838 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7839     DWORD   mode;
7840     HANDLE  out;
7841 
7842 # ifdef VIMDLL
7843     if (!gui.in_use)
7844 # endif
7845     {
7846 	out = GetStdHandle(STD_OUTPUT_HANDLE);
7847 
7848 	vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7849 	GetConsoleMode(out, &mode);
7850 	mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7851 	if (SetConsoleMode(out, mode) == 0)
7852 	    vtp_working = 0;
7853     }
7854 #endif
7855 
7856     if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
7857 	conpty_working = 1;
7858     if (ver >= CONPTY_STABLE_BUILD)
7859 	conpty_stable = 1;
7860 
7861     if (ver <= CONPTY_INSIDER_BUILD)
7862 	conpty_type = 3;
7863     if (ver <= CONPTY_1909_BUILD)
7864 	conpty_type = 2;
7865     if (ver <= CONPTY_1903_BUILD)
7866 	conpty_type = 2;
7867     if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7868 	conpty_type = 1;
7869 
7870     if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7871 	conpty_fix_type = 1;
7872 }
7873 
7874 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
7875 
7876     static void
7877 vtp_init(void)
7878 {
7879     HMODULE hKerneldll;
7880     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7881 # ifdef FEAT_TERMGUICOLORS
7882     COLORREF fg, bg;
7883 # endif
7884 
7885     // Use functions supported from Vista
7886     hKerneldll = GetModuleHandle("kernel32.dll");
7887     if (hKerneldll != NULL)
7888     {
7889 	pGetConsoleScreenBufferInfoEx =
7890 		(PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7891 		hKerneldll, "GetConsoleScreenBufferInfoEx");
7892 	pSetConsoleScreenBufferInfoEx =
7893 		(PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7894 		hKerneldll, "SetConsoleScreenBufferInfoEx");
7895 	if (pGetConsoleScreenBufferInfoEx != NULL
7896 		&& pSetConsoleScreenBufferInfoEx != NULL)
7897 	    has_csbiex = TRUE;
7898     }
7899 
7900     csbi.cbSize = sizeof(csbi);
7901     if (has_csbiex)
7902 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7903     save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7904     save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7905     store_console_bg_rgb = save_console_bg_rgb;
7906     store_console_fg_rgb = save_console_fg_rgb;
7907 
7908 # ifdef FEAT_TERMGUICOLORS
7909     bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7910     fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7911     bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7912     fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7913     default_console_color_bg = bg;
7914     default_console_color_fg = fg;
7915 # endif
7916 
7917     set_console_color_rgb();
7918 }
7919 
7920     static void
7921 vtp_exit(void)
7922 {
7923     restore_console_color_rgb();
7924 }
7925 
7926     int
7927 vtp_printf(
7928     char *format,
7929     ...)
7930 {
7931     char_u  buf[100];
7932     va_list list;
7933     DWORD   result;
7934     int	    len;
7935 
7936     va_start(list, format);
7937     len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
7938     va_end(list);
7939     WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
7940     return (int)result;
7941 }
7942 
7943     static void
7944 vtp_sgr_bulk(
7945     int arg)
7946 {
7947     int args[1];
7948 
7949     args[0] = arg;
7950     vtp_sgr_bulks(1, args);
7951 }
7952 
7953 #define FAST256(x) \
7954     if ((*p-- = "0123456789"[(n = x % 10)]) \
7955 	    && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7956 	    && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7957 
7958 #define FAST256CASE(x) \
7959     case x: \
7960 	FAST256(newargs[x - 1]);
7961 
7962     static void
7963 vtp_sgr_bulks(
7964     int argc,
7965     int *args)
7966 {
7967 #define MAXSGR 16
7968 #define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
7969     char_u  buf[SGRBUFSIZE];
7970     char_u  *p;
7971     int	    in, out;
7972     int	    newargs[16];
7973     static int sgrfgr = -1, sgrfgg, sgrfgb;
7974     static int sgrbgr = -1, sgrbgg, sgrbgb;
7975 
7976     if (argc == 0)
7977     {
7978 	sgrfgr = sgrbgr = -1;
7979 	vtp_printf("033[m");
7980 	return;
7981     }
7982 
7983     in = out = 0;
7984     while (in < argc)
7985     {
7986 	int s = args[in];
7987 	int copylen = 1;
7988 
7989 	if (s == 38)
7990 	{
7991 	    if (argc - in >= 5 && args[in + 1] == 2)
7992 	    {
7993 		if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7994 						     && sgrfgb == args[in + 4])
7995 		{
7996 		    in += 5;
7997 		    copylen = 0;
7998 		}
7999 		else
8000 		{
8001 		    sgrfgr = args[in + 2];
8002 		    sgrfgg = args[in + 3];
8003 		    sgrfgb = args[in + 4];
8004 		    copylen = 5;
8005 		}
8006 	    }
8007 	    else if (argc - in >= 3 && args[in + 1] == 5)
8008 	    {
8009 		sgrfgr = -1;
8010 		copylen = 3;
8011 	    }
8012 	}
8013 	else if (s == 48)
8014 	{
8015 	    if (argc - in >= 5 && args[in + 1] == 2)
8016 	    {
8017 		if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8018 						     && sgrbgb == args[in + 4])
8019 		{
8020 		    in += 5;
8021 		    copylen = 0;
8022 		}
8023 		else
8024 		{
8025 		    sgrbgr = args[in + 2];
8026 		    sgrbgg = args[in + 3];
8027 		    sgrbgb = args[in + 4];
8028 		    copylen = 5;
8029 		}
8030 	    }
8031 	    else if (argc - in >= 3 && args[in + 1] == 5)
8032 	    {
8033 		sgrbgr = -1;
8034 		copylen = 3;
8035 	    }
8036 	}
8037 	else if (30 <= s && s <= 39)
8038 	    sgrfgr = -1;
8039 	else if (90 <= s && s <= 97)
8040 	    sgrfgr = -1;
8041 	else if (40 <= s && s <= 49)
8042 	    sgrbgr = -1;
8043 	else if (100 <= s && s <= 107)
8044 	    sgrbgr = -1;
8045 	else if (s == 0)
8046 	    sgrfgr = sgrbgr = -1;
8047 
8048 	while (copylen--)
8049 	    newargs[out++] = args[in++];
8050     }
8051 
8052     p = &buf[sizeof(buf) - 1];
8053     *p-- = 'm';
8054 
8055     switch (out)
8056     {
8057 	int	n, m;
8058 	DWORD	r;
8059 
8060 	FAST256CASE(16);
8061 	*p-- = ';';
8062 	FAST256CASE(15);
8063 	*p-- = ';';
8064 	FAST256CASE(14);
8065 	*p-- = ';';
8066 	FAST256CASE(13);
8067 	*p-- = ';';
8068 	FAST256CASE(12);
8069 	*p-- = ';';
8070 	FAST256CASE(11);
8071 	*p-- = ';';
8072 	FAST256CASE(10);
8073 	*p-- = ';';
8074 	FAST256CASE(9);
8075 	*p-- = ';';
8076 	FAST256CASE(8);
8077 	*p-- = ';';
8078 	FAST256CASE(7);
8079 	*p-- = ';';
8080 	FAST256CASE(6);
8081 	*p-- = ';';
8082 	FAST256CASE(5);
8083 	*p-- = ';';
8084 	FAST256CASE(4);
8085 	*p-- = ';';
8086 	FAST256CASE(3);
8087 	*p-- = ';';
8088 	FAST256CASE(2);
8089 	*p-- = ';';
8090 	FAST256CASE(1);
8091 	*p-- = '[';
8092 	*p = '\033';
8093 	WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8094     default:
8095 	break;
8096     }
8097 }
8098 
8099     static void
8100 wt_init(void)
8101 {
8102     wt_working = (mch_getenv("WT_SESSION") != NULL);
8103 }
8104 
8105     int
8106 use_wt(void)
8107 {
8108     return USE_WT;
8109 }
8110 
8111 # ifdef FEAT_TERMGUICOLORS
8112     static int
8113 ctermtoxterm(
8114     int cterm)
8115 {
8116     char_u r, g, b, idx;
8117 
8118     cterm_color2rgb(cterm, &r, &g, &b, &idx);
8119     return (((int)r << 16) | ((int)g << 8) | (int)b);
8120 }
8121 # endif
8122 
8123     static void
8124 set_console_color_rgb(void)
8125 {
8126 # ifdef FEAT_TERMGUICOLORS
8127     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8128     guicolor_T	fg, bg;
8129     int		ctermfg, ctermbg;
8130 
8131     if (!USE_VTP)
8132 	return;
8133 
8134     get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8135 
8136     if (USE_WT)
8137     {
8138 	term_fg_rgb_color(fg);
8139 	term_bg_rgb_color(bg);
8140 	return;
8141     }
8142 
8143     fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8144     bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8145 
8146     csbi.cbSize = sizeof(csbi);
8147     if (has_csbiex)
8148 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8149 
8150     csbi.cbSize = sizeof(csbi);
8151     csbi.srWindow.Right += 1;
8152     csbi.srWindow.Bottom += 1;
8153     store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8154     store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8155     csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8156     csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8157     if (has_csbiex)
8158 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8159 # endif
8160 }
8161 
8162 # if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8163     void
8164 get_default_console_color(
8165     int *cterm_fg,
8166     int *cterm_bg,
8167     guicolor_T *gui_fg,
8168     guicolor_T *gui_bg)
8169 {
8170     int id;
8171     guicolor_T guifg = INVALCOLOR;
8172     guicolor_T guibg = INVALCOLOR;
8173     int ctermfg = 0;
8174     int ctermbg = 0;
8175 
8176     id = syn_name2id((char_u *)"Normal");
8177     if (id > 0 && p_tgc)
8178 	syn_id2colors(id, &guifg, &guibg);
8179     if (guifg == INVALCOLOR)
8180     {
8181 	ctermfg = -1;
8182 	if (id > 0)
8183 	    syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8184 	guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8185 						    : default_console_color_fg;
8186 	cterm_normal_fg_gui_color = guifg;
8187 	ctermfg = ctermfg < 0 ? 0 : ctermfg;
8188     }
8189     if (guibg == INVALCOLOR)
8190     {
8191 	ctermbg = -1;
8192 	if (id > 0)
8193 	    syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8194 	guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8195 						    : default_console_color_bg;
8196 	cterm_normal_bg_gui_color = guibg;
8197 	ctermbg = ctermbg < 0 ? 0 : ctermbg;
8198     }
8199 
8200     *cterm_fg = ctermfg;
8201     *cterm_bg = ctermbg;
8202     *gui_fg = guifg;
8203     *gui_bg = guibg;
8204 }
8205 # endif
8206 
8207 /*
8208  * Set the console colors to the original colors or the last set colors.
8209  */
8210     static void
8211 reset_console_color_rgb(void)
8212 {
8213 # ifdef FEAT_TERMGUICOLORS
8214     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8215 
8216     if (USE_WT)
8217 	return;
8218 
8219     csbi.cbSize = sizeof(csbi);
8220     if (has_csbiex)
8221 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8222 
8223     csbi.cbSize = sizeof(csbi);
8224     csbi.srWindow.Right += 1;
8225     csbi.srWindow.Bottom += 1;
8226     csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8227     csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8228     if (has_csbiex)
8229 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8230 # endif
8231 }
8232 
8233 /*
8234  * Set the console colors to the original colors.
8235  */
8236     static void
8237 restore_console_color_rgb(void)
8238 {
8239 # ifdef FEAT_TERMGUICOLORS
8240     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8241 
8242     csbi.cbSize = sizeof(csbi);
8243     if (has_csbiex)
8244 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8245 
8246     csbi.cbSize = sizeof(csbi);
8247     csbi.srWindow.Right += 1;
8248     csbi.srWindow.Bottom += 1;
8249     csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8250     csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
8251     if (has_csbiex)
8252 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8253 # endif
8254 }
8255 
8256     void
8257 control_console_color_rgb(void)
8258 {
8259     if (USE_VTP)
8260 	set_console_color_rgb();
8261     else
8262 	reset_console_color_rgb();
8263 }
8264 
8265     int
8266 use_vtp(void)
8267 {
8268     return USE_VTP;
8269 }
8270 
8271     int
8272 is_term_win32(void)
8273 {
8274     return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8275 }
8276 
8277     int
8278 has_vtp_working(void)
8279 {
8280     return vtp_working;
8281 }
8282 
8283 #endif
8284 
8285     int
8286 has_conpty_working(void)
8287 {
8288     return conpty_working;
8289 }
8290 
8291     int
8292 get_conpty_type(void)
8293 {
8294     return conpty_type;
8295 }
8296 
8297     int
8298 is_conpty_stable(void)
8299 {
8300     return conpty_stable;
8301 }
8302 
8303     int
8304 get_conpty_fix_type(void)
8305 {
8306     return conpty_fix_type;
8307 }
8308 
8309 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
8310     void
8311 resize_console_buf(void)
8312 {
8313     CONSOLE_SCREEN_BUFFER_INFO csbi;
8314     COORD coord;
8315     SMALL_RECT newsize;
8316 
8317     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8318     {
8319 	coord.X = SRWIDTH(csbi.srWindow);
8320 	coord.Y = SRHEIGHT(csbi.srWindow);
8321 	SetConsoleScreenBufferSize(g_hConOut, coord);
8322 
8323 	newsize.Left = 0;
8324 	newsize.Top = 0;
8325 	newsize.Right = coord.X - 1;
8326 	newsize.Bottom = coord.Y - 1;
8327 	SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8328 
8329 	SetConsoleScreenBufferSize(g_hConOut, coord);
8330     }
8331 }
8332 #endif
8333