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