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