blob: 537af4675f6c7d2866826cc719e46ce37883819d [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 Moolenaarafde13b2019-04-28 19:46:49 +0200154#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
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;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200182#endif
183#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000184static int s_dont_use_vimrun = TRUE;
185static int need_vimrun_warning = FALSE;
186static char *vimrun_path = "vimrun ";
187#endif
188
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200189static int win32_getattrs(char_u *name);
190static int win32_setattrs(char_u *name, int attrs);
191static int win32_set_archive(char_u *name);
192
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100193static int conpty_working = 0;
194static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100195static void vtp_flag_init();
196
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200197#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100198static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_init();
200static void vtp_exit();
201static int vtp_printf(char *format, ...);
202static void vtp_sgr_bulk(int arg);
203static void vtp_sgr_bulks(int argc, int *argv);
204
205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
207
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200208static int g_color_index_bg = 0;
209static int g_color_index_fg = 7;
210
211# ifdef FEAT_TERMGUICOLORS
212static int default_console_color_bg = 0x000000; // black
213static int default_console_color_fg = 0xc0c0c0; // white
214# endif
215
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100216# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200217# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# else
219# define USE_VTP 0
220# endif
221
222static void set_console_color_rgb(void);
223static void reset_console_color_rgb(void);
224#endif
225
226/* This flag is newly created from Windows 10 */
227#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
228# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
229#endif
230
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200231#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200239#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100240/* Dynamic loading for portability */
241typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
242{
243 ULONG cbSize;
244 COORD dwSize;
245 COORD dwCursorPosition;
246 WORD wAttributes;
247 SMALL_RECT srWindow;
248 COORD dwMaximumWindowSize;
249 WORD wPopupAttributes;
250 BOOL bFullscreenSupported;
251 COLORREF ColorTable[16];
252} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
253typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
254static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
255typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
256static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
257static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100258#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100259
260/*
261 * Get version number including build number
262 */
263typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
264# define MAKE_VER(major, minor, build) \
265 (((major) << 24) | ((minor) << 16) | (build))
266
267 static DWORD
268get_build_number(void)
269{
270 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
271 HMODULE hNtdll;
272 PfnRtlGetVersion pRtlGetVersion;
273 DWORD ver = MAKE_VER(0, 0, 0);
274
275 hNtdll = GetModuleHandle("ntdll.dll");
276 if (hNtdll != NULL)
277 {
278 pRtlGetVersion =
279 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
280 pRtlGetVersion(&osver);
281 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
282 min(osver.dwMinorVersion, 255),
283 min(osver.dwBuildNumber, 32767));
284 }
285 return ver;
286}
287
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200288#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100289/*
290 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100291 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100292 */
293 static BOOL
294read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 HANDLE hInput,
296 INPUT_RECORD *lpBuffer,
297 DWORD nLength,
298 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299{
300 enum
301 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100302 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100303 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100304 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100305 static DWORD s_dwIndex = 0;
306 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100307 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100308 int head;
309 int tail;
310 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200312 if (nLength == -2)
313 return (s_dwMax > 0) ? TRUE : FALSE;
314
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100315 if (!win8_or_later)
316 {
317 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200318 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
319 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100320 }
321
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 if (s_dwMax == 0)
323 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100324 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200325 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
326 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100328 s_dwIndex = 0;
329 s_dwMax = dwEvents;
330 if (dwEvents == 0)
331 {
332 *lpEvents = 0;
333 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100335
336 if (s_dwMax > 1)
337 {
338 head = 0;
339 tail = s_dwMax - 1;
340 while (head != tail)
341 {
342 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
343 && s_irCache[head + 1].EventType
344 == WINDOW_BUFFER_SIZE_EVENT)
345 {
346 /* Remove duplicate event to avoid flicker. */
347 for (i = head; i < tail; ++i)
348 s_irCache[i] = s_irCache[i + 1];
349 --tail;
350 continue;
351 }
352 head++;
353 }
354 s_dwMax = tail + 1;
355 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100356 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100357
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100358 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200359 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100360 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100362 return TRUE;
363}
364
365/*
366 * Version of PeekConsoleInput() that works with IME.
367 */
368 static BOOL
369peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100370 HANDLE hInput,
371 INPUT_RECORD *lpBuffer,
372 DWORD nLength,
373 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100374{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100375 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100376}
377
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100378# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200379 static DWORD
380msg_wait_for_multiple_objects(
381 DWORD nCount,
382 LPHANDLE pHandles,
383 BOOL fWaitAll,
384 DWORD dwMilliseconds,
385 DWORD dwWakeMask)
386{
387 if (read_console_input(NULL, NULL, -2, NULL))
388 return WAIT_OBJECT_0;
389 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
390 dwMilliseconds, dwWakeMask);
391}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100392# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200393
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100394# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200395 static DWORD
396wait_for_single_object(
397 HANDLE hHandle,
398 DWORD dwMilliseconds)
399{
400 if (read_console_input(NULL, NULL, -2, NULL))
401 return WAIT_OBJECT_0;
402 return WaitForSingleObject(hHandle, dwMilliseconds);
403}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100404# endif
405#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200406
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 static void
408get_exe_name(void)
409{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
411 * as the maximum length that works (plus a NUL byte). */
412#define MAX_ENV_PATH_LEN 8192
413 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200414 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415
416 if (exe_name == NULL)
417 {
418 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100419 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 if (*temp != NUL)
421 exe_name = FullName_save((char_u *)temp, FALSE);
422 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000423
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000425 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200426 exe_path = vim_strnsave(exe_name,
427 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200428 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000429 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200430 /* Append our starting directory to $PATH, so that when doing
431 * "!xxd" it's found in our starting directory. Needed because
432 * SearchPath() also looks there. */
433 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100434 if (p == NULL
435 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200436 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100437 if (p == NULL || *p == NUL)
438 temp[0] = NUL;
439 else
440 {
441 STRCPY(temp, p);
442 STRCAT(temp, ";");
443 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200444 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100445 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449}
450
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200451/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100452 * Unescape characters in "p" that appear in "escaped".
453 */
454 static void
455unescape_shellxquote(char_u *p, char_u *escaped)
456{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100457 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100458 int n;
459
460 while (*p != NUL)
461 {
462 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
463 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100464 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100465 p += n;
466 l -= n;
467 }
468}
469
470/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200471 * Load library "name".
472 */
473 HINSTANCE
474vimLoadLib(char *name)
475{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200476 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200477
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200478 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
479 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 if (exe_path == NULL)
481 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200482 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200483 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200484 WCHAR old_dirw[MAXPATHL];
485
486 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
487 {
488 /* Change directory to where the executable is, both to make
489 * sure we find a .dll there and to avoid looking for a .dll
490 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100491 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200492 dll = LoadLibrary(name);
493 SetCurrentDirectoryW(old_dirw);
494 return dll;
495 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200496 }
497 return dll;
498}
499
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200500#if defined(VIMDLL) || defined(PROTO)
501/*
502 * Check if the current executable file is for the GUI subsystem.
503 */
504 int
505mch_is_gui_executable(void)
506{
507 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
508 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
509 PIMAGE_NT_HEADERS pPE;
510
511 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
512 return FALSE;
513 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
514 if (pPE->Signature != IMAGE_NT_SIGNATURE)
515 return FALSE;
516 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
517 return TRUE;
518 return FALSE;
519}
520#endif
521
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100522#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
523/*
524 * Get related information about 'funcname' which is imported by 'hInst'.
525 * If 'info' is 0, return the function address.
526 * If 'info' is 1, return the module name which the function is imported from.
527 */
528 static void *
529get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
530{
531 PBYTE pImage = (PBYTE)hInst;
532 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
533 PIMAGE_NT_HEADERS pPE;
534 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
535 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
536 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
537 PIMAGE_IMPORT_BY_NAME pImpName;
538
539 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
540 return NULL;
541 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
542 if (pPE->Signature != IMAGE_NT_SIGNATURE)
543 return NULL;
544 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
545 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
546 .VirtualAddress);
547 for (; pImpDesc->FirstThunk; ++pImpDesc)
548 {
549 if (!pImpDesc->OriginalFirstThunk)
550 continue;
551 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
552 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
553 for (; pIAT->u1.Function; ++pIAT, ++pINT)
554 {
555 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
556 continue;
557 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
558 + (UINT_PTR)(pINT->u1.AddressOfData));
559 if (strcmp((char *)pImpName->Name, funcname) == 0)
560 {
561 switch (info)
562 {
563 case 0:
564 return (void *)pIAT->u1.Function;
565 case 1:
566 return (void *)(pImage + pImpDesc->Name);
567 default:
568 return NULL;
569 }
570 }
571 }
572 }
573 return NULL;
574}
575
576/*
577 * Get the module handle which 'funcname' in 'hInst' is imported from.
578 */
579 HINSTANCE
580find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
581{
582 char *modulename;
583
584 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
585 if (modulename != NULL)
586 return GetModuleHandleA(modulename);
587 return NULL;
588}
589
590/*
591 * Get the address of 'funcname' which is imported by 'hInst' DLL.
592 */
593 void *
594get_dll_import_func(HINSTANCE hInst, const char *funcname)
595{
596 return get_imported_func_info(hInst, funcname, 0);
597}
598#endif
599
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
601# ifndef GETTEXT_DLL
602# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200603# define GETTEXT_DLL_ALT1 "libintl-8.dll"
604# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200606/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000607static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200608static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000609static char *null_libintl_textdomain(const char *);
610static char *null_libintl_bindtextdomain(const char *, const char *);
611static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100612static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200614static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000615char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200616char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
617 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000618char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
619char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000621char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
622 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100623int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
625 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100626dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627{
628 int i;
629 static struct
630 {
631 char *name;
632 FARPROC *ptr;
633 } libintl_entry[] =
634 {
635 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200636 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
638 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
639 {NULL, NULL}
640 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100641 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642
Bram Moolenaar7554c542018-10-06 15:03:15 +0200643 // No need to initialize twice.
644 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200646 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100647 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200648#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100649 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200650 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
651#endif
652#ifdef GETTEXT_DLL_ALT2
653 if (!hLibintlDLL)
654 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100655#endif
656 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200658 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200660 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100661 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200662 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200664 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 }
666 for (i = 0; libintl_entry[i].name != NULL
667 && libintl_entry[i].ptr != NULL; ++i)
668 {
669 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
670 libintl_entry[i].name)) == NULL)
671 {
672 dyn_libintl_end();
673 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000674 {
675 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100676 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000677 verbose_leave();
678 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 return 0;
680 }
681 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000682
683 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000684 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000685 "bind_textdomain_codeset");
686 if (dyn_libintl_bind_textdomain_codeset == NULL)
687 dyn_libintl_bind_textdomain_codeset =
688 null_libintl_bind_textdomain_codeset;
689
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200690 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
692 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100693 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100694 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
695 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100696
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 return 1;
698}
699
700 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100701dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702{
703 if (hLibintlDLL)
704 FreeLibrary(hLibintlDLL);
705 hLibintlDLL = NULL;
706 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200707 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 dyn_libintl_textdomain = null_libintl_textdomain;
709 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000710 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100711 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712}
713
714 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000715null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716{
717 return (char*)msgid;
718}
719
720 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721null_libintl_ngettext(
722 const char *msgid,
723 const char *msgid_plural,
724 unsigned long n)
725{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200726 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200727}
728
Bram Moolenaaree695f72016-08-03 22:08:45 +0200729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_bindtextdomain(
731 const char *domainname UNUSED,
732 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733{
734 return NULL;
735}
736
737 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100738null_libintl_bind_textdomain_codeset(
739 const char *domainname UNUSED,
740 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000741{
742 return NULL;
743}
744
745 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100746null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747{
748 return NULL;
749}
750
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200751 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100752null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100753{
754 return 0;
755}
756
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757#endif /* DYNAMIC_GETTEXT */
758
759/* This symbol is not defined in older versions of the SDK or Visual C++ */
760
761#ifndef VER_PLATFORM_WIN32_WINDOWS
762# define VER_PLATFORM_WIN32_WINDOWS 1
763#endif
764
765DWORD g_PlatformId;
766
767#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100768# ifndef PROTO
769# include <aclapi.h>
770# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200771# ifndef PROTECTED_DACL_SECURITY_INFORMATION
772# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
773# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774#endif
775
Bram Moolenaar27515922013-06-29 15:36:26 +0200776#ifdef HAVE_ACL
777/*
778 * Enables or disables the specified privilege.
779 */
780 static BOOL
781win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
782{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100783 BOOL bResult;
784 LUID luid;
785 HANDLE hToken;
786 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200787
788 if (!OpenProcessToken(GetCurrentProcess(),
789 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
790 return FALSE;
791
792 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
793 {
794 CloseHandle(hToken);
795 return FALSE;
796 }
797
Bram Moolenaar45500912014-07-09 20:51:07 +0200798 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200799 tokenPrivileges.Privileges[0].Luid = luid;
800 tokenPrivileges.Privileges[0].Attributes = bEnable ?
801 SE_PRIVILEGE_ENABLED : 0;
802
803 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
804 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
805
806 CloseHandle(hToken);
807
808 return bResult && GetLastError() == ERROR_SUCCESS;
809}
810#endif
811
Bram Moolenaar071d4272004-06-13 20:20:40 +0000812/*
813 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
814 * VER_PLATFORM_WIN32_WINDOWS (Win95).
815 */
816 void
817PlatformId(void)
818{
819 static int done = FALSE;
820
821 if (!done)
822 {
823 OSVERSIONINFO ovi;
824
825 ovi.dwOSVersionInfoSize = sizeof(ovi);
826 GetVersionEx(&ovi);
827
828 g_PlatformId = ovi.dwPlatformId;
829
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100830 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
831 || ovi.dwMajorVersion > 6)
832 win8_or_later = TRUE;
833
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200835 /* Enable privilege for getting or setting SACLs. */
836 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837#endif
838 done = TRUE;
839 }
840}
841
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200842#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843
844#define SHIFT (SHIFT_PRESSED)
845#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
846#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
847#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
848
849
850/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
851 * We map function keys to their ANSI terminal equivalents, as produced
852 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
853 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
854 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
855 * combinations of function/arrow/etc keys.
856 */
857
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000858static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859{
860 WORD wVirtKey;
861 BOOL fAnsiKey;
862 int chAlone;
863 int chShift;
864 int chCtrl;
865 int chAlt;
866} VirtKeyMap[] =
867{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200868// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
870
871 { VK_F1, TRUE, ';', 'T', '^', 'h', },
872 { VK_F2, TRUE, '<', 'U', '_', 'i', },
873 { VK_F3, TRUE, '=', 'V', '`', 'j', },
874 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
875 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
876 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
877 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
878 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
879 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
880 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200881 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
882 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200884 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
885 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
886 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
887 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
888 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
889 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
890 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
891 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
892 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
893 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100894 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200896 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200899 // Most people don't have F13-F20, but what the hell...
900 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
901 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
902 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
903 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
904 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
905 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
906 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
907 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200909 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
910 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
911 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
912 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200914 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
915 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
916 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
917 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
918 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
919 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
920 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
921 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
922 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
923 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100924 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925};
926
927
928#ifdef _MSC_VER
929// The ToAscii bug destroys several registers. Need to turn off optimization
930// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000931# pragma warning(push)
932# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933# pragma optimize("", off)
934#endif
935
936#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200937# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000938#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200939# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940#endif
941
942/* The return code indicates key code size. */
943 static int
944#ifdef __BORLANDC__
945 __stdcall
946#endif
947win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000948 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949{
950 UINT uMods = pker->dwControlKeyState;
951 static int s_iIsDead = 0;
952 static WORD awAnsiCode[2];
953 static BYTE abKeystate[256];
954
955
956 if (s_iIsDead == 2)
957 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200958 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 s_iIsDead = 0;
960 return 1;
961 }
962
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200963 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964 return 1;
965
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200966 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200969 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970
971 if (uMods & SHIFT_PRESSED)
972 abKeystate[VK_SHIFT] = 0x80;
973 if (uMods & CAPSLOCK_ON)
974 abKeystate[VK_CAPITAL] = 1;
975
976 if ((uMods & ALT_GR) == ALT_GR)
977 {
978 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
979 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
980 }
981
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200982 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
983 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984
985 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200986 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988 return s_iIsDead;
989}
990
991#ifdef _MSC_VER
992/* MUST switch optimization on again here, otherwise a call to
993 * decode_key_event() may crash (e.g. when hitting caps-lock) */
994# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000995# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996
997# if (_MSC_VER < 1100)
998/* MUST turn off global optimisation for this next function, or
999 * pressing ctrl-minus in insert mode crashes Vim when built with
1000 * VC4.1. -- negri. */
1001# pragma optimize("g", off)
1002# endif
1003#endif
1004
1005static BOOL g_fJustGotFocus = FALSE;
1006
1007/*
1008 * Decode a KEY_EVENT into one or two keystrokes
1009 */
1010 static BOOL
1011decode_key_event(
1012 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001013 WCHAR *pch,
1014 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015 int *pmodifiers,
1016 BOOL fDoPost)
1017{
1018 int i;
1019 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1020
1021 *pch = *pch2 = NUL;
1022 g_fJustGotFocus = FALSE;
1023
1024 /* ignore key up events */
1025 if (!pker->bKeyDown)
1026 return FALSE;
1027
1028 /* ignore some keystrokes */
1029 switch (pker->wVirtualKeyCode)
1030 {
1031 /* modifiers */
1032 case VK_SHIFT:
1033 case VK_CONTROL:
1034 case VK_MENU: /* Alt key */
1035 return FALSE;
1036
1037 default:
1038 break;
1039 }
1040
1041 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001042 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 {
1044 /* Ctrl-6 is Ctrl-^ */
1045 if (pker->wVirtualKeyCode == '6')
1046 {
1047 *pch = Ctrl_HAT;
1048 return TRUE;
1049 }
1050 /* Ctrl-2 is Ctrl-@ */
1051 else if (pker->wVirtualKeyCode == '2')
1052 {
1053 *pch = NUL;
1054 return TRUE;
1055 }
1056 /* Ctrl-- is Ctrl-_ */
1057 else if (pker->wVirtualKeyCode == 0xBD)
1058 {
1059 *pch = Ctrl__;
1060 return TRUE;
1061 }
1062 }
1063
1064 /* Shift-TAB */
1065 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1066 {
1067 *pch = K_NUL;
1068 *pch2 = '\017';
1069 return TRUE;
1070 }
1071
1072 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1073 {
1074 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1075 {
1076 if (nModifs == 0)
1077 *pch = VirtKeyMap[i].chAlone;
1078 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1079 *pch = VirtKeyMap[i].chShift;
1080 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1081 *pch = VirtKeyMap[i].chCtrl;
1082 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1083 *pch = VirtKeyMap[i].chAlt;
1084
1085 if (*pch != 0)
1086 {
1087 if (VirtKeyMap[i].fAnsiKey)
1088 {
1089 *pch2 = *pch;
1090 *pch = K_NUL;
1091 }
1092
1093 return TRUE;
1094 }
1095 }
1096 }
1097
1098 i = win32_kbd_patch_key(pker);
1099
1100 if (i < 0)
1101 *pch = NUL;
1102 else
1103 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001104 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105
1106 if (pmodifiers != NULL)
1107 {
1108 /* Pass on the ALT key as a modifier, but only when not combined
1109 * with CTRL (which is ALTGR). */
1110 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1111 *pmodifiers |= MOD_MASK_ALT;
1112
1113 /* Pass on SHIFT only for special keys, because we don't know when
1114 * it's already included with the character. */
1115 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1116 *pmodifiers |= MOD_MASK_SHIFT;
1117
1118 /* Pass on CTRL only for non-special keys, because we don't know
1119 * when it's already included with the character. And not when
1120 * combined with ALT (which is ALTGR). */
1121 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1122 && *pch >= 0x20 && *pch < 0x80)
1123 *pmodifiers |= MOD_MASK_CTRL;
1124 }
1125 }
1126
1127 return (*pch != NUL);
1128}
1129
1130#ifdef _MSC_VER
1131# pragma optimize("", on)
1132#endif
1133
Bram Moolenaar4f974752019-02-17 17:44:42 +01001134#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135
1136
1137#ifdef FEAT_MOUSE
1138
1139/*
1140 * For the GUI the mouse handling is in gui_w32.c.
1141 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001142# if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001144mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145{
1146}
1147# else
1148static int g_fMouseAvail = FALSE; /* mouse present */
1149static int g_fMouseActive = FALSE; /* mouse enabled */
1150static int g_nMouseClick = -1; /* mouse status */
1151static int g_xMouse; /* mouse x coordinate */
1152static int g_yMouse; /* mouse y coordinate */
1153
1154/*
1155 * Enable or disable mouse input
1156 */
1157 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001158mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001159{
1160 DWORD cmodein;
1161
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001162# ifdef VIMDLL
1163 if (gui.in_use)
1164 return;
1165# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166 if (!g_fMouseAvail)
1167 return;
1168
1169 g_fMouseActive = on;
1170 GetConsoleMode(g_hConIn, &cmodein);
1171
1172 if (g_fMouseActive)
1173 cmodein |= ENABLE_MOUSE_INPUT;
1174 else
1175 cmodein &= ~ENABLE_MOUSE_INPUT;
1176
1177 SetConsoleMode(g_hConIn, cmodein);
1178}
1179
Bram Moolenaar157d8132018-03-06 17:09:20 +01001180
1181#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1182/*
1183 * Called when 'balloonevalterm' changed.
1184 */
1185 void
1186mch_bevalterm_changed(void)
1187{
1188 mch_setmouse(g_fMouseActive);
1189}
1190#endif
1191
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192/*
1193 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1194 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1195 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1196 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1197 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1198 * and we return the mouse position in g_xMouse and g_yMouse.
1199 *
1200 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1201 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1202 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1203 *
1204 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1205 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1206 *
1207 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1208 * moves, even if it stays within the same character cell. We ignore
1209 * all MOUSE_MOVED messages if the position hasn't really changed, and
1210 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1211 * we're only interested in MOUSE_DRAG).
1212 *
1213 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1214 * 2-button mouses by pressing the left & right buttons simultaneously.
1215 * In practice, it's almost impossible to click both at the same time,
1216 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1217 * in such cases, if the user is clicking quickly.
1218 */
1219 static BOOL
1220decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001221 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222{
1223 static int s_nOldButton = -1;
1224 static int s_nOldMouseClick = -1;
1225 static int s_xOldMouse = -1;
1226 static int s_yOldMouse = -1;
1227 static linenr_T s_old_topline = 0;
1228#ifdef FEAT_DIFF
1229 static int s_old_topfill = 0;
1230#endif
1231 static int s_cClicks = 1;
1232 static BOOL s_fReleased = TRUE;
1233 static DWORD s_dwLastClickTime = 0;
1234 static BOOL s_fNextIsMiddle = FALSE;
1235
1236 static DWORD cButtons = 0; /* number of buttons supported */
1237
1238 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1239 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1240 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1241 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1242
1243 int nButton;
1244
1245 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1246 cButtons = 2;
1247
1248 if (!g_fMouseAvail || !g_fMouseActive)
1249 {
1250 g_nMouseClick = -1;
1251 return FALSE;
1252 }
1253
1254 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1255 if (g_fJustGotFocus)
1256 {
1257 g_fJustGotFocus = FALSE;
1258 return FALSE;
1259 }
1260
1261 /* unprocessed mouse click? */
1262 if (g_nMouseClick != -1)
1263 return TRUE;
1264
1265 nButton = -1;
1266 g_xMouse = pmer->dwMousePosition.X;
1267 g_yMouse = pmer->dwMousePosition.Y;
1268
1269 if (pmer->dwEventFlags == MOUSE_MOVED)
1270 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272 * events even when the mouse moves only within a char cell.) */
1273 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1274 return FALSE;
1275 }
1276
1277 /* If no buttons are pressed... */
1278 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1279 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001280 nButton = MOUSE_RELEASE;
1281
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1283 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001284 {
1285#ifdef FEAT_BEVAL_TERM
1286 /* do return mouse move events when we want them */
1287 if (p_bevalterm)
1288 nButton = MOUSE_DRAG;
1289 else
1290#endif
1291 return FALSE;
1292 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 s_fReleased = TRUE;
1295 }
1296 else /* one or more buttons pressed */
1297 {
1298 /* on a 2-button mouse, hold down left and right buttons
1299 * simultaneously to get MIDDLE. */
1300
1301 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1302 {
1303 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1304
1305 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001306 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307 if (dwLR == LEFT || dwLR == RIGHT)
1308 {
1309 for (;;)
1310 {
1311 /* wait a short time for next input event */
1312 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1313 != WAIT_OBJECT_0)
1314 break;
1315 else
1316 {
1317 DWORD cRecords = 0;
1318 INPUT_RECORD ir;
1319 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1320
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001321 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322
1323 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1324 || !(pmer2->dwButtonState & LEFT_RIGHT))
1325 break;
1326 else
1327 {
1328 if (pmer2->dwEventFlags != MOUSE_MOVED)
1329 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001330 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331
1332 return decode_mouse_event(pmer2);
1333 }
1334 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1335 s_yOldMouse == pmer2->dwMousePosition.Y)
1336 {
1337 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001338 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339
1340 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001341 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342
1343 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1344 break;
1345 }
1346 else
1347 break;
1348 }
1349 }
1350 }
1351 }
1352 }
1353
1354 if (s_fNextIsMiddle)
1355 {
1356 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1357 ? MOUSE_DRAG : MOUSE_MIDDLE;
1358 s_fNextIsMiddle = FALSE;
1359 }
1360 else if (cButtons == 2 &&
1361 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1362 {
1363 nButton = MOUSE_MIDDLE;
1364
1365 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1366 {
1367 s_fNextIsMiddle = TRUE;
1368 nButton = MOUSE_RELEASE;
1369 }
1370 }
1371 else if ((pmer->dwButtonState & LEFT) == LEFT)
1372 nButton = MOUSE_LEFT;
1373 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1374 nButton = MOUSE_MIDDLE;
1375 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1376 nButton = MOUSE_RIGHT;
1377
1378 if (! s_fReleased && ! s_fNextIsMiddle
1379 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1380 return FALSE;
1381
1382 s_fReleased = s_fNextIsMiddle;
1383 }
1384
1385 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1386 {
1387 /* button pressed or released, without mouse moving */
1388 if (nButton != -1 && nButton != MOUSE_RELEASE)
1389 {
1390 DWORD dwCurrentTime = GetTickCount();
1391
1392 if (s_xOldMouse != g_xMouse
1393 || s_yOldMouse != g_yMouse
1394 || s_nOldButton != nButton
1395 || s_old_topline != curwin->w_topline
1396#ifdef FEAT_DIFF
1397 || s_old_topfill != curwin->w_topfill
1398#endif
1399 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1400 {
1401 s_cClicks = 1;
1402 }
1403 else if (++s_cClicks > 4)
1404 {
1405 s_cClicks = 1;
1406 }
1407
1408 s_dwLastClickTime = dwCurrentTime;
1409 }
1410 }
1411 else if (pmer->dwEventFlags == MOUSE_MOVED)
1412 {
1413 if (nButton != -1 && nButton != MOUSE_RELEASE)
1414 nButton = MOUSE_DRAG;
1415
1416 s_cClicks = 1;
1417 }
1418
1419 if (nButton == -1)
1420 return FALSE;
1421
1422 if (nButton != MOUSE_RELEASE)
1423 s_nOldButton = nButton;
1424
1425 g_nMouseClick = nButton;
1426
1427 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1428 g_nMouseClick |= MOUSE_SHIFT;
1429 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1430 g_nMouseClick |= MOUSE_CTRL;
1431 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1432 g_nMouseClick |= MOUSE_ALT;
1433
1434 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1435 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1436
1437 /* only pass on interesting (i.e., different) mouse events */
1438 if (s_xOldMouse == g_xMouse
1439 && s_yOldMouse == g_yMouse
1440 && s_nOldMouseClick == g_nMouseClick)
1441 {
1442 g_nMouseClick = -1;
1443 return FALSE;
1444 }
1445
1446 s_xOldMouse = g_xMouse;
1447 s_yOldMouse = g_yMouse;
1448 s_old_topline = curwin->w_topline;
1449#ifdef FEAT_DIFF
1450 s_old_topfill = curwin->w_topfill;
1451#endif
1452 s_nOldMouseClick = g_nMouseClick;
1453
1454 return TRUE;
1455}
1456
Bram Moolenaar4f974752019-02-17 17:44:42 +01001457# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458#endif /* FEAT_MOUSE */
1459
1460
1461#ifdef MCH_CURSOR_SHAPE
1462/*
1463 * Set the shape of the cursor.
1464 * 'thickness' can be from 1 (thin) to 99 (block)
1465 */
1466 static void
1467mch_set_cursor_shape(int thickness)
1468{
1469 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1470 ConsoleCursorInfo.dwSize = thickness;
1471 ConsoleCursorInfo.bVisible = s_cursor_visible;
1472
1473 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1474 if (s_cursor_visible)
1475 SetConsoleCursorPosition(g_hConOut, g_coord);
1476}
1477
1478 void
1479mch_update_cursor(void)
1480{
1481 int idx;
1482 int thickness;
1483
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001484# ifdef VIMDLL
1485 if (gui.in_use)
1486 return;
1487# endif
1488
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 /*
1490 * How the cursor is drawn depends on the current mode.
1491 */
1492 idx = get_shape_idx(FALSE);
1493
1494 if (shape_table[idx].shape == SHAPE_BLOCK)
1495 thickness = 99; /* 100 doesn't work on W95 */
1496 else
1497 thickness = shape_table[idx].percentage;
1498 mch_set_cursor_shape(thickness);
1499}
1500#endif
1501
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001502#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503/*
1504 * Handle FOCUS_EVENT.
1505 */
1506 static void
1507handle_focus_event(INPUT_RECORD ir)
1508{
1509 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1510 ui_focus_change((int)g_fJustGotFocus);
1511}
1512
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001513static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1514
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515/*
1516 * Wait until console input from keyboard or mouse is available,
1517 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001518 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519 * Return TRUE if something is available FALSE if not.
1520 */
1521 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001522WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523{
1524 DWORD dwNow = 0, dwEndTime = 0;
1525 INPUT_RECORD ir;
1526 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001527 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001528#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001529 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001530#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531
1532 if (msec > 0)
1533 /* Wait until the specified time has elapsed. */
1534 dwEndTime = GetTickCount() + msec;
1535 else if (msec < 0)
1536 /* Wait forever. */
1537 dwEndTime = INFINITE;
1538
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001539 // We need to loop until the end of the time period, because
1540 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 for (;;)
1542 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001543 // Only process messages when waiting.
1544 if (msec != 0)
1545 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001546#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001547 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001548#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001549#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001550 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001551#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001553 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001555 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001556
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 if (0
1558#ifdef FEAT_MOUSE
1559 || g_nMouseClick != -1
1560#endif
1561#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001562 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563#endif
1564 )
1565 return TRUE;
1566
1567 if (msec > 0)
1568 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001569 /* If the specified wait time has passed, return. Beware that
1570 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001572 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 break;
1574 }
1575 if (msec != 0)
1576 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001577 DWORD dwWaitTime = dwEndTime - dwNow;
1578
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001579#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001580 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001581 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001582 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001583 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001584 /* If there is readahead then parse_queued_messages() timed out
1585 * and we should call it again soon. */
1586 if (channel_any_readahead())
1587 dwWaitTime = 10;
1588 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001589#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001590#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001591 if (p_beval && dwWaitTime > 100)
1592 /* The 'balloonexpr' may indirectly invoke a callback while
1593 * waiting for a character, need to check often. */
1594 dwWaitTime = 100;
1595#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001596#ifdef FEAT_MZSCHEME
1597 if (mzthreads_allowed() && p_mzq > 0
1598 && (msec < 0 || (long)dwWaitTime > p_mzq))
1599 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1600#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001601#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001602 // When waiting very briefly don't trigger timers.
1603 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001604 {
1605 long due_time;
1606
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001607 // Trigger timers and then get the time in msec until the next
1608 // one is due. Wait up to that time.
1609 due_time = check_due_timer();
1610 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001611 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001612 // timer may have used feedkeys().
1613 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001614 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001615 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1616 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001617 }
1618#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001619 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001621 // Wait for either an event on the console input or a
1622 // message in the client-server window.
1623 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1624 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001626 wait_for_single_object(g_hConIn, dwWaitTime)
1627 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001629 )
1630 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631 }
1632
1633 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001634 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635
1636#ifdef FEAT_MBYTE_IME
1637 if (State & CMDLINE && msg_row == Rows - 1)
1638 {
1639 CONSOLE_SCREEN_BUFFER_INFO csbi;
1640
1641 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1642 {
1643 if (csbi.dwCursorPosition.Y != msg_row)
1644 {
1645 /* The screen is now messed up, must redraw the
1646 * command line and later all the windows. */
1647 redraw_all_later(CLEAR);
1648 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1649 redrawcmd();
1650 }
1651 }
1652 }
1653#endif
1654
1655 if (cRecords > 0)
1656 {
1657 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1658 {
1659#ifdef FEAT_MBYTE_IME
1660 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1661 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001662 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1664 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001665 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 continue;
1667 }
1668#endif
1669 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1670 NULL, FALSE))
1671 return TRUE;
1672 }
1673
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001674 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675
1676 if (ir.EventType == FOCUS_EVENT)
1677 handle_focus_event(ir);
1678 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001679 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001680 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1681
1682 // Only call shell_resized() when the size actually change to
1683 // avoid the screen is cleard.
1684 if (dwSize.X != Columns || dwSize.Y != Rows)
1685 {
1686 CONSOLE_SCREEN_BUFFER_INFO csbi;
1687 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1688 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1689 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001690 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001691 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001692 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693#ifdef FEAT_MOUSE
1694 else if (ir.EventType == MOUSE_EVENT
1695 && decode_mouse_event(&ir.Event.MouseEvent))
1696 return TRUE;
1697#endif
1698 }
1699 else if (msec == 0)
1700 break;
1701 }
1702
1703#ifdef FEAT_CLIENTSERVER
1704 /* Something might have been received while we were waiting. */
1705 if (input_available())
1706 return TRUE;
1707#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001708
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 return FALSE;
1710}
1711
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712/*
1713 * return non-zero if a character is available
1714 */
1715 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001716mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001718# ifdef VIMDLL
1719 if (gui.in_use)
1720 return TRUE;
1721# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001722 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001724
1725# if defined(FEAT_TERMINAL) || defined(PROTO)
1726/*
1727 * Check for any pending input or messages.
1728 */
1729 int
1730mch_check_messages(void)
1731{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001732# ifdef VIMDLL
1733 if (gui.in_use)
1734 return TRUE;
1735# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001736 return WaitForChar(0L, TRUE);
1737}
1738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739
1740/*
1741 * Create the console input. Used when reading stdin doesn't work.
1742 */
1743 static void
1744create_conin(void)
1745{
1746 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1747 FILE_SHARE_READ|FILE_SHARE_WRITE,
1748 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001749 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750 did_create_conin = TRUE;
1751}
1752
1753/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001754 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001756 static WCHAR
1757tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001758{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001759 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760
1761 for (;;)
1762 {
1763 INPUT_RECORD ir;
1764 DWORD cRecords = 0;
1765
1766#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001767 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 if (input_available())
1769 return 0;
1770# ifdef FEAT_MOUSE
1771 if (g_nMouseClick != -1)
1772 return 0;
1773# endif
1774#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001775 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 {
1777 if (did_create_conin)
1778 read_error_exit();
1779 create_conin();
1780 continue;
1781 }
1782
1783 if (ir.EventType == KEY_EVENT)
1784 {
1785 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1786 pmodifiers, TRUE))
1787 return ch;
1788 }
1789 else if (ir.EventType == FOCUS_EVENT)
1790 handle_focus_event(ir);
1791 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1792 shell_resized();
1793#ifdef FEAT_MOUSE
1794 else if (ir.EventType == MOUSE_EVENT)
1795 {
1796 if (decode_mouse_event(&ir.Event.MouseEvent))
1797 return 0;
1798 }
1799#endif
1800 }
1801}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001802#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803
1804
1805/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001806 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 * Get one or more characters from the keyboard or the mouse.
1808 * If time == 0, do not wait for characters.
1809 * If time == n, wait a short time for characters.
1810 * If time == -1, wait forever for characters.
1811 * Returns the number of characters read into buf.
1812 */
1813 int
1814mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001815 char_u *buf UNUSED,
1816 int maxlen UNUSED,
1817 long time UNUSED,
1818 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001820#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821
1822 int len;
1823 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824#define TYPEAHEADLEN 20
1825 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1826 static int typeaheadlen = 0;
1827
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001828# ifdef VIMDLL
1829 if (gui.in_use)
1830 return 0;
1831# endif
1832
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 /* First use any typeahead that was kept because "buf" was too small. */
1834 if (typeaheadlen > 0)
1835 goto theend;
1836
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 if (time >= 0)
1838 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001839 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 }
1842 else /* time == -1, wait forever */
1843 {
1844 mch_set_winsize_now(); /* Allow winsize changes from now on */
1845
Bram Moolenaar3918c952005-03-15 22:34:55 +00001846 /*
1847 * If there is no character available within 2 seconds (default)
1848 * write the autoscript file to disk. Or cause the CursorHold event
1849 * to be triggered.
1850 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001851 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001853 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001855 buf[0] = K_SPECIAL;
1856 buf[1] = KS_EXTRA;
1857 buf[2] = (int)KE_CURSORHOLD;
1858 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001860 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 }
1862 }
1863
1864 /*
1865 * Try to read as many characters as there are, until the buffer is full.
1866 */
1867
1868 /* we will get at least one key. Get more if they are available. */
1869 g_fCBrkPressed = FALSE;
1870
1871#ifdef MCH_WRITE_DUMP
1872 if (fdDump)
1873 fputc('[', fdDump);
1874#endif
1875
1876 /* Keep looping until there is something in the typeahead buffer and more
1877 * to get and still room in the buffer (up to two bytes for a char and
1878 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001879 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880 && typeaheadlen + 5 <= TYPEAHEADLEN)
1881 {
1882 if (typebuf_changed(tb_change_cnt))
1883 {
1884 /* "buf" may be invalid now if a client put something in the
1885 * typeahead buffer and "buf" is in the typeahead buffer. */
1886 typeaheadlen = 0;
1887 break;
1888 }
1889#ifdef FEAT_MOUSE
1890 if (g_nMouseClick != -1)
1891 {
1892# ifdef MCH_WRITE_DUMP
1893 if (fdDump)
1894 fprintf(fdDump, "{%02x @ %d, %d}",
1895 g_nMouseClick, g_xMouse, g_yMouse);
1896# endif
1897 typeahead[typeaheadlen++] = ESC + 128;
1898 typeahead[typeaheadlen++] = 'M';
1899 typeahead[typeaheadlen++] = g_nMouseClick;
1900 typeahead[typeaheadlen++] = g_xMouse + '!';
1901 typeahead[typeaheadlen++] = g_yMouse + '!';
1902 g_nMouseClick = -1;
1903 }
1904 else
1905#endif
1906 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001907 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 int modifiers = 0;
1909
1910 c = tgetch(&modifiers, &ch2);
1911
1912 if (typebuf_changed(tb_change_cnt))
1913 {
1914 /* "buf" may be invalid now if a client put something in the
1915 * typeahead buffer and "buf" is in the typeahead buffer. */
1916 typeaheadlen = 0;
1917 break;
1918 }
1919
1920 if (c == Ctrl_C && ctrl_c_interrupts)
1921 {
1922#if defined(FEAT_CLIENTSERVER)
1923 trash_input_buf();
1924#endif
1925 got_int = TRUE;
1926 }
1927
1928#ifdef FEAT_MOUSE
1929 if (g_nMouseClick == -1)
1930#endif
1931 {
1932 int n = 1;
1933
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001934 if (ch2 == NUL)
1935 {
1936 int i;
1937 char_u *p;
1938 WCHAR ch[2];
1939
1940 ch[0] = c;
1941 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1942 {
1943 ch[1] = tgetch(&modifiers, &ch2);
1944 n++;
1945 }
1946 p = utf16_to_enc(ch, &n);
1947 if (p != NULL)
1948 {
1949 for (i = 0; i < n; i++)
1950 typeahead[typeaheadlen + i] = p[i];
1951 vim_free(p);
1952 }
1953 }
1954 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001955 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 if (ch2 != NUL)
1957 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001958 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001959 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001960 switch (ch2)
1961 {
1962 case (WCHAR)'\324': // SHIFT+Insert
1963 case (WCHAR)'\325': // CTRL+Insert
1964 case (WCHAR)'\327': // SHIFT+Delete
1965 case (WCHAR)'\330': // CTRL+Delete
1966 typeahead[typeaheadlen + n] = (char_u)ch2;
1967 n++;
1968 break;
1969
1970 default:
1971 typeahead[typeaheadlen + n] = 3;
1972 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1973 n += 2;
1974 break;
1975 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001976 }
1977 else
1978 {
1979 typeahead[typeaheadlen + n] = 3;
1980 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1981 n += 2;
1982 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001983 }
1984
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 /* Use the ALT key to set the 8th bit of the character
1986 * when it's one byte, the 8th bit isn't set yet and not
1987 * using a double-byte encoding (would become a lead
1988 * byte). */
1989 if ((modifiers & MOD_MASK_ALT)
1990 && n == 1
1991 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 )
1994 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001995 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1996 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 modifiers &= ~MOD_MASK_ALT;
1998 }
1999
2000 if (modifiers != 0)
2001 {
2002 /* Prepend modifiers to the character. */
2003 mch_memmove(typeahead + typeaheadlen + 3,
2004 typeahead + typeaheadlen, n);
2005 typeahead[typeaheadlen++] = K_SPECIAL;
2006 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2007 typeahead[typeaheadlen++] = modifiers;
2008 }
2009
2010 typeaheadlen += n;
2011
2012#ifdef MCH_WRITE_DUMP
2013 if (fdDump)
2014 fputc(c, fdDump);
2015#endif
2016 }
2017 }
2018 }
2019
2020#ifdef MCH_WRITE_DUMP
2021 if (fdDump)
2022 {
2023 fputs("]\n", fdDump);
2024 fflush(fdDump);
2025 }
2026#endif
2027
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028theend:
2029 /* Move typeahead to "buf", as much as fits. */
2030 len = 0;
2031 while (len < maxlen && typeaheadlen > 0)
2032 {
2033 buf[len++] = typeahead[0];
2034 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2035 }
2036 return len;
2037
Bram Moolenaar4f974752019-02-17 17:44:42 +01002038#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002040#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041}
2042
Bram Moolenaar82881492012-11-20 16:53:39 +01002043#ifndef PROTO
2044# ifndef __MINGW32__
2045# include <shellapi.h> /* required for FindExecutable() */
2046# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047#endif
2048
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002049/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002050 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2051 * If "use_path" is FALSE: Return TRUE if "name" exists.
2052 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2053 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002054 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002055 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002057executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002059 WCHAR *p;
2060 WCHAR fnamew[_MAX_PATH];
2061 WCHAR *dumw;
2062 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002063 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064
Bram Moolenaar43663192017-03-05 14:29:12 +01002065 if (!use_path)
2066 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002067 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002068 {
2069 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002070 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002071 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002072 *path = vim_strsave((char_u *)name);
2073 else
2074 *path = FullName_save((char_u *)name, FALSE);
2075 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002076 return TRUE;
2077 }
2078 return FALSE;
2079 }
2080
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002081 p = enc_to_utf16((char_u *)name, NULL);
2082 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002083 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002084
2085 wcurpath = _wgetenv(L"PATH");
2086 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2087 * sizeof(WCHAR));
2088 if (wnewpath == NULL)
2089 return FALSE;
2090 wcscpy(wnewpath, L".;");
2091 wcscat(wnewpath, wcurpath);
2092 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2093 vim_free(wnewpath);
2094 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002095 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002096 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002097 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002098 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002099 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002100 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002101 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102}
2103
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002104#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2105 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002106/*
2107 * Bad parameter handler.
2108 *
2109 * Certain MS CRT functions will intentionally crash when passed invalid
2110 * parameters to highlight possible security holes. Setting this function as
2111 * the bad parameter handler will prevent the crash.
2112 *
2113 * In debug builds the parameters contain CRT information that might help track
2114 * down the source of a problem, but in non-debug builds the arguments are all
2115 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2116 * worth allowing these to make debugging of issues easier.
2117 */
2118 static void
2119bad_param_handler(const wchar_t *expression,
2120 const wchar_t *function,
2121 const wchar_t *file,
2122 unsigned int line,
2123 uintptr_t pReserved)
2124{
2125}
2126
2127# define SET_INVALID_PARAM_HANDLER \
2128 ((void)_set_invalid_parameter_handler(bad_param_handler))
2129#else
2130# define SET_INVALID_PARAM_HANDLER
2131#endif
2132
Bram Moolenaar4f974752019-02-17 17:44:42 +01002133#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002134
2135/*
2136 * GUI version of mch_init().
2137 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002138 static void
2139mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140{
2141#ifndef __MINGW32__
2142 extern int _fmode;
2143#endif
2144
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002145 /* Silently handle invalid parameters to CRT functions */
2146 SET_INVALID_PARAM_HANDLER;
2147
Bram Moolenaar071d4272004-06-13 20:20:40 +00002148 /* Let critical errors result in a failure, not in a dialog box. Required
2149 * for the timestamp test to work on removed floppies. */
2150 SetErrorMode(SEM_FAILCRITICALERRORS);
2151
2152 _fmode = O_BINARY; /* we do our own CR-LF translation */
2153
2154 /* Specify window size. Is there a place to get the default from? */
2155 Rows = 25;
2156 Columns = 80;
2157
2158 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 {
2160 char_u vimrun_location[_MAX_PATH + 4];
2161
2162 /* First try in same directory as gvim.exe */
2163 STRCPY(vimrun_location, exe_name);
2164 STRCPY(gettail(vimrun_location), "vimrun.exe");
2165 if (mch_getperm(vimrun_location) >= 0)
2166 {
2167 if (*skiptowhite(vimrun_location) != NUL)
2168 {
2169 /* Enclose path with white space in double quotes. */
2170 mch_memmove(vimrun_location + 1, vimrun_location,
2171 STRLEN(vimrun_location) + 1);
2172 *vimrun_location = '"';
2173 STRCPY(gettail(vimrun_location), "vimrun\" ");
2174 }
2175 else
2176 STRCPY(gettail(vimrun_location), "vimrun ");
2177
2178 vimrun_path = (char *)vim_strsave(vimrun_location);
2179 s_dont_use_vimrun = FALSE;
2180 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002181 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 s_dont_use_vimrun = FALSE;
2183
2184 /* Don't give the warning for a missing vimrun.exe right now, but only
2185 * when vimrun was supposed to be used. Don't bother people that do
2186 * not need vimrun.exe. */
2187 if (s_dont_use_vimrun)
2188 need_vimrun_warning = TRUE;
2189 }
2190
2191 /*
2192 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2193 * Otherwise the default "findstr /n" is used.
2194 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002195 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2197
2198#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002199 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002201
2202 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203}
2204
2205
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002206#endif /* FEAT_GUI_MSWIN */
2207
2208#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209
2210#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2211#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2212
2213/*
2214 * ClearConsoleBuffer()
2215 * Description:
2216 * Clears the entire contents of the console screen buffer, using the
2217 * specified attribute.
2218 * Returns:
2219 * TRUE on success
2220 */
2221 static BOOL
2222ClearConsoleBuffer(WORD wAttribute)
2223{
2224 CONSOLE_SCREEN_BUFFER_INFO csbi;
2225 COORD coord;
2226 DWORD NumCells, dummy;
2227
2228 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2229 return FALSE;
2230
2231 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2232 coord.X = 0;
2233 coord.Y = 0;
2234 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2235 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2238 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240
2241 return TRUE;
2242}
2243
2244/*
2245 * FitConsoleWindow()
2246 * Description:
2247 * Checks if the console window will fit within given buffer dimensions.
2248 * Also, if requested, will shrink the window to fit.
2249 * Returns:
2250 * TRUE on success
2251 */
2252 static BOOL
2253FitConsoleWindow(
2254 COORD dwBufferSize,
2255 BOOL WantAdjust)
2256{
2257 CONSOLE_SCREEN_BUFFER_INFO csbi;
2258 COORD dwWindowSize;
2259 BOOL NeedAdjust = FALSE;
2260
2261 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2262 {
2263 /*
2264 * A buffer resize will fail if the current console window does
2265 * not lie completely within that buffer. To avoid this, we might
2266 * have to move and possibly shrink the window.
2267 */
2268 if (csbi.srWindow.Right >= dwBufferSize.X)
2269 {
2270 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2271 if (dwWindowSize.X > dwBufferSize.X)
2272 dwWindowSize.X = dwBufferSize.X;
2273 csbi.srWindow.Right = dwBufferSize.X - 1;
2274 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2275 NeedAdjust = TRUE;
2276 }
2277 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2278 {
2279 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2280 if (dwWindowSize.Y > dwBufferSize.Y)
2281 dwWindowSize.Y = dwBufferSize.Y;
2282 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2283 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2284 NeedAdjust = TRUE;
2285 }
2286 if (NeedAdjust && WantAdjust)
2287 {
2288 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2289 return FALSE;
2290 }
2291 return TRUE;
2292 }
2293
2294 return FALSE;
2295}
2296
2297typedef struct ConsoleBufferStruct
2298{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002299 BOOL IsValid;
2300 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002301 PCHAR_INFO Buffer;
2302 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002303 PSMALL_RECT Regions;
2304 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305} ConsoleBuffer;
2306
2307/*
2308 * SaveConsoleBuffer()
2309 * Description:
2310 * Saves important information about the console buffer, including the
2311 * actual buffer contents. The saved information is suitable for later
2312 * restoration by RestoreConsoleBuffer().
2313 * Returns:
2314 * TRUE if all information was saved; FALSE otherwise
2315 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2316 */
2317 static BOOL
2318SaveConsoleBuffer(
2319 ConsoleBuffer *cb)
2320{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002321 DWORD NumCells;
2322 COORD BufferCoord;
2323 SMALL_RECT ReadRegion;
2324 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002325 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002326
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 if (cb == NULL)
2328 return FALSE;
2329
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002330 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 {
2332 cb->IsValid = FALSE;
2333 return FALSE;
2334 }
2335 cb->IsValid = TRUE;
2336
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002337 /*
2338 * Allocate a buffer large enough to hold the entire console screen
2339 * buffer. If this ConsoleBuffer structure has already been initialized
2340 * with a buffer of the correct size, then just use that one.
2341 */
2342 if (!cb->IsValid || cb->Buffer == NULL ||
2343 cb->BufferSize.X != cb->Info.dwSize.X ||
2344 cb->BufferSize.Y != cb->Info.dwSize.Y)
2345 {
2346 cb->BufferSize.X = cb->Info.dwSize.X;
2347 cb->BufferSize.Y = cb->Info.dwSize.Y;
2348 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2349 vim_free(cb->Buffer);
2350 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2351 if (cb->Buffer == NULL)
2352 return FALSE;
2353 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354
2355 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002356 * We will now copy the console screen buffer into our buffer.
2357 * ReadConsoleOutput() seems to be limited as far as how much you
2358 * can read at a time. Empirically, this number seems to be about
2359 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2360 * in chunks until it is all copied. The chunks will all have the
2361 * same horizontal characteristics, so initialize them now. The
2362 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002364 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002365 ReadRegion.Left = 0;
2366 ReadRegion.Right = cb->Info.dwSize.X - 1;
2367 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002368
2369 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2370 if (cb->Regions == NULL || numregions != cb->NumRegions)
2371 {
2372 cb->NumRegions = numregions;
2373 vim_free(cb->Regions);
2374 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2375 if (cb->Regions == NULL)
2376 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002377 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002378 return FALSE;
2379 }
2380 }
2381
2382 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002384 /*
2385 * Read into position (0, Y) in our buffer.
2386 */
2387 BufferCoord.Y = Y;
2388 /*
2389 * Read the region whose top left corner is (0, Y) and whose bottom
2390 * right corner is (width - 1, Y + Y_incr - 1). This should define
2391 * a region of size width by Y_incr. Don't worry if this region is
2392 * too large for the remaining buffer; it will be cropped.
2393 */
2394 ReadRegion.Top = Y;
2395 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002396 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002397 cb->Buffer, /* our buffer */
2398 cb->BufferSize, /* dimensions of our buffer */
2399 BufferCoord, /* offset in our buffer */
2400 &ReadRegion)) /* region to save */
2401 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002402 VIM_CLEAR(cb->Buffer);
2403 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002404 return FALSE;
2405 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002406 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 }
2408
2409 return TRUE;
2410}
2411
2412/*
2413 * RestoreConsoleBuffer()
2414 * Description:
2415 * Restores important information about the console buffer, including the
2416 * actual buffer contents, if desired. The information to restore is in
2417 * the same format used by SaveConsoleBuffer().
2418 * Returns:
2419 * TRUE on success
2420 */
2421 static BOOL
2422RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002423 ConsoleBuffer *cb,
2424 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002426 COORD BufferCoord;
2427 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002428 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429
2430 if (cb == NULL || !cb->IsValid)
2431 return FALSE;
2432
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002433 /*
2434 * Before restoring the buffer contents, clear the current buffer, and
2435 * restore the cursor position and window information. Doing this now
2436 * prevents old buffer contents from "flashing" onto the screen.
2437 */
2438 if (RestoreScreen)
2439 ClearConsoleBuffer(cb->Info.wAttributes);
2440
2441 FitConsoleWindow(cb->Info.dwSize, TRUE);
2442 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2443 return FALSE;
2444 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2445 return FALSE;
2446
2447 if (!RestoreScreen)
2448 {
2449 /*
2450 * No need to restore the screen buffer contents, so we're done.
2451 */
2452 return TRUE;
2453 }
2454
2455 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2456 return FALSE;
2457 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2458 return FALSE;
2459
2460 /*
2461 * Restore the screen buffer contents.
2462 */
2463 if (cb->Buffer != NULL)
2464 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002465 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002466 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002467 BufferCoord.X = cb->Regions[i].Left;
2468 BufferCoord.Y = cb->Regions[i].Top;
2469 WriteRegion = cb->Regions[i];
2470 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2471 cb->Buffer, /* our buffer */
2472 cb->BufferSize, /* dimensions of our buffer */
2473 BufferCoord, /* offset in our buffer */
2474 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002475 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002476 }
2477 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478
2479 return TRUE;
2480}
2481
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002482#define FEAT_RESTORE_ORIG_SCREEN
2483#ifdef FEAT_RESTORE_ORIG_SCREEN
2484static ConsoleBuffer g_cbOrig = { 0 };
2485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486static ConsoleBuffer g_cbNonTermcap = { 0 };
2487static ConsoleBuffer g_cbTermcap = { 0 };
2488
2489#ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490char g_szOrigTitle[256] = { 0 };
2491HWND g_hWnd = NULL; /* also used in os_mswin.c */
2492static HICON g_hOrigIconSmall = NULL;
2493static HICON g_hOrigIcon = NULL;
2494static HICON g_hVimIcon = NULL;
2495static BOOL g_fCanChangeIcon = FALSE;
2496
2497/* ICON* are not defined in VC++ 4.0 */
2498#ifndef ICON_SMALL
2499#define ICON_SMALL 0
2500#endif
2501#ifndef ICON_BIG
2502#define ICON_BIG 1
2503#endif
2504/*
2505 * GetConsoleIcon()
2506 * Description:
2507 * Attempts to retrieve the small icon and/or the big icon currently in
2508 * use by a given window.
2509 * Returns:
2510 * TRUE on success
2511 */
2512 static BOOL
2513GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002514 HWND hWnd,
2515 HICON *phIconSmall,
2516 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517{
2518 if (hWnd == NULL)
2519 return FALSE;
2520
2521 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002522 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2523 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002525 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2526 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 return TRUE;
2528}
2529
2530/*
2531 * SetConsoleIcon()
2532 * Description:
2533 * Attempts to change the small icon and/or the big icon currently in
2534 * use by a given window.
2535 * Returns:
2536 * TRUE on success
2537 */
2538 static BOOL
2539SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002540 HWND hWnd,
2541 HICON hIconSmall,
2542 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 if (hWnd == NULL)
2545 return FALSE;
2546
2547 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002548 SendMessage(hWnd, WM_SETICON,
2549 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002551 SendMessage(hWnd, WM_SETICON,
2552 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 return TRUE;
2554}
2555
2556/*
2557 * SaveConsoleTitleAndIcon()
2558 * Description:
2559 * Saves the current console window title in g_szOrigTitle, for later
2560 * restoration. Also, attempts to obtain a handle to the console window,
2561 * and use it to save the small and big icons currently in use by the
2562 * console window. This is not always possible on some versions of Windows;
2563 * nor is it possible when running Vim remotely using Telnet (since the
2564 * console window the user sees is owned by a remote process).
2565 */
2566 static void
2567SaveConsoleTitleAndIcon(void)
2568{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569 /* Save the original title. */
2570 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2571 return;
2572
2573 /*
2574 * Obtain a handle to the console window using GetConsoleWindow() from
2575 * KERNEL32.DLL; we need to handle in order to change the window icon.
2576 * This function only exists on NT-based Windows, starting with Windows
2577 * 2000. On older operating systems, we can't change the window icon
2578 * anyway.
2579 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002580 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 if (g_hWnd == NULL)
2582 return;
2583
2584 /* Save the original console window icon. */
2585 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2586 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2587 return;
2588
2589 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002590 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002591 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 if (g_hVimIcon != NULL)
2593 g_fCanChangeIcon = TRUE;
2594}
2595#endif
2596
2597static int g_fWindInitCalled = FALSE;
2598static int g_fTermcapMode = FALSE;
2599static CONSOLE_CURSOR_INFO g_cci;
2600static DWORD g_cmodein = 0;
2601static DWORD g_cmodeout = 0;
2602
2603/*
2604 * non-GUI version of mch_init().
2605 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002606 static void
2607mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002609#ifndef FEAT_RESTORE_ORIG_SCREEN
2610 CONSOLE_SCREEN_BUFFER_INFO csbi;
2611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612#ifndef __MINGW32__
2613 extern int _fmode;
2614#endif
2615
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002616 /* Silently handle invalid parameters to CRT functions */
2617 SET_INVALID_PARAM_HANDLER;
2618
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 /* Let critical errors result in a failure, not in a dialog box. Required
2620 * for the timestamp test to work on removed floppies. */
2621 SetErrorMode(SEM_FAILCRITICALERRORS);
2622
2623 _fmode = O_BINARY; /* we do our own CR-LF translation */
2624 out_flush();
2625
2626 /* Obtain handles for the standard Console I/O devices */
2627 if (read_cmd_fd == 0)
2628 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2629 else
2630 create_conin();
2631 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2632
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002633#ifdef FEAT_RESTORE_ORIG_SCREEN
2634 /* Save the initial console buffer for later restoration */
2635 SaveConsoleBuffer(&g_cbOrig);
2636 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2637#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002639 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2640 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2641#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 if (cterm_normal_fg_color == 0)
2643 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2644 if (cterm_normal_bg_color == 0)
2645 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2646
Bram Moolenaarbdace832019-03-02 10:13:42 +01002647 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002648 g_color_index_fg = g_attrDefault & 0xf;
2649 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2650
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 /* set termcap codes to current text attributes */
2652 update_tcap(g_attrCurrent);
2653
2654 GetConsoleCursorInfo(g_hConOut, &g_cci);
2655 GetConsoleMode(g_hConIn, &g_cmodein);
2656 GetConsoleMode(g_hConOut, &g_cmodeout);
2657
2658#ifdef FEAT_TITLE
2659 SaveConsoleTitleAndIcon();
2660 /*
2661 * Set both the small and big icons of the console window to Vim's icon.
2662 * Note that Vim presently only has one size of icon (32x32), but it
2663 * automatically gets scaled down to 16x16 when setting the small icon.
2664 */
2665 if (g_fCanChangeIcon)
2666 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2667#endif
2668
2669 ui_get_shellsize();
2670
2671#ifdef MCH_WRITE_DUMP
2672 fdDump = fopen("dump", "wt");
2673
2674 if (fdDump)
2675 {
2676 time_t t;
2677
2678 time(&t);
2679 fputs(ctime(&t), fdDump);
2680 fflush(fdDump);
2681 }
2682#endif
2683
2684 g_fWindInitCalled = TRUE;
2685
2686#ifdef FEAT_MOUSE
2687 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2688#endif
2689
2690#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002691 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002693
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002694 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002695 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696}
2697
2698/*
2699 * non-GUI version of mch_exit().
2700 * Shut down and exit with status `r'
2701 * Careful: mch_exit() may be called before mch_init()!
2702 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002703 static void
2704mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002706 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002708 vtp_exit();
2709
Bram Moolenaar955f1982017-02-05 15:10:51 +01002710 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 if (g_fWindInitCalled)
2712 settmode(TMODE_COOK);
2713
2714 ml_close_all(TRUE); /* remove all memfiles */
2715
2716 if (g_fWindInitCalled)
2717 {
2718#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002719 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 /*
2721 * Restore both the small and big icons of the console window to
2722 * what they were at startup. Don't do this when the window is
2723 * closed, Vim would hang here.
2724 */
2725 if (g_fCanChangeIcon && !g_fForceExit)
2726 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2727#endif
2728
2729#ifdef MCH_WRITE_DUMP
2730 if (fdDump)
2731 {
2732 time_t t;
2733
2734 time(&t);
2735 fputs(ctime(&t), fdDump);
2736 fclose(fdDump);
2737 }
2738 fdDump = NULL;
2739#endif
2740 }
2741
2742 SetConsoleCursorInfo(g_hConOut, &g_cci);
2743 SetConsoleMode(g_hConIn, g_cmodein);
2744 SetConsoleMode(g_hConOut, g_cmodeout);
2745
2746#ifdef DYNAMIC_GETTEXT
2747 dyn_libintl_end();
2748#endif
2749
2750 exit(r);
2751}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002752#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002754 void
2755mch_init(void)
2756{
2757#ifdef VIMDLL
2758 if (gui.starting)
2759 mch_init_g();
2760 else
2761 mch_init_c();
2762#elif defined(FEAT_GUI_MSWIN)
2763 mch_init_g();
2764#else
2765 mch_init_c();
2766#endif
2767}
2768
2769 void
2770mch_exit(int r)
2771{
2772#ifdef VIMDLL
2773 if (gui.starting || gui.in_use)
2774 mch_exit_g(r);
2775 else
2776 mch_exit_c(r);
2777#elif defined(FEAT_GUI_MSWIN)
2778 mch_exit_g(r);
2779#else
2780 mch_exit_c(r);
2781#endif
2782}
2783
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784/*
2785 * Do we have an interactive window?
2786 */
2787 int
2788mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002789 int argc UNUSED,
2790 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791{
2792 get_exe_name();
2793
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002794#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 return OK; /* GUI always has a tty */
2796#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002797# ifdef VIMDLL
2798 if (gui.in_use)
2799 return OK;
2800# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 if (isatty(1))
2802 return OK;
2803 return FAIL;
2804#endif
2805}
2806
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002807/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002808 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 * When "len" is > 0, also expand short to long filenames.
2810 */
2811 void
2812fname_case(
2813 char_u *name,
2814 int len)
2815{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002816 int flen;
2817 WCHAR *p;
2818 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002820 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002821 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 return;
2823
2824 slash_adjust(name);
2825
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002826 p = enc_to_utf16(name, NULL);
2827 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002828 return;
2829
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002830 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002832 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002834 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002836 if (len > 0 || flen >= (int)STRLEN(q))
2837 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2838 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839 }
2840 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002841 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842}
2843
2844
2845/*
2846 * Insert user name in s[len].
2847 */
2848 int
2849mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002850 char_u *s,
2851 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002853 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2854 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002856 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002857 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002858 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002859
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002860 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002861 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002862 vim_strncpy(s, p, len - 1);
2863 vim_free(p);
2864 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002865 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002866 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 s[0] = NUL;
2868 return FAIL;
2869}
2870
2871
2872/*
2873 * Insert host name in s[len].
2874 */
2875 void
2876mch_get_host_name(
2877 char_u *s,
2878 int len)
2879{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002880 WCHAR wszHostName[256 + 1];
2881 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002883 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002884 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002885 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002886
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002887 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002888 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002889 vim_strncpy(s, p, len - 1);
2890 vim_free(p);
2891 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002892 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894}
2895
2896
2897/*
2898 * return process ID
2899 */
2900 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002901mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902{
2903 return (long)GetCurrentProcessId();
2904}
2905
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002906/*
2907 * return TRUE if process "pid" is still running
2908 */
2909 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002910mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002911{
2912 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
2913 DWORD status = 0;
2914 int ret = FALSE;
2915
2916 if (hProcess == NULL)
2917 return FALSE; // might not have access
2918 if (GetExitCodeProcess(hProcess, &status) )
2919 ret = status == STILL_ACTIVE;
2920 CloseHandle(hProcess);
2921 return ret;
2922}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924/*
2925 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2926 * Return OK for success, FAIL for failure.
2927 */
2928 int
2929mch_dirname(
2930 char_u *buf,
2931 int len)
2932{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002933 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002934
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 /*
2936 * Originally this was:
2937 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2938 * But the Win32s known bug list says that getcwd() doesn't work
2939 * so use the Win32 system call instead. <Negri>
2940 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002941 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002943 WCHAR wcbuf[_MAX_PATH + 1];
2944 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002946 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002948 p = utf16_to_enc(wcbuf, NULL);
2949 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002950 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002951 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002953 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 }
2955 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002956 if (p == NULL)
2957 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002958
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002959 if (p != NULL)
2960 {
2961 vim_strncpy(buf, p, len - 1);
2962 vim_free(p);
2963 return OK;
2964 }
2965 }
2966 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967}
2968
2969/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002970 * Get file permissions for "name".
2971 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 */
2973 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002974mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002976 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002977 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002979 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002980 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981}
2982
2983
2984/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002985 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002986 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002987 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 */
2989 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002990mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002992 long n;
2993 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002994
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002995 p = enc_to_utf16(name, NULL);
2996 if (p == NULL)
2997 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002999 n = _wchmod(p, perm);
3000 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003001 if (n == -1)
3002 return FAIL;
3003
3004 win32_set_archive(name);
3005
3006 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007}
3008
3009/*
3010 * Set hidden flag for "name".
3011 */
3012 void
3013mch_hide(char_u *name)
3014{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003015 int attrs = win32_getattrs(name);
3016 if (attrs == -1)
3017 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003019 attrs |= FILE_ATTRIBUTE_HIDDEN;
3020 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021}
3022
3023/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003024 * Return TRUE if file "name" exists and is hidden.
3025 */
3026 int
3027mch_ishidden(char_u *name)
3028{
3029 int f = win32_getattrs(name);
3030
3031 if (f == -1)
3032 return FALSE; /* file does not exist at all */
3033
3034 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3035}
3036
3037/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 * return TRUE if "name" is a directory
3039 * return FALSE if "name" is not a directory or upon error
3040 */
3041 int
3042mch_isdir(char_u *name)
3043{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003044 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045
3046 if (f == -1)
3047 return FALSE; /* file does not exist at all */
3048
3049 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3050}
3051
3052/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003053 * return TRUE if "name" is a directory, NOT a symlink to a directory
3054 * return FALSE if "name" is not a directory
3055 * return FALSE for error
3056 */
3057 int
3058mch_isrealdir(char_u *name)
3059{
3060 return mch_isdir(name) && !mch_is_symbolic_link(name);
3061}
3062
3063/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003064 * Create directory "name".
3065 * Return 0 on success, -1 on error.
3066 */
3067 int
3068mch_mkdir(char_u *name)
3069{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003070 WCHAR *p;
3071 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003072
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003073 p = enc_to_utf16(name, NULL);
3074 if (p == NULL)
3075 return -1;
3076 retval = _wmkdir(p);
3077 vim_free(p);
3078 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003079}
3080
3081/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003082 * Delete directory "name".
3083 * Return 0 on success, -1 on error.
3084 */
3085 int
3086mch_rmdir(char_u *name)
3087{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003088 WCHAR *p;
3089 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003090
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003091 p = enc_to_utf16(name, NULL);
3092 if (p == NULL)
3093 return -1;
3094 retval = _wrmdir(p);
3095 vim_free(p);
3096 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003097}
3098
3099/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003100 * Return TRUE if file "fname" has more than one link.
3101 */
3102 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003104{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003105 BY_HANDLE_FILE_INFORMATION info;
3106
3107 return win32_fileinfo(fname, &info) == FILEINFO_OK
3108 && info.nNumberOfLinks > 1;
3109}
3110
3111/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003112 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 */
3114 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003115mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003116{
3117 HANDLE hFind;
3118 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003119 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003120 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 WIN32_FIND_DATAW findDataW;
3122
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003123 wn = enc_to_utf16(name, NULL);
3124 if (wn == NULL)
3125 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003126
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003127 hFind = FindFirstFileW(wn, &findDataW);
3128 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003129 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003130 {
3131 fileFlags = findDataW.dwFileAttributes;
3132 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003133 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003134 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003135
3136 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003137 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3138 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003139 res = TRUE;
3140
3141 return res;
3142}
3143
3144/*
3145 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3146 * link.
3147 */
3148 int
3149mch_is_linked(char_u *fname)
3150{
3151 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3152 return TRUE;
3153 return FALSE;
3154}
3155
3156/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003157 * Get the by-handle-file-information for "fname".
3158 * Returns FILEINFO_OK when OK.
3159 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3160 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3161 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3162 */
3163 int
3164win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3165{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003166 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003167 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003168 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003169
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003170 wn = enc_to_utf16(fname, NULL);
3171 if (wn == NULL)
3172 return FILEINFO_ENC_FAIL;
3173
3174 hFile = CreateFileW(wn, // file name
3175 GENERIC_READ, // access mode
3176 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3177 NULL, // security descriptor
3178 OPEN_EXISTING, // creation disposition
3179 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3180 NULL); // handle to template file
3181 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003182
3183 if (hFile != INVALID_HANDLE_VALUE)
3184 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003185 if (GetFileInformationByHandle(hFile, info) != 0)
3186 res = FILEINFO_OK;
3187 else
3188 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003189 CloseHandle(hFile);
3190 }
3191
Bram Moolenaar03f48552006-02-28 23:52:23 +00003192 return res;
3193}
3194
3195/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196 * get file attributes for `name'
3197 * -1 : error
3198 * else FILE_ATTRIBUTE_* defined in winnt.h
3199 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003200 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201win32_getattrs(char_u *name)
3202{
3203 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003204 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003206 p = enc_to_utf16(name, NULL);
3207 if (p == NULL)
3208 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003210 attr = GetFileAttributesW(p);
3211 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003212
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003213 return attr;
3214}
3215
3216/*
3217 * set file attributes for `name' to `attrs'
3218 *
3219 * return -1 for failure, 0 otherwise
3220 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003221 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222win32_setattrs(char_u *name, int attrs)
3223{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003224 int res;
3225 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003227 p = enc_to_utf16(name, NULL);
3228 if (p == NULL)
3229 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003231 res = SetFileAttributesW(p, attrs);
3232 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003233
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003234 return res ? 0 : -1;
3235}
3236
3237/*
3238 * Set archive flag for "name".
3239 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003240 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241win32_set_archive(char_u *name)
3242{
3243 int attrs = win32_getattrs(name);
3244 if (attrs == -1)
3245 return -1;
3246
3247 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3248 return win32_setattrs(name, attrs);
3249}
3250
3251/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 * Return TRUE if file or directory "name" is writable (not readonly).
3253 * Strange semantics of Win32: a readonly directory is writable, but you can't
3254 * delete a file. Let's say this means it is writable.
3255 */
3256 int
3257mch_writable(char_u *name)
3258{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003259 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003261 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3262 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263}
3264
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003266 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003267 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003268 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3269 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003270 */
3271 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003272mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273{
Bram Moolenaar86621892019-03-30 21:51:28 +01003274 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3275 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3276 // UTF-8.
3277 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003278 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003279 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003280
Bram Moolenaar86621892019-03-30 21:51:28 +01003281 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003282 return FALSE;
3283
Bram Moolenaar86621892019-03-30 21:51:28 +01003284 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003285 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003286 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003287 return TRUE;
3288
3289 /*
3290 * Loop over all extensions in $PATHEXT.
3291 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003292 p = mch_getenv("PATHEXT");
3293 if (p == NULL)
3294 p = (char_u *)".com;.exe;.bat;.cmd";
3295 saved = vim_strsave(p);
3296 if (saved == NULL)
3297 return FALSE;
3298 p = saved;
3299 while (*p)
3300 {
3301 char_u *tmp = vim_strchr(p, ';');
3302
3303 if (tmp != NULL)
3304 *tmp = NUL;
3305 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3306 && executable_exists((char *)name, path, use_path))
3307 {
3308 vim_free(saved);
3309 return TRUE;
3310 }
3311 if (tmp == NULL)
3312 break;
3313 p = tmp + 1;
3314 }
3315 vim_free(saved);
3316
Bram Moolenaar86621892019-03-30 21:51:28 +01003317 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003318 p = mch_getenv("PATHEXT");
3319 if (p == NULL)
3320 p = (char_u *)".com;.exe;.bat;.cmd";
3321 while (*p)
3322 {
3323 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3324 {
3325 /* A single "." means no extension is added. */
3326 buf[len] = NUL;
3327 ++p;
3328 if (*p)
3329 ++p;
3330 }
3331 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003332 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003333 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003334 return TRUE;
3335 }
3336 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338
3339/*
3340 * Check what "name" is:
3341 * NODE_NORMAL: file or directory (or doesn't exist)
3342 * NODE_WRITABLE: writable device, socket, fifo, etc.
3343 * NODE_OTHER: non-writable things
3344 */
3345 int
3346mch_nodetype(char_u *name)
3347{
3348 HANDLE hFile;
3349 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003350 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351
Bram Moolenaar043545e2006-10-10 16:44:07 +00003352 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3353 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3354 * here. */
3355 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3356 return NODE_WRITABLE;
3357
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003358 wn = enc_to_utf16(name, NULL);
3359 if (wn == NULL)
3360 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003361
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003362 hFile = CreateFileW(wn, // file name
3363 GENERIC_WRITE, // access mode
3364 0, // share mode
3365 NULL, // security descriptor
3366 OPEN_EXISTING, // creation disposition
3367 0, // file attributes
3368 NULL); // handle to template file
3369 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370 if (hFile == INVALID_HANDLE_VALUE)
3371 return NODE_NORMAL;
3372
3373 type = GetFileType(hFile);
3374 CloseHandle(hFile);
3375 if (type == FILE_TYPE_CHAR)
3376 return NODE_WRITABLE;
3377 if (type == FILE_TYPE_DISK)
3378 return NODE_NORMAL;
3379 return NODE_OTHER;
3380}
3381
3382#ifdef HAVE_ACL
3383struct my_acl
3384{
3385 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3386 PSID pSidOwner;
3387 PSID pSidGroup;
3388 PACL pDacl;
3389 PACL pSacl;
3390};
3391#endif
3392
3393/*
3394 * Return a pointer to the ACL of file "fname" in allocated memory.
3395 * Return NULL if the ACL is not available for whatever reason.
3396 */
3397 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003398mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399{
3400#ifndef HAVE_ACL
3401 return (vim_acl_T)NULL;
3402#else
3403 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003404 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003405
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003406 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3407 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003409 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003410
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003411 wn = enc_to_utf16(fname, NULL);
3412 if (wn == NULL)
3413 return NULL;
3414
3415 // Try to retrieve the entire security descriptor.
3416 err = GetNamedSecurityInfoW(
3417 wn, // Abstract filename
3418 SE_FILE_OBJECT, // File Object
3419 OWNER_SECURITY_INFORMATION |
3420 GROUP_SECURITY_INFORMATION |
3421 DACL_SECURITY_INFORMATION |
3422 SACL_SECURITY_INFORMATION,
3423 &p->pSidOwner, // Ownership information.
3424 &p->pSidGroup, // Group membership.
3425 &p->pDacl, // Discretionary information.
3426 &p->pSacl, // For auditing purposes.
3427 &p->pSecurityDescriptor);
3428 if (err == ERROR_ACCESS_DENIED ||
3429 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003430 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003431 // Retrieve only DACL.
3432 (void)GetNamedSecurityInfoW(
3433 wn,
3434 SE_FILE_OBJECT,
3435 DACL_SECURITY_INFORMATION,
3436 NULL,
3437 NULL,
3438 &p->pDacl,
3439 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003440 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003441 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003442 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003443 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003444 mch_free_acl((vim_acl_T)p);
3445 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003447 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448 }
3449
3450 return (vim_acl_T)p;
3451#endif
3452}
3453
Bram Moolenaar27515922013-06-29 15:36:26 +02003454#ifdef HAVE_ACL
3455/*
3456 * Check if "acl" contains inherited ACE.
3457 */
3458 static BOOL
3459is_acl_inherited(PACL acl)
3460{
3461 DWORD i;
3462 ACL_SIZE_INFORMATION acl_info;
3463 PACCESS_ALLOWED_ACE ace;
3464
3465 acl_info.AceCount = 0;
3466 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3467 for (i = 0; i < acl_info.AceCount; i++)
3468 {
3469 GetAce(acl, i, (LPVOID *)&ace);
3470 if (ace->Header.AceFlags & INHERITED_ACE)
3471 return TRUE;
3472 }
3473 return FALSE;
3474}
3475#endif
3476
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477/*
3478 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3479 * Errors are ignored.
3480 * This must only be called with "acl" equal to what mch_get_acl() returned.
3481 */
3482 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003483mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484{
3485#ifdef HAVE_ACL
3486 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003487 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003488 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003490 if (p == NULL)
3491 return;
3492
3493 wn = enc_to_utf16(fname, NULL);
3494 if (wn == NULL)
3495 return;
3496
3497 // Set security flags
3498 if (p->pSidOwner)
3499 sec_info |= OWNER_SECURITY_INFORMATION;
3500 if (p->pSidGroup)
3501 sec_info |= GROUP_SECURITY_INFORMATION;
3502 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003503 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003504 sec_info |= DACL_SECURITY_INFORMATION;
3505 // Do not inherit its parent's DACL.
3506 // If the DACL is inherited, Cygwin permissions would be changed.
3507 if (!is_acl_inherited(p->pDacl))
3508 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003509 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003510 if (p->pSacl)
3511 sec_info |= SACL_SECURITY_INFORMATION;
3512
3513 (void)SetNamedSecurityInfoW(
3514 wn, // Abstract filename
3515 SE_FILE_OBJECT, // File Object
3516 sec_info,
3517 p->pSidOwner, // Ownership information.
3518 p->pSidGroup, // Group membership.
3519 p->pDacl, // Discretionary information.
3520 p->pSacl // For auditing purposes.
3521 );
3522 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523#endif
3524}
3525
3526 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003527mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528{
3529#ifdef HAVE_ACL
3530 struct my_acl *p = (struct my_acl *)acl;
3531
3532 if (p != NULL)
3533 {
3534 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3535 vim_free(p);
3536 }
3537#endif
3538}
3539
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003540#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541
3542/*
3543 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3544 */
3545 static BOOL WINAPI
3546handler_routine(
3547 DWORD dwCtrlType)
3548{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003549 INPUT_RECORD ir;
3550 DWORD out;
3551
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 switch (dwCtrlType)
3553 {
3554 case CTRL_C_EVENT:
3555 if (ctrl_c_interrupts)
3556 g_fCtrlCPressed = TRUE;
3557 return TRUE;
3558
3559 case CTRL_BREAK_EVENT:
3560 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003561 ctrl_break_was_pressed = TRUE;
3562 /* ReadConsoleInput is blocking, send a key event to continue. */
3563 ir.EventType = KEY_EVENT;
3564 ir.Event.KeyEvent.bKeyDown = TRUE;
3565 ir.Event.KeyEvent.wRepeatCount = 1;
3566 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3567 ir.Event.KeyEvent.wVirtualScanCode = 0;
3568 ir.Event.KeyEvent.dwControlKeyState = 0;
3569 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3570 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571 return TRUE;
3572
3573 /* fatal events: shut down gracefully */
3574 case CTRL_CLOSE_EVENT:
3575 case CTRL_LOGOFF_EVENT:
3576 case CTRL_SHUTDOWN_EVENT:
3577 windgoto((int)Rows - 1, 0);
3578 g_fForceExit = TRUE;
3579
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003580 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 (dwCtrlType == CTRL_CLOSE_EVENT
3582 ? _("close")
3583 : dwCtrlType == CTRL_LOGOFF_EVENT
3584 ? _("logoff")
3585 : _("shutdown")));
3586#ifdef DEBUG
3587 OutputDebugString(IObuff);
3588#endif
3589
3590 preserve_exit(); /* output IObuff, preserve files and exit */
3591
3592 return TRUE; /* not reached */
3593
3594 default:
3595 return FALSE;
3596 }
3597}
3598
3599
3600/*
3601 * set the tty in (raw) ? "raw" : "cooked" mode
3602 */
3603 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003604mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605{
3606 DWORD cmodein;
3607 DWORD cmodeout;
3608 BOOL bEnableHandler;
3609
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003610# ifdef VIMDLL
3611 if (gui.in_use)
3612 return;
3613# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 GetConsoleMode(g_hConIn, &cmodein);
3615 GetConsoleMode(g_hConOut, &cmodeout);
3616 if (tmode == TMODE_RAW)
3617 {
3618 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3619 ENABLE_ECHO_INPUT);
3620#ifdef FEAT_MOUSE
3621 if (g_fMouseActive)
3622 cmodein |= ENABLE_MOUSE_INPUT;
3623#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003624 cmodeout &= ~(
3625#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003626 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003627 * VTP. */
3628 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3629#else
3630 ENABLE_PROCESSED_OUTPUT |
3631#endif
3632 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 bEnableHandler = TRUE;
3634 }
3635 else /* cooked */
3636 {
3637 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3638 ENABLE_ECHO_INPUT);
3639 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3640 bEnableHandler = FALSE;
3641 }
3642 SetConsoleMode(g_hConIn, cmodein);
3643 SetConsoleMode(g_hConOut, cmodeout);
3644 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3645
3646#ifdef MCH_WRITE_DUMP
3647 if (fdDump)
3648 {
3649 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3650 tmode == TMODE_RAW ? "raw" :
3651 tmode == TMODE_COOK ? "cooked" : "normal",
3652 cmodein, cmodeout);
3653 fflush(fdDump);
3654 }
3655#endif
3656}
3657
3658
3659/*
3660 * Get the size of the current window in `Rows' and `Columns'
3661 * Return OK when size could be determined, FAIL otherwise.
3662 */
3663 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003664mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665{
3666 CONSOLE_SCREEN_BUFFER_INFO csbi;
3667
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003668# ifdef VIMDLL
3669 if (gui.in_use)
3670 return OK;
3671# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003672 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3673 {
3674 /*
3675 * For some reason, we are trying to get the screen dimensions
3676 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3677 * variables are really intended to mean the size of Vim screen
3678 * while in termcap mode.
3679 */
3680 Rows = g_cbTermcap.Info.dwSize.Y;
3681 Columns = g_cbTermcap.Info.dwSize.X;
3682 }
3683 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3684 {
3685 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3686 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3687 }
3688 else
3689 {
3690 Rows = 25;
3691 Columns = 80;
3692 }
3693 return OK;
3694}
3695
3696/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003697 * Resize console buffer to 'COORD'
3698 */
3699 static void
3700ResizeConBuf(
3701 HANDLE hConsole,
3702 COORD coordScreen)
3703{
3704 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3705 {
3706#ifdef MCH_WRITE_DUMP
3707 if (fdDump)
3708 {
3709 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3710 GetLastError());
3711 fflush(fdDump);
3712 }
3713#endif
3714 }
3715}
3716
3717/*
3718 * Resize console window size to 'srWindowRect'
3719 */
3720 static void
3721ResizeWindow(
3722 HANDLE hConsole,
3723 SMALL_RECT srWindowRect)
3724{
3725 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3726 {
3727#ifdef MCH_WRITE_DUMP
3728 if (fdDump)
3729 {
3730 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3731 GetLastError());
3732 fflush(fdDump);
3733 }
3734#endif
3735 }
3736}
3737
3738/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 * Set a console window to `xSize' * `ySize'
3740 */
3741 static void
3742ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003743 HANDLE hConsole,
3744 int xSize,
3745 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746{
3747 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3748 SMALL_RECT srWindowRect; /* hold the new console size */
3749 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003750 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751
3752#ifdef MCH_WRITE_DUMP
3753 if (fdDump)
3754 {
3755 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3756 fflush(fdDump);
3757 }
3758#endif
3759
3760 /* get the largest size we can size the console window to */
3761 coordScreen = GetLargestConsoleWindowSize(hConsole);
3762
3763 /* define the new console window size and scroll position */
3764 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3765 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3766 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3767
3768 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3769 {
3770 int sx, sy;
3771
3772 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3773 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3774 if (sy < ySize || sx < xSize)
3775 {
3776 /*
3777 * Increasing number of lines/columns, do buffer first.
3778 * Use the maximal size in x and y direction.
3779 */
3780 if (sy < ySize)
3781 coordScreen.Y = ySize;
3782 else
3783 coordScreen.Y = sy;
3784 if (sx < xSize)
3785 coordScreen.X = xSize;
3786 else
3787 coordScreen.X = sx;
3788 SetConsoleScreenBufferSize(hConsole, coordScreen);
3789 }
3790 }
3791
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003792 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 coordScreen.X = xSize;
3794 coordScreen.Y = ySize;
3795
Bram Moolenaar2551c032018-08-23 22:38:31 +02003796 // In the new console call API, only the first time in reverse order
3797 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003799 ResizeWindow(hConsole, srWindowRect);
3800 ResizeConBuf(hConsole, coordScreen);
3801 }
3802 else
3803 {
3804 ResizeConBuf(hConsole, coordScreen);
3805 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003806 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 }
3808}
3809
3810
3811/*
3812 * Set the console window to `Rows' * `Columns'
3813 */
3814 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003815mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816{
3817 COORD coordScreen;
3818
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003819# ifdef VIMDLL
3820 if (gui.in_use)
3821 return;
3822# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 /* Don't change window size while still starting up */
3824 if (suppress_winsize != 0)
3825 {
3826 suppress_winsize = 2;
3827 return;
3828 }
3829
3830 if (term_console)
3831 {
3832 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3833
3834 /* Clamp Rows and Columns to reasonable values */
3835 if (Rows > coordScreen.Y)
3836 Rows = coordScreen.Y;
3837 if (Columns > coordScreen.X)
3838 Columns = coordScreen.X;
3839
3840 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3841 }
3842}
3843
3844/*
3845 * Rows and/or Columns has changed.
3846 */
3847 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003848mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003850# ifdef VIMDLL
3851 if (gui.in_use)
3852 return;
3853# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3855}
3856
3857
3858/*
3859 * Called when started up, to set the winsize that was delayed.
3860 */
3861 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003862mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863{
3864 if (suppress_winsize == 2)
3865 {
3866 suppress_winsize = 0;
3867 mch_set_shellsize();
3868 shell_resized();
3869 }
3870 suppress_winsize = 0;
3871}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003872#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003874 static BOOL
3875vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003876 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003877 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003878 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003879 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003880 PROCESS_INFORMATION *pi,
3881 LPVOID *env,
3882 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003883{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003884 BOOL ret = FALSE;
3885 WCHAR *wcmd, *wcwd = NULL;
3886
3887 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3888 if (wcmd == NULL)
3889 return FALSE;
3890 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003891 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003892 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3893 if (wcwd == NULL)
3894 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003895 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003896
3897 ret = CreateProcessW(
3898 NULL, // Executable name
3899 wcmd, // Command to execute
3900 NULL, // Process security attributes
3901 NULL, // Thread security attributes
3902 inherit_handles, // Inherit handles
3903 flags, // Creation flags
3904 env, // Environment
3905 wcwd, // Current directory
3906 (LPSTARTUPINFOW)si, // Startup information
3907 pi); // Process information
3908theend:
3909 vim_free(wcmd);
3910 vim_free(wcwd);
3911 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003912}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913
3914
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003915 static HINSTANCE
3916vim_shell_execute(
3917 char *cmd,
3918 INT n_show_cmd)
3919{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003920 HINSTANCE ret;
3921 WCHAR *wcmd;
3922
3923 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3924 if (wcmd == NULL)
3925 return (HINSTANCE) 0;
3926
3927 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3928 vim_free(wcmd);
3929 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003930}
3931
3932
Bram Moolenaar4f974752019-02-17 17:44:42 +01003933#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934
3935/*
3936 * Specialised version of system() for Win32 GUI mode.
3937 * This version proceeds as follows:
3938 * 1. Create a console window for use by the subprocess
3939 * 2. Run the subprocess (it gets the allocated console by default)
3940 * 3. Wait for the subprocess to terminate and get its exit code
3941 * 4. Prompt the user to press a key to close the console window
3942 */
3943 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003944mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945{
3946 STARTUPINFO si;
3947 PROCESS_INFORMATION pi;
3948 DWORD ret = 0;
3949 HWND hwnd = GetFocus();
3950
3951 si.cb = sizeof(si);
3952 si.lpReserved = NULL;
3953 si.lpDesktop = NULL;
3954 si.lpTitle = NULL;
3955 si.dwFlags = STARTF_USESHOWWINDOW;
3956 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003957 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003958 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003960 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003961 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 else
3963 si.wShowWindow = SW_SHOWNORMAL;
3964 si.cbReserved2 = 0;
3965 si.lpReserved2 = NULL;
3966
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003968 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003969 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3970 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971
3972 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 {
3974#ifdef FEAT_GUI
3975 int delay = 1;
3976
3977 /* Keep updating the window while waiting for the shell to finish. */
3978 for (;;)
3979 {
3980 MSG msg;
3981
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003982 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983 {
3984 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003985 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003986 delay = 1;
3987 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 }
3989 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3990 break;
3991
3992 /* We start waiting for a very short time and then increase it, so
3993 * that we respond quickly when the process is quick, and don't
3994 * consume too much overhead when it's slow. */
3995 if (delay < 50)
3996 delay += 10;
3997 }
3998#else
3999 WaitForSingleObject(pi.hProcess, INFINITE);
4000#endif
4001
4002 /* Get the command exit code */
4003 GetExitCodeProcess(pi.hProcess, &ret);
4004 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005
4006 /* Close the handles to the subprocess, so that it goes away */
4007 CloseHandle(pi.hThread);
4008 CloseHandle(pi.hProcess);
4009
4010 /* Try to get input focus back. Doesn't always work though. */
4011 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4012
4013 return ret;
4014}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004015
4016/*
4017 * Thread launched by the gui to send the current buffer data to the
4018 * process. This way avoid to hang up vim totally if the children
4019 * process take a long time to process the lines.
4020 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004021 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004022sub_process_writer(LPVOID param)
4023{
4024 HANDLE g_hChildStd_IN_Wr = param;
4025 linenr_T lnum = curbuf->b_op_start.lnum;
4026 DWORD len = 0;
4027 DWORD l;
4028 char_u *lp = ml_get(lnum);
4029 char_u *s;
4030 int written = 0;
4031
4032 for (;;)
4033 {
4034 l = (DWORD)STRLEN(lp + written);
4035 if (l == 0)
4036 len = 0;
4037 else if (lp[written] == NL)
4038 {
4039 /* NL -> NUL translation */
4040 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4041 }
4042 else
4043 {
4044 s = vim_strchr(lp + written, NL);
4045 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4046 s == NULL ? l : (DWORD)(s - (lp + written)),
4047 &len, NULL);
4048 }
4049 if (len == (int)l)
4050 {
4051 /* Finished a line, add a NL, unless this line should not have
4052 * one. */
4053 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004054 || (!curbuf->b_p_bin
4055 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004056 || (lnum != curbuf->b_no_eol_lnum
4057 && (lnum != curbuf->b_ml.ml_line_count
4058 || curbuf->b_p_eol)))
4059 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004060 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4061 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004062 }
4063
4064 ++lnum;
4065 if (lnum > curbuf->b_op_end.lnum)
4066 break;
4067
4068 lp = ml_get(lnum);
4069 written = 0;
4070 }
4071 else if (len > 0)
4072 written += len;
4073 }
4074
4075 /* finished all the lines, close pipe */
4076 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004077 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004078}
4079
4080
4081# define BUFLEN 100 /* length for buffer, stolen from unix version */
4082
4083/*
4084 * This function read from the children's stdout and write the
4085 * data on screen or in the buffer accordingly.
4086 */
4087 static void
4088dump_pipe(int options,
4089 HANDLE g_hChildStd_OUT_Rd,
4090 garray_T *ga,
4091 char_u buffer[],
4092 DWORD *buffer_off)
4093{
4094 DWORD availableBytes = 0;
4095 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004096 int ret;
4097 DWORD len;
4098 DWORD toRead;
4099 int repeatCount;
4100
4101 /* we query the pipe to see if there is any data to read
4102 * to avoid to perform a blocking read */
4103 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4104 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004105 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004106 NULL, /* number of read bytes */
4107 &availableBytes, /* available bytes total */
4108 NULL); /* byteLeft */
4109
4110 repeatCount = 0;
4111 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004112 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004113 {
4114 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004115 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004116 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004117 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004118
4119 /* If we haven't read anything, there is a problem */
4120 if (len == 0)
4121 break;
4122
4123 availableBytes -= len;
4124
4125 if (options & SHELL_READ)
4126 {
4127 /* Do NUL -> NL translation, append NL separated
4128 * lines to the current buffer. */
4129 for (i = 0; i < len; ++i)
4130 {
4131 if (buffer[i] == NL)
4132 append_ga_line(ga);
4133 else if (buffer[i] == NUL)
4134 ga_append(ga, NL);
4135 else
4136 ga_append(ga, buffer[i]);
4137 }
4138 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004139 else if (has_mbyte)
4140 {
4141 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004142 int c;
4143 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004144
4145 len += *buffer_off;
4146 buffer[len] = NUL;
4147
4148 /* Check if the last character in buffer[] is
4149 * incomplete, keep these bytes for the next
4150 * round. */
4151 for (p = buffer; p < buffer + len; p += l)
4152 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004153 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004154 if (l == 0)
4155 l = 1; /* NUL byte? */
4156 else if (MB_BYTE2LEN(*p) != l)
4157 break;
4158 }
4159 if (p == buffer) /* no complete character */
4160 {
4161 /* avoid getting stuck at an illegal byte */
4162 if (len >= 12)
4163 ++p;
4164 else
4165 {
4166 *buffer_off = len;
4167 return;
4168 }
4169 }
4170 c = *p;
4171 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004172 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004173 if (p < buffer + len)
4174 {
4175 *p = c;
4176 *buffer_off = (DWORD)((buffer + len) - p);
4177 mch_memmove(buffer, p, *buffer_off);
4178 return;
4179 }
4180 *buffer_off = 0;
4181 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004182 else
4183 {
4184 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004185 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004186 }
4187
4188 windgoto(msg_row, msg_col);
4189 cursor_on();
4190 out_flush();
4191 }
4192}
4193
4194/*
4195 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4196 * for communication and doesn't open any new window.
4197 */
4198 static int
4199mch_system_piped(char *cmd, int options)
4200{
4201 STARTUPINFO si;
4202 PROCESS_INFORMATION pi;
4203 DWORD ret = 0;
4204
4205 HANDLE g_hChildStd_IN_Rd = NULL;
4206 HANDLE g_hChildStd_IN_Wr = NULL;
4207 HANDLE g_hChildStd_OUT_Rd = NULL;
4208 HANDLE g_hChildStd_OUT_Wr = NULL;
4209
4210 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4211 DWORD len;
4212
4213 /* buffer used to receive keys */
4214 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4215 int ta_len = 0; /* valid bytes in ta_buf[] */
4216
4217 DWORD i;
4218 int c;
4219 int noread_cnt = 0;
4220 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004221 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004223 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004224
4225 SECURITY_ATTRIBUTES saAttr;
4226
4227 /* Set the bInheritHandle flag so pipe handles are inherited. */
4228 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4229 saAttr.bInheritHandle = TRUE;
4230 saAttr.lpSecurityDescriptor = NULL;
4231
4232 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4233 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004234 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235 /* Create a pipe for the child process's STDIN. */
4236 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4237 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004238 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239 {
4240 CloseHandle(g_hChildStd_IN_Rd);
4241 CloseHandle(g_hChildStd_IN_Wr);
4242 CloseHandle(g_hChildStd_OUT_Rd);
4243 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004244 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004245 }
4246
4247 si.cb = sizeof(si);
4248 si.lpReserved = NULL;
4249 si.lpDesktop = NULL;
4250 si.lpTitle = NULL;
4251 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4252
4253 /* set-up our file redirection */
4254 si.hStdError = g_hChildStd_OUT_Wr;
4255 si.hStdOutput = g_hChildStd_OUT_Wr;
4256 si.hStdInput = g_hChildStd_IN_Rd;
4257 si.wShowWindow = SW_HIDE;
4258 si.cbReserved2 = 0;
4259 si.lpReserved2 = NULL;
4260
4261 if (options & SHELL_READ)
4262 ga_init2(&ga, 1, BUFLEN);
4263
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004264 if (cmd != NULL)
4265 {
4266 p = (char *)vim_strsave((char_u *)cmd);
4267 if (p != NULL)
4268 unescape_shellxquote((char_u *)p, p_sxe);
4269 else
4270 p = cmd;
4271 }
4272
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004273 /* Now, run the command.
4274 * About "Inherit handles" being TRUE: this command can be litigious,
4275 * handle inheritance was deactivated for pending temp file, but, if we
4276 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004277 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4278 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004279
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004280 if (p != cmd)
4281 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004282
4283 /* Close our unused side of the pipes */
4284 CloseHandle(g_hChildStd_IN_Rd);
4285 CloseHandle(g_hChildStd_OUT_Wr);
4286
4287 if (options & SHELL_WRITE)
4288 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004289 HANDLE thread = (HANDLE)
4290 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004291 0, /* default stack size */
4292 sub_process_writer, /* function to be executed */
4293 g_hChildStd_IN_Wr, /* parameter */
4294 0, /* creation flag, start immediately */
4295 NULL); /* we don't care about thread id */
4296 CloseHandle(thread);
4297 g_hChildStd_IN_Wr = NULL;
4298 }
4299
4300 /* Keep updating the window while waiting for the shell to finish. */
4301 for (;;)
4302 {
4303 MSG msg;
4304
Bram Moolenaar175d0702013-12-11 18:36:33 +01004305 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 {
4307 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004308 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004309 }
4310
4311 /* write pipe information in the window */
4312 if ((options & (SHELL_READ|SHELL_WRITE))
4313# ifdef FEAT_GUI
4314 || gui.in_use
4315# endif
4316 )
4317 {
4318 len = 0;
4319 if (!(options & SHELL_EXPAND)
4320 && ((options &
4321 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4322 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4323# ifdef FEAT_GUI
4324 || gui.in_use
4325# endif
4326 )
4327 && (ta_len > 0 || noread_cnt > 4))
4328 {
4329 if (ta_len == 0)
4330 {
4331 /* Get extra characters when we don't have any. Reset the
4332 * counter and timer. */
4333 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004334 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4335 }
4336 if (ta_len > 0 || len > 0)
4337 {
4338 /*
4339 * For pipes: Check for CTRL-C: send interrupt signal to
4340 * child. Check for CTRL-D: EOF, close pipe to child.
4341 */
4342 if (len == 1 && cmd != NULL)
4343 {
4344 if (ta_buf[ta_len] == Ctrl_C)
4345 {
4346 /* Learn what exit code is expected, for
4347 * now put 9 as SIGKILL */
4348 TerminateProcess(pi.hProcess, 9);
4349 }
4350 if (ta_buf[ta_len] == Ctrl_D)
4351 {
4352 CloseHandle(g_hChildStd_IN_Wr);
4353 g_hChildStd_IN_Wr = NULL;
4354 }
4355 }
4356
4357 /* replace K_BS by <BS> and K_DEL by <DEL> */
4358 for (i = ta_len; i < ta_len + len; ++i)
4359 {
4360 if (ta_buf[i] == CSI && len - i > 2)
4361 {
4362 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4363 if (c == K_DEL || c == K_KDEL || c == K_BS)
4364 {
4365 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4366 (size_t)(len - i - 2));
4367 if (c == K_DEL || c == K_KDEL)
4368 ta_buf[i] = DEL;
4369 else
4370 ta_buf[i] = Ctrl_H;
4371 len -= 2;
4372 }
4373 }
4374 else if (ta_buf[i] == '\r')
4375 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004376 if (has_mbyte)
4377 i += (*mb_ptr2len_len)(ta_buf + i,
4378 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379 }
4380
4381 /*
4382 * For pipes: echo the typed characters. For a pty this
4383 * does not seem to work.
4384 */
4385 for (i = ta_len; i < ta_len + len; ++i)
4386 {
4387 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4388 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004389 else if (has_mbyte)
4390 {
4391 int l = (*mb_ptr2len)(ta_buf + i);
4392
4393 msg_outtrans_len(ta_buf + i, l);
4394 i += l - 1;
4395 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 else
4397 msg_outtrans_len(ta_buf + i, 1);
4398 }
4399 windgoto(msg_row, msg_col);
4400 out_flush();
4401
4402 ta_len += len;
4403
4404 /*
4405 * Write the characters to the child, unless EOF has been
4406 * typed for pipes. Write one character at a time, to
4407 * avoid losing too much typeahead. When writing buffer
4408 * lines, drop the typed characters (only check for
4409 * CTRL-C).
4410 */
4411 if (options & SHELL_WRITE)
4412 ta_len = 0;
4413 else if (g_hChildStd_IN_Wr != NULL)
4414 {
4415 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4416 1, &len, NULL);
4417 // if we are typing in, we want to keep things reactive
4418 delay = 1;
4419 if (len > 0)
4420 {
4421 ta_len -= len;
4422 mch_memmove(ta_buf, ta_buf + len, ta_len);
4423 }
4424 }
4425 }
4426 }
4427 }
4428
4429 if (ta_len)
4430 ui_inchar_undo(ta_buf, ta_len);
4431
4432 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4433 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004434 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004435 break;
4436 }
4437
4438 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004439 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004440
4441 /* We start waiting for a very short time and then increase it, so
4442 * that we respond quickly when the process is quick, and don't
4443 * consume too much overhead when it's slow. */
4444 if (delay < 50)
4445 delay += 10;
4446 }
4447
4448 /* Close the pipe */
4449 CloseHandle(g_hChildStd_OUT_Rd);
4450 if (g_hChildStd_IN_Wr != NULL)
4451 CloseHandle(g_hChildStd_IN_Wr);
4452
4453 WaitForSingleObject(pi.hProcess, INFINITE);
4454
4455 /* Get the command exit code */
4456 GetExitCodeProcess(pi.hProcess, &ret);
4457
4458 if (options & SHELL_READ)
4459 {
4460 if (ga.ga_len > 0)
4461 {
4462 append_ga_line(&ga);
4463 /* remember that the NL was missing */
4464 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4465 }
4466 else
4467 curbuf->b_no_eol_lnum = 0;
4468 ga_clear(&ga);
4469 }
4470
4471 /* Close the handles to the subprocess, so that it goes away */
4472 CloseHandle(pi.hThread);
4473 CloseHandle(pi.hProcess);
4474
4475 return ret;
4476}
4477
4478 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004479mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480{
4481 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004482 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483 return mch_system_piped(cmd, options);
4484 else
4485 return mch_system_classic(cmd, options);
4486}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004489#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004490 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004491mch_system_c(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004492{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004493 int ret;
4494 WCHAR *wcmd;
4495
4496 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4497 if (wcmd == NULL)
4498 return -1;
4499
4500 ret = _wsystem(wcmd);
4501 vim_free(wcmd);
4502 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004503}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504
4505#endif
4506
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004507 static int
4508mch_system(char *cmd, int options)
4509{
4510#ifdef VIMDLL
4511 if (gui.in_use)
4512 return mch_system_g(cmd, options);
4513 else
4514 return mch_system_c(cmd, options);
4515#elif defined(FEAT_GUI_MSWIN)
4516 return mch_system_g(cmd, options);
4517#else
4518 return mch_system_c(cmd, options);
4519#endif
4520}
4521
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004522#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4523/*
4524 * Use a terminal window to run a shell command in.
4525 */
4526 static int
4527mch_call_shell_terminal(
4528 char_u *cmd,
4529 int options UNUSED) /* SHELL_*, see vim.h */
4530{
4531 jobopt_T opt;
4532 char_u *newcmd = NULL;
4533 typval_T argvar[2];
4534 long_u cmdlen;
4535 int retval = -1;
4536 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004537 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004538 aco_save_T aco;
4539 oparg_T oa; /* operator arguments */
4540
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004541 if (cmd == NULL)
4542 cmdlen = STRLEN(p_sh) + 1;
4543 else
4544 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004545 newcmd = lalloc(cmdlen, TRUE);
4546 if (newcmd == NULL)
4547 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004548 if (cmd == NULL)
4549 {
4550 STRCPY(newcmd, p_sh);
4551 ch_log(NULL, "starting terminal to run a shell");
4552 }
4553 else
4554 {
4555 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4556 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4557 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004558
4559 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004560
4561 argvar[0].v_type = VAR_STRING;
4562 argvar[0].vval.v_string = newcmd;
4563 argvar[1].v_type = VAR_UNKNOWN;
4564 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004565 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004566 {
4567 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004568 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004569 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004570
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004571 job = term_getjob(buf->b_term);
4572 ++job->jv_refcount;
4573
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004574 /* Find a window to make "buf" curbuf. */
4575 aucmd_prepbuf(&aco, buf);
4576
4577 clear_oparg(&oa);
4578 while (term_use_loop())
4579 {
4580 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4581 {
4582 /* If terminal_loop() returns OK we got a key that is handled
4583 * in Normal model. We don't do redrawing anyway. */
4584 if (terminal_loop(TRUE) == OK)
4585 normal_cmd(&oa, TRUE);
4586 }
4587 else
4588 normal_cmd(&oa, TRUE);
4589 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004590 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004591 ch_log(NULL, "system command finished");
4592
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004593 job_unref(job);
4594
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004595 /* restore curwin/curbuf and a few other things */
4596 aucmd_restbuf(&aco);
4597
4598 wait_return(TRUE);
4599 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4600
4601 vim_free(newcmd);
4602 return retval;
4603}
4604#endif
4605
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606/*
4607 * Either execute a command by calling the shell or start a new shell
4608 */
4609 int
4610mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004611 char_u *cmd,
4612 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004613{
4614 int x = 0;
4615 int tmode = cur_tmode;
4616#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004617 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004618
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004619 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004620 if (GetConsoleTitleW(szShellTitle,
4621 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004622 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004623 if (cmd == NULL)
4624 wcscat(szShellTitle, L" :sh");
4625 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004626 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004627 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004628
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004629 if (wn != NULL)
4630 {
4631 wcscat(szShellTitle, L" - !");
4632 if ((wcslen(szShellTitle) + wcslen(wn) <
4633 sizeof(szShellTitle)/sizeof(WCHAR)))
4634 wcscat(szShellTitle, wn);
4635 SetConsoleTitleW(szShellTitle);
4636 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004637 }
4638 }
4639 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640#endif
4641
4642 out_flush();
4643
4644#ifdef MCH_WRITE_DUMP
4645 if (fdDump)
4646 {
4647 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4648 fflush(fdDump);
4649 }
4650#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004651#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4652 /* TODO: make the terminal window work with input or output redirected. */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004653 if (
4654# ifdef VIMDLL
4655 gui.in_use &&
4656# endif
4657 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004658 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4659 {
4660 /* Use a terminal window to run the command in. */
4661 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004662# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004663 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004664# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004665 return x;
4666 }
4667#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668
4669 /*
4670 * Catch all deadly signals while running the external command, because a
4671 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4672 */
4673 signal(SIGINT, SIG_IGN);
4674#if defined(__GNUC__) && !defined(__MINGW32__)
4675 signal(SIGKILL, SIG_IGN);
4676#else
4677 signal(SIGBREAK, SIG_IGN);
4678#endif
4679 signal(SIGILL, SIG_IGN);
4680 signal(SIGFPE, SIG_IGN);
4681 signal(SIGSEGV, SIG_IGN);
4682 signal(SIGTERM, SIG_IGN);
4683 signal(SIGABRT, SIG_IGN);
4684
4685 if (options & SHELL_COOKED)
4686 settmode(TMODE_COOK); /* set to normal mode */
4687
4688 if (cmd == NULL)
4689 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004690 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 }
4692 else
4693 {
4694 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004695 char_u *newcmd = NULL;
4696 char_u *cmdbase = cmd;
4697 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004698
4699 /* Skip a leading ", ( and "(. */
4700 if (*cmdbase == '"' )
4701 ++cmdbase;
4702 if (*cmdbase == '(')
4703 ++cmdbase;
4704
Bram Moolenaar1c465442017-03-12 20:10:05 +01004705 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004706 {
4707 STARTUPINFO si;
4708 PROCESS_INFORMATION pi;
4709 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004710 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004711 char_u *p;
4712
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004713 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004714 si.cb = sizeof(si);
4715 si.lpReserved = NULL;
4716 si.lpDesktop = NULL;
4717 si.lpTitle = NULL;
4718 si.dwFlags = 0;
4719 si.cbReserved2 = 0;
4720 si.lpReserved2 = NULL;
4721
4722 cmdbase = skipwhite(cmdbase + 5);
4723 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004724 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004725 {
4726 cmdbase = skipwhite(cmdbase + 4);
4727 si.dwFlags = STARTF_USESHOWWINDOW;
4728 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004729 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004730 }
4731 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004732 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004733 {
4734 cmdbase = skipwhite(cmdbase + 2);
4735 flags = CREATE_NO_WINDOW;
4736 si.dwFlags = STARTF_USESTDHANDLES;
4737 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004738 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004739 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004740 NULL, // Security att.
4741 OPEN_EXISTING, // Open flags
4742 FILE_ATTRIBUTE_NORMAL, // File att.
4743 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004744 si.hStdOutput = si.hStdInput;
4745 si.hStdError = si.hStdInput;
4746 }
4747
4748 /* Remove a trailing ", ) and )" if they have a match
4749 * at the start of the command. */
4750 if (cmdbase > cmd)
4751 {
4752 p = cmdbase + STRLEN(cmdbase);
4753 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4754 *--p = NUL;
4755 if (p > cmdbase && p[-1] == ')'
4756 && (*cmd =='(' || cmd[1] == '('))
4757 *--p = NUL;
4758 }
4759
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004760 newcmd = cmdbase;
4761 unescape_shellxquote(cmdbase, p_sxe);
4762
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004763 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004764 * If creating new console, arguments are passed to the
4765 * 'cmd.exe' as-is. If it's not, arguments are not treated
4766 * correctly for current 'cmd.exe'. So unescape characters in
4767 * shellxescape except '|' for avoiding to be treated as
4768 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004769 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004770 if (flags != CREATE_NEW_CONSOLE)
4771 {
4772 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004773 char_u *cmd_shell = mch_getenv("COMSPEC");
4774
4775 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004776 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004777
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004778 subcmd = vim_strsave_escaped_ext(cmdbase,
4779 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004780 if (subcmd != NULL)
4781 {
4782 /* make "cmd.exe /c arguments" */
4783 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004784 newcmd = lalloc(cmdlen, TRUE);
4785 if (newcmd != NULL)
4786 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004787 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004788 else
4789 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004790 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004791 }
4792 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004793
4794 /*
4795 * Now, start the command as a process, so that it doesn't
4796 * inherit our handles which causes unpleasant dangling swap
4797 * files if we exit before the spawned process
4798 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004799 if (vim_create_process((char *)newcmd, FALSE, flags,
4800 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004801 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004802 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4803 > (HINSTANCE)32)
4804 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004805 else
4806 {
4807 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004808#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004809# ifdef VIMDLL
4810 if (gui.in_use)
4811# endif
4812 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004813#endif
4814 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004815
4816 if (newcmd != cmdbase)
4817 vim_free(newcmd);
4818
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004819 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004821 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004822 CloseHandle(si.hStdInput);
4823 }
4824 /* Close the handles to the subprocess, so that it goes away */
4825 CloseHandle(pi.hThread);
4826 CloseHandle(pi.hProcess);
4827 }
4828 else
4829 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004830 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004831#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004832 (gui.in_use ? (!p_stmp ? 0 : STRLEN(vimrun_path)) : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004834 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4835
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004836 newcmd = lalloc(cmdlen, TRUE);
4837 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004839#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004840 if (
4841# ifdef VIMDLL
4842 gui.in_use &&
4843# endif
4844 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004846 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4847 "External commands will not pause after completion.\n"
4848 "See :help win32-vimrun for more information.");
4849 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004850 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4851 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004852
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004853 if (wmsg != NULL && wtitle != NULL)
4854 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4855 vim_free(wmsg);
4856 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 need_vimrun_warning = FALSE;
4858 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004859 if (
4860# ifdef VIMDLL
4861 gui.in_use &&
4862# endif
4863 !s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864 /* Use vimrun to execute the command. It opens a console
4865 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004866 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 vimrun_path,
4868 (msg_silent != 0 || (options & SHELL_DOOUT))
4869 ? "-s " : "",
4870 p_sh, p_shcf, cmd);
4871 else
4872#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004873 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004874 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004876 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 }
4879 }
4880
4881 if (tmode == TMODE_RAW)
4882 settmode(TMODE_RAW); /* set to raw mode */
4883
4884 /* Print the return value, unless "vimrun" was used. */
4885 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004886#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004887 && (gui.in_use ?
4888 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889#endif
4890 )
4891 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004892 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 msg_putchar('\n');
4894 }
4895#ifdef FEAT_TITLE
4896 resettitle();
4897#endif
4898
4899 signal(SIGINT, SIG_DFL);
4900#if defined(__GNUC__) && !defined(__MINGW32__)
4901 signal(SIGKILL, SIG_DFL);
4902#else
4903 signal(SIGBREAK, SIG_DFL);
4904#endif
4905 signal(SIGILL, SIG_DFL);
4906 signal(SIGFPE, SIG_DFL);
4907 signal(SIGSEGV, SIG_DFL);
4908 signal(SIGTERM, SIG_DFL);
4909 signal(SIGABRT, SIG_DFL);
4910
4911 return x;
4912}
4913
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004914#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004915 static HANDLE
4916job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004917 char_u *fname,
4918 DWORD dwDesiredAccess,
4919 DWORD dwShareMode,
4920 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4921 DWORD dwCreationDisposition,
4922 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004923{
4924 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004925 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004926
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004927 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004928 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004929 return INVALID_HANDLE_VALUE;
4930
4931 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4932 lpSecurityAttributes, dwCreationDisposition,
4933 dwFlagsAndAttributes, NULL);
4934 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004935 return h;
4936}
4937
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004938/*
4939 * Turn the dictionary "env" into a NUL separated list that can be used as the
4940 * environment argument of vim_create_process().
4941 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004942 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004943win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004944{
4945 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004946 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004947 LPVOID base = GetEnvironmentStringsW();
4948
4949 /* for last \0 */
4950 if (ga_grow(gap, 1) == FAIL)
4951 return;
4952
4953 if (base)
4954 {
4955 WCHAR *p = (WCHAR*) base;
4956
4957 /* for last \0 */
4958 if (ga_grow(gap, 1) == FAIL)
4959 return;
4960
4961 while (*p != 0 || *(p + 1) != 0)
4962 {
4963 if (ga_grow(gap, 1) == OK)
4964 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4965 p++;
4966 }
4967 FreeEnvironmentStrings(base);
4968 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4969 }
4970
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004971 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004972 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004973 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004974 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004975 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004976 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004977 typval_T *item = &dict_lookup(hi)->di_tv;
4978 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004979 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004980 --todo;
4981 if (wkey != NULL && wval != NULL)
4982 {
4983 size_t n;
4984 size_t lkey = wcslen(wkey);
4985 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02004986
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004987 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
4988 continue;
4989 for (n = 0; n < lkey; n++)
4990 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
4991 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
4992 for (n = 0; n < lval; n++)
4993 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
4994 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4995 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01004996 vim_free(wkey);
4997 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004998 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004999 }
5000 }
5001
Bram Moolenaar493359e2018-06-12 20:25:52 +02005002# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005003 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005004# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005005 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005006 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005007# endif
5008# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005009 char_u *version = get_vim_var_str(VV_VERSION);
5010 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005011# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005012 // size of "VIM_SERVERNAME=" and value,
5013 // plus "VIM_TERMINAL=" and value,
5014 // plus two terminating NULs
5015 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005016# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005017 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005018# endif
5019# ifdef FEAT_TERMINAL
5020 + 13 + version_len + 2
5021# endif
5022 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005023
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005024 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005025 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005026# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005027 for (n = 0; n < 15; n++)
5028 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5029 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005030 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005031 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5032 (WCHAR)servername[n];
5033 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005034# endif
5035# ifdef FEAT_TERMINAL
5036 if (is_terminal)
5037 {
5038 for (n = 0; n < 13; n++)
5039 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5040 (WCHAR)"VIM_TERMINAL="[n];
5041 for (n = 0; n < version_len; n++)
5042 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5043 (WCHAR)version[n];
5044 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5045 }
5046# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005047 }
5048 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005049# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005050}
5051
Bram Moolenaarb091f302019-01-19 14:37:00 +01005052/*
5053 * Create a pair of pipes.
5054 * Return TRUE for success, FALSE for failure.
5055 */
5056 static BOOL
5057create_pipe_pair(HANDLE handles[2])
5058{
5059 static LONG s;
5060 char name[64];
5061 SECURITY_ATTRIBUTES sa;
5062
5063 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5064 GetCurrentProcessId(),
5065 InterlockedIncrement(&s));
5066
5067 // Create named pipe. Max size of named pipe is 65535.
5068 handles[1] = CreateNamedPipe(
5069 name,
5070 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5071 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005072 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005073
5074 if (handles[1] == INVALID_HANDLE_VALUE)
5075 return FALSE;
5076
5077 sa.nLength = sizeof(sa);
5078 sa.bInheritHandle = TRUE;
5079 sa.lpSecurityDescriptor = NULL;
5080
5081 handles[0] = CreateFile(name,
5082 FILE_GENERIC_READ,
5083 FILE_SHARE_READ, &sa,
5084 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5085
5086 if (handles[0] == INVALID_HANDLE_VALUE)
5087 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005088 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005089 return FALSE;
5090 }
5091
5092 return TRUE;
5093}
5094
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005095 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005096mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005097{
5098 STARTUPINFO si;
5099 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005100 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005101 SECURITY_ATTRIBUTES saAttr;
5102 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005103 HANDLE ifd[2];
5104 HANDLE ofd[2];
5105 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005106 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005107
5108 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5109 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5110 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5111 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5112 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5113 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5114 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5115
5116 if (use_out_for_err && use_null_for_out)
5117 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005118
5119 ifd[0] = INVALID_HANDLE_VALUE;
5120 ifd[1] = INVALID_HANDLE_VALUE;
5121 ofd[0] = INVALID_HANDLE_VALUE;
5122 ofd[1] = INVALID_HANDLE_VALUE;
5123 efd[0] = INVALID_HANDLE_VALUE;
5124 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005125 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005126
Bram Moolenaar14207f42016-10-27 21:13:10 +02005127 jo = CreateJobObject(NULL, NULL);
5128 if (jo == NULL)
5129 {
5130 job->jv_status = JOB_FAILED;
5131 goto failed;
5132 }
5133
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005134 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005135 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005136
Bram Moolenaar76467df2016-02-12 19:30:26 +01005137 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005138 ZeroMemory(&si, sizeof(si));
5139 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005140 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005141 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005142
Bram Moolenaard8070362016-02-15 21:56:54 +01005143 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5144 saAttr.bInheritHandle = TRUE;
5145 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005146
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005147 if (use_file_for_in)
5148 {
5149 char_u *fname = options->jo_io_name[PART_IN];
5150
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005151 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5152 FILE_SHARE_READ | FILE_SHARE_WRITE,
5153 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5154 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005155 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005156 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005157 goto failed;
5158 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005159 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005160 else if (!use_null_for_in
5161 && (!create_pipe_pair(ifd)
5162 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005163 goto failed;
5164
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005165 if (use_file_for_out)
5166 {
5167 char_u *fname = options->jo_io_name[PART_OUT];
5168
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005169 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5170 FILE_SHARE_READ | FILE_SHARE_WRITE,
5171 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5172 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005173 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005174 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005175 goto failed;
5176 }
5177 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005178 else if (!use_null_for_out &&
5179 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005180 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005181 goto failed;
5182
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005183 if (use_file_for_err)
5184 {
5185 char_u *fname = options->jo_io_name[PART_ERR];
5186
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005187 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5188 FILE_SHARE_READ | FILE_SHARE_WRITE,
5189 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5190 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005191 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005192 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005193 goto failed;
5194 }
5195 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005196 else if (!use_out_for_err && !use_null_for_err &&
5197 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005198 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005199 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005200
Bram Moolenaard8070362016-02-15 21:56:54 +01005201 si.dwFlags |= STARTF_USESTDHANDLES;
5202 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005203 si.hStdOutput = ofd[1];
5204 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5205
5206 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5207 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005208 if (options->jo_set & JO_CHANNEL)
5209 {
5210 channel = options->jo_channel;
5211 if (channel != NULL)
5212 ++channel->ch_refcount;
5213 }
5214 else
5215 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005216 if (channel == NULL)
5217 goto failed;
5218 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005219
5220 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005221 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005222 CREATE_DEFAULT_ERROR_MODE |
5223 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005224 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005225 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005226 &si, &pi,
5227 ga.ga_data,
5228 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005229 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005230 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005231 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005232 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005233 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005234
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005235 ga_clear(&ga);
5236
Bram Moolenaar14207f42016-10-27 21:13:10 +02005237 if (!AssignProcessToJobObject(jo, pi.hProcess))
5238 {
5239 /* if failing, switch the way to terminate
5240 * process with TerminateProcess. */
5241 CloseHandle(jo);
5242 jo = NULL;
5243 }
5244 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005245 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005246 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005247 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005248 job->jv_status = JOB_STARTED;
5249
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005250 CloseHandle(ifd[0]);
5251 CloseHandle(ofd[1]);
5252 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005253 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005254
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005255 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005256 if (channel != NULL)
5257 {
5258 channel_set_pipes(channel,
5259 use_file_for_in || use_null_for_in
5260 ? INVALID_FD : (sock_T)ifd[1],
5261 use_file_for_out || use_null_for_out
5262 ? INVALID_FD : (sock_T)ofd[0],
5263 use_out_for_err || use_file_for_err || use_null_for_err
5264 ? INVALID_FD : (sock_T)efd[0]);
5265 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005266 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005267 return;
5268
5269failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005270 CloseHandle(ifd[0]);
5271 CloseHandle(ofd[0]);
5272 CloseHandle(efd[0]);
5273 CloseHandle(ifd[1]);
5274 CloseHandle(ofd[1]);
5275 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005276 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005277 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005278}
5279
5280 char *
5281mch_job_status(job_T *job)
5282{
5283 DWORD dwExitCode = 0;
5284
Bram Moolenaar76467df2016-02-12 19:30:26 +01005285 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5286 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005287 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005288 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005289 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005290 {
5291 ch_log(job->jv_channel, "Job ended");
5292 job->jv_status = JOB_ENDED;
5293 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005294 return "dead";
5295 }
5296 return "run";
5297}
5298
Bram Moolenaar97792de2016-10-15 18:36:49 +02005299 job_T *
5300mch_detect_ended_job(job_T *job_list)
5301{
5302 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5303 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5304 job_T *job = job_list;
5305
5306 while (job != NULL)
5307 {
5308 DWORD n;
5309 DWORD result;
5310
5311 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5312 && job != NULL; job = job->jv_next)
5313 {
5314 if (job->jv_status == JOB_STARTED)
5315 {
5316 jobHandles[n] = job->jv_proc_info.hProcess;
5317 jobArray[n] = job;
5318 ++n;
5319 }
5320 }
5321 if (n == 0)
5322 continue;
5323 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5324 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5325 {
5326 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5327
5328 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5329 return wait_job;
5330 }
5331 }
5332 return NULL;
5333}
5334
Bram Moolenaarfb630902016-10-29 14:55:00 +02005335 static BOOL
5336terminate_all(HANDLE process, int code)
5337{
5338 PROCESSENTRY32 pe;
5339 HANDLE h = INVALID_HANDLE_VALUE;
5340 DWORD pid = GetProcessId(process);
5341
5342 if (pid != 0)
5343 {
5344 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5345 if (h != INVALID_HANDLE_VALUE)
5346 {
5347 pe.dwSize = sizeof(PROCESSENTRY32);
5348 if (!Process32First(h, &pe))
5349 goto theend;
5350
5351 do
5352 {
5353 if (pe.th32ParentProcessID == pid)
5354 {
5355 HANDLE ph = OpenProcess(
5356 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5357 if (ph != NULL)
5358 {
5359 terminate_all(ph, code);
5360 CloseHandle(ph);
5361 }
5362 }
5363 } while (Process32Next(h, &pe));
5364
5365 CloseHandle(h);
5366 }
5367 }
5368
5369theend:
5370 return TerminateProcess(process, code);
5371}
5372
5373/*
5374 * Send a (deadly) signal to "job".
5375 * Return FAIL if it didn't work.
5376 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005377 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005378mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005379{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005380 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005381
Bram Moolenaar923d9262016-02-25 20:56:01 +01005382 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005383 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005384 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005385 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005386 {
5387 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5388 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005389 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005390 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005391 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005392 }
5393
5394 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5395 return FAIL;
5396 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005397 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5398 job->jv_proc_info.dwProcessId)
5399 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005400 FreeConsole();
5401 return ret;
5402}
5403
5404/*
5405 * Clear the data related to "job".
5406 */
5407 void
5408mch_clear_job(job_T *job)
5409{
5410 if (job->jv_status != JOB_FAILED)
5411 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005412 if (job->jv_job_object != NULL)
5413 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005414 CloseHandle(job->jv_proc_info.hProcess);
5415 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005416}
5417#endif
5418
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005420#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421
5422/*
5423 * Start termcap mode
5424 */
5425 static void
5426termcap_mode_start(void)
5427{
5428 DWORD cmodein;
5429
5430 if (g_fTermcapMode)
5431 return;
5432
5433 SaveConsoleBuffer(&g_cbNonTermcap);
5434
5435 if (g_cbTermcap.IsValid)
5436 {
5437 /*
5438 * We've been in termcap mode before. Restore certain screen
5439 * characteristics, including the buffer size and the window
5440 * size. Since we will be redrawing the screen, we don't need
5441 * to restore the actual contents of the buffer.
5442 */
5443 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005444 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5446 Rows = g_cbTermcap.Info.dwSize.Y;
5447 Columns = g_cbTermcap.Info.dwSize.X;
5448 }
5449 else
5450 {
5451 /*
5452 * This is our first time entering termcap mode. Clear the console
5453 * screen buffer, and resize the buffer to match the current window
5454 * size. We will use this as the size of our editing environment.
5455 */
5456 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005457 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005458 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5459 }
5460
5461#ifdef FEAT_TITLE
5462 resettitle();
5463#endif
5464
5465 GetConsoleMode(g_hConIn, &cmodein);
5466#ifdef FEAT_MOUSE
5467 if (g_fMouseActive)
5468 cmodein |= ENABLE_MOUSE_INPUT;
5469 else
5470 cmodein &= ~ENABLE_MOUSE_INPUT;
5471#endif
5472 cmodein |= ENABLE_WINDOW_INPUT;
5473 SetConsoleMode(g_hConIn, cmodein);
5474
5475 redraw_later_clear();
5476 g_fTermcapMode = TRUE;
5477}
5478
5479
5480/*
5481 * End termcap mode
5482 */
5483 static void
5484termcap_mode_end(void)
5485{
5486 DWORD cmodein;
5487 ConsoleBuffer *cb;
5488 COORD coord;
5489 DWORD dwDummy;
5490
5491 if (!g_fTermcapMode)
5492 return;
5493
5494 SaveConsoleBuffer(&g_cbTermcap);
5495
5496 GetConsoleMode(g_hConIn, &cmodein);
5497 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5498 SetConsoleMode(g_hConIn, cmodein);
5499
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005500#ifdef FEAT_RESTORE_ORIG_SCREEN
5501 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5502#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005506 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 SetConsoleCursorInfo(g_hConOut, &g_cci);
5508
5509 if (p_rs || exiting)
5510 {
5511 /*
5512 * Clear anything that happens to be on the current line.
5513 */
5514 coord.X = 0;
5515 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5516 FillConsoleOutputCharacter(g_hConOut, ' ',
5517 cb->Info.dwSize.X, coord, &dwDummy);
5518 /*
5519 * The following is just for aesthetics. If we are exiting without
5520 * restoring the screen, then we want to have a prompt string
5521 * appear at the bottom line. However, the command interpreter
5522 * seems to always advance the cursor one line before displaying
5523 * the prompt string, which causes the screen to scroll. To
5524 * counter this, move the cursor up one line before exiting.
5525 */
5526 if (exiting && !p_rs)
5527 coord.Y--;
5528 /*
5529 * Position the cursor at the leftmost column of the desired row.
5530 */
5531 SetConsoleCursorPosition(g_hConOut, coord);
5532 }
5533
5534 g_fTermcapMode = FALSE;
5535}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005536#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537
5538
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005539#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 void
5541mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005542 char_u *s UNUSED,
5543 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544{
5545 /* never used */
5546}
5547
5548#else
5549
5550/*
5551 * clear `n' chars, starting from `coord'
5552 */
5553 static void
5554clear_chars(
5555 COORD coord,
5556 DWORD n)
5557{
5558 DWORD dwDummy;
5559
5560 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005561
5562 if (!USE_VTP)
5563 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5564 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005565 {
5566 set_console_color_rgb();
5567 gotoxy(coord.X + 1, coord.Y + 1);
5568 vtp_printf("\033[%dX", n);
5569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570}
5571
5572
5573/*
5574 * Clear the screen
5575 */
5576 static void
5577clear_screen(void)
5578{
5579 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005580
5581 if (!USE_VTP)
5582 clear_chars(g_coord, Rows * Columns);
5583 else
5584 {
5585 set_console_color_rgb();
5586 gotoxy(1, 1);
5587 vtp_printf("\033[2J");
5588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589}
5590
5591
5592/*
5593 * Clear to end of display
5594 */
5595 static void
5596clear_to_end_of_display(void)
5597{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005598 COORD save = g_coord;
5599
5600 if (!USE_VTP)
5601 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005603 else
5604 {
5605 set_console_color_rgb();
5606 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5607 vtp_printf("\033[0J");
5608
5609 gotoxy(save.X + 1, save.Y + 1);
5610 g_coord = save;
5611 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612}
5613
5614
5615/*
5616 * Clear to end of line
5617 */
5618 static void
5619clear_to_end_of_line(void)
5620{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005621 COORD save = g_coord;
5622
5623 if (!USE_VTP)
5624 clear_chars(g_coord, Columns - g_coord.X);
5625 else
5626 {
5627 set_console_color_rgb();
5628 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5629 vtp_printf("\033[0K");
5630
5631 gotoxy(save.X + 1, save.Y + 1);
5632 g_coord = save;
5633 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634}
5635
5636
5637/*
5638 * Scroll the scroll region up by `cLines' lines
5639 */
5640 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005641scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642{
5643 COORD oldcoord = g_coord;
5644
5645 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5646 delete_lines(cLines);
5647
5648 g_coord = oldcoord;
5649}
5650
5651
5652/*
5653 * Set the scroll region
5654 */
5655 static void
5656set_scroll_region(
5657 unsigned left,
5658 unsigned top,
5659 unsigned right,
5660 unsigned bottom)
5661{
5662 if (left >= right
5663 || top >= bottom
5664 || right > (unsigned) Columns - 1
5665 || bottom > (unsigned) Rows - 1)
5666 return;
5667
5668 g_srScrollRegion.Left = left;
5669 g_srScrollRegion.Top = top;
5670 g_srScrollRegion.Right = right;
5671 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005672}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005673
Bram Moolenaar6982f422019-02-16 16:48:01 +01005674 static void
5675set_scroll_region_tb(
5676 unsigned top,
5677 unsigned bottom)
5678{
5679 if (top >= bottom || bottom > (unsigned)Rows - 1)
5680 return;
5681
5682 g_srScrollRegion.Top = top;
5683 g_srScrollRegion.Bottom = bottom;
5684}
5685
5686 static void
5687set_scroll_region_lr(
5688 unsigned left,
5689 unsigned right)
5690{
5691 if (left >= right || right > (unsigned)Columns - 1)
5692 return;
5693
5694 g_srScrollRegion.Left = left;
5695 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696}
5697
5698
5699/*
5700 * Insert `cLines' lines at the current cursor position
5701 */
5702 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005703insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005705 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 COORD dest;
5707 CHAR_INFO fill;
5708
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005709 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5710
Bram Moolenaar6982f422019-02-16 16:48:01 +01005711 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712 dest.Y = g_coord.Y + cLines;
5713
Bram Moolenaar6982f422019-02-16 16:48:01 +01005714 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715 source.Top = g_coord.Y;
5716 source.Right = g_srScrollRegion.Right;
5717 source.Bottom = g_srScrollRegion.Bottom - cLines;
5718
Bram Moolenaar6982f422019-02-16 16:48:01 +01005719 clip.Left = g_srScrollRegion.Left;
5720 clip.Top = g_coord.Y;
5721 clip.Right = g_srScrollRegion.Right;
5722 clip.Bottom = g_srScrollRegion.Bottom;
5723
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005724 fill.Char.AsciiChar = ' ';
5725 if (!USE_VTP)
5726 fill.Attributes = g_attrCurrent;
5727 else
5728 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005730 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005731
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005732 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5733
Bram Moolenaar6982f422019-02-16 16:48:01 +01005734 // Here we have to deal with a win32 console flake: If the scroll
5735 // region looks like abc and we scroll c to a and fill with d we get
5736 // cbd... if we scroll block c one line at a time to a, we get cdd...
5737 // vim expects cdd consistently... So we have to deal with that
5738 // here... (this also occurs scrolling the same way in the other
5739 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740
5741 if (source.Bottom < dest.Y)
5742 {
5743 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005744 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745
Bram Moolenaar6982f422019-02-16 16:48:01 +01005746 coord.X = source.Left;
5747 for (i = clip.Top; i < dest.Y; ++i)
5748 {
5749 coord.Y = i;
5750 clear_chars(coord, source.Right - source.Left + 1);
5751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752 }
5753}
5754
5755
5756/*
5757 * Delete `cLines' lines at the current cursor position
5758 */
5759 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005760delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005762 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 COORD dest;
5764 CHAR_INFO fill;
5765 int nb;
5766
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005767 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5768
Bram Moolenaar6982f422019-02-16 16:48:01 +01005769 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770 dest.Y = g_coord.Y;
5771
Bram Moolenaar6982f422019-02-16 16:48:01 +01005772 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773 source.Top = g_coord.Y + cLines;
5774 source.Right = g_srScrollRegion.Right;
5775 source.Bottom = g_srScrollRegion.Bottom;
5776
Bram Moolenaar6982f422019-02-16 16:48:01 +01005777 clip.Left = g_srScrollRegion.Left;
5778 clip.Top = g_coord.Y;
5779 clip.Right = g_srScrollRegion.Right;
5780 clip.Bottom = g_srScrollRegion.Bottom;
5781
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005782 fill.Char.AsciiChar = ' ';
5783 if (!USE_VTP)
5784 fill.Attributes = g_attrCurrent;
5785 else
5786 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005788 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005789
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005790 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5791
Bram Moolenaar6982f422019-02-16 16:48:01 +01005792 // Here we have to deal with a win32 console flake; See insert_lines()
5793 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794
5795 nb = dest.Y + (source.Bottom - source.Top) + 1;
5796
5797 if (nb < source.Top)
5798 {
5799 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005800 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801
Bram Moolenaar6982f422019-02-16 16:48:01 +01005802 coord.X = source.Left;
5803 for (i = nb; i < clip.Bottom; ++i)
5804 {
5805 coord.Y = i;
5806 clear_chars(coord, source.Right - source.Left + 1);
5807 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 }
5809}
5810
5811
5812/*
5813 * Set the cursor position
5814 */
5815 static void
5816gotoxy(
5817 unsigned x,
5818 unsigned y)
5819{
5820 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5821 return;
5822
5823 /* external cursor coords are 1-based; internal are 0-based */
5824 g_coord.X = x - 1;
5825 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005826
5827 if (!USE_VTP)
5828 SetConsoleCursorPosition(g_hConOut, g_coord);
5829 else
5830 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831}
5832
5833
5834/*
5835 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005836 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837 */
5838 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005839textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005841 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842
5843 SetConsoleTextAttribute(g_hConOut, wAttr);
5844}
5845
5846
5847 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005848textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005850 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005852 if (!USE_VTP)
5853 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5854 else
5855 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856}
5857
5858
5859 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005860textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005862 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005864 if (!USE_VTP)
5865 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5866 else
5867 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868}
5869
5870
5871/*
5872 * restore the default text attribute (whatever we started with)
5873 */
5874 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005875normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005877 if (!USE_VTP)
5878 textattr(g_attrDefault);
5879 else
5880 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881}
5882
5883
5884static WORD g_attrPreStandout = 0;
5885
5886/*
5887 * Make the text standout, by brightening it
5888 */
5889 static void
5890standout(void)
5891{
5892 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005893
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5895}
5896
5897
5898/*
5899 * Turn off standout mode
5900 */
5901 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005902standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903{
5904 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005906
5907 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908}
5909
5910
5911/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005912 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913 */
5914 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005915mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916{
5917 char_u *p;
5918 int n;
5919
5920 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5921 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005922 if (
5923#ifdef FEAT_TERMGUICOLORS
5924 !p_tgc &&
5925#endif
5926 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927 {
5928 p = T_ME + 2;
5929 n = getdigits(&p);
5930 if (*p == 'm' && n > 0)
5931 {
5932 cterm_normal_fg_color = (n & 0xf) + 1;
5933 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5934 }
5935 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005936#ifdef FEAT_TERMGUICOLORS
5937 cterm_normal_fg_gui_color = INVALCOLOR;
5938 cterm_normal_bg_gui_color = INVALCOLOR;
5939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005940}
5941
5942
5943/*
5944 * visual bell: flash the screen
5945 */
5946 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005947visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948{
5949 COORD coordOrigin = {0, 0};
5950 WORD attrFlash = ~g_attrCurrent & 0xff;
5951
5952 DWORD dwDummy;
5953 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5954
5955 if (oldattrs == NULL)
5956 return;
5957 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5958 coordOrigin, &dwDummy);
5959 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5960 coordOrigin, &dwDummy);
5961
5962 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005963 if (!USE_VTP)
5964 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965 coordOrigin, &dwDummy);
5966 vim_free(oldattrs);
5967}
5968
5969
5970/*
5971 * Make the cursor visible or invisible
5972 */
5973 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005974cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
5976 s_cursor_visible = fVisible;
5977#ifdef MCH_CURSOR_SHAPE
5978 mch_update_cursor();
5979#endif
5980}
5981
5982
5983/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005984 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005985 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005987 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005989 char_u *pchBuf,
5990 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005992 COORD coord = g_coord;
5993 DWORD written;
5994 DWORD n, cchwritten, cells;
5995 static WCHAR *unicodebuf = NULL;
5996 static int unibuflen = 0;
5997 int length;
5998 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006000 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6001 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006002 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006003 vim_free(unicodebuf);
6004 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6005 unibuflen = length;
6006 }
6007 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6008 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006010 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006011
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006012 if (!USE_VTP)
6013 {
6014 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6015 coord, &written);
6016 // When writing fails or didn't write a single character, pretend one
6017 // character was written, otherwise we get stuck.
6018 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6019 coord, &cchwritten) == 0
6020 || cchwritten == 0 || cchwritten == (DWORD)-1)
6021 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006022 }
6023 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006024 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006025 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6026 NULL) == 0 || cchwritten == 0)
6027 cchwritten = 1;
6028 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006029
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006030 if (cchwritten == length)
6031 {
6032 written = cbToWrite;
6033 g_coord.X += (SHORT)cells;
6034 }
6035 else
6036 {
6037 char_u *p = pchBuf;
6038 for (n = 0; n < cchwritten; n++)
6039 MB_CPTR_ADV(p);
6040 written = p - pchBuf;
6041 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043
6044 while (g_coord.X > g_srScrollRegion.Right)
6045 {
6046 g_coord.X -= (SHORT) Columns;
6047 if (g_coord.Y < g_srScrollRegion.Bottom)
6048 g_coord.Y++;
6049 }
6050
6051 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6052
6053 return written;
6054}
6055
6056
6057/*
6058 * mch_write(): write the output buffer to the screen, translating ESC
6059 * sequences into calls to console output routines.
6060 */
6061 void
6062mch_write(
6063 char_u *s,
6064 int len)
6065{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006066# ifdef VIMDLL
6067 if (gui.in_use)
6068 return;
6069# endif
6070
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071 s[len] = NUL;
6072
6073 if (!term_console)
6074 {
6075 write(1, s, (unsigned)len);
6076 return;
6077 }
6078
6079 /* translate ESC | sequences into faked bios calls */
6080 while (len--)
6081 {
6082 /* optimization: use one single write_chars for runs of text,
6083 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006084 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085
6086 if (p_wd)
6087 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006088 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006089 if (prefix != 0)
6090 prefix = 1;
6091 }
6092
6093 if (prefix != 0)
6094 {
6095 DWORD nWritten;
6096
6097 nWritten = write_chars(s, prefix);
6098#ifdef MCH_WRITE_DUMP
6099 if (fdDump)
6100 {
6101 fputc('>', fdDump);
6102 fwrite(s, sizeof(char_u), nWritten, fdDump);
6103 fputs("<\n", fdDump);
6104 }
6105#endif
6106 len -= (nWritten - 1);
6107 s += nWritten;
6108 }
6109 else if (s[0] == '\n')
6110 {
6111 /* \n, newline: go to the beginning of the next line or scroll */
6112 if (g_coord.Y == g_srScrollRegion.Bottom)
6113 {
6114 scroll(1);
6115 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6116 }
6117 else
6118 {
6119 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6120 }
6121#ifdef MCH_WRITE_DUMP
6122 if (fdDump)
6123 fputs("\\n\n", fdDump);
6124#endif
6125 s++;
6126 }
6127 else if (s[0] == '\r')
6128 {
6129 /* \r, carriage return: go to beginning of line */
6130 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6131#ifdef MCH_WRITE_DUMP
6132 if (fdDump)
6133 fputs("\\r\n", fdDump);
6134#endif
6135 s++;
6136 }
6137 else if (s[0] == '\b')
6138 {
6139 /* \b, backspace: move cursor one position left */
6140 if (g_coord.X > g_srScrollRegion.Left)
6141 g_coord.X--;
6142 else if (g_coord.Y > g_srScrollRegion.Top)
6143 {
6144 g_coord.X = g_srScrollRegion.Right;
6145 g_coord.Y--;
6146 }
6147 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6148#ifdef MCH_WRITE_DUMP
6149 if (fdDump)
6150 fputs("\\b\n", fdDump);
6151#endif
6152 s++;
6153 }
6154 else if (s[0] == '\a')
6155 {
6156 /* \a, bell */
6157 MessageBeep(0xFFFFFFFF);
6158#ifdef MCH_WRITE_DUMP
6159 if (fdDump)
6160 fputs("\\a\n", fdDump);
6161#endif
6162 s++;
6163 }
6164 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6165 {
6166#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006167 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006169 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006170 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171
6172 switch (s[2])
6173 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 case '0': case '1': case '2': case '3': case '4':
6175 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006176 p = s + 1;
6177 do
6178 {
6179 ++p;
6180 args[argc] = getdigits(&p);
6181 argc += (argc < 15) ? 1 : 0;
6182 if (p > s + len)
6183 break;
6184 } while (*p == ';');
6185
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 if (p > s + len)
6187 break;
6188
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006189 arg1 = args[0];
6190 arg2 = args[1];
6191 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006193 if (argc == 1 && args[0] == 0)
6194 normvideo();
6195 else if (argc == 1)
6196 {
6197 if (USE_VTP)
6198 textcolor((WORD) arg1);
6199 else
6200 textattr((WORD) arg1);
6201 }
6202 else if (USE_VTP)
6203 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006205 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006207 gotoxy(arg2, arg1);
6208 }
6209 else if (argc == 2 && *p == 'r')
6210 {
6211 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6212 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006213 else if (argc == 2 && *p == 'R')
6214 {
6215 set_scroll_region_tb(arg1, arg2);
6216 }
6217 else if (argc == 2 && *p == 'V')
6218 {
6219 set_scroll_region_lr(arg1, arg2);
6220 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006221 else if (argc == 1 && *p == 'A')
6222 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 gotoxy(g_coord.X + 1,
6224 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6225 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006226 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 {
6228 textbackground((WORD) arg1);
6229 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006230 else if (argc == 1 && *p == 'C')
6231 {
6232 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6233 g_coord.Y + 1);
6234 }
6235 else if (argc == 1 && *p == 'f')
6236 {
6237 textcolor((WORD) arg1);
6238 }
6239 else if (argc == 1 && *p == 'H')
6240 {
6241 gotoxy(1, arg1);
6242 }
6243 else if (argc == 1 && *p == 'L')
6244 {
6245 insert_lines(arg1);
6246 }
6247 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 {
6249 delete_lines(arg1);
6250 }
6251
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006252 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 s = p + 1;
6254 break;
6255
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 gotoxy(g_coord.X + 1,
6258 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6259 goto got3;
6260
6261 case 'B':
6262 visual_bell();
6263 goto got3;
6264
6265 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6267 g_coord.Y + 1);
6268 goto got3;
6269
6270 case 'E':
6271 termcap_mode_end();
6272 goto got3;
6273
6274 case 'F':
6275 standout();
6276 goto got3;
6277
6278 case 'f':
6279 standend();
6280 goto got3;
6281
6282 case 'H':
6283 gotoxy(1, 1);
6284 goto got3;
6285
6286 case 'j':
6287 clear_to_end_of_display();
6288 goto got3;
6289
6290 case 'J':
6291 clear_screen();
6292 goto got3;
6293
6294 case 'K':
6295 clear_to_end_of_line();
6296 goto got3;
6297
6298 case 'L':
6299 insert_lines(1);
6300 goto got3;
6301
6302 case 'M':
6303 delete_lines(1);
6304 goto got3;
6305
6306 case 'S':
6307 termcap_mode_start();
6308 goto got3;
6309
6310 case 'V':
6311 cursor_visible(TRUE);
6312 goto got3;
6313
6314 case 'v':
6315 cursor_visible(FALSE);
6316 goto got3;
6317
6318 got3:
6319 s += 3;
6320 len -= 2;
6321 }
6322
6323#ifdef MCH_WRITE_DUMP
6324 if (fdDump)
6325 {
6326 fputs("ESC | ", fdDump);
6327 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6328 fputc('\n', fdDump);
6329 }
6330#endif
6331 }
6332 else
6333 {
6334 /* Write a single character */
6335 DWORD nWritten;
6336
6337 nWritten = write_chars(s, 1);
6338#ifdef MCH_WRITE_DUMP
6339 if (fdDump)
6340 {
6341 fputc('>', fdDump);
6342 fwrite(s, sizeof(char_u), nWritten, fdDump);
6343 fputs("<\n", fdDump);
6344 }
6345#endif
6346
6347 len -= (nWritten - 1);
6348 s += nWritten;
6349 }
6350 }
6351
6352#ifdef MCH_WRITE_DUMP
6353 if (fdDump)
6354 fflush(fdDump);
6355#endif
6356}
6357
Bram Moolenaar4f974752019-02-17 17:44:42 +01006358#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359
6360
6361/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006362 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 */
6364 void
6365mch_delay(
6366 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006367 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006369#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006371#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006372# ifdef VIMDLL
6373 if (gui.in_use)
6374 {
6375 Sleep((int)msec); /* never wait for input */
6376 return;
6377 }
6378# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006380# ifdef FEAT_MZSCHEME
6381 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6382 {
6383 int towait = p_mzq;
6384
6385 /* if msec is large enough, wait by portions in p_mzq */
6386 while (msec > 0)
6387 {
6388 mzvim_check_threads();
6389 if (msec < towait)
6390 towait = msec;
6391 Sleep(towait);
6392 msec -= towait;
6393 }
6394 }
6395 else
6396# endif
6397 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006399 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400#endif
6401}
6402
6403
6404/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006405 * This version of remove is not scared by a readonly (backup) file.
6406 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 * Return 0 for success, -1 for failure.
6408 */
6409 int
6410mch_remove(char_u *name)
6411{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006412 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 int n;
6414
Bram Moolenaar203258c2016-01-17 22:15:16 +01006415 /*
6416 * On Windows, deleting a directory's symbolic link is done by
6417 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6418 */
6419 if (mch_isdir(name) && mch_is_symbolic_link(name))
6420 return mch_rmdir(name);
6421
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006422 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6423
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006424 wn = enc_to_utf16(name, NULL);
6425 if (wn == NULL)
6426 return -1;
6427
6428 n = DeleteFileW(wn) ? 0 : -1;
6429 vim_free(wn);
6430 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431}
6432
6433
6434/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006435 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436 */
6437 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006438mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006440#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6441# ifdef VIMDLL
6442 if (!gui.in_use)
6443# endif
6444 if (g_fCtrlCPressed || g_fCBrkPressed)
6445 {
6446 ctrl_break_was_pressed = g_fCBrkPressed;
6447 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6448 got_int = TRUE;
6449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450#endif
6451}
6452
Bram Moolenaaree273972016-01-02 21:11:51 +01006453/* physical RAM to leave for the OS */
6454#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006455
6456/*
6457 * How much main memory in KiB that can be used by VIM.
6458 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006459 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006460mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006461{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006462 MEMORYSTATUSEX ms;
6463
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006464 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006465 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006466 ms.dwLength = sizeof(MEMORYSTATUSEX);
6467 GlobalMemoryStatusEx(&ms);
6468 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006469 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006470 /* Process address space fits in physical RAM, use all of it. */
6471 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006472 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006473 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006474 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006475 /* Catch old NT box or perverse hardware setup. */
6476 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006477 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006478 /* Use physical RAM less reserve for OS + data. */
6479 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006480}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006483 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6485 * file whose short file name is "FOO.BAR" (its long file name will
6486 * be correct: "foo.bar~"). Because a file can be accessed by
6487 * either its SFN or its LFN, "foo.bar" has effectively been
6488 * renamed to "foo.bar", which is not at all what was wanted. This
6489 * seems to happen only when renaming files with three-character
6490 * extensions by appending a suffix that does not include ".".
6491 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6492 *
6493 * There is another problem, which isn't really a bug but isn't right either:
6494 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6495 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6496 * service pack 6. Doesn't seem to happen on Windows 98.
6497 *
6498 * Like rename(), returns 0 upon success, non-zero upon failure.
6499 * Should probably set errno appropriately when errors occur.
6500 */
6501 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006502mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006504 WCHAR *p;
6505 int i;
6506 WCHAR szTempFile[_MAX_PATH + 1];
6507 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006510 // No need to play tricks unless the file name contains a "~" as the
6511 // seventh character.
6512 p = wold;
6513 for (i = 0; wold[i] != NUL; ++i)
6514 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6515 && wold[i + 1] != 0)
6516 p = wold + i + 1;
6517 if ((int)(wold + i - p) < 8 || p[6] != '~')
6518 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006520 // Get base path of new file name. Undocumented feature: If pszNewFile is
6521 // a directory, no error is returned and pszFilePart will be NULL.
6522 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006524 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006526 // Get (and create) a unique temporary file name in directory of new file
6527 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 return -2;
6529
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006530 // blow the temp file away
6531 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 return -3;
6533
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006534 // rename old file to the temp file
6535 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536 return -4;
6537
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006538 // now create an empty file called pszOldFile; this prevents the operating
6539 // system using pszOldFile as an alias (SFN) if we're renaming within the
6540 // same directory. For example, we're editing a file called
6541 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6542 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6543 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6544 // cause all sorts of problems later in buf_write(). So, we create an
6545 // empty file called filena~1.txt and the system will have to find some
6546 // other SFN for filena~1.txt~, such as filena~2.txt
6547 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6549 return -5;
6550 if (!CloseHandle(hf))
6551 return -6;
6552
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006553 // rename the temp file to the new file
6554 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006556 // Renaming failed. Rename the file back to its old name, so that it
6557 // looks like nothing happened.
6558 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 return -7;
6560 }
6561
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006562 // Seems to be left around on Novell filesystems
6563 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006565 // finally, remove the empty old file
6566 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 return -8;
6568
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006569 return 0;
6570}
6571
6572
6573/*
6574 * Converts the filenames to UTF-16, then call mch_wrename().
6575 * Like rename(), returns 0 upon success, non-zero upon failure.
6576 */
6577 int
6578mch_rename(
6579 const char *pszOldFile,
6580 const char *pszNewFile)
6581{
6582 WCHAR *wold = NULL;
6583 WCHAR *wnew = NULL;
6584 int retval = -1;
6585
6586 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6587 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6588 if (wold != NULL && wnew != NULL)
6589 retval = mch_wrename(wold, wnew);
6590 vim_free(wold);
6591 vim_free(wnew);
6592 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593}
6594
6595/*
6596 * Get the default shell for the current hardware platform
6597 */
6598 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006599default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006601 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602}
6603
6604/*
6605 * mch_access() extends access() to do more detailed check on network drives.
6606 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6607 */
6608 int
6609mch_access(char *n, int p)
6610{
6611 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006613 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006615 wn = enc_to_utf16((char_u *)n, NULL);
6616 if (wn == NULL)
6617 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006619 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622
6623 if (p & R_OK)
6624 {
6625 /* Read check is performed by seeing if we can do a find file on
6626 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006627 int i;
6628 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006630 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6631 TempNameW[i] = wn[i];
6632 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6633 TempNameW[i++] = '\\';
6634 TempNameW[i++] = '*';
6635 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006637 hFile = FindFirstFileW(TempNameW, &d);
6638 if (hFile == INVALID_HANDLE_VALUE)
6639 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006640 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 }
6643
6644 if (p & W_OK)
6645 {
6646 /* Trying to create a temporary file in the directory should catch
6647 * directories on read-only network shares. However, in
6648 * directories whose ACL allows writes but denies deletes will end
6649 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006650 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6651 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006652 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006653 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 }
6655 }
6656 else
6657 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006658 // Don't consider a file read-only if another process has opened it.
6659 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6660
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 /* Trying to open the file for the required access does ACL, read-only
6662 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006663 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6664 | ((p & R_OK) ? GENERIC_READ : 0);
6665
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006666 hFile = CreateFileW(wn, access_mode, share_mode,
6667 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 if (hFile == INVALID_HANDLE_VALUE)
6669 goto getout;
6670 CloseHandle(hFile);
6671 }
6672
6673 retval = 0; /* success */
6674getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 return retval;
6677}
6678
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006680 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 */
6682 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006683mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006685 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01006686#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 WCHAR *wn;
6688 int f;
6689
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006690 wn = enc_to_utf16((char_u *)name, NULL);
6691 if (wn == NULL)
6692 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006694 f = _wopen(wn, flags, mode);
6695 vim_free(wn);
6696 return f;
6697#else
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006698 /* open() can open a file which name is longer than _MAX_PATH bytes
6699 * and shorter than _MAX_PATH characters successfully, but sometimes it
6700 * causes unexpected error in another part. We make it an error explicitly
6701 * here. */
6702 if (strlen(name) >= _MAX_PATH)
6703 return -1;
6704
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 return open(name, flags, mode);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006706#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707}
6708
6709/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006710 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711 */
6712 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006713mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714{
6715 WCHAR *wn, *wm;
6716 FILE *f = NULL;
6717
Bram Moolenaara12a1612019-01-24 16:39:02 +01006718#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006719 /* Work around an annoying assertion in the Microsoft debug CRT
6720 * when mode's text/binary setting doesn't match _get_fmode(). */
6721 char newMode = mode[strlen(mode) - 1];
6722 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006723
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006724 _get_fmode(&oldMode);
6725 if (newMode == 't')
6726 _set_fmode(_O_TEXT);
6727 else if (newMode == 'b')
6728 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006729#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006730 wn = enc_to_utf16((char_u *)name, NULL);
6731 wm = enc_to_utf16((char_u *)mode, NULL);
6732 if (wn != NULL && wm != NULL)
6733 f = _wfopen(wn, wm);
6734 vim_free(wn);
6735 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006736
Bram Moolenaara12a1612019-01-24 16:39:02 +01006737#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006738 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006739#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006740 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742
Bram Moolenaar071d4272004-06-13 20:20:40 +00006743/*
6744 * SUB STREAM (aka info stream) handling:
6745 *
6746 * NTFS can have sub streams for each file. Normal contents of file is
6747 * stored in the main stream, and extra contents (author information and
6748 * title and so on) can be stored in sub stream. After Windows 2000, user
6749 * can access and store those informations in sub streams via explorer's
6750 * property menuitem in right click menu. Those informations in sub streams
6751 * were lost when copying only the main stream. So we have to copy sub
6752 * streams.
6753 *
6754 * Incomplete explanation:
6755 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6756 * More useful info and an example:
6757 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6758 */
6759
6760/*
6761 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6762 * and write to stream "substream" of file "to".
6763 * Errors are ignored.
6764 */
6765 static void
6766copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6767{
6768 HANDLE hTo;
6769 WCHAR *to_name;
6770
6771 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6772 wcscpy(to_name, to);
6773 wcscat(to_name, substream);
6774
6775 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6776 FILE_ATTRIBUTE_NORMAL, NULL);
6777 if (hTo != INVALID_HANDLE_VALUE)
6778 {
6779 long done;
6780 DWORD todo;
6781 DWORD readcnt, written;
6782 char buf[4096];
6783
6784 /* Copy block of bytes at a time. Abort when something goes wrong. */
6785 for (done = 0; done < len; done += written)
6786 {
6787 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006788 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6789 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6791 FALSE, FALSE, context)
6792 || readcnt != todo
6793 || !WriteFile(hTo, buf, todo, &written, NULL)
6794 || written != todo)
6795 break;
6796 }
6797 CloseHandle(hTo);
6798 }
6799
6800 free(to_name);
6801}
6802
6803/*
6804 * Copy info streams from file "from" to file "to".
6805 */
6806 static void
6807copy_infostreams(char_u *from, char_u *to)
6808{
6809 WCHAR *fromw;
6810 WCHAR *tow;
6811 HANDLE sh;
6812 WIN32_STREAM_ID sid;
6813 int headersize;
6814 WCHAR streamname[_MAX_PATH];
6815 DWORD readcount;
6816 void *context = NULL;
6817 DWORD lo, hi;
6818 int len;
6819
6820 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006821 fromw = enc_to_utf16(from, NULL);
6822 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 if (fromw != NULL && tow != NULL)
6824 {
6825 /* Open the file for reading. */
6826 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6827 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6828 if (sh != INVALID_HANDLE_VALUE)
6829 {
6830 /* Use BackupRead() to find the info streams. Repeat until we
6831 * have done them all.*/
6832 for (;;)
6833 {
6834 /* Get the header to find the length of the stream name. If
6835 * the "readcount" is zero we have done all info streams. */
6836 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006837 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6839 &readcount, FALSE, FALSE, &context)
6840 || readcount == 0)
6841 break;
6842
6843 /* We only deal with streams that have a name. The normal
6844 * file data appears to be without a name, even though docs
6845 * suggest it is called "::$DATA". */
6846 if (sid.dwStreamNameSize > 0)
6847 {
6848 /* Read the stream name. */
6849 if (!BackupRead(sh, (LPBYTE)streamname,
6850 sid.dwStreamNameSize,
6851 &readcount, FALSE, FALSE, &context))
6852 break;
6853
6854 /* Copy an info stream with a name ":anything:$DATA".
6855 * Skip "::$DATA", it has no stream name (examples suggest
6856 * it might be used for the normal file contents).
6857 * Note that BackupRead() counts bytes, but the name is in
6858 * wide characters. */
6859 len = readcount / sizeof(WCHAR);
6860 streamname[len] = 0;
6861 if (len > 7 && wcsicmp(streamname + len - 6,
6862 L":$DATA") == 0)
6863 {
6864 streamname[len - 6] = 0;
6865 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006866 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 }
6868 }
6869
6870 /* Advance to the next stream. We might try seeking too far,
6871 * but BackupSeek() doesn't skip over stream borders, thus
6872 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006873 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 &lo, &hi, &context);
6875 }
6876
6877 /* Clear the context. */
6878 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6879
6880 CloseHandle(sh);
6881 }
6882 }
6883 vim_free(fromw);
6884 vim_free(tow);
6885}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886
6887/*
6888 * Copy file attributes from file "from" to file "to".
6889 * For Windows NT and later we copy info streams.
6890 * Always returns zero, errors are ignored.
6891 */
6892 int
6893mch_copy_file_attribute(char_u *from, char_u *to)
6894{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006896 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 return 0;
6898}
6899
6900#if defined(MYRESETSTKOFLW) || defined(PROTO)
6901/*
6902 * Recreate a destroyed stack guard page in win32.
6903 * Written by Benjamin Peterson.
6904 */
6905
6906/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006907# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908
6909/*
6910 * This function does the same thing as _resetstkoflw(), which is only
6911 * available in DevStudio .net and later.
6912 * Returns 0 for failure, 1 for success.
6913 */
6914 int
6915myresetstkoflw(void)
6916{
6917 BYTE *pStackPtr;
6918 BYTE *pGuardPage;
6919 BYTE *pStackBase;
6920 BYTE *pLowestPossiblePage;
6921 MEMORY_BASIC_INFORMATION mbi;
6922 SYSTEM_INFO si;
6923 DWORD nPageSize;
6924 DWORD dummy;
6925
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926 /* We need to know the system page size. */
6927 GetSystemInfo(&si);
6928 nPageSize = si.dwPageSize;
6929
6930 /* ...and the current stack pointer */
6931 pStackPtr = (BYTE*)_alloca(1);
6932
6933 /* ...and the base of the stack. */
6934 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6935 return 0;
6936 pStackBase = (BYTE*)mbi.AllocationBase;
6937
6938 /* ...and the page thats min_stack_req pages away from stack base; this is
6939 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006940 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006943 /* We want the first committed page in the stack Start at the stack
6944 * base and move forward through memory until we find a committed block.
6945 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 BYTE *pBlock = pStackBase;
6947
Bram Moolenaara466c992005-07-09 21:03:22 +00006948 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 {
6950 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6951 return 0;
6952
6953 pBlock += mbi.RegionSize;
6954
6955 if (mbi.State & MEM_COMMIT)
6956 break;
6957 }
6958
6959 /* mbi now describes the first committed block in the stack. */
6960 if (mbi.Protect & PAGE_GUARD)
6961 return 1;
6962
6963 /* decide where the guard page should start */
6964 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6965 pGuardPage = pLowestPossiblePage;
6966 else
6967 pGuardPage = (BYTE*)mbi.BaseAddress;
6968
6969 /* allocate the guard page */
6970 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6971 return 0;
6972
6973 /* apply the guard attribute to the page */
6974 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6975 &dummy))
6976 return 0;
6977 }
6978
6979 return 1;
6980}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006981#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006983
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984/*
6985 * The command line arguments in UCS2
6986 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006987static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006988static LPWSTR *ArglistW = NULL;
6989static int global_argc = 0;
6990static char **global_argv;
6991
6992static int used_file_argc = 0; /* last argument in global_argv[] used
6993 for the argument list. */
6994static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6995 command line arguments added to
6996 the argument list */
6997static int used_file_count = 0; /* nr of entries in used_file_indexes */
6998static int used_file_literal = FALSE; /* take file names literally */
6999static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007000static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001static int used_alist_count = 0;
7002
7003
7004/*
7005 * Get the command line arguments. Unicode version.
7006 * Returns argc. Zero when something fails.
7007 */
7008 int
7009get_cmd_argsW(char ***argvp)
7010{
7011 char **argv = NULL;
7012 int argc = 0;
7013 int i;
7014
Bram Moolenaar14993322014-09-09 12:25:33 +02007015 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007016 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7017 if (ArglistW != NULL)
7018 {
7019 argv = malloc((nArgsW + 1) * sizeof(char *));
7020 if (argv != NULL)
7021 {
7022 argc = nArgsW;
7023 argv[argc] = NULL;
7024 for (i = 0; i < argc; ++i)
7025 {
7026 int len;
7027
7028 /* Convert each Unicode argument to the current codepage. */
7029 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007030 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007031 (LPSTR *)&argv[i], &len, 0, 0);
7032 if (argv[i] == NULL)
7033 {
7034 /* Out of memory, clear everything. */
7035 while (i > 0)
7036 free(argv[--i]);
7037 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007038 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007039 argc = 0;
7040 }
7041 }
7042 }
7043 }
7044
7045 global_argc = argc;
7046 global_argv = argv;
7047 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007048 {
7049 if (used_file_indexes != NULL)
7050 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007051 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007052 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007053
7054 if (argvp != NULL)
7055 *argvp = argv;
7056 return argc;
7057}
7058
7059 void
7060free_cmd_argsW(void)
7061{
7062 if (ArglistW != NULL)
7063 {
7064 GlobalFree(ArglistW);
7065 ArglistW = NULL;
7066 }
7067}
7068
7069/*
7070 * Remember "name" is an argument that was added to the argument list.
7071 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7072 * is called.
7073 */
7074 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007075used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007076{
7077 int i;
7078
7079 if (used_file_indexes == NULL)
7080 return;
7081 for (i = used_file_argc + 1; i < global_argc; ++i)
7082 if (STRCMP(global_argv[i], name) == 0)
7083 {
7084 used_file_argc = i;
7085 used_file_indexes[used_file_count++] = i;
7086 break;
7087 }
7088 used_file_literal = literal;
7089 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007090 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007091}
7092
7093/*
7094 * Remember the length of the argument list as it was. If it changes then we
7095 * leave it alone when 'encoding' is set.
7096 */
7097 void
7098set_alist_count(void)
7099{
7100 used_alist_count = GARGCOUNT;
7101}
7102
7103/*
7104 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7105 * has been changed while starting up. Use the UCS-2 command line arguments
7106 * and convert them to 'encoding'.
7107 */
7108 void
7109fix_arg_enc(void)
7110{
7111 int i;
7112 int idx;
7113 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007114 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007115
7116 /* Safety checks:
7117 * - if argument count differs between the wide and non-wide argument
7118 * list, something must be wrong.
7119 * - the file name arguments must have been located.
7120 * - the length of the argument list wasn't changed by the user.
7121 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007122 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007123 || ArglistW == NULL
7124 || used_file_indexes == NULL
7125 || used_file_count == 0
7126 || used_alist_count != GARGCOUNT)
7127 return;
7128
Bram Moolenaar86b68352004-12-27 21:59:20 +00007129 /* Remember the buffer numbers for the arguments. */
7130 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7131 if (fnum_list == NULL)
7132 return; /* out of memory */
7133 for (i = 0; i < GARGCOUNT; ++i)
7134 fnum_list[i] = GARGLIST[i].ae_fnum;
7135
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007136 /* Clear the argument list. Make room for the new arguments. */
7137 alist_clear(&global_alist);
7138 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007139 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007140
7141 for (i = 0; i < used_file_count; ++i)
7142 {
7143 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007144 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007145 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007146 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007147 int literal = used_file_literal;
7148
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007149# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007150 /* When using diff mode may need to concatenate file name to
7151 * directory name. Just like it's done in main(). */
7152 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7153 && !mch_isdir(alist_name(&GARGLIST[0])))
7154 {
7155 char_u *r;
7156
7157 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7158 if (r != NULL)
7159 {
7160 vim_free(str);
7161 str = r;
7162 }
7163 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007164# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007165 /* Re-use the old buffer by renaming it. When not using literal
7166 * names it's done by alist_expand() below. */
7167 if (used_file_literal)
7168 buf_set_name(fnum_list[i], str);
7169
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007170 /* Check backtick literal. backtick literal is already expanded in
7171 * main.c, so this part add str as literal. */
7172 if (literal == FALSE)
7173 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007174 size_t len = STRLEN(str);
7175
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007176 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7177 literal = TRUE;
7178 }
7179 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007180 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007181 }
7182
7183 if (!used_file_literal)
7184 {
7185 /* Now expand wildcards in the arguments. */
7186 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7187 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007188 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7189 * Also, unset wildignore to not be influenced by this option.
7190 * The arguments specified in command-line should be kept even if
7191 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007192 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007193 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007194 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007195 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007196 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007197 }
7198
7199 /* If wildcard expansion failed, we are editing the first file of the
7200 * arglist and there is no file name: Edit the first argument now. */
7201 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7202 {
7203 do_cmdline_cmd((char_u *)":rewind");
7204 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007205 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007206 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007207
7208 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007209}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007210
7211 int
7212mch_setenv(char *var, char *value, int x)
7213{
7214 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007215 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007216
7217 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7218 if (envbuf == NULL)
7219 return -1;
7220
7221 sprintf((char *)envbuf, "%s=%s", var, value);
7222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007224
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007225 vim_free(envbuf);
7226 if (p == NULL)
7227 return -1;
7228 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007229#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007230 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007231#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007232 // Unlike Un*x systems, we can free the string for _wputenv().
7233 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007234
7235 return 0;
7236}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007237
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007238/*
7239 * Support for 256 colors and 24-bit colors was added in Windows 10
7240 * version 1703 (Creators update).
7241 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007242#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7243
7244/*
7245 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007246 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007247 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007248#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7249#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007250
7251 static void
7252vtp_flag_init(void)
7253{
7254 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007255#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007256 DWORD mode;
7257 HANDLE out;
7258
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007259# ifdef VIMDLL
7260 if (!gui.in_use)
7261# endif
7262 {
7263 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007264
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007265 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7266 GetConsoleMode(out, &mode);
7267 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7268 if (SetConsoleMode(out, mode) == 0)
7269 vtp_working = 0;
7270 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007271#endif
7272
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007273 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007274 conpty_working = 1;
7275 if (ver >= CONPTY_STABLE_BUILD)
7276 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007277
7278}
7279
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007280#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007281
7282 static void
7283vtp_init(void)
7284{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007285 HMODULE hKerneldll;
7286 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007287# ifdef FEAT_TERMGUICOLORS
7288 COLORREF fg, bg;
7289# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007290
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007291 /* Use functions supported from Vista */
7292 hKerneldll = GetModuleHandle("kernel32.dll");
7293 if (hKerneldll != NULL)
7294 {
7295 pGetConsoleScreenBufferInfoEx =
7296 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7297 hKerneldll, "GetConsoleScreenBufferInfoEx");
7298 pSetConsoleScreenBufferInfoEx =
7299 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7300 hKerneldll, "SetConsoleScreenBufferInfoEx");
7301 if (pGetConsoleScreenBufferInfoEx != NULL
7302 && pSetConsoleScreenBufferInfoEx != NULL)
7303 has_csbiex = TRUE;
7304 }
7305
7306 csbi.cbSize = sizeof(csbi);
7307 if (has_csbiex)
7308 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007309 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7310 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7311
7312# ifdef FEAT_TERMGUICOLORS
7313 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7314 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7315 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7316 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7317 default_console_color_bg = bg;
7318 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007319# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007320
7321 set_console_color_rgb();
7322}
7323
7324 static void
7325vtp_exit(void)
7326{
7327 reset_console_color_rgb();
7328}
7329
7330 static int
7331vtp_printf(
7332 char *format,
7333 ...)
7334{
7335 char_u buf[100];
7336 va_list list;
7337 DWORD result;
7338
7339 va_start(list, format);
7340 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7341 va_end(list);
7342 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7343 return (int)result;
7344}
7345
7346 static void
7347vtp_sgr_bulk(
7348 int arg)
7349{
7350 int args[1];
7351
7352 args[0] = arg;
7353 vtp_sgr_bulks(1, args);
7354}
7355
7356 static void
7357vtp_sgr_bulks(
7358 int argc,
7359 int *args
7360)
7361{
7362 /* 2('\033[') + 4('255.') * 16 + NUL */
7363 char_u buf[2 + (4 * 16) + 1];
7364 char_u *p;
7365 int i;
7366
7367 p = buf;
7368 *p++ = '\033';
7369 *p++ = '[';
7370
7371 for (i = 0; i < argc; ++i)
7372 {
7373 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7374 *p++ = ';';
7375 }
7376 p--;
7377 *p++ = 'm';
7378 *p = NUL;
7379 vtp_printf((char *)buf);
7380}
7381
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007382# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007383 static int
7384ctermtoxterm(
7385 int cterm)
7386{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007387 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007388
7389 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7390 return (((int)r << 16) | ((int)g << 8) | (int)b);
7391}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007392# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007393
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007394 static void
7395set_console_color_rgb(void)
7396{
7397# ifdef FEAT_TERMGUICOLORS
7398 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7399 int id;
7400 guicolor_T fg = INVALCOLOR;
7401 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007402 int ctermfg;
7403 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007404
7405 if (!USE_VTP)
7406 return;
7407
7408 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007409 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007410 syn_id2colors(id, &fg, &bg);
7411 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007412 {
7413 ctermfg = -1;
7414 if (id > 0)
7415 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007416 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7417 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007418 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007419 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007420 {
7421 ctermbg = -1;
7422 if (id > 0)
7423 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007424 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7425 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007426 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007427 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7428 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7429
7430 csbi.cbSize = sizeof(csbi);
7431 if (has_csbiex)
7432 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7433
7434 csbi.cbSize = sizeof(csbi);
7435 csbi.srWindow.Right += 1;
7436 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007437 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7438 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007439 if (has_csbiex)
7440 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7441# endif
7442}
7443
7444 static void
7445reset_console_color_rgb(void)
7446{
7447# ifdef FEAT_TERMGUICOLORS
7448 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7449
7450 csbi.cbSize = sizeof(csbi);
7451 if (has_csbiex)
7452 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7453
7454 csbi.cbSize = sizeof(csbi);
7455 csbi.srWindow.Right += 1;
7456 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007457 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7458 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007459 if (has_csbiex)
7460 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7461# endif
7462}
7463
7464 void
7465control_console_color_rgb(void)
7466{
7467 if (USE_VTP)
7468 set_console_color_rgb();
7469 else
7470 reset_console_color_rgb();
7471}
7472
7473 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007474use_vtp(void)
7475{
7476 return USE_VTP;
7477}
7478
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007479 int
7480is_term_win32(void)
7481{
7482 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7483}
7484
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007485 int
7486has_vtp_working(void)
7487{
7488 return vtp_working;
7489}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007490
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007491#endif
7492
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007493 int
7494has_conpty_working(void)
7495{
7496 return conpty_working;
7497}
7498
7499 int
7500is_conpty_stable(void)
7501{
7502 return conpty_stable;
7503}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007504
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007505#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007506 void
7507resize_console_buf(void)
7508{
7509 CONSOLE_SCREEN_BUFFER_INFO csbi;
7510 COORD coord;
7511 SMALL_RECT newsize;
7512
7513 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7514 {
7515 coord.X = SRWIDTH(csbi.srWindow);
7516 coord.Y = SRHEIGHT(csbi.srWindow);
7517 SetConsoleScreenBufferSize(g_hConOut, coord);
7518
7519 newsize.Left = 0;
7520 newsize.Top = 0;
7521 newsize.Right = coord.X - 1;
7522 newsize.Bottom = coord.Y - 1;
7523 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7524
7525 SetConsoleScreenBufferSize(g_hConOut, coord);
7526 }
7527}
7528#endif