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