blob: a4c106d75cb3483f8270563092c7709751cc15fc [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
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
Bram Moolenaar4f974752019-02-17 17:44:42 +010013 * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
Bram Moolenaar071d4272004-06-13 20:20:40 +000014 *
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 <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#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
89FILE* 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
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
Bram Moolenaar4f974752019-02-17 17:44:42 +0100154#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100174static void set_scroll_region_tb(unsigned top, unsigned bottom);
175static void set_scroll_region_lr(unsigned left, unsigned right);
176static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void delete_lines(unsigned cLines);
178static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_cursor_visible = TRUE;
181static int did_create_conin = FALSE;
182#else
183static int s_dont_use_vimrun = TRUE;
184static int need_vimrun_warning = FALSE;
185static char *vimrun_path = "vimrun ";
186#endif
187
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200188static int win32_getattrs(char_u *name);
189static int win32_setattrs(char_u *name, int attrs);
190static int win32_set_archive(char_u *name);
191
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100192static int conpty_working = 0;
193static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100194static void vtp_flag_init();
195
Bram Moolenaar4f974752019-02-17 17:44:42 +0100196#ifndef FEAT_GUI_MSWIN
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100197static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100198static void vtp_init();
199static void vtp_exit();
200static int vtp_printf(char *format, ...);
201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
204static guicolor_T save_console_bg_rgb;
205static guicolor_T save_console_fg_rgb;
206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
211static int default_console_color_bg = 0x000000; // black
212static int default_console_color_fg = 0xc0c0c0; // white
213# endif
214
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200216# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217# else
218# define USE_VTP 0
219# endif
220
221static void set_console_color_rgb(void);
222static void reset_console_color_rgb(void);
223#endif
224
225/* This flag is newly created from Windows 10 */
226#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
227# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
228#endif
229
Bram Moolenaar4f974752019-02-17 17:44:42 +0100230#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231static int suppress_winsize = 1; /* don't fiddle with console */
232#endif
233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234static char_u *exe_path = NULL;
235
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100236static BOOL win8_or_later = FALSE;
237
Bram Moolenaar4f974752019-02-17 17:44:42 +0100238#ifndef FEAT_GUI_MSWIN
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100239/* Dynamic loading for portability */
240typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
241{
242 ULONG cbSize;
243 COORD dwSize;
244 COORD dwCursorPosition;
245 WORD wAttributes;
246 SMALL_RECT srWindow;
247 COORD dwMaximumWindowSize;
248 WORD wPopupAttributes;
249 BOOL bFullscreenSupported;
250 COLORREF ColorTable[16];
251} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
252typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
253static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
254typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
255static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
256static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100257#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
Bram Moolenaar4f974752019-02-17 17:44:42 +0100287#ifndef FEAT_GUI_MSWIN
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100463 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100464 p += n;
465 l -= n;
466 }
467}
468
469/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200470 * Load library "name".
471 */
472 HINSTANCE
473vimLoadLib(char *name)
474{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200475 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200477 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
478 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL)
480 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200481 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200483 WCHAR old_dirw[MAXPATHL];
484
485 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
486 {
487 /* Change directory to where the executable is, both to make
488 * sure we find a .dll there and to avoid looking for a .dll
489 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100490 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200491 dll = LoadLibrary(name);
492 SetCurrentDirectoryW(old_dirw);
493 return dll;
494 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
496 return dll;
497}
498
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100499#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
500/*
501 * Get related information about 'funcname' which is imported by 'hInst'.
502 * If 'info' is 0, return the function address.
503 * If 'info' is 1, return the module name which the function is imported from.
504 */
505 static void *
506get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
507{
508 PBYTE pImage = (PBYTE)hInst;
509 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
510 PIMAGE_NT_HEADERS pPE;
511 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
512 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
513 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
514 PIMAGE_IMPORT_BY_NAME pImpName;
515
516 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
517 return NULL;
518 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
519 if (pPE->Signature != IMAGE_NT_SIGNATURE)
520 return NULL;
521 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
522 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
523 .VirtualAddress);
524 for (; pImpDesc->FirstThunk; ++pImpDesc)
525 {
526 if (!pImpDesc->OriginalFirstThunk)
527 continue;
528 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
529 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
530 for (; pIAT->u1.Function; ++pIAT, ++pINT)
531 {
532 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
533 continue;
534 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
535 + (UINT_PTR)(pINT->u1.AddressOfData));
536 if (strcmp((char *)pImpName->Name, funcname) == 0)
537 {
538 switch (info)
539 {
540 case 0:
541 return (void *)pIAT->u1.Function;
542 case 1:
543 return (void *)(pImage + pImpDesc->Name);
544 default:
545 return NULL;
546 }
547 }
548 }
549 }
550 return NULL;
551}
552
553/*
554 * Get the module handle which 'funcname' in 'hInst' is imported from.
555 */
556 HINSTANCE
557find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
558{
559 char *modulename;
560
561 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
562 if (modulename != NULL)
563 return GetModuleHandleA(modulename);
564 return NULL;
565}
566
567/*
568 * Get the address of 'funcname' which is imported by 'hInst' DLL.
569 */
570 void *
571get_dll_import_func(HINSTANCE hInst, const char *funcname)
572{
573 return get_imported_func_info(hInst, funcname, 0);
574}
575#endif
576
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
578# ifndef GETTEXT_DLL
579# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200580# define GETTEXT_DLL_ALT1 "libintl-8.dll"
581# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200583/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000584static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200585static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586static char *null_libintl_textdomain(const char *);
587static char *null_libintl_bindtextdomain(const char *, const char *);
588static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100589static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200591static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200593char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
594 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
596char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000598char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
599 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100600int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601
602 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100603dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604{
605 int i;
606 static struct
607 {
608 char *name;
609 FARPROC *ptr;
610 } libintl_entry[] =
611 {
612 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200613 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
615 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
616 {NULL, NULL}
617 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100618 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619
Bram Moolenaar7554c542018-10-06 15:03:15 +0200620 // No need to initialize twice.
621 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200623 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100624 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100626 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200627 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
628#endif
629#ifdef GETTEXT_DLL_ALT2
630 if (!hLibintlDLL)
631 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100632#endif
633 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100638 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200641 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 }
643 for (i = 0; libintl_entry[i].name != NULL
644 && libintl_entry[i].ptr != NULL; ++i)
645 {
646 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
647 libintl_entry[i].name)) == NULL)
648 {
649 dyn_libintl_end();
650 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000651 {
652 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100653 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000654 verbose_leave();
655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656 return 0;
657 }
658 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000659
660 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000661 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000662 "bind_textdomain_codeset");
663 if (dyn_libintl_bind_textdomain_codeset == NULL)
664 dyn_libintl_bind_textdomain_codeset =
665 null_libintl_bind_textdomain_codeset;
666
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200667 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100668 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
669 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100671 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
672 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674 return 1;
675}
676
677 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100678dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679{
680 if (hLibintlDLL)
681 FreeLibrary(hLibintlDLL);
682 hLibintlDLL = NULL;
683 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200684 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685 dyn_libintl_textdomain = null_libintl_textdomain;
686 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000687 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100688 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000689}
690
691 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000692null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693{
694 return (char*)msgid;
695}
696
697 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200698null_libintl_ngettext(
699 const char *msgid,
700 const char *msgid_plural,
701 unsigned long n)
702{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200703 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200704}
705
Bram Moolenaaree695f72016-08-03 22:08:45 +0200706 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100707null_libintl_bindtextdomain(
708 const char *domainname UNUSED,
709 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710{
711 return NULL;
712}
713
714 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100715null_libintl_bind_textdomain_codeset(
716 const char *domainname UNUSED,
717 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000718{
719 return NULL;
720}
721
722 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100723null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724{
725 return NULL;
726}
727
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200728 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100729null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100730{
731 return 0;
732}
733
Bram Moolenaar071d4272004-06-13 20:20:40 +0000734#endif /* DYNAMIC_GETTEXT */
735
736/* This symbol is not defined in older versions of the SDK or Visual C++ */
737
738#ifndef VER_PLATFORM_WIN32_WINDOWS
739# define VER_PLATFORM_WIN32_WINDOWS 1
740#endif
741
742DWORD g_PlatformId;
743
744#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100745# ifndef PROTO
746# include <aclapi.h>
747# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200748# ifndef PROTECTED_DACL_SECURITY_INFORMATION
749# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
750# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751#endif
752
Bram Moolenaar27515922013-06-29 15:36:26 +0200753#ifdef HAVE_ACL
754/*
755 * Enables or disables the specified privilege.
756 */
757 static BOOL
758win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
759{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100760 BOOL bResult;
761 LUID luid;
762 HANDLE hToken;
763 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200764
765 if (!OpenProcessToken(GetCurrentProcess(),
766 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
767 return FALSE;
768
769 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
770 {
771 CloseHandle(hToken);
772 return FALSE;
773 }
774
Bram Moolenaar45500912014-07-09 20:51:07 +0200775 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200776 tokenPrivileges.Privileges[0].Luid = luid;
777 tokenPrivileges.Privileges[0].Attributes = bEnable ?
778 SE_PRIVILEGE_ENABLED : 0;
779
780 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
781 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
782
783 CloseHandle(hToken);
784
785 return bResult && GetLastError() == ERROR_SUCCESS;
786}
787#endif
788
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789/*
790 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
791 * VER_PLATFORM_WIN32_WINDOWS (Win95).
792 */
793 void
794PlatformId(void)
795{
796 static int done = FALSE;
797
798 if (!done)
799 {
800 OSVERSIONINFO ovi;
801
802 ovi.dwOSVersionInfoSize = sizeof(ovi);
803 GetVersionEx(&ovi);
804
805 g_PlatformId = ovi.dwPlatformId;
806
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100807 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
808 || ovi.dwMajorVersion > 6)
809 win8_or_later = TRUE;
810
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200812 /* Enable privilege for getting or setting SACLs. */
813 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814#endif
815 done = TRUE;
816 }
817}
818
Bram Moolenaar4f974752019-02-17 17:44:42 +0100819#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820
821#define SHIFT (SHIFT_PRESSED)
822#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
823#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
824#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
825
826
827/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
828 * We map function keys to their ANSI terminal equivalents, as produced
829 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
830 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
831 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
832 * combinations of function/arrow/etc keys.
833 */
834
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000835static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836{
837 WORD wVirtKey;
838 BOOL fAnsiKey;
839 int chAlone;
840 int chShift;
841 int chCtrl;
842 int chAlt;
843} VirtKeyMap[] =
844{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200845// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
847
848 { VK_F1, TRUE, ';', 'T', '^', 'h', },
849 { VK_F2, TRUE, '<', 'U', '_', 'i', },
850 { VK_F3, TRUE, '=', 'V', '`', 'j', },
851 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
852 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
853 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
854 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
855 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
856 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
857 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200858 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
859 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200861 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
862 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
863 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
864 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
865 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
866 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
867 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
868 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
869 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
870 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100871 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200873 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
875#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200876 // Most people don't have F13-F20, but what the hell...
877 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
878 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
879 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
880 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
881 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
882 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
883 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
884 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200886 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
887 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
888 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
889 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200891 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
892 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
893 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
894 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
895 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
896 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
897 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
898 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
899 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
900 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100901 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902};
903
904
905#ifdef _MSC_VER
906// The ToAscii bug destroys several registers. Need to turn off optimization
907// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000908# pragma warning(push)
909# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910# pragma optimize("", off)
911#endif
912
913#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200914# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200916# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917#endif
918
919/* The return code indicates key code size. */
920 static int
921#ifdef __BORLANDC__
922 __stdcall
923#endif
924win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000925 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926{
927 UINT uMods = pker->dwControlKeyState;
928 static int s_iIsDead = 0;
929 static WORD awAnsiCode[2];
930 static BYTE abKeystate[256];
931
932
933 if (s_iIsDead == 2)
934 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936 s_iIsDead = 0;
937 return 1;
938 }
939
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200940 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 return 1;
942
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200943 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200946 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947
948 if (uMods & SHIFT_PRESSED)
949 abKeystate[VK_SHIFT] = 0x80;
950 if (uMods & CAPSLOCK_ON)
951 abKeystate[VK_CAPITAL] = 1;
952
953 if ((uMods & ALT_GR) == ALT_GR)
954 {
955 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
956 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
957 }
958
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200959 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
960 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200963 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964
965 return s_iIsDead;
966}
967
968#ifdef _MSC_VER
969/* MUST switch optimization on again here, otherwise a call to
970 * decode_key_event() may crash (e.g. when hitting caps-lock) */
971# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000972# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
974# if (_MSC_VER < 1100)
975/* MUST turn off global optimisation for this next function, or
976 * pressing ctrl-minus in insert mode crashes Vim when built with
977 * VC4.1. -- negri. */
978# pragma optimize("g", off)
979# endif
980#endif
981
982static BOOL g_fJustGotFocus = FALSE;
983
984/*
985 * Decode a KEY_EVENT into one or two keystrokes
986 */
987 static BOOL
988decode_key_event(
989 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200990 WCHAR *pch,
991 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 int *pmodifiers,
993 BOOL fDoPost)
994{
995 int i;
996 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
997
998 *pch = *pch2 = NUL;
999 g_fJustGotFocus = FALSE;
1000
1001 /* ignore key up events */
1002 if (!pker->bKeyDown)
1003 return FALSE;
1004
1005 /* ignore some keystrokes */
1006 switch (pker->wVirtualKeyCode)
1007 {
1008 /* modifiers */
1009 case VK_SHIFT:
1010 case VK_CONTROL:
1011 case VK_MENU: /* Alt key */
1012 return FALSE;
1013
1014 default:
1015 break;
1016 }
1017
1018 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001019 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 {
1021 /* Ctrl-6 is Ctrl-^ */
1022 if (pker->wVirtualKeyCode == '6')
1023 {
1024 *pch = Ctrl_HAT;
1025 return TRUE;
1026 }
1027 /* Ctrl-2 is Ctrl-@ */
1028 else if (pker->wVirtualKeyCode == '2')
1029 {
1030 *pch = NUL;
1031 return TRUE;
1032 }
1033 /* Ctrl-- is Ctrl-_ */
1034 else if (pker->wVirtualKeyCode == 0xBD)
1035 {
1036 *pch = Ctrl__;
1037 return TRUE;
1038 }
1039 }
1040
1041 /* Shift-TAB */
1042 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1043 {
1044 *pch = K_NUL;
1045 *pch2 = '\017';
1046 return TRUE;
1047 }
1048
1049 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1050 {
1051 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1052 {
1053 if (nModifs == 0)
1054 *pch = VirtKeyMap[i].chAlone;
1055 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1056 *pch = VirtKeyMap[i].chShift;
1057 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1058 *pch = VirtKeyMap[i].chCtrl;
1059 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1060 *pch = VirtKeyMap[i].chAlt;
1061
1062 if (*pch != 0)
1063 {
1064 if (VirtKeyMap[i].fAnsiKey)
1065 {
1066 *pch2 = *pch;
1067 *pch = K_NUL;
1068 }
1069
1070 return TRUE;
1071 }
1072 }
1073 }
1074
1075 i = win32_kbd_patch_key(pker);
1076
1077 if (i < 0)
1078 *pch = NUL;
1079 else
1080 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001081 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001082
1083 if (pmodifiers != NULL)
1084 {
1085 /* Pass on the ALT key as a modifier, but only when not combined
1086 * with CTRL (which is ALTGR). */
1087 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1088 *pmodifiers |= MOD_MASK_ALT;
1089
1090 /* Pass on SHIFT only for special keys, because we don't know when
1091 * it's already included with the character. */
1092 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1093 *pmodifiers |= MOD_MASK_SHIFT;
1094
1095 /* Pass on CTRL only for non-special keys, because we don't know
1096 * when it's already included with the character. And not when
1097 * combined with ALT (which is ALTGR). */
1098 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1099 && *pch >= 0x20 && *pch < 0x80)
1100 *pmodifiers |= MOD_MASK_CTRL;
1101 }
1102 }
1103
1104 return (*pch != NUL);
1105}
1106
1107#ifdef _MSC_VER
1108# pragma optimize("", on)
1109#endif
1110
Bram Moolenaar4f974752019-02-17 17:44:42 +01001111#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112
1113
1114#ifdef FEAT_MOUSE
1115
1116/*
1117 * For the GUI the mouse handling is in gui_w32.c.
1118 */
Bram Moolenaar4f974752019-02-17 17:44:42 +01001119# ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001121mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122{
1123}
1124# else
1125static int g_fMouseAvail = FALSE; /* mouse present */
1126static int g_fMouseActive = FALSE; /* mouse enabled */
1127static int g_nMouseClick = -1; /* mouse status */
1128static int g_xMouse; /* mouse x coordinate */
1129static int g_yMouse; /* mouse y coordinate */
1130
1131/*
1132 * Enable or disable mouse input
1133 */
1134 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001135mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137 DWORD cmodein;
1138
1139 if (!g_fMouseAvail)
1140 return;
1141
1142 g_fMouseActive = on;
1143 GetConsoleMode(g_hConIn, &cmodein);
1144
1145 if (g_fMouseActive)
1146 cmodein |= ENABLE_MOUSE_INPUT;
1147 else
1148 cmodein &= ~ENABLE_MOUSE_INPUT;
1149
1150 SetConsoleMode(g_hConIn, cmodein);
1151}
1152
Bram Moolenaar157d8132018-03-06 17:09:20 +01001153
1154#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1155/*
1156 * Called when 'balloonevalterm' changed.
1157 */
1158 void
1159mch_bevalterm_changed(void)
1160{
1161 mch_setmouse(g_fMouseActive);
1162}
1163#endif
1164
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165/*
1166 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1167 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1168 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1169 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1170 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1171 * and we return the mouse position in g_xMouse and g_yMouse.
1172 *
1173 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1174 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1175 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1176 *
1177 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1178 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1179 *
1180 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1181 * moves, even if it stays within the same character cell. We ignore
1182 * all MOUSE_MOVED messages if the position hasn't really changed, and
1183 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1184 * we're only interested in MOUSE_DRAG).
1185 *
1186 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1187 * 2-button mouses by pressing the left & right buttons simultaneously.
1188 * In practice, it's almost impossible to click both at the same time,
1189 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1190 * in such cases, if the user is clicking quickly.
1191 */
1192 static BOOL
1193decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001194 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195{
1196 static int s_nOldButton = -1;
1197 static int s_nOldMouseClick = -1;
1198 static int s_xOldMouse = -1;
1199 static int s_yOldMouse = -1;
1200 static linenr_T s_old_topline = 0;
1201#ifdef FEAT_DIFF
1202 static int s_old_topfill = 0;
1203#endif
1204 static int s_cClicks = 1;
1205 static BOOL s_fReleased = TRUE;
1206 static DWORD s_dwLastClickTime = 0;
1207 static BOOL s_fNextIsMiddle = FALSE;
1208
1209 static DWORD cButtons = 0; /* number of buttons supported */
1210
1211 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1212 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1213 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1214 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1215
1216 int nButton;
1217
1218 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1219 cButtons = 2;
1220
1221 if (!g_fMouseAvail || !g_fMouseActive)
1222 {
1223 g_nMouseClick = -1;
1224 return FALSE;
1225 }
1226
1227 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1228 if (g_fJustGotFocus)
1229 {
1230 g_fJustGotFocus = FALSE;
1231 return FALSE;
1232 }
1233
1234 /* unprocessed mouse click? */
1235 if (g_nMouseClick != -1)
1236 return TRUE;
1237
1238 nButton = -1;
1239 g_xMouse = pmer->dwMousePosition.X;
1240 g_yMouse = pmer->dwMousePosition.Y;
1241
1242 if (pmer->dwEventFlags == MOUSE_MOVED)
1243 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001244 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 * events even when the mouse moves only within a char cell.) */
1246 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1247 return FALSE;
1248 }
1249
1250 /* If no buttons are pressed... */
1251 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1252 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001253 nButton = MOUSE_RELEASE;
1254
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1256 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001257 {
1258#ifdef FEAT_BEVAL_TERM
1259 /* do return mouse move events when we want them */
1260 if (p_bevalterm)
1261 nButton = MOUSE_DRAG;
1262 else
1263#endif
1264 return FALSE;
1265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267 s_fReleased = TRUE;
1268 }
1269 else /* one or more buttons pressed */
1270 {
1271 /* on a 2-button mouse, hold down left and right buttons
1272 * simultaneously to get MIDDLE. */
1273
1274 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1275 {
1276 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1277
1278 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001279 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280 if (dwLR == LEFT || dwLR == RIGHT)
1281 {
1282 for (;;)
1283 {
1284 /* wait a short time for next input event */
1285 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1286 != WAIT_OBJECT_0)
1287 break;
1288 else
1289 {
1290 DWORD cRecords = 0;
1291 INPUT_RECORD ir;
1292 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1293
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001294 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001295
1296 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1297 || !(pmer2->dwButtonState & LEFT_RIGHT))
1298 break;
1299 else
1300 {
1301 if (pmer2->dwEventFlags != MOUSE_MOVED)
1302 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001303 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304
1305 return decode_mouse_event(pmer2);
1306 }
1307 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1308 s_yOldMouse == pmer2->dwMousePosition.Y)
1309 {
1310 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001311 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312
1313 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001314 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315
1316 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1317 break;
1318 }
1319 else
1320 break;
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 if (s_fNextIsMiddle)
1328 {
1329 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1330 ? MOUSE_DRAG : MOUSE_MIDDLE;
1331 s_fNextIsMiddle = FALSE;
1332 }
1333 else if (cButtons == 2 &&
1334 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1335 {
1336 nButton = MOUSE_MIDDLE;
1337
1338 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1339 {
1340 s_fNextIsMiddle = TRUE;
1341 nButton = MOUSE_RELEASE;
1342 }
1343 }
1344 else if ((pmer->dwButtonState & LEFT) == LEFT)
1345 nButton = MOUSE_LEFT;
1346 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1347 nButton = MOUSE_MIDDLE;
1348 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1349 nButton = MOUSE_RIGHT;
1350
1351 if (! s_fReleased && ! s_fNextIsMiddle
1352 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1353 return FALSE;
1354
1355 s_fReleased = s_fNextIsMiddle;
1356 }
1357
1358 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1359 {
1360 /* button pressed or released, without mouse moving */
1361 if (nButton != -1 && nButton != MOUSE_RELEASE)
1362 {
1363 DWORD dwCurrentTime = GetTickCount();
1364
1365 if (s_xOldMouse != g_xMouse
1366 || s_yOldMouse != g_yMouse
1367 || s_nOldButton != nButton
1368 || s_old_topline != curwin->w_topline
1369#ifdef FEAT_DIFF
1370 || s_old_topfill != curwin->w_topfill
1371#endif
1372 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1373 {
1374 s_cClicks = 1;
1375 }
1376 else if (++s_cClicks > 4)
1377 {
1378 s_cClicks = 1;
1379 }
1380
1381 s_dwLastClickTime = dwCurrentTime;
1382 }
1383 }
1384 else if (pmer->dwEventFlags == MOUSE_MOVED)
1385 {
1386 if (nButton != -1 && nButton != MOUSE_RELEASE)
1387 nButton = MOUSE_DRAG;
1388
1389 s_cClicks = 1;
1390 }
1391
1392 if (nButton == -1)
1393 return FALSE;
1394
1395 if (nButton != MOUSE_RELEASE)
1396 s_nOldButton = nButton;
1397
1398 g_nMouseClick = nButton;
1399
1400 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1401 g_nMouseClick |= MOUSE_SHIFT;
1402 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1403 g_nMouseClick |= MOUSE_CTRL;
1404 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1405 g_nMouseClick |= MOUSE_ALT;
1406
1407 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1408 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1409
1410 /* only pass on interesting (i.e., different) mouse events */
1411 if (s_xOldMouse == g_xMouse
1412 && s_yOldMouse == g_yMouse
1413 && s_nOldMouseClick == g_nMouseClick)
1414 {
1415 g_nMouseClick = -1;
1416 return FALSE;
1417 }
1418
1419 s_xOldMouse = g_xMouse;
1420 s_yOldMouse = g_yMouse;
1421 s_old_topline = curwin->w_topline;
1422#ifdef FEAT_DIFF
1423 s_old_topfill = curwin->w_topfill;
1424#endif
1425 s_nOldMouseClick = g_nMouseClick;
1426
1427 return TRUE;
1428}
1429
Bram Moolenaar4f974752019-02-17 17:44:42 +01001430# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431#endif /* FEAT_MOUSE */
1432
1433
1434#ifdef MCH_CURSOR_SHAPE
1435/*
1436 * Set the shape of the cursor.
1437 * 'thickness' can be from 1 (thin) to 99 (block)
1438 */
1439 static void
1440mch_set_cursor_shape(int thickness)
1441{
1442 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1443 ConsoleCursorInfo.dwSize = thickness;
1444 ConsoleCursorInfo.bVisible = s_cursor_visible;
1445
1446 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1447 if (s_cursor_visible)
1448 SetConsoleCursorPosition(g_hConOut, g_coord);
1449}
1450
1451 void
1452mch_update_cursor(void)
1453{
1454 int idx;
1455 int thickness;
1456
1457 /*
1458 * How the cursor is drawn depends on the current mode.
1459 */
1460 idx = get_shape_idx(FALSE);
1461
1462 if (shape_table[idx].shape == SHAPE_BLOCK)
1463 thickness = 99; /* 100 doesn't work on W95 */
1464 else
1465 thickness = shape_table[idx].percentage;
1466 mch_set_cursor_shape(thickness);
1467}
1468#endif
1469
Bram Moolenaar4f974752019-02-17 17:44:42 +01001470#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471/*
1472 * Handle FOCUS_EVENT.
1473 */
1474 static void
1475handle_focus_event(INPUT_RECORD ir)
1476{
1477 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1478 ui_focus_change((int)g_fJustGotFocus);
1479}
1480
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001481static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1482
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483/*
1484 * Wait until console input from keyboard or mouse is available,
1485 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001486 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 * Return TRUE if something is available FALSE if not.
1488 */
1489 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001490WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491{
1492 DWORD dwNow = 0, dwEndTime = 0;
1493 INPUT_RECORD ir;
1494 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001495 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001496#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001497 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001498#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499
1500 if (msec > 0)
1501 /* Wait until the specified time has elapsed. */
1502 dwEndTime = GetTickCount() + msec;
1503 else if (msec < 0)
1504 /* Wait forever. */
1505 dwEndTime = INFINITE;
1506
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001507 // We need to loop until the end of the time period, because
1508 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509 for (;;)
1510 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001511 // Only process messages when waiting.
1512 if (msec != 0)
1513 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001514#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001515 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001516#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001517#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001518 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001519#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001521 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001524
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 if (0
1526#ifdef FEAT_MOUSE
1527 || g_nMouseClick != -1
1528#endif
1529#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001530 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531#endif
1532 )
1533 return TRUE;
1534
1535 if (msec > 0)
1536 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001537 /* If the specified wait time has passed, return. Beware that
1538 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001540 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 break;
1542 }
1543 if (msec != 0)
1544 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001545 DWORD dwWaitTime = dwEndTime - dwNow;
1546
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001547#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001548 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001549 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001550 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001551 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001552 /* If there is readahead then parse_queued_messages() timed out
1553 * and we should call it again soon. */
1554 if (channel_any_readahead())
1555 dwWaitTime = 10;
1556 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001557#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001558#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001559 if (p_beval && dwWaitTime > 100)
1560 /* The 'balloonexpr' may indirectly invoke a callback while
1561 * waiting for a character, need to check often. */
1562 dwWaitTime = 100;
1563#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001564#ifdef FEAT_MZSCHEME
1565 if (mzthreads_allowed() && p_mzq > 0
1566 && (msec < 0 || (long)dwWaitTime > p_mzq))
1567 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1568#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001569#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001570 // When waiting very briefly don't trigger timers.
1571 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001572 {
1573 long due_time;
1574
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001575 // Trigger timers and then get the time in msec until the next
1576 // one is due. Wait up to that time.
1577 due_time = check_due_timer();
1578 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001579 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001580 // timer may have used feedkeys().
1581 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001582 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001583 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1584 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001585 }
1586#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001587 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001589 // Wait for either an event on the console input or a
1590 // message in the client-server window.
1591 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1592 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 wait_for_single_object(g_hConIn, dwWaitTime)
1595 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001597 )
1598 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 }
1600
1601 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001602 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603
1604#ifdef FEAT_MBYTE_IME
1605 if (State & CMDLINE && msg_row == Rows - 1)
1606 {
1607 CONSOLE_SCREEN_BUFFER_INFO csbi;
1608
1609 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1610 {
1611 if (csbi.dwCursorPosition.Y != msg_row)
1612 {
1613 /* The screen is now messed up, must redraw the
1614 * command line and later all the windows. */
1615 redraw_all_later(CLEAR);
1616 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1617 redrawcmd();
1618 }
1619 }
1620 }
1621#endif
1622
1623 if (cRecords > 0)
1624 {
1625 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1626 {
1627#ifdef FEAT_MBYTE_IME
1628 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1629 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001630 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1632 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001633 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 continue;
1635 }
1636#endif
1637 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1638 NULL, FALSE))
1639 return TRUE;
1640 }
1641
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001642 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643
1644 if (ir.EventType == FOCUS_EVENT)
1645 handle_focus_event(ir);
1646 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001647 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001648 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1649
1650 // Only call shell_resized() when the size actually change to
1651 // avoid the screen is cleard.
1652 if (dwSize.X != Columns || dwSize.Y != Rows)
1653 {
1654 CONSOLE_SCREEN_BUFFER_INFO csbi;
1655 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1656 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1657 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001658 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001659 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661#ifdef FEAT_MOUSE
1662 else if (ir.EventType == MOUSE_EVENT
1663 && decode_mouse_event(&ir.Event.MouseEvent))
1664 return TRUE;
1665#endif
1666 }
1667 else if (msec == 0)
1668 break;
1669 }
1670
1671#ifdef FEAT_CLIENTSERVER
1672 /* Something might have been received while we were waiting. */
1673 if (input_available())
1674 return TRUE;
1675#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001676
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 return FALSE;
1678}
1679
1680#ifndef FEAT_GUI_MSWIN
1681/*
1682 * return non-zero if a character is available
1683 */
1684 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001685mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001687 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001689
1690# if defined(FEAT_TERMINAL) || defined(PROTO)
1691/*
1692 * Check for any pending input or messages.
1693 */
1694 int
1695mch_check_messages(void)
1696{
1697 return WaitForChar(0L, TRUE);
1698}
1699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700#endif
1701
1702/*
1703 * Create the console input. Used when reading stdin doesn't work.
1704 */
1705 static void
1706create_conin(void)
1707{
1708 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1709 FILE_SHARE_READ|FILE_SHARE_WRITE,
1710 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001711 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 did_create_conin = TRUE;
1713}
1714
1715/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001716 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001718 static WCHAR
1719tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001721 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722
1723 for (;;)
1724 {
1725 INPUT_RECORD ir;
1726 DWORD cRecords = 0;
1727
1728#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001729 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (input_available())
1731 return 0;
1732# ifdef FEAT_MOUSE
1733 if (g_nMouseClick != -1)
1734 return 0;
1735# endif
1736#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001737 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 {
1739 if (did_create_conin)
1740 read_error_exit();
1741 create_conin();
1742 continue;
1743 }
1744
1745 if (ir.EventType == KEY_EVENT)
1746 {
1747 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1748 pmodifiers, TRUE))
1749 return ch;
1750 }
1751 else if (ir.EventType == FOCUS_EVENT)
1752 handle_focus_event(ir);
1753 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1754 shell_resized();
1755#ifdef FEAT_MOUSE
1756 else if (ir.EventType == MOUSE_EVENT)
1757 {
1758 if (decode_mouse_event(&ir.Event.MouseEvent))
1759 return 0;
1760 }
1761#endif
1762 }
1763}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001764#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765
1766
1767/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001768 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 * Get one or more characters from the keyboard or the mouse.
1770 * If time == 0, do not wait for characters.
1771 * If time == n, wait a short time for characters.
1772 * If time == -1, wait forever for characters.
1773 * Returns the number of characters read into buf.
1774 */
1775 int
1776mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001777 char_u *buf UNUSED,
1778 int maxlen UNUSED,
1779 long time UNUSED,
1780 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781{
Bram Moolenaar4f974752019-02-17 17:44:42 +01001782#ifndef FEAT_GUI_MSWIN /* this isn't used for the GUI */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783
1784 int len;
1785 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786#define TYPEAHEADLEN 20
1787 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1788 static int typeaheadlen = 0;
1789
1790 /* First use any typeahead that was kept because "buf" was too small. */
1791 if (typeaheadlen > 0)
1792 goto theend;
1793
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 if (time >= 0)
1795 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001796 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799 else /* time == -1, wait forever */
1800 {
1801 mch_set_winsize_now(); /* Allow winsize changes from now on */
1802
Bram Moolenaar3918c952005-03-15 22:34:55 +00001803 /*
1804 * If there is no character available within 2 seconds (default)
1805 * write the autoscript file to disk. Or cause the CursorHold event
1806 * to be triggered.
1807 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001808 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001810 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001812 buf[0] = K_SPECIAL;
1813 buf[1] = KS_EXTRA;
1814 buf[2] = (int)KE_CURSORHOLD;
1815 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001817 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819 }
1820
1821 /*
1822 * Try to read as many characters as there are, until the buffer is full.
1823 */
1824
1825 /* we will get at least one key. Get more if they are available. */
1826 g_fCBrkPressed = FALSE;
1827
1828#ifdef MCH_WRITE_DUMP
1829 if (fdDump)
1830 fputc('[', fdDump);
1831#endif
1832
1833 /* Keep looping until there is something in the typeahead buffer and more
1834 * to get and still room in the buffer (up to two bytes for a char and
1835 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001836 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 && typeaheadlen + 5 <= TYPEAHEADLEN)
1838 {
1839 if (typebuf_changed(tb_change_cnt))
1840 {
1841 /* "buf" may be invalid now if a client put something in the
1842 * typeahead buffer and "buf" is in the typeahead buffer. */
1843 typeaheadlen = 0;
1844 break;
1845 }
1846#ifdef FEAT_MOUSE
1847 if (g_nMouseClick != -1)
1848 {
1849# ifdef MCH_WRITE_DUMP
1850 if (fdDump)
1851 fprintf(fdDump, "{%02x @ %d, %d}",
1852 g_nMouseClick, g_xMouse, g_yMouse);
1853# endif
1854 typeahead[typeaheadlen++] = ESC + 128;
1855 typeahead[typeaheadlen++] = 'M';
1856 typeahead[typeaheadlen++] = g_nMouseClick;
1857 typeahead[typeaheadlen++] = g_xMouse + '!';
1858 typeahead[typeaheadlen++] = g_yMouse + '!';
1859 g_nMouseClick = -1;
1860 }
1861 else
1862#endif
1863 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001864 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 int modifiers = 0;
1866
1867 c = tgetch(&modifiers, &ch2);
1868
1869 if (typebuf_changed(tb_change_cnt))
1870 {
1871 /* "buf" may be invalid now if a client put something in the
1872 * typeahead buffer and "buf" is in the typeahead buffer. */
1873 typeaheadlen = 0;
1874 break;
1875 }
1876
1877 if (c == Ctrl_C && ctrl_c_interrupts)
1878 {
1879#if defined(FEAT_CLIENTSERVER)
1880 trash_input_buf();
1881#endif
1882 got_int = TRUE;
1883 }
1884
1885#ifdef FEAT_MOUSE
1886 if (g_nMouseClick == -1)
1887#endif
1888 {
1889 int n = 1;
1890
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001891 if (ch2 == NUL)
1892 {
1893 int i;
1894 char_u *p;
1895 WCHAR ch[2];
1896
1897 ch[0] = c;
1898 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1899 {
1900 ch[1] = tgetch(&modifiers, &ch2);
1901 n++;
1902 }
1903 p = utf16_to_enc(ch, &n);
1904 if (p != NULL)
1905 {
1906 for (i = 0; i < n; i++)
1907 typeahead[typeaheadlen + i] = p[i];
1908 vim_free(p);
1909 }
1910 }
1911 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001912 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 if (ch2 != NUL)
1914 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001915 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001916 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001917 switch (ch2)
1918 {
1919 case (WCHAR)'\324': // SHIFT+Insert
1920 case (WCHAR)'\325': // CTRL+Insert
1921 case (WCHAR)'\327': // SHIFT+Delete
1922 case (WCHAR)'\330': // CTRL+Delete
1923 typeahead[typeaheadlen + n] = (char_u)ch2;
1924 n++;
1925 break;
1926
1927 default:
1928 typeahead[typeaheadlen + n] = 3;
1929 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1930 n += 2;
1931 break;
1932 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001933 }
1934 else
1935 {
1936 typeahead[typeaheadlen + n] = 3;
1937 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1938 n += 2;
1939 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001940 }
1941
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 /* Use the ALT key to set the 8th bit of the character
1943 * when it's one byte, the 8th bit isn't set yet and not
1944 * using a double-byte encoding (would become a lead
1945 * byte). */
1946 if ((modifiers & MOD_MASK_ALT)
1947 && n == 1
1948 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 )
1951 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001952 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1953 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 modifiers &= ~MOD_MASK_ALT;
1955 }
1956
1957 if (modifiers != 0)
1958 {
1959 /* Prepend modifiers to the character. */
1960 mch_memmove(typeahead + typeaheadlen + 3,
1961 typeahead + typeaheadlen, n);
1962 typeahead[typeaheadlen++] = K_SPECIAL;
1963 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1964 typeahead[typeaheadlen++] = modifiers;
1965 }
1966
1967 typeaheadlen += n;
1968
1969#ifdef MCH_WRITE_DUMP
1970 if (fdDump)
1971 fputc(c, fdDump);
1972#endif
1973 }
1974 }
1975 }
1976
1977#ifdef MCH_WRITE_DUMP
1978 if (fdDump)
1979 {
1980 fputs("]\n", fdDump);
1981 fflush(fdDump);
1982 }
1983#endif
1984
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985theend:
1986 /* Move typeahead to "buf", as much as fits. */
1987 len = 0;
1988 while (len < maxlen && typeaheadlen > 0)
1989 {
1990 buf[len++] = typeahead[0];
1991 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1992 }
1993 return len;
1994
Bram Moolenaar4f974752019-02-17 17:44:42 +01001995#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001997#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998}
1999
Bram Moolenaar82881492012-11-20 16:53:39 +01002000#ifndef PROTO
2001# ifndef __MINGW32__
2002# include <shellapi.h> /* required for FindExecutable() */
2003# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002004#endif
2005
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002006/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002007 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2008 * If "use_path" is FALSE: Return TRUE if "name" exists.
2009 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2010 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002011 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002012 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002014executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002016 WCHAR *p;
2017 WCHAR fnamew[_MAX_PATH];
2018 WCHAR *dumw;
2019 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002020 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021
Bram Moolenaar43663192017-03-05 14:29:12 +01002022 if (!use_path)
2023 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002024 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002025 {
2026 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002027 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002028 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002029 *path = vim_strsave((char_u *)name);
2030 else
2031 *path = FullName_save((char_u *)name, FALSE);
2032 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002033 return TRUE;
2034 }
2035 return FALSE;
2036 }
2037
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002038 p = enc_to_utf16((char_u *)name, NULL);
2039 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002040 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002041
2042 wcurpath = _wgetenv(L"PATH");
2043 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2044 * sizeof(WCHAR));
2045 if (wnewpath == NULL)
2046 return FALSE;
2047 wcscpy(wnewpath, L".;");
2048 wcscat(wnewpath, wcurpath);
2049 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2050 vim_free(wnewpath);
2051 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002052 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002053 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002054 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002055 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002056 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002057 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002058 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059}
2060
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002061#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2062 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002063/*
2064 * Bad parameter handler.
2065 *
2066 * Certain MS CRT functions will intentionally crash when passed invalid
2067 * parameters to highlight possible security holes. Setting this function as
2068 * the bad parameter handler will prevent the crash.
2069 *
2070 * In debug builds the parameters contain CRT information that might help track
2071 * down the source of a problem, but in non-debug builds the arguments are all
2072 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2073 * worth allowing these to make debugging of issues easier.
2074 */
2075 static void
2076bad_param_handler(const wchar_t *expression,
2077 const wchar_t *function,
2078 const wchar_t *file,
2079 unsigned int line,
2080 uintptr_t pReserved)
2081{
2082}
2083
2084# define SET_INVALID_PARAM_HANDLER \
2085 ((void)_set_invalid_parameter_handler(bad_param_handler))
2086#else
2087# define SET_INVALID_PARAM_HANDLER
2088#endif
2089
Bram Moolenaar4f974752019-02-17 17:44:42 +01002090#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091
2092/*
2093 * GUI version of mch_init().
2094 */
2095 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002096mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097{
2098#ifndef __MINGW32__
2099 extern int _fmode;
2100#endif
2101
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002102 /* Silently handle invalid parameters to CRT functions */
2103 SET_INVALID_PARAM_HANDLER;
2104
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105 /* Let critical errors result in a failure, not in a dialog box. Required
2106 * for the timestamp test to work on removed floppies. */
2107 SetErrorMode(SEM_FAILCRITICALERRORS);
2108
2109 _fmode = O_BINARY; /* we do our own CR-LF translation */
2110
2111 /* Specify window size. Is there a place to get the default from? */
2112 Rows = 25;
2113 Columns = 80;
2114
2115 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116 {
2117 char_u vimrun_location[_MAX_PATH + 4];
2118
2119 /* First try in same directory as gvim.exe */
2120 STRCPY(vimrun_location, exe_name);
2121 STRCPY(gettail(vimrun_location), "vimrun.exe");
2122 if (mch_getperm(vimrun_location) >= 0)
2123 {
2124 if (*skiptowhite(vimrun_location) != NUL)
2125 {
2126 /* Enclose path with white space in double quotes. */
2127 mch_memmove(vimrun_location + 1, vimrun_location,
2128 STRLEN(vimrun_location) + 1);
2129 *vimrun_location = '"';
2130 STRCPY(gettail(vimrun_location), "vimrun\" ");
2131 }
2132 else
2133 STRCPY(gettail(vimrun_location), "vimrun ");
2134
2135 vimrun_path = (char *)vim_strsave(vimrun_location);
2136 s_dont_use_vimrun = FALSE;
2137 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002138 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 s_dont_use_vimrun = FALSE;
2140
2141 /* Don't give the warning for a missing vimrun.exe right now, but only
2142 * when vimrun was supposed to be used. Don't bother people that do
2143 * not need vimrun.exe. */
2144 if (s_dont_use_vimrun)
2145 need_vimrun_warning = TRUE;
2146 }
2147
2148 /*
2149 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2150 * Otherwise the default "findstr /n" is used.
2151 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002152 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2154
2155#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002156 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002157#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002158
2159 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160}
2161
2162
Bram Moolenaar4f974752019-02-17 17:44:42 +01002163#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164
2165#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2166#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2167
2168/*
2169 * ClearConsoleBuffer()
2170 * Description:
2171 * Clears the entire contents of the console screen buffer, using the
2172 * specified attribute.
2173 * Returns:
2174 * TRUE on success
2175 */
2176 static BOOL
2177ClearConsoleBuffer(WORD wAttribute)
2178{
2179 CONSOLE_SCREEN_BUFFER_INFO csbi;
2180 COORD coord;
2181 DWORD NumCells, dummy;
2182
2183 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2184 return FALSE;
2185
2186 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2187 coord.X = 0;
2188 coord.Y = 0;
2189 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2190 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2193 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195
2196 return TRUE;
2197}
2198
2199/*
2200 * FitConsoleWindow()
2201 * Description:
2202 * Checks if the console window will fit within given buffer dimensions.
2203 * Also, if requested, will shrink the window to fit.
2204 * Returns:
2205 * TRUE on success
2206 */
2207 static BOOL
2208FitConsoleWindow(
2209 COORD dwBufferSize,
2210 BOOL WantAdjust)
2211{
2212 CONSOLE_SCREEN_BUFFER_INFO csbi;
2213 COORD dwWindowSize;
2214 BOOL NeedAdjust = FALSE;
2215
2216 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2217 {
2218 /*
2219 * A buffer resize will fail if the current console window does
2220 * not lie completely within that buffer. To avoid this, we might
2221 * have to move and possibly shrink the window.
2222 */
2223 if (csbi.srWindow.Right >= dwBufferSize.X)
2224 {
2225 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2226 if (dwWindowSize.X > dwBufferSize.X)
2227 dwWindowSize.X = dwBufferSize.X;
2228 csbi.srWindow.Right = dwBufferSize.X - 1;
2229 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2230 NeedAdjust = TRUE;
2231 }
2232 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2233 {
2234 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2235 if (dwWindowSize.Y > dwBufferSize.Y)
2236 dwWindowSize.Y = dwBufferSize.Y;
2237 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2238 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2239 NeedAdjust = TRUE;
2240 }
2241 if (NeedAdjust && WantAdjust)
2242 {
2243 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2244 return FALSE;
2245 }
2246 return TRUE;
2247 }
2248
2249 return FALSE;
2250}
2251
2252typedef struct ConsoleBufferStruct
2253{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002254 BOOL IsValid;
2255 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002256 PCHAR_INFO Buffer;
2257 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002258 PSMALL_RECT Regions;
2259 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260} ConsoleBuffer;
2261
2262/*
2263 * SaveConsoleBuffer()
2264 * Description:
2265 * Saves important information about the console buffer, including the
2266 * actual buffer contents. The saved information is suitable for later
2267 * restoration by RestoreConsoleBuffer().
2268 * Returns:
2269 * TRUE if all information was saved; FALSE otherwise
2270 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2271 */
2272 static BOOL
2273SaveConsoleBuffer(
2274 ConsoleBuffer *cb)
2275{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002276 DWORD NumCells;
2277 COORD BufferCoord;
2278 SMALL_RECT ReadRegion;
2279 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002280 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002281
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 if (cb == NULL)
2283 return FALSE;
2284
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002285 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 {
2287 cb->IsValid = FALSE;
2288 return FALSE;
2289 }
2290 cb->IsValid = TRUE;
2291
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 /*
2293 * Allocate a buffer large enough to hold the entire console screen
2294 * buffer. If this ConsoleBuffer structure has already been initialized
2295 * with a buffer of the correct size, then just use that one.
2296 */
2297 if (!cb->IsValid || cb->Buffer == NULL ||
2298 cb->BufferSize.X != cb->Info.dwSize.X ||
2299 cb->BufferSize.Y != cb->Info.dwSize.Y)
2300 {
2301 cb->BufferSize.X = cb->Info.dwSize.X;
2302 cb->BufferSize.Y = cb->Info.dwSize.Y;
2303 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2304 vim_free(cb->Buffer);
2305 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2306 if (cb->Buffer == NULL)
2307 return FALSE;
2308 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309
2310 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002311 * We will now copy the console screen buffer into our buffer.
2312 * ReadConsoleOutput() seems to be limited as far as how much you
2313 * can read at a time. Empirically, this number seems to be about
2314 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2315 * in chunks until it is all copied. The chunks will all have the
2316 * same horizontal characteristics, so initialize them now. The
2317 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002319 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002320 ReadRegion.Left = 0;
2321 ReadRegion.Right = cb->Info.dwSize.X - 1;
2322 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002323
2324 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2325 if (cb->Regions == NULL || numregions != cb->NumRegions)
2326 {
2327 cb->NumRegions = numregions;
2328 vim_free(cb->Regions);
2329 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2330 if (cb->Regions == NULL)
2331 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002332 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002333 return FALSE;
2334 }
2335 }
2336
2337 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002339 /*
2340 * Read into position (0, Y) in our buffer.
2341 */
2342 BufferCoord.Y = Y;
2343 /*
2344 * Read the region whose top left corner is (0, Y) and whose bottom
2345 * right corner is (width - 1, Y + Y_incr - 1). This should define
2346 * a region of size width by Y_incr. Don't worry if this region is
2347 * too large for the remaining buffer; it will be cropped.
2348 */
2349 ReadRegion.Top = Y;
2350 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002351 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002352 cb->Buffer, /* our buffer */
2353 cb->BufferSize, /* dimensions of our buffer */
2354 BufferCoord, /* offset in our buffer */
2355 &ReadRegion)) /* region to save */
2356 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002357 VIM_CLEAR(cb->Buffer);
2358 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002359 return FALSE;
2360 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002361 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362 }
2363
2364 return TRUE;
2365}
2366
2367/*
2368 * RestoreConsoleBuffer()
2369 * Description:
2370 * Restores important information about the console buffer, including the
2371 * actual buffer contents, if desired. The information to restore is in
2372 * the same format used by SaveConsoleBuffer().
2373 * Returns:
2374 * TRUE on success
2375 */
2376 static BOOL
2377RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002378 ConsoleBuffer *cb,
2379 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002381 COORD BufferCoord;
2382 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002383 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384
2385 if (cb == NULL || !cb->IsValid)
2386 return FALSE;
2387
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002388 /*
2389 * Before restoring the buffer contents, clear the current buffer, and
2390 * restore the cursor position and window information. Doing this now
2391 * prevents old buffer contents from "flashing" onto the screen.
2392 */
2393 if (RestoreScreen)
2394 ClearConsoleBuffer(cb->Info.wAttributes);
2395
2396 FitConsoleWindow(cb->Info.dwSize, TRUE);
2397 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2398 return FALSE;
2399 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2400 return FALSE;
2401
2402 if (!RestoreScreen)
2403 {
2404 /*
2405 * No need to restore the screen buffer contents, so we're done.
2406 */
2407 return TRUE;
2408 }
2409
2410 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2411 return FALSE;
2412 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2413 return FALSE;
2414
2415 /*
2416 * Restore the screen buffer contents.
2417 */
2418 if (cb->Buffer != NULL)
2419 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002420 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002421 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002422 BufferCoord.X = cb->Regions[i].Left;
2423 BufferCoord.Y = cb->Regions[i].Top;
2424 WriteRegion = cb->Regions[i];
2425 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2426 cb->Buffer, /* our buffer */
2427 cb->BufferSize, /* dimensions of our buffer */
2428 BufferCoord, /* offset in our buffer */
2429 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002430 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002431 }
2432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433
2434 return TRUE;
2435}
2436
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002437#define FEAT_RESTORE_ORIG_SCREEN
2438#ifdef FEAT_RESTORE_ORIG_SCREEN
2439static ConsoleBuffer g_cbOrig = { 0 };
2440#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441static ConsoleBuffer g_cbNonTermcap = { 0 };
2442static ConsoleBuffer g_cbTermcap = { 0 };
2443
2444#ifdef FEAT_TITLE
2445#ifdef __BORLANDC__
2446typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2447#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002448typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449#endif
2450char g_szOrigTitle[256] = { 0 };
2451HWND g_hWnd = NULL; /* also used in os_mswin.c */
2452static HICON g_hOrigIconSmall = NULL;
2453static HICON g_hOrigIcon = NULL;
2454static HICON g_hVimIcon = NULL;
2455static BOOL g_fCanChangeIcon = FALSE;
2456
2457/* ICON* are not defined in VC++ 4.0 */
2458#ifndef ICON_SMALL
2459#define ICON_SMALL 0
2460#endif
2461#ifndef ICON_BIG
2462#define ICON_BIG 1
2463#endif
2464/*
2465 * GetConsoleIcon()
2466 * Description:
2467 * Attempts to retrieve the small icon and/or the big icon currently in
2468 * use by a given window.
2469 * Returns:
2470 * TRUE on success
2471 */
2472 static BOOL
2473GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002474 HWND hWnd,
2475 HICON *phIconSmall,
2476 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477{
2478 if (hWnd == NULL)
2479 return FALSE;
2480
2481 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002482 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2483 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002485 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2486 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 return TRUE;
2488}
2489
2490/*
2491 * SetConsoleIcon()
2492 * Description:
2493 * Attempts to change the small icon and/or the big icon currently in
2494 * use by a given window.
2495 * Returns:
2496 * TRUE on success
2497 */
2498 static BOOL
2499SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002500 HWND hWnd,
2501 HICON hIconSmall,
2502 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 if (hWnd == NULL)
2505 return FALSE;
2506
2507 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002508 SendMessage(hWnd, WM_SETICON,
2509 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002511 SendMessage(hWnd, WM_SETICON,
2512 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 return TRUE;
2514}
2515
2516/*
2517 * SaveConsoleTitleAndIcon()
2518 * Description:
2519 * Saves the current console window title in g_szOrigTitle, for later
2520 * restoration. Also, attempts to obtain a handle to the console window,
2521 * and use it to save the small and big icons currently in use by the
2522 * console window. This is not always possible on some versions of Windows;
2523 * nor is it possible when running Vim remotely using Telnet (since the
2524 * console window the user sees is owned by a remote process).
2525 */
2526 static void
2527SaveConsoleTitleAndIcon(void)
2528{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 /* Save the original title. */
2530 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2531 return;
2532
2533 /*
2534 * Obtain a handle to the console window using GetConsoleWindow() from
2535 * KERNEL32.DLL; we need to handle in order to change the window icon.
2536 * This function only exists on NT-based Windows, starting with Windows
2537 * 2000. On older operating systems, we can't change the window icon
2538 * anyway.
2539 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002540 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 if (g_hWnd == NULL)
2542 return;
2543
2544 /* Save the original console window icon. */
2545 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2546 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2547 return;
2548
2549 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002550 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002551 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 if (g_hVimIcon != NULL)
2553 g_fCanChangeIcon = TRUE;
2554}
2555#endif
2556
2557static int g_fWindInitCalled = FALSE;
2558static int g_fTermcapMode = FALSE;
2559static CONSOLE_CURSOR_INFO g_cci;
2560static DWORD g_cmodein = 0;
2561static DWORD g_cmodeout = 0;
2562
2563/*
2564 * non-GUI version of mch_init().
2565 */
2566 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002567mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002569#ifndef FEAT_RESTORE_ORIG_SCREEN
2570 CONSOLE_SCREEN_BUFFER_INFO csbi;
2571#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572#ifndef __MINGW32__
2573 extern int _fmode;
2574#endif
2575
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002576 /* Silently handle invalid parameters to CRT functions */
2577 SET_INVALID_PARAM_HANDLER;
2578
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 /* Let critical errors result in a failure, not in a dialog box. Required
2580 * for the timestamp test to work on removed floppies. */
2581 SetErrorMode(SEM_FAILCRITICALERRORS);
2582
2583 _fmode = O_BINARY; /* we do our own CR-LF translation */
2584 out_flush();
2585
2586 /* Obtain handles for the standard Console I/O devices */
2587 if (read_cmd_fd == 0)
2588 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2589 else
2590 create_conin();
2591 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2592
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002593#ifdef FEAT_RESTORE_ORIG_SCREEN
2594 /* Save the initial console buffer for later restoration */
2595 SaveConsoleBuffer(&g_cbOrig);
2596 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2597#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002599 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2600 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2601#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 if (cterm_normal_fg_color == 0)
2603 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2604 if (cterm_normal_bg_color == 0)
2605 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2606
Bram Moolenaarbdace832019-03-02 10:13:42 +01002607 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002608 g_color_index_fg = g_attrDefault & 0xf;
2609 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2610
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 /* set termcap codes to current text attributes */
2612 update_tcap(g_attrCurrent);
2613
2614 GetConsoleCursorInfo(g_hConOut, &g_cci);
2615 GetConsoleMode(g_hConIn, &g_cmodein);
2616 GetConsoleMode(g_hConOut, &g_cmodeout);
2617
2618#ifdef FEAT_TITLE
2619 SaveConsoleTitleAndIcon();
2620 /*
2621 * Set both the small and big icons of the console window to Vim's icon.
2622 * Note that Vim presently only has one size of icon (32x32), but it
2623 * automatically gets scaled down to 16x16 when setting the small icon.
2624 */
2625 if (g_fCanChangeIcon)
2626 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2627#endif
2628
2629 ui_get_shellsize();
2630
2631#ifdef MCH_WRITE_DUMP
2632 fdDump = fopen("dump", "wt");
2633
2634 if (fdDump)
2635 {
2636 time_t t;
2637
2638 time(&t);
2639 fputs(ctime(&t), fdDump);
2640 fflush(fdDump);
2641 }
2642#endif
2643
2644 g_fWindInitCalled = TRUE;
2645
2646#ifdef FEAT_MOUSE
2647 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2648#endif
2649
2650#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002651 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002653
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002654 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002655 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656}
2657
2658/*
2659 * non-GUI version of mch_exit().
2660 * Shut down and exit with status `r'
2661 * Careful: mch_exit() may be called before mch_init()!
2662 */
2663 void
2664mch_exit(int r)
2665{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002666 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002668 vtp_exit();
2669
Bram Moolenaar955f1982017-02-05 15:10:51 +01002670 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671 if (g_fWindInitCalled)
2672 settmode(TMODE_COOK);
2673
2674 ml_close_all(TRUE); /* remove all memfiles */
2675
2676 if (g_fWindInitCalled)
2677 {
2678#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002679 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 /*
2681 * Restore both the small and big icons of the console window to
2682 * what they were at startup. Don't do this when the window is
2683 * closed, Vim would hang here.
2684 */
2685 if (g_fCanChangeIcon && !g_fForceExit)
2686 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2687#endif
2688
2689#ifdef MCH_WRITE_DUMP
2690 if (fdDump)
2691 {
2692 time_t t;
2693
2694 time(&t);
2695 fputs(ctime(&t), fdDump);
2696 fclose(fdDump);
2697 }
2698 fdDump = NULL;
2699#endif
2700 }
2701
2702 SetConsoleCursorInfo(g_hConOut, &g_cci);
2703 SetConsoleMode(g_hConIn, g_cmodein);
2704 SetConsoleMode(g_hConOut, g_cmodeout);
2705
2706#ifdef DYNAMIC_GETTEXT
2707 dyn_libintl_end();
2708#endif
2709
2710 exit(r);
2711}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002712#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714/*
2715 * Do we have an interactive window?
2716 */
2717 int
2718mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002719 int argc UNUSED,
2720 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721{
2722 get_exe_name();
2723
Bram Moolenaar4f974752019-02-17 17:44:42 +01002724#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 return OK; /* GUI always has a tty */
2726#else
2727 if (isatty(1))
2728 return OK;
2729 return FAIL;
2730#endif
2731}
2732
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002733/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002734 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 * When "len" is > 0, also expand short to long filenames.
2736 */
2737 void
2738fname_case(
2739 char_u *name,
2740 int len)
2741{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002742 int flen;
2743 WCHAR *p;
2744 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002746 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002747 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748 return;
2749
2750 slash_adjust(name);
2751
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002752 p = enc_to_utf16(name, NULL);
2753 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002754 return;
2755
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002756 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002758 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002760 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002762 if (len > 0 || flen >= (int)STRLEN(q))
2763 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2764 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765 }
2766 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002767 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768}
2769
2770
2771/*
2772 * Insert user name in s[len].
2773 */
2774 int
2775mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002776 char_u *s,
2777 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002779 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2780 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002782 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002783 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002784 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002785
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002786 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002787 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002788 vim_strncpy(s, p, len - 1);
2789 vim_free(p);
2790 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002791 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793 s[0] = NUL;
2794 return FAIL;
2795}
2796
2797
2798/*
2799 * Insert host name in s[len].
2800 */
2801 void
2802mch_get_host_name(
2803 char_u *s,
2804 int len)
2805{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002806 WCHAR wszHostName[256 + 1];
2807 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002809 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002810 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002811 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002812
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002813 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002814 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002815 vim_strncpy(s, p, len - 1);
2816 vim_free(p);
2817 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002818 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820}
2821
2822
2823/*
2824 * return process ID
2825 */
2826 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002827mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828{
2829 return (long)GetCurrentProcessId();
2830}
2831
2832
2833/*
2834 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2835 * Return OK for success, FAIL for failure.
2836 */
2837 int
2838mch_dirname(
2839 char_u *buf,
2840 int len)
2841{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002842 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002843
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844 /*
2845 * Originally this was:
2846 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2847 * But the Win32s known bug list says that getcwd() doesn't work
2848 * so use the Win32 system call instead. <Negri>
2849 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002850 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002852 WCHAR wcbuf[_MAX_PATH + 1];
2853 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002855 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002857 p = utf16_to_enc(wcbuf, NULL);
2858 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002859 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002860 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002862 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 }
2864 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002865 if (p == NULL)
2866 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002867
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002868 if (p != NULL)
2869 {
2870 vim_strncpy(buf, p, len - 1);
2871 vim_free(p);
2872 return OK;
2873 }
2874 }
2875 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876}
2877
2878/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002879 * Get file permissions for "name".
2880 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 */
2882 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002883mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002885 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002886 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002888 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002889 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890}
2891
2892
2893/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002894 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002895 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002896 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 */
2898 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002899mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002901 long n;
2902 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002903
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002904 p = enc_to_utf16(name, NULL);
2905 if (p == NULL)
2906 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002908 n = _wchmod(p, perm);
2909 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002910 if (n == -1)
2911 return FAIL;
2912
2913 win32_set_archive(name);
2914
2915 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916}
2917
2918/*
2919 * Set hidden flag for "name".
2920 */
2921 void
2922mch_hide(char_u *name)
2923{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002924 int attrs = win32_getattrs(name);
2925 if (attrs == -1)
2926 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002928 attrs |= FILE_ATTRIBUTE_HIDDEN;
2929 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930}
2931
2932/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01002933 * Return TRUE if file "name" exists and is hidden.
2934 */
2935 int
2936mch_ishidden(char_u *name)
2937{
2938 int f = win32_getattrs(name);
2939
2940 if (f == -1)
2941 return FALSE; /* file does not exist at all */
2942
2943 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
2944}
2945
2946/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 * return TRUE if "name" is a directory
2948 * return FALSE if "name" is not a directory or upon error
2949 */
2950 int
2951mch_isdir(char_u *name)
2952{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002953 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954
2955 if (f == -1)
2956 return FALSE; /* file does not exist at all */
2957
2958 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2959}
2960
2961/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01002962 * return TRUE if "name" is a directory, NOT a symlink to a directory
2963 * return FALSE if "name" is not a directory
2964 * return FALSE for error
2965 */
2966 int
2967mch_isrealdir(char_u *name)
2968{
2969 return mch_isdir(name) && !mch_is_symbolic_link(name);
2970}
2971
2972/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002973 * Create directory "name".
2974 * Return 0 on success, -1 on error.
2975 */
2976 int
2977mch_mkdir(char_u *name)
2978{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002979 WCHAR *p;
2980 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002981
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002982 p = enc_to_utf16(name, NULL);
2983 if (p == NULL)
2984 return -1;
2985 retval = _wmkdir(p);
2986 vim_free(p);
2987 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002988}
2989
2990/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01002991 * Delete directory "name".
2992 * Return 0 on success, -1 on error.
2993 */
2994 int
2995mch_rmdir(char_u *name)
2996{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002997 WCHAR *p;
2998 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01002999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003000 p = enc_to_utf16(name, NULL);
3001 if (p == NULL)
3002 return -1;
3003 retval = _wrmdir(p);
3004 vim_free(p);
3005 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003006}
3007
3008/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003009 * Return TRUE if file "fname" has more than one link.
3010 */
3011 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003012mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003013{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003014 BY_HANDLE_FILE_INFORMATION info;
3015
3016 return win32_fileinfo(fname, &info) == FILEINFO_OK
3017 && info.nNumberOfLinks > 1;
3018}
3019
3020/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003021 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003022 */
3023 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003024mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003025{
3026 HANDLE hFind;
3027 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003028 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003029 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003030 WIN32_FIND_DATAW findDataW;
3031
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003032 wn = enc_to_utf16(name, NULL);
3033 if (wn == NULL)
3034 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003035
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003036 hFind = FindFirstFileW(wn, &findDataW);
3037 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003038 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003039 {
3040 fileFlags = findDataW.dwFileAttributes;
3041 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003042 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003043 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003044
3045 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003046 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3047 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003048 res = TRUE;
3049
3050 return res;
3051}
3052
3053/*
3054 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3055 * link.
3056 */
3057 int
3058mch_is_linked(char_u *fname)
3059{
3060 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3061 return TRUE;
3062 return FALSE;
3063}
3064
3065/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003066 * Get the by-handle-file-information for "fname".
3067 * Returns FILEINFO_OK when OK.
3068 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3069 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3070 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3071 */
3072 int
3073win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3074{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003075 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003076 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003077 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003078
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003079 wn = enc_to_utf16(fname, NULL);
3080 if (wn == NULL)
3081 return FILEINFO_ENC_FAIL;
3082
3083 hFile = CreateFileW(wn, // file name
3084 GENERIC_READ, // access mode
3085 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3086 NULL, // security descriptor
3087 OPEN_EXISTING, // creation disposition
3088 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3089 NULL); // handle to template file
3090 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003091
3092 if (hFile != INVALID_HANDLE_VALUE)
3093 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003094 if (GetFileInformationByHandle(hFile, info) != 0)
3095 res = FILEINFO_OK;
3096 else
3097 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003098 CloseHandle(hFile);
3099 }
3100
Bram Moolenaar03f48552006-02-28 23:52:23 +00003101 return res;
3102}
3103
3104/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003105 * get file attributes for `name'
3106 * -1 : error
3107 * else FILE_ATTRIBUTE_* defined in winnt.h
3108 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003109 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110win32_getattrs(char_u *name)
3111{
3112 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 p = enc_to_utf16(name, NULL);
3116 if (p == NULL)
3117 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003119 attr = GetFileAttributesW(p);
3120 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003121
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003122 return attr;
3123}
3124
3125/*
3126 * set file attributes for `name' to `attrs'
3127 *
3128 * return -1 for failure, 0 otherwise
3129 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003130 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131win32_setattrs(char_u *name, int attrs)
3132{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003133 int res;
3134 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003135
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003136 p = enc_to_utf16(name, NULL);
3137 if (p == NULL)
3138 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003140 res = SetFileAttributesW(p, attrs);
3141 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003142
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003143 return res ? 0 : -1;
3144}
3145
3146/*
3147 * Set archive flag for "name".
3148 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003149 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003150win32_set_archive(char_u *name)
3151{
3152 int attrs = win32_getattrs(name);
3153 if (attrs == -1)
3154 return -1;
3155
3156 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3157 return win32_setattrs(name, attrs);
3158}
3159
3160/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 * Return TRUE if file or directory "name" is writable (not readonly).
3162 * Strange semantics of Win32: a readonly directory is writable, but you can't
3163 * delete a file. Let's say this means it is writable.
3164 */
3165 int
3166mch_writable(char_u *name)
3167{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003168 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003170 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3171 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172}
3173
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003175 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003176 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003177 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3178 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 */
3180 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003181mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182{
Bram Moolenaar86621892019-03-30 21:51:28 +01003183 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3184 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3185 // UTF-8.
3186 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003187 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003188 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003189
Bram Moolenaar86621892019-03-30 21:51:28 +01003190 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003191 return FALSE;
3192
Bram Moolenaar86621892019-03-30 21:51:28 +01003193 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003194 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003195 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003196 return TRUE;
3197
3198 /*
3199 * Loop over all extensions in $PATHEXT.
3200 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003201 p = mch_getenv("PATHEXT");
3202 if (p == NULL)
3203 p = (char_u *)".com;.exe;.bat;.cmd";
3204 saved = vim_strsave(p);
3205 if (saved == NULL)
3206 return FALSE;
3207 p = saved;
3208 while (*p)
3209 {
3210 char_u *tmp = vim_strchr(p, ';');
3211
3212 if (tmp != NULL)
3213 *tmp = NUL;
3214 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3215 && executable_exists((char *)name, path, use_path))
3216 {
3217 vim_free(saved);
3218 return TRUE;
3219 }
3220 if (tmp == NULL)
3221 break;
3222 p = tmp + 1;
3223 }
3224 vim_free(saved);
3225
Bram Moolenaar86621892019-03-30 21:51:28 +01003226 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003227 p = mch_getenv("PATHEXT");
3228 if (p == NULL)
3229 p = (char_u *)".com;.exe;.bat;.cmd";
3230 while (*p)
3231 {
3232 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3233 {
3234 /* A single "." means no extension is added. */
3235 buf[len] = NUL;
3236 ++p;
3237 if (*p)
3238 ++p;
3239 }
3240 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003241 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003242 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003243 return TRUE;
3244 }
3245 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247
3248/*
3249 * Check what "name" is:
3250 * NODE_NORMAL: file or directory (or doesn't exist)
3251 * NODE_WRITABLE: writable device, socket, fifo, etc.
3252 * NODE_OTHER: non-writable things
3253 */
3254 int
3255mch_nodetype(char_u *name)
3256{
3257 HANDLE hFile;
3258 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003259 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260
Bram Moolenaar043545e2006-10-10 16:44:07 +00003261 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3262 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3263 * here. */
3264 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3265 return NODE_WRITABLE;
3266
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003267 wn = enc_to_utf16(name, NULL);
3268 if (wn == NULL)
3269 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003270
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003271 hFile = CreateFileW(wn, // file name
3272 GENERIC_WRITE, // access mode
3273 0, // share mode
3274 NULL, // security descriptor
3275 OPEN_EXISTING, // creation disposition
3276 0, // file attributes
3277 NULL); // handle to template file
3278 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279 if (hFile == INVALID_HANDLE_VALUE)
3280 return NODE_NORMAL;
3281
3282 type = GetFileType(hFile);
3283 CloseHandle(hFile);
3284 if (type == FILE_TYPE_CHAR)
3285 return NODE_WRITABLE;
3286 if (type == FILE_TYPE_DISK)
3287 return NODE_NORMAL;
3288 return NODE_OTHER;
3289}
3290
3291#ifdef HAVE_ACL
3292struct my_acl
3293{
3294 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3295 PSID pSidOwner;
3296 PSID pSidGroup;
3297 PACL pDacl;
3298 PACL pSacl;
3299};
3300#endif
3301
3302/*
3303 * Return a pointer to the ACL of file "fname" in allocated memory.
3304 * Return NULL if the ACL is not available for whatever reason.
3305 */
3306 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003307mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308{
3309#ifndef HAVE_ACL
3310 return (vim_acl_T)NULL;
3311#else
3312 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003313 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003315 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3316 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003318 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003319
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003320 wn = enc_to_utf16(fname, NULL);
3321 if (wn == NULL)
3322 return NULL;
3323
3324 // Try to retrieve the entire security descriptor.
3325 err = GetNamedSecurityInfoW(
3326 wn, // Abstract filename
3327 SE_FILE_OBJECT, // File Object
3328 OWNER_SECURITY_INFORMATION |
3329 GROUP_SECURITY_INFORMATION |
3330 DACL_SECURITY_INFORMATION |
3331 SACL_SECURITY_INFORMATION,
3332 &p->pSidOwner, // Ownership information.
3333 &p->pSidGroup, // Group membership.
3334 &p->pDacl, // Discretionary information.
3335 &p->pSacl, // For auditing purposes.
3336 &p->pSecurityDescriptor);
3337 if (err == ERROR_ACCESS_DENIED ||
3338 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003339 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003340 // Retrieve only DACL.
3341 (void)GetNamedSecurityInfoW(
3342 wn,
3343 SE_FILE_OBJECT,
3344 DACL_SECURITY_INFORMATION,
3345 NULL,
3346 NULL,
3347 &p->pDacl,
3348 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003349 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003350 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003351 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003352 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003353 mch_free_acl((vim_acl_T)p);
3354 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 }
3358
3359 return (vim_acl_T)p;
3360#endif
3361}
3362
Bram Moolenaar27515922013-06-29 15:36:26 +02003363#ifdef HAVE_ACL
3364/*
3365 * Check if "acl" contains inherited ACE.
3366 */
3367 static BOOL
3368is_acl_inherited(PACL acl)
3369{
3370 DWORD i;
3371 ACL_SIZE_INFORMATION acl_info;
3372 PACCESS_ALLOWED_ACE ace;
3373
3374 acl_info.AceCount = 0;
3375 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3376 for (i = 0; i < acl_info.AceCount; i++)
3377 {
3378 GetAce(acl, i, (LPVOID *)&ace);
3379 if (ace->Header.AceFlags & INHERITED_ACE)
3380 return TRUE;
3381 }
3382 return FALSE;
3383}
3384#endif
3385
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386/*
3387 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3388 * Errors are ignored.
3389 * This must only be called with "acl" equal to what mch_get_acl() returned.
3390 */
3391 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003392mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393{
3394#ifdef HAVE_ACL
3395 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003396 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003397 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003399 if (p == NULL)
3400 return;
3401
3402 wn = enc_to_utf16(fname, NULL);
3403 if (wn == NULL)
3404 return;
3405
3406 // Set security flags
3407 if (p->pSidOwner)
3408 sec_info |= OWNER_SECURITY_INFORMATION;
3409 if (p->pSidGroup)
3410 sec_info |= GROUP_SECURITY_INFORMATION;
3411 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003412 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003413 sec_info |= DACL_SECURITY_INFORMATION;
3414 // Do not inherit its parent's DACL.
3415 // If the DACL is inherited, Cygwin permissions would be changed.
3416 if (!is_acl_inherited(p->pDacl))
3417 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003418 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 if (p->pSacl)
3420 sec_info |= SACL_SECURITY_INFORMATION;
3421
3422 (void)SetNamedSecurityInfoW(
3423 wn, // Abstract filename
3424 SE_FILE_OBJECT, // File Object
3425 sec_info,
3426 p->pSidOwner, // Ownership information.
3427 p->pSidGroup, // Group membership.
3428 p->pDacl, // Discretionary information.
3429 p->pSacl // For auditing purposes.
3430 );
3431 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432#endif
3433}
3434
3435 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003436mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437{
3438#ifdef HAVE_ACL
3439 struct my_acl *p = (struct my_acl *)acl;
3440
3441 if (p != NULL)
3442 {
3443 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3444 vim_free(p);
3445 }
3446#endif
3447}
3448
Bram Moolenaar4f974752019-02-17 17:44:42 +01003449#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450
3451/*
3452 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3453 */
3454 static BOOL WINAPI
3455handler_routine(
3456 DWORD dwCtrlType)
3457{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003458 INPUT_RECORD ir;
3459 DWORD out;
3460
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 switch (dwCtrlType)
3462 {
3463 case CTRL_C_EVENT:
3464 if (ctrl_c_interrupts)
3465 g_fCtrlCPressed = TRUE;
3466 return TRUE;
3467
3468 case CTRL_BREAK_EVENT:
3469 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003470 ctrl_break_was_pressed = TRUE;
3471 /* ReadConsoleInput is blocking, send a key event to continue. */
3472 ir.EventType = KEY_EVENT;
3473 ir.Event.KeyEvent.bKeyDown = TRUE;
3474 ir.Event.KeyEvent.wRepeatCount = 1;
3475 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3476 ir.Event.KeyEvent.wVirtualScanCode = 0;
3477 ir.Event.KeyEvent.dwControlKeyState = 0;
3478 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3479 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480 return TRUE;
3481
3482 /* fatal events: shut down gracefully */
3483 case CTRL_CLOSE_EVENT:
3484 case CTRL_LOGOFF_EVENT:
3485 case CTRL_SHUTDOWN_EVENT:
3486 windgoto((int)Rows - 1, 0);
3487 g_fForceExit = TRUE;
3488
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003489 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 (dwCtrlType == CTRL_CLOSE_EVENT
3491 ? _("close")
3492 : dwCtrlType == CTRL_LOGOFF_EVENT
3493 ? _("logoff")
3494 : _("shutdown")));
3495#ifdef DEBUG
3496 OutputDebugString(IObuff);
3497#endif
3498
3499 preserve_exit(); /* output IObuff, preserve files and exit */
3500
3501 return TRUE; /* not reached */
3502
3503 default:
3504 return FALSE;
3505 }
3506}
3507
3508
3509/*
3510 * set the tty in (raw) ? "raw" : "cooked" mode
3511 */
3512 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003513mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514{
3515 DWORD cmodein;
3516 DWORD cmodeout;
3517 BOOL bEnableHandler;
3518
3519 GetConsoleMode(g_hConIn, &cmodein);
3520 GetConsoleMode(g_hConOut, &cmodeout);
3521 if (tmode == TMODE_RAW)
3522 {
3523 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3524 ENABLE_ECHO_INPUT);
3525#ifdef FEAT_MOUSE
3526 if (g_fMouseActive)
3527 cmodein |= ENABLE_MOUSE_INPUT;
3528#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003529 cmodeout &= ~(
3530#ifdef FEAT_TERMGUICOLORS
3531 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3532 * VTP. */
3533 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3534#else
3535 ENABLE_PROCESSED_OUTPUT |
3536#endif
3537 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 bEnableHandler = TRUE;
3539 }
3540 else /* cooked */
3541 {
3542 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3543 ENABLE_ECHO_INPUT);
3544 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3545 bEnableHandler = FALSE;
3546 }
3547 SetConsoleMode(g_hConIn, cmodein);
3548 SetConsoleMode(g_hConOut, cmodeout);
3549 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3550
3551#ifdef MCH_WRITE_DUMP
3552 if (fdDump)
3553 {
3554 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3555 tmode == TMODE_RAW ? "raw" :
3556 tmode == TMODE_COOK ? "cooked" : "normal",
3557 cmodein, cmodeout);
3558 fflush(fdDump);
3559 }
3560#endif
3561}
3562
3563
3564/*
3565 * Get the size of the current window in `Rows' and `Columns'
3566 * Return OK when size could be determined, FAIL otherwise.
3567 */
3568 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003569mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570{
3571 CONSOLE_SCREEN_BUFFER_INFO csbi;
3572
3573 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3574 {
3575 /*
3576 * For some reason, we are trying to get the screen dimensions
3577 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3578 * variables are really intended to mean the size of Vim screen
3579 * while in termcap mode.
3580 */
3581 Rows = g_cbTermcap.Info.dwSize.Y;
3582 Columns = g_cbTermcap.Info.dwSize.X;
3583 }
3584 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3585 {
3586 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3587 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3588 }
3589 else
3590 {
3591 Rows = 25;
3592 Columns = 80;
3593 }
3594 return OK;
3595}
3596
3597/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003598 * Resize console buffer to 'COORD'
3599 */
3600 static void
3601ResizeConBuf(
3602 HANDLE hConsole,
3603 COORD coordScreen)
3604{
3605 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3606 {
3607#ifdef MCH_WRITE_DUMP
3608 if (fdDump)
3609 {
3610 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3611 GetLastError());
3612 fflush(fdDump);
3613 }
3614#endif
3615 }
3616}
3617
3618/*
3619 * Resize console window size to 'srWindowRect'
3620 */
3621 static void
3622ResizeWindow(
3623 HANDLE hConsole,
3624 SMALL_RECT srWindowRect)
3625{
3626 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3627 {
3628#ifdef MCH_WRITE_DUMP
3629 if (fdDump)
3630 {
3631 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3632 GetLastError());
3633 fflush(fdDump);
3634 }
3635#endif
3636 }
3637}
3638
3639/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 * Set a console window to `xSize' * `ySize'
3641 */
3642 static void
3643ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003644 HANDLE hConsole,
3645 int xSize,
3646 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647{
3648 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3649 SMALL_RECT srWindowRect; /* hold the new console size */
3650 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003651 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652
3653#ifdef MCH_WRITE_DUMP
3654 if (fdDump)
3655 {
3656 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3657 fflush(fdDump);
3658 }
3659#endif
3660
3661 /* get the largest size we can size the console window to */
3662 coordScreen = GetLargestConsoleWindowSize(hConsole);
3663
3664 /* define the new console window size and scroll position */
3665 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3666 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3667 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3668
3669 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3670 {
3671 int sx, sy;
3672
3673 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3674 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3675 if (sy < ySize || sx < xSize)
3676 {
3677 /*
3678 * Increasing number of lines/columns, do buffer first.
3679 * Use the maximal size in x and y direction.
3680 */
3681 if (sy < ySize)
3682 coordScreen.Y = ySize;
3683 else
3684 coordScreen.Y = sy;
3685 if (sx < xSize)
3686 coordScreen.X = xSize;
3687 else
3688 coordScreen.X = sx;
3689 SetConsoleScreenBufferSize(hConsole, coordScreen);
3690 }
3691 }
3692
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003693 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 coordScreen.X = xSize;
3695 coordScreen.Y = ySize;
3696
Bram Moolenaar2551c032018-08-23 22:38:31 +02003697 // In the new console call API, only the first time in reverse order
3698 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003700 ResizeWindow(hConsole, srWindowRect);
3701 ResizeConBuf(hConsole, coordScreen);
3702 }
3703 else
3704 {
3705 ResizeConBuf(hConsole, coordScreen);
3706 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003707 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003708 }
3709}
3710
3711
3712/*
3713 * Set the console window to `Rows' * `Columns'
3714 */
3715 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003716mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717{
3718 COORD coordScreen;
3719
3720 /* Don't change window size while still starting up */
3721 if (suppress_winsize != 0)
3722 {
3723 suppress_winsize = 2;
3724 return;
3725 }
3726
3727 if (term_console)
3728 {
3729 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3730
3731 /* Clamp Rows and Columns to reasonable values */
3732 if (Rows > coordScreen.Y)
3733 Rows = coordScreen.Y;
3734 if (Columns > coordScreen.X)
3735 Columns = coordScreen.X;
3736
3737 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3738 }
3739}
3740
3741/*
3742 * Rows and/or Columns has changed.
3743 */
3744 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003745mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746{
3747 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3748}
3749
3750
3751/*
3752 * Called when started up, to set the winsize that was delayed.
3753 */
3754 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003755mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756{
3757 if (suppress_winsize == 2)
3758 {
3759 suppress_winsize = 0;
3760 mch_set_shellsize();
3761 shell_resized();
3762 }
3763 suppress_winsize = 0;
3764}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003765#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003767 static BOOL
3768vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003769 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003770 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003771 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003772 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003773 PROCESS_INFORMATION *pi,
3774 LPVOID *env,
3775 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003776{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003777 BOOL ret = FALSE;
3778 WCHAR *wcmd, *wcwd = NULL;
3779
3780 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3781 if (wcmd == NULL)
3782 return FALSE;
3783 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003784 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003785 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3786 if (wcwd == NULL)
3787 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003788 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003789
3790 ret = CreateProcessW(
3791 NULL, // Executable name
3792 wcmd, // Command to execute
3793 NULL, // Process security attributes
3794 NULL, // Thread security attributes
3795 inherit_handles, // Inherit handles
3796 flags, // Creation flags
3797 env, // Environment
3798 wcwd, // Current directory
3799 (LPSTARTUPINFOW)si, // Startup information
3800 pi); // Process information
3801theend:
3802 vim_free(wcmd);
3803 vim_free(wcwd);
3804 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003805}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806
3807
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003808 static HINSTANCE
3809vim_shell_execute(
3810 char *cmd,
3811 INT n_show_cmd)
3812{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003813 HINSTANCE ret;
3814 WCHAR *wcmd;
3815
3816 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3817 if (wcmd == NULL)
3818 return (HINSTANCE) 0;
3819
3820 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3821 vim_free(wcmd);
3822 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003823}
3824
3825
Bram Moolenaar4f974752019-02-17 17:44:42 +01003826#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827
3828/*
3829 * Specialised version of system() for Win32 GUI mode.
3830 * This version proceeds as follows:
3831 * 1. Create a console window for use by the subprocess
3832 * 2. Run the subprocess (it gets the allocated console by default)
3833 * 3. Wait for the subprocess to terminate and get its exit code
3834 * 4. Prompt the user to press a key to close the console window
3835 */
3836 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003837mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838{
3839 STARTUPINFO si;
3840 PROCESS_INFORMATION pi;
3841 DWORD ret = 0;
3842 HWND hwnd = GetFocus();
3843
3844 si.cb = sizeof(si);
3845 si.lpReserved = NULL;
3846 si.lpDesktop = NULL;
3847 si.lpTitle = NULL;
3848 si.dwFlags = STARTF_USESHOWWINDOW;
3849 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003850 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003851 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003853 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003854 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 else
3856 si.wShowWindow = SW_SHOWNORMAL;
3857 si.cbReserved2 = 0;
3858 si.lpReserved2 = NULL;
3859
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003861 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003862 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3863 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864
3865 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 {
3867#ifdef FEAT_GUI
3868 int delay = 1;
3869
3870 /* Keep updating the window while waiting for the shell to finish. */
3871 for (;;)
3872 {
3873 MSG msg;
3874
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003875 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 {
3877 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003878 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003879 delay = 1;
3880 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 }
3882 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3883 break;
3884
3885 /* We start waiting for a very short time and then increase it, so
3886 * that we respond quickly when the process is quick, and don't
3887 * consume too much overhead when it's slow. */
3888 if (delay < 50)
3889 delay += 10;
3890 }
3891#else
3892 WaitForSingleObject(pi.hProcess, INFINITE);
3893#endif
3894
3895 /* Get the command exit code */
3896 GetExitCodeProcess(pi.hProcess, &ret);
3897 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898
3899 /* Close the handles to the subprocess, so that it goes away */
3900 CloseHandle(pi.hThread);
3901 CloseHandle(pi.hProcess);
3902
3903 /* Try to get input focus back. Doesn't always work though. */
3904 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3905
3906 return ret;
3907}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003908
3909/*
3910 * Thread launched by the gui to send the current buffer data to the
3911 * process. This way avoid to hang up vim totally if the children
3912 * process take a long time to process the lines.
3913 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02003914 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003915sub_process_writer(LPVOID param)
3916{
3917 HANDLE g_hChildStd_IN_Wr = param;
3918 linenr_T lnum = curbuf->b_op_start.lnum;
3919 DWORD len = 0;
3920 DWORD l;
3921 char_u *lp = ml_get(lnum);
3922 char_u *s;
3923 int written = 0;
3924
3925 for (;;)
3926 {
3927 l = (DWORD)STRLEN(lp + written);
3928 if (l == 0)
3929 len = 0;
3930 else if (lp[written] == NL)
3931 {
3932 /* NL -> NUL translation */
3933 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3934 }
3935 else
3936 {
3937 s = vim_strchr(lp + written, NL);
3938 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3939 s == NULL ? l : (DWORD)(s - (lp + written)),
3940 &len, NULL);
3941 }
3942 if (len == (int)l)
3943 {
3944 /* Finished a line, add a NL, unless this line should not have
3945 * one. */
3946 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02003947 || (!curbuf->b_p_bin
3948 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003949 || (lnum != curbuf->b_no_eol_lnum
3950 && (lnum != curbuf->b_ml.ml_line_count
3951 || curbuf->b_p_eol)))
3952 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02003953 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
3954 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003955 }
3956
3957 ++lnum;
3958 if (lnum > curbuf->b_op_end.lnum)
3959 break;
3960
3961 lp = ml_get(lnum);
3962 written = 0;
3963 }
3964 else if (len > 0)
3965 written += len;
3966 }
3967
3968 /* finished all the lines, close pipe */
3969 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02003970 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003971}
3972
3973
3974# define BUFLEN 100 /* length for buffer, stolen from unix version */
3975
3976/*
3977 * This function read from the children's stdout and write the
3978 * data on screen or in the buffer accordingly.
3979 */
3980 static void
3981dump_pipe(int options,
3982 HANDLE g_hChildStd_OUT_Rd,
3983 garray_T *ga,
3984 char_u buffer[],
3985 DWORD *buffer_off)
3986{
3987 DWORD availableBytes = 0;
3988 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003989 int ret;
3990 DWORD len;
3991 DWORD toRead;
3992 int repeatCount;
3993
3994 /* we query the pipe to see if there is any data to read
3995 * to avoid to perform a blocking read */
3996 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3997 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003998 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003999 NULL, /* number of read bytes */
4000 &availableBytes, /* available bytes total */
4001 NULL); /* byteLeft */
4002
4003 repeatCount = 0;
4004 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004005 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004006 {
4007 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004008 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004009 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004010 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004011
4012 /* If we haven't read anything, there is a problem */
4013 if (len == 0)
4014 break;
4015
4016 availableBytes -= len;
4017
4018 if (options & SHELL_READ)
4019 {
4020 /* Do NUL -> NL translation, append NL separated
4021 * lines to the current buffer. */
4022 for (i = 0; i < len; ++i)
4023 {
4024 if (buffer[i] == NL)
4025 append_ga_line(ga);
4026 else if (buffer[i] == NUL)
4027 ga_append(ga, NL);
4028 else
4029 ga_append(ga, buffer[i]);
4030 }
4031 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004032 else if (has_mbyte)
4033 {
4034 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004035 int c;
4036 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004037
4038 len += *buffer_off;
4039 buffer[len] = NUL;
4040
4041 /* Check if the last character in buffer[] is
4042 * incomplete, keep these bytes for the next
4043 * round. */
4044 for (p = buffer; p < buffer + len; p += l)
4045 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004046 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004047 if (l == 0)
4048 l = 1; /* NUL byte? */
4049 else if (MB_BYTE2LEN(*p) != l)
4050 break;
4051 }
4052 if (p == buffer) /* no complete character */
4053 {
4054 /* avoid getting stuck at an illegal byte */
4055 if (len >= 12)
4056 ++p;
4057 else
4058 {
4059 *buffer_off = len;
4060 return;
4061 }
4062 }
4063 c = *p;
4064 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004065 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004066 if (p < buffer + len)
4067 {
4068 *p = c;
4069 *buffer_off = (DWORD)((buffer + len) - p);
4070 mch_memmove(buffer, p, *buffer_off);
4071 return;
4072 }
4073 *buffer_off = 0;
4074 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004075 else
4076 {
4077 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004078 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004079 }
4080
4081 windgoto(msg_row, msg_col);
4082 cursor_on();
4083 out_flush();
4084 }
4085}
4086
4087/*
4088 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4089 * for communication and doesn't open any new window.
4090 */
4091 static int
4092mch_system_piped(char *cmd, int options)
4093{
4094 STARTUPINFO si;
4095 PROCESS_INFORMATION pi;
4096 DWORD ret = 0;
4097
4098 HANDLE g_hChildStd_IN_Rd = NULL;
4099 HANDLE g_hChildStd_IN_Wr = NULL;
4100 HANDLE g_hChildStd_OUT_Rd = NULL;
4101 HANDLE g_hChildStd_OUT_Wr = NULL;
4102
4103 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4104 DWORD len;
4105
4106 /* buffer used to receive keys */
4107 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4108 int ta_len = 0; /* valid bytes in ta_buf[] */
4109
4110 DWORD i;
4111 int c;
4112 int noread_cnt = 0;
4113 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004114 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004115 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004116 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004117
4118 SECURITY_ATTRIBUTES saAttr;
4119
4120 /* Set the bInheritHandle flag so pipe handles are inherited. */
4121 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4122 saAttr.bInheritHandle = TRUE;
4123 saAttr.lpSecurityDescriptor = NULL;
4124
4125 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4126 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004127 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004128 /* Create a pipe for the child process's STDIN. */
4129 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4130 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004131 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004132 {
4133 CloseHandle(g_hChildStd_IN_Rd);
4134 CloseHandle(g_hChildStd_IN_Wr);
4135 CloseHandle(g_hChildStd_OUT_Rd);
4136 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004137 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004138 }
4139
4140 si.cb = sizeof(si);
4141 si.lpReserved = NULL;
4142 si.lpDesktop = NULL;
4143 si.lpTitle = NULL;
4144 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4145
4146 /* set-up our file redirection */
4147 si.hStdError = g_hChildStd_OUT_Wr;
4148 si.hStdOutput = g_hChildStd_OUT_Wr;
4149 si.hStdInput = g_hChildStd_IN_Rd;
4150 si.wShowWindow = SW_HIDE;
4151 si.cbReserved2 = 0;
4152 si.lpReserved2 = NULL;
4153
4154 if (options & SHELL_READ)
4155 ga_init2(&ga, 1, BUFLEN);
4156
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004157 if (cmd != NULL)
4158 {
4159 p = (char *)vim_strsave((char_u *)cmd);
4160 if (p != NULL)
4161 unescape_shellxquote((char_u *)p, p_sxe);
4162 else
4163 p = cmd;
4164 }
4165
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 /* Now, run the command.
4167 * About "Inherit handles" being TRUE: this command can be litigious,
4168 * handle inheritance was deactivated for pending temp file, but, if we
4169 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004170 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4171 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004172
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004173 if (p != cmd)
4174 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004175
4176 /* Close our unused side of the pipes */
4177 CloseHandle(g_hChildStd_IN_Rd);
4178 CloseHandle(g_hChildStd_OUT_Wr);
4179
4180 if (options & SHELL_WRITE)
4181 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004182 HANDLE thread = (HANDLE)
4183 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004184 0, /* default stack size */
4185 sub_process_writer, /* function to be executed */
4186 g_hChildStd_IN_Wr, /* parameter */
4187 0, /* creation flag, start immediately */
4188 NULL); /* we don't care about thread id */
4189 CloseHandle(thread);
4190 g_hChildStd_IN_Wr = NULL;
4191 }
4192
4193 /* Keep updating the window while waiting for the shell to finish. */
4194 for (;;)
4195 {
4196 MSG msg;
4197
Bram Moolenaar175d0702013-12-11 18:36:33 +01004198 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004199 {
4200 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004201 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202 }
4203
4204 /* write pipe information in the window */
4205 if ((options & (SHELL_READ|SHELL_WRITE))
4206# ifdef FEAT_GUI
4207 || gui.in_use
4208# endif
4209 )
4210 {
4211 len = 0;
4212 if (!(options & SHELL_EXPAND)
4213 && ((options &
4214 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4215 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4216# ifdef FEAT_GUI
4217 || gui.in_use
4218# endif
4219 )
4220 && (ta_len > 0 || noread_cnt > 4))
4221 {
4222 if (ta_len == 0)
4223 {
4224 /* Get extra characters when we don't have any. Reset the
4225 * counter and timer. */
4226 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004227 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4228 }
4229 if (ta_len > 0 || len > 0)
4230 {
4231 /*
4232 * For pipes: Check for CTRL-C: send interrupt signal to
4233 * child. Check for CTRL-D: EOF, close pipe to child.
4234 */
4235 if (len == 1 && cmd != NULL)
4236 {
4237 if (ta_buf[ta_len] == Ctrl_C)
4238 {
4239 /* Learn what exit code is expected, for
4240 * now put 9 as SIGKILL */
4241 TerminateProcess(pi.hProcess, 9);
4242 }
4243 if (ta_buf[ta_len] == Ctrl_D)
4244 {
4245 CloseHandle(g_hChildStd_IN_Wr);
4246 g_hChildStd_IN_Wr = NULL;
4247 }
4248 }
4249
4250 /* replace K_BS by <BS> and K_DEL by <DEL> */
4251 for (i = ta_len; i < ta_len + len; ++i)
4252 {
4253 if (ta_buf[i] == CSI && len - i > 2)
4254 {
4255 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4256 if (c == K_DEL || c == K_KDEL || c == K_BS)
4257 {
4258 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4259 (size_t)(len - i - 2));
4260 if (c == K_DEL || c == K_KDEL)
4261 ta_buf[i] = DEL;
4262 else
4263 ta_buf[i] = Ctrl_H;
4264 len -= 2;
4265 }
4266 }
4267 else if (ta_buf[i] == '\r')
4268 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004269 if (has_mbyte)
4270 i += (*mb_ptr2len_len)(ta_buf + i,
4271 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 }
4273
4274 /*
4275 * For pipes: echo the typed characters. For a pty this
4276 * does not seem to work.
4277 */
4278 for (i = ta_len; i < ta_len + len; ++i)
4279 {
4280 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4281 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004282 else if (has_mbyte)
4283 {
4284 int l = (*mb_ptr2len)(ta_buf + i);
4285
4286 msg_outtrans_len(ta_buf + i, l);
4287 i += l - 1;
4288 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 else
4290 msg_outtrans_len(ta_buf + i, 1);
4291 }
4292 windgoto(msg_row, msg_col);
4293 out_flush();
4294
4295 ta_len += len;
4296
4297 /*
4298 * Write the characters to the child, unless EOF has been
4299 * typed for pipes. Write one character at a time, to
4300 * avoid losing too much typeahead. When writing buffer
4301 * lines, drop the typed characters (only check for
4302 * CTRL-C).
4303 */
4304 if (options & SHELL_WRITE)
4305 ta_len = 0;
4306 else if (g_hChildStd_IN_Wr != NULL)
4307 {
4308 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4309 1, &len, NULL);
4310 // if we are typing in, we want to keep things reactive
4311 delay = 1;
4312 if (len > 0)
4313 {
4314 ta_len -= len;
4315 mch_memmove(ta_buf, ta_buf + len, ta_len);
4316 }
4317 }
4318 }
4319 }
4320 }
4321
4322 if (ta_len)
4323 ui_inchar_undo(ta_buf, ta_len);
4324
4325 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4326 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004327 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004328 break;
4329 }
4330
4331 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004332 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004333
4334 /* We start waiting for a very short time and then increase it, so
4335 * that we respond quickly when the process is quick, and don't
4336 * consume too much overhead when it's slow. */
4337 if (delay < 50)
4338 delay += 10;
4339 }
4340
4341 /* Close the pipe */
4342 CloseHandle(g_hChildStd_OUT_Rd);
4343 if (g_hChildStd_IN_Wr != NULL)
4344 CloseHandle(g_hChildStd_IN_Wr);
4345
4346 WaitForSingleObject(pi.hProcess, INFINITE);
4347
4348 /* Get the command exit code */
4349 GetExitCodeProcess(pi.hProcess, &ret);
4350
4351 if (options & SHELL_READ)
4352 {
4353 if (ga.ga_len > 0)
4354 {
4355 append_ga_line(&ga);
4356 /* remember that the NL was missing */
4357 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4358 }
4359 else
4360 curbuf->b_no_eol_lnum = 0;
4361 ga_clear(&ga);
4362 }
4363
4364 /* Close the handles to the subprocess, so that it goes away */
4365 CloseHandle(pi.hThread);
4366 CloseHandle(pi.hProcess);
4367
4368 return ret;
4369}
4370
4371 static int
4372mch_system(char *cmd, int options)
4373{
4374 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004375 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376 return mch_system_piped(cmd, options);
4377 else
4378 return mch_system_classic(cmd, options);
4379}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004380#else
4381
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004382 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004383mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004384{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004385 int ret;
4386 WCHAR *wcmd;
4387
4388 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4389 if (wcmd == NULL)
4390 return -1;
4391
4392 ret = _wsystem(wcmd);
4393 vim_free(wcmd);
4394 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004395}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396
4397#endif
4398
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004399#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4400/*
4401 * Use a terminal window to run a shell command in.
4402 */
4403 static int
4404mch_call_shell_terminal(
4405 char_u *cmd,
4406 int options UNUSED) /* SHELL_*, see vim.h */
4407{
4408 jobopt_T opt;
4409 char_u *newcmd = NULL;
4410 typval_T argvar[2];
4411 long_u cmdlen;
4412 int retval = -1;
4413 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004414 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004415 aco_save_T aco;
4416 oparg_T oa; /* operator arguments */
4417
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004418 if (cmd == NULL)
4419 cmdlen = STRLEN(p_sh) + 1;
4420 else
4421 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004422 newcmd = lalloc(cmdlen, TRUE);
4423 if (newcmd == NULL)
4424 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004425 if (cmd == NULL)
4426 {
4427 STRCPY(newcmd, p_sh);
4428 ch_log(NULL, "starting terminal to run a shell");
4429 }
4430 else
4431 {
4432 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4433 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4434 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004435
4436 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004437
4438 argvar[0].v_type = VAR_STRING;
4439 argvar[0].vval.v_string = newcmd;
4440 argvar[1].v_type = VAR_UNKNOWN;
4441 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004442 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004443 {
4444 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004445 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004446 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004447
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004448 job = term_getjob(buf->b_term);
4449 ++job->jv_refcount;
4450
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004451 /* Find a window to make "buf" curbuf. */
4452 aucmd_prepbuf(&aco, buf);
4453
4454 clear_oparg(&oa);
4455 while (term_use_loop())
4456 {
4457 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4458 {
4459 /* If terminal_loop() returns OK we got a key that is handled
4460 * in Normal model. We don't do redrawing anyway. */
4461 if (terminal_loop(TRUE) == OK)
4462 normal_cmd(&oa, TRUE);
4463 }
4464 else
4465 normal_cmd(&oa, TRUE);
4466 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004467 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004468 ch_log(NULL, "system command finished");
4469
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004470 job_unref(job);
4471
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004472 /* restore curwin/curbuf and a few other things */
4473 aucmd_restbuf(&aco);
4474
4475 wait_return(TRUE);
4476 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4477
4478 vim_free(newcmd);
4479 return retval;
4480}
4481#endif
4482
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483/*
4484 * Either execute a command by calling the shell or start a new shell
4485 */
4486 int
4487mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004488 char_u *cmd,
4489 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490{
4491 int x = 0;
4492 int tmode = cur_tmode;
4493#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004494 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004495
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004496 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004497 if (GetConsoleTitleW(szShellTitle,
4498 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004499 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004500 if (cmd == NULL)
4501 wcscat(szShellTitle, L" :sh");
4502 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004503 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004504 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004505
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004506 if (wn != NULL)
4507 {
4508 wcscat(szShellTitle, L" - !");
4509 if ((wcslen(szShellTitle) + wcslen(wn) <
4510 sizeof(szShellTitle)/sizeof(WCHAR)))
4511 wcscat(szShellTitle, wn);
4512 SetConsoleTitleW(szShellTitle);
4513 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004514 }
4515 }
4516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517#endif
4518
4519 out_flush();
4520
4521#ifdef MCH_WRITE_DUMP
4522 if (fdDump)
4523 {
4524 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4525 fflush(fdDump);
4526 }
4527#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004528#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4529 /* TODO: make the terminal window work with input or output redirected. */
4530 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4531 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4532 {
4533 /* Use a terminal window to run the command in. */
4534 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004535# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004536 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004537# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004538 return x;
4539 }
4540#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541
4542 /*
4543 * Catch all deadly signals while running the external command, because a
4544 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4545 */
4546 signal(SIGINT, SIG_IGN);
4547#if defined(__GNUC__) && !defined(__MINGW32__)
4548 signal(SIGKILL, SIG_IGN);
4549#else
4550 signal(SIGBREAK, SIG_IGN);
4551#endif
4552 signal(SIGILL, SIG_IGN);
4553 signal(SIGFPE, SIG_IGN);
4554 signal(SIGSEGV, SIG_IGN);
4555 signal(SIGTERM, SIG_IGN);
4556 signal(SIGABRT, SIG_IGN);
4557
4558 if (options & SHELL_COOKED)
4559 settmode(TMODE_COOK); /* set to normal mode */
4560
4561 if (cmd == NULL)
4562 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004563 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 }
4565 else
4566 {
4567 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004568 char_u *newcmd = NULL;
4569 char_u *cmdbase = cmd;
4570 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004571
4572 /* Skip a leading ", ( and "(. */
4573 if (*cmdbase == '"' )
4574 ++cmdbase;
4575 if (*cmdbase == '(')
4576 ++cmdbase;
4577
Bram Moolenaar1c465442017-03-12 20:10:05 +01004578 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004579 {
4580 STARTUPINFO si;
4581 PROCESS_INFORMATION pi;
4582 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004583 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004584 char_u *p;
4585
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004586 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004587 si.cb = sizeof(si);
4588 si.lpReserved = NULL;
4589 si.lpDesktop = NULL;
4590 si.lpTitle = NULL;
4591 si.dwFlags = 0;
4592 si.cbReserved2 = 0;
4593 si.lpReserved2 = NULL;
4594
4595 cmdbase = skipwhite(cmdbase + 5);
4596 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004597 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004598 {
4599 cmdbase = skipwhite(cmdbase + 4);
4600 si.dwFlags = STARTF_USESHOWWINDOW;
4601 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004602 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004603 }
4604 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004605 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004606 {
4607 cmdbase = skipwhite(cmdbase + 2);
4608 flags = CREATE_NO_WINDOW;
4609 si.dwFlags = STARTF_USESTDHANDLES;
4610 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004611 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004612 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004613 NULL, // Security att.
4614 OPEN_EXISTING, // Open flags
4615 FILE_ATTRIBUTE_NORMAL, // File att.
4616 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004617 si.hStdOutput = si.hStdInput;
4618 si.hStdError = si.hStdInput;
4619 }
4620
4621 /* Remove a trailing ", ) and )" if they have a match
4622 * at the start of the command. */
4623 if (cmdbase > cmd)
4624 {
4625 p = cmdbase + STRLEN(cmdbase);
4626 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4627 *--p = NUL;
4628 if (p > cmdbase && p[-1] == ')'
4629 && (*cmd =='(' || cmd[1] == '('))
4630 *--p = NUL;
4631 }
4632
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004633 newcmd = cmdbase;
4634 unescape_shellxquote(cmdbase, p_sxe);
4635
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004636 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004637 * If creating new console, arguments are passed to the
4638 * 'cmd.exe' as-is. If it's not, arguments are not treated
4639 * correctly for current 'cmd.exe'. So unescape characters in
4640 * shellxescape except '|' for avoiding to be treated as
4641 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004642 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004643 if (flags != CREATE_NEW_CONSOLE)
4644 {
4645 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004646 char_u *cmd_shell = mch_getenv("COMSPEC");
4647
4648 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004649 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004650
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004651 subcmd = vim_strsave_escaped_ext(cmdbase,
4652 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004653 if (subcmd != NULL)
4654 {
4655 /* make "cmd.exe /c arguments" */
4656 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004657 newcmd = lalloc(cmdlen, TRUE);
4658 if (newcmd != NULL)
4659 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004660 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004661 else
4662 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004663 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004664 }
4665 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004666
4667 /*
4668 * Now, start the command as a process, so that it doesn't
4669 * inherit our handles which causes unpleasant dangling swap
4670 * files if we exit before the spawned process
4671 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004672 if (vim_create_process((char *)newcmd, FALSE, flags,
4673 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004674 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004675 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4676 > (HINSTANCE)32)
4677 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004678 else
4679 {
4680 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004681#ifdef FEAT_GUI_MSWIN
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004682 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004683#endif
4684 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004685
4686 if (newcmd != cmdbase)
4687 vim_free(newcmd);
4688
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004689 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004690 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004691 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004692 CloseHandle(si.hStdInput);
4693 }
4694 /* Close the handles to the subprocess, so that it goes away */
4695 CloseHandle(pi.hThread);
4696 CloseHandle(pi.hProcess);
4697 }
4698 else
4699 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004700 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004701#ifdef FEAT_GUI_MSWIN
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004702 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004703#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004704 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4705
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004706 newcmd = lalloc(cmdlen, TRUE);
4707 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004709#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 if (need_vimrun_warning)
4711 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004712 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4713 "External commands will not pause after completion.\n"
4714 "See :help win32-vimrun for more information.");
4715 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004716 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4717 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004718
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004719 if (wmsg != NULL && wtitle != NULL)
4720 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4721 vim_free(wmsg);
4722 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 need_vimrun_warning = FALSE;
4724 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004725 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 /* Use vimrun to execute the command. It opens a console
4727 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004728 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 vimrun_path,
4730 (msg_silent != 0 || (options & SHELL_DOOUT))
4731 ? "-s " : "",
4732 p_sh, p_shcf, cmd);
4733 else
4734#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004735 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004736 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004738 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 }
4741 }
4742
4743 if (tmode == TMODE_RAW)
4744 settmode(TMODE_RAW); /* set to raw mode */
4745
4746 /* Print the return value, unless "vimrun" was used. */
4747 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004748#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004749 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750#endif
4751 )
4752 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004753 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 msg_putchar('\n');
4755 }
4756#ifdef FEAT_TITLE
4757 resettitle();
4758#endif
4759
4760 signal(SIGINT, SIG_DFL);
4761#if defined(__GNUC__) && !defined(__MINGW32__)
4762 signal(SIGKILL, SIG_DFL);
4763#else
4764 signal(SIGBREAK, SIG_DFL);
4765#endif
4766 signal(SIGILL, SIG_DFL);
4767 signal(SIGFPE, SIG_DFL);
4768 signal(SIGSEGV, SIG_DFL);
4769 signal(SIGTERM, SIG_DFL);
4770 signal(SIGABRT, SIG_DFL);
4771
4772 return x;
4773}
4774
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004775#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004776 static HANDLE
4777job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004778 char_u *fname,
4779 DWORD dwDesiredAccess,
4780 DWORD dwShareMode,
4781 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4782 DWORD dwCreationDisposition,
4783 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004784{
4785 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004786 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004787
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004788 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004789 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004790 return INVALID_HANDLE_VALUE;
4791
4792 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4793 lpSecurityAttributes, dwCreationDisposition,
4794 dwFlagsAndAttributes, NULL);
4795 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004796 return h;
4797}
4798
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004799/*
4800 * Turn the dictionary "env" into a NUL separated list that can be used as the
4801 * environment argument of vim_create_process().
4802 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004803 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004804win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004805{
4806 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004807 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004808 LPVOID base = GetEnvironmentStringsW();
4809
4810 /* for last \0 */
4811 if (ga_grow(gap, 1) == FAIL)
4812 return;
4813
4814 if (base)
4815 {
4816 WCHAR *p = (WCHAR*) base;
4817
4818 /* for last \0 */
4819 if (ga_grow(gap, 1) == FAIL)
4820 return;
4821
4822 while (*p != 0 || *(p + 1) != 0)
4823 {
4824 if (ga_grow(gap, 1) == OK)
4825 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4826 p++;
4827 }
4828 FreeEnvironmentStrings(base);
4829 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4830 }
4831
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004832 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004833 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004834 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004835 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004836 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004837 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004838 typval_T *item = &dict_lookup(hi)->di_tv;
4839 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004840 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004841 --todo;
4842 if (wkey != NULL && wval != NULL)
4843 {
4844 size_t n;
4845 size_t lkey = wcslen(wkey);
4846 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02004847
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004848 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
4849 continue;
4850 for (n = 0; n < lkey; n++)
4851 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
4852 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
4853 for (n = 0; n < lval; n++)
4854 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
4855 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4856 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01004857 vim_free(wkey);
4858 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004859 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004860 }
4861 }
4862
Bram Moolenaar493359e2018-06-12 20:25:52 +02004863# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004864 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02004865# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004866 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004867 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004868# endif
4869# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004870 char_u *version = get_vim_var_str(VV_VERSION);
4871 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004872# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004873 // size of "VIM_SERVERNAME=" and value,
4874 // plus "VIM_TERMINAL=" and value,
4875 // plus two terminating NULs
4876 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02004877# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004878 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02004879# endif
4880# ifdef FEAT_TERMINAL
4881 + 13 + version_len + 2
4882# endif
4883 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004884
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004885 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004886 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02004887# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004888 for (n = 0; n < 15; n++)
4889 *((WCHAR*)gap->ga_data + gap->ga_len++) =
4890 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004891 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004892 *((WCHAR*)gap->ga_data + gap->ga_len++) =
4893 (WCHAR)servername[n];
4894 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02004895# endif
4896# ifdef FEAT_TERMINAL
4897 if (is_terminal)
4898 {
4899 for (n = 0; n < 13; n++)
4900 *((WCHAR*)gap->ga_data + gap->ga_len++) =
4901 (WCHAR)"VIM_TERMINAL="[n];
4902 for (n = 0; n < version_len; n++)
4903 *((WCHAR*)gap->ga_data + gap->ga_len++) =
4904 (WCHAR)version[n];
4905 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4906 }
4907# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004908 }
4909 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02004910# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004911}
4912
Bram Moolenaarb091f302019-01-19 14:37:00 +01004913/*
4914 * Create a pair of pipes.
4915 * Return TRUE for success, FALSE for failure.
4916 */
4917 static BOOL
4918create_pipe_pair(HANDLE handles[2])
4919{
4920 static LONG s;
4921 char name[64];
4922 SECURITY_ATTRIBUTES sa;
4923
4924 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
4925 GetCurrentProcessId(),
4926 InterlockedIncrement(&s));
4927
4928 // Create named pipe. Max size of named pipe is 65535.
4929 handles[1] = CreateNamedPipe(
4930 name,
4931 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
4932 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01004933 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01004934
4935 if (handles[1] == INVALID_HANDLE_VALUE)
4936 return FALSE;
4937
4938 sa.nLength = sizeof(sa);
4939 sa.bInheritHandle = TRUE;
4940 sa.lpSecurityDescriptor = NULL;
4941
4942 handles[0] = CreateFile(name,
4943 FILE_GENERIC_READ,
4944 FILE_SHARE_READ, &sa,
4945 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
4946
4947 if (handles[0] == INVALID_HANDLE_VALUE)
4948 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01004949 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01004950 return FALSE;
4951 }
4952
4953 return TRUE;
4954}
4955
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004956 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004957mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004958{
4959 STARTUPINFO si;
4960 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004961 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004962 SECURITY_ATTRIBUTES saAttr;
4963 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004964 HANDLE ifd[2];
4965 HANDLE ofd[2];
4966 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004967 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004968
4969 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4970 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4971 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4972 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4973 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4974 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4975 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4976
4977 if (use_out_for_err && use_null_for_out)
4978 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004979
4980 ifd[0] = INVALID_HANDLE_VALUE;
4981 ifd[1] = INVALID_HANDLE_VALUE;
4982 ofd[0] = INVALID_HANDLE_VALUE;
4983 ofd[1] = INVALID_HANDLE_VALUE;
4984 efd[0] = INVALID_HANDLE_VALUE;
4985 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004986 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004987
Bram Moolenaar14207f42016-10-27 21:13:10 +02004988 jo = CreateJobObject(NULL, NULL);
4989 if (jo == NULL)
4990 {
4991 job->jv_status = JOB_FAILED;
4992 goto failed;
4993 }
4994
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004995 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004996 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004997
Bram Moolenaar76467df2016-02-12 19:30:26 +01004998 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004999 ZeroMemory(&si, sizeof(si));
5000 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005001 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005002 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005003
Bram Moolenaard8070362016-02-15 21:56:54 +01005004 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5005 saAttr.bInheritHandle = TRUE;
5006 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005007
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005008 if (use_file_for_in)
5009 {
5010 char_u *fname = options->jo_io_name[PART_IN];
5011
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005012 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5013 FILE_SHARE_READ | FILE_SHARE_WRITE,
5014 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5015 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005016 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005017 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005018 goto failed;
5019 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005020 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005021 else if (!use_null_for_in
5022 && (!create_pipe_pair(ifd)
5023 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005024 goto failed;
5025
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005026 if (use_file_for_out)
5027 {
5028 char_u *fname = options->jo_io_name[PART_OUT];
5029
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005030 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5031 FILE_SHARE_READ | FILE_SHARE_WRITE,
5032 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5033 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005034 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005035 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005036 goto failed;
5037 }
5038 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005039 else if (!use_null_for_out &&
5040 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005041 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005042 goto failed;
5043
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005044 if (use_file_for_err)
5045 {
5046 char_u *fname = options->jo_io_name[PART_ERR];
5047
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005048 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5049 FILE_SHARE_READ | FILE_SHARE_WRITE,
5050 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5051 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005052 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005053 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005054 goto failed;
5055 }
5056 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005057 else if (!use_out_for_err && !use_null_for_err &&
5058 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005059 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005060 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005061
Bram Moolenaard8070362016-02-15 21:56:54 +01005062 si.dwFlags |= STARTF_USESTDHANDLES;
5063 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005064 si.hStdOutput = ofd[1];
5065 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5066
5067 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5068 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005069 if (options->jo_set & JO_CHANNEL)
5070 {
5071 channel = options->jo_channel;
5072 if (channel != NULL)
5073 ++channel->ch_refcount;
5074 }
5075 else
5076 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005077 if (channel == NULL)
5078 goto failed;
5079 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005080
5081 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005082 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005083 CREATE_DEFAULT_ERROR_MODE |
5084 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005085 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005086 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005087 &si, &pi,
5088 ga.ga_data,
5089 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005090 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005091 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005092 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005093 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005094 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005095
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005096 ga_clear(&ga);
5097
Bram Moolenaar14207f42016-10-27 21:13:10 +02005098 if (!AssignProcessToJobObject(jo, pi.hProcess))
5099 {
5100 /* if failing, switch the way to terminate
5101 * process with TerminateProcess. */
5102 CloseHandle(jo);
5103 jo = NULL;
5104 }
5105 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005106 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005107 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005108 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005109 job->jv_status = JOB_STARTED;
5110
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005111 CloseHandle(ifd[0]);
5112 CloseHandle(ofd[1]);
5113 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005114 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005115
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005116 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005117 if (channel != NULL)
5118 {
5119 channel_set_pipes(channel,
5120 use_file_for_in || use_null_for_in
5121 ? INVALID_FD : (sock_T)ifd[1],
5122 use_file_for_out || use_null_for_out
5123 ? INVALID_FD : (sock_T)ofd[0],
5124 use_out_for_err || use_file_for_err || use_null_for_err
5125 ? INVALID_FD : (sock_T)efd[0]);
5126 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005127 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005128 return;
5129
5130failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005131 CloseHandle(ifd[0]);
5132 CloseHandle(ofd[0]);
5133 CloseHandle(efd[0]);
5134 CloseHandle(ifd[1]);
5135 CloseHandle(ofd[1]);
5136 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005137 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005138 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005139}
5140
5141 char *
5142mch_job_status(job_T *job)
5143{
5144 DWORD dwExitCode = 0;
5145
Bram Moolenaar76467df2016-02-12 19:30:26 +01005146 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5147 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005148 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005149 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005150 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005151 {
5152 ch_log(job->jv_channel, "Job ended");
5153 job->jv_status = JOB_ENDED;
5154 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005155 return "dead";
5156 }
5157 return "run";
5158}
5159
Bram Moolenaar97792de2016-10-15 18:36:49 +02005160 job_T *
5161mch_detect_ended_job(job_T *job_list)
5162{
5163 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5164 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5165 job_T *job = job_list;
5166
5167 while (job != NULL)
5168 {
5169 DWORD n;
5170 DWORD result;
5171
5172 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5173 && job != NULL; job = job->jv_next)
5174 {
5175 if (job->jv_status == JOB_STARTED)
5176 {
5177 jobHandles[n] = job->jv_proc_info.hProcess;
5178 jobArray[n] = job;
5179 ++n;
5180 }
5181 }
5182 if (n == 0)
5183 continue;
5184 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5185 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5186 {
5187 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5188
5189 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5190 return wait_job;
5191 }
5192 }
5193 return NULL;
5194}
5195
Bram Moolenaarfb630902016-10-29 14:55:00 +02005196 static BOOL
5197terminate_all(HANDLE process, int code)
5198{
5199 PROCESSENTRY32 pe;
5200 HANDLE h = INVALID_HANDLE_VALUE;
5201 DWORD pid = GetProcessId(process);
5202
5203 if (pid != 0)
5204 {
5205 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5206 if (h != INVALID_HANDLE_VALUE)
5207 {
5208 pe.dwSize = sizeof(PROCESSENTRY32);
5209 if (!Process32First(h, &pe))
5210 goto theend;
5211
5212 do
5213 {
5214 if (pe.th32ParentProcessID == pid)
5215 {
5216 HANDLE ph = OpenProcess(
5217 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5218 if (ph != NULL)
5219 {
5220 terminate_all(ph, code);
5221 CloseHandle(ph);
5222 }
5223 }
5224 } while (Process32Next(h, &pe));
5225
5226 CloseHandle(h);
5227 }
5228 }
5229
5230theend:
5231 return TerminateProcess(process, code);
5232}
5233
5234/*
5235 * Send a (deadly) signal to "job".
5236 * Return FAIL if it didn't work.
5237 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005238 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005239mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005240{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005241 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005242
Bram Moolenaar923d9262016-02-25 20:56:01 +01005243 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005244 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005245 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005246 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005247 {
5248 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5249 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005250 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005251 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005252 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005253 }
5254
5255 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5256 return FAIL;
5257 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005258 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5259 job->jv_proc_info.dwProcessId)
5260 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005261 FreeConsole();
5262 return ret;
5263}
5264
5265/*
5266 * Clear the data related to "job".
5267 */
5268 void
5269mch_clear_job(job_T *job)
5270{
5271 if (job->jv_status != JOB_FAILED)
5272 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005273 if (job->jv_job_object != NULL)
5274 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005275 CloseHandle(job->jv_proc_info.hProcess);
5276 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005277}
5278#endif
5279
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280
Bram Moolenaar4f974752019-02-17 17:44:42 +01005281#ifndef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005282
5283/*
5284 * Start termcap mode
5285 */
5286 static void
5287termcap_mode_start(void)
5288{
5289 DWORD cmodein;
5290
5291 if (g_fTermcapMode)
5292 return;
5293
5294 SaveConsoleBuffer(&g_cbNonTermcap);
5295
5296 if (g_cbTermcap.IsValid)
5297 {
5298 /*
5299 * We've been in termcap mode before. Restore certain screen
5300 * characteristics, including the buffer size and the window
5301 * size. Since we will be redrawing the screen, we don't need
5302 * to restore the actual contents of the buffer.
5303 */
5304 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005305 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5307 Rows = g_cbTermcap.Info.dwSize.Y;
5308 Columns = g_cbTermcap.Info.dwSize.X;
5309 }
5310 else
5311 {
5312 /*
5313 * This is our first time entering termcap mode. Clear the console
5314 * screen buffer, and resize the buffer to match the current window
5315 * size. We will use this as the size of our editing environment.
5316 */
5317 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005318 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5320 }
5321
5322#ifdef FEAT_TITLE
5323 resettitle();
5324#endif
5325
5326 GetConsoleMode(g_hConIn, &cmodein);
5327#ifdef FEAT_MOUSE
5328 if (g_fMouseActive)
5329 cmodein |= ENABLE_MOUSE_INPUT;
5330 else
5331 cmodein &= ~ENABLE_MOUSE_INPUT;
5332#endif
5333 cmodein |= ENABLE_WINDOW_INPUT;
5334 SetConsoleMode(g_hConIn, cmodein);
5335
5336 redraw_later_clear();
5337 g_fTermcapMode = TRUE;
5338}
5339
5340
5341/*
5342 * End termcap mode
5343 */
5344 static void
5345termcap_mode_end(void)
5346{
5347 DWORD cmodein;
5348 ConsoleBuffer *cb;
5349 COORD coord;
5350 DWORD dwDummy;
5351
5352 if (!g_fTermcapMode)
5353 return;
5354
5355 SaveConsoleBuffer(&g_cbTermcap);
5356
5357 GetConsoleMode(g_hConIn, &cmodein);
5358 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5359 SetConsoleMode(g_hConIn, cmodein);
5360
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005361#ifdef FEAT_RESTORE_ORIG_SCREEN
5362 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5363#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005365#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005366 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005367 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368 SetConsoleCursorInfo(g_hConOut, &g_cci);
5369
5370 if (p_rs || exiting)
5371 {
5372 /*
5373 * Clear anything that happens to be on the current line.
5374 */
5375 coord.X = 0;
5376 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5377 FillConsoleOutputCharacter(g_hConOut, ' ',
5378 cb->Info.dwSize.X, coord, &dwDummy);
5379 /*
5380 * The following is just for aesthetics. If we are exiting without
5381 * restoring the screen, then we want to have a prompt string
5382 * appear at the bottom line. However, the command interpreter
5383 * seems to always advance the cursor one line before displaying
5384 * the prompt string, which causes the screen to scroll. To
5385 * counter this, move the cursor up one line before exiting.
5386 */
5387 if (exiting && !p_rs)
5388 coord.Y--;
5389 /*
5390 * Position the cursor at the leftmost column of the desired row.
5391 */
5392 SetConsoleCursorPosition(g_hConOut, coord);
5393 }
5394
5395 g_fTermcapMode = FALSE;
5396}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005397#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398
5399
Bram Moolenaar4f974752019-02-17 17:44:42 +01005400#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401 void
5402mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005403 char_u *s UNUSED,
5404 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405{
5406 /* never used */
5407}
5408
5409#else
5410
5411/*
5412 * clear `n' chars, starting from `coord'
5413 */
5414 static void
5415clear_chars(
5416 COORD coord,
5417 DWORD n)
5418{
5419 DWORD dwDummy;
5420
5421 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005422
5423 if (!USE_VTP)
5424 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5425 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005426 {
5427 set_console_color_rgb();
5428 gotoxy(coord.X + 1, coord.Y + 1);
5429 vtp_printf("\033[%dX", n);
5430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005431}
5432
5433
5434/*
5435 * Clear the screen
5436 */
5437 static void
5438clear_screen(void)
5439{
5440 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005441
5442 if (!USE_VTP)
5443 clear_chars(g_coord, Rows * Columns);
5444 else
5445 {
5446 set_console_color_rgb();
5447 gotoxy(1, 1);
5448 vtp_printf("\033[2J");
5449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450}
5451
5452
5453/*
5454 * Clear to end of display
5455 */
5456 static void
5457clear_to_end_of_display(void)
5458{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005459 COORD save = g_coord;
5460
5461 if (!USE_VTP)
5462 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005464 else
5465 {
5466 set_console_color_rgb();
5467 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5468 vtp_printf("\033[0J");
5469
5470 gotoxy(save.X + 1, save.Y + 1);
5471 g_coord = save;
5472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005473}
5474
5475
5476/*
5477 * Clear to end of line
5478 */
5479 static void
5480clear_to_end_of_line(void)
5481{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005482 COORD save = g_coord;
5483
5484 if (!USE_VTP)
5485 clear_chars(g_coord, Columns - g_coord.X);
5486 else
5487 {
5488 set_console_color_rgb();
5489 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5490 vtp_printf("\033[0K");
5491
5492 gotoxy(save.X + 1, save.Y + 1);
5493 g_coord = save;
5494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495}
5496
5497
5498/*
5499 * Scroll the scroll region up by `cLines' lines
5500 */
5501 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005502scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503{
5504 COORD oldcoord = g_coord;
5505
5506 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5507 delete_lines(cLines);
5508
5509 g_coord = oldcoord;
5510}
5511
5512
5513/*
5514 * Set the scroll region
5515 */
5516 static void
5517set_scroll_region(
5518 unsigned left,
5519 unsigned top,
5520 unsigned right,
5521 unsigned bottom)
5522{
5523 if (left >= right
5524 || top >= bottom
5525 || right > (unsigned) Columns - 1
5526 || bottom > (unsigned) Rows - 1)
5527 return;
5528
5529 g_srScrollRegion.Left = left;
5530 g_srScrollRegion.Top = top;
5531 g_srScrollRegion.Right = right;
5532 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005533}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005534
Bram Moolenaar6982f422019-02-16 16:48:01 +01005535 static void
5536set_scroll_region_tb(
5537 unsigned top,
5538 unsigned bottom)
5539{
5540 if (top >= bottom || bottom > (unsigned)Rows - 1)
5541 return;
5542
5543 g_srScrollRegion.Top = top;
5544 g_srScrollRegion.Bottom = bottom;
5545}
5546
5547 static void
5548set_scroll_region_lr(
5549 unsigned left,
5550 unsigned right)
5551{
5552 if (left >= right || right > (unsigned)Columns - 1)
5553 return;
5554
5555 g_srScrollRegion.Left = left;
5556 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557}
5558
5559
5560/*
5561 * Insert `cLines' lines at the current cursor position
5562 */
5563 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005564insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005566 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 COORD dest;
5568 CHAR_INFO fill;
5569
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005570 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5571
Bram Moolenaar6982f422019-02-16 16:48:01 +01005572 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 dest.Y = g_coord.Y + cLines;
5574
Bram Moolenaar6982f422019-02-16 16:48:01 +01005575 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576 source.Top = g_coord.Y;
5577 source.Right = g_srScrollRegion.Right;
5578 source.Bottom = g_srScrollRegion.Bottom - cLines;
5579
Bram Moolenaar6982f422019-02-16 16:48:01 +01005580 clip.Left = g_srScrollRegion.Left;
5581 clip.Top = g_coord.Y;
5582 clip.Right = g_srScrollRegion.Right;
5583 clip.Bottom = g_srScrollRegion.Bottom;
5584
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005585 fill.Char.AsciiChar = ' ';
5586 if (!USE_VTP)
5587 fill.Attributes = g_attrCurrent;
5588 else
5589 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005591 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005592
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005593 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5594
Bram Moolenaar6982f422019-02-16 16:48:01 +01005595 // Here we have to deal with a win32 console flake: If the scroll
5596 // region looks like abc and we scroll c to a and fill with d we get
5597 // cbd... if we scroll block c one line at a time to a, we get cdd...
5598 // vim expects cdd consistently... So we have to deal with that
5599 // here... (this also occurs scrolling the same way in the other
5600 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601
5602 if (source.Bottom < dest.Y)
5603 {
5604 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005605 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606
Bram Moolenaar6982f422019-02-16 16:48:01 +01005607 coord.X = source.Left;
5608 for (i = clip.Top; i < dest.Y; ++i)
5609 {
5610 coord.Y = i;
5611 clear_chars(coord, source.Right - source.Left + 1);
5612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 }
5614}
5615
5616
5617/*
5618 * Delete `cLines' lines at the current cursor position
5619 */
5620 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005621delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005623 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 COORD dest;
5625 CHAR_INFO fill;
5626 int nb;
5627
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005628 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5629
Bram Moolenaar6982f422019-02-16 16:48:01 +01005630 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 dest.Y = g_coord.Y;
5632
Bram Moolenaar6982f422019-02-16 16:48:01 +01005633 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 source.Top = g_coord.Y + cLines;
5635 source.Right = g_srScrollRegion.Right;
5636 source.Bottom = g_srScrollRegion.Bottom;
5637
Bram Moolenaar6982f422019-02-16 16:48:01 +01005638 clip.Left = g_srScrollRegion.Left;
5639 clip.Top = g_coord.Y;
5640 clip.Right = g_srScrollRegion.Right;
5641 clip.Bottom = g_srScrollRegion.Bottom;
5642
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005643 fill.Char.AsciiChar = ' ';
5644 if (!USE_VTP)
5645 fill.Attributes = g_attrCurrent;
5646 else
5647 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005649 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005650
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005651 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5652
Bram Moolenaar6982f422019-02-16 16:48:01 +01005653 // Here we have to deal with a win32 console flake; See insert_lines()
5654 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655
5656 nb = dest.Y + (source.Bottom - source.Top) + 1;
5657
5658 if (nb < source.Top)
5659 {
5660 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005661 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662
Bram Moolenaar6982f422019-02-16 16:48:01 +01005663 coord.X = source.Left;
5664 for (i = nb; i < clip.Bottom; ++i)
5665 {
5666 coord.Y = i;
5667 clear_chars(coord, source.Right - source.Left + 1);
5668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 }
5670}
5671
5672
5673/*
5674 * Set the cursor position
5675 */
5676 static void
5677gotoxy(
5678 unsigned x,
5679 unsigned y)
5680{
5681 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5682 return;
5683
5684 /* external cursor coords are 1-based; internal are 0-based */
5685 g_coord.X = x - 1;
5686 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005687
5688 if (!USE_VTP)
5689 SetConsoleCursorPosition(g_hConOut, g_coord);
5690 else
5691 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692}
5693
5694
5695/*
5696 * Set the current text attribute = (foreground | background)
5697 * See ../doc/os_win32.txt for the numbers.
5698 */
5699 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005700textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005702 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703
5704 SetConsoleTextAttribute(g_hConOut, wAttr);
5705}
5706
5707
5708 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005709textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005711 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005713 if (!USE_VTP)
5714 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5715 else
5716 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717}
5718
5719
5720 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005721textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005723 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005725 if (!USE_VTP)
5726 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5727 else
5728 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729}
5730
5731
5732/*
5733 * restore the default text attribute (whatever we started with)
5734 */
5735 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005736normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005738 if (!USE_VTP)
5739 textattr(g_attrDefault);
5740 else
5741 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742}
5743
5744
5745static WORD g_attrPreStandout = 0;
5746
5747/*
5748 * Make the text standout, by brightening it
5749 */
5750 static void
5751standout(void)
5752{
5753 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5756}
5757
5758
5759/*
5760 * Turn off standout mode
5761 */
5762 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005763standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764{
5765 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005767
5768 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769}
5770
5771
5772/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005773 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774 */
5775 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005776mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777{
5778 char_u *p;
5779 int n;
5780
5781 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5782 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005783 if (
5784#ifdef FEAT_TERMGUICOLORS
5785 !p_tgc &&
5786#endif
5787 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788 {
5789 p = T_ME + 2;
5790 n = getdigits(&p);
5791 if (*p == 'm' && n > 0)
5792 {
5793 cterm_normal_fg_color = (n & 0xf) + 1;
5794 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5795 }
5796 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005797#ifdef FEAT_TERMGUICOLORS
5798 cterm_normal_fg_gui_color = INVALCOLOR;
5799 cterm_normal_bg_gui_color = INVALCOLOR;
5800#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801}
5802
5803
5804/*
5805 * visual bell: flash the screen
5806 */
5807 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005808visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809{
5810 COORD coordOrigin = {0, 0};
5811 WORD attrFlash = ~g_attrCurrent & 0xff;
5812
5813 DWORD dwDummy;
5814 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5815
5816 if (oldattrs == NULL)
5817 return;
5818 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5819 coordOrigin, &dwDummy);
5820 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5821 coordOrigin, &dwDummy);
5822
5823 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005824 if (!USE_VTP)
5825 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826 coordOrigin, &dwDummy);
5827 vim_free(oldattrs);
5828}
5829
5830
5831/*
5832 * Make the cursor visible or invisible
5833 */
5834 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005835cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005836{
5837 s_cursor_visible = fVisible;
5838#ifdef MCH_CURSOR_SHAPE
5839 mch_update_cursor();
5840#endif
5841}
5842
5843
5844/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005845 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005846 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005848 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005850 char_u *pchBuf,
5851 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005853 COORD coord = g_coord;
5854 DWORD written;
5855 DWORD n, cchwritten, cells;
5856 static WCHAR *unicodebuf = NULL;
5857 static int unibuflen = 0;
5858 int length;
5859 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005861 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5862 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005863 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005864 vim_free(unicodebuf);
5865 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5866 unibuflen = length;
5867 }
5868 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
5869 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005871 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005872
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005873 if (!USE_VTP)
5874 {
5875 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5876 coord, &written);
5877 // When writing fails or didn't write a single character, pretend one
5878 // character was written, otherwise we get stuck.
5879 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5880 coord, &cchwritten) == 0
5881 || cchwritten == 0 || cchwritten == (DWORD)-1)
5882 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005883 }
5884 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005885 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005886 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
5887 NULL) == 0 || cchwritten == 0)
5888 cchwritten = 1;
5889 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005890
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005891 if (cchwritten == length)
5892 {
5893 written = cbToWrite;
5894 g_coord.X += (SHORT)cells;
5895 }
5896 else
5897 {
5898 char_u *p = pchBuf;
5899 for (n = 0; n < cchwritten; n++)
5900 MB_CPTR_ADV(p);
5901 written = p - pchBuf;
5902 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005903 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904
5905 while (g_coord.X > g_srScrollRegion.Right)
5906 {
5907 g_coord.X -= (SHORT) Columns;
5908 if (g_coord.Y < g_srScrollRegion.Bottom)
5909 g_coord.Y++;
5910 }
5911
5912 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5913
5914 return written;
5915}
5916
5917
5918/*
5919 * mch_write(): write the output buffer to the screen, translating ESC
5920 * sequences into calls to console output routines.
5921 */
5922 void
5923mch_write(
5924 char_u *s,
5925 int len)
5926{
5927 s[len] = NUL;
5928
5929 if (!term_console)
5930 {
5931 write(1, s, (unsigned)len);
5932 return;
5933 }
5934
5935 /* translate ESC | sequences into faked bios calls */
5936 while (len--)
5937 {
5938 /* optimization: use one single write_chars for runs of text,
5939 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005940 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941
5942 if (p_wd)
5943 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005944 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 if (prefix != 0)
5946 prefix = 1;
5947 }
5948
5949 if (prefix != 0)
5950 {
5951 DWORD nWritten;
5952
5953 nWritten = write_chars(s, prefix);
5954#ifdef MCH_WRITE_DUMP
5955 if (fdDump)
5956 {
5957 fputc('>', fdDump);
5958 fwrite(s, sizeof(char_u), nWritten, fdDump);
5959 fputs("<\n", fdDump);
5960 }
5961#endif
5962 len -= (nWritten - 1);
5963 s += nWritten;
5964 }
5965 else if (s[0] == '\n')
5966 {
5967 /* \n, newline: go to the beginning of the next line or scroll */
5968 if (g_coord.Y == g_srScrollRegion.Bottom)
5969 {
5970 scroll(1);
5971 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5972 }
5973 else
5974 {
5975 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5976 }
5977#ifdef MCH_WRITE_DUMP
5978 if (fdDump)
5979 fputs("\\n\n", fdDump);
5980#endif
5981 s++;
5982 }
5983 else if (s[0] == '\r')
5984 {
5985 /* \r, carriage return: go to beginning of line */
5986 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5987#ifdef MCH_WRITE_DUMP
5988 if (fdDump)
5989 fputs("\\r\n", fdDump);
5990#endif
5991 s++;
5992 }
5993 else if (s[0] == '\b')
5994 {
5995 /* \b, backspace: move cursor one position left */
5996 if (g_coord.X > g_srScrollRegion.Left)
5997 g_coord.X--;
5998 else if (g_coord.Y > g_srScrollRegion.Top)
5999 {
6000 g_coord.X = g_srScrollRegion.Right;
6001 g_coord.Y--;
6002 }
6003 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6004#ifdef MCH_WRITE_DUMP
6005 if (fdDump)
6006 fputs("\\b\n", fdDump);
6007#endif
6008 s++;
6009 }
6010 else if (s[0] == '\a')
6011 {
6012 /* \a, bell */
6013 MessageBeep(0xFFFFFFFF);
6014#ifdef MCH_WRITE_DUMP
6015 if (fdDump)
6016 fputs("\\a\n", fdDump);
6017#endif
6018 s++;
6019 }
6020 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6021 {
6022#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006023 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006025 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006026 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027
6028 switch (s[2])
6029 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030 case '0': case '1': case '2': case '3': case '4':
6031 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006032 p = s + 1;
6033 do
6034 {
6035 ++p;
6036 args[argc] = getdigits(&p);
6037 argc += (argc < 15) ? 1 : 0;
6038 if (p > s + len)
6039 break;
6040 } while (*p == ';');
6041
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 if (p > s + len)
6043 break;
6044
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006045 arg1 = args[0];
6046 arg2 = args[1];
6047 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006049 if (argc == 1 && args[0] == 0)
6050 normvideo();
6051 else if (argc == 1)
6052 {
6053 if (USE_VTP)
6054 textcolor((WORD) arg1);
6055 else
6056 textattr((WORD) arg1);
6057 }
6058 else if (USE_VTP)
6059 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006061 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006063 gotoxy(arg2, arg1);
6064 }
6065 else if (argc == 2 && *p == 'r')
6066 {
6067 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6068 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006069 else if (argc == 2 && *p == 'R')
6070 {
6071 set_scroll_region_tb(arg1, arg2);
6072 }
6073 else if (argc == 2 && *p == 'V')
6074 {
6075 set_scroll_region_lr(arg1, arg2);
6076 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006077 else if (argc == 1 && *p == 'A')
6078 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079 gotoxy(g_coord.X + 1,
6080 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6081 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006082 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 {
6084 textbackground((WORD) arg1);
6085 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006086 else if (argc == 1 && *p == 'C')
6087 {
6088 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6089 g_coord.Y + 1);
6090 }
6091 else if (argc == 1 && *p == 'f')
6092 {
6093 textcolor((WORD) arg1);
6094 }
6095 else if (argc == 1 && *p == 'H')
6096 {
6097 gotoxy(1, arg1);
6098 }
6099 else if (argc == 1 && *p == 'L')
6100 {
6101 insert_lines(arg1);
6102 }
6103 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104 {
6105 delete_lines(arg1);
6106 }
6107
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006108 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 s = p + 1;
6110 break;
6111
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 gotoxy(g_coord.X + 1,
6114 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6115 goto got3;
6116
6117 case 'B':
6118 visual_bell();
6119 goto got3;
6120
6121 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6123 g_coord.Y + 1);
6124 goto got3;
6125
6126 case 'E':
6127 termcap_mode_end();
6128 goto got3;
6129
6130 case 'F':
6131 standout();
6132 goto got3;
6133
6134 case 'f':
6135 standend();
6136 goto got3;
6137
6138 case 'H':
6139 gotoxy(1, 1);
6140 goto got3;
6141
6142 case 'j':
6143 clear_to_end_of_display();
6144 goto got3;
6145
6146 case 'J':
6147 clear_screen();
6148 goto got3;
6149
6150 case 'K':
6151 clear_to_end_of_line();
6152 goto got3;
6153
6154 case 'L':
6155 insert_lines(1);
6156 goto got3;
6157
6158 case 'M':
6159 delete_lines(1);
6160 goto got3;
6161
6162 case 'S':
6163 termcap_mode_start();
6164 goto got3;
6165
6166 case 'V':
6167 cursor_visible(TRUE);
6168 goto got3;
6169
6170 case 'v':
6171 cursor_visible(FALSE);
6172 goto got3;
6173
6174 got3:
6175 s += 3;
6176 len -= 2;
6177 }
6178
6179#ifdef MCH_WRITE_DUMP
6180 if (fdDump)
6181 {
6182 fputs("ESC | ", fdDump);
6183 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6184 fputc('\n', fdDump);
6185 }
6186#endif
6187 }
6188 else
6189 {
6190 /* Write a single character */
6191 DWORD nWritten;
6192
6193 nWritten = write_chars(s, 1);
6194#ifdef MCH_WRITE_DUMP
6195 if (fdDump)
6196 {
6197 fputc('>', fdDump);
6198 fwrite(s, sizeof(char_u), nWritten, fdDump);
6199 fputs("<\n", fdDump);
6200 }
6201#endif
6202
6203 len -= (nWritten - 1);
6204 s += nWritten;
6205 }
6206 }
6207
6208#ifdef MCH_WRITE_DUMP
6209 if (fdDump)
6210 fflush(fdDump);
6211#endif
6212}
6213
Bram Moolenaar4f974752019-02-17 17:44:42 +01006214#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215
6216
6217/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006218 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219 */
6220 void
6221mch_delay(
6222 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006223 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006225#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006227#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006229# ifdef FEAT_MZSCHEME
6230 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6231 {
6232 int towait = p_mzq;
6233
6234 /* if msec is large enough, wait by portions in p_mzq */
6235 while (msec > 0)
6236 {
6237 mzvim_check_threads();
6238 if (msec < towait)
6239 towait = msec;
6240 Sleep(towait);
6241 msec -= towait;
6242 }
6243 }
6244 else
6245# endif
6246 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006248 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249#endif
6250}
6251
6252
6253/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006254 * This version of remove is not scared by a readonly (backup) file.
6255 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 * Return 0 for success, -1 for failure.
6257 */
6258 int
6259mch_remove(char_u *name)
6260{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006261 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 int n;
6263
Bram Moolenaar203258c2016-01-17 22:15:16 +01006264 /*
6265 * On Windows, deleting a directory's symbolic link is done by
6266 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6267 */
6268 if (mch_isdir(name) && mch_is_symbolic_link(name))
6269 return mch_rmdir(name);
6270
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006271 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6272
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006273 wn = enc_to_utf16(name, NULL);
6274 if (wn == NULL)
6275 return -1;
6276
6277 n = DeleteFileW(wn) ? 0 : -1;
6278 vim_free(wn);
6279 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280}
6281
6282
6283/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006284 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 */
6286 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006287mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288{
Bram Moolenaar4f974752019-02-17 17:44:42 +01006289#ifndef FEAT_GUI_MSWIN /* never used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 if (g_fCtrlCPressed || g_fCBrkPressed)
6291 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006292 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6294 got_int = TRUE;
6295 }
6296#endif
6297}
6298
Bram Moolenaaree273972016-01-02 21:11:51 +01006299/* physical RAM to leave for the OS */
6300#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006301
6302/*
6303 * How much main memory in KiB that can be used by VIM.
6304 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006305 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006306mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006307{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006308 MEMORYSTATUSEX ms;
6309
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006310 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6311 * what fits in 32 bits. But it's not always available. */
6312 ms.dwLength = sizeof(MEMORYSTATUSEX);
6313 GlobalMemoryStatusEx(&ms);
6314 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006315 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006316 /* Process address space fits in physical RAM, use all of it. */
6317 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006318 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006319 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006320 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006321 /* Catch old NT box or perverse hardware setup. */
6322 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006323 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006324 /* Use physical RAM less reserve for OS + data. */
6325 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006326}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006329 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6331 * file whose short file name is "FOO.BAR" (its long file name will
6332 * be correct: "foo.bar~"). Because a file can be accessed by
6333 * either its SFN or its LFN, "foo.bar" has effectively been
6334 * renamed to "foo.bar", which is not at all what was wanted. This
6335 * seems to happen only when renaming files with three-character
6336 * extensions by appending a suffix that does not include ".".
6337 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6338 *
6339 * There is another problem, which isn't really a bug but isn't right either:
6340 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6341 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6342 * service pack 6. Doesn't seem to happen on Windows 98.
6343 *
6344 * Like rename(), returns 0 upon success, non-zero upon failure.
6345 * Should probably set errno appropriately when errors occur.
6346 */
6347 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006348mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006350 WCHAR *p;
6351 int i;
6352 WCHAR szTempFile[_MAX_PATH + 1];
6353 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006356 // No need to play tricks unless the file name contains a "~" as the
6357 // seventh character.
6358 p = wold;
6359 for (i = 0; wold[i] != NUL; ++i)
6360 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6361 && wold[i + 1] != 0)
6362 p = wold + i + 1;
6363 if ((int)(wold + i - p) < 8 || p[6] != '~')
6364 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006366 // Get base path of new file name. Undocumented feature: If pszNewFile is
6367 // a directory, no error is returned and pszFilePart will be NULL.
6368 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006370 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006372 // Get (and create) a unique temporary file name in directory of new file
6373 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 return -2;
6375
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006376 // blow the temp file away
6377 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 return -3;
6379
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006380 // rename old file to the temp file
6381 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 return -4;
6383
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006384 // now create an empty file called pszOldFile; this prevents the operating
6385 // system using pszOldFile as an alias (SFN) if we're renaming within the
6386 // same directory. For example, we're editing a file called
6387 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6388 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6389 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6390 // cause all sorts of problems later in buf_write(). So, we create an
6391 // empty file called filena~1.txt and the system will have to find some
6392 // other SFN for filena~1.txt~, such as filena~2.txt
6393 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6395 return -5;
6396 if (!CloseHandle(hf))
6397 return -6;
6398
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006399 // rename the temp file to the new file
6400 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006402 // Renaming failed. Rename the file back to its old name, so that it
6403 // looks like nothing happened.
6404 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 return -7;
6406 }
6407
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006408 // Seems to be left around on Novell filesystems
6409 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006411 // finally, remove the empty old file
6412 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 return -8;
6414
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006415 return 0;
6416}
6417
6418
6419/*
6420 * Converts the filenames to UTF-16, then call mch_wrename().
6421 * Like rename(), returns 0 upon success, non-zero upon failure.
6422 */
6423 int
6424mch_rename(
6425 const char *pszOldFile,
6426 const char *pszNewFile)
6427{
6428 WCHAR *wold = NULL;
6429 WCHAR *wnew = NULL;
6430 int retval = -1;
6431
6432 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6433 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6434 if (wold != NULL && wnew != NULL)
6435 retval = mch_wrename(wold, wnew);
6436 vim_free(wold);
6437 vim_free(wnew);
6438 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439}
6440
6441/*
6442 * Get the default shell for the current hardware platform
6443 */
6444 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006445default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006447 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448}
6449
6450/*
6451 * mch_access() extends access() to do more detailed check on network drives.
6452 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6453 */
6454 int
6455mch_access(char *n, int p)
6456{
6457 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006459 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006460
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006461 wn = enc_to_utf16((char_u *)n, NULL);
6462 if (wn == NULL)
6463 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006465 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468
6469 if (p & R_OK)
6470 {
6471 /* Read check is performed by seeing if we can do a find file on
6472 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006473 int i;
6474 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006476 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6477 TempNameW[i] = wn[i];
6478 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6479 TempNameW[i++] = '\\';
6480 TempNameW[i++] = '*';
6481 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006483 hFile = FindFirstFileW(TempNameW, &d);
6484 if (hFile == INVALID_HANDLE_VALUE)
6485 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006486 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488 }
6489
6490 if (p & W_OK)
6491 {
6492 /* Trying to create a temporary file in the directory should catch
6493 * directories on read-only network shares. However, in
6494 * directories whose ACL allows writes but denies deletes will end
6495 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006496 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6497 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006498 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006499 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500 }
6501 }
6502 else
6503 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006504 // Don't consider a file read-only if another process has opened it.
6505 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6506
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 /* Trying to open the file for the required access does ACL, read-only
6508 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006509 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6510 | ((p & R_OK) ? GENERIC_READ : 0);
6511
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006512 hFile = CreateFileW(wn, access_mode, share_mode,
6513 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 if (hFile == INVALID_HANDLE_VALUE)
6515 goto getout;
6516 CloseHandle(hFile);
6517 }
6518
6519 retval = 0; /* success */
6520getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 return retval;
6523}
6524
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006526 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 */
6528 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006529mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006531 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01006532#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 WCHAR *wn;
6534 int f;
6535
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006536 wn = enc_to_utf16((char_u *)name, NULL);
6537 if (wn == NULL)
6538 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006540 f = _wopen(wn, flags, mode);
6541 vim_free(wn);
6542 return f;
6543#else
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006544 /* open() can open a file which name is longer than _MAX_PATH bytes
6545 * and shorter than _MAX_PATH characters successfully, but sometimes it
6546 * causes unexpected error in another part. We make it an error explicitly
6547 * here. */
6548 if (strlen(name) >= _MAX_PATH)
6549 return -1;
6550
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 return open(name, flags, mode);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006552#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553}
6554
6555/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006556 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 */
6558 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006559mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560{
6561 WCHAR *wn, *wm;
6562 FILE *f = NULL;
6563
Bram Moolenaara12a1612019-01-24 16:39:02 +01006564#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006565 /* Work around an annoying assertion in the Microsoft debug CRT
6566 * when mode's text/binary setting doesn't match _get_fmode(). */
6567 char newMode = mode[strlen(mode) - 1];
6568 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006569
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006570 _get_fmode(&oldMode);
6571 if (newMode == 't')
6572 _set_fmode(_O_TEXT);
6573 else if (newMode == 'b')
6574 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006575#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006576 wn = enc_to_utf16((char_u *)name, NULL);
6577 wm = enc_to_utf16((char_u *)mode, NULL);
6578 if (wn != NULL && wm != NULL)
6579 f = _wfopen(wn, wm);
6580 vim_free(wn);
6581 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006582
Bram Moolenaara12a1612019-01-24 16:39:02 +01006583#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006584 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006585#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006586 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589/*
6590 * SUB STREAM (aka info stream) handling:
6591 *
6592 * NTFS can have sub streams for each file. Normal contents of file is
6593 * stored in the main stream, and extra contents (author information and
6594 * title and so on) can be stored in sub stream. After Windows 2000, user
6595 * can access and store those informations in sub streams via explorer's
6596 * property menuitem in right click menu. Those informations in sub streams
6597 * were lost when copying only the main stream. So we have to copy sub
6598 * streams.
6599 *
6600 * Incomplete explanation:
6601 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6602 * More useful info and an example:
6603 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6604 */
6605
6606/*
6607 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6608 * and write to stream "substream" of file "to".
6609 * Errors are ignored.
6610 */
6611 static void
6612copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6613{
6614 HANDLE hTo;
6615 WCHAR *to_name;
6616
6617 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6618 wcscpy(to_name, to);
6619 wcscat(to_name, substream);
6620
6621 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6622 FILE_ATTRIBUTE_NORMAL, NULL);
6623 if (hTo != INVALID_HANDLE_VALUE)
6624 {
6625 long done;
6626 DWORD todo;
6627 DWORD readcnt, written;
6628 char buf[4096];
6629
6630 /* Copy block of bytes at a time. Abort when something goes wrong. */
6631 for (done = 0; done < len; done += written)
6632 {
6633 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006634 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6635 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6637 FALSE, FALSE, context)
6638 || readcnt != todo
6639 || !WriteFile(hTo, buf, todo, &written, NULL)
6640 || written != todo)
6641 break;
6642 }
6643 CloseHandle(hTo);
6644 }
6645
6646 free(to_name);
6647}
6648
6649/*
6650 * Copy info streams from file "from" to file "to".
6651 */
6652 static void
6653copy_infostreams(char_u *from, char_u *to)
6654{
6655 WCHAR *fromw;
6656 WCHAR *tow;
6657 HANDLE sh;
6658 WIN32_STREAM_ID sid;
6659 int headersize;
6660 WCHAR streamname[_MAX_PATH];
6661 DWORD readcount;
6662 void *context = NULL;
6663 DWORD lo, hi;
6664 int len;
6665
6666 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006667 fromw = enc_to_utf16(from, NULL);
6668 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 if (fromw != NULL && tow != NULL)
6670 {
6671 /* Open the file for reading. */
6672 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6673 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6674 if (sh != INVALID_HANDLE_VALUE)
6675 {
6676 /* Use BackupRead() to find the info streams. Repeat until we
6677 * have done them all.*/
6678 for (;;)
6679 {
6680 /* Get the header to find the length of the stream name. If
6681 * the "readcount" is zero we have done all info streams. */
6682 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006683 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6685 &readcount, FALSE, FALSE, &context)
6686 || readcount == 0)
6687 break;
6688
6689 /* We only deal with streams that have a name. The normal
6690 * file data appears to be without a name, even though docs
6691 * suggest it is called "::$DATA". */
6692 if (sid.dwStreamNameSize > 0)
6693 {
6694 /* Read the stream name. */
6695 if (!BackupRead(sh, (LPBYTE)streamname,
6696 sid.dwStreamNameSize,
6697 &readcount, FALSE, FALSE, &context))
6698 break;
6699
6700 /* Copy an info stream with a name ":anything:$DATA".
6701 * Skip "::$DATA", it has no stream name (examples suggest
6702 * it might be used for the normal file contents).
6703 * Note that BackupRead() counts bytes, but the name is in
6704 * wide characters. */
6705 len = readcount / sizeof(WCHAR);
6706 streamname[len] = 0;
6707 if (len > 7 && wcsicmp(streamname + len - 6,
6708 L":$DATA") == 0)
6709 {
6710 streamname[len - 6] = 0;
6711 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006712 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 }
6714 }
6715
6716 /* Advance to the next stream. We might try seeking too far,
6717 * but BackupSeek() doesn't skip over stream borders, thus
6718 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006719 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 &lo, &hi, &context);
6721 }
6722
6723 /* Clear the context. */
6724 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6725
6726 CloseHandle(sh);
6727 }
6728 }
6729 vim_free(fromw);
6730 vim_free(tow);
6731}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732
6733/*
6734 * Copy file attributes from file "from" to file "to".
6735 * For Windows NT and later we copy info streams.
6736 * Always returns zero, errors are ignored.
6737 */
6738 int
6739mch_copy_file_attribute(char_u *from, char_u *to)
6740{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006742 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743 return 0;
6744}
6745
6746#if defined(MYRESETSTKOFLW) || defined(PROTO)
6747/*
6748 * Recreate a destroyed stack guard page in win32.
6749 * Written by Benjamin Peterson.
6750 */
6751
6752/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006753# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754
6755/*
6756 * This function does the same thing as _resetstkoflw(), which is only
6757 * available in DevStudio .net and later.
6758 * Returns 0 for failure, 1 for success.
6759 */
6760 int
6761myresetstkoflw(void)
6762{
6763 BYTE *pStackPtr;
6764 BYTE *pGuardPage;
6765 BYTE *pStackBase;
6766 BYTE *pLowestPossiblePage;
6767 MEMORY_BASIC_INFORMATION mbi;
6768 SYSTEM_INFO si;
6769 DWORD nPageSize;
6770 DWORD dummy;
6771
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 /* We need to know the system page size. */
6773 GetSystemInfo(&si);
6774 nPageSize = si.dwPageSize;
6775
6776 /* ...and the current stack pointer */
6777 pStackPtr = (BYTE*)_alloca(1);
6778
6779 /* ...and the base of the stack. */
6780 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6781 return 0;
6782 pStackBase = (BYTE*)mbi.AllocationBase;
6783
6784 /* ...and the page thats min_stack_req pages away from stack base; this is
6785 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006786 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006789 /* We want the first committed page in the stack Start at the stack
6790 * base and move forward through memory until we find a committed block.
6791 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 BYTE *pBlock = pStackBase;
6793
Bram Moolenaara466c992005-07-09 21:03:22 +00006794 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 {
6796 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6797 return 0;
6798
6799 pBlock += mbi.RegionSize;
6800
6801 if (mbi.State & MEM_COMMIT)
6802 break;
6803 }
6804
6805 /* mbi now describes the first committed block in the stack. */
6806 if (mbi.Protect & PAGE_GUARD)
6807 return 1;
6808
6809 /* decide where the guard page should start */
6810 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6811 pGuardPage = pLowestPossiblePage;
6812 else
6813 pGuardPage = (BYTE*)mbi.BaseAddress;
6814
6815 /* allocate the guard page */
6816 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6817 return 0;
6818
6819 /* apply the guard attribute to the page */
6820 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6821 &dummy))
6822 return 0;
6823 }
6824
6825 return 1;
6826}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006827#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006829
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006830/*
6831 * The command line arguments in UCS2
6832 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006833static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006834static LPWSTR *ArglistW = NULL;
6835static int global_argc = 0;
6836static char **global_argv;
6837
6838static int used_file_argc = 0; /* last argument in global_argv[] used
6839 for the argument list. */
6840static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6841 command line arguments added to
6842 the argument list */
6843static int used_file_count = 0; /* nr of entries in used_file_indexes */
6844static int used_file_literal = FALSE; /* take file names literally */
6845static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006846static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006847static int used_alist_count = 0;
6848
6849
6850/*
6851 * Get the command line arguments. Unicode version.
6852 * Returns argc. Zero when something fails.
6853 */
6854 int
6855get_cmd_argsW(char ***argvp)
6856{
6857 char **argv = NULL;
6858 int argc = 0;
6859 int i;
6860
Bram Moolenaar14993322014-09-09 12:25:33 +02006861 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006862 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6863 if (ArglistW != NULL)
6864 {
6865 argv = malloc((nArgsW + 1) * sizeof(char *));
6866 if (argv != NULL)
6867 {
6868 argc = nArgsW;
6869 argv[argc] = NULL;
6870 for (i = 0; i < argc; ++i)
6871 {
6872 int len;
6873
6874 /* Convert each Unicode argument to the current codepage. */
6875 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006876 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006877 (LPSTR *)&argv[i], &len, 0, 0);
6878 if (argv[i] == NULL)
6879 {
6880 /* Out of memory, clear everything. */
6881 while (i > 0)
6882 free(argv[--i]);
6883 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006884 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006885 argc = 0;
6886 }
6887 }
6888 }
6889 }
6890
6891 global_argc = argc;
6892 global_argv = argv;
6893 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006894 {
6895 if (used_file_indexes != NULL)
6896 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006897 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006898 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006899
6900 if (argvp != NULL)
6901 *argvp = argv;
6902 return argc;
6903}
6904
6905 void
6906free_cmd_argsW(void)
6907{
6908 if (ArglistW != NULL)
6909 {
6910 GlobalFree(ArglistW);
6911 ArglistW = NULL;
6912 }
6913}
6914
6915/*
6916 * Remember "name" is an argument that was added to the argument list.
6917 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6918 * is called.
6919 */
6920 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006921used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006922{
6923 int i;
6924
6925 if (used_file_indexes == NULL)
6926 return;
6927 for (i = used_file_argc + 1; i < global_argc; ++i)
6928 if (STRCMP(global_argv[i], name) == 0)
6929 {
6930 used_file_argc = i;
6931 used_file_indexes[used_file_count++] = i;
6932 break;
6933 }
6934 used_file_literal = literal;
6935 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006936 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006937}
6938
6939/*
6940 * Remember the length of the argument list as it was. If it changes then we
6941 * leave it alone when 'encoding' is set.
6942 */
6943 void
6944set_alist_count(void)
6945{
6946 used_alist_count = GARGCOUNT;
6947}
6948
6949/*
6950 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6951 * has been changed while starting up. Use the UCS-2 command line arguments
6952 * and convert them to 'encoding'.
6953 */
6954 void
6955fix_arg_enc(void)
6956{
6957 int i;
6958 int idx;
6959 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006960 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006961
6962 /* Safety checks:
6963 * - if argument count differs between the wide and non-wide argument
6964 * list, something must be wrong.
6965 * - the file name arguments must have been located.
6966 * - the length of the argument list wasn't changed by the user.
6967 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006968 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006969 || ArglistW == NULL
6970 || used_file_indexes == NULL
6971 || used_file_count == 0
6972 || used_alist_count != GARGCOUNT)
6973 return;
6974
Bram Moolenaar86b68352004-12-27 21:59:20 +00006975 /* Remember the buffer numbers for the arguments. */
6976 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6977 if (fnum_list == NULL)
6978 return; /* out of memory */
6979 for (i = 0; i < GARGCOUNT; ++i)
6980 fnum_list[i] = GARGLIST[i].ae_fnum;
6981
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006982 /* Clear the argument list. Make room for the new arguments. */
6983 alist_clear(&global_alist);
6984 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006985 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006986
6987 for (i = 0; i < used_file_count; ++i)
6988 {
6989 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006990 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006991 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006992 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02006993 int literal = used_file_literal;
6994
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006995# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006996 /* When using diff mode may need to concatenate file name to
6997 * directory name. Just like it's done in main(). */
6998 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6999 && !mch_isdir(alist_name(&GARGLIST[0])))
7000 {
7001 char_u *r;
7002
7003 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7004 if (r != NULL)
7005 {
7006 vim_free(str);
7007 str = r;
7008 }
7009 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007010# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007011 /* Re-use the old buffer by renaming it. When not using literal
7012 * names it's done by alist_expand() below. */
7013 if (used_file_literal)
7014 buf_set_name(fnum_list[i], str);
7015
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007016 /* Check backtick literal. backtick literal is already expanded in
7017 * main.c, so this part add str as literal. */
7018 if (literal == FALSE)
7019 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007020 size_t len = STRLEN(str);
7021
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007022 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7023 literal = TRUE;
7024 }
7025 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007026 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007027 }
7028
7029 if (!used_file_literal)
7030 {
7031 /* Now expand wildcards in the arguments. */
7032 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7033 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007034 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7035 * Also, unset wildignore to not be influenced by this option.
7036 * The arguments specified in command-line should be kept even if
7037 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007038 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007039 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007040 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007041 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007042 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007043 }
7044
7045 /* If wildcard expansion failed, we are editing the first file of the
7046 * arglist and there is no file name: Edit the first argument now. */
7047 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7048 {
7049 do_cmdline_cmd((char_u *)":rewind");
7050 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007051 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007052 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007053
7054 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007055}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007056
7057 int
7058mch_setenv(char *var, char *value, int x)
7059{
7060 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007061 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007062
7063 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7064 if (envbuf == NULL)
7065 return -1;
7066
7067 sprintf((char *)envbuf, "%s=%s", var, value);
7068
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007069 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007070
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007071 vim_free(envbuf);
7072 if (p == NULL)
7073 return -1;
7074 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007075#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007076 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007077#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007078 // Unlike Un*x systems, we can free the string for _wputenv().
7079 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007080
7081 return 0;
7082}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007083
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007084/*
7085 * Support for 256 colors and 24-bit colors was added in Windows 10
7086 * version 1703 (Creators update).
7087 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007088#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7089
7090/*
7091 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007092 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007093 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007094#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7095#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007096
7097 static void
7098vtp_flag_init(void)
7099{
7100 DWORD ver = get_build_number();
Bram Moolenaar4f974752019-02-17 17:44:42 +01007101#ifndef FEAT_GUI_MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007102 DWORD mode;
7103 HANDLE out;
7104
7105 out = GetStdHandle(STD_OUTPUT_HANDLE);
7106
7107 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7108 GetConsoleMode(out, &mode);
7109 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7110 if (SetConsoleMode(out, mode) == 0)
7111 vtp_working = 0;
7112#endif
7113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007114 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007115 conpty_working = 1;
7116 if (ver >= CONPTY_STABLE_BUILD)
7117 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007118
7119}
7120
Bram Moolenaar4f974752019-02-17 17:44:42 +01007121#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007122
7123 static void
7124vtp_init(void)
7125{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007126 HMODULE hKerneldll;
7127 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007128# ifdef FEAT_TERMGUICOLORS
7129 COLORREF fg, bg;
7130# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007131
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007132 /* Use functions supported from Vista */
7133 hKerneldll = GetModuleHandle("kernel32.dll");
7134 if (hKerneldll != NULL)
7135 {
7136 pGetConsoleScreenBufferInfoEx =
7137 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7138 hKerneldll, "GetConsoleScreenBufferInfoEx");
7139 pSetConsoleScreenBufferInfoEx =
7140 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7141 hKerneldll, "SetConsoleScreenBufferInfoEx");
7142 if (pGetConsoleScreenBufferInfoEx != NULL
7143 && pSetConsoleScreenBufferInfoEx != NULL)
7144 has_csbiex = TRUE;
7145 }
7146
7147 csbi.cbSize = sizeof(csbi);
7148 if (has_csbiex)
7149 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007150 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7151 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7152
7153# ifdef FEAT_TERMGUICOLORS
7154 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7155 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7156 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7157 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7158 default_console_color_bg = bg;
7159 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007160# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007161
7162 set_console_color_rgb();
7163}
7164
7165 static void
7166vtp_exit(void)
7167{
7168 reset_console_color_rgb();
7169}
7170
7171 static int
7172vtp_printf(
7173 char *format,
7174 ...)
7175{
7176 char_u buf[100];
7177 va_list list;
7178 DWORD result;
7179
7180 va_start(list, format);
7181 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7182 va_end(list);
7183 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7184 return (int)result;
7185}
7186
7187 static void
7188vtp_sgr_bulk(
7189 int arg)
7190{
7191 int args[1];
7192
7193 args[0] = arg;
7194 vtp_sgr_bulks(1, args);
7195}
7196
7197 static void
7198vtp_sgr_bulks(
7199 int argc,
7200 int *args
7201)
7202{
7203 /* 2('\033[') + 4('255.') * 16 + NUL */
7204 char_u buf[2 + (4 * 16) + 1];
7205 char_u *p;
7206 int i;
7207
7208 p = buf;
7209 *p++ = '\033';
7210 *p++ = '[';
7211
7212 for (i = 0; i < argc; ++i)
7213 {
7214 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7215 *p++ = ';';
7216 }
7217 p--;
7218 *p++ = 'm';
7219 *p = NUL;
7220 vtp_printf((char *)buf);
7221}
7222
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007223# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007224 static int
7225ctermtoxterm(
7226 int cterm)
7227{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007228 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007229
7230 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7231 return (((int)r << 16) | ((int)g << 8) | (int)b);
7232}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007233# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007234
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007235 static void
7236set_console_color_rgb(void)
7237{
7238# ifdef FEAT_TERMGUICOLORS
7239 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7240 int id;
7241 guicolor_T fg = INVALCOLOR;
7242 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007243 int ctermfg;
7244 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007245
7246 if (!USE_VTP)
7247 return;
7248
7249 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007250 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007251 syn_id2colors(id, &fg, &bg);
7252 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007253 {
7254 ctermfg = -1;
7255 if (id > 0)
7256 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007257 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7258 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007259 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007260 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007261 {
7262 ctermbg = -1;
7263 if (id > 0)
7264 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007265 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7266 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007267 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007268 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7269 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7270
7271 csbi.cbSize = sizeof(csbi);
7272 if (has_csbiex)
7273 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7274
7275 csbi.cbSize = sizeof(csbi);
7276 csbi.srWindow.Right += 1;
7277 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007278 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7279 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007280 if (has_csbiex)
7281 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7282# endif
7283}
7284
7285 static void
7286reset_console_color_rgb(void)
7287{
7288# ifdef FEAT_TERMGUICOLORS
7289 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7290
7291 csbi.cbSize = sizeof(csbi);
7292 if (has_csbiex)
7293 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7294
7295 csbi.cbSize = sizeof(csbi);
7296 csbi.srWindow.Right += 1;
7297 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007298 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7299 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007300 if (has_csbiex)
7301 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7302# endif
7303}
7304
7305 void
7306control_console_color_rgb(void)
7307{
7308 if (USE_VTP)
7309 set_console_color_rgb();
7310 else
7311 reset_console_color_rgb();
7312}
7313
7314 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007315use_vtp(void)
7316{
7317 return USE_VTP;
7318}
7319
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007320 int
7321is_term_win32(void)
7322{
7323 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7324}
7325
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007326 int
7327has_vtp_working(void)
7328{
7329 return vtp_working;
7330}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007331
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007332#endif
7333
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007334 int
7335has_conpty_working(void)
7336{
7337 return conpty_working;
7338}
7339
7340 int
7341is_conpty_stable(void)
7342{
7343 return conpty_stable;
7344}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007345
Bram Moolenaar4f974752019-02-17 17:44:42 +01007346#if !defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007347 void
7348resize_console_buf(void)
7349{
7350 CONSOLE_SCREEN_BUFFER_INFO csbi;
7351 COORD coord;
7352 SMALL_RECT newsize;
7353
7354 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7355 {
7356 coord.X = SRWIDTH(csbi.srWindow);
7357 coord.Y = SRHEIGHT(csbi.srWindow);
7358 SetConsoleScreenBufferSize(g_hConOut, coord);
7359
7360 newsize.Left = 0;
7361 newsize.Top = 0;
7362 newsize.Right = coord.X - 1;
7363 newsize.Bottom = coord.Y - 1;
7364 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7365
7366 SetConsoleScreenBufferSize(g_hConOut, coord);
7367 }
7368}
7369#endif