blob: 5d4a1b10adb8ed2596b62232841371b488536388 [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
2906
2907/*
2908 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2909 * Return OK for success, FAIL for failure.
2910 */
2911 int
2912mch_dirname(
2913 char_u *buf,
2914 int len)
2915{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002916 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002917
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 /*
2919 * Originally this was:
2920 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2921 * But the Win32s known bug list says that getcwd() doesn't work
2922 * so use the Win32 system call instead. <Negri>
2923 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002924 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002926 WCHAR wcbuf[_MAX_PATH + 1];
2927 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002929 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002931 p = utf16_to_enc(wcbuf, NULL);
2932 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002933 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002934 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002936 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 }
2938 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002939 if (p == NULL)
2940 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002941
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002942 if (p != NULL)
2943 {
2944 vim_strncpy(buf, p, len - 1);
2945 vim_free(p);
2946 return OK;
2947 }
2948 }
2949 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950}
2951
2952/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002953 * Get file permissions for "name".
2954 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 */
2956 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002957mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002959 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002960 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002962 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002963 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964}
2965
2966
2967/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002968 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002969 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002970 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 */
2972 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002973mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002975 long n;
2976 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002977
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002978 p = enc_to_utf16(name, NULL);
2979 if (p == NULL)
2980 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002982 n = _wchmod(p, perm);
2983 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002984 if (n == -1)
2985 return FAIL;
2986
2987 win32_set_archive(name);
2988
2989 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990}
2991
2992/*
2993 * Set hidden flag for "name".
2994 */
2995 void
2996mch_hide(char_u *name)
2997{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002998 int attrs = win32_getattrs(name);
2999 if (attrs == -1)
3000 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003002 attrs |= FILE_ATTRIBUTE_HIDDEN;
3003 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004}
3005
3006/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003007 * Return TRUE if file "name" exists and is hidden.
3008 */
3009 int
3010mch_ishidden(char_u *name)
3011{
3012 int f = win32_getattrs(name);
3013
3014 if (f == -1)
3015 return FALSE; /* file does not exist at all */
3016
3017 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3018}
3019
3020/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 * return TRUE if "name" is a directory
3022 * return FALSE if "name" is not a directory or upon error
3023 */
3024 int
3025mch_isdir(char_u *name)
3026{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003027 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
3029 if (f == -1)
3030 return FALSE; /* file does not exist at all */
3031
3032 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3033}
3034
3035/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003036 * return TRUE if "name" is a directory, NOT a symlink to a directory
3037 * return FALSE if "name" is not a directory
3038 * return FALSE for error
3039 */
3040 int
3041mch_isrealdir(char_u *name)
3042{
3043 return mch_isdir(name) && !mch_is_symbolic_link(name);
3044}
3045
3046/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003047 * Create directory "name".
3048 * Return 0 on success, -1 on error.
3049 */
3050 int
3051mch_mkdir(char_u *name)
3052{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003053 WCHAR *p;
3054 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003055
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003056 p = enc_to_utf16(name, NULL);
3057 if (p == NULL)
3058 return -1;
3059 retval = _wmkdir(p);
3060 vim_free(p);
3061 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003062}
3063
3064/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003065 * Delete directory "name".
3066 * Return 0 on success, -1 on error.
3067 */
3068 int
3069mch_rmdir(char_u *name)
3070{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003071 WCHAR *p;
3072 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003073
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003074 p = enc_to_utf16(name, NULL);
3075 if (p == NULL)
3076 return -1;
3077 retval = _wrmdir(p);
3078 vim_free(p);
3079 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003080}
3081
3082/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003083 * Return TRUE if file "fname" has more than one link.
3084 */
3085 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003086mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003087{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003088 BY_HANDLE_FILE_INFORMATION info;
3089
3090 return win32_fileinfo(fname, &info) == FILEINFO_OK
3091 && info.nNumberOfLinks > 1;
3092}
3093
3094/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003095 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096 */
3097 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003098mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003099{
3100 HANDLE hFind;
3101 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003102 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003103 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003104 WIN32_FIND_DATAW findDataW;
3105
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003106 wn = enc_to_utf16(name, NULL);
3107 if (wn == NULL)
3108 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003109
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003110 hFind = FindFirstFileW(wn, &findDataW);
3111 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003112 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003113 {
3114 fileFlags = findDataW.dwFileAttributes;
3115 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003116 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003117 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003118
3119 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003120 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3121 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003122 res = TRUE;
3123
3124 return res;
3125}
3126
3127/*
3128 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3129 * link.
3130 */
3131 int
3132mch_is_linked(char_u *fname)
3133{
3134 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3135 return TRUE;
3136 return FALSE;
3137}
3138
3139/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003140 * Get the by-handle-file-information for "fname".
3141 * Returns FILEINFO_OK when OK.
3142 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3143 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3144 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3145 */
3146 int
3147win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3148{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003149 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003150 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003151 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003152
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003153 wn = enc_to_utf16(fname, NULL);
3154 if (wn == NULL)
3155 return FILEINFO_ENC_FAIL;
3156
3157 hFile = CreateFileW(wn, // file name
3158 GENERIC_READ, // access mode
3159 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3160 NULL, // security descriptor
3161 OPEN_EXISTING, // creation disposition
3162 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3163 NULL); // handle to template file
3164 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003165
3166 if (hFile != INVALID_HANDLE_VALUE)
3167 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003168 if (GetFileInformationByHandle(hFile, info) != 0)
3169 res = FILEINFO_OK;
3170 else
3171 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003172 CloseHandle(hFile);
3173 }
3174
Bram Moolenaar03f48552006-02-28 23:52:23 +00003175 return res;
3176}
3177
3178/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003179 * get file attributes for `name'
3180 * -1 : error
3181 * else FILE_ATTRIBUTE_* defined in winnt.h
3182 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003183 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003184win32_getattrs(char_u *name)
3185{
3186 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003187 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003189 p = enc_to_utf16(name, NULL);
3190 if (p == NULL)
3191 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003192
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003193 attr = GetFileAttributesW(p);
3194 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003195
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003196 return attr;
3197}
3198
3199/*
3200 * set file attributes for `name' to `attrs'
3201 *
3202 * return -1 for failure, 0 otherwise
3203 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003204 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205win32_setattrs(char_u *name, int attrs)
3206{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003207 int res;
3208 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003210 p = enc_to_utf16(name, NULL);
3211 if (p == NULL)
3212 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003213
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003214 res = SetFileAttributesW(p, attrs);
3215 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003216
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217 return res ? 0 : -1;
3218}
3219
3220/*
3221 * Set archive flag for "name".
3222 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003223 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224win32_set_archive(char_u *name)
3225{
3226 int attrs = win32_getattrs(name);
3227 if (attrs == -1)
3228 return -1;
3229
3230 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3231 return win32_setattrs(name, attrs);
3232}
3233
3234/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 * Return TRUE if file or directory "name" is writable (not readonly).
3236 * Strange semantics of Win32: a readonly directory is writable, but you can't
3237 * delete a file. Let's say this means it is writable.
3238 */
3239 int
3240mch_writable(char_u *name)
3241{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003242 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3245 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246}
3247
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003249 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003250 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003251 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3252 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253 */
3254 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003255mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256{
Bram Moolenaar86621892019-03-30 21:51:28 +01003257 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3258 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3259 // UTF-8.
3260 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003261 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003262 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003263
Bram Moolenaar86621892019-03-30 21:51:28 +01003264 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003265 return FALSE;
3266
Bram Moolenaar86621892019-03-30 21:51:28 +01003267 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003268 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003269 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003270 return TRUE;
3271
3272 /*
3273 * Loop over all extensions in $PATHEXT.
3274 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003275 p = mch_getenv("PATHEXT");
3276 if (p == NULL)
3277 p = (char_u *)".com;.exe;.bat;.cmd";
3278 saved = vim_strsave(p);
3279 if (saved == NULL)
3280 return FALSE;
3281 p = saved;
3282 while (*p)
3283 {
3284 char_u *tmp = vim_strchr(p, ';');
3285
3286 if (tmp != NULL)
3287 *tmp = NUL;
3288 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3289 && executable_exists((char *)name, path, use_path))
3290 {
3291 vim_free(saved);
3292 return TRUE;
3293 }
3294 if (tmp == NULL)
3295 break;
3296 p = tmp + 1;
3297 }
3298 vim_free(saved);
3299
Bram Moolenaar86621892019-03-30 21:51:28 +01003300 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003301 p = mch_getenv("PATHEXT");
3302 if (p == NULL)
3303 p = (char_u *)".com;.exe;.bat;.cmd";
3304 while (*p)
3305 {
3306 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3307 {
3308 /* A single "." means no extension is added. */
3309 buf[len] = NUL;
3310 ++p;
3311 if (*p)
3312 ++p;
3313 }
3314 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003315 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003316 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003317 return TRUE;
3318 }
3319 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321
3322/*
3323 * Check what "name" is:
3324 * NODE_NORMAL: file or directory (or doesn't exist)
3325 * NODE_WRITABLE: writable device, socket, fifo, etc.
3326 * NODE_OTHER: non-writable things
3327 */
3328 int
3329mch_nodetype(char_u *name)
3330{
3331 HANDLE hFile;
3332 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003333 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334
Bram Moolenaar043545e2006-10-10 16:44:07 +00003335 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3336 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3337 * here. */
3338 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3339 return NODE_WRITABLE;
3340
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003341 wn = enc_to_utf16(name, NULL);
3342 if (wn == NULL)
3343 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003344
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003345 hFile = CreateFileW(wn, // file name
3346 GENERIC_WRITE, // access mode
3347 0, // share mode
3348 NULL, // security descriptor
3349 OPEN_EXISTING, // creation disposition
3350 0, // file attributes
3351 NULL); // handle to template file
3352 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 if (hFile == INVALID_HANDLE_VALUE)
3354 return NODE_NORMAL;
3355
3356 type = GetFileType(hFile);
3357 CloseHandle(hFile);
3358 if (type == FILE_TYPE_CHAR)
3359 return NODE_WRITABLE;
3360 if (type == FILE_TYPE_DISK)
3361 return NODE_NORMAL;
3362 return NODE_OTHER;
3363}
3364
3365#ifdef HAVE_ACL
3366struct my_acl
3367{
3368 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3369 PSID pSidOwner;
3370 PSID pSidGroup;
3371 PACL pDacl;
3372 PACL pSacl;
3373};
3374#endif
3375
3376/*
3377 * Return a pointer to the ACL of file "fname" in allocated memory.
3378 * Return NULL if the ACL is not available for whatever reason.
3379 */
3380 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003381mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382{
3383#ifndef HAVE_ACL
3384 return (vim_acl_T)NULL;
3385#else
3386 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003387 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003389 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3390 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003392 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003393
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003394 wn = enc_to_utf16(fname, NULL);
3395 if (wn == NULL)
3396 return NULL;
3397
3398 // Try to retrieve the entire security descriptor.
3399 err = GetNamedSecurityInfoW(
3400 wn, // Abstract filename
3401 SE_FILE_OBJECT, // File Object
3402 OWNER_SECURITY_INFORMATION |
3403 GROUP_SECURITY_INFORMATION |
3404 DACL_SECURITY_INFORMATION |
3405 SACL_SECURITY_INFORMATION,
3406 &p->pSidOwner, // Ownership information.
3407 &p->pSidGroup, // Group membership.
3408 &p->pDacl, // Discretionary information.
3409 &p->pSacl, // For auditing purposes.
3410 &p->pSecurityDescriptor);
3411 if (err == ERROR_ACCESS_DENIED ||
3412 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003413 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003414 // Retrieve only DACL.
3415 (void)GetNamedSecurityInfoW(
3416 wn,
3417 SE_FILE_OBJECT,
3418 DACL_SECURITY_INFORMATION,
3419 NULL,
3420 NULL,
3421 &p->pDacl,
3422 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003423 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003424 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003425 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003426 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003427 mch_free_acl((vim_acl_T)p);
3428 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003430 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431 }
3432
3433 return (vim_acl_T)p;
3434#endif
3435}
3436
Bram Moolenaar27515922013-06-29 15:36:26 +02003437#ifdef HAVE_ACL
3438/*
3439 * Check if "acl" contains inherited ACE.
3440 */
3441 static BOOL
3442is_acl_inherited(PACL acl)
3443{
3444 DWORD i;
3445 ACL_SIZE_INFORMATION acl_info;
3446 PACCESS_ALLOWED_ACE ace;
3447
3448 acl_info.AceCount = 0;
3449 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3450 for (i = 0; i < acl_info.AceCount; i++)
3451 {
3452 GetAce(acl, i, (LPVOID *)&ace);
3453 if (ace->Header.AceFlags & INHERITED_ACE)
3454 return TRUE;
3455 }
3456 return FALSE;
3457}
3458#endif
3459
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460/*
3461 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3462 * Errors are ignored.
3463 * This must only be called with "acl" equal to what mch_get_acl() returned.
3464 */
3465 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003466mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467{
3468#ifdef HAVE_ACL
3469 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003470 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003471 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003473 if (p == NULL)
3474 return;
3475
3476 wn = enc_to_utf16(fname, NULL);
3477 if (wn == NULL)
3478 return;
3479
3480 // Set security flags
3481 if (p->pSidOwner)
3482 sec_info |= OWNER_SECURITY_INFORMATION;
3483 if (p->pSidGroup)
3484 sec_info |= GROUP_SECURITY_INFORMATION;
3485 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003486 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003487 sec_info |= DACL_SECURITY_INFORMATION;
3488 // Do not inherit its parent's DACL.
3489 // If the DACL is inherited, Cygwin permissions would be changed.
3490 if (!is_acl_inherited(p->pDacl))
3491 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003492 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003493 if (p->pSacl)
3494 sec_info |= SACL_SECURITY_INFORMATION;
3495
3496 (void)SetNamedSecurityInfoW(
3497 wn, // Abstract filename
3498 SE_FILE_OBJECT, // File Object
3499 sec_info,
3500 p->pSidOwner, // Ownership information.
3501 p->pSidGroup, // Group membership.
3502 p->pDacl, // Discretionary information.
3503 p->pSacl // For auditing purposes.
3504 );
3505 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506#endif
3507}
3508
3509 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003510mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511{
3512#ifdef HAVE_ACL
3513 struct my_acl *p = (struct my_acl *)acl;
3514
3515 if (p != NULL)
3516 {
3517 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3518 vim_free(p);
3519 }
3520#endif
3521}
3522
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003523#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524
3525/*
3526 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3527 */
3528 static BOOL WINAPI
3529handler_routine(
3530 DWORD dwCtrlType)
3531{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003532 INPUT_RECORD ir;
3533 DWORD out;
3534
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 switch (dwCtrlType)
3536 {
3537 case CTRL_C_EVENT:
3538 if (ctrl_c_interrupts)
3539 g_fCtrlCPressed = TRUE;
3540 return TRUE;
3541
3542 case CTRL_BREAK_EVENT:
3543 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003544 ctrl_break_was_pressed = TRUE;
3545 /* ReadConsoleInput is blocking, send a key event to continue. */
3546 ir.EventType = KEY_EVENT;
3547 ir.Event.KeyEvent.bKeyDown = TRUE;
3548 ir.Event.KeyEvent.wRepeatCount = 1;
3549 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3550 ir.Event.KeyEvent.wVirtualScanCode = 0;
3551 ir.Event.KeyEvent.dwControlKeyState = 0;
3552 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3553 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 return TRUE;
3555
3556 /* fatal events: shut down gracefully */
3557 case CTRL_CLOSE_EVENT:
3558 case CTRL_LOGOFF_EVENT:
3559 case CTRL_SHUTDOWN_EVENT:
3560 windgoto((int)Rows - 1, 0);
3561 g_fForceExit = TRUE;
3562
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003563 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564 (dwCtrlType == CTRL_CLOSE_EVENT
3565 ? _("close")
3566 : dwCtrlType == CTRL_LOGOFF_EVENT
3567 ? _("logoff")
3568 : _("shutdown")));
3569#ifdef DEBUG
3570 OutputDebugString(IObuff);
3571#endif
3572
3573 preserve_exit(); /* output IObuff, preserve files and exit */
3574
3575 return TRUE; /* not reached */
3576
3577 default:
3578 return FALSE;
3579 }
3580}
3581
3582
3583/*
3584 * set the tty in (raw) ? "raw" : "cooked" mode
3585 */
3586 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003587mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588{
3589 DWORD cmodein;
3590 DWORD cmodeout;
3591 BOOL bEnableHandler;
3592
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003593# ifdef VIMDLL
3594 if (gui.in_use)
3595 return;
3596# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597 GetConsoleMode(g_hConIn, &cmodein);
3598 GetConsoleMode(g_hConOut, &cmodeout);
3599 if (tmode == TMODE_RAW)
3600 {
3601 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3602 ENABLE_ECHO_INPUT);
3603#ifdef FEAT_MOUSE
3604 if (g_fMouseActive)
3605 cmodein |= ENABLE_MOUSE_INPUT;
3606#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003607 cmodeout &= ~(
3608#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003609 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003610 * VTP. */
3611 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3612#else
3613 ENABLE_PROCESSED_OUTPUT |
3614#endif
3615 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 bEnableHandler = TRUE;
3617 }
3618 else /* cooked */
3619 {
3620 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3621 ENABLE_ECHO_INPUT);
3622 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3623 bEnableHandler = FALSE;
3624 }
3625 SetConsoleMode(g_hConIn, cmodein);
3626 SetConsoleMode(g_hConOut, cmodeout);
3627 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3628
3629#ifdef MCH_WRITE_DUMP
3630 if (fdDump)
3631 {
3632 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3633 tmode == TMODE_RAW ? "raw" :
3634 tmode == TMODE_COOK ? "cooked" : "normal",
3635 cmodein, cmodeout);
3636 fflush(fdDump);
3637 }
3638#endif
3639}
3640
3641
3642/*
3643 * Get the size of the current window in `Rows' and `Columns'
3644 * Return OK when size could be determined, FAIL otherwise.
3645 */
3646 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003647mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648{
3649 CONSOLE_SCREEN_BUFFER_INFO csbi;
3650
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003651# ifdef VIMDLL
3652 if (gui.in_use)
3653 return OK;
3654# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3656 {
3657 /*
3658 * For some reason, we are trying to get the screen dimensions
3659 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3660 * variables are really intended to mean the size of Vim screen
3661 * while in termcap mode.
3662 */
3663 Rows = g_cbTermcap.Info.dwSize.Y;
3664 Columns = g_cbTermcap.Info.dwSize.X;
3665 }
3666 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3667 {
3668 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3669 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3670 }
3671 else
3672 {
3673 Rows = 25;
3674 Columns = 80;
3675 }
3676 return OK;
3677}
3678
3679/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003680 * Resize console buffer to 'COORD'
3681 */
3682 static void
3683ResizeConBuf(
3684 HANDLE hConsole,
3685 COORD coordScreen)
3686{
3687 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3688 {
3689#ifdef MCH_WRITE_DUMP
3690 if (fdDump)
3691 {
3692 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3693 GetLastError());
3694 fflush(fdDump);
3695 }
3696#endif
3697 }
3698}
3699
3700/*
3701 * Resize console window size to 'srWindowRect'
3702 */
3703 static void
3704ResizeWindow(
3705 HANDLE hConsole,
3706 SMALL_RECT srWindowRect)
3707{
3708 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3709 {
3710#ifdef MCH_WRITE_DUMP
3711 if (fdDump)
3712 {
3713 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3714 GetLastError());
3715 fflush(fdDump);
3716 }
3717#endif
3718 }
3719}
3720
3721/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 * Set a console window to `xSize' * `ySize'
3723 */
3724 static void
3725ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003726 HANDLE hConsole,
3727 int xSize,
3728 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729{
3730 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3731 SMALL_RECT srWindowRect; /* hold the new console size */
3732 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003733 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734
3735#ifdef MCH_WRITE_DUMP
3736 if (fdDump)
3737 {
3738 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3739 fflush(fdDump);
3740 }
3741#endif
3742
3743 /* get the largest size we can size the console window to */
3744 coordScreen = GetLargestConsoleWindowSize(hConsole);
3745
3746 /* define the new console window size and scroll position */
3747 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3748 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3749 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3750
3751 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3752 {
3753 int sx, sy;
3754
3755 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3756 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3757 if (sy < ySize || sx < xSize)
3758 {
3759 /*
3760 * Increasing number of lines/columns, do buffer first.
3761 * Use the maximal size in x and y direction.
3762 */
3763 if (sy < ySize)
3764 coordScreen.Y = ySize;
3765 else
3766 coordScreen.Y = sy;
3767 if (sx < xSize)
3768 coordScreen.X = xSize;
3769 else
3770 coordScreen.X = sx;
3771 SetConsoleScreenBufferSize(hConsole, coordScreen);
3772 }
3773 }
3774
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003775 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776 coordScreen.X = xSize;
3777 coordScreen.Y = ySize;
3778
Bram Moolenaar2551c032018-08-23 22:38:31 +02003779 // In the new console call API, only the first time in reverse order
3780 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003782 ResizeWindow(hConsole, srWindowRect);
3783 ResizeConBuf(hConsole, coordScreen);
3784 }
3785 else
3786 {
3787 ResizeConBuf(hConsole, coordScreen);
3788 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003789 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 }
3791}
3792
3793
3794/*
3795 * Set the console window to `Rows' * `Columns'
3796 */
3797 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003798mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799{
3800 COORD coordScreen;
3801
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003802# ifdef VIMDLL
3803 if (gui.in_use)
3804 return;
3805# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 /* Don't change window size while still starting up */
3807 if (suppress_winsize != 0)
3808 {
3809 suppress_winsize = 2;
3810 return;
3811 }
3812
3813 if (term_console)
3814 {
3815 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3816
3817 /* Clamp Rows and Columns to reasonable values */
3818 if (Rows > coordScreen.Y)
3819 Rows = coordScreen.Y;
3820 if (Columns > coordScreen.X)
3821 Columns = coordScreen.X;
3822
3823 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3824 }
3825}
3826
3827/*
3828 * Rows and/or Columns has changed.
3829 */
3830 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003831mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003833# ifdef VIMDLL
3834 if (gui.in_use)
3835 return;
3836# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3838}
3839
3840
3841/*
3842 * Called when started up, to set the winsize that was delayed.
3843 */
3844 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003845mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846{
3847 if (suppress_winsize == 2)
3848 {
3849 suppress_winsize = 0;
3850 mch_set_shellsize();
3851 shell_resized();
3852 }
3853 suppress_winsize = 0;
3854}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003855#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003857 static BOOL
3858vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003859 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003860 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003861 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003862 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003863 PROCESS_INFORMATION *pi,
3864 LPVOID *env,
3865 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003866{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003867 BOOL ret = FALSE;
3868 WCHAR *wcmd, *wcwd = NULL;
3869
3870 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3871 if (wcmd == NULL)
3872 return FALSE;
3873 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003874 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003875 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3876 if (wcwd == NULL)
3877 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003878 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003879
3880 ret = CreateProcessW(
3881 NULL, // Executable name
3882 wcmd, // Command to execute
3883 NULL, // Process security attributes
3884 NULL, // Thread security attributes
3885 inherit_handles, // Inherit handles
3886 flags, // Creation flags
3887 env, // Environment
3888 wcwd, // Current directory
3889 (LPSTARTUPINFOW)si, // Startup information
3890 pi); // Process information
3891theend:
3892 vim_free(wcmd);
3893 vim_free(wcwd);
3894 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003895}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896
3897
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003898 static HINSTANCE
3899vim_shell_execute(
3900 char *cmd,
3901 INT n_show_cmd)
3902{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003903 HINSTANCE ret;
3904 WCHAR *wcmd;
3905
3906 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3907 if (wcmd == NULL)
3908 return (HINSTANCE) 0;
3909
3910 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3911 vim_free(wcmd);
3912 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003913}
3914
3915
Bram Moolenaar4f974752019-02-17 17:44:42 +01003916#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917
3918/*
3919 * Specialised version of system() for Win32 GUI mode.
3920 * This version proceeds as follows:
3921 * 1. Create a console window for use by the subprocess
3922 * 2. Run the subprocess (it gets the allocated console by default)
3923 * 3. Wait for the subprocess to terminate and get its exit code
3924 * 4. Prompt the user to press a key to close the console window
3925 */
3926 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003927mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928{
3929 STARTUPINFO si;
3930 PROCESS_INFORMATION pi;
3931 DWORD ret = 0;
3932 HWND hwnd = GetFocus();
3933
3934 si.cb = sizeof(si);
3935 si.lpReserved = NULL;
3936 si.lpDesktop = NULL;
3937 si.lpTitle = NULL;
3938 si.dwFlags = STARTF_USESHOWWINDOW;
3939 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003940 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003941 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003943 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003944 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 else
3946 si.wShowWindow = SW_SHOWNORMAL;
3947 si.cbReserved2 = 0;
3948 si.lpReserved2 = NULL;
3949
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003951 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003952 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3953 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954
3955 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 {
3957#ifdef FEAT_GUI
3958 int delay = 1;
3959
3960 /* Keep updating the window while waiting for the shell to finish. */
3961 for (;;)
3962 {
3963 MSG msg;
3964
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003965 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 {
3967 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003968 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003969 delay = 1;
3970 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 }
3972 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3973 break;
3974
3975 /* We start waiting for a very short time and then increase it, so
3976 * that we respond quickly when the process is quick, and don't
3977 * consume too much overhead when it's slow. */
3978 if (delay < 50)
3979 delay += 10;
3980 }
3981#else
3982 WaitForSingleObject(pi.hProcess, INFINITE);
3983#endif
3984
3985 /* Get the command exit code */
3986 GetExitCodeProcess(pi.hProcess, &ret);
3987 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988
3989 /* Close the handles to the subprocess, so that it goes away */
3990 CloseHandle(pi.hThread);
3991 CloseHandle(pi.hProcess);
3992
3993 /* Try to get input focus back. Doesn't always work though. */
3994 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3995
3996 return ret;
3997}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003998
3999/*
4000 * Thread launched by the gui to send the current buffer data to the
4001 * process. This way avoid to hang up vim totally if the children
4002 * process take a long time to process the lines.
4003 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004004 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004005sub_process_writer(LPVOID param)
4006{
4007 HANDLE g_hChildStd_IN_Wr = param;
4008 linenr_T lnum = curbuf->b_op_start.lnum;
4009 DWORD len = 0;
4010 DWORD l;
4011 char_u *lp = ml_get(lnum);
4012 char_u *s;
4013 int written = 0;
4014
4015 for (;;)
4016 {
4017 l = (DWORD)STRLEN(lp + written);
4018 if (l == 0)
4019 len = 0;
4020 else if (lp[written] == NL)
4021 {
4022 /* NL -> NUL translation */
4023 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4024 }
4025 else
4026 {
4027 s = vim_strchr(lp + written, NL);
4028 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4029 s == NULL ? l : (DWORD)(s - (lp + written)),
4030 &len, NULL);
4031 }
4032 if (len == (int)l)
4033 {
4034 /* Finished a line, add a NL, unless this line should not have
4035 * one. */
4036 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004037 || (!curbuf->b_p_bin
4038 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004039 || (lnum != curbuf->b_no_eol_lnum
4040 && (lnum != curbuf->b_ml.ml_line_count
4041 || curbuf->b_p_eol)))
4042 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004043 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4044 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004045 }
4046
4047 ++lnum;
4048 if (lnum > curbuf->b_op_end.lnum)
4049 break;
4050
4051 lp = ml_get(lnum);
4052 written = 0;
4053 }
4054 else if (len > 0)
4055 written += len;
4056 }
4057
4058 /* finished all the lines, close pipe */
4059 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004060 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004061}
4062
4063
4064# define BUFLEN 100 /* length for buffer, stolen from unix version */
4065
4066/*
4067 * This function read from the children's stdout and write the
4068 * data on screen or in the buffer accordingly.
4069 */
4070 static void
4071dump_pipe(int options,
4072 HANDLE g_hChildStd_OUT_Rd,
4073 garray_T *ga,
4074 char_u buffer[],
4075 DWORD *buffer_off)
4076{
4077 DWORD availableBytes = 0;
4078 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004079 int ret;
4080 DWORD len;
4081 DWORD toRead;
4082 int repeatCount;
4083
4084 /* we query the pipe to see if there is any data to read
4085 * to avoid to perform a blocking read */
4086 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4087 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004088 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004089 NULL, /* number of read bytes */
4090 &availableBytes, /* available bytes total */
4091 NULL); /* byteLeft */
4092
4093 repeatCount = 0;
4094 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004095 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004096 {
4097 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004098 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004099 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004100 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004101
4102 /* If we haven't read anything, there is a problem */
4103 if (len == 0)
4104 break;
4105
4106 availableBytes -= len;
4107
4108 if (options & SHELL_READ)
4109 {
4110 /* Do NUL -> NL translation, append NL separated
4111 * lines to the current buffer. */
4112 for (i = 0; i < len; ++i)
4113 {
4114 if (buffer[i] == NL)
4115 append_ga_line(ga);
4116 else if (buffer[i] == NUL)
4117 ga_append(ga, NL);
4118 else
4119 ga_append(ga, buffer[i]);
4120 }
4121 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004122 else if (has_mbyte)
4123 {
4124 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004125 int c;
4126 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004127
4128 len += *buffer_off;
4129 buffer[len] = NUL;
4130
4131 /* Check if the last character in buffer[] is
4132 * incomplete, keep these bytes for the next
4133 * round. */
4134 for (p = buffer; p < buffer + len; p += l)
4135 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004136 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004137 if (l == 0)
4138 l = 1; /* NUL byte? */
4139 else if (MB_BYTE2LEN(*p) != l)
4140 break;
4141 }
4142 if (p == buffer) /* no complete character */
4143 {
4144 /* avoid getting stuck at an illegal byte */
4145 if (len >= 12)
4146 ++p;
4147 else
4148 {
4149 *buffer_off = len;
4150 return;
4151 }
4152 }
4153 c = *p;
4154 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004155 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004156 if (p < buffer + len)
4157 {
4158 *p = c;
4159 *buffer_off = (DWORD)((buffer + len) - p);
4160 mch_memmove(buffer, p, *buffer_off);
4161 return;
4162 }
4163 *buffer_off = 0;
4164 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004165 else
4166 {
4167 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004168 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004169 }
4170
4171 windgoto(msg_row, msg_col);
4172 cursor_on();
4173 out_flush();
4174 }
4175}
4176
4177/*
4178 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4179 * for communication and doesn't open any new window.
4180 */
4181 static int
4182mch_system_piped(char *cmd, int options)
4183{
4184 STARTUPINFO si;
4185 PROCESS_INFORMATION pi;
4186 DWORD ret = 0;
4187
4188 HANDLE g_hChildStd_IN_Rd = NULL;
4189 HANDLE g_hChildStd_IN_Wr = NULL;
4190 HANDLE g_hChildStd_OUT_Rd = NULL;
4191 HANDLE g_hChildStd_OUT_Wr = NULL;
4192
4193 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4194 DWORD len;
4195
4196 /* buffer used to receive keys */
4197 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4198 int ta_len = 0; /* valid bytes in ta_buf[] */
4199
4200 DWORD i;
4201 int c;
4202 int noread_cnt = 0;
4203 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004204 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004205 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004206 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004207
4208 SECURITY_ATTRIBUTES saAttr;
4209
4210 /* Set the bInheritHandle flag so pipe handles are inherited. */
4211 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4212 saAttr.bInheritHandle = TRUE;
4213 saAttr.lpSecurityDescriptor = NULL;
4214
4215 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4216 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004217 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004218 /* Create a pipe for the child process's STDIN. */
4219 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4220 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004221 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222 {
4223 CloseHandle(g_hChildStd_IN_Rd);
4224 CloseHandle(g_hChildStd_IN_Wr);
4225 CloseHandle(g_hChildStd_OUT_Rd);
4226 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004227 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004228 }
4229
4230 si.cb = sizeof(si);
4231 si.lpReserved = NULL;
4232 si.lpDesktop = NULL;
4233 si.lpTitle = NULL;
4234 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4235
4236 /* set-up our file redirection */
4237 si.hStdError = g_hChildStd_OUT_Wr;
4238 si.hStdOutput = g_hChildStd_OUT_Wr;
4239 si.hStdInput = g_hChildStd_IN_Rd;
4240 si.wShowWindow = SW_HIDE;
4241 si.cbReserved2 = 0;
4242 si.lpReserved2 = NULL;
4243
4244 if (options & SHELL_READ)
4245 ga_init2(&ga, 1, BUFLEN);
4246
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004247 if (cmd != NULL)
4248 {
4249 p = (char *)vim_strsave((char_u *)cmd);
4250 if (p != NULL)
4251 unescape_shellxquote((char_u *)p, p_sxe);
4252 else
4253 p = cmd;
4254 }
4255
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004256 /* Now, run the command.
4257 * About "Inherit handles" being TRUE: this command can be litigious,
4258 * handle inheritance was deactivated for pending temp file, but, if we
4259 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004260 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4261 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004263 if (p != cmd)
4264 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004265
4266 /* Close our unused side of the pipes */
4267 CloseHandle(g_hChildStd_IN_Rd);
4268 CloseHandle(g_hChildStd_OUT_Wr);
4269
4270 if (options & SHELL_WRITE)
4271 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004272 HANDLE thread = (HANDLE)
4273 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274 0, /* default stack size */
4275 sub_process_writer, /* function to be executed */
4276 g_hChildStd_IN_Wr, /* parameter */
4277 0, /* creation flag, start immediately */
4278 NULL); /* we don't care about thread id */
4279 CloseHandle(thread);
4280 g_hChildStd_IN_Wr = NULL;
4281 }
4282
4283 /* Keep updating the window while waiting for the shell to finish. */
4284 for (;;)
4285 {
4286 MSG msg;
4287
Bram Moolenaar175d0702013-12-11 18:36:33 +01004288 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 {
4290 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004291 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004292 }
4293
4294 /* write pipe information in the window */
4295 if ((options & (SHELL_READ|SHELL_WRITE))
4296# ifdef FEAT_GUI
4297 || gui.in_use
4298# endif
4299 )
4300 {
4301 len = 0;
4302 if (!(options & SHELL_EXPAND)
4303 && ((options &
4304 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4305 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4306# ifdef FEAT_GUI
4307 || gui.in_use
4308# endif
4309 )
4310 && (ta_len > 0 || noread_cnt > 4))
4311 {
4312 if (ta_len == 0)
4313 {
4314 /* Get extra characters when we don't have any. Reset the
4315 * counter and timer. */
4316 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004317 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4318 }
4319 if (ta_len > 0 || len > 0)
4320 {
4321 /*
4322 * For pipes: Check for CTRL-C: send interrupt signal to
4323 * child. Check for CTRL-D: EOF, close pipe to child.
4324 */
4325 if (len == 1 && cmd != NULL)
4326 {
4327 if (ta_buf[ta_len] == Ctrl_C)
4328 {
4329 /* Learn what exit code is expected, for
4330 * now put 9 as SIGKILL */
4331 TerminateProcess(pi.hProcess, 9);
4332 }
4333 if (ta_buf[ta_len] == Ctrl_D)
4334 {
4335 CloseHandle(g_hChildStd_IN_Wr);
4336 g_hChildStd_IN_Wr = NULL;
4337 }
4338 }
4339
4340 /* replace K_BS by <BS> and K_DEL by <DEL> */
4341 for (i = ta_len; i < ta_len + len; ++i)
4342 {
4343 if (ta_buf[i] == CSI && len - i > 2)
4344 {
4345 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4346 if (c == K_DEL || c == K_KDEL || c == K_BS)
4347 {
4348 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4349 (size_t)(len - i - 2));
4350 if (c == K_DEL || c == K_KDEL)
4351 ta_buf[i] = DEL;
4352 else
4353 ta_buf[i] = Ctrl_H;
4354 len -= 2;
4355 }
4356 }
4357 else if (ta_buf[i] == '\r')
4358 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004359 if (has_mbyte)
4360 i += (*mb_ptr2len_len)(ta_buf + i,
4361 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004362 }
4363
4364 /*
4365 * For pipes: echo the typed characters. For a pty this
4366 * does not seem to work.
4367 */
4368 for (i = ta_len; i < ta_len + len; ++i)
4369 {
4370 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4371 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372 else if (has_mbyte)
4373 {
4374 int l = (*mb_ptr2len)(ta_buf + i);
4375
4376 msg_outtrans_len(ta_buf + i, l);
4377 i += l - 1;
4378 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004379 else
4380 msg_outtrans_len(ta_buf + i, 1);
4381 }
4382 windgoto(msg_row, msg_col);
4383 out_flush();
4384
4385 ta_len += len;
4386
4387 /*
4388 * Write the characters to the child, unless EOF has been
4389 * typed for pipes. Write one character at a time, to
4390 * avoid losing too much typeahead. When writing buffer
4391 * lines, drop the typed characters (only check for
4392 * CTRL-C).
4393 */
4394 if (options & SHELL_WRITE)
4395 ta_len = 0;
4396 else if (g_hChildStd_IN_Wr != NULL)
4397 {
4398 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4399 1, &len, NULL);
4400 // if we are typing in, we want to keep things reactive
4401 delay = 1;
4402 if (len > 0)
4403 {
4404 ta_len -= len;
4405 mch_memmove(ta_buf, ta_buf + len, ta_len);
4406 }
4407 }
4408 }
4409 }
4410 }
4411
4412 if (ta_len)
4413 ui_inchar_undo(ta_buf, ta_len);
4414
4415 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4416 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004417 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004418 break;
4419 }
4420
4421 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004422 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004423
4424 /* We start waiting for a very short time and then increase it, so
4425 * that we respond quickly when the process is quick, and don't
4426 * consume too much overhead when it's slow. */
4427 if (delay < 50)
4428 delay += 10;
4429 }
4430
4431 /* Close the pipe */
4432 CloseHandle(g_hChildStd_OUT_Rd);
4433 if (g_hChildStd_IN_Wr != NULL)
4434 CloseHandle(g_hChildStd_IN_Wr);
4435
4436 WaitForSingleObject(pi.hProcess, INFINITE);
4437
4438 /* Get the command exit code */
4439 GetExitCodeProcess(pi.hProcess, &ret);
4440
4441 if (options & SHELL_READ)
4442 {
4443 if (ga.ga_len > 0)
4444 {
4445 append_ga_line(&ga);
4446 /* remember that the NL was missing */
4447 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4448 }
4449 else
4450 curbuf->b_no_eol_lnum = 0;
4451 ga_clear(&ga);
4452 }
4453
4454 /* Close the handles to the subprocess, so that it goes away */
4455 CloseHandle(pi.hThread);
4456 CloseHandle(pi.hProcess);
4457
4458 return ret;
4459}
4460
4461 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004462mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463{
4464 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004465 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 return mch_system_piped(cmd, options);
4467 else
4468 return mch_system_classic(cmd, options);
4469}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004470#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004472#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004473 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004474mch_system_c(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004475{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004476 int ret;
4477 WCHAR *wcmd;
4478
4479 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4480 if (wcmd == NULL)
4481 return -1;
4482
4483 ret = _wsystem(wcmd);
4484 vim_free(wcmd);
4485 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004486}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
4488#endif
4489
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004490 static int
4491mch_system(char *cmd, int options)
4492{
4493#ifdef VIMDLL
4494 if (gui.in_use)
4495 return mch_system_g(cmd, options);
4496 else
4497 return mch_system_c(cmd, options);
4498#elif defined(FEAT_GUI_MSWIN)
4499 return mch_system_g(cmd, options);
4500#else
4501 return mch_system_c(cmd, options);
4502#endif
4503}
4504
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004505#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4506/*
4507 * Use a terminal window to run a shell command in.
4508 */
4509 static int
4510mch_call_shell_terminal(
4511 char_u *cmd,
4512 int options UNUSED) /* SHELL_*, see vim.h */
4513{
4514 jobopt_T opt;
4515 char_u *newcmd = NULL;
4516 typval_T argvar[2];
4517 long_u cmdlen;
4518 int retval = -1;
4519 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004520 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004521 aco_save_T aco;
4522 oparg_T oa; /* operator arguments */
4523
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004524 if (cmd == NULL)
4525 cmdlen = STRLEN(p_sh) + 1;
4526 else
4527 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004528 newcmd = lalloc(cmdlen, TRUE);
4529 if (newcmd == NULL)
4530 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004531 if (cmd == NULL)
4532 {
4533 STRCPY(newcmd, p_sh);
4534 ch_log(NULL, "starting terminal to run a shell");
4535 }
4536 else
4537 {
4538 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4539 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4540 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004541
4542 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004543
4544 argvar[0].v_type = VAR_STRING;
4545 argvar[0].vval.v_string = newcmd;
4546 argvar[1].v_type = VAR_UNKNOWN;
4547 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004548 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004549 {
4550 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004551 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004552 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004553
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004554 job = term_getjob(buf->b_term);
4555 ++job->jv_refcount;
4556
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004557 /* Find a window to make "buf" curbuf. */
4558 aucmd_prepbuf(&aco, buf);
4559
4560 clear_oparg(&oa);
4561 while (term_use_loop())
4562 {
4563 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4564 {
4565 /* If terminal_loop() returns OK we got a key that is handled
4566 * in Normal model. We don't do redrawing anyway. */
4567 if (terminal_loop(TRUE) == OK)
4568 normal_cmd(&oa, TRUE);
4569 }
4570 else
4571 normal_cmd(&oa, TRUE);
4572 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004573 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004574 ch_log(NULL, "system command finished");
4575
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004576 job_unref(job);
4577
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004578 /* restore curwin/curbuf and a few other things */
4579 aucmd_restbuf(&aco);
4580
4581 wait_return(TRUE);
4582 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4583
4584 vim_free(newcmd);
4585 return retval;
4586}
4587#endif
4588
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589/*
4590 * Either execute a command by calling the shell or start a new shell
4591 */
4592 int
4593mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004594 char_u *cmd,
4595 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596{
4597 int x = 0;
4598 int tmode = cur_tmode;
4599#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004600 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004601
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004602 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004603 if (GetConsoleTitleW(szShellTitle,
4604 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004605 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004606 if (cmd == NULL)
4607 wcscat(szShellTitle, L" :sh");
4608 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004609 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004610 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004611
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004612 if (wn != NULL)
4613 {
4614 wcscat(szShellTitle, L" - !");
4615 if ((wcslen(szShellTitle) + wcslen(wn) <
4616 sizeof(szShellTitle)/sizeof(WCHAR)))
4617 wcscat(szShellTitle, wn);
4618 SetConsoleTitleW(szShellTitle);
4619 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004620 }
4621 }
4622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623#endif
4624
4625 out_flush();
4626
4627#ifdef MCH_WRITE_DUMP
4628 if (fdDump)
4629 {
4630 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4631 fflush(fdDump);
4632 }
4633#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004634#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4635 /* TODO: make the terminal window work with input or output redirected. */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004636 if (
4637# ifdef VIMDLL
4638 gui.in_use &&
4639# endif
4640 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004641 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4642 {
4643 /* Use a terminal window to run the command in. */
4644 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004645# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004646 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004647# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004648 return x;
4649 }
4650#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651
4652 /*
4653 * Catch all deadly signals while running the external command, because a
4654 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4655 */
4656 signal(SIGINT, SIG_IGN);
4657#if defined(__GNUC__) && !defined(__MINGW32__)
4658 signal(SIGKILL, SIG_IGN);
4659#else
4660 signal(SIGBREAK, SIG_IGN);
4661#endif
4662 signal(SIGILL, SIG_IGN);
4663 signal(SIGFPE, SIG_IGN);
4664 signal(SIGSEGV, SIG_IGN);
4665 signal(SIGTERM, SIG_IGN);
4666 signal(SIGABRT, SIG_IGN);
4667
4668 if (options & SHELL_COOKED)
4669 settmode(TMODE_COOK); /* set to normal mode */
4670
4671 if (cmd == NULL)
4672 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004673 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004674 }
4675 else
4676 {
4677 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004678 char_u *newcmd = NULL;
4679 char_u *cmdbase = cmd;
4680 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004681
4682 /* Skip a leading ", ( and "(. */
4683 if (*cmdbase == '"' )
4684 ++cmdbase;
4685 if (*cmdbase == '(')
4686 ++cmdbase;
4687
Bram Moolenaar1c465442017-03-12 20:10:05 +01004688 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004689 {
4690 STARTUPINFO si;
4691 PROCESS_INFORMATION pi;
4692 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004693 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004694 char_u *p;
4695
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004696 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004697 si.cb = sizeof(si);
4698 si.lpReserved = NULL;
4699 si.lpDesktop = NULL;
4700 si.lpTitle = NULL;
4701 si.dwFlags = 0;
4702 si.cbReserved2 = 0;
4703 si.lpReserved2 = NULL;
4704
4705 cmdbase = skipwhite(cmdbase + 5);
4706 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004707 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004708 {
4709 cmdbase = skipwhite(cmdbase + 4);
4710 si.dwFlags = STARTF_USESHOWWINDOW;
4711 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004712 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004713 }
4714 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004715 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004716 {
4717 cmdbase = skipwhite(cmdbase + 2);
4718 flags = CREATE_NO_WINDOW;
4719 si.dwFlags = STARTF_USESTDHANDLES;
4720 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004721 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004722 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004723 NULL, // Security att.
4724 OPEN_EXISTING, // Open flags
4725 FILE_ATTRIBUTE_NORMAL, // File att.
4726 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004727 si.hStdOutput = si.hStdInput;
4728 si.hStdError = si.hStdInput;
4729 }
4730
4731 /* Remove a trailing ", ) and )" if they have a match
4732 * at the start of the command. */
4733 if (cmdbase > cmd)
4734 {
4735 p = cmdbase + STRLEN(cmdbase);
4736 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4737 *--p = NUL;
4738 if (p > cmdbase && p[-1] == ')'
4739 && (*cmd =='(' || cmd[1] == '('))
4740 *--p = NUL;
4741 }
4742
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004743 newcmd = cmdbase;
4744 unescape_shellxquote(cmdbase, p_sxe);
4745
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004746 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004747 * If creating new console, arguments are passed to the
4748 * 'cmd.exe' as-is. If it's not, arguments are not treated
4749 * correctly for current 'cmd.exe'. So unescape characters in
4750 * shellxescape except '|' for avoiding to be treated as
4751 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004752 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004753 if (flags != CREATE_NEW_CONSOLE)
4754 {
4755 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004756 char_u *cmd_shell = mch_getenv("COMSPEC");
4757
4758 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004759 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004760
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004761 subcmd = vim_strsave_escaped_ext(cmdbase,
4762 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004763 if (subcmd != NULL)
4764 {
4765 /* make "cmd.exe /c arguments" */
4766 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004767 newcmd = lalloc(cmdlen, TRUE);
4768 if (newcmd != NULL)
4769 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004770 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004771 else
4772 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004773 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004774 }
4775 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004776
4777 /*
4778 * Now, start the command as a process, so that it doesn't
4779 * inherit our handles which causes unpleasant dangling swap
4780 * files if we exit before the spawned process
4781 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004782 if (vim_create_process((char *)newcmd, FALSE, flags,
4783 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004784 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004785 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4786 > (HINSTANCE)32)
4787 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004788 else
4789 {
4790 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004791#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004792# ifdef VIMDLL
4793 if (gui.in_use)
4794# endif
4795 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004796#endif
4797 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004798
4799 if (newcmd != cmdbase)
4800 vim_free(newcmd);
4801
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004802 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004803 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004804 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004805 CloseHandle(si.hStdInput);
4806 }
4807 /* Close the handles to the subprocess, so that it goes away */
4808 CloseHandle(pi.hThread);
4809 CloseHandle(pi.hProcess);
4810 }
4811 else
4812 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004813 cmdlen = (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004814#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004815 (gui.in_use ? (!p_stmp ? 0 : STRLEN(vimrun_path)) : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004817 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4818
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004819 newcmd = lalloc(cmdlen, TRUE);
4820 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004822#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004823 if (
4824# ifdef VIMDLL
4825 gui.in_use &&
4826# endif
4827 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004829 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4830 "External commands will not pause after completion.\n"
4831 "See :help win32-vimrun for more information.");
4832 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004833 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4834 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004835
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004836 if (wmsg != NULL && wtitle != NULL)
4837 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4838 vim_free(wmsg);
4839 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840 need_vimrun_warning = FALSE;
4841 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004842 if (
4843# ifdef VIMDLL
4844 gui.in_use &&
4845# endif
4846 !s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 /* Use vimrun to execute the command. It opens a console
4848 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004849 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 vimrun_path,
4851 (msg_silent != 0 || (options & SHELL_DOOUT))
4852 ? "-s " : "",
4853 p_sh, p_shcf, cmd);
4854 else
4855#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004856 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004857 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004859 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 }
4862 }
4863
4864 if (tmode == TMODE_RAW)
4865 settmode(TMODE_RAW); /* set to raw mode */
4866
4867 /* Print the return value, unless "vimrun" was used. */
4868 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004869#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004870 && (gui.in_use ?
4871 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872#endif
4873 )
4874 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004875 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 msg_putchar('\n');
4877 }
4878#ifdef FEAT_TITLE
4879 resettitle();
4880#endif
4881
4882 signal(SIGINT, SIG_DFL);
4883#if defined(__GNUC__) && !defined(__MINGW32__)
4884 signal(SIGKILL, SIG_DFL);
4885#else
4886 signal(SIGBREAK, SIG_DFL);
4887#endif
4888 signal(SIGILL, SIG_DFL);
4889 signal(SIGFPE, SIG_DFL);
4890 signal(SIGSEGV, SIG_DFL);
4891 signal(SIGTERM, SIG_DFL);
4892 signal(SIGABRT, SIG_DFL);
4893
4894 return x;
4895}
4896
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004897#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004898 static HANDLE
4899job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004900 char_u *fname,
4901 DWORD dwDesiredAccess,
4902 DWORD dwShareMode,
4903 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4904 DWORD dwCreationDisposition,
4905 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004906{
4907 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004908 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004909
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004910 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004911 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004912 return INVALID_HANDLE_VALUE;
4913
4914 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4915 lpSecurityAttributes, dwCreationDisposition,
4916 dwFlagsAndAttributes, NULL);
4917 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004918 return h;
4919}
4920
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004921/*
4922 * Turn the dictionary "env" into a NUL separated list that can be used as the
4923 * environment argument of vim_create_process().
4924 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004925 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004926win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004927{
4928 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004929 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004930 LPVOID base = GetEnvironmentStringsW();
4931
4932 /* for last \0 */
4933 if (ga_grow(gap, 1) == FAIL)
4934 return;
4935
4936 if (base)
4937 {
4938 WCHAR *p = (WCHAR*) base;
4939
4940 /* for last \0 */
4941 if (ga_grow(gap, 1) == FAIL)
4942 return;
4943
4944 while (*p != 0 || *(p + 1) != 0)
4945 {
4946 if (ga_grow(gap, 1) == OK)
4947 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4948 p++;
4949 }
4950 FreeEnvironmentStrings(base);
4951 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4952 }
4953
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004954 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004955 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004956 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004957 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004958 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004959 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004960 typval_T *item = &dict_lookup(hi)->di_tv;
4961 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004962 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004963 --todo;
4964 if (wkey != NULL && wval != NULL)
4965 {
4966 size_t n;
4967 size_t lkey = wcslen(wkey);
4968 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02004969
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004970 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
4971 continue;
4972 for (n = 0; n < lkey; n++)
4973 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
4974 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
4975 for (n = 0; n < lval; n++)
4976 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
4977 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4978 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01004979 vim_free(wkey);
4980 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004981 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004982 }
4983 }
4984
Bram Moolenaar493359e2018-06-12 20:25:52 +02004985# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004986 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02004987# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004988 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004989 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004990# endif
4991# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004992 char_u *version = get_vim_var_str(VV_VERSION);
4993 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004994# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004995 // size of "VIM_SERVERNAME=" and value,
4996 // plus "VIM_TERMINAL=" and value,
4997 // plus two terminating NULs
4998 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02004999# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005000 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005001# endif
5002# ifdef FEAT_TERMINAL
5003 + 13 + version_len + 2
5004# endif
5005 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005006
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005007 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005008 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005009# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005010 for (n = 0; n < 15; n++)
5011 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5012 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005013 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005014 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5015 (WCHAR)servername[n];
5016 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005017# endif
5018# ifdef FEAT_TERMINAL
5019 if (is_terminal)
5020 {
5021 for (n = 0; n < 13; n++)
5022 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5023 (WCHAR)"VIM_TERMINAL="[n];
5024 for (n = 0; n < version_len; n++)
5025 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5026 (WCHAR)version[n];
5027 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5028 }
5029# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005030 }
5031 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005032# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005033}
5034
Bram Moolenaarb091f302019-01-19 14:37:00 +01005035/*
5036 * Create a pair of pipes.
5037 * Return TRUE for success, FALSE for failure.
5038 */
5039 static BOOL
5040create_pipe_pair(HANDLE handles[2])
5041{
5042 static LONG s;
5043 char name[64];
5044 SECURITY_ATTRIBUTES sa;
5045
5046 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5047 GetCurrentProcessId(),
5048 InterlockedIncrement(&s));
5049
5050 // Create named pipe. Max size of named pipe is 65535.
5051 handles[1] = CreateNamedPipe(
5052 name,
5053 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5054 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005055 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005056
5057 if (handles[1] == INVALID_HANDLE_VALUE)
5058 return FALSE;
5059
5060 sa.nLength = sizeof(sa);
5061 sa.bInheritHandle = TRUE;
5062 sa.lpSecurityDescriptor = NULL;
5063
5064 handles[0] = CreateFile(name,
5065 FILE_GENERIC_READ,
5066 FILE_SHARE_READ, &sa,
5067 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5068
5069 if (handles[0] == INVALID_HANDLE_VALUE)
5070 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005071 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005072 return FALSE;
5073 }
5074
5075 return TRUE;
5076}
5077
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005078 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005079mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005080{
5081 STARTUPINFO si;
5082 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005083 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005084 SECURITY_ATTRIBUTES saAttr;
5085 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005086 HANDLE ifd[2];
5087 HANDLE ofd[2];
5088 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005089 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005090
5091 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5092 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5093 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5094 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5095 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5096 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5097 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5098
5099 if (use_out_for_err && use_null_for_out)
5100 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005101
5102 ifd[0] = INVALID_HANDLE_VALUE;
5103 ifd[1] = INVALID_HANDLE_VALUE;
5104 ofd[0] = INVALID_HANDLE_VALUE;
5105 ofd[1] = INVALID_HANDLE_VALUE;
5106 efd[0] = INVALID_HANDLE_VALUE;
5107 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005109
Bram Moolenaar14207f42016-10-27 21:13:10 +02005110 jo = CreateJobObject(NULL, NULL);
5111 if (jo == NULL)
5112 {
5113 job->jv_status = JOB_FAILED;
5114 goto failed;
5115 }
5116
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005117 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005118 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005119
Bram Moolenaar76467df2016-02-12 19:30:26 +01005120 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005121 ZeroMemory(&si, sizeof(si));
5122 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005123 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005124 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005125
Bram Moolenaard8070362016-02-15 21:56:54 +01005126 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5127 saAttr.bInheritHandle = TRUE;
5128 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005129
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005130 if (use_file_for_in)
5131 {
5132 char_u *fname = options->jo_io_name[PART_IN];
5133
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005134 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5135 FILE_SHARE_READ | FILE_SHARE_WRITE,
5136 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5137 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005138 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005139 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005140 goto failed;
5141 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005142 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005143 else if (!use_null_for_in
5144 && (!create_pipe_pair(ifd)
5145 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005146 goto failed;
5147
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005148 if (use_file_for_out)
5149 {
5150 char_u *fname = options->jo_io_name[PART_OUT];
5151
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005152 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5153 FILE_SHARE_READ | FILE_SHARE_WRITE,
5154 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5155 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005156 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005157 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005158 goto failed;
5159 }
5160 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005161 else if (!use_null_for_out &&
5162 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005163 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005164 goto failed;
5165
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005166 if (use_file_for_err)
5167 {
5168 char_u *fname = options->jo_io_name[PART_ERR];
5169
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005170 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5171 FILE_SHARE_READ | FILE_SHARE_WRITE,
5172 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5173 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005174 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005175 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005176 goto failed;
5177 }
5178 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005179 else if (!use_out_for_err && !use_null_for_err &&
5180 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005181 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005182 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005183
Bram Moolenaard8070362016-02-15 21:56:54 +01005184 si.dwFlags |= STARTF_USESTDHANDLES;
5185 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005186 si.hStdOutput = ofd[1];
5187 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5188
5189 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5190 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005191 if (options->jo_set & JO_CHANNEL)
5192 {
5193 channel = options->jo_channel;
5194 if (channel != NULL)
5195 ++channel->ch_refcount;
5196 }
5197 else
5198 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005199 if (channel == NULL)
5200 goto failed;
5201 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005202
5203 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005204 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005205 CREATE_DEFAULT_ERROR_MODE |
5206 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005207 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005208 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005209 &si, &pi,
5210 ga.ga_data,
5211 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005212 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005213 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005214 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005215 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005216 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005217
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005218 ga_clear(&ga);
5219
Bram Moolenaar14207f42016-10-27 21:13:10 +02005220 if (!AssignProcessToJobObject(jo, pi.hProcess))
5221 {
5222 /* if failing, switch the way to terminate
5223 * process with TerminateProcess. */
5224 CloseHandle(jo);
5225 jo = NULL;
5226 }
5227 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005228 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005229 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005230 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005231 job->jv_status = JOB_STARTED;
5232
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005233 CloseHandle(ifd[0]);
5234 CloseHandle(ofd[1]);
5235 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005236 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005237
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005238 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005239 if (channel != NULL)
5240 {
5241 channel_set_pipes(channel,
5242 use_file_for_in || use_null_for_in
5243 ? INVALID_FD : (sock_T)ifd[1],
5244 use_file_for_out || use_null_for_out
5245 ? INVALID_FD : (sock_T)ofd[0],
5246 use_out_for_err || use_file_for_err || use_null_for_err
5247 ? INVALID_FD : (sock_T)efd[0]);
5248 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005249 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005250 return;
5251
5252failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005253 CloseHandle(ifd[0]);
5254 CloseHandle(ofd[0]);
5255 CloseHandle(efd[0]);
5256 CloseHandle(ifd[1]);
5257 CloseHandle(ofd[1]);
5258 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005259 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005260 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005261}
5262
5263 char *
5264mch_job_status(job_T *job)
5265{
5266 DWORD dwExitCode = 0;
5267
Bram Moolenaar76467df2016-02-12 19:30:26 +01005268 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5269 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005270 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005271 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005272 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005273 {
5274 ch_log(job->jv_channel, "Job ended");
5275 job->jv_status = JOB_ENDED;
5276 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005277 return "dead";
5278 }
5279 return "run";
5280}
5281
Bram Moolenaar97792de2016-10-15 18:36:49 +02005282 job_T *
5283mch_detect_ended_job(job_T *job_list)
5284{
5285 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5286 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5287 job_T *job = job_list;
5288
5289 while (job != NULL)
5290 {
5291 DWORD n;
5292 DWORD result;
5293
5294 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5295 && job != NULL; job = job->jv_next)
5296 {
5297 if (job->jv_status == JOB_STARTED)
5298 {
5299 jobHandles[n] = job->jv_proc_info.hProcess;
5300 jobArray[n] = job;
5301 ++n;
5302 }
5303 }
5304 if (n == 0)
5305 continue;
5306 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5307 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5308 {
5309 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5310
5311 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5312 return wait_job;
5313 }
5314 }
5315 return NULL;
5316}
5317
Bram Moolenaarfb630902016-10-29 14:55:00 +02005318 static BOOL
5319terminate_all(HANDLE process, int code)
5320{
5321 PROCESSENTRY32 pe;
5322 HANDLE h = INVALID_HANDLE_VALUE;
5323 DWORD pid = GetProcessId(process);
5324
5325 if (pid != 0)
5326 {
5327 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5328 if (h != INVALID_HANDLE_VALUE)
5329 {
5330 pe.dwSize = sizeof(PROCESSENTRY32);
5331 if (!Process32First(h, &pe))
5332 goto theend;
5333
5334 do
5335 {
5336 if (pe.th32ParentProcessID == pid)
5337 {
5338 HANDLE ph = OpenProcess(
5339 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5340 if (ph != NULL)
5341 {
5342 terminate_all(ph, code);
5343 CloseHandle(ph);
5344 }
5345 }
5346 } while (Process32Next(h, &pe));
5347
5348 CloseHandle(h);
5349 }
5350 }
5351
5352theend:
5353 return TerminateProcess(process, code);
5354}
5355
5356/*
5357 * Send a (deadly) signal to "job".
5358 * Return FAIL if it didn't work.
5359 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005360 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005361mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005362{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005363 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005364
Bram Moolenaar923d9262016-02-25 20:56:01 +01005365 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005366 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005367 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005368 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005369 {
5370 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5371 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005372 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005373 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005374 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005375 }
5376
5377 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5378 return FAIL;
5379 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005380 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5381 job->jv_proc_info.dwProcessId)
5382 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005383 FreeConsole();
5384 return ret;
5385}
5386
5387/*
5388 * Clear the data related to "job".
5389 */
5390 void
5391mch_clear_job(job_T *job)
5392{
5393 if (job->jv_status != JOB_FAILED)
5394 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005395 if (job->jv_job_object != NULL)
5396 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005397 CloseHandle(job->jv_proc_info.hProcess);
5398 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005399}
5400#endif
5401
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005403#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005404
5405/*
5406 * Start termcap mode
5407 */
5408 static void
5409termcap_mode_start(void)
5410{
5411 DWORD cmodein;
5412
5413 if (g_fTermcapMode)
5414 return;
5415
5416 SaveConsoleBuffer(&g_cbNonTermcap);
5417
5418 if (g_cbTermcap.IsValid)
5419 {
5420 /*
5421 * We've been in termcap mode before. Restore certain screen
5422 * characteristics, including the buffer size and the window
5423 * size. Since we will be redrawing the screen, we don't need
5424 * to restore the actual contents of the buffer.
5425 */
5426 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005427 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005428 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5429 Rows = g_cbTermcap.Info.dwSize.Y;
5430 Columns = g_cbTermcap.Info.dwSize.X;
5431 }
5432 else
5433 {
5434 /*
5435 * This is our first time entering termcap mode. Clear the console
5436 * screen buffer, and resize the buffer to match the current window
5437 * size. We will use this as the size of our editing environment.
5438 */
5439 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005440 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5442 }
5443
5444#ifdef FEAT_TITLE
5445 resettitle();
5446#endif
5447
5448 GetConsoleMode(g_hConIn, &cmodein);
5449#ifdef FEAT_MOUSE
5450 if (g_fMouseActive)
5451 cmodein |= ENABLE_MOUSE_INPUT;
5452 else
5453 cmodein &= ~ENABLE_MOUSE_INPUT;
5454#endif
5455 cmodein |= ENABLE_WINDOW_INPUT;
5456 SetConsoleMode(g_hConIn, cmodein);
5457
5458 redraw_later_clear();
5459 g_fTermcapMode = TRUE;
5460}
5461
5462
5463/*
5464 * End termcap mode
5465 */
5466 static void
5467termcap_mode_end(void)
5468{
5469 DWORD cmodein;
5470 ConsoleBuffer *cb;
5471 COORD coord;
5472 DWORD dwDummy;
5473
5474 if (!g_fTermcapMode)
5475 return;
5476
5477 SaveConsoleBuffer(&g_cbTermcap);
5478
5479 GetConsoleMode(g_hConIn, &cmodein);
5480 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5481 SetConsoleMode(g_hConIn, cmodein);
5482
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005483#ifdef FEAT_RESTORE_ORIG_SCREEN
5484 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5485#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005486 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005489 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 SetConsoleCursorInfo(g_hConOut, &g_cci);
5491
5492 if (p_rs || exiting)
5493 {
5494 /*
5495 * Clear anything that happens to be on the current line.
5496 */
5497 coord.X = 0;
5498 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5499 FillConsoleOutputCharacter(g_hConOut, ' ',
5500 cb->Info.dwSize.X, coord, &dwDummy);
5501 /*
5502 * The following is just for aesthetics. If we are exiting without
5503 * restoring the screen, then we want to have a prompt string
5504 * appear at the bottom line. However, the command interpreter
5505 * seems to always advance the cursor one line before displaying
5506 * the prompt string, which causes the screen to scroll. To
5507 * counter this, move the cursor up one line before exiting.
5508 */
5509 if (exiting && !p_rs)
5510 coord.Y--;
5511 /*
5512 * Position the cursor at the leftmost column of the desired row.
5513 */
5514 SetConsoleCursorPosition(g_hConOut, coord);
5515 }
5516
5517 g_fTermcapMode = FALSE;
5518}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005519#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520
5521
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005522#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 void
5524mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005525 char_u *s UNUSED,
5526 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527{
5528 /* never used */
5529}
5530
5531#else
5532
5533/*
5534 * clear `n' chars, starting from `coord'
5535 */
5536 static void
5537clear_chars(
5538 COORD coord,
5539 DWORD n)
5540{
5541 DWORD dwDummy;
5542
5543 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005544
5545 if (!USE_VTP)
5546 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5547 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005548 {
5549 set_console_color_rgb();
5550 gotoxy(coord.X + 1, coord.Y + 1);
5551 vtp_printf("\033[%dX", n);
5552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553}
5554
5555
5556/*
5557 * Clear the screen
5558 */
5559 static void
5560clear_screen(void)
5561{
5562 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005563
5564 if (!USE_VTP)
5565 clear_chars(g_coord, Rows * Columns);
5566 else
5567 {
5568 set_console_color_rgb();
5569 gotoxy(1, 1);
5570 vtp_printf("\033[2J");
5571 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572}
5573
5574
5575/*
5576 * Clear to end of display
5577 */
5578 static void
5579clear_to_end_of_display(void)
5580{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005581 COORD save = g_coord;
5582
5583 if (!USE_VTP)
5584 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005586 else
5587 {
5588 set_console_color_rgb();
5589 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5590 vtp_printf("\033[0J");
5591
5592 gotoxy(save.X + 1, save.Y + 1);
5593 g_coord = save;
5594 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595}
5596
5597
5598/*
5599 * Clear to end of line
5600 */
5601 static void
5602clear_to_end_of_line(void)
5603{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005604 COORD save = g_coord;
5605
5606 if (!USE_VTP)
5607 clear_chars(g_coord, Columns - g_coord.X);
5608 else
5609 {
5610 set_console_color_rgb();
5611 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5612 vtp_printf("\033[0K");
5613
5614 gotoxy(save.X + 1, save.Y + 1);
5615 g_coord = save;
5616 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617}
5618
5619
5620/*
5621 * Scroll the scroll region up by `cLines' lines
5622 */
5623 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005624scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625{
5626 COORD oldcoord = g_coord;
5627
5628 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5629 delete_lines(cLines);
5630
5631 g_coord = oldcoord;
5632}
5633
5634
5635/*
5636 * Set the scroll region
5637 */
5638 static void
5639set_scroll_region(
5640 unsigned left,
5641 unsigned top,
5642 unsigned right,
5643 unsigned bottom)
5644{
5645 if (left >= right
5646 || top >= bottom
5647 || right > (unsigned) Columns - 1
5648 || bottom > (unsigned) Rows - 1)
5649 return;
5650
5651 g_srScrollRegion.Left = left;
5652 g_srScrollRegion.Top = top;
5653 g_srScrollRegion.Right = right;
5654 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005655}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005656
Bram Moolenaar6982f422019-02-16 16:48:01 +01005657 static void
5658set_scroll_region_tb(
5659 unsigned top,
5660 unsigned bottom)
5661{
5662 if (top >= bottom || bottom > (unsigned)Rows - 1)
5663 return;
5664
5665 g_srScrollRegion.Top = top;
5666 g_srScrollRegion.Bottom = bottom;
5667}
5668
5669 static void
5670set_scroll_region_lr(
5671 unsigned left,
5672 unsigned right)
5673{
5674 if (left >= right || right > (unsigned)Columns - 1)
5675 return;
5676
5677 g_srScrollRegion.Left = left;
5678 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005679}
5680
5681
5682/*
5683 * Insert `cLines' lines at the current cursor position
5684 */
5685 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005686insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005688 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 COORD dest;
5690 CHAR_INFO fill;
5691
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005692 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5693
Bram Moolenaar6982f422019-02-16 16:48:01 +01005694 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 dest.Y = g_coord.Y + cLines;
5696
Bram Moolenaar6982f422019-02-16 16:48:01 +01005697 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 source.Top = g_coord.Y;
5699 source.Right = g_srScrollRegion.Right;
5700 source.Bottom = g_srScrollRegion.Bottom - cLines;
5701
Bram Moolenaar6982f422019-02-16 16:48:01 +01005702 clip.Left = g_srScrollRegion.Left;
5703 clip.Top = g_coord.Y;
5704 clip.Right = g_srScrollRegion.Right;
5705 clip.Bottom = g_srScrollRegion.Bottom;
5706
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005707 fill.Char.AsciiChar = ' ';
5708 if (!USE_VTP)
5709 fill.Attributes = g_attrCurrent;
5710 else
5711 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005713 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005714
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005715 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5716
Bram Moolenaar6982f422019-02-16 16:48:01 +01005717 // Here we have to deal with a win32 console flake: If the scroll
5718 // region looks like abc and we scroll c to a and fill with d we get
5719 // cbd... if we scroll block c one line at a time to a, we get cdd...
5720 // vim expects cdd consistently... So we have to deal with that
5721 // here... (this also occurs scrolling the same way in the other
5722 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723
5724 if (source.Bottom < dest.Y)
5725 {
5726 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005727 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728
Bram Moolenaar6982f422019-02-16 16:48:01 +01005729 coord.X = source.Left;
5730 for (i = clip.Top; i < dest.Y; ++i)
5731 {
5732 coord.Y = i;
5733 clear_chars(coord, source.Right - source.Left + 1);
5734 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 }
5736}
5737
5738
5739/*
5740 * Delete `cLines' lines at the current cursor position
5741 */
5742 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005743delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005745 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 COORD dest;
5747 CHAR_INFO fill;
5748 int nb;
5749
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005750 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5751
Bram Moolenaar6982f422019-02-16 16:48:01 +01005752 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753 dest.Y = g_coord.Y;
5754
Bram Moolenaar6982f422019-02-16 16:48:01 +01005755 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756 source.Top = g_coord.Y + cLines;
5757 source.Right = g_srScrollRegion.Right;
5758 source.Bottom = g_srScrollRegion.Bottom;
5759
Bram Moolenaar6982f422019-02-16 16:48:01 +01005760 clip.Left = g_srScrollRegion.Left;
5761 clip.Top = g_coord.Y;
5762 clip.Right = g_srScrollRegion.Right;
5763 clip.Bottom = g_srScrollRegion.Bottom;
5764
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005765 fill.Char.AsciiChar = ' ';
5766 if (!USE_VTP)
5767 fill.Attributes = g_attrCurrent;
5768 else
5769 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005771 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005772
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005773 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5774
Bram Moolenaar6982f422019-02-16 16:48:01 +01005775 // Here we have to deal with a win32 console flake; See insert_lines()
5776 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777
5778 nb = dest.Y + (source.Bottom - source.Top) + 1;
5779
5780 if (nb < source.Top)
5781 {
5782 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005783 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784
Bram Moolenaar6982f422019-02-16 16:48:01 +01005785 coord.X = source.Left;
5786 for (i = nb; i < clip.Bottom; ++i)
5787 {
5788 coord.Y = i;
5789 clear_chars(coord, source.Right - source.Left + 1);
5790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 }
5792}
5793
5794
5795/*
5796 * Set the cursor position
5797 */
5798 static void
5799gotoxy(
5800 unsigned x,
5801 unsigned y)
5802{
5803 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5804 return;
5805
5806 /* external cursor coords are 1-based; internal are 0-based */
5807 g_coord.X = x - 1;
5808 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005809
5810 if (!USE_VTP)
5811 SetConsoleCursorPosition(g_hConOut, g_coord);
5812 else
5813 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814}
5815
5816
5817/*
5818 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005819 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 */
5821 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005822textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005824 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825
5826 SetConsoleTextAttribute(g_hConOut, wAttr);
5827}
5828
5829
5830 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005831textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005833 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005835 if (!USE_VTP)
5836 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5837 else
5838 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839}
5840
5841
5842 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005843textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005845 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005846
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005847 if (!USE_VTP)
5848 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5849 else
5850 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851}
5852
5853
5854/*
5855 * restore the default text attribute (whatever we started with)
5856 */
5857 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005858normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005860 if (!USE_VTP)
5861 textattr(g_attrDefault);
5862 else
5863 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864}
5865
5866
5867static WORD g_attrPreStandout = 0;
5868
5869/*
5870 * Make the text standout, by brightening it
5871 */
5872 static void
5873standout(void)
5874{
5875 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005876
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5878}
5879
5880
5881/*
5882 * Turn off standout mode
5883 */
5884 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005885standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005886{
5887 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005889
5890 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891}
5892
5893
5894/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005895 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 */
5897 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005898mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899{
5900 char_u *p;
5901 int n;
5902
5903 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5904 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005905 if (
5906#ifdef FEAT_TERMGUICOLORS
5907 !p_tgc &&
5908#endif
5909 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 {
5911 p = T_ME + 2;
5912 n = getdigits(&p);
5913 if (*p == 'm' && n > 0)
5914 {
5915 cterm_normal_fg_color = (n & 0xf) + 1;
5916 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5917 }
5918 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005919#ifdef FEAT_TERMGUICOLORS
5920 cterm_normal_fg_gui_color = INVALCOLOR;
5921 cterm_normal_bg_gui_color = INVALCOLOR;
5922#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923}
5924
5925
5926/*
5927 * visual bell: flash the screen
5928 */
5929 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005930visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931{
5932 COORD coordOrigin = {0, 0};
5933 WORD attrFlash = ~g_attrCurrent & 0xff;
5934
5935 DWORD dwDummy;
5936 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5937
5938 if (oldattrs == NULL)
5939 return;
5940 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5941 coordOrigin, &dwDummy);
5942 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5943 coordOrigin, &dwDummy);
5944
5945 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005946 if (!USE_VTP)
5947 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948 coordOrigin, &dwDummy);
5949 vim_free(oldattrs);
5950}
5951
5952
5953/*
5954 * Make the cursor visible or invisible
5955 */
5956 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005957cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958{
5959 s_cursor_visible = fVisible;
5960#ifdef MCH_CURSOR_SHAPE
5961 mch_update_cursor();
5962#endif
5963}
5964
5965
5966/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005967 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005968 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005970 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005972 char_u *pchBuf,
5973 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005975 COORD coord = g_coord;
5976 DWORD written;
5977 DWORD n, cchwritten, cells;
5978 static WCHAR *unicodebuf = NULL;
5979 static int unibuflen = 0;
5980 int length;
5981 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005983 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5984 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005985 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005986 vim_free(unicodebuf);
5987 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5988 unibuflen = length;
5989 }
5990 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
5991 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005993 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005994
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005995 if (!USE_VTP)
5996 {
5997 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5998 coord, &written);
5999 // When writing fails or didn't write a single character, pretend one
6000 // character was written, otherwise we get stuck.
6001 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6002 coord, &cchwritten) == 0
6003 || cchwritten == 0 || cchwritten == (DWORD)-1)
6004 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006005 }
6006 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006007 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006008 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6009 NULL) == 0 || cchwritten == 0)
6010 cchwritten = 1;
6011 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006012
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006013 if (cchwritten == length)
6014 {
6015 written = cbToWrite;
6016 g_coord.X += (SHORT)cells;
6017 }
6018 else
6019 {
6020 char_u *p = pchBuf;
6021 for (n = 0; n < cchwritten; n++)
6022 MB_CPTR_ADV(p);
6023 written = p - pchBuf;
6024 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026
6027 while (g_coord.X > g_srScrollRegion.Right)
6028 {
6029 g_coord.X -= (SHORT) Columns;
6030 if (g_coord.Y < g_srScrollRegion.Bottom)
6031 g_coord.Y++;
6032 }
6033
6034 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6035
6036 return written;
6037}
6038
6039
6040/*
6041 * mch_write(): write the output buffer to the screen, translating ESC
6042 * sequences into calls to console output routines.
6043 */
6044 void
6045mch_write(
6046 char_u *s,
6047 int len)
6048{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006049# ifdef VIMDLL
6050 if (gui.in_use)
6051 return;
6052# endif
6053
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 s[len] = NUL;
6055
6056 if (!term_console)
6057 {
6058 write(1, s, (unsigned)len);
6059 return;
6060 }
6061
6062 /* translate ESC | sequences into faked bios calls */
6063 while (len--)
6064 {
6065 /* optimization: use one single write_chars for runs of text,
6066 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006067 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068
6069 if (p_wd)
6070 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006071 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072 if (prefix != 0)
6073 prefix = 1;
6074 }
6075
6076 if (prefix != 0)
6077 {
6078 DWORD nWritten;
6079
6080 nWritten = write_chars(s, prefix);
6081#ifdef MCH_WRITE_DUMP
6082 if (fdDump)
6083 {
6084 fputc('>', fdDump);
6085 fwrite(s, sizeof(char_u), nWritten, fdDump);
6086 fputs("<\n", fdDump);
6087 }
6088#endif
6089 len -= (nWritten - 1);
6090 s += nWritten;
6091 }
6092 else if (s[0] == '\n')
6093 {
6094 /* \n, newline: go to the beginning of the next line or scroll */
6095 if (g_coord.Y == g_srScrollRegion.Bottom)
6096 {
6097 scroll(1);
6098 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6099 }
6100 else
6101 {
6102 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6103 }
6104#ifdef MCH_WRITE_DUMP
6105 if (fdDump)
6106 fputs("\\n\n", fdDump);
6107#endif
6108 s++;
6109 }
6110 else if (s[0] == '\r')
6111 {
6112 /* \r, carriage return: go to beginning of line */
6113 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6114#ifdef MCH_WRITE_DUMP
6115 if (fdDump)
6116 fputs("\\r\n", fdDump);
6117#endif
6118 s++;
6119 }
6120 else if (s[0] == '\b')
6121 {
6122 /* \b, backspace: move cursor one position left */
6123 if (g_coord.X > g_srScrollRegion.Left)
6124 g_coord.X--;
6125 else if (g_coord.Y > g_srScrollRegion.Top)
6126 {
6127 g_coord.X = g_srScrollRegion.Right;
6128 g_coord.Y--;
6129 }
6130 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6131#ifdef MCH_WRITE_DUMP
6132 if (fdDump)
6133 fputs("\\b\n", fdDump);
6134#endif
6135 s++;
6136 }
6137 else if (s[0] == '\a')
6138 {
6139 /* \a, bell */
6140 MessageBeep(0xFFFFFFFF);
6141#ifdef MCH_WRITE_DUMP
6142 if (fdDump)
6143 fputs("\\a\n", fdDump);
6144#endif
6145 s++;
6146 }
6147 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6148 {
6149#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006150 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006152 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006153 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154
6155 switch (s[2])
6156 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 case '0': case '1': case '2': case '3': case '4':
6158 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006159 p = s + 1;
6160 do
6161 {
6162 ++p;
6163 args[argc] = getdigits(&p);
6164 argc += (argc < 15) ? 1 : 0;
6165 if (p > s + len)
6166 break;
6167 } while (*p == ';');
6168
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 if (p > s + len)
6170 break;
6171
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172 arg1 = args[0];
6173 arg2 = args[1];
6174 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006176 if (argc == 1 && args[0] == 0)
6177 normvideo();
6178 else if (argc == 1)
6179 {
6180 if (USE_VTP)
6181 textcolor((WORD) arg1);
6182 else
6183 textattr((WORD) arg1);
6184 }
6185 else if (USE_VTP)
6186 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006190 gotoxy(arg2, arg1);
6191 }
6192 else if (argc == 2 && *p == 'r')
6193 {
6194 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6195 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006196 else if (argc == 2 && *p == 'R')
6197 {
6198 set_scroll_region_tb(arg1, arg2);
6199 }
6200 else if (argc == 2 && *p == 'V')
6201 {
6202 set_scroll_region_lr(arg1, arg2);
6203 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006204 else if (argc == 1 && *p == 'A')
6205 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 gotoxy(g_coord.X + 1,
6207 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6208 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006209 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 {
6211 textbackground((WORD) arg1);
6212 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006213 else if (argc == 1 && *p == 'C')
6214 {
6215 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6216 g_coord.Y + 1);
6217 }
6218 else if (argc == 1 && *p == 'f')
6219 {
6220 textcolor((WORD) arg1);
6221 }
6222 else if (argc == 1 && *p == 'H')
6223 {
6224 gotoxy(1, arg1);
6225 }
6226 else if (argc == 1 && *p == 'L')
6227 {
6228 insert_lines(arg1);
6229 }
6230 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 {
6232 delete_lines(arg1);
6233 }
6234
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006235 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 s = p + 1;
6237 break;
6238
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 gotoxy(g_coord.X + 1,
6241 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6242 goto got3;
6243
6244 case 'B':
6245 visual_bell();
6246 goto got3;
6247
6248 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6250 g_coord.Y + 1);
6251 goto got3;
6252
6253 case 'E':
6254 termcap_mode_end();
6255 goto got3;
6256
6257 case 'F':
6258 standout();
6259 goto got3;
6260
6261 case 'f':
6262 standend();
6263 goto got3;
6264
6265 case 'H':
6266 gotoxy(1, 1);
6267 goto got3;
6268
6269 case 'j':
6270 clear_to_end_of_display();
6271 goto got3;
6272
6273 case 'J':
6274 clear_screen();
6275 goto got3;
6276
6277 case 'K':
6278 clear_to_end_of_line();
6279 goto got3;
6280
6281 case 'L':
6282 insert_lines(1);
6283 goto got3;
6284
6285 case 'M':
6286 delete_lines(1);
6287 goto got3;
6288
6289 case 'S':
6290 termcap_mode_start();
6291 goto got3;
6292
6293 case 'V':
6294 cursor_visible(TRUE);
6295 goto got3;
6296
6297 case 'v':
6298 cursor_visible(FALSE);
6299 goto got3;
6300
6301 got3:
6302 s += 3;
6303 len -= 2;
6304 }
6305
6306#ifdef MCH_WRITE_DUMP
6307 if (fdDump)
6308 {
6309 fputs("ESC | ", fdDump);
6310 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6311 fputc('\n', fdDump);
6312 }
6313#endif
6314 }
6315 else
6316 {
6317 /* Write a single character */
6318 DWORD nWritten;
6319
6320 nWritten = write_chars(s, 1);
6321#ifdef MCH_WRITE_DUMP
6322 if (fdDump)
6323 {
6324 fputc('>', fdDump);
6325 fwrite(s, sizeof(char_u), nWritten, fdDump);
6326 fputs("<\n", fdDump);
6327 }
6328#endif
6329
6330 len -= (nWritten - 1);
6331 s += nWritten;
6332 }
6333 }
6334
6335#ifdef MCH_WRITE_DUMP
6336 if (fdDump)
6337 fflush(fdDump);
6338#endif
6339}
6340
Bram Moolenaar4f974752019-02-17 17:44:42 +01006341#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006342
6343
6344/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006345 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 */
6347 void
6348mch_delay(
6349 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006350 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006352#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006353 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006354#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006355# ifdef VIMDLL
6356 if (gui.in_use)
6357 {
6358 Sleep((int)msec); /* never wait for input */
6359 return;
6360 }
6361# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006363# ifdef FEAT_MZSCHEME
6364 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6365 {
6366 int towait = p_mzq;
6367
6368 /* if msec is large enough, wait by portions in p_mzq */
6369 while (msec > 0)
6370 {
6371 mzvim_check_threads();
6372 if (msec < towait)
6373 towait = msec;
6374 Sleep(towait);
6375 msec -= towait;
6376 }
6377 }
6378 else
6379# endif
6380 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006382 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383#endif
6384}
6385
6386
6387/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006388 * This version of remove is not scared by a readonly (backup) file.
6389 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 * Return 0 for success, -1 for failure.
6391 */
6392 int
6393mch_remove(char_u *name)
6394{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006395 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 int n;
6397
Bram Moolenaar203258c2016-01-17 22:15:16 +01006398 /*
6399 * On Windows, deleting a directory's symbolic link is done by
6400 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6401 */
6402 if (mch_isdir(name) && mch_is_symbolic_link(name))
6403 return mch_rmdir(name);
6404
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006405 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6406
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006407 wn = enc_to_utf16(name, NULL);
6408 if (wn == NULL)
6409 return -1;
6410
6411 n = DeleteFileW(wn) ? 0 : -1;
6412 vim_free(wn);
6413 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414}
6415
6416
6417/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006418 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419 */
6420 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006421mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006423#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6424# ifdef VIMDLL
6425 if (!gui.in_use)
6426# endif
6427 if (g_fCtrlCPressed || g_fCBrkPressed)
6428 {
6429 ctrl_break_was_pressed = g_fCBrkPressed;
6430 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6431 got_int = TRUE;
6432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433#endif
6434}
6435
Bram Moolenaaree273972016-01-02 21:11:51 +01006436/* physical RAM to leave for the OS */
6437#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006438
6439/*
6440 * How much main memory in KiB that can be used by VIM.
6441 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006442 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006443mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006444{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006445 MEMORYSTATUSEX ms;
6446
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006447 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006448 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006449 ms.dwLength = sizeof(MEMORYSTATUSEX);
6450 GlobalMemoryStatusEx(&ms);
6451 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006452 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006453 /* Process address space fits in physical RAM, use all of it. */
6454 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006455 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006456 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006457 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006458 /* Catch old NT box or perverse hardware setup. */
6459 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006460 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006461 /* Use physical RAM less reserve for OS + data. */
6462 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006463}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006466 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006467 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6468 * file whose short file name is "FOO.BAR" (its long file name will
6469 * be correct: "foo.bar~"). Because a file can be accessed by
6470 * either its SFN or its LFN, "foo.bar" has effectively been
6471 * renamed to "foo.bar", which is not at all what was wanted. This
6472 * seems to happen only when renaming files with three-character
6473 * extensions by appending a suffix that does not include ".".
6474 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6475 *
6476 * There is another problem, which isn't really a bug but isn't right either:
6477 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6478 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6479 * service pack 6. Doesn't seem to happen on Windows 98.
6480 *
6481 * Like rename(), returns 0 upon success, non-zero upon failure.
6482 * Should probably set errno appropriately when errors occur.
6483 */
6484 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006485mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006487 WCHAR *p;
6488 int i;
6489 WCHAR szTempFile[_MAX_PATH + 1];
6490 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006493 // No need to play tricks unless the file name contains a "~" as the
6494 // seventh character.
6495 p = wold;
6496 for (i = 0; wold[i] != NUL; ++i)
6497 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6498 && wold[i + 1] != 0)
6499 p = wold + i + 1;
6500 if ((int)(wold + i - p) < 8 || p[6] != '~')
6501 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006503 // Get base path of new file name. Undocumented feature: If pszNewFile is
6504 // a directory, no error is returned and pszFilePart will be NULL.
6505 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006507 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006509 // Get (and create) a unique temporary file name in directory of new file
6510 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 return -2;
6512
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006513 // blow the temp file away
6514 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 return -3;
6516
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006517 // rename old file to the temp file
6518 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 return -4;
6520
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006521 // now create an empty file called pszOldFile; this prevents the operating
6522 // system using pszOldFile as an alias (SFN) if we're renaming within the
6523 // same directory. For example, we're editing a file called
6524 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6525 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6526 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6527 // cause all sorts of problems later in buf_write(). So, we create an
6528 // empty file called filena~1.txt and the system will have to find some
6529 // other SFN for filena~1.txt~, such as filena~2.txt
6530 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6532 return -5;
6533 if (!CloseHandle(hf))
6534 return -6;
6535
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006536 // rename the temp file to the new file
6537 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006539 // Renaming failed. Rename the file back to its old name, so that it
6540 // looks like nothing happened.
6541 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 return -7;
6543 }
6544
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006545 // Seems to be left around on Novell filesystems
6546 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006548 // finally, remove the empty old file
6549 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 return -8;
6551
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006552 return 0;
6553}
6554
6555
6556/*
6557 * Converts the filenames to UTF-16, then call mch_wrename().
6558 * Like rename(), returns 0 upon success, non-zero upon failure.
6559 */
6560 int
6561mch_rename(
6562 const char *pszOldFile,
6563 const char *pszNewFile)
6564{
6565 WCHAR *wold = NULL;
6566 WCHAR *wnew = NULL;
6567 int retval = -1;
6568
6569 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6570 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6571 if (wold != NULL && wnew != NULL)
6572 retval = mch_wrename(wold, wnew);
6573 vim_free(wold);
6574 vim_free(wnew);
6575 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576}
6577
6578/*
6579 * Get the default shell for the current hardware platform
6580 */
6581 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006582default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006584 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585}
6586
6587/*
6588 * mch_access() extends access() to do more detailed check on network drives.
6589 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6590 */
6591 int
6592mch_access(char *n, int p)
6593{
6594 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006596 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006598 wn = enc_to_utf16((char_u *)n, NULL);
6599 if (wn == NULL)
6600 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006602 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605
6606 if (p & R_OK)
6607 {
6608 /* Read check is performed by seeing if we can do a find file on
6609 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006610 int i;
6611 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006613 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6614 TempNameW[i] = wn[i];
6615 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6616 TempNameW[i++] = '\\';
6617 TempNameW[i++] = '*';
6618 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006620 hFile = FindFirstFileW(TempNameW, &d);
6621 if (hFile == INVALID_HANDLE_VALUE)
6622 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006623 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 }
6626
6627 if (p & W_OK)
6628 {
6629 /* Trying to create a temporary file in the directory should catch
6630 * directories on read-only network shares. However, in
6631 * directories whose ACL allows writes but denies deletes will end
6632 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006633 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6634 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006635 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006636 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 }
6638 }
6639 else
6640 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006641 // Don't consider a file read-only if another process has opened it.
6642 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6643
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 /* Trying to open the file for the required access does ACL, read-only
6645 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006646 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6647 | ((p & R_OK) ? GENERIC_READ : 0);
6648
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006649 hFile = CreateFileW(wn, access_mode, share_mode,
6650 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 if (hFile == INVALID_HANDLE_VALUE)
6652 goto getout;
6653 CloseHandle(hFile);
6654 }
6655
6656 retval = 0; /* success */
6657getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 return retval;
6660}
6661
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006663 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 */
6665 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006666mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006668 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01006669#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 WCHAR *wn;
6671 int f;
6672
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006673 wn = enc_to_utf16((char_u *)name, NULL);
6674 if (wn == NULL)
6675 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006677 f = _wopen(wn, flags, mode);
6678 vim_free(wn);
6679 return f;
6680#else
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006681 /* open() can open a file which name is longer than _MAX_PATH bytes
6682 * and shorter than _MAX_PATH characters successfully, but sometimes it
6683 * causes unexpected error in another part. We make it an error explicitly
6684 * here. */
6685 if (strlen(name) >= _MAX_PATH)
6686 return -1;
6687
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 return open(name, flags, mode);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006689#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690}
6691
6692/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006693 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 */
6695 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006696mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697{
6698 WCHAR *wn, *wm;
6699 FILE *f = NULL;
6700
Bram Moolenaara12a1612019-01-24 16:39:02 +01006701#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006702 /* Work around an annoying assertion in the Microsoft debug CRT
6703 * when mode's text/binary setting doesn't match _get_fmode(). */
6704 char newMode = mode[strlen(mode) - 1];
6705 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006706
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006707 _get_fmode(&oldMode);
6708 if (newMode == 't')
6709 _set_fmode(_O_TEXT);
6710 else if (newMode == 'b')
6711 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006712#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006713 wn = enc_to_utf16((char_u *)name, NULL);
6714 wm = enc_to_utf16((char_u *)mode, NULL);
6715 if (wn != NULL && wm != NULL)
6716 f = _wfopen(wn, wm);
6717 vim_free(wn);
6718 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006719
Bram Moolenaara12a1612019-01-24 16:39:02 +01006720#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006721 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006722#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006723 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726/*
6727 * SUB STREAM (aka info stream) handling:
6728 *
6729 * NTFS can have sub streams for each file. Normal contents of file is
6730 * stored in the main stream, and extra contents (author information and
6731 * title and so on) can be stored in sub stream. After Windows 2000, user
6732 * can access and store those informations in sub streams via explorer's
6733 * property menuitem in right click menu. Those informations in sub streams
6734 * were lost when copying only the main stream. So we have to copy sub
6735 * streams.
6736 *
6737 * Incomplete explanation:
6738 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6739 * More useful info and an example:
6740 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6741 */
6742
6743/*
6744 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6745 * and write to stream "substream" of file "to".
6746 * Errors are ignored.
6747 */
6748 static void
6749copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6750{
6751 HANDLE hTo;
6752 WCHAR *to_name;
6753
6754 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6755 wcscpy(to_name, to);
6756 wcscat(to_name, substream);
6757
6758 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6759 FILE_ATTRIBUTE_NORMAL, NULL);
6760 if (hTo != INVALID_HANDLE_VALUE)
6761 {
6762 long done;
6763 DWORD todo;
6764 DWORD readcnt, written;
6765 char buf[4096];
6766
6767 /* Copy block of bytes at a time. Abort when something goes wrong. */
6768 for (done = 0; done < len; done += written)
6769 {
6770 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006771 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6772 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6774 FALSE, FALSE, context)
6775 || readcnt != todo
6776 || !WriteFile(hTo, buf, todo, &written, NULL)
6777 || written != todo)
6778 break;
6779 }
6780 CloseHandle(hTo);
6781 }
6782
6783 free(to_name);
6784}
6785
6786/*
6787 * Copy info streams from file "from" to file "to".
6788 */
6789 static void
6790copy_infostreams(char_u *from, char_u *to)
6791{
6792 WCHAR *fromw;
6793 WCHAR *tow;
6794 HANDLE sh;
6795 WIN32_STREAM_ID sid;
6796 int headersize;
6797 WCHAR streamname[_MAX_PATH];
6798 DWORD readcount;
6799 void *context = NULL;
6800 DWORD lo, hi;
6801 int len;
6802
6803 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006804 fromw = enc_to_utf16(from, NULL);
6805 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006806 if (fromw != NULL && tow != NULL)
6807 {
6808 /* Open the file for reading. */
6809 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6810 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6811 if (sh != INVALID_HANDLE_VALUE)
6812 {
6813 /* Use BackupRead() to find the info streams. Repeat until we
6814 * have done them all.*/
6815 for (;;)
6816 {
6817 /* Get the header to find the length of the stream name. If
6818 * the "readcount" is zero we have done all info streams. */
6819 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006820 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6822 &readcount, FALSE, FALSE, &context)
6823 || readcount == 0)
6824 break;
6825
6826 /* We only deal with streams that have a name. The normal
6827 * file data appears to be without a name, even though docs
6828 * suggest it is called "::$DATA". */
6829 if (sid.dwStreamNameSize > 0)
6830 {
6831 /* Read the stream name. */
6832 if (!BackupRead(sh, (LPBYTE)streamname,
6833 sid.dwStreamNameSize,
6834 &readcount, FALSE, FALSE, &context))
6835 break;
6836
6837 /* Copy an info stream with a name ":anything:$DATA".
6838 * Skip "::$DATA", it has no stream name (examples suggest
6839 * it might be used for the normal file contents).
6840 * Note that BackupRead() counts bytes, but the name is in
6841 * wide characters. */
6842 len = readcount / sizeof(WCHAR);
6843 streamname[len] = 0;
6844 if (len > 7 && wcsicmp(streamname + len - 6,
6845 L":$DATA") == 0)
6846 {
6847 streamname[len - 6] = 0;
6848 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006849 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 }
6851 }
6852
6853 /* Advance to the next stream. We might try seeking too far,
6854 * but BackupSeek() doesn't skip over stream borders, thus
6855 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006856 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 &lo, &hi, &context);
6858 }
6859
6860 /* Clear the context. */
6861 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6862
6863 CloseHandle(sh);
6864 }
6865 }
6866 vim_free(fromw);
6867 vim_free(tow);
6868}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869
6870/*
6871 * Copy file attributes from file "from" to file "to".
6872 * For Windows NT and later we copy info streams.
6873 * Always returns zero, errors are ignored.
6874 */
6875 int
6876mch_copy_file_attribute(char_u *from, char_u *to)
6877{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006879 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 return 0;
6881}
6882
6883#if defined(MYRESETSTKOFLW) || defined(PROTO)
6884/*
6885 * Recreate a destroyed stack guard page in win32.
6886 * Written by Benjamin Peterson.
6887 */
6888
6889/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006890# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891
6892/*
6893 * This function does the same thing as _resetstkoflw(), which is only
6894 * available in DevStudio .net and later.
6895 * Returns 0 for failure, 1 for success.
6896 */
6897 int
6898myresetstkoflw(void)
6899{
6900 BYTE *pStackPtr;
6901 BYTE *pGuardPage;
6902 BYTE *pStackBase;
6903 BYTE *pLowestPossiblePage;
6904 MEMORY_BASIC_INFORMATION mbi;
6905 SYSTEM_INFO si;
6906 DWORD nPageSize;
6907 DWORD dummy;
6908
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 /* We need to know the system page size. */
6910 GetSystemInfo(&si);
6911 nPageSize = si.dwPageSize;
6912
6913 /* ...and the current stack pointer */
6914 pStackPtr = (BYTE*)_alloca(1);
6915
6916 /* ...and the base of the stack. */
6917 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6918 return 0;
6919 pStackBase = (BYTE*)mbi.AllocationBase;
6920
6921 /* ...and the page thats min_stack_req pages away from stack base; this is
6922 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006923 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006926 /* We want the first committed page in the stack Start at the stack
6927 * base and move forward through memory until we find a committed block.
6928 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 BYTE *pBlock = pStackBase;
6930
Bram Moolenaara466c992005-07-09 21:03:22 +00006931 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 {
6933 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6934 return 0;
6935
6936 pBlock += mbi.RegionSize;
6937
6938 if (mbi.State & MEM_COMMIT)
6939 break;
6940 }
6941
6942 /* mbi now describes the first committed block in the stack. */
6943 if (mbi.Protect & PAGE_GUARD)
6944 return 1;
6945
6946 /* decide where the guard page should start */
6947 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6948 pGuardPage = pLowestPossiblePage;
6949 else
6950 pGuardPage = (BYTE*)mbi.BaseAddress;
6951
6952 /* allocate the guard page */
6953 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6954 return 0;
6955
6956 /* apply the guard attribute to the page */
6957 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6958 &dummy))
6959 return 0;
6960 }
6961
6962 return 1;
6963}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006966
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006967/*
6968 * The command line arguments in UCS2
6969 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006970static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006971static LPWSTR *ArglistW = NULL;
6972static int global_argc = 0;
6973static char **global_argv;
6974
6975static int used_file_argc = 0; /* last argument in global_argv[] used
6976 for the argument list. */
6977static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6978 command line arguments added to
6979 the argument list */
6980static int used_file_count = 0; /* nr of entries in used_file_indexes */
6981static int used_file_literal = FALSE; /* take file names literally */
6982static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006983static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006984static int used_alist_count = 0;
6985
6986
6987/*
6988 * Get the command line arguments. Unicode version.
6989 * Returns argc. Zero when something fails.
6990 */
6991 int
6992get_cmd_argsW(char ***argvp)
6993{
6994 char **argv = NULL;
6995 int argc = 0;
6996 int i;
6997
Bram Moolenaar14993322014-09-09 12:25:33 +02006998 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7000 if (ArglistW != NULL)
7001 {
7002 argv = malloc((nArgsW + 1) * sizeof(char *));
7003 if (argv != NULL)
7004 {
7005 argc = nArgsW;
7006 argv[argc] = NULL;
7007 for (i = 0; i < argc; ++i)
7008 {
7009 int len;
7010
7011 /* Convert each Unicode argument to the current codepage. */
7012 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007013 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007014 (LPSTR *)&argv[i], &len, 0, 0);
7015 if (argv[i] == NULL)
7016 {
7017 /* Out of memory, clear everything. */
7018 while (i > 0)
7019 free(argv[--i]);
7020 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007021 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007022 argc = 0;
7023 }
7024 }
7025 }
7026 }
7027
7028 global_argc = argc;
7029 global_argv = argv;
7030 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007031 {
7032 if (used_file_indexes != NULL)
7033 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007034 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007035 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007036
7037 if (argvp != NULL)
7038 *argvp = argv;
7039 return argc;
7040}
7041
7042 void
7043free_cmd_argsW(void)
7044{
7045 if (ArglistW != NULL)
7046 {
7047 GlobalFree(ArglistW);
7048 ArglistW = NULL;
7049 }
7050}
7051
7052/*
7053 * Remember "name" is an argument that was added to the argument list.
7054 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7055 * is called.
7056 */
7057 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007058used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007059{
7060 int i;
7061
7062 if (used_file_indexes == NULL)
7063 return;
7064 for (i = used_file_argc + 1; i < global_argc; ++i)
7065 if (STRCMP(global_argv[i], name) == 0)
7066 {
7067 used_file_argc = i;
7068 used_file_indexes[used_file_count++] = i;
7069 break;
7070 }
7071 used_file_literal = literal;
7072 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007073 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007074}
7075
7076/*
7077 * Remember the length of the argument list as it was. If it changes then we
7078 * leave it alone when 'encoding' is set.
7079 */
7080 void
7081set_alist_count(void)
7082{
7083 used_alist_count = GARGCOUNT;
7084}
7085
7086/*
7087 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7088 * has been changed while starting up. Use the UCS-2 command line arguments
7089 * and convert them to 'encoding'.
7090 */
7091 void
7092fix_arg_enc(void)
7093{
7094 int i;
7095 int idx;
7096 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007097 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007098
7099 /* Safety checks:
7100 * - if argument count differs between the wide and non-wide argument
7101 * list, something must be wrong.
7102 * - the file name arguments must have been located.
7103 * - the length of the argument list wasn't changed by the user.
7104 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007105 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007106 || ArglistW == NULL
7107 || used_file_indexes == NULL
7108 || used_file_count == 0
7109 || used_alist_count != GARGCOUNT)
7110 return;
7111
Bram Moolenaar86b68352004-12-27 21:59:20 +00007112 /* Remember the buffer numbers for the arguments. */
7113 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7114 if (fnum_list == NULL)
7115 return; /* out of memory */
7116 for (i = 0; i < GARGCOUNT; ++i)
7117 fnum_list[i] = GARGLIST[i].ae_fnum;
7118
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007119 /* Clear the argument list. Make room for the new arguments. */
7120 alist_clear(&global_alist);
7121 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007122 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007123
7124 for (i = 0; i < used_file_count; ++i)
7125 {
7126 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007127 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007128 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007129 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007130 int literal = used_file_literal;
7131
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007132# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007133 /* When using diff mode may need to concatenate file name to
7134 * directory name. Just like it's done in main(). */
7135 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7136 && !mch_isdir(alist_name(&GARGLIST[0])))
7137 {
7138 char_u *r;
7139
7140 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7141 if (r != NULL)
7142 {
7143 vim_free(str);
7144 str = r;
7145 }
7146 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007147# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007148 /* Re-use the old buffer by renaming it. When not using literal
7149 * names it's done by alist_expand() below. */
7150 if (used_file_literal)
7151 buf_set_name(fnum_list[i], str);
7152
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007153 /* Check backtick literal. backtick literal is already expanded in
7154 * main.c, so this part add str as literal. */
7155 if (literal == FALSE)
7156 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007157 size_t len = STRLEN(str);
7158
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007159 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7160 literal = TRUE;
7161 }
7162 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007163 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007164 }
7165
7166 if (!used_file_literal)
7167 {
7168 /* Now expand wildcards in the arguments. */
7169 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7170 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007171 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7172 * Also, unset wildignore to not be influenced by this option.
7173 * The arguments specified in command-line should be kept even if
7174 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007175 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007176 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007177 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007178 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007179 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007180 }
7181
7182 /* If wildcard expansion failed, we are editing the first file of the
7183 * arglist and there is no file name: Edit the first argument now. */
7184 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7185 {
7186 do_cmdline_cmd((char_u *)":rewind");
7187 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007188 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007189 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007190
7191 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007192}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007193
7194 int
7195mch_setenv(char *var, char *value, int x)
7196{
7197 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007198 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007199
7200 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7201 if (envbuf == NULL)
7202 return -1;
7203
7204 sprintf((char *)envbuf, "%s=%s", var, value);
7205
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007206 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007207
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007208 vim_free(envbuf);
7209 if (p == NULL)
7210 return -1;
7211 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007212#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007213 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007214#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007215 // Unlike Un*x systems, we can free the string for _wputenv().
7216 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007217
7218 return 0;
7219}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007220
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007221/*
7222 * Support for 256 colors and 24-bit colors was added in Windows 10
7223 * version 1703 (Creators update).
7224 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007225#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7226
7227/*
7228 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007229 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007230 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007231#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7232#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007233
7234 static void
7235vtp_flag_init(void)
7236{
7237 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007238#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007239 DWORD mode;
7240 HANDLE out;
7241
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007242# ifdef VIMDLL
7243 if (!gui.in_use)
7244# endif
7245 {
7246 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007247
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007248 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7249 GetConsoleMode(out, &mode);
7250 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7251 if (SetConsoleMode(out, mode) == 0)
7252 vtp_working = 0;
7253 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007254#endif
7255
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007256 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007257 conpty_working = 1;
7258 if (ver >= CONPTY_STABLE_BUILD)
7259 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007260
7261}
7262
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007263#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007264
7265 static void
7266vtp_init(void)
7267{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007268 HMODULE hKerneldll;
7269 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007270# ifdef FEAT_TERMGUICOLORS
7271 COLORREF fg, bg;
7272# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007273
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007274 /* Use functions supported from Vista */
7275 hKerneldll = GetModuleHandle("kernel32.dll");
7276 if (hKerneldll != NULL)
7277 {
7278 pGetConsoleScreenBufferInfoEx =
7279 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7280 hKerneldll, "GetConsoleScreenBufferInfoEx");
7281 pSetConsoleScreenBufferInfoEx =
7282 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7283 hKerneldll, "SetConsoleScreenBufferInfoEx");
7284 if (pGetConsoleScreenBufferInfoEx != NULL
7285 && pSetConsoleScreenBufferInfoEx != NULL)
7286 has_csbiex = TRUE;
7287 }
7288
7289 csbi.cbSize = sizeof(csbi);
7290 if (has_csbiex)
7291 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007292 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7293 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7294
7295# ifdef FEAT_TERMGUICOLORS
7296 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7297 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7298 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7299 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7300 default_console_color_bg = bg;
7301 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007302# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007303
7304 set_console_color_rgb();
7305}
7306
7307 static void
7308vtp_exit(void)
7309{
7310 reset_console_color_rgb();
7311}
7312
7313 static int
7314vtp_printf(
7315 char *format,
7316 ...)
7317{
7318 char_u buf[100];
7319 va_list list;
7320 DWORD result;
7321
7322 va_start(list, format);
7323 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7324 va_end(list);
7325 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7326 return (int)result;
7327}
7328
7329 static void
7330vtp_sgr_bulk(
7331 int arg)
7332{
7333 int args[1];
7334
7335 args[0] = arg;
7336 vtp_sgr_bulks(1, args);
7337}
7338
7339 static void
7340vtp_sgr_bulks(
7341 int argc,
7342 int *args
7343)
7344{
7345 /* 2('\033[') + 4('255.') * 16 + NUL */
7346 char_u buf[2 + (4 * 16) + 1];
7347 char_u *p;
7348 int i;
7349
7350 p = buf;
7351 *p++ = '\033';
7352 *p++ = '[';
7353
7354 for (i = 0; i < argc; ++i)
7355 {
7356 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7357 *p++ = ';';
7358 }
7359 p--;
7360 *p++ = 'm';
7361 *p = NUL;
7362 vtp_printf((char *)buf);
7363}
7364
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007365# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007366 static int
7367ctermtoxterm(
7368 int cterm)
7369{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007370 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007371
7372 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7373 return (((int)r << 16) | ((int)g << 8) | (int)b);
7374}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007375# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007376
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007377 static void
7378set_console_color_rgb(void)
7379{
7380# ifdef FEAT_TERMGUICOLORS
7381 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7382 int id;
7383 guicolor_T fg = INVALCOLOR;
7384 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007385 int ctermfg;
7386 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007387
7388 if (!USE_VTP)
7389 return;
7390
7391 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007392 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007393 syn_id2colors(id, &fg, &bg);
7394 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007395 {
7396 ctermfg = -1;
7397 if (id > 0)
7398 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007399 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7400 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007401 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007402 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007403 {
7404 ctermbg = -1;
7405 if (id > 0)
7406 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007407 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7408 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007409 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007410 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7411 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7412
7413 csbi.cbSize = sizeof(csbi);
7414 if (has_csbiex)
7415 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7416
7417 csbi.cbSize = sizeof(csbi);
7418 csbi.srWindow.Right += 1;
7419 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007420 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7421 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007422 if (has_csbiex)
7423 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7424# endif
7425}
7426
7427 static void
7428reset_console_color_rgb(void)
7429{
7430# ifdef FEAT_TERMGUICOLORS
7431 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7432
7433 csbi.cbSize = sizeof(csbi);
7434 if (has_csbiex)
7435 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7436
7437 csbi.cbSize = sizeof(csbi);
7438 csbi.srWindow.Right += 1;
7439 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007440 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7441 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007442 if (has_csbiex)
7443 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7444# endif
7445}
7446
7447 void
7448control_console_color_rgb(void)
7449{
7450 if (USE_VTP)
7451 set_console_color_rgb();
7452 else
7453 reset_console_color_rgb();
7454}
7455
7456 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007457use_vtp(void)
7458{
7459 return USE_VTP;
7460}
7461
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007462 int
7463is_term_win32(void)
7464{
7465 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7466}
7467
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007468 int
7469has_vtp_working(void)
7470{
7471 return vtp_working;
7472}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007473
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007474#endif
7475
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007476 int
7477has_conpty_working(void)
7478{
7479 return conpty_working;
7480}
7481
7482 int
7483is_conpty_stable(void)
7484{
7485 return conpty_stable;
7486}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007487
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007488#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007489 void
7490resize_console_buf(void)
7491{
7492 CONSOLE_SCREEN_BUFFER_INFO csbi;
7493 COORD coord;
7494 SMALL_RECT newsize;
7495
7496 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7497 {
7498 coord.X = SRWIDTH(csbi.srWindow);
7499 coord.Y = SRHEIGHT(csbi.srWindow);
7500 SetConsoleScreenBufferSize(g_hConOut, coord);
7501
7502 newsize.Left = 0;
7503 newsize.Top = 0;
7504 newsize.Right = coord.X - 1;
7505 newsize.Bottom = coord.Y - 1;
7506 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7507
7508 SetConsoleScreenBufferSize(g_hConOut, coord);
7509 }
7510}
7511#endif