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