blob: 97fc2a401b5e281f75e27f12d043a01118ba1d8b [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
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <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
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# 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
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100174static void set_scroll_region_tb(unsigned top, unsigned bottom);
175static void set_scroll_region_lr(unsigned left, unsigned right);
176static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static void delete_lines(unsigned cLines);
178static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_cursor_visible = TRUE;
181static int did_create_conin = FALSE;
182#else
183static int s_dont_use_vimrun = TRUE;
184static int need_vimrun_warning = FALSE;
185static char *vimrun_path = "vimrun ";
186#endif
187
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200188static int win32_getattrs(char_u *name);
189static int win32_setattrs(char_u *name, int attrs);
190static int win32_set_archive(char_u *name);
191
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100192static int conpty_working = 0;
193static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100194static void vtp_flag_init();
195
196#ifndef FEAT_GUI_W32
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100197static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100198static void vtp_init();
199static void vtp_exit();
200static int vtp_printf(char *format, ...);
201static void vtp_sgr_bulk(int arg);
202static void vtp_sgr_bulks(int argc, int *argv);
203
204static guicolor_T save_console_bg_rgb;
205static guicolor_T save_console_fg_rgb;
206
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200207static int g_color_index_bg = 0;
208static int g_color_index_fg = 7;
209
210# ifdef FEAT_TERMGUICOLORS
211static int default_console_color_bg = 0x000000; // black
212static int default_console_color_fg = 0xc0c0c0; // white
213# endif
214
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100215# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200216# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100217# else
218# define USE_VTP 0
219# endif
220
221static void set_console_color_rgb(void);
222static void reset_console_color_rgb(void);
223#endif
224
225/* This flag is newly created from Windows 10 */
226#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
227# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
228#endif
229
230#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231static int suppress_winsize = 1; /* don't fiddle with console */
232#endif
233
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200234static char_u *exe_path = NULL;
235
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100236static BOOL win8_or_later = FALSE;
237
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100238#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100239/* Dynamic loading for portability */
240typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
241{
242 ULONG cbSize;
243 COORD dwSize;
244 COORD dwCursorPosition;
245 WORD wAttributes;
246 SMALL_RECT srWindow;
247 COORD dwMaximumWindowSize;
248 WORD wPopupAttributes;
249 BOOL bFullscreenSupported;
250 COLORREF ColorTable[16];
251} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
252typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
253static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
254typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
255static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
256static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100257#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100258
259/*
260 * Get version number including build number
261 */
262typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
263# define MAKE_VER(major, minor, build) \
264 (((major) << 24) | ((minor) << 16) | (build))
265
266 static DWORD
267get_build_number(void)
268{
269 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
270 HMODULE hNtdll;
271 PfnRtlGetVersion pRtlGetVersion;
272 DWORD ver = MAKE_VER(0, 0, 0);
273
274 hNtdll = GetModuleHandle("ntdll.dll");
275 if (hNtdll != NULL)
276 {
277 pRtlGetVersion =
278 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
279 pRtlGetVersion(&osver);
280 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
281 min(osver.dwMinorVersion, 255),
282 min(osver.dwBuildNumber, 32767));
283 }
284 return ver;
285}
286
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100287#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100288/*
289 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100291 */
292 static BOOL
293read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
299 enum
300 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100301 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100303 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100304 static DWORD s_dwIndex = 0;
305 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100306 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307 int head;
308 int tail;
309 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200311 if (nLength == -2)
312 return (s_dwMax > 0) ? TRUE : FALSE;
313
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100314 if (!win8_or_later)
315 {
316 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200317 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
318 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100319 }
320
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100321 if (s_dwMax == 0)
322 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200324 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
325 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100327 s_dwIndex = 0;
328 s_dwMax = dwEvents;
329 if (dwEvents == 0)
330 {
331 *lpEvents = 0;
332 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100333 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100334
335 if (s_dwMax > 1)
336 {
337 head = 0;
338 tail = s_dwMax - 1;
339 while (head != tail)
340 {
341 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
342 && s_irCache[head + 1].EventType
343 == WINDOW_BUFFER_SIZE_EVENT)
344 {
345 /* Remove duplicate event to avoid flicker. */
346 for (i = head; i < tail; ++i)
347 s_irCache[i] = s_irCache[i + 1];
348 --tail;
349 continue;
350 }
351 head++;
352 }
353 s_dwMax = tail + 1;
354 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100356
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100357 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200358 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100359 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100360 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100361 return TRUE;
362}
363
364/*
365 * Version of PeekConsoleInput() that works with IME.
366 */
367 static BOOL
368peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100369 HANDLE hInput,
370 INPUT_RECORD *lpBuffer,
371 DWORD nLength,
372 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100373{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100374 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100375}
376
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100377# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200378 static DWORD
379msg_wait_for_multiple_objects(
380 DWORD nCount,
381 LPHANDLE pHandles,
382 BOOL fWaitAll,
383 DWORD dwMilliseconds,
384 DWORD dwWakeMask)
385{
386 if (read_console_input(NULL, NULL, -2, NULL))
387 return WAIT_OBJECT_0;
388 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
389 dwMilliseconds, dwWakeMask);
390}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100391# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200392
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100393# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200394 static DWORD
395wait_for_single_object(
396 HANDLE hHandle,
397 DWORD dwMilliseconds)
398{
399 if (read_console_input(NULL, NULL, -2, NULL))
400 return WAIT_OBJECT_0;
401 return WaitForSingleObject(hHandle, dwMilliseconds);
402}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100403# endif
404#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200405
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 static void
407get_exe_name(void)
408{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100409 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
410 * as the maximum length that works (plus a NUL byte). */
411#define MAX_ENV_PATH_LEN 8192
412 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200413 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414
415 if (exe_name == NULL)
416 {
417 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100418 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 if (*temp != NUL)
420 exe_name = FullName_save((char_u *)temp, FALSE);
421 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000422
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200425 exe_path = vim_strnsave(exe_name,
426 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000428 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200429 /* Append our starting directory to $PATH, so that when doing
430 * "!xxd" it's found in our starting directory. Needed because
431 * SearchPath() also looks there. */
432 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100433 if (p == NULL
434 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100436 if (p == NULL || *p == NUL)
437 temp[0] = NUL;
438 else
439 {
440 STRCPY(temp, p);
441 STRCAT(temp, ";");
442 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100444 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200445 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000446 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448}
449
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200450/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100451 * Unescape characters in "p" that appear in "escaped".
452 */
453 static void
454unescape_shellxquote(char_u *p, char_u *escaped)
455{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100456 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100457 int n;
458
459 while (*p != NUL)
460 {
461 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
462 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100463 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100464 p += n;
465 l -= n;
466 }
467}
468
469/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200470 * Load library "name".
471 */
472 HINSTANCE
473vimLoadLib(char *name)
474{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200475 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200477 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
478 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL)
480 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200481 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200483 WCHAR old_dirw[MAXPATHL];
484
485 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
486 {
487 /* Change directory to where the executable is, both to make
488 * sure we find a .dll there and to avoid looking for a .dll
489 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100490 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200491 dll = LoadLibrary(name);
492 SetCurrentDirectoryW(old_dirw);
493 return dll;
494 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200495 }
496 return dll;
497}
498
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100499#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
500/*
501 * Get related information about 'funcname' which is imported by 'hInst'.
502 * If 'info' is 0, return the function address.
503 * If 'info' is 1, return the module name which the function is imported from.
504 */
505 static void *
506get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
507{
508 PBYTE pImage = (PBYTE)hInst;
509 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
510 PIMAGE_NT_HEADERS pPE;
511 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
512 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
513 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
514 PIMAGE_IMPORT_BY_NAME pImpName;
515
516 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
517 return NULL;
518 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
519 if (pPE->Signature != IMAGE_NT_SIGNATURE)
520 return NULL;
521 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
522 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
523 .VirtualAddress);
524 for (; pImpDesc->FirstThunk; ++pImpDesc)
525 {
526 if (!pImpDesc->OriginalFirstThunk)
527 continue;
528 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
529 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
530 for (; pIAT->u1.Function; ++pIAT, ++pINT)
531 {
532 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
533 continue;
534 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
535 + (UINT_PTR)(pINT->u1.AddressOfData));
536 if (strcmp((char *)pImpName->Name, funcname) == 0)
537 {
538 switch (info)
539 {
540 case 0:
541 return (void *)pIAT->u1.Function;
542 case 1:
543 return (void *)(pImage + pImpDesc->Name);
544 default:
545 return NULL;
546 }
547 }
548 }
549 }
550 return NULL;
551}
552
553/*
554 * Get the module handle which 'funcname' in 'hInst' is imported from.
555 */
556 HINSTANCE
557find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
558{
559 char *modulename;
560
561 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
562 if (modulename != NULL)
563 return GetModuleHandleA(modulename);
564 return NULL;
565}
566
567/*
568 * Get the address of 'funcname' which is imported by 'hInst' DLL.
569 */
570 void *
571get_dll_import_func(HINSTANCE hInst, const char *funcname)
572{
573 return get_imported_func_info(hInst, funcname, 0);
574}
575#endif
576
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
578# ifndef GETTEXT_DLL
579# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200580# define GETTEXT_DLL_ALT1 "libintl-8.dll"
581# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200583/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000584static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200585static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586static char *null_libintl_textdomain(const char *);
587static char *null_libintl_bindtextdomain(const char *, const char *);
588static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100589static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100590static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200592static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000593char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200594char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
595 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000596char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
597char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000599char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
600 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100601int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100602int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100605dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606{
607 int i;
608 static struct
609 {
610 char *name;
611 FARPROC *ptr;
612 } libintl_entry[] =
613 {
614 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200615 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
617 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
618 {NULL, NULL}
619 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621
Bram Moolenaar7554c542018-10-06 15:03:15 +0200622 // No need to initialize twice.
623 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100626 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200627#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100628 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
630#endif
631#ifdef GETTEXT_DLL_ALT2
632 if (!hLibintlDLL)
633 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100634#endif
635 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100640 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200641 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200643 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644 }
645 for (i = 0; libintl_entry[i].name != NULL
646 && libintl_entry[i].ptr != NULL; ++i)
647 {
648 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
649 libintl_entry[i].name)) == NULL)
650 {
651 dyn_libintl_end();
652 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000653 {
654 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100655 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000656 verbose_leave();
657 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 return 0;
659 }
660 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000661
662 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000663 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000664 "bind_textdomain_codeset");
665 if (dyn_libintl_bind_textdomain_codeset == NULL)
666 dyn_libintl_bind_textdomain_codeset =
667 null_libintl_bind_textdomain_codeset;
668
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 /* _putenv() function for the libintl.dll is optional. */
670 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
671 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100672 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
675 }
676 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100677 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100678 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
679 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681 return 1;
682}
683
684 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100685dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686{
687 if (hLibintlDLL)
688 FreeLibrary(hLibintlDLL);
689 hLibintlDLL = NULL;
690 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200691 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 dyn_libintl_textdomain = null_libintl_textdomain;
693 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000694 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100695 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100696 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697}
698
699 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000700null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701{
702 return (char*)msgid;
703}
704
705 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200706null_libintl_ngettext(
707 const char *msgid,
708 const char *msgid_plural,
709 unsigned long n)
710{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200711 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200712}
713
Bram Moolenaaree695f72016-08-03 22:08:45 +0200714 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100715null_libintl_bindtextdomain(
716 const char *domainname UNUSED,
717 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718{
719 return NULL;
720}
721
722 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100723null_libintl_bind_textdomain_codeset(
724 const char *domainname UNUSED,
725 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000726{
727 return NULL;
728}
729
730 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100731null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732{
733 return NULL;
734}
735
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200736 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100737null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100738{
739 return 0;
740}
741
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200742 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100743null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100744{
745 return 0;
746}
747
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748#endif /* DYNAMIC_GETTEXT */
749
750/* This symbol is not defined in older versions of the SDK or Visual C++ */
751
752#ifndef VER_PLATFORM_WIN32_WINDOWS
753# define VER_PLATFORM_WIN32_WINDOWS 1
754#endif
755
756DWORD g_PlatformId;
757
758#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100759# ifndef PROTO
760# include <aclapi.h>
761# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200762# ifndef PROTECTED_DACL_SECURITY_INFORMATION
763# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
764# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765#endif
766
Bram Moolenaar27515922013-06-29 15:36:26 +0200767#ifdef HAVE_ACL
768/*
769 * Enables or disables the specified privilege.
770 */
771 static BOOL
772win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
773{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100774 BOOL bResult;
775 LUID luid;
776 HANDLE hToken;
777 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200778
779 if (!OpenProcessToken(GetCurrentProcess(),
780 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
781 return FALSE;
782
783 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
784 {
785 CloseHandle(hToken);
786 return FALSE;
787 }
788
Bram Moolenaar45500912014-07-09 20:51:07 +0200789 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200790 tokenPrivileges.Privileges[0].Luid = luid;
791 tokenPrivileges.Privileges[0].Attributes = bEnable ?
792 SE_PRIVILEGE_ENABLED : 0;
793
794 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
795 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
796
797 CloseHandle(hToken);
798
799 return bResult && GetLastError() == ERROR_SUCCESS;
800}
801#endif
802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803/*
804 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
805 * VER_PLATFORM_WIN32_WINDOWS (Win95).
806 */
807 void
808PlatformId(void)
809{
810 static int done = FALSE;
811
812 if (!done)
813 {
814 OSVERSIONINFO ovi;
815
816 ovi.dwOSVersionInfoSize = sizeof(ovi);
817 GetVersionEx(&ovi);
818
819 g_PlatformId = ovi.dwPlatformId;
820
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100821 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
822 || ovi.dwMajorVersion > 6)
823 win8_or_later = TRUE;
824
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200826 /* Enable privilege for getting or setting SACLs. */
827 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828#endif
829 done = TRUE;
830 }
831}
832
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833#ifndef FEAT_GUI_W32
834
835#define SHIFT (SHIFT_PRESSED)
836#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
837#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
838#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
839
840
841/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
842 * We map function keys to their ANSI terminal equivalents, as produced
843 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
844 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
845 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
846 * combinations of function/arrow/etc keys.
847 */
848
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000849static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850{
851 WORD wVirtKey;
852 BOOL fAnsiKey;
853 int chAlone;
854 int chShift;
855 int chCtrl;
856 int chAlt;
857} VirtKeyMap[] =
858{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200859// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
861
862 { VK_F1, TRUE, ';', 'T', '^', 'h', },
863 { VK_F2, TRUE, '<', 'U', '_', 'i', },
864 { VK_F3, TRUE, '=', 'V', '`', 'j', },
865 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
866 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
867 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
868 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
869 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
870 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
871 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200872 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
873 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200875 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
876 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
877 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
878 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
879 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
880 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
881 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
882 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
883 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
884 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200886 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200889 // Most people don't have F13-F20, but what the hell...
890 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
891 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
892 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
893 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
894 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
895 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
896 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
897 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200899 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
900 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
901 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
902 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200904 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
905 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
906 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
907 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
908 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
909 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
910 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
911 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
912 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
913 // Sorry, out of number space! <negri>
914 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
915
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916};
917
918
919#ifdef _MSC_VER
920// The ToAscii bug destroys several registers. Need to turn off optimization
921// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000922# pragma warning(push)
923# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924# pragma optimize("", off)
925#endif
926
927#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200928# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931#endif
932
933/* The return code indicates key code size. */
934 static int
935#ifdef __BORLANDC__
936 __stdcall
937#endif
938win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000939 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940{
941 UINT uMods = pker->dwControlKeyState;
942 static int s_iIsDead = 0;
943 static WORD awAnsiCode[2];
944 static BYTE abKeystate[256];
945
946
947 if (s_iIsDead == 2)
948 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 s_iIsDead = 0;
951 return 1;
952 }
953
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200954 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 return 1;
956
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200957 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200960 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (uMods & SHIFT_PRESSED)
963 abKeystate[VK_SHIFT] = 0x80;
964 if (uMods & CAPSLOCK_ON)
965 abKeystate[VK_CAPITAL] = 1;
966
967 if ((uMods & ALT_GR) == ALT_GR)
968 {
969 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
970 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
971 }
972
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
974 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200977 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
979 return s_iIsDead;
980}
981
982#ifdef _MSC_VER
983/* MUST switch optimization on again here, otherwise a call to
984 * decode_key_event() may crash (e.g. when hitting caps-lock) */
985# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000986# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988# if (_MSC_VER < 1100)
989/* MUST turn off global optimisation for this next function, or
990 * pressing ctrl-minus in insert mode crashes Vim when built with
991 * VC4.1. -- negri. */
992# pragma optimize("g", off)
993# endif
994#endif
995
996static BOOL g_fJustGotFocus = FALSE;
997
998/*
999 * Decode a KEY_EVENT into one or two keystrokes
1000 */
1001 static BOOL
1002decode_key_event(
1003 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001004 WCHAR *pch,
1005 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 int *pmodifiers,
1007 BOOL fDoPost)
1008{
1009 int i;
1010 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1011
1012 *pch = *pch2 = NUL;
1013 g_fJustGotFocus = FALSE;
1014
1015 /* ignore key up events */
1016 if (!pker->bKeyDown)
1017 return FALSE;
1018
1019 /* ignore some keystrokes */
1020 switch (pker->wVirtualKeyCode)
1021 {
1022 /* modifiers */
1023 case VK_SHIFT:
1024 case VK_CONTROL:
1025 case VK_MENU: /* Alt key */
1026 return FALSE;
1027
1028 default:
1029 break;
1030 }
1031
1032 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001033 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 {
1035 /* Ctrl-6 is Ctrl-^ */
1036 if (pker->wVirtualKeyCode == '6')
1037 {
1038 *pch = Ctrl_HAT;
1039 return TRUE;
1040 }
1041 /* Ctrl-2 is Ctrl-@ */
1042 else if (pker->wVirtualKeyCode == '2')
1043 {
1044 *pch = NUL;
1045 return TRUE;
1046 }
1047 /* Ctrl-- is Ctrl-_ */
1048 else if (pker->wVirtualKeyCode == 0xBD)
1049 {
1050 *pch = Ctrl__;
1051 return TRUE;
1052 }
1053 }
1054
1055 /* Shift-TAB */
1056 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1057 {
1058 *pch = K_NUL;
1059 *pch2 = '\017';
1060 return TRUE;
1061 }
1062
1063 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1064 {
1065 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1066 {
1067 if (nModifs == 0)
1068 *pch = VirtKeyMap[i].chAlone;
1069 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1070 *pch = VirtKeyMap[i].chShift;
1071 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1072 *pch = VirtKeyMap[i].chCtrl;
1073 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1074 *pch = VirtKeyMap[i].chAlt;
1075
1076 if (*pch != 0)
1077 {
1078 if (VirtKeyMap[i].fAnsiKey)
1079 {
1080 *pch2 = *pch;
1081 *pch = K_NUL;
1082 }
1083
1084 return TRUE;
1085 }
1086 }
1087 }
1088
1089 i = win32_kbd_patch_key(pker);
1090
1091 if (i < 0)
1092 *pch = NUL;
1093 else
1094 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001095 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (pmodifiers != NULL)
1098 {
1099 /* Pass on the ALT key as a modifier, but only when not combined
1100 * with CTRL (which is ALTGR). */
1101 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1102 *pmodifiers |= MOD_MASK_ALT;
1103
1104 /* Pass on SHIFT only for special keys, because we don't know when
1105 * it's already included with the character. */
1106 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1107 *pmodifiers |= MOD_MASK_SHIFT;
1108
1109 /* Pass on CTRL only for non-special keys, because we don't know
1110 * when it's already included with the character. And not when
1111 * combined with ALT (which is ALTGR). */
1112 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1113 && *pch >= 0x20 && *pch < 0x80)
1114 *pmodifiers |= MOD_MASK_CTRL;
1115 }
1116 }
1117
1118 return (*pch != NUL);
1119}
1120
1121#ifdef _MSC_VER
1122# pragma optimize("", on)
1123#endif
1124
1125#endif /* FEAT_GUI_W32 */
1126
1127
1128#ifdef FEAT_MOUSE
1129
1130/*
1131 * For the GUI the mouse handling is in gui_w32.c.
1132 */
1133# ifdef FEAT_GUI_W32
1134 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001135mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136{
1137}
1138# else
1139static int g_fMouseAvail = FALSE; /* mouse present */
1140static int g_fMouseActive = FALSE; /* mouse enabled */
1141static int g_nMouseClick = -1; /* mouse status */
1142static int g_xMouse; /* mouse x coordinate */
1143static int g_yMouse; /* mouse y coordinate */
1144
1145/*
1146 * Enable or disable mouse input
1147 */
1148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001149mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150{
1151 DWORD cmodein;
1152
1153 if (!g_fMouseAvail)
1154 return;
1155
1156 g_fMouseActive = on;
1157 GetConsoleMode(g_hConIn, &cmodein);
1158
1159 if (g_fMouseActive)
1160 cmodein |= ENABLE_MOUSE_INPUT;
1161 else
1162 cmodein &= ~ENABLE_MOUSE_INPUT;
1163
1164 SetConsoleMode(g_hConIn, cmodein);
1165}
1166
Bram Moolenaar157d8132018-03-06 17:09:20 +01001167
1168#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1169/*
1170 * Called when 'balloonevalterm' changed.
1171 */
1172 void
1173mch_bevalterm_changed(void)
1174{
1175 mch_setmouse(g_fMouseActive);
1176}
1177#endif
1178
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179/*
1180 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1181 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1182 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1183 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1184 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1185 * and we return the mouse position in g_xMouse and g_yMouse.
1186 *
1187 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1188 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1189 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1190 *
1191 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1192 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1193 *
1194 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1195 * moves, even if it stays within the same character cell. We ignore
1196 * all MOUSE_MOVED messages if the position hasn't really changed, and
1197 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1198 * we're only interested in MOUSE_DRAG).
1199 *
1200 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1201 * 2-button mouses by pressing the left & right buttons simultaneously.
1202 * In practice, it's almost impossible to click both at the same time,
1203 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1204 * in such cases, if the user is clicking quickly.
1205 */
1206 static BOOL
1207decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001208 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209{
1210 static int s_nOldButton = -1;
1211 static int s_nOldMouseClick = -1;
1212 static int s_xOldMouse = -1;
1213 static int s_yOldMouse = -1;
1214 static linenr_T s_old_topline = 0;
1215#ifdef FEAT_DIFF
1216 static int s_old_topfill = 0;
1217#endif
1218 static int s_cClicks = 1;
1219 static BOOL s_fReleased = TRUE;
1220 static DWORD s_dwLastClickTime = 0;
1221 static BOOL s_fNextIsMiddle = FALSE;
1222
1223 static DWORD cButtons = 0; /* number of buttons supported */
1224
1225 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1226 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1227 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1228 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1229
1230 int nButton;
1231
1232 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1233 cButtons = 2;
1234
1235 if (!g_fMouseAvail || !g_fMouseActive)
1236 {
1237 g_nMouseClick = -1;
1238 return FALSE;
1239 }
1240
1241 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1242 if (g_fJustGotFocus)
1243 {
1244 g_fJustGotFocus = FALSE;
1245 return FALSE;
1246 }
1247
1248 /* unprocessed mouse click? */
1249 if (g_nMouseClick != -1)
1250 return TRUE;
1251
1252 nButton = -1;
1253 g_xMouse = pmer->dwMousePosition.X;
1254 g_yMouse = pmer->dwMousePosition.Y;
1255
1256 if (pmer->dwEventFlags == MOUSE_MOVED)
1257 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001258 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 * events even when the mouse moves only within a char cell.) */
1260 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1261 return FALSE;
1262 }
1263
1264 /* If no buttons are pressed... */
1265 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1266 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 nButton = MOUSE_RELEASE;
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1270 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001271 {
1272#ifdef FEAT_BEVAL_TERM
1273 /* do return mouse move events when we want them */
1274 if (p_bevalterm)
1275 nButton = MOUSE_DRAG;
1276 else
1277#endif
1278 return FALSE;
1279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 s_fReleased = TRUE;
1282 }
1283 else /* one or more buttons pressed */
1284 {
1285 /* on a 2-button mouse, hold down left and right buttons
1286 * simultaneously to get MIDDLE. */
1287
1288 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1289 {
1290 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1291
1292 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001293 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 if (dwLR == LEFT || dwLR == RIGHT)
1295 {
1296 for (;;)
1297 {
1298 /* wait a short time for next input event */
1299 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1300 != WAIT_OBJECT_0)
1301 break;
1302 else
1303 {
1304 DWORD cRecords = 0;
1305 INPUT_RECORD ir;
1306 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1307
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001308 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001309
1310 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1311 || !(pmer2->dwButtonState & LEFT_RIGHT))
1312 break;
1313 else
1314 {
1315 if (pmer2->dwEventFlags != MOUSE_MOVED)
1316 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 return decode_mouse_event(pmer2);
1320 }
1321 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1322 s_yOldMouse == pmer2->dwMousePosition.Y)
1323 {
1324 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001328 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1331 break;
1332 }
1333 else
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 if (s_fNextIsMiddle)
1342 {
1343 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1344 ? MOUSE_DRAG : MOUSE_MIDDLE;
1345 s_fNextIsMiddle = FALSE;
1346 }
1347 else if (cButtons == 2 &&
1348 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1349 {
1350 nButton = MOUSE_MIDDLE;
1351
1352 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1353 {
1354 s_fNextIsMiddle = TRUE;
1355 nButton = MOUSE_RELEASE;
1356 }
1357 }
1358 else if ((pmer->dwButtonState & LEFT) == LEFT)
1359 nButton = MOUSE_LEFT;
1360 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1361 nButton = MOUSE_MIDDLE;
1362 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1363 nButton = MOUSE_RIGHT;
1364
1365 if (! s_fReleased && ! s_fNextIsMiddle
1366 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1367 return FALSE;
1368
1369 s_fReleased = s_fNextIsMiddle;
1370 }
1371
1372 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1373 {
1374 /* button pressed or released, without mouse moving */
1375 if (nButton != -1 && nButton != MOUSE_RELEASE)
1376 {
1377 DWORD dwCurrentTime = GetTickCount();
1378
1379 if (s_xOldMouse != g_xMouse
1380 || s_yOldMouse != g_yMouse
1381 || s_nOldButton != nButton
1382 || s_old_topline != curwin->w_topline
1383#ifdef FEAT_DIFF
1384 || s_old_topfill != curwin->w_topfill
1385#endif
1386 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1387 {
1388 s_cClicks = 1;
1389 }
1390 else if (++s_cClicks > 4)
1391 {
1392 s_cClicks = 1;
1393 }
1394
1395 s_dwLastClickTime = dwCurrentTime;
1396 }
1397 }
1398 else if (pmer->dwEventFlags == MOUSE_MOVED)
1399 {
1400 if (nButton != -1 && nButton != MOUSE_RELEASE)
1401 nButton = MOUSE_DRAG;
1402
1403 s_cClicks = 1;
1404 }
1405
1406 if (nButton == -1)
1407 return FALSE;
1408
1409 if (nButton != MOUSE_RELEASE)
1410 s_nOldButton = nButton;
1411
1412 g_nMouseClick = nButton;
1413
1414 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1415 g_nMouseClick |= MOUSE_SHIFT;
1416 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1417 g_nMouseClick |= MOUSE_CTRL;
1418 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1419 g_nMouseClick |= MOUSE_ALT;
1420
1421 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1422 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1423
1424 /* only pass on interesting (i.e., different) mouse events */
1425 if (s_xOldMouse == g_xMouse
1426 && s_yOldMouse == g_yMouse
1427 && s_nOldMouseClick == g_nMouseClick)
1428 {
1429 g_nMouseClick = -1;
1430 return FALSE;
1431 }
1432
1433 s_xOldMouse = g_xMouse;
1434 s_yOldMouse = g_yMouse;
1435 s_old_topline = curwin->w_topline;
1436#ifdef FEAT_DIFF
1437 s_old_topfill = curwin->w_topfill;
1438#endif
1439 s_nOldMouseClick = g_nMouseClick;
1440
1441 return TRUE;
1442}
1443
1444# endif /* FEAT_GUI_W32 */
1445#endif /* FEAT_MOUSE */
1446
1447
1448#ifdef MCH_CURSOR_SHAPE
1449/*
1450 * Set the shape of the cursor.
1451 * 'thickness' can be from 1 (thin) to 99 (block)
1452 */
1453 static void
1454mch_set_cursor_shape(int thickness)
1455{
1456 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1457 ConsoleCursorInfo.dwSize = thickness;
1458 ConsoleCursorInfo.bVisible = s_cursor_visible;
1459
1460 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1461 if (s_cursor_visible)
1462 SetConsoleCursorPosition(g_hConOut, g_coord);
1463}
1464
1465 void
1466mch_update_cursor(void)
1467{
1468 int idx;
1469 int thickness;
1470
1471 /*
1472 * How the cursor is drawn depends on the current mode.
1473 */
1474 idx = get_shape_idx(FALSE);
1475
1476 if (shape_table[idx].shape == SHAPE_BLOCK)
1477 thickness = 99; /* 100 doesn't work on W95 */
1478 else
1479 thickness = shape_table[idx].percentage;
1480 mch_set_cursor_shape(thickness);
1481}
1482#endif
1483
1484#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1485/*
1486 * Handle FOCUS_EVENT.
1487 */
1488 static void
1489handle_focus_event(INPUT_RECORD ir)
1490{
1491 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1492 ui_focus_change((int)g_fJustGotFocus);
1493}
1494
1495/*
1496 * Wait until console input from keyboard or mouse is available,
1497 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001498 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 * Return TRUE if something is available FALSE if not.
1500 */
1501 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001502WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503{
1504 DWORD dwNow = 0, dwEndTime = 0;
1505 INPUT_RECORD ir;
1506 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001507 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001508#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001509 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511
1512 if (msec > 0)
1513 /* Wait until the specified time has elapsed. */
1514 dwEndTime = GetTickCount() + msec;
1515 else if (msec < 0)
1516 /* Wait forever. */
1517 dwEndTime = INFINITE;
1518
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001519 // We need to loop until the end of the time period, because
1520 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 for (;;)
1522 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 // Only process messages when waiting.
1524 if (msec != 0)
1525 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001526#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001527 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001528#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001529#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001530 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001531#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001533 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001535 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001536
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 if (0
1538#ifdef FEAT_MOUSE
1539 || g_nMouseClick != -1
1540#endif
1541#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001542 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543#endif
1544 )
1545 return TRUE;
1546
1547 if (msec > 0)
1548 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001549 /* If the specified wait time has passed, return. Beware that
1550 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001552 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 break;
1554 }
1555 if (msec != 0)
1556 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001557 DWORD dwWaitTime = dwEndTime - dwNow;
1558
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001559#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001560 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001561 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001562 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001563 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001564 /* If there is readahead then parse_queued_messages() timed out
1565 * and we should call it again soon. */
1566 if (channel_any_readahead())
1567 dwWaitTime = 10;
1568 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001569#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001570#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001571 if (p_beval && dwWaitTime > 100)
1572 /* The 'balloonexpr' may indirectly invoke a callback while
1573 * waiting for a character, need to check often. */
1574 dwWaitTime = 100;
1575#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001576#ifdef FEAT_MZSCHEME
1577 if (mzthreads_allowed() && p_mzq > 0
1578 && (msec < 0 || (long)dwWaitTime > p_mzq))
1579 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1580#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001581#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001582 // When waiting very briefly don't trigger timers.
1583 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001584 {
1585 long due_time;
1586
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001587 // Trigger timers and then get the time in msec until the next
1588 // one is due. Wait up to that time.
1589 due_time = check_due_timer();
1590 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001591 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001592 // timer may have used feedkeys().
1593 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001594 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001595 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1596 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001597 }
1598#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001599 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001601 // Wait for either an event on the console input or a
1602 // message in the client-server window.
1603 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1604 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001606 wait_for_single_object(g_hConIn, dwWaitTime)
1607 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001609 )
1610 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 }
1612
1613 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001614 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615
1616#ifdef FEAT_MBYTE_IME
1617 if (State & CMDLINE && msg_row == Rows - 1)
1618 {
1619 CONSOLE_SCREEN_BUFFER_INFO csbi;
1620
1621 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1622 {
1623 if (csbi.dwCursorPosition.Y != msg_row)
1624 {
1625 /* The screen is now messed up, must redraw the
1626 * command line and later all the windows. */
1627 redraw_all_later(CLEAR);
1628 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1629 redrawcmd();
1630 }
1631 }
1632 }
1633#endif
1634
1635 if (cRecords > 0)
1636 {
1637 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1638 {
1639#ifdef FEAT_MBYTE_IME
1640 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1641 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001642 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1644 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001645 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 continue;
1647 }
1648#endif
1649 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1650 NULL, FALSE))
1651 return TRUE;
1652 }
1653
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001654 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655
1656 if (ir.EventType == FOCUS_EVENT)
1657 handle_focus_event(ir);
1658 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001659 {
1660 /* Only call shell_resized() when the size actually change to
1661 * avoid the screen is cleard. */
1662 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1663 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1664 shell_resized();
1665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666#ifdef FEAT_MOUSE
1667 else if (ir.EventType == MOUSE_EVENT
1668 && decode_mouse_event(&ir.Event.MouseEvent))
1669 return TRUE;
1670#endif
1671 }
1672 else if (msec == 0)
1673 break;
1674 }
1675
1676#ifdef FEAT_CLIENTSERVER
1677 /* Something might have been received while we were waiting. */
1678 if (input_available())
1679 return TRUE;
1680#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001681
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 return FALSE;
1683}
1684
1685#ifndef FEAT_GUI_MSWIN
1686/*
1687 * return non-zero if a character is available
1688 */
1689 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001690mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001692 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001694
1695# if defined(FEAT_TERMINAL) || defined(PROTO)
1696/*
1697 * Check for any pending input or messages.
1698 */
1699 int
1700mch_check_messages(void)
1701{
1702 return WaitForChar(0L, TRUE);
1703}
1704# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705#endif
1706
1707/*
1708 * Create the console input. Used when reading stdin doesn't work.
1709 */
1710 static void
1711create_conin(void)
1712{
1713 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1714 FILE_SHARE_READ|FILE_SHARE_WRITE,
1715 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001716 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 did_create_conin = TRUE;
1718}
1719
1720/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001721 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001723 static WCHAR
1724tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001726 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727
1728 for (;;)
1729 {
1730 INPUT_RECORD ir;
1731 DWORD cRecords = 0;
1732
1733#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001734 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 if (input_available())
1736 return 0;
1737# ifdef FEAT_MOUSE
1738 if (g_nMouseClick != -1)
1739 return 0;
1740# endif
1741#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001742 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 {
1744 if (did_create_conin)
1745 read_error_exit();
1746 create_conin();
1747 continue;
1748 }
1749
1750 if (ir.EventType == KEY_EVENT)
1751 {
1752 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1753 pmodifiers, TRUE))
1754 return ch;
1755 }
1756 else if (ir.EventType == FOCUS_EVENT)
1757 handle_focus_event(ir);
1758 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1759 shell_resized();
1760#ifdef FEAT_MOUSE
1761 else if (ir.EventType == MOUSE_EVENT)
1762 {
1763 if (decode_mouse_event(&ir.Event.MouseEvent))
1764 return 0;
1765 }
1766#endif
1767 }
1768}
1769#endif /* !FEAT_GUI_W32 */
1770
1771
1772/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001773 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 * Get one or more characters from the keyboard or the mouse.
1775 * If time == 0, do not wait for characters.
1776 * If time == n, wait a short time for characters.
1777 * If time == -1, wait forever for characters.
1778 * Returns the number of characters read into buf.
1779 */
1780 int
1781mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001782 char_u *buf UNUSED,
1783 int maxlen UNUSED,
1784 long time UNUSED,
1785 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786{
1787#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1788
1789 int len;
1790 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791#define TYPEAHEADLEN 20
1792 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1793 static int typeaheadlen = 0;
1794
1795 /* First use any typeahead that was kept because "buf" was too small. */
1796 if (typeaheadlen > 0)
1797 goto theend;
1798
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 if (time >= 0)
1800 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001801 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 }
1804 else /* time == -1, wait forever */
1805 {
1806 mch_set_winsize_now(); /* Allow winsize changes from now on */
1807
Bram Moolenaar3918c952005-03-15 22:34:55 +00001808 /*
1809 * If there is no character available within 2 seconds (default)
1810 * write the autoscript file to disk. Or cause the CursorHold event
1811 * to be triggered.
1812 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001813 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001815 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001817 buf[0] = K_SPECIAL;
1818 buf[1] = KS_EXTRA;
1819 buf[2] = (int)KE_CURSORHOLD;
1820 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001822 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 }
1824 }
1825
1826 /*
1827 * Try to read as many characters as there are, until the buffer is full.
1828 */
1829
1830 /* we will get at least one key. Get more if they are available. */
1831 g_fCBrkPressed = FALSE;
1832
1833#ifdef MCH_WRITE_DUMP
1834 if (fdDump)
1835 fputc('[', fdDump);
1836#endif
1837
1838 /* Keep looping until there is something in the typeahead buffer and more
1839 * to get and still room in the buffer (up to two bytes for a char and
1840 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001841 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 && typeaheadlen + 5 <= TYPEAHEADLEN)
1843 {
1844 if (typebuf_changed(tb_change_cnt))
1845 {
1846 /* "buf" may be invalid now if a client put something in the
1847 * typeahead buffer and "buf" is in the typeahead buffer. */
1848 typeaheadlen = 0;
1849 break;
1850 }
1851#ifdef FEAT_MOUSE
1852 if (g_nMouseClick != -1)
1853 {
1854# ifdef MCH_WRITE_DUMP
1855 if (fdDump)
1856 fprintf(fdDump, "{%02x @ %d, %d}",
1857 g_nMouseClick, g_xMouse, g_yMouse);
1858# endif
1859 typeahead[typeaheadlen++] = ESC + 128;
1860 typeahead[typeaheadlen++] = 'M';
1861 typeahead[typeaheadlen++] = g_nMouseClick;
1862 typeahead[typeaheadlen++] = g_xMouse + '!';
1863 typeahead[typeaheadlen++] = g_yMouse + '!';
1864 g_nMouseClick = -1;
1865 }
1866 else
1867#endif
1868 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001869 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 int modifiers = 0;
1871
1872 c = tgetch(&modifiers, &ch2);
1873
1874 if (typebuf_changed(tb_change_cnt))
1875 {
1876 /* "buf" may be invalid now if a client put something in the
1877 * typeahead buffer and "buf" is in the typeahead buffer. */
1878 typeaheadlen = 0;
1879 break;
1880 }
1881
1882 if (c == Ctrl_C && ctrl_c_interrupts)
1883 {
1884#if defined(FEAT_CLIENTSERVER)
1885 trash_input_buf();
1886#endif
1887 got_int = TRUE;
1888 }
1889
1890#ifdef FEAT_MOUSE
1891 if (g_nMouseClick == -1)
1892#endif
1893 {
1894 int n = 1;
1895
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001896 if (ch2 == NUL)
1897 {
1898 int i;
1899 char_u *p;
1900 WCHAR ch[2];
1901
1902 ch[0] = c;
1903 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1904 {
1905 ch[1] = tgetch(&modifiers, &ch2);
1906 n++;
1907 }
1908 p = utf16_to_enc(ch, &n);
1909 if (p != NULL)
1910 {
1911 for (i = 0; i < n; i++)
1912 typeahead[typeaheadlen + i] = p[i];
1913 vim_free(p);
1914 }
1915 }
1916 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001917 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 if (ch2 != NUL)
1919 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001920 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001921 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001922 switch (ch2)
1923 {
1924 case (WCHAR)'\324': // SHIFT+Insert
1925 case (WCHAR)'\325': // CTRL+Insert
1926 case (WCHAR)'\327': // SHIFT+Delete
1927 case (WCHAR)'\330': // CTRL+Delete
1928 typeahead[typeaheadlen + n] = (char_u)ch2;
1929 n++;
1930 break;
1931
1932 default:
1933 typeahead[typeaheadlen + n] = 3;
1934 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1935 n += 2;
1936 break;
1937 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001938 }
1939 else
1940 {
1941 typeahead[typeaheadlen + n] = 3;
1942 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1943 n += 2;
1944 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001945 }
1946
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 /* Use the ALT key to set the 8th bit of the character
1948 * when it's one byte, the 8th bit isn't set yet and not
1949 * using a double-byte encoding (would become a lead
1950 * byte). */
1951 if ((modifiers & MOD_MASK_ALT)
1952 && n == 1
1953 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 )
1956 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001957 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1958 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 modifiers &= ~MOD_MASK_ALT;
1960 }
1961
1962 if (modifiers != 0)
1963 {
1964 /* Prepend modifiers to the character. */
1965 mch_memmove(typeahead + typeaheadlen + 3,
1966 typeahead + typeaheadlen, n);
1967 typeahead[typeaheadlen++] = K_SPECIAL;
1968 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1969 typeahead[typeaheadlen++] = modifiers;
1970 }
1971
1972 typeaheadlen += n;
1973
1974#ifdef MCH_WRITE_DUMP
1975 if (fdDump)
1976 fputc(c, fdDump);
1977#endif
1978 }
1979 }
1980 }
1981
1982#ifdef MCH_WRITE_DUMP
1983 if (fdDump)
1984 {
1985 fputs("]\n", fdDump);
1986 fflush(fdDump);
1987 }
1988#endif
1989
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990theend:
1991 /* Move typeahead to "buf", as much as fits. */
1992 len = 0;
1993 while (len < maxlen && typeaheadlen > 0)
1994 {
1995 buf[len++] = typeahead[0];
1996 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1997 }
1998 return len;
1999
2000#else /* FEAT_GUI_W32 */
2001 return 0;
2002#endif /* FEAT_GUI_W32 */
2003}
2004
Bram Moolenaar82881492012-11-20 16:53:39 +01002005#ifndef PROTO
2006# ifndef __MINGW32__
2007# include <shellapi.h> /* required for FindExecutable() */
2008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009#endif
2010
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002011/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002012 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2013 * If "use_path" is FALSE: Return TRUE if "name" exists.
2014 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2015 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002016 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002017 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002019executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002021 char *dum;
2022 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002023 char *curpath, *newpath;
2024 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025
Bram Moolenaar43663192017-03-05 14:29:12 +01002026 if (!use_path)
2027 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002028 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002029 {
2030 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002031 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002032 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002033 *path = vim_strsave((char_u *)name);
2034 else
2035 *path = FullName_save((char_u *)name, FALSE);
2036 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002037 return TRUE;
2038 }
2039 return FALSE;
2040 }
2041
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002042 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002044 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002045 WCHAR fnamew[_MAX_PATH];
2046 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002047 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002048
2049 if (p != NULL)
2050 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002051 wcurpath = _wgetenv(L"PATH");
2052 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2053 * sizeof(WCHAR));
2054 if (wnewpath == NULL)
2055 return FALSE;
2056 wcscpy(wnewpath, L".;");
2057 wcscat(wnewpath, wcurpath);
2058 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2059 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002060 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002061 if (n == 0)
2062 return FALSE;
2063 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2064 return FALSE;
2065 if (path != NULL)
2066 *path = utf16_to_enc(fnamew, NULL);
2067 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 }
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002070
2071 curpath = getenv("PATH");
2072 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2073 if (newpath == NULL)
2074 return FALSE;
2075 STRCPY(newpath, ".;");
2076 STRCAT(newpath, curpath);
2077 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2078 vim_free(newpath);
2079 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002080 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002081 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002082 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002083 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002084 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002085 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086}
2087
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002088#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002089 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002090/*
2091 * Bad parameter handler.
2092 *
2093 * Certain MS CRT functions will intentionally crash when passed invalid
2094 * parameters to highlight possible security holes. Setting this function as
2095 * the bad parameter handler will prevent the crash.
2096 *
2097 * In debug builds the parameters contain CRT information that might help track
2098 * down the source of a problem, but in non-debug builds the arguments are all
2099 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2100 * worth allowing these to make debugging of issues easier.
2101 */
2102 static void
2103bad_param_handler(const wchar_t *expression,
2104 const wchar_t *function,
2105 const wchar_t *file,
2106 unsigned int line,
2107 uintptr_t pReserved)
2108{
2109}
2110
2111# define SET_INVALID_PARAM_HANDLER \
2112 ((void)_set_invalid_parameter_handler(bad_param_handler))
2113#else
2114# define SET_INVALID_PARAM_HANDLER
2115#endif
2116
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117#ifdef FEAT_GUI_W32
2118
2119/*
2120 * GUI version of mch_init().
2121 */
2122 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002123mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124{
2125#ifndef __MINGW32__
2126 extern int _fmode;
2127#endif
2128
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002129 /* Silently handle invalid parameters to CRT functions */
2130 SET_INVALID_PARAM_HANDLER;
2131
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 /* Let critical errors result in a failure, not in a dialog box. Required
2133 * for the timestamp test to work on removed floppies. */
2134 SetErrorMode(SEM_FAILCRITICALERRORS);
2135
2136 _fmode = O_BINARY; /* we do our own CR-LF translation */
2137
2138 /* Specify window size. Is there a place to get the default from? */
2139 Rows = 25;
2140 Columns = 80;
2141
2142 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143 {
2144 char_u vimrun_location[_MAX_PATH + 4];
2145
2146 /* First try in same directory as gvim.exe */
2147 STRCPY(vimrun_location, exe_name);
2148 STRCPY(gettail(vimrun_location), "vimrun.exe");
2149 if (mch_getperm(vimrun_location) >= 0)
2150 {
2151 if (*skiptowhite(vimrun_location) != NUL)
2152 {
2153 /* Enclose path with white space in double quotes. */
2154 mch_memmove(vimrun_location + 1, vimrun_location,
2155 STRLEN(vimrun_location) + 1);
2156 *vimrun_location = '"';
2157 STRCPY(gettail(vimrun_location), "vimrun\" ");
2158 }
2159 else
2160 STRCPY(gettail(vimrun_location), "vimrun ");
2161
2162 vimrun_path = (char *)vim_strsave(vimrun_location);
2163 s_dont_use_vimrun = FALSE;
2164 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002165 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 s_dont_use_vimrun = FALSE;
2167
2168 /* Don't give the warning for a missing vimrun.exe right now, but only
2169 * when vimrun was supposed to be used. Don't bother people that do
2170 * not need vimrun.exe. */
2171 if (s_dont_use_vimrun)
2172 need_vimrun_warning = TRUE;
2173 }
2174
2175 /*
2176 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2177 * Otherwise the default "findstr /n" is used.
2178 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002179 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002180 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2181
2182#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002183 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002185
2186 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187}
2188
2189
2190#else /* FEAT_GUI_W32 */
2191
2192#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2193#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2194
2195/*
2196 * ClearConsoleBuffer()
2197 * Description:
2198 * Clears the entire contents of the console screen buffer, using the
2199 * specified attribute.
2200 * Returns:
2201 * TRUE on success
2202 */
2203 static BOOL
2204ClearConsoleBuffer(WORD wAttribute)
2205{
2206 CONSOLE_SCREEN_BUFFER_INFO csbi;
2207 COORD coord;
2208 DWORD NumCells, dummy;
2209
2210 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2211 return FALSE;
2212
2213 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2214 coord.X = 0;
2215 coord.Y = 0;
2216 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2217 coord, &dummy))
2218 {
2219 return FALSE;
2220 }
2221 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2222 coord, &dummy))
2223 {
2224 return FALSE;
2225 }
2226
2227 return TRUE;
2228}
2229
2230/*
2231 * FitConsoleWindow()
2232 * Description:
2233 * Checks if the console window will fit within given buffer dimensions.
2234 * Also, if requested, will shrink the window to fit.
2235 * Returns:
2236 * TRUE on success
2237 */
2238 static BOOL
2239FitConsoleWindow(
2240 COORD dwBufferSize,
2241 BOOL WantAdjust)
2242{
2243 CONSOLE_SCREEN_BUFFER_INFO csbi;
2244 COORD dwWindowSize;
2245 BOOL NeedAdjust = FALSE;
2246
2247 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2248 {
2249 /*
2250 * A buffer resize will fail if the current console window does
2251 * not lie completely within that buffer. To avoid this, we might
2252 * have to move and possibly shrink the window.
2253 */
2254 if (csbi.srWindow.Right >= dwBufferSize.X)
2255 {
2256 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2257 if (dwWindowSize.X > dwBufferSize.X)
2258 dwWindowSize.X = dwBufferSize.X;
2259 csbi.srWindow.Right = dwBufferSize.X - 1;
2260 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2261 NeedAdjust = TRUE;
2262 }
2263 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2264 {
2265 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2266 if (dwWindowSize.Y > dwBufferSize.Y)
2267 dwWindowSize.Y = dwBufferSize.Y;
2268 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2269 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2270 NeedAdjust = TRUE;
2271 }
2272 if (NeedAdjust && WantAdjust)
2273 {
2274 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2275 return FALSE;
2276 }
2277 return TRUE;
2278 }
2279
2280 return FALSE;
2281}
2282
2283typedef struct ConsoleBufferStruct
2284{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002285 BOOL IsValid;
2286 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002287 PCHAR_INFO Buffer;
2288 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002289 PSMALL_RECT Regions;
2290 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291} ConsoleBuffer;
2292
2293/*
2294 * SaveConsoleBuffer()
2295 * Description:
2296 * Saves important information about the console buffer, including the
2297 * actual buffer contents. The saved information is suitable for later
2298 * restoration by RestoreConsoleBuffer().
2299 * Returns:
2300 * TRUE if all information was saved; FALSE otherwise
2301 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2302 */
2303 static BOOL
2304SaveConsoleBuffer(
2305 ConsoleBuffer *cb)
2306{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002307 DWORD NumCells;
2308 COORD BufferCoord;
2309 SMALL_RECT ReadRegion;
2310 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002311 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002312
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 if (cb == NULL)
2314 return FALSE;
2315
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 {
2318 cb->IsValid = FALSE;
2319 return FALSE;
2320 }
2321 cb->IsValid = TRUE;
2322
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002323 /*
2324 * Allocate a buffer large enough to hold the entire console screen
2325 * buffer. If this ConsoleBuffer structure has already been initialized
2326 * with a buffer of the correct size, then just use that one.
2327 */
2328 if (!cb->IsValid || cb->Buffer == NULL ||
2329 cb->BufferSize.X != cb->Info.dwSize.X ||
2330 cb->BufferSize.Y != cb->Info.dwSize.Y)
2331 {
2332 cb->BufferSize.X = cb->Info.dwSize.X;
2333 cb->BufferSize.Y = cb->Info.dwSize.Y;
2334 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2335 vim_free(cb->Buffer);
2336 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2337 if (cb->Buffer == NULL)
2338 return FALSE;
2339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340
2341 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002342 * We will now copy the console screen buffer into our buffer.
2343 * ReadConsoleOutput() seems to be limited as far as how much you
2344 * can read at a time. Empirically, this number seems to be about
2345 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2346 * in chunks until it is all copied. The chunks will all have the
2347 * same horizontal characteristics, so initialize them now. The
2348 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002350 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002351 ReadRegion.Left = 0;
2352 ReadRegion.Right = cb->Info.dwSize.X - 1;
2353 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002354
2355 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2356 if (cb->Regions == NULL || numregions != cb->NumRegions)
2357 {
2358 cb->NumRegions = numregions;
2359 vim_free(cb->Regions);
2360 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2361 if (cb->Regions == NULL)
2362 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002363 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002364 return FALSE;
2365 }
2366 }
2367
2368 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002370 /*
2371 * Read into position (0, Y) in our buffer.
2372 */
2373 BufferCoord.Y = Y;
2374 /*
2375 * Read the region whose top left corner is (0, Y) and whose bottom
2376 * right corner is (width - 1, Y + Y_incr - 1). This should define
2377 * a region of size width by Y_incr. Don't worry if this region is
2378 * too large for the remaining buffer; it will be cropped.
2379 */
2380 ReadRegion.Top = Y;
2381 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002382 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002383 cb->Buffer, /* our buffer */
2384 cb->BufferSize, /* dimensions of our buffer */
2385 BufferCoord, /* offset in our buffer */
2386 &ReadRegion)) /* region to save */
2387 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002388 VIM_CLEAR(cb->Buffer);
2389 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002390 return FALSE;
2391 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002392 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 }
2394
2395 return TRUE;
2396}
2397
2398/*
2399 * RestoreConsoleBuffer()
2400 * Description:
2401 * Restores important information about the console buffer, including the
2402 * actual buffer contents, if desired. The information to restore is in
2403 * the same format used by SaveConsoleBuffer().
2404 * Returns:
2405 * TRUE on success
2406 */
2407 static BOOL
2408RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002409 ConsoleBuffer *cb,
2410 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002412 COORD BufferCoord;
2413 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002414 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415
2416 if (cb == NULL || !cb->IsValid)
2417 return FALSE;
2418
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002419 /*
2420 * Before restoring the buffer contents, clear the current buffer, and
2421 * restore the cursor position and window information. Doing this now
2422 * prevents old buffer contents from "flashing" onto the screen.
2423 */
2424 if (RestoreScreen)
2425 ClearConsoleBuffer(cb->Info.wAttributes);
2426
2427 FitConsoleWindow(cb->Info.dwSize, TRUE);
2428 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2429 return FALSE;
2430 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2431 return FALSE;
2432
2433 if (!RestoreScreen)
2434 {
2435 /*
2436 * No need to restore the screen buffer contents, so we're done.
2437 */
2438 return TRUE;
2439 }
2440
2441 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2442 return FALSE;
2443 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2444 return FALSE;
2445
2446 /*
2447 * Restore the screen buffer contents.
2448 */
2449 if (cb->Buffer != NULL)
2450 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002451 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002452 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002453 BufferCoord.X = cb->Regions[i].Left;
2454 BufferCoord.Y = cb->Regions[i].Top;
2455 WriteRegion = cb->Regions[i];
2456 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2457 cb->Buffer, /* our buffer */
2458 cb->BufferSize, /* dimensions of our buffer */
2459 BufferCoord, /* offset in our buffer */
2460 &WriteRegion)) /* region to restore */
2461 {
2462 return FALSE;
2463 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002464 }
2465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466
2467 return TRUE;
2468}
2469
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002470#define FEAT_RESTORE_ORIG_SCREEN
2471#ifdef FEAT_RESTORE_ORIG_SCREEN
2472static ConsoleBuffer g_cbOrig = { 0 };
2473#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474static ConsoleBuffer g_cbNonTermcap = { 0 };
2475static ConsoleBuffer g_cbTermcap = { 0 };
2476
2477#ifdef FEAT_TITLE
2478#ifdef __BORLANDC__
2479typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2480#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002481typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482#endif
2483char g_szOrigTitle[256] = { 0 };
2484HWND g_hWnd = NULL; /* also used in os_mswin.c */
2485static HICON g_hOrigIconSmall = NULL;
2486static HICON g_hOrigIcon = NULL;
2487static HICON g_hVimIcon = NULL;
2488static BOOL g_fCanChangeIcon = FALSE;
2489
2490/* ICON* are not defined in VC++ 4.0 */
2491#ifndef ICON_SMALL
2492#define ICON_SMALL 0
2493#endif
2494#ifndef ICON_BIG
2495#define ICON_BIG 1
2496#endif
2497/*
2498 * GetConsoleIcon()
2499 * Description:
2500 * Attempts to retrieve the small icon and/or the big icon currently in
2501 * use by a given window.
2502 * Returns:
2503 * TRUE on success
2504 */
2505 static BOOL
2506GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002507 HWND hWnd,
2508 HICON *phIconSmall,
2509 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510{
2511 if (hWnd == NULL)
2512 return FALSE;
2513
2514 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002515 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2516 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2519 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 return TRUE;
2521}
2522
2523/*
2524 * SetConsoleIcon()
2525 * Description:
2526 * Attempts to change the small icon and/or the big icon currently in
2527 * use by a given window.
2528 * Returns:
2529 * TRUE on success
2530 */
2531 static BOOL
2532SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002533 HWND hWnd,
2534 HICON hIconSmall,
2535 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 if (hWnd == NULL)
2538 return FALSE;
2539
2540 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002541 SendMessage(hWnd, WM_SETICON,
2542 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002544 SendMessage(hWnd, WM_SETICON,
2545 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 return TRUE;
2547}
2548
2549/*
2550 * SaveConsoleTitleAndIcon()
2551 * Description:
2552 * Saves the current console window title in g_szOrigTitle, for later
2553 * restoration. Also, attempts to obtain a handle to the console window,
2554 * and use it to save the small and big icons currently in use by the
2555 * console window. This is not always possible on some versions of Windows;
2556 * nor is it possible when running Vim remotely using Telnet (since the
2557 * console window the user sees is owned by a remote process).
2558 */
2559 static void
2560SaveConsoleTitleAndIcon(void)
2561{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 /* Save the original title. */
2563 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2564 return;
2565
2566 /*
2567 * Obtain a handle to the console window using GetConsoleWindow() from
2568 * KERNEL32.DLL; we need to handle in order to change the window icon.
2569 * This function only exists on NT-based Windows, starting with Windows
2570 * 2000. On older operating systems, we can't change the window icon
2571 * anyway.
2572 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002573 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 if (g_hWnd == NULL)
2575 return;
2576
2577 /* Save the original console window icon. */
2578 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2579 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2580 return;
2581
2582 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002583 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002584 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 if (g_hVimIcon != NULL)
2586 g_fCanChangeIcon = TRUE;
2587}
2588#endif
2589
2590static int g_fWindInitCalled = FALSE;
2591static int g_fTermcapMode = FALSE;
2592static CONSOLE_CURSOR_INFO g_cci;
2593static DWORD g_cmodein = 0;
2594static DWORD g_cmodeout = 0;
2595
2596/*
2597 * non-GUI version of mch_init().
2598 */
2599 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002600mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002602#ifndef FEAT_RESTORE_ORIG_SCREEN
2603 CONSOLE_SCREEN_BUFFER_INFO csbi;
2604#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605#ifndef __MINGW32__
2606 extern int _fmode;
2607#endif
2608
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002609 /* Silently handle invalid parameters to CRT functions */
2610 SET_INVALID_PARAM_HANDLER;
2611
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 /* Let critical errors result in a failure, not in a dialog box. Required
2613 * for the timestamp test to work on removed floppies. */
2614 SetErrorMode(SEM_FAILCRITICALERRORS);
2615
2616 _fmode = O_BINARY; /* we do our own CR-LF translation */
2617 out_flush();
2618
2619 /* Obtain handles for the standard Console I/O devices */
2620 if (read_cmd_fd == 0)
2621 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2622 else
2623 create_conin();
2624 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2625
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002626#ifdef FEAT_RESTORE_ORIG_SCREEN
2627 /* Save the initial console buffer for later restoration */
2628 SaveConsoleBuffer(&g_cbOrig);
2629 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2630#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002632 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2633 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2634#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 if (cterm_normal_fg_color == 0)
2636 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2637 if (cterm_normal_bg_color == 0)
2638 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2639
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002640 // Fg and Bg color index nunmber at startup
2641 g_color_index_fg = g_attrDefault & 0xf;
2642 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2643
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 /* set termcap codes to current text attributes */
2645 update_tcap(g_attrCurrent);
2646
2647 GetConsoleCursorInfo(g_hConOut, &g_cci);
2648 GetConsoleMode(g_hConIn, &g_cmodein);
2649 GetConsoleMode(g_hConOut, &g_cmodeout);
2650
2651#ifdef FEAT_TITLE
2652 SaveConsoleTitleAndIcon();
2653 /*
2654 * Set both the small and big icons of the console window to Vim's icon.
2655 * Note that Vim presently only has one size of icon (32x32), but it
2656 * automatically gets scaled down to 16x16 when setting the small icon.
2657 */
2658 if (g_fCanChangeIcon)
2659 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2660#endif
2661
2662 ui_get_shellsize();
2663
2664#ifdef MCH_WRITE_DUMP
2665 fdDump = fopen("dump", "wt");
2666
2667 if (fdDump)
2668 {
2669 time_t t;
2670
2671 time(&t);
2672 fputs(ctime(&t), fdDump);
2673 fflush(fdDump);
2674 }
2675#endif
2676
2677 g_fWindInitCalled = TRUE;
2678
2679#ifdef FEAT_MOUSE
2680 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2681#endif
2682
2683#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002684 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002686
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002687 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002688 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689}
2690
2691/*
2692 * non-GUI version of mch_exit().
2693 * Shut down and exit with status `r'
2694 * Careful: mch_exit() may be called before mch_init()!
2695 */
2696 void
2697mch_exit(int r)
2698{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002699 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002701 vtp_exit();
2702
Bram Moolenaar955f1982017-02-05 15:10:51 +01002703 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 if (g_fWindInitCalled)
2705 settmode(TMODE_COOK);
2706
2707 ml_close_all(TRUE); /* remove all memfiles */
2708
2709 if (g_fWindInitCalled)
2710 {
2711#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002712 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 /*
2714 * Restore both the small and big icons of the console window to
2715 * what they were at startup. Don't do this when the window is
2716 * closed, Vim would hang here.
2717 */
2718 if (g_fCanChangeIcon && !g_fForceExit)
2719 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2720#endif
2721
2722#ifdef MCH_WRITE_DUMP
2723 if (fdDump)
2724 {
2725 time_t t;
2726
2727 time(&t);
2728 fputs(ctime(&t), fdDump);
2729 fclose(fdDump);
2730 }
2731 fdDump = NULL;
2732#endif
2733 }
2734
2735 SetConsoleCursorInfo(g_hConOut, &g_cci);
2736 SetConsoleMode(g_hConIn, g_cmodein);
2737 SetConsoleMode(g_hConOut, g_cmodeout);
2738
2739#ifdef DYNAMIC_GETTEXT
2740 dyn_libintl_end();
2741#endif
2742
2743 exit(r);
2744}
2745#endif /* !FEAT_GUI_W32 */
2746
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747/*
2748 * Do we have an interactive window?
2749 */
2750 int
2751mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002752 int argc UNUSED,
2753 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754{
2755 get_exe_name();
2756
2757#ifdef FEAT_GUI_W32
2758 return OK; /* GUI always has a tty */
2759#else
2760 if (isatty(1))
2761 return OK;
2762 return FAIL;
2763#endif
2764}
2765
2766
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002767/*
2768 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2769 * if it already exists. When "len" is > 0, also expand short to long
2770 * filenames.
2771 * Return FAIL if wide functions are not available, OK otherwise.
2772 * NOTE: much of this is identical to fname_case(), keep in sync!
2773 */
2774 static int
2775fname_casew(
2776 WCHAR *name,
2777 int len)
2778{
2779 WCHAR szTrueName[_MAX_PATH + 2];
2780 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2781 WCHAR *ptrue, *ptruePrev;
2782 WCHAR *porig, *porigPrev;
2783 int flen;
2784 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002785 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002786 int c;
2787 int slen;
2788
2789 flen = (int)wcslen(name);
2790 if (flen > _MAX_PATH)
2791 return OK;
2792
2793 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2794
2795 /* Build the new name in szTrueName[] one component at a time. */
2796 porig = name;
2797 ptrue = szTrueName;
2798
2799 if (iswalpha(porig[0]) && porig[1] == L':')
2800 {
2801 /* copy leading drive letter */
2802 *ptrue++ = *porig++;
2803 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002804 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002805 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002806
2807 while (*porig != NUL)
2808 {
2809 /* copy \ characters */
2810 while (*porig == psepc)
2811 *ptrue++ = *porig++;
2812
2813 ptruePrev = ptrue;
2814 porigPrev = porig;
2815 while (*porig != NUL && *porig != psepc)
2816 {
2817 *ptrue++ = *porig++;
2818 }
2819 *ptrue = NUL;
2820
2821 /* To avoid a slow failure append "\*" when searching a directory,
2822 * server or network share. */
2823 wcscpy(szTrueNameTemp, szTrueName);
2824 slen = (int)wcslen(szTrueNameTemp);
2825 if (*porig == psepc && slen + 2 < _MAX_PATH)
2826 wcscpy(szTrueNameTemp + slen, L"\\*");
2827
2828 /* Skip "", "." and "..". */
2829 if (ptrue > ptruePrev
2830 && (ptruePrev[0] != L'.'
2831 || (ptruePrev[1] != NUL
2832 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2833 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2834 != INVALID_HANDLE_VALUE)
2835 {
2836 c = *porig;
2837 *porig = NUL;
2838
2839 /* Only use the match when it's the same name (ignoring case) or
2840 * expansion is allowed and there is a match with the short name
2841 * and there is enough room. */
2842 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2843 || (len > 0
2844 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2845 && (int)(ptruePrev - szTrueName)
2846 + (int)wcslen(fb.cFileName) < len)))
2847 {
2848 wcscpy(ptruePrev, fb.cFileName);
2849
2850 /* Look for exact match and prefer it if found. Must be a
2851 * long name, otherwise there would be only one match. */
2852 while (FindNextFileW(hFind, &fb))
2853 {
2854 if (*fb.cAlternateFileName != NUL
2855 && (wcscoll(porigPrev, fb.cFileName) == 0
2856 || (len > 0
2857 && (_wcsicoll(porigPrev,
2858 fb.cAlternateFileName) == 0
2859 && (int)(ptruePrev - szTrueName)
2860 + (int)wcslen(fb.cFileName) < len))))
2861 {
2862 wcscpy(ptruePrev, fb.cFileName);
2863 break;
2864 }
2865 }
2866 }
2867 FindClose(hFind);
2868 *porig = c;
2869 ptrue = ptruePrev + wcslen(ptruePrev);
2870 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002871 }
2872
2873 wcscpy(name, szTrueName);
2874 return OK;
2875}
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002876
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877/*
2878 * fname_case(): Set the case of the file name, if it already exists.
2879 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002880 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 */
2882 void
2883fname_case(
2884 char_u *name,
2885 int len)
2886{
2887 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002888 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 char *ptrue, *ptruePrev;
2890 char *porig, *porigPrev;
2891 int flen;
2892 WIN32_FIND_DATA fb;
2893 HANDLE hFind;
2894 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002895 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002897 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002898 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 return;
2900
2901 slash_adjust(name);
2902
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2904 {
2905 WCHAR *p = enc_to_utf16(name, NULL);
2906
2907 if (p != NULL)
2908 {
2909 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002910 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002911
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002912 wcsncpy(buf, p, _MAX_PATH);
2913 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002914 vim_free(p);
2915
2916 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2917 {
2918 q = utf16_to_enc(buf, NULL);
2919 if (q != NULL)
2920 {
2921 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2922 vim_free(q);
2923 return;
2924 }
2925 }
2926 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002927 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002928 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002929
2930 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2931 * So we should check this after calling wide function. */
2932 if (flen > _MAX_PATH)
2933 return;
2934
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002936 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 ptrue = szTrueName;
2938
2939 if (isalpha(porig[0]) && porig[1] == ':')
2940 {
2941 /* copy leading drive letter */
2942 *ptrue++ = *porig++;
2943 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002945 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946
2947 while (*porig != NUL)
2948 {
2949 /* copy \ characters */
2950 while (*porig == psepc)
2951 *ptrue++ = *porig++;
2952
2953 ptruePrev = ptrue;
2954 porigPrev = porig;
2955 while (*porig != NUL && *porig != psepc)
2956 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 int l;
2958
2959 if (enc_dbcs)
2960 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002961 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 while (--l >= 0)
2963 *ptrue++ = *porig++;
2964 }
2965 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 *ptrue++ = *porig++;
2967 }
2968 *ptrue = NUL;
2969
Bram Moolenaar464c9252010-10-13 20:37:41 +02002970 /* To avoid a slow failure append "\*" when searching a directory,
2971 * server or network share. */
2972 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002973 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002974 if (*porig == psepc && slen + 2 < _MAX_PATH)
2975 STRCPY(szTrueNameTemp + slen, "\\*");
2976
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 /* Skip "", "." and "..". */
2978 if (ptrue > ptruePrev
2979 && (ptruePrev[0] != '.'
2980 || (ptruePrev[1] != NUL
2981 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002982 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 != INVALID_HANDLE_VALUE)
2984 {
2985 c = *porig;
2986 *porig = NUL;
2987
2988 /* Only use the match when it's the same name (ignoring case) or
2989 * expansion is allowed and there is a match with the short name
2990 * and there is enough room. */
2991 if (_stricoll(porigPrev, fb.cFileName) == 0
2992 || (len > 0
2993 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2994 && (int)(ptruePrev - szTrueName)
2995 + (int)strlen(fb.cFileName) < len)))
2996 {
2997 STRCPY(ptruePrev, fb.cFileName);
2998
2999 /* Look for exact match and prefer it if found. Must be a
3000 * long name, otherwise there would be only one match. */
3001 while (FindNextFile(hFind, &fb))
3002 {
3003 if (*fb.cAlternateFileName != NUL
3004 && (strcoll(porigPrev, fb.cFileName) == 0
3005 || (len > 0
3006 && (_stricoll(porigPrev,
3007 fb.cAlternateFileName) == 0
3008 && (int)(ptruePrev - szTrueName)
3009 + (int)strlen(fb.cFileName) < len))))
3010 {
3011 STRCPY(ptruePrev, fb.cFileName);
3012 break;
3013 }
3014 }
3015 }
3016 FindClose(hFind);
3017 *porig = c;
3018 ptrue = ptruePrev + strlen(ptruePrev);
3019 }
3020 }
3021
3022 STRCPY(name, szTrueName);
3023}
3024
3025
3026/*
3027 * Insert user name in s[len].
3028 */
3029 int
3030mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003031 char_u *s,
3032 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003034 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 DWORD cch = sizeof szUserName;
3036
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003037 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3038 {
3039 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3040 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3041
3042 if (GetUserNameW(wszUserName, &wcch))
3043 {
3044 char_u *p = utf16_to_enc(wszUserName, NULL);
3045
3046 if (p != NULL)
3047 {
3048 vim_strncpy(s, p, len - 1);
3049 vim_free(p);
3050 return OK;
3051 }
3052 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003053 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 if (GetUserName(szUserName, &cch))
3055 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003056 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 return OK;
3058 }
3059 s[0] = NUL;
3060 return FAIL;
3061}
3062
3063
3064/*
3065 * Insert host name in s[len].
3066 */
3067 void
3068mch_get_host_name(
3069 char_u *s,
3070 int len)
3071{
3072 DWORD cch = len;
3073
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003074 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3075 {
3076 WCHAR wszHostName[256 + 1];
3077 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3078
3079 if (GetComputerNameW(wszHostName, &wcch))
3080 {
3081 char_u *p = utf16_to_enc(wszHostName, NULL);
3082
3083 if (p != NULL)
3084 {
3085 vim_strncpy(s, p, len - 1);
3086 vim_free(p);
3087 return;
3088 }
3089 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003090 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003091 if (!GetComputerName((LPSTR)s, &cch))
3092 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093}
3094
3095
3096/*
3097 * return process ID
3098 */
3099 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003100mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101{
3102 return (long)GetCurrentProcessId();
3103}
3104
3105
3106/*
3107 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3108 * Return OK for success, FAIL for failure.
3109 */
3110 int
3111mch_dirname(
3112 char_u *buf,
3113 int len)
3114{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003115 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003116 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003117
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 /*
3119 * Originally this was:
3120 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3121 * But the Win32s known bug list says that getcwd() doesn't work
3122 * so use the Win32 system call instead. <Negri>
3123 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3125 {
3126 WCHAR wbuf[_MAX_PATH + 1];
3127
3128 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3129 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003130 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003132
3133 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003134 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003135 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003136 if (STRLEN(p) >= (size_t)len)
3137 {
3138 // long path name is too long, fall back to short one
3139 vim_free(p);
3140 p = NULL;
3141 }
3142 }
3143 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145
3146 if (p != NULL)
3147 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003148 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 vim_free(p);
3150 return OK;
3151 }
3152 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003153 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 }
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003155 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3156 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003157 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3158 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3159 // Failed to get long path name or it's too long: fall back to the
3160 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003161 return OK;
3162
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003163 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003164 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165}
3166
3167/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003168 * Get file permissions for "name".
3169 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 */
3171 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003172mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003174 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003175 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003177 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003178 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179}
3180
3181
3182/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003183 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003184 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003185 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 */
3187 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003188mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003190 long n = -1;
3191
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3193 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003194 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
3196 if (p != NULL)
3197 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003200 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 }
3203 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003204 if (n == -1)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003205 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206 if (n == -1)
3207 return FAIL;
3208
3209 win32_set_archive(name);
3210
3211 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212}
3213
3214/*
3215 * Set hidden flag for "name".
3216 */
3217 void
3218mch_hide(char_u *name)
3219{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003220 int attrs = win32_getattrs(name);
3221 if (attrs == -1)
3222 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 attrs |= FILE_ATTRIBUTE_HIDDEN;
3225 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226}
3227
3228/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003229 * Return TRUE if file "name" exists and is hidden.
3230 */
3231 int
3232mch_ishidden(char_u *name)
3233{
3234 int f = win32_getattrs(name);
3235
3236 if (f == -1)
3237 return FALSE; /* file does not exist at all */
3238
3239 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3240}
3241
3242/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 * return TRUE if "name" is a directory
3244 * return FALSE if "name" is not a directory or upon error
3245 */
3246 int
3247mch_isdir(char_u *name)
3248{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003249 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250
3251 if (f == -1)
3252 return FALSE; /* file does not exist at all */
3253
3254 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3255}
3256
3257/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003258 * return TRUE if "name" is a directory, NOT a symlink to a directory
3259 * return FALSE if "name" is not a directory
3260 * return FALSE for error
3261 */
3262 int
3263mch_isrealdir(char_u *name)
3264{
3265 return mch_isdir(name) && !mch_is_symbolic_link(name);
3266}
3267
3268/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003269 * Create directory "name".
3270 * Return 0 on success, -1 on error.
3271 */
3272 int
3273mch_mkdir(char_u *name)
3274{
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003275 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3276 {
3277 WCHAR *p;
3278 int retval;
3279
3280 p = enc_to_utf16(name, NULL);
3281 if (p == NULL)
3282 return -1;
3283 retval = _wmkdir(p);
3284 vim_free(p);
3285 return retval;
3286 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003287 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003288}
3289
3290/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003291 * Delete directory "name".
3292 * Return 0 on success, -1 on error.
3293 */
3294 int
3295mch_rmdir(char_u *name)
3296{
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003297 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3298 {
3299 WCHAR *p;
3300 int retval;
3301
3302 p = enc_to_utf16(name, NULL);
3303 if (p == NULL)
3304 return -1;
3305 retval = _wrmdir(p);
3306 vim_free(p);
3307 return retval;
3308 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003309 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003310}
3311
3312/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003313 * Return TRUE if file "fname" has more than one link.
3314 */
3315 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003316mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003318 BY_HANDLE_FILE_INFORMATION info;
3319
3320 return win32_fileinfo(fname, &info) == FILEINFO_OK
3321 && info.nNumberOfLinks > 1;
3322}
3323
3324/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003325 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003326 */
3327 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003328mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003329{
3330 HANDLE hFind;
3331 int res = FALSE;
3332 WIN32_FIND_DATAA findDataA;
3333 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003334 WCHAR *wn = NULL;
3335 WIN32_FIND_DATAW findDataW;
3336
3337 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003338 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003339 if (wn != NULL)
3340 {
3341 hFind = FindFirstFileW(wn, &findDataW);
3342 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003343 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344 {
3345 fileFlags = findDataW.dwFileAttributes;
3346 reparseTag = findDataW.dwReserved0;
3347 }
3348 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003349 else
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003350 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003351 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003352 if (hFind != INVALID_HANDLE_VALUE)
3353 {
3354 fileFlags = findDataA.dwFileAttributes;
3355 reparseTag = findDataA.dwReserved0;
3356 }
3357 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358
3359 if (hFind != INVALID_HANDLE_VALUE)
3360 FindClose(hFind);
3361
3362 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003363 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3364 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 res = TRUE;
3366
3367 return res;
3368}
3369
3370/*
3371 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3372 * link.
3373 */
3374 int
3375mch_is_linked(char_u *fname)
3376{
3377 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3378 return TRUE;
3379 return FALSE;
3380}
3381
3382/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003383 * Get the by-handle-file-information for "fname".
3384 * Returns FILEINFO_OK when OK.
3385 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3386 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3387 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3388 */
3389 int
3390win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3391{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003392 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003393 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003394 WCHAR *wn = NULL;
3395
3396 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003397 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003398 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003399 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003400 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003401 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003402 if (wn != NULL)
3403 {
3404 hFile = CreateFileW(wn, /* file name */
3405 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003407 NULL, /* security descriptor */
3408 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003409 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003410 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003411 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003413 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003414 hFile = CreateFile((LPCSTR)fname, /* file name */
3415 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 NULL, /* security descriptor */
3418 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003419 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003420 NULL); /* handle to template file */
3421
3422 if (hFile != INVALID_HANDLE_VALUE)
3423 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003424 if (GetFileInformationByHandle(hFile, info) != 0)
3425 res = FILEINFO_OK;
3426 else
3427 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428 CloseHandle(hFile);
3429 }
3430
Bram Moolenaar03f48552006-02-28 23:52:23 +00003431 return res;
3432}
3433
3434/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003435 * get file attributes for `name'
3436 * -1 : error
3437 * else FILE_ATTRIBUTE_* defined in winnt.h
3438 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003439 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003440win32_getattrs(char_u *name)
3441{
3442 int attr;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 WCHAR *p = NULL;
3444
3445 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3446 p = enc_to_utf16(name, NULL);
3447
3448 if (p != NULL)
3449 {
3450 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003451 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003452 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003453 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003454 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003455
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003456 return attr;
3457}
3458
3459/*
3460 * set file attributes for `name' to `attrs'
3461 *
3462 * return -1 for failure, 0 otherwise
3463 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003464 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465win32_setattrs(char_u *name, int attrs)
3466{
3467 int res;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 WCHAR *p = NULL;
3469
3470 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3471 p = enc_to_utf16(name, NULL);
3472
3473 if (p != NULL)
3474 {
3475 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003476 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003478 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003480
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003481 return res ? 0 : -1;
3482}
3483
3484/*
3485 * Set archive flag for "name".
3486 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003487 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488win32_set_archive(char_u *name)
3489{
3490 int attrs = win32_getattrs(name);
3491 if (attrs == -1)
3492 return -1;
3493
3494 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3495 return win32_setattrs(name, attrs);
3496}
3497
3498/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499 * Return TRUE if file or directory "name" is writable (not readonly).
3500 * Strange semantics of Win32: a readonly directory is writable, but you can't
3501 * delete a file. Let's say this means it is writable.
3502 */
3503 int
3504mch_writable(char_u *name)
3505{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003506 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003508 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3509 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510}
3511
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003513 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003514 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003515 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3516 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 */
3518 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003519mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003521 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003522 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003523 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003524
3525 if (len >= _MAX_PATH) /* safety check */
3526 return FALSE;
3527
Bram Moolenaar82956662018-10-06 15:18:45 +02003528 /* Ty using the name directly when a Unix-shell like 'shell'. */
3529 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003530 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003531 return TRUE;
3532
3533 /*
3534 * Loop over all extensions in $PATHEXT.
3535 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003536 p = mch_getenv("PATHEXT");
3537 if (p == NULL)
3538 p = (char_u *)".com;.exe;.bat;.cmd";
3539 saved = vim_strsave(p);
3540 if (saved == NULL)
3541 return FALSE;
3542 p = saved;
3543 while (*p)
3544 {
3545 char_u *tmp = vim_strchr(p, ';');
3546
3547 if (tmp != NULL)
3548 *tmp = NUL;
3549 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3550 && executable_exists((char *)name, path, use_path))
3551 {
3552 vim_free(saved);
3553 return TRUE;
3554 }
3555 if (tmp == NULL)
3556 break;
3557 p = tmp + 1;
3558 }
3559 vim_free(saved);
3560
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003561 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003562 p = mch_getenv("PATHEXT");
3563 if (p == NULL)
3564 p = (char_u *)".com;.exe;.bat;.cmd";
3565 while (*p)
3566 {
3567 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3568 {
3569 /* A single "." means no extension is added. */
3570 buf[len] = NUL;
3571 ++p;
3572 if (*p)
3573 ++p;
3574 }
3575 else
3576 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003577 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003578 return TRUE;
3579 }
3580 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582
3583/*
3584 * Check what "name" is:
3585 * NODE_NORMAL: file or directory (or doesn't exist)
3586 * NODE_WRITABLE: writable device, socket, fifo, etc.
3587 * NODE_OTHER: non-writable things
3588 */
3589 int
3590mch_nodetype(char_u *name)
3591{
3592 HANDLE hFile;
3593 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003594 WCHAR *wn = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595
Bram Moolenaar043545e2006-10-10 16:44:07 +00003596 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3597 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3598 * here. */
3599 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3600 return NODE_WRITABLE;
3601
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003602 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003603 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003604
3605 if (wn != NULL)
3606 {
3607 hFile = CreateFileW(wn, /* file name */
3608 GENERIC_WRITE, /* access mode */
3609 0, /* share mode */
3610 NULL, /* security descriptor */
3611 OPEN_EXISTING, /* creation disposition */
3612 0, /* file attributes */
3613 NULL); /* handle to template file */
3614 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003615 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003616 else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003617 hFile = CreateFile((LPCSTR)name, /* file name */
3618 GENERIC_WRITE, /* access mode */
3619 0, /* share mode */
3620 NULL, /* security descriptor */
3621 OPEN_EXISTING, /* creation disposition */
3622 0, /* file attributes */
3623 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624
3625 if (hFile == INVALID_HANDLE_VALUE)
3626 return NODE_NORMAL;
3627
3628 type = GetFileType(hFile);
3629 CloseHandle(hFile);
3630 if (type == FILE_TYPE_CHAR)
3631 return NODE_WRITABLE;
3632 if (type == FILE_TYPE_DISK)
3633 return NODE_NORMAL;
3634 return NODE_OTHER;
3635}
3636
3637#ifdef HAVE_ACL
3638struct my_acl
3639{
3640 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3641 PSID pSidOwner;
3642 PSID pSidGroup;
3643 PACL pDacl;
3644 PACL pSacl;
3645};
3646#endif
3647
3648/*
3649 * Return a pointer to the ACL of file "fname" in allocated memory.
3650 * Return NULL if the ACL is not available for whatever reason.
3651 */
3652 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003653mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654{
3655#ifndef HAVE_ACL
3656 return (vim_acl_T)NULL;
3657#else
3658 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003659 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003661 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3662 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003664 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003665
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003666 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3667 wn = enc_to_utf16(fname, NULL);
3668 if (wn != NULL)
3669 {
3670 /* Try to retrieve the entire security descriptor. */
3671 err = GetNamedSecurityInfoW(
3672 wn, // Abstract filename
3673 SE_FILE_OBJECT, // File Object
3674 OWNER_SECURITY_INFORMATION |
3675 GROUP_SECURITY_INFORMATION |
3676 DACL_SECURITY_INFORMATION |
3677 SACL_SECURITY_INFORMATION,
3678 &p->pSidOwner, // Ownership information.
3679 &p->pSidGroup, // Group membership.
3680 &p->pDacl, // Discretionary information.
3681 &p->pSacl, // For auditing purposes.
3682 &p->pSecurityDescriptor);
3683 if (err == ERROR_ACCESS_DENIED ||
3684 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003685 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003686 /* Retrieve only DACL. */
3687 (void)GetNamedSecurityInfoW(
3688 wn,
3689 SE_FILE_OBJECT,
3690 DACL_SECURITY_INFORMATION,
3691 NULL,
3692 NULL,
3693 &p->pDacl,
3694 NULL,
3695 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003696 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003697 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003698 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003699 mch_free_acl((vim_acl_T)p);
3700 p = NULL;
3701 }
3702 vim_free(wn);
3703 }
3704 else
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003705 {
3706 /* Try to retrieve the entire security descriptor. */
3707 err = GetNamedSecurityInfo(
3708 (LPSTR)fname, // Abstract filename
3709 SE_FILE_OBJECT, // File Object
3710 OWNER_SECURITY_INFORMATION |
3711 GROUP_SECURITY_INFORMATION |
3712 DACL_SECURITY_INFORMATION |
3713 SACL_SECURITY_INFORMATION,
3714 &p->pSidOwner, // Ownership information.
3715 &p->pSidGroup, // Group membership.
3716 &p->pDacl, // Discretionary information.
3717 &p->pSacl, // For auditing purposes.
3718 &p->pSecurityDescriptor);
3719 if (err == ERROR_ACCESS_DENIED ||
3720 err == ERROR_PRIVILEGE_NOT_HELD)
3721 {
3722 /* Retrieve only DACL. */
3723 (void)GetNamedSecurityInfo(
3724 (LPSTR)fname,
3725 SE_FILE_OBJECT,
3726 DACL_SECURITY_INFORMATION,
3727 NULL,
3728 NULL,
3729 &p->pDacl,
3730 NULL,
3731 &p->pSecurityDescriptor);
3732 }
3733 if (p->pSecurityDescriptor == NULL)
3734 {
3735 mch_free_acl((vim_acl_T)p);
3736 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 }
3738 }
3739 }
3740
3741 return (vim_acl_T)p;
3742#endif
3743}
3744
Bram Moolenaar27515922013-06-29 15:36:26 +02003745#ifdef HAVE_ACL
3746/*
3747 * Check if "acl" contains inherited ACE.
3748 */
3749 static BOOL
3750is_acl_inherited(PACL acl)
3751{
3752 DWORD i;
3753 ACL_SIZE_INFORMATION acl_info;
3754 PACCESS_ALLOWED_ACE ace;
3755
3756 acl_info.AceCount = 0;
3757 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3758 for (i = 0; i < acl_info.AceCount; i++)
3759 {
3760 GetAce(acl, i, (LPVOID *)&ace);
3761 if (ace->Header.AceFlags & INHERITED_ACE)
3762 return TRUE;
3763 }
3764 return FALSE;
3765}
3766#endif
3767
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768/*
3769 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3770 * Errors are ignored.
3771 * This must only be called with "acl" equal to what mch_get_acl() returned.
3772 */
3773 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003774mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775{
3776#ifdef HAVE_ACL
3777 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003778 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003780 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003781 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003782 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003783
3784 /* Set security flags */
3785 if (p->pSidOwner)
3786 sec_info |= OWNER_SECURITY_INFORMATION;
3787 if (p->pSidGroup)
3788 sec_info |= GROUP_SECURITY_INFORMATION;
3789 if (p->pDacl)
3790 {
3791 sec_info |= DACL_SECURITY_INFORMATION;
3792 /* Do not inherit its parent's DACL.
3793 * If the DACL is inherited, Cygwin permissions would be changed.
3794 */
3795 if (!is_acl_inherited(p->pDacl))
3796 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3797 }
3798 if (p->pSacl)
3799 sec_info |= SACL_SECURITY_INFORMATION;
3800
Bram Moolenaar27515922013-06-29 15:36:26 +02003801 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3802 wn = enc_to_utf16(fname, NULL);
3803 if (wn != NULL)
3804 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003805 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003806 wn, // Abstract filename
3807 SE_FILE_OBJECT, // File Object
3808 sec_info,
3809 p->pSidOwner, // Ownership information.
3810 p->pSidGroup, // Group membership.
3811 p->pDacl, // Discretionary information.
3812 p->pSacl // For auditing purposes.
3813 );
3814 vim_free(wn);
3815 }
3816 else
Bram Moolenaar27515922013-06-29 15:36:26 +02003817 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003818 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003819 (LPSTR)fname, // Abstract filename
3820 SE_FILE_OBJECT, // File Object
3821 sec_info,
3822 p->pSidOwner, // Ownership information.
3823 p->pSidGroup, // Group membership.
3824 p->pDacl, // Discretionary information.
3825 p->pSacl // For auditing purposes.
3826 );
3827 }
3828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829#endif
3830}
3831
3832 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003833mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834{
3835#ifdef HAVE_ACL
3836 struct my_acl *p = (struct my_acl *)acl;
3837
3838 if (p != NULL)
3839 {
3840 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3841 vim_free(p);
3842 }
3843#endif
3844}
3845
3846#ifndef FEAT_GUI_W32
3847
3848/*
3849 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3850 */
3851 static BOOL WINAPI
3852handler_routine(
3853 DWORD dwCtrlType)
3854{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003855 INPUT_RECORD ir;
3856 DWORD out;
3857
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858 switch (dwCtrlType)
3859 {
3860 case CTRL_C_EVENT:
3861 if (ctrl_c_interrupts)
3862 g_fCtrlCPressed = TRUE;
3863 return TRUE;
3864
3865 case CTRL_BREAK_EVENT:
3866 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003867 ctrl_break_was_pressed = TRUE;
3868 /* ReadConsoleInput is blocking, send a key event to continue. */
3869 ir.EventType = KEY_EVENT;
3870 ir.Event.KeyEvent.bKeyDown = TRUE;
3871 ir.Event.KeyEvent.wRepeatCount = 1;
3872 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3873 ir.Event.KeyEvent.wVirtualScanCode = 0;
3874 ir.Event.KeyEvent.dwControlKeyState = 0;
3875 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3876 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 return TRUE;
3878
3879 /* fatal events: shut down gracefully */
3880 case CTRL_CLOSE_EVENT:
3881 case CTRL_LOGOFF_EVENT:
3882 case CTRL_SHUTDOWN_EVENT:
3883 windgoto((int)Rows - 1, 0);
3884 g_fForceExit = TRUE;
3885
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003886 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 (dwCtrlType == CTRL_CLOSE_EVENT
3888 ? _("close")
3889 : dwCtrlType == CTRL_LOGOFF_EVENT
3890 ? _("logoff")
3891 : _("shutdown")));
3892#ifdef DEBUG
3893 OutputDebugString(IObuff);
3894#endif
3895
3896 preserve_exit(); /* output IObuff, preserve files and exit */
3897
3898 return TRUE; /* not reached */
3899
3900 default:
3901 return FALSE;
3902 }
3903}
3904
3905
3906/*
3907 * set the tty in (raw) ? "raw" : "cooked" mode
3908 */
3909 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003910mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911{
3912 DWORD cmodein;
3913 DWORD cmodeout;
3914 BOOL bEnableHandler;
3915
3916 GetConsoleMode(g_hConIn, &cmodein);
3917 GetConsoleMode(g_hConOut, &cmodeout);
3918 if (tmode == TMODE_RAW)
3919 {
3920 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3921 ENABLE_ECHO_INPUT);
3922#ifdef FEAT_MOUSE
3923 if (g_fMouseActive)
3924 cmodein |= ENABLE_MOUSE_INPUT;
3925#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003926 cmodeout &= ~(
3927#ifdef FEAT_TERMGUICOLORS
3928 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3929 * VTP. */
3930 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3931#else
3932 ENABLE_PROCESSED_OUTPUT |
3933#endif
3934 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 bEnableHandler = TRUE;
3936 }
3937 else /* cooked */
3938 {
3939 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3940 ENABLE_ECHO_INPUT);
3941 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3942 bEnableHandler = FALSE;
3943 }
3944 SetConsoleMode(g_hConIn, cmodein);
3945 SetConsoleMode(g_hConOut, cmodeout);
3946 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3947
3948#ifdef MCH_WRITE_DUMP
3949 if (fdDump)
3950 {
3951 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3952 tmode == TMODE_RAW ? "raw" :
3953 tmode == TMODE_COOK ? "cooked" : "normal",
3954 cmodein, cmodeout);
3955 fflush(fdDump);
3956 }
3957#endif
3958}
3959
3960
3961/*
3962 * Get the size of the current window in `Rows' and `Columns'
3963 * Return OK when size could be determined, FAIL otherwise.
3964 */
3965 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003966mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967{
3968 CONSOLE_SCREEN_BUFFER_INFO csbi;
3969
3970 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3971 {
3972 /*
3973 * For some reason, we are trying to get the screen dimensions
3974 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3975 * variables are really intended to mean the size of Vim screen
3976 * while in termcap mode.
3977 */
3978 Rows = g_cbTermcap.Info.dwSize.Y;
3979 Columns = g_cbTermcap.Info.dwSize.X;
3980 }
3981 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3982 {
3983 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3984 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3985 }
3986 else
3987 {
3988 Rows = 25;
3989 Columns = 80;
3990 }
3991 return OK;
3992}
3993
3994/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003995 * Resize console buffer to 'COORD'
3996 */
3997 static void
3998ResizeConBuf(
3999 HANDLE hConsole,
4000 COORD coordScreen)
4001{
4002 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4003 {
4004#ifdef MCH_WRITE_DUMP
4005 if (fdDump)
4006 {
4007 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4008 GetLastError());
4009 fflush(fdDump);
4010 }
4011#endif
4012 }
4013}
4014
4015/*
4016 * Resize console window size to 'srWindowRect'
4017 */
4018 static void
4019ResizeWindow(
4020 HANDLE hConsole,
4021 SMALL_RECT srWindowRect)
4022{
4023 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4024 {
4025#ifdef MCH_WRITE_DUMP
4026 if (fdDump)
4027 {
4028 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4029 GetLastError());
4030 fflush(fdDump);
4031 }
4032#endif
4033 }
4034}
4035
4036/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004037 * Set a console window to `xSize' * `ySize'
4038 */
4039 static void
4040ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004041 HANDLE hConsole,
4042 int xSize,
4043 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004044{
4045 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4046 SMALL_RECT srWindowRect; /* hold the new console size */
4047 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004048 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049
4050#ifdef MCH_WRITE_DUMP
4051 if (fdDump)
4052 {
4053 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4054 fflush(fdDump);
4055 }
4056#endif
4057
4058 /* get the largest size we can size the console window to */
4059 coordScreen = GetLargestConsoleWindowSize(hConsole);
4060
4061 /* define the new console window size and scroll position */
4062 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4063 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4064 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4065
4066 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4067 {
4068 int sx, sy;
4069
4070 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4071 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4072 if (sy < ySize || sx < xSize)
4073 {
4074 /*
4075 * Increasing number of lines/columns, do buffer first.
4076 * Use the maximal size in x and y direction.
4077 */
4078 if (sy < ySize)
4079 coordScreen.Y = ySize;
4080 else
4081 coordScreen.Y = sy;
4082 if (sx < xSize)
4083 coordScreen.X = xSize;
4084 else
4085 coordScreen.X = sx;
4086 SetConsoleScreenBufferSize(hConsole, coordScreen);
4087 }
4088 }
4089
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004090 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 coordScreen.X = xSize;
4092 coordScreen.Y = ySize;
4093
Bram Moolenaar2551c032018-08-23 22:38:31 +02004094 // In the new console call API, only the first time in reverse order
4095 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004097 ResizeWindow(hConsole, srWindowRect);
4098 ResizeConBuf(hConsole, coordScreen);
4099 }
4100 else
4101 {
4102 ResizeConBuf(hConsole, coordScreen);
4103 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004104 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105 }
4106}
4107
4108
4109/*
4110 * Set the console window to `Rows' * `Columns'
4111 */
4112 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004113mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114{
4115 COORD coordScreen;
4116
4117 /* Don't change window size while still starting up */
4118 if (suppress_winsize != 0)
4119 {
4120 suppress_winsize = 2;
4121 return;
4122 }
4123
4124 if (term_console)
4125 {
4126 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4127
4128 /* Clamp Rows and Columns to reasonable values */
4129 if (Rows > coordScreen.Y)
4130 Rows = coordScreen.Y;
4131 if (Columns > coordScreen.X)
4132 Columns = coordScreen.X;
4133
4134 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4135 }
4136}
4137
4138/*
4139 * Rows and/or Columns has changed.
4140 */
4141 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004142mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143{
4144 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4145}
4146
4147
4148/*
4149 * Called when started up, to set the winsize that was delayed.
4150 */
4151 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004152mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153{
4154 if (suppress_winsize == 2)
4155 {
4156 suppress_winsize = 0;
4157 mch_set_shellsize();
4158 shell_resized();
4159 }
4160 suppress_winsize = 0;
4161}
4162#endif /* FEAT_GUI_W32 */
4163
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004164 static BOOL
4165vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004166 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004167 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004168 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004169 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004170 PROCESS_INFORMATION *pi,
4171 LPVOID *env,
4172 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004173{
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004174 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4175 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004176 BOOL ret;
4177 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004178
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004179 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4180 if (wcmd == NULL)
4181 goto fallback;
4182 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004183 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004184 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4185 if (wcwd == NULL)
4186 {
4187 vim_free(wcmd);
4188 goto fallback;
4189 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004190 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004191
4192 ret = CreateProcessW(
4193 NULL, /* Executable name */
4194 wcmd, /* Command to execute */
4195 NULL, /* Process security attributes */
4196 NULL, /* Thread security attributes */
4197 inherit_handles, /* Inherit handles */
4198 flags, /* Creation flags */
4199 env, /* Environment */
4200 wcwd, /* Current directory */
4201 (LPSTARTUPINFOW)si, /* Startup information */
4202 pi); /* Process information */
4203 vim_free(wcmd);
4204 if (wcwd != NULL)
4205 vim_free(wcwd);
4206 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004208fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209 return CreateProcess(
4210 NULL, /* Executable name */
4211 cmd, /* Command to execute */
4212 NULL, /* Process security attributes */
4213 NULL, /* Thread security attributes */
4214 inherit_handles, /* Inherit handles */
4215 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004216 env, /* Environment */
4217 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004218 si, /* Startup information */
4219 pi); /* Process information */
4220}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221
4222
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004223 static HINSTANCE
4224vim_shell_execute(
4225 char *cmd,
4226 INT n_show_cmd)
4227{
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004228 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4229 {
4230 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4231 if (wcmd != NULL)
4232 {
4233 HINSTANCE ret;
4234 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4235 vim_free(wcmd);
4236 return ret;
4237 }
4238 }
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004239 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4240}
4241
4242
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243#if defined(FEAT_GUI_W32) || defined(PROTO)
4244
4245/*
4246 * Specialised version of system() for Win32 GUI mode.
4247 * This version proceeds as follows:
4248 * 1. Create a console window for use by the subprocess
4249 * 2. Run the subprocess (it gets the allocated console by default)
4250 * 3. Wait for the subprocess to terminate and get its exit code
4251 * 4. Prompt the user to press a key to close the console window
4252 */
4253 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255{
4256 STARTUPINFO si;
4257 PROCESS_INFORMATION pi;
4258 DWORD ret = 0;
4259 HWND hwnd = GetFocus();
4260
4261 si.cb = sizeof(si);
4262 si.lpReserved = NULL;
4263 si.lpDesktop = NULL;
4264 si.lpTitle = NULL;
4265 si.dwFlags = STARTF_USESHOWWINDOW;
4266 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004267 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004268 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004270 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004271 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 else
4273 si.wShowWindow = SW_SHOWNORMAL;
4274 si.cbReserved2 = 0;
4275 si.lpReserved2 = NULL;
4276
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004278 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004279 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4280 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281
4282 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 {
4284#ifdef FEAT_GUI
4285 int delay = 1;
4286
4287 /* Keep updating the window while waiting for the shell to finish. */
4288 for (;;)
4289 {
4290 MSG msg;
4291
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004292 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 {
4294 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004295 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004296 delay = 1;
4297 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 }
4299 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4300 break;
4301
4302 /* We start waiting for a very short time and then increase it, so
4303 * that we respond quickly when the process is quick, and don't
4304 * consume too much overhead when it's slow. */
4305 if (delay < 50)
4306 delay += 10;
4307 }
4308#else
4309 WaitForSingleObject(pi.hProcess, INFINITE);
4310#endif
4311
4312 /* Get the command exit code */
4313 GetExitCodeProcess(pi.hProcess, &ret);
4314 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315
4316 /* Close the handles to the subprocess, so that it goes away */
4317 CloseHandle(pi.hThread);
4318 CloseHandle(pi.hProcess);
4319
4320 /* Try to get input focus back. Doesn't always work though. */
4321 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4322
4323 return ret;
4324}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004325
4326/*
4327 * Thread launched by the gui to send the current buffer data to the
4328 * process. This way avoid to hang up vim totally if the children
4329 * process take a long time to process the lines.
4330 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004331 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004332sub_process_writer(LPVOID param)
4333{
4334 HANDLE g_hChildStd_IN_Wr = param;
4335 linenr_T lnum = curbuf->b_op_start.lnum;
4336 DWORD len = 0;
4337 DWORD l;
4338 char_u *lp = ml_get(lnum);
4339 char_u *s;
4340 int written = 0;
4341
4342 for (;;)
4343 {
4344 l = (DWORD)STRLEN(lp + written);
4345 if (l == 0)
4346 len = 0;
4347 else if (lp[written] == NL)
4348 {
4349 /* NL -> NUL translation */
4350 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4351 }
4352 else
4353 {
4354 s = vim_strchr(lp + written, NL);
4355 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4356 s == NULL ? l : (DWORD)(s - (lp + written)),
4357 &len, NULL);
4358 }
4359 if (len == (int)l)
4360 {
4361 /* Finished a line, add a NL, unless this line should not have
4362 * one. */
4363 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004364 || (!curbuf->b_p_bin
4365 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004366 || (lnum != curbuf->b_no_eol_lnum
4367 && (lnum != curbuf->b_ml.ml_line_count
4368 || curbuf->b_p_eol)))
4369 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004370 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4371 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372 }
4373
4374 ++lnum;
4375 if (lnum > curbuf->b_op_end.lnum)
4376 break;
4377
4378 lp = ml_get(lnum);
4379 written = 0;
4380 }
4381 else if (len > 0)
4382 written += len;
4383 }
4384
4385 /* finished all the lines, close pipe */
4386 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004387 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388}
4389
4390
4391# define BUFLEN 100 /* length for buffer, stolen from unix version */
4392
4393/*
4394 * This function read from the children's stdout and write the
4395 * data on screen or in the buffer accordingly.
4396 */
4397 static void
4398dump_pipe(int options,
4399 HANDLE g_hChildStd_OUT_Rd,
4400 garray_T *ga,
4401 char_u buffer[],
4402 DWORD *buffer_off)
4403{
4404 DWORD availableBytes = 0;
4405 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406 int ret;
4407 DWORD len;
4408 DWORD toRead;
4409 int repeatCount;
4410
4411 /* we query the pipe to see if there is any data to read
4412 * to avoid to perform a blocking read */
4413 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4414 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004415 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 NULL, /* number of read bytes */
4417 &availableBytes, /* available bytes total */
4418 NULL); /* byteLeft */
4419
4420 repeatCount = 0;
4421 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004422 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004423 {
4424 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004425 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004427 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428
4429 /* If we haven't read anything, there is a problem */
4430 if (len == 0)
4431 break;
4432
4433 availableBytes -= len;
4434
4435 if (options & SHELL_READ)
4436 {
4437 /* Do NUL -> NL translation, append NL separated
4438 * lines to the current buffer. */
4439 for (i = 0; i < len; ++i)
4440 {
4441 if (buffer[i] == NL)
4442 append_ga_line(ga);
4443 else if (buffer[i] == NUL)
4444 ga_append(ga, NL);
4445 else
4446 ga_append(ga, buffer[i]);
4447 }
4448 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 else if (has_mbyte)
4450 {
4451 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004452 int c;
4453 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004454
4455 len += *buffer_off;
4456 buffer[len] = NUL;
4457
4458 /* Check if the last character in buffer[] is
4459 * incomplete, keep these bytes for the next
4460 * round. */
4461 for (p = buffer; p < buffer + len; p += l)
4462 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004463 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 if (l == 0)
4465 l = 1; /* NUL byte? */
4466 else if (MB_BYTE2LEN(*p) != l)
4467 break;
4468 }
4469 if (p == buffer) /* no complete character */
4470 {
4471 /* avoid getting stuck at an illegal byte */
4472 if (len >= 12)
4473 ++p;
4474 else
4475 {
4476 *buffer_off = len;
4477 return;
4478 }
4479 }
4480 c = *p;
4481 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004482 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004483 if (p < buffer + len)
4484 {
4485 *p = c;
4486 *buffer_off = (DWORD)((buffer + len) - p);
4487 mch_memmove(buffer, p, *buffer_off);
4488 return;
4489 }
4490 *buffer_off = 0;
4491 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 else
4493 {
4494 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004495 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004496 }
4497
4498 windgoto(msg_row, msg_col);
4499 cursor_on();
4500 out_flush();
4501 }
4502}
4503
4504/*
4505 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4506 * for communication and doesn't open any new window.
4507 */
4508 static int
4509mch_system_piped(char *cmd, int options)
4510{
4511 STARTUPINFO si;
4512 PROCESS_INFORMATION pi;
4513 DWORD ret = 0;
4514
4515 HANDLE g_hChildStd_IN_Rd = NULL;
4516 HANDLE g_hChildStd_IN_Wr = NULL;
4517 HANDLE g_hChildStd_OUT_Rd = NULL;
4518 HANDLE g_hChildStd_OUT_Wr = NULL;
4519
4520 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4521 DWORD len;
4522
4523 /* buffer used to receive keys */
4524 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4525 int ta_len = 0; /* valid bytes in ta_buf[] */
4526
4527 DWORD i;
4528 int c;
4529 int noread_cnt = 0;
4530 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004531 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004533 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004534
4535 SECURITY_ATTRIBUTES saAttr;
4536
4537 /* Set the bInheritHandle flag so pipe handles are inherited. */
4538 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4539 saAttr.bInheritHandle = TRUE;
4540 saAttr.lpSecurityDescriptor = NULL;
4541
4542 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4543 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004544 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 /* Create a pipe for the child process's STDIN. */
4546 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4547 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004548 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004549 {
4550 CloseHandle(g_hChildStd_IN_Rd);
4551 CloseHandle(g_hChildStd_IN_Wr);
4552 CloseHandle(g_hChildStd_OUT_Rd);
4553 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004554 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004555 }
4556
4557 si.cb = sizeof(si);
4558 si.lpReserved = NULL;
4559 si.lpDesktop = NULL;
4560 si.lpTitle = NULL;
4561 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4562
4563 /* set-up our file redirection */
4564 si.hStdError = g_hChildStd_OUT_Wr;
4565 si.hStdOutput = g_hChildStd_OUT_Wr;
4566 si.hStdInput = g_hChildStd_IN_Rd;
4567 si.wShowWindow = SW_HIDE;
4568 si.cbReserved2 = 0;
4569 si.lpReserved2 = NULL;
4570
4571 if (options & SHELL_READ)
4572 ga_init2(&ga, 1, BUFLEN);
4573
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004574 if (cmd != NULL)
4575 {
4576 p = (char *)vim_strsave((char_u *)cmd);
4577 if (p != NULL)
4578 unescape_shellxquote((char_u *)p, p_sxe);
4579 else
4580 p = cmd;
4581 }
4582
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004583 /* Now, run the command.
4584 * About "Inherit handles" being TRUE: this command can be litigious,
4585 * handle inheritance was deactivated for pending temp file, but, if we
4586 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004587 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4588 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004589
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004590 if (p != cmd)
4591 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004592
4593 /* Close our unused side of the pipes */
4594 CloseHandle(g_hChildStd_IN_Rd);
4595 CloseHandle(g_hChildStd_OUT_Wr);
4596
4597 if (options & SHELL_WRITE)
4598 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004599 HANDLE thread = (HANDLE)
4600 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601 0, /* default stack size */
4602 sub_process_writer, /* function to be executed */
4603 g_hChildStd_IN_Wr, /* parameter */
4604 0, /* creation flag, start immediately */
4605 NULL); /* we don't care about thread id */
4606 CloseHandle(thread);
4607 g_hChildStd_IN_Wr = NULL;
4608 }
4609
4610 /* Keep updating the window while waiting for the shell to finish. */
4611 for (;;)
4612 {
4613 MSG msg;
4614
Bram Moolenaar175d0702013-12-11 18:36:33 +01004615 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004616 {
4617 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004618 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004619 }
4620
4621 /* write pipe information in the window */
4622 if ((options & (SHELL_READ|SHELL_WRITE))
4623# ifdef FEAT_GUI
4624 || gui.in_use
4625# endif
4626 )
4627 {
4628 len = 0;
4629 if (!(options & SHELL_EXPAND)
4630 && ((options &
4631 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4632 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4633# ifdef FEAT_GUI
4634 || gui.in_use
4635# endif
4636 )
4637 && (ta_len > 0 || noread_cnt > 4))
4638 {
4639 if (ta_len == 0)
4640 {
4641 /* Get extra characters when we don't have any. Reset the
4642 * counter and timer. */
4643 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004644 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4645 }
4646 if (ta_len > 0 || len > 0)
4647 {
4648 /*
4649 * For pipes: Check for CTRL-C: send interrupt signal to
4650 * child. Check for CTRL-D: EOF, close pipe to child.
4651 */
4652 if (len == 1 && cmd != NULL)
4653 {
4654 if (ta_buf[ta_len] == Ctrl_C)
4655 {
4656 /* Learn what exit code is expected, for
4657 * now put 9 as SIGKILL */
4658 TerminateProcess(pi.hProcess, 9);
4659 }
4660 if (ta_buf[ta_len] == Ctrl_D)
4661 {
4662 CloseHandle(g_hChildStd_IN_Wr);
4663 g_hChildStd_IN_Wr = NULL;
4664 }
4665 }
4666
4667 /* replace K_BS by <BS> and K_DEL by <DEL> */
4668 for (i = ta_len; i < ta_len + len; ++i)
4669 {
4670 if (ta_buf[i] == CSI && len - i > 2)
4671 {
4672 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4673 if (c == K_DEL || c == K_KDEL || c == K_BS)
4674 {
4675 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4676 (size_t)(len - i - 2));
4677 if (c == K_DEL || c == K_KDEL)
4678 ta_buf[i] = DEL;
4679 else
4680 ta_buf[i] = Ctrl_H;
4681 len -= 2;
4682 }
4683 }
4684 else if (ta_buf[i] == '\r')
4685 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004686 if (has_mbyte)
4687 i += (*mb_ptr2len_len)(ta_buf + i,
4688 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004689 }
4690
4691 /*
4692 * For pipes: echo the typed characters. For a pty this
4693 * does not seem to work.
4694 */
4695 for (i = ta_len; i < ta_len + len; ++i)
4696 {
4697 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4698 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004699 else if (has_mbyte)
4700 {
4701 int l = (*mb_ptr2len)(ta_buf + i);
4702
4703 msg_outtrans_len(ta_buf + i, l);
4704 i += l - 1;
4705 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004706 else
4707 msg_outtrans_len(ta_buf + i, 1);
4708 }
4709 windgoto(msg_row, msg_col);
4710 out_flush();
4711
4712 ta_len += len;
4713
4714 /*
4715 * Write the characters to the child, unless EOF has been
4716 * typed for pipes. Write one character at a time, to
4717 * avoid losing too much typeahead. When writing buffer
4718 * lines, drop the typed characters (only check for
4719 * CTRL-C).
4720 */
4721 if (options & SHELL_WRITE)
4722 ta_len = 0;
4723 else if (g_hChildStd_IN_Wr != NULL)
4724 {
4725 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4726 1, &len, NULL);
4727 // if we are typing in, we want to keep things reactive
4728 delay = 1;
4729 if (len > 0)
4730 {
4731 ta_len -= len;
4732 mch_memmove(ta_buf, ta_buf + len, ta_len);
4733 }
4734 }
4735 }
4736 }
4737 }
4738
4739 if (ta_len)
4740 ui_inchar_undo(ta_buf, ta_len);
4741
4742 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4743 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004744 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004745 break;
4746 }
4747
4748 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004749 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004750
4751 /* We start waiting for a very short time and then increase it, so
4752 * that we respond quickly when the process is quick, and don't
4753 * consume too much overhead when it's slow. */
4754 if (delay < 50)
4755 delay += 10;
4756 }
4757
4758 /* Close the pipe */
4759 CloseHandle(g_hChildStd_OUT_Rd);
4760 if (g_hChildStd_IN_Wr != NULL)
4761 CloseHandle(g_hChildStd_IN_Wr);
4762
4763 WaitForSingleObject(pi.hProcess, INFINITE);
4764
4765 /* Get the command exit code */
4766 GetExitCodeProcess(pi.hProcess, &ret);
4767
4768 if (options & SHELL_READ)
4769 {
4770 if (ga.ga_len > 0)
4771 {
4772 append_ga_line(&ga);
4773 /* remember that the NL was missing */
4774 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4775 }
4776 else
4777 curbuf->b_no_eol_lnum = 0;
4778 ga_clear(&ga);
4779 }
4780
4781 /* Close the handles to the subprocess, so that it goes away */
4782 CloseHandle(pi.hThread);
4783 CloseHandle(pi.hProcess);
4784
4785 return ret;
4786}
4787
4788 static int
4789mch_system(char *cmd, int options)
4790{
4791 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004792 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004793 return mch_system_piped(cmd, options);
4794 else
4795 return mch_system_classic(cmd, options);
4796}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797#else
4798
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004799 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004800mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004801{
4802 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4803 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004804 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004805 if (wcmd != NULL)
4806 {
4807 int ret = _wsystem(wcmd);
4808 vim_free(wcmd);
4809 return ret;
4810 }
4811 }
4812 return system(cmd);
4813}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814
4815#endif
4816
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004817#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4818/*
4819 * Use a terminal window to run a shell command in.
4820 */
4821 static int
4822mch_call_shell_terminal(
4823 char_u *cmd,
4824 int options UNUSED) /* SHELL_*, see vim.h */
4825{
4826 jobopt_T opt;
4827 char_u *newcmd = NULL;
4828 typval_T argvar[2];
4829 long_u cmdlen;
4830 int retval = -1;
4831 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004832 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004833 aco_save_T aco;
4834 oparg_T oa; /* operator arguments */
4835
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004836 if (cmd == NULL)
4837 cmdlen = STRLEN(p_sh) + 1;
4838 else
4839 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004840 newcmd = lalloc(cmdlen, TRUE);
4841 if (newcmd == NULL)
4842 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004843 if (cmd == NULL)
4844 {
4845 STRCPY(newcmd, p_sh);
4846 ch_log(NULL, "starting terminal to run a shell");
4847 }
4848 else
4849 {
4850 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4851 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4852 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004853
4854 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004855
4856 argvar[0].v_type = VAR_STRING;
4857 argvar[0].vval.v_string = newcmd;
4858 argvar[1].v_type = VAR_UNKNOWN;
4859 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004860 if (buf == NULL)
4861 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004862
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004863 job = term_getjob(buf->b_term);
4864 ++job->jv_refcount;
4865
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004866 /* Find a window to make "buf" curbuf. */
4867 aucmd_prepbuf(&aco, buf);
4868
4869 clear_oparg(&oa);
4870 while (term_use_loop())
4871 {
4872 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4873 {
4874 /* If terminal_loop() returns OK we got a key that is handled
4875 * in Normal model. We don't do redrawing anyway. */
4876 if (terminal_loop(TRUE) == OK)
4877 normal_cmd(&oa, TRUE);
4878 }
4879 else
4880 normal_cmd(&oa, TRUE);
4881 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004882 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004883 ch_log(NULL, "system command finished");
4884
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004885 job_unref(job);
4886
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004887 /* restore curwin/curbuf and a few other things */
4888 aucmd_restbuf(&aco);
4889
4890 wait_return(TRUE);
4891 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4892
4893 vim_free(newcmd);
4894 return retval;
4895}
4896#endif
4897
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898/*
4899 * Either execute a command by calling the shell or start a new shell
4900 */
4901 int
4902mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004903 char_u *cmd,
4904 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905{
4906 int x = 0;
4907 int tmode = cur_tmode;
4908#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004909 char szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004910 int did_set_title = FALSE;
4911
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004912 /* Change the title to reflect that we are in a subshell. */
4913 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4914 {
4915 WCHAR szShellTitle[512];
4916
4917 if (GetConsoleTitleW(szShellTitle,
4918 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4919 {
4920 if (cmd == NULL)
4921 wcscat(szShellTitle, L" :sh");
4922 else
4923 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004924 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004925
4926 if (wn != NULL)
4927 {
4928 wcscat(szShellTitle, L" - !");
4929 if ((wcslen(szShellTitle) + wcslen(wn) <
4930 sizeof(szShellTitle)/sizeof(WCHAR)))
4931 wcscat(szShellTitle, wn);
4932 SetConsoleTitleW(szShellTitle);
4933 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004934 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004935 }
4936 }
4937 }
4938 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004939 if (!did_set_title)
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004940 /* Change the title to reflect that we are in a subshell. */
4941 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004943 if (cmd == NULL)
4944 strcat(szShellTitle, " :sh");
4945 else
4946 {
4947 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004948 if ((strlen(szShellTitle) + strlen((char *)cmd)
4949 < sizeof(szShellTitle)))
4950 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004951 }
4952 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954#endif
4955
4956 out_flush();
4957
4958#ifdef MCH_WRITE_DUMP
4959 if (fdDump)
4960 {
4961 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4962 fflush(fdDump);
4963 }
4964#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004965#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4966 /* TODO: make the terminal window work with input or output redirected. */
4967 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4968 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4969 {
4970 /* Use a terminal window to run the command in. */
4971 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004972# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004973 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004974# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004975 return x;
4976 }
4977#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978
4979 /*
4980 * Catch all deadly signals while running the external command, because a
4981 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4982 */
4983 signal(SIGINT, SIG_IGN);
4984#if defined(__GNUC__) && !defined(__MINGW32__)
4985 signal(SIGKILL, SIG_IGN);
4986#else
4987 signal(SIGBREAK, SIG_IGN);
4988#endif
4989 signal(SIGILL, SIG_IGN);
4990 signal(SIGFPE, SIG_IGN);
4991 signal(SIGSEGV, SIG_IGN);
4992 signal(SIGTERM, SIG_IGN);
4993 signal(SIGABRT, SIG_IGN);
4994
4995 if (options & SHELL_COOKED)
4996 settmode(TMODE_COOK); /* set to normal mode */
4997
4998 if (cmd == NULL)
4999 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005000 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 }
5002 else
5003 {
5004 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005005 char_u *newcmd = NULL;
5006 char_u *cmdbase = cmd;
5007 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005008
5009 /* Skip a leading ", ( and "(. */
5010 if (*cmdbase == '"' )
5011 ++cmdbase;
5012 if (*cmdbase == '(')
5013 ++cmdbase;
5014
Bram Moolenaar1c465442017-03-12 20:10:05 +01005015 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005016 {
5017 STARTUPINFO si;
5018 PROCESS_INFORMATION pi;
5019 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005020 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005021 char_u *p;
5022
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005023 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005024 si.cb = sizeof(si);
5025 si.lpReserved = NULL;
5026 si.lpDesktop = NULL;
5027 si.lpTitle = NULL;
5028 si.dwFlags = 0;
5029 si.cbReserved2 = 0;
5030 si.lpReserved2 = NULL;
5031
5032 cmdbase = skipwhite(cmdbase + 5);
5033 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005034 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005035 {
5036 cmdbase = skipwhite(cmdbase + 4);
5037 si.dwFlags = STARTF_USESHOWWINDOW;
5038 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005039 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005040 }
5041 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005042 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005043 {
5044 cmdbase = skipwhite(cmdbase + 2);
5045 flags = CREATE_NO_WINDOW;
5046 si.dwFlags = STARTF_USESTDHANDLES;
5047 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005048 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005049 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005050 NULL, // Security att.
5051 OPEN_EXISTING, // Open flags
5052 FILE_ATTRIBUTE_NORMAL, // File att.
5053 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005054 si.hStdOutput = si.hStdInput;
5055 si.hStdError = si.hStdInput;
5056 }
5057
5058 /* Remove a trailing ", ) and )" if they have a match
5059 * at the start of the command. */
5060 if (cmdbase > cmd)
5061 {
5062 p = cmdbase + STRLEN(cmdbase);
5063 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5064 *--p = NUL;
5065 if (p > cmdbase && p[-1] == ')'
5066 && (*cmd =='(' || cmd[1] == '('))
5067 *--p = NUL;
5068 }
5069
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005070 newcmd = cmdbase;
5071 unescape_shellxquote(cmdbase, p_sxe);
5072
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005073 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005074 * If creating new console, arguments are passed to the
5075 * 'cmd.exe' as-is. If it's not, arguments are not treated
5076 * correctly for current 'cmd.exe'. So unescape characters in
5077 * shellxescape except '|' for avoiding to be treated as
5078 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005079 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005080 if (flags != CREATE_NEW_CONSOLE)
5081 {
5082 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005083 char_u *cmd_shell = mch_getenv("COMSPEC");
5084
5085 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005086 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005087
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005088 subcmd = vim_strsave_escaped_ext(cmdbase,
5089 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005090 if (subcmd != NULL)
5091 {
5092 /* make "cmd.exe /c arguments" */
5093 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005094 newcmd = lalloc(cmdlen, TRUE);
5095 if (newcmd != NULL)
5096 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005097 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005098 else
5099 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005100 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005101 }
5102 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005103
5104 /*
5105 * Now, start the command as a process, so that it doesn't
5106 * inherit our handles which causes unpleasant dangling swap
5107 * files if we exit before the spawned process
5108 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005109 if (vim_create_process((char *)newcmd, FALSE, flags,
5110 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005111 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005112 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5113 > (HINSTANCE)32)
5114 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005115 else
5116 {
5117 x = -1;
5118#ifdef FEAT_GUI_W32
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005119 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005120#endif
5121 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005122
5123 if (newcmd != cmdbase)
5124 vim_free(newcmd);
5125
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005126 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005127 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005128 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005129 CloseHandle(si.hStdInput);
5130 }
5131 /* Close the handles to the subprocess, so that it goes away */
5132 CloseHandle(pi.hThread);
5133 CloseHandle(pi.hProcess);
5134 }
5135 else
5136 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005137 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005138#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005139 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005141 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5142
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005143 newcmd = lalloc(cmdlen, TRUE);
5144 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145 {
5146#if defined(FEAT_GUI_W32)
5147 if (need_vimrun_warning)
5148 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005149 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5150 "External commands will not pause after completion.\n"
5151 "See :help win32-vimrun for more information.");
5152 char *title = _("Vim Warning");
Bram Moolenaar63e43442016-11-19 17:28:44 +01005153 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5154 {
5155 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5156 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5157
5158 if (wmsg != NULL && wtitle != NULL)
5159 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5160 vim_free(wmsg);
5161 vim_free(wtitle);
5162 }
5163 else
Bram Moolenaar63e43442016-11-19 17:28:44 +01005164 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 need_vimrun_warning = FALSE;
5166 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005167 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 /* Use vimrun to execute the command. It opens a console
5169 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005170 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 vimrun_path,
5172 (msg_silent != 0 || (options & SHELL_DOOUT))
5173 ? "-s " : "",
5174 p_sh, p_shcf, cmd);
5175 else
5176#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005177 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005178 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005180 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 }
5183 }
5184
5185 if (tmode == TMODE_RAW)
5186 settmode(TMODE_RAW); /* set to raw mode */
5187
5188 /* Print the return value, unless "vimrun" was used. */
5189 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5190#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005191 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192#endif
5193 )
5194 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005195 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 msg_putchar('\n');
5197 }
5198#ifdef FEAT_TITLE
5199 resettitle();
5200#endif
5201
5202 signal(SIGINT, SIG_DFL);
5203#if defined(__GNUC__) && !defined(__MINGW32__)
5204 signal(SIGKILL, SIG_DFL);
5205#else
5206 signal(SIGBREAK, SIG_DFL);
5207#endif
5208 signal(SIGILL, SIG_DFL);
5209 signal(SIGFPE, SIG_DFL);
5210 signal(SIGSEGV, SIG_DFL);
5211 signal(SIGTERM, SIG_DFL);
5212 signal(SIGABRT, SIG_DFL);
5213
5214 return x;
5215}
5216
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005217#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005218 static HANDLE
5219job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005220 char_u *fname,
5221 DWORD dwDesiredAccess,
5222 DWORD dwShareMode,
5223 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5224 DWORD dwCreationDisposition,
5225 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005226{
5227 HANDLE h;
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005228 WCHAR *wn = NULL;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005229
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005230 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5231 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005232 wn = enc_to_utf16(fname, NULL);
5233 if (wn != NULL)
5234 {
5235 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5236 lpSecurityAttributes, dwCreationDisposition,
5237 dwFlagsAndAttributes, NULL);
5238 vim_free(wn);
5239 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005240 }
5241 if (wn == NULL)
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005242 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5243 lpSecurityAttributes, dwCreationDisposition,
5244 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005245 return h;
5246}
5247
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005248/*
5249 * Turn the dictionary "env" into a NUL separated list that can be used as the
5250 * environment argument of vim_create_process().
5251 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005252 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005253win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005254{
5255 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005256 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005257 LPVOID base = GetEnvironmentStringsW();
5258
5259 /* for last \0 */
5260 if (ga_grow(gap, 1) == FAIL)
5261 return;
5262
5263 if (base)
5264 {
5265 WCHAR *p = (WCHAR*) base;
5266
5267 /* for last \0 */
5268 if (ga_grow(gap, 1) == FAIL)
5269 return;
5270
5271 while (*p != 0 || *(p + 1) != 0)
5272 {
5273 if (ga_grow(gap, 1) == OK)
5274 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5275 p++;
5276 }
5277 FreeEnvironmentStrings(base);
5278 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5279 }
5280
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005281 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005282 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005283 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005284 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005285 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005287 typval_T *item = &dict_lookup(hi)->di_tv;
5288 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005289 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005290 --todo;
5291 if (wkey != NULL && wval != NULL)
5292 {
5293 size_t n;
5294 size_t lkey = wcslen(wkey);
5295 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005296
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005297 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5298 continue;
5299 for (n = 0; n < lkey; n++)
5300 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5301 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5302 for (n = 0; n < lval; n++)
5303 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5304 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5305 }
5306 if (wkey != NULL) vim_free(wkey);
5307 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005308 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005309 }
5310 }
5311
Bram Moolenaar493359e2018-06-12 20:25:52 +02005312# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005313 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005314# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005316 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005317# endif
5318# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005319 char_u *version = get_vim_var_str(VV_VERSION);
5320 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005321# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005322 // size of "VIM_SERVERNAME=" and value,
5323 // plus "VIM_TERMINAL=" and value,
5324 // plus two terminating NULs
5325 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005326# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005327 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005328# endif
5329# ifdef FEAT_TERMINAL
5330 + 13 + version_len + 2
5331# endif
5332 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005333
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005334 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005335 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005336# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005337 for (n = 0; n < 15; n++)
5338 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5339 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005340 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005341 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5342 (WCHAR)servername[n];
5343 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# endif
5345# ifdef FEAT_TERMINAL
5346 if (is_terminal)
5347 {
5348 for (n = 0; n < 13; n++)
5349 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5350 (WCHAR)"VIM_TERMINAL="[n];
5351 for (n = 0; n < version_len; n++)
5352 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5353 (WCHAR)version[n];
5354 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5355 }
5356# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005357 }
5358 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005359# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005360}
5361
Bram Moolenaarb091f302019-01-19 14:37:00 +01005362/*
5363 * Create a pair of pipes.
5364 * Return TRUE for success, FALSE for failure.
5365 */
5366 static BOOL
5367create_pipe_pair(HANDLE handles[2])
5368{
5369 static LONG s;
5370 char name[64];
5371 SECURITY_ATTRIBUTES sa;
5372
5373 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5374 GetCurrentProcessId(),
5375 InterlockedIncrement(&s));
5376
5377 // Create named pipe. Max size of named pipe is 65535.
5378 handles[1] = CreateNamedPipe(
5379 name,
5380 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5381 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005382 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005383
5384 if (handles[1] == INVALID_HANDLE_VALUE)
5385 return FALSE;
5386
5387 sa.nLength = sizeof(sa);
5388 sa.bInheritHandle = TRUE;
5389 sa.lpSecurityDescriptor = NULL;
5390
5391 handles[0] = CreateFile(name,
5392 FILE_GENERIC_READ,
5393 FILE_SHARE_READ, &sa,
5394 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5395
5396 if (handles[0] == INVALID_HANDLE_VALUE)
5397 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005398 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005399 return FALSE;
5400 }
5401
5402 return TRUE;
5403}
5404
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005405 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005406mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005407{
5408 STARTUPINFO si;
5409 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005410 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005411 SECURITY_ATTRIBUTES saAttr;
5412 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005413 HANDLE ifd[2];
5414 HANDLE ofd[2];
5415 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005416 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005417
5418 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5419 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5420 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5421 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5422 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5423 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5424 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5425
5426 if (use_out_for_err && use_null_for_out)
5427 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005428
5429 ifd[0] = INVALID_HANDLE_VALUE;
5430 ifd[1] = INVALID_HANDLE_VALUE;
5431 ofd[0] = INVALID_HANDLE_VALUE;
5432 ofd[1] = INVALID_HANDLE_VALUE;
5433 efd[0] = INVALID_HANDLE_VALUE;
5434 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005435 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005436
Bram Moolenaar14207f42016-10-27 21:13:10 +02005437 jo = CreateJobObject(NULL, NULL);
5438 if (jo == NULL)
5439 {
5440 job->jv_status = JOB_FAILED;
5441 goto failed;
5442 }
5443
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005444 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005445 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005446
Bram Moolenaar76467df2016-02-12 19:30:26 +01005447 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005448 ZeroMemory(&si, sizeof(si));
5449 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005450 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005451 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005452
Bram Moolenaard8070362016-02-15 21:56:54 +01005453 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5454 saAttr.bInheritHandle = TRUE;
5455 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005456
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005457 if (use_file_for_in)
5458 {
5459 char_u *fname = options->jo_io_name[PART_IN];
5460
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005461 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5462 FILE_SHARE_READ | FILE_SHARE_WRITE,
5463 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5464 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005465 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005466 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005467 goto failed;
5468 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005469 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005470 else if (!use_null_for_in
5471 && (!create_pipe_pair(ifd)
5472 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005473 goto failed;
5474
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005475 if (use_file_for_out)
5476 {
5477 char_u *fname = options->jo_io_name[PART_OUT];
5478
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005479 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5480 FILE_SHARE_READ | FILE_SHARE_WRITE,
5481 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5482 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005483 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005484 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005485 goto failed;
5486 }
5487 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005488 else if (!use_null_for_out &&
5489 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005490 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005491 goto failed;
5492
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005493 if (use_file_for_err)
5494 {
5495 char_u *fname = options->jo_io_name[PART_ERR];
5496
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005497 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5498 FILE_SHARE_READ | FILE_SHARE_WRITE,
5499 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5500 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005501 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005502 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005503 goto failed;
5504 }
5505 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005506 else if (!use_out_for_err && !use_null_for_err &&
5507 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005508 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005509 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005510
Bram Moolenaard8070362016-02-15 21:56:54 +01005511 si.dwFlags |= STARTF_USESTDHANDLES;
5512 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005513 si.hStdOutput = ofd[1];
5514 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5515
5516 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5517 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005518 if (options->jo_set & JO_CHANNEL)
5519 {
5520 channel = options->jo_channel;
5521 if (channel != NULL)
5522 ++channel->ch_refcount;
5523 }
5524 else
5525 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005526 if (channel == NULL)
5527 goto failed;
5528 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005529
5530 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005531 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005532 CREATE_DEFAULT_ERROR_MODE |
5533 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005534 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005535 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005536 &si, &pi,
5537 ga.ga_data,
5538 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005539 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005540 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005541 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005542 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005543 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005544
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005545 ga_clear(&ga);
5546
Bram Moolenaar14207f42016-10-27 21:13:10 +02005547 if (!AssignProcessToJobObject(jo, pi.hProcess))
5548 {
5549 /* if failing, switch the way to terminate
5550 * process with TerminateProcess. */
5551 CloseHandle(jo);
5552 jo = NULL;
5553 }
5554 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005555 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005556 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005557 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005558 job->jv_status = JOB_STARTED;
5559
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005560 CloseHandle(ifd[0]);
5561 CloseHandle(ofd[1]);
5562 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005563 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005564
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005565 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005566 if (channel != NULL)
5567 {
5568 channel_set_pipes(channel,
5569 use_file_for_in || use_null_for_in
5570 ? INVALID_FD : (sock_T)ifd[1],
5571 use_file_for_out || use_null_for_out
5572 ? INVALID_FD : (sock_T)ofd[0],
5573 use_out_for_err || use_file_for_err || use_null_for_err
5574 ? INVALID_FD : (sock_T)efd[0]);
5575 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005576 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005577 return;
5578
5579failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005580 CloseHandle(ifd[0]);
5581 CloseHandle(ofd[0]);
5582 CloseHandle(efd[0]);
5583 CloseHandle(ifd[1]);
5584 CloseHandle(ofd[1]);
5585 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005586 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005587 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005588}
5589
5590 char *
5591mch_job_status(job_T *job)
5592{
5593 DWORD dwExitCode = 0;
5594
Bram Moolenaar76467df2016-02-12 19:30:26 +01005595 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5596 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005597 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005598 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005599 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005600 {
5601 ch_log(job->jv_channel, "Job ended");
5602 job->jv_status = JOB_ENDED;
5603 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005604 return "dead";
5605 }
5606 return "run";
5607}
5608
Bram Moolenaar97792de2016-10-15 18:36:49 +02005609 job_T *
5610mch_detect_ended_job(job_T *job_list)
5611{
5612 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5613 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5614 job_T *job = job_list;
5615
5616 while (job != NULL)
5617 {
5618 DWORD n;
5619 DWORD result;
5620
5621 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5622 && job != NULL; job = job->jv_next)
5623 {
5624 if (job->jv_status == JOB_STARTED)
5625 {
5626 jobHandles[n] = job->jv_proc_info.hProcess;
5627 jobArray[n] = job;
5628 ++n;
5629 }
5630 }
5631 if (n == 0)
5632 continue;
5633 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5634 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5635 {
5636 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5637
5638 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5639 return wait_job;
5640 }
5641 }
5642 return NULL;
5643}
5644
Bram Moolenaarfb630902016-10-29 14:55:00 +02005645 static BOOL
5646terminate_all(HANDLE process, int code)
5647{
5648 PROCESSENTRY32 pe;
5649 HANDLE h = INVALID_HANDLE_VALUE;
5650 DWORD pid = GetProcessId(process);
5651
5652 if (pid != 0)
5653 {
5654 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5655 if (h != INVALID_HANDLE_VALUE)
5656 {
5657 pe.dwSize = sizeof(PROCESSENTRY32);
5658 if (!Process32First(h, &pe))
5659 goto theend;
5660
5661 do
5662 {
5663 if (pe.th32ParentProcessID == pid)
5664 {
5665 HANDLE ph = OpenProcess(
5666 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5667 if (ph != NULL)
5668 {
5669 terminate_all(ph, code);
5670 CloseHandle(ph);
5671 }
5672 }
5673 } while (Process32Next(h, &pe));
5674
5675 CloseHandle(h);
5676 }
5677 }
5678
5679theend:
5680 return TerminateProcess(process, code);
5681}
5682
5683/*
5684 * Send a (deadly) signal to "job".
5685 * Return FAIL if it didn't work.
5686 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005687 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005688mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005689{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005690 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005691
Bram Moolenaar923d9262016-02-25 20:56:01 +01005692 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005693 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005694 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005695 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005696 {
5697 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5698 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005699 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005700 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005701 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005702 }
5703
5704 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5705 return FAIL;
5706 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005707 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5708 job->jv_proc_info.dwProcessId)
5709 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 FreeConsole();
5711 return ret;
5712}
5713
5714/*
5715 * Clear the data related to "job".
5716 */
5717 void
5718mch_clear_job(job_T *job)
5719{
5720 if (job->jv_status != JOB_FAILED)
5721 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005722 if (job->jv_job_object != NULL)
5723 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005724 CloseHandle(job->jv_proc_info.hProcess);
5725 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005726}
5727#endif
5728
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
5730#ifndef FEAT_GUI_W32
5731
5732/*
5733 * Start termcap mode
5734 */
5735 static void
5736termcap_mode_start(void)
5737{
5738 DWORD cmodein;
5739
5740 if (g_fTermcapMode)
5741 return;
5742
5743 SaveConsoleBuffer(&g_cbNonTermcap);
5744
5745 if (g_cbTermcap.IsValid)
5746 {
5747 /*
5748 * We've been in termcap mode before. Restore certain screen
5749 * characteristics, including the buffer size and the window
5750 * size. Since we will be redrawing the screen, we don't need
5751 * to restore the actual contents of the buffer.
5752 */
5753 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005754 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5756 Rows = g_cbTermcap.Info.dwSize.Y;
5757 Columns = g_cbTermcap.Info.dwSize.X;
5758 }
5759 else
5760 {
5761 /*
5762 * This is our first time entering termcap mode. Clear the console
5763 * screen buffer, and resize the buffer to match the current window
5764 * size. We will use this as the size of our editing environment.
5765 */
5766 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005767 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5769 }
5770
5771#ifdef FEAT_TITLE
5772 resettitle();
5773#endif
5774
5775 GetConsoleMode(g_hConIn, &cmodein);
5776#ifdef FEAT_MOUSE
5777 if (g_fMouseActive)
5778 cmodein |= ENABLE_MOUSE_INPUT;
5779 else
5780 cmodein &= ~ENABLE_MOUSE_INPUT;
5781#endif
5782 cmodein |= ENABLE_WINDOW_INPUT;
5783 SetConsoleMode(g_hConIn, cmodein);
5784
5785 redraw_later_clear();
5786 g_fTermcapMode = TRUE;
5787}
5788
5789
5790/*
5791 * End termcap mode
5792 */
5793 static void
5794termcap_mode_end(void)
5795{
5796 DWORD cmodein;
5797 ConsoleBuffer *cb;
5798 COORD coord;
5799 DWORD dwDummy;
5800
5801 if (!g_fTermcapMode)
5802 return;
5803
5804 SaveConsoleBuffer(&g_cbTermcap);
5805
5806 GetConsoleMode(g_hConIn, &cmodein);
5807 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5808 SetConsoleMode(g_hConIn, cmodein);
5809
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005810#ifdef FEAT_RESTORE_ORIG_SCREEN
5811 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5812#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005816 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817 SetConsoleCursorInfo(g_hConOut, &g_cci);
5818
5819 if (p_rs || exiting)
5820 {
5821 /*
5822 * Clear anything that happens to be on the current line.
5823 */
5824 coord.X = 0;
5825 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5826 FillConsoleOutputCharacter(g_hConOut, ' ',
5827 cb->Info.dwSize.X, coord, &dwDummy);
5828 /*
5829 * The following is just for aesthetics. If we are exiting without
5830 * restoring the screen, then we want to have a prompt string
5831 * appear at the bottom line. However, the command interpreter
5832 * seems to always advance the cursor one line before displaying
5833 * the prompt string, which causes the screen to scroll. To
5834 * counter this, move the cursor up one line before exiting.
5835 */
5836 if (exiting && !p_rs)
5837 coord.Y--;
5838 /*
5839 * Position the cursor at the leftmost column of the desired row.
5840 */
5841 SetConsoleCursorPosition(g_hConOut, coord);
5842 }
5843
5844 g_fTermcapMode = FALSE;
5845}
5846#endif /* FEAT_GUI_W32 */
5847
5848
5849#ifdef FEAT_GUI_W32
5850 void
5851mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005852 char_u *s UNUSED,
5853 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854{
5855 /* never used */
5856}
5857
5858#else
5859
5860/*
5861 * clear `n' chars, starting from `coord'
5862 */
5863 static void
5864clear_chars(
5865 COORD coord,
5866 DWORD n)
5867{
5868 DWORD dwDummy;
5869
5870 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005871
5872 if (!USE_VTP)
5873 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5874 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005875 {
5876 set_console_color_rgb();
5877 gotoxy(coord.X + 1, coord.Y + 1);
5878 vtp_printf("\033[%dX", n);
5879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880}
5881
5882
5883/*
5884 * Clear the screen
5885 */
5886 static void
5887clear_screen(void)
5888{
5889 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005890
5891 if (!USE_VTP)
5892 clear_chars(g_coord, Rows * Columns);
5893 else
5894 {
5895 set_console_color_rgb();
5896 gotoxy(1, 1);
5897 vtp_printf("\033[2J");
5898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899}
5900
5901
5902/*
5903 * Clear to end of display
5904 */
5905 static void
5906clear_to_end_of_display(void)
5907{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005908 COORD save = g_coord;
5909
5910 if (!USE_VTP)
5911 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005913 else
5914 {
5915 set_console_color_rgb();
5916 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5917 vtp_printf("\033[0J");
5918
5919 gotoxy(save.X + 1, save.Y + 1);
5920 g_coord = save;
5921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922}
5923
5924
5925/*
5926 * Clear to end of line
5927 */
5928 static void
5929clear_to_end_of_line(void)
5930{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005931 COORD save = g_coord;
5932
5933 if (!USE_VTP)
5934 clear_chars(g_coord, Columns - g_coord.X);
5935 else
5936 {
5937 set_console_color_rgb();
5938 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5939 vtp_printf("\033[0K");
5940
5941 gotoxy(save.X + 1, save.Y + 1);
5942 g_coord = save;
5943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944}
5945
5946
5947/*
5948 * Scroll the scroll region up by `cLines' lines
5949 */
5950 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005951scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952{
5953 COORD oldcoord = g_coord;
5954
5955 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5956 delete_lines(cLines);
5957
5958 g_coord = oldcoord;
5959}
5960
5961
5962/*
5963 * Set the scroll region
5964 */
5965 static void
5966set_scroll_region(
5967 unsigned left,
5968 unsigned top,
5969 unsigned right,
5970 unsigned bottom)
5971{
5972 if (left >= right
5973 || top >= bottom
5974 || right > (unsigned) Columns - 1
5975 || bottom > (unsigned) Rows - 1)
5976 return;
5977
5978 g_srScrollRegion.Left = left;
5979 g_srScrollRegion.Top = top;
5980 g_srScrollRegion.Right = right;
5981 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005982}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005983
Bram Moolenaar6982f422019-02-16 16:48:01 +01005984 static void
5985set_scroll_region_tb(
5986 unsigned top,
5987 unsigned bottom)
5988{
5989 if (top >= bottom || bottom > (unsigned)Rows - 1)
5990 return;
5991
5992 g_srScrollRegion.Top = top;
5993 g_srScrollRegion.Bottom = bottom;
5994}
5995
5996 static void
5997set_scroll_region_lr(
5998 unsigned left,
5999 unsigned right)
6000{
6001 if (left >= right || right > (unsigned)Columns - 1)
6002 return;
6003
6004 g_srScrollRegion.Left = left;
6005 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006}
6007
6008
6009/*
6010 * Insert `cLines' lines at the current cursor position
6011 */
6012 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006013insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006015 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 COORD dest;
6017 CHAR_INFO fill;
6018
Bram Moolenaar6982f422019-02-16 16:48:01 +01006019 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 dest.Y = g_coord.Y + cLines;
6021
Bram Moolenaar6982f422019-02-16 16:48:01 +01006022 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023 source.Top = g_coord.Y;
6024 source.Right = g_srScrollRegion.Right;
6025 source.Bottom = g_srScrollRegion.Bottom - cLines;
6026
Bram Moolenaar6982f422019-02-16 16:48:01 +01006027 clip.Left = g_srScrollRegion.Left;
6028 clip.Top = g_coord.Y;
6029 clip.Right = g_srScrollRegion.Right;
6030 clip.Bottom = g_srScrollRegion.Bottom;
6031
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006032 {
6033 fill.Char.AsciiChar = ' ';
Bram Moolenaar21edde82019-02-17 14:10:56 +01006034 if (!USE_VTP)
6035 fill.Attributes = g_attrCurrent;
6036 else
6037 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006039 set_console_color_rgb();
6040
Bram Moolenaar6982f422019-02-16 16:48:01 +01006041 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006042 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006043 // Here we have to deal with a win32 console flake: If the scroll
6044 // region looks like abc and we scroll c to a and fill with d we get
6045 // cbd... if we scroll block c one line at a time to a, we get cdd...
6046 // vim expects cdd consistently... So we have to deal with that
6047 // here... (this also occurs scrolling the same way in the other
6048 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049
6050 if (source.Bottom < dest.Y)
6051 {
6052 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006053 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054
Bram Moolenaar6982f422019-02-16 16:48:01 +01006055 coord.X = source.Left;
6056 for (i = clip.Top; i < dest.Y; ++i)
6057 {
6058 coord.Y = i;
6059 clear_chars(coord, source.Right - source.Left + 1);
6060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061 }
6062}
6063
6064
6065/*
6066 * Delete `cLines' lines at the current cursor position
6067 */
6068 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006069delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070{
Bram Moolenaar6982f422019-02-16 16:48:01 +01006071 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072 COORD dest;
6073 CHAR_INFO fill;
6074 int nb;
6075
Bram Moolenaar6982f422019-02-16 16:48:01 +01006076 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077 dest.Y = g_coord.Y;
6078
Bram Moolenaar6982f422019-02-16 16:48:01 +01006079 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 source.Top = g_coord.Y + cLines;
6081 source.Right = g_srScrollRegion.Right;
6082 source.Bottom = g_srScrollRegion.Bottom;
6083
Bram Moolenaar6982f422019-02-16 16:48:01 +01006084 clip.Left = g_srScrollRegion.Left;
6085 clip.Top = g_coord.Y;
6086 clip.Right = g_srScrollRegion.Right;
6087 clip.Bottom = g_srScrollRegion.Bottom;
6088
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006089 {
6090 fill.Char.AsciiChar = ' ';
Bram Moolenaar21edde82019-02-17 14:10:56 +01006091 if (!USE_VTP)
6092 fill.Attributes = g_attrCurrent;
6093 else
6094 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006096 set_console_color_rgb();
6097
Bram Moolenaar6982f422019-02-16 16:48:01 +01006098 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006099 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006100 // Here we have to deal with a win32 console flake; See insert_lines()
6101 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102
6103 nb = dest.Y + (source.Bottom - source.Top) + 1;
6104
6105 if (nb < source.Top)
6106 {
6107 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01006108 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109
Bram Moolenaar6982f422019-02-16 16:48:01 +01006110 coord.X = source.Left;
6111 for (i = nb; i < clip.Bottom; ++i)
6112 {
6113 coord.Y = i;
6114 clear_chars(coord, source.Right - source.Left + 1);
6115 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 }
6117}
6118
6119
6120/*
6121 * Set the cursor position
6122 */
6123 static void
6124gotoxy(
6125 unsigned x,
6126 unsigned y)
6127{
6128 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6129 return;
6130
6131 /* external cursor coords are 1-based; internal are 0-based */
6132 g_coord.X = x - 1;
6133 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006134
6135 if (!USE_VTP)
6136 SetConsoleCursorPosition(g_hConOut, g_coord);
6137 else
6138 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139}
6140
6141
6142/*
6143 * Set the current text attribute = (foreground | background)
6144 * See ../doc/os_win32.txt for the numbers.
6145 */
6146 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006147textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006149 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150
6151 SetConsoleTextAttribute(g_hConOut, wAttr);
6152}
6153
6154
6155 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006156textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006158 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006160 if (!USE_VTP)
6161 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6162 else
6163 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164}
6165
6166
6167 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006168textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006170 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172 if (!USE_VTP)
6173 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6174 else
6175 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176}
6177
6178
6179/*
6180 * restore the default text attribute (whatever we started with)
6181 */
6182 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006183normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006185 if (!USE_VTP)
6186 textattr(g_attrDefault);
6187 else
6188 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189}
6190
6191
6192static WORD g_attrPreStandout = 0;
6193
6194/*
6195 * Make the text standout, by brightening it
6196 */
6197 static void
6198standout(void)
6199{
6200 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006201
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6203}
6204
6205
6206/*
6207 * Turn off standout mode
6208 */
6209 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006210standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211{
6212 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006214
6215 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216}
6217
6218
6219/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006220 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 */
6222 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006223mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224{
6225 char_u *p;
6226 int n;
6227
6228 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6229 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006230 if (
6231#ifdef FEAT_TERMGUICOLORS
6232 !p_tgc &&
6233#endif
6234 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 {
6236 p = T_ME + 2;
6237 n = getdigits(&p);
6238 if (*p == 'm' && n > 0)
6239 {
6240 cterm_normal_fg_color = (n & 0xf) + 1;
6241 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6242 }
6243 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006244#ifdef FEAT_TERMGUICOLORS
6245 cterm_normal_fg_gui_color = INVALCOLOR;
6246 cterm_normal_bg_gui_color = INVALCOLOR;
6247#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248}
6249
6250
6251/*
6252 * visual bell: flash the screen
6253 */
6254 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006255visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256{
6257 COORD coordOrigin = {0, 0};
6258 WORD attrFlash = ~g_attrCurrent & 0xff;
6259
6260 DWORD dwDummy;
6261 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6262
6263 if (oldattrs == NULL)
6264 return;
6265 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6266 coordOrigin, &dwDummy);
6267 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6268 coordOrigin, &dwDummy);
6269
6270 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006271 if (!USE_VTP)
6272 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 coordOrigin, &dwDummy);
6274 vim_free(oldattrs);
6275}
6276
6277
6278/*
6279 * Make the cursor visible or invisible
6280 */
6281 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006282cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283{
6284 s_cursor_visible = fVisible;
6285#ifdef MCH_CURSOR_SHAPE
6286 mch_update_cursor();
6287#endif
6288}
6289
6290
6291/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006292 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006293 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006295 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006297 char_u *pchBuf,
6298 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299{
6300 COORD coord = g_coord;
6301 DWORD written;
6302
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006303 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6304 {
6305 static WCHAR *unicodebuf = NULL;
6306 static int unibuflen = 0;
6307 int length;
6308 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006310 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6311 if (unicodebuf == NULL || length > unibuflen)
6312 {
6313 vim_free(unicodebuf);
6314 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6315 unibuflen = length;
6316 }
6317 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6318 unicodebuf, unibuflen);
6319
6320 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006321
6322 if (!USE_VTP)
6323 {
6324 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6325 coord, &written);
6326 /* When writing fails or didn't write a single character, pretend one
6327 * character was written, otherwise we get stuck. */
6328 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6329 coord, &cchwritten) == 0
6330 || cchwritten == 0)
6331 cchwritten = 1;
6332 }
6333 else
6334 {
6335 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6336 NULL) == 0 || cchwritten == 0)
6337 cchwritten = 1;
6338 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006339
6340 if (cchwritten == length)
6341 {
6342 written = cbToWrite;
6343 g_coord.X += (SHORT)cells;
6344 }
6345 else
6346 {
6347 char_u *p = pchBuf;
6348 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006349 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006350 written = p - pchBuf;
6351 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6352 }
6353 }
6354 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006355 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006356 if (!USE_VTP)
6357 {
6358 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6359 coord, &written);
6360 /* When writing fails or didn't write a single character, pretend one
6361 * character was written, otherwise we get stuck. */
6362 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6363 coord, &written) == 0
6364 || written == 0)
6365 written = 1;
6366 }
6367 else
6368 {
6369 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6370 NULL) == 0 || written == 0)
6371 written = 1;
6372 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006373
6374 g_coord.X += (SHORT) written;
6375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376
6377 while (g_coord.X > g_srScrollRegion.Right)
6378 {
6379 g_coord.X -= (SHORT) Columns;
6380 if (g_coord.Y < g_srScrollRegion.Bottom)
6381 g_coord.Y++;
6382 }
6383
6384 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6385
6386 return written;
6387}
6388
6389
6390/*
6391 * mch_write(): write the output buffer to the screen, translating ESC
6392 * sequences into calls to console output routines.
6393 */
6394 void
6395mch_write(
6396 char_u *s,
6397 int len)
6398{
6399 s[len] = NUL;
6400
6401 if (!term_console)
6402 {
6403 write(1, s, (unsigned)len);
6404 return;
6405 }
6406
6407 /* translate ESC | sequences into faked bios calls */
6408 while (len--)
6409 {
6410 /* optimization: use one single write_chars for runs of text,
6411 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006412 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413
6414 if (p_wd)
6415 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006416 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417 if (prefix != 0)
6418 prefix = 1;
6419 }
6420
6421 if (prefix != 0)
6422 {
6423 DWORD nWritten;
6424
6425 nWritten = write_chars(s, prefix);
6426#ifdef MCH_WRITE_DUMP
6427 if (fdDump)
6428 {
6429 fputc('>', fdDump);
6430 fwrite(s, sizeof(char_u), nWritten, fdDump);
6431 fputs("<\n", fdDump);
6432 }
6433#endif
6434 len -= (nWritten - 1);
6435 s += nWritten;
6436 }
6437 else if (s[0] == '\n')
6438 {
6439 /* \n, newline: go to the beginning of the next line or scroll */
6440 if (g_coord.Y == g_srScrollRegion.Bottom)
6441 {
6442 scroll(1);
6443 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6444 }
6445 else
6446 {
6447 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6448 }
6449#ifdef MCH_WRITE_DUMP
6450 if (fdDump)
6451 fputs("\\n\n", fdDump);
6452#endif
6453 s++;
6454 }
6455 else if (s[0] == '\r')
6456 {
6457 /* \r, carriage return: go to beginning of line */
6458 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6459#ifdef MCH_WRITE_DUMP
6460 if (fdDump)
6461 fputs("\\r\n", fdDump);
6462#endif
6463 s++;
6464 }
6465 else if (s[0] == '\b')
6466 {
6467 /* \b, backspace: move cursor one position left */
6468 if (g_coord.X > g_srScrollRegion.Left)
6469 g_coord.X--;
6470 else if (g_coord.Y > g_srScrollRegion.Top)
6471 {
6472 g_coord.X = g_srScrollRegion.Right;
6473 g_coord.Y--;
6474 }
6475 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6476#ifdef MCH_WRITE_DUMP
6477 if (fdDump)
6478 fputs("\\b\n", fdDump);
6479#endif
6480 s++;
6481 }
6482 else if (s[0] == '\a')
6483 {
6484 /* \a, bell */
6485 MessageBeep(0xFFFFFFFF);
6486#ifdef MCH_WRITE_DUMP
6487 if (fdDump)
6488 fputs("\\a\n", fdDump);
6489#endif
6490 s++;
6491 }
6492 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6493 {
6494#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006495 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006497 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006498 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499
6500 switch (s[2])
6501 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 case '0': case '1': case '2': case '3': case '4':
6503 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006504 p = s + 1;
6505 do
6506 {
6507 ++p;
6508 args[argc] = getdigits(&p);
6509 argc += (argc < 15) ? 1 : 0;
6510 if (p > s + len)
6511 break;
6512 } while (*p == ';');
6513
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514 if (p > s + len)
6515 break;
6516
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006517 arg1 = args[0];
6518 arg2 = args[1];
6519 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006521 if (argc == 1 && args[0] == 0)
6522 normvideo();
6523 else if (argc == 1)
6524 {
6525 if (USE_VTP)
6526 textcolor((WORD) arg1);
6527 else
6528 textattr((WORD) arg1);
6529 }
6530 else if (USE_VTP)
6531 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006533 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006535 gotoxy(arg2, arg1);
6536 }
6537 else if (argc == 2 && *p == 'r')
6538 {
6539 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6540 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006541 else if (argc == 2 && *p == 'R')
6542 {
6543 set_scroll_region_tb(arg1, arg2);
6544 }
6545 else if (argc == 2 && *p == 'V')
6546 {
6547 set_scroll_region_lr(arg1, arg2);
6548 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006549 else if (argc == 1 && *p == 'A')
6550 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 gotoxy(g_coord.X + 1,
6552 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6553 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006554 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 {
6556 textbackground((WORD) arg1);
6557 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006558 else if (argc == 1 && *p == 'C')
6559 {
6560 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6561 g_coord.Y + 1);
6562 }
6563 else if (argc == 1 && *p == 'f')
6564 {
6565 textcolor((WORD) arg1);
6566 }
6567 else if (argc == 1 && *p == 'H')
6568 {
6569 gotoxy(1, arg1);
6570 }
6571 else if (argc == 1 && *p == 'L')
6572 {
6573 insert_lines(arg1);
6574 }
6575 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 {
6577 delete_lines(arg1);
6578 }
6579
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006580 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 s = p + 1;
6582 break;
6583
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 gotoxy(g_coord.X + 1,
6586 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6587 goto got3;
6588
6589 case 'B':
6590 visual_bell();
6591 goto got3;
6592
6593 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6595 g_coord.Y + 1);
6596 goto got3;
6597
6598 case 'E':
6599 termcap_mode_end();
6600 goto got3;
6601
6602 case 'F':
6603 standout();
6604 goto got3;
6605
6606 case 'f':
6607 standend();
6608 goto got3;
6609
6610 case 'H':
6611 gotoxy(1, 1);
6612 goto got3;
6613
6614 case 'j':
6615 clear_to_end_of_display();
6616 goto got3;
6617
6618 case 'J':
6619 clear_screen();
6620 goto got3;
6621
6622 case 'K':
6623 clear_to_end_of_line();
6624 goto got3;
6625
6626 case 'L':
6627 insert_lines(1);
6628 goto got3;
6629
6630 case 'M':
6631 delete_lines(1);
6632 goto got3;
6633
6634 case 'S':
6635 termcap_mode_start();
6636 goto got3;
6637
6638 case 'V':
6639 cursor_visible(TRUE);
6640 goto got3;
6641
6642 case 'v':
6643 cursor_visible(FALSE);
6644 goto got3;
6645
6646 got3:
6647 s += 3;
6648 len -= 2;
6649 }
6650
6651#ifdef MCH_WRITE_DUMP
6652 if (fdDump)
6653 {
6654 fputs("ESC | ", fdDump);
6655 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6656 fputc('\n', fdDump);
6657 }
6658#endif
6659 }
6660 else
6661 {
6662 /* Write a single character */
6663 DWORD nWritten;
6664
6665 nWritten = write_chars(s, 1);
6666#ifdef MCH_WRITE_DUMP
6667 if (fdDump)
6668 {
6669 fputc('>', fdDump);
6670 fwrite(s, sizeof(char_u), nWritten, fdDump);
6671 fputs("<\n", fdDump);
6672 }
6673#endif
6674
6675 len -= (nWritten - 1);
6676 s += nWritten;
6677 }
6678 }
6679
6680#ifdef MCH_WRITE_DUMP
6681 if (fdDump)
6682 fflush(fdDump);
6683#endif
6684}
6685
6686#endif /* FEAT_GUI_W32 */
6687
6688
6689/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006690 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 */
6692 void
6693mch_delay(
6694 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006695 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696{
6697#ifdef FEAT_GUI_W32
6698 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006699#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006701# ifdef FEAT_MZSCHEME
6702 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6703 {
6704 int towait = p_mzq;
6705
6706 /* if msec is large enough, wait by portions in p_mzq */
6707 while (msec > 0)
6708 {
6709 mzvim_check_threads();
6710 if (msec < towait)
6711 towait = msec;
6712 Sleep(towait);
6713 msec -= towait;
6714 }
6715 }
6716 else
6717# endif
6718 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006720 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721#endif
6722}
6723
6724
6725/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006726 * This version of remove is not scared by a readonly (backup) file.
6727 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 * Return 0 for success, -1 for failure.
6729 */
6730 int
6731mch_remove(char_u *name)
6732{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 WCHAR *wn = NULL;
6734 int n;
6735
Bram Moolenaar203258c2016-01-17 22:15:16 +01006736 /*
6737 * On Windows, deleting a directory's symbolic link is done by
6738 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6739 */
6740 if (mch_isdir(name) && mch_is_symbolic_link(name))
6741 return mch_rmdir(name);
6742
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006743 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6744
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6746 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006747 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 if (wn != NULL)
6749 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 n = DeleteFileW(wn) ? 0 : -1;
6751 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006752 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 }
6754 }
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006755 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756}
6757
6758
6759/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006760 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 */
6762 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006763mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764{
6765#ifndef FEAT_GUI_W32 /* never used */
6766 if (g_fCtrlCPressed || g_fCBrkPressed)
6767 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006768 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6770 got_int = TRUE;
6771 }
6772#endif
6773}
6774
Bram Moolenaaree273972016-01-02 21:11:51 +01006775/* physical RAM to leave for the OS */
6776#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006777
6778/*
6779 * How much main memory in KiB that can be used by VIM.
6780 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006781 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006782mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006783{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006784 MEMORYSTATUSEX ms;
6785
Bram Moolenaaree273972016-01-02 21:11:51 +01006786 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006787 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6788 * what fits in 32 bits. But it's not always available. */
6789 ms.dwLength = sizeof(MEMORYSTATUSEX);
6790 GlobalMemoryStatusEx(&ms);
6791 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006792 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006793 /* Process address space fits in physical RAM, use all of it. */
6794 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006795 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006796 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006797 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006798 /* Catch old NT box or perverse hardware setup. */
6799 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006800 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006801 /* Use physical RAM less reserve for OS + data. */
6802 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006803}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805/*
6806 * Same code as below, but with wide functions and no comments.
6807 * Return 0 for success, non-zero for failure.
6808 */
6809 int
6810mch_wrename(WCHAR *wold, WCHAR *wnew)
6811{
6812 WCHAR *p;
6813 int i;
6814 WCHAR szTempFile[_MAX_PATH + 1];
6815 WCHAR szNewPath[_MAX_PATH + 1];
6816 HANDLE hf;
6817
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006818 p = wold;
6819 for (i = 0; wold[i] != NUL; ++i)
6820 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6821 && wold[i + 1] != 0)
6822 p = wold + i + 1;
6823 if ((int)(wold + i - p) < 8 || p[6] != '~')
6824 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825
6826 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6827 return -1;
6828 *p = NUL;
6829
6830 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6831 return -2;
6832
6833 if (!DeleteFileW(szTempFile))
6834 return -3;
6835
6836 if (!MoveFileW(wold, szTempFile))
6837 return -4;
6838
6839 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6840 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6841 return -5;
6842 if (!CloseHandle(hf))
6843 return -6;
6844
6845 if (!MoveFileW(szTempFile, wnew))
6846 {
6847 (void)MoveFileW(szTempFile, wold);
6848 return -7;
6849 }
6850
6851 DeleteFileW(szTempFile);
6852
6853 if (!DeleteFileW(wold))
6854 return -8;
6855
6856 return 0;
6857}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858
6859
6860/*
6861 * mch_rename() works around a bug in rename (aka MoveFile) in
6862 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6863 * file whose short file name is "FOO.BAR" (its long file name will
6864 * be correct: "foo.bar~"). Because a file can be accessed by
6865 * either its SFN or its LFN, "foo.bar" has effectively been
6866 * renamed to "foo.bar", which is not at all what was wanted. This
6867 * seems to happen only when renaming files with three-character
6868 * extensions by appending a suffix that does not include ".".
6869 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6870 *
6871 * There is another problem, which isn't really a bug but isn't right either:
6872 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6873 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6874 * service pack 6. Doesn't seem to happen on Windows 98.
6875 *
6876 * Like rename(), returns 0 upon success, non-zero upon failure.
6877 * Should probably set errno appropriately when errors occur.
6878 */
6879 int
6880mch_rename(
6881 const char *pszOldFile,
6882 const char *pszNewFile)
6883{
6884 char szTempFile[_MAX_PATH+1];
6885 char szNewPath[_MAX_PATH+1];
6886 char *pszFilePart;
6887 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 WCHAR *wold = NULL;
6889 WCHAR *wnew = NULL;
6890 int retval = -1;
6891
6892 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6893 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006894 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6895 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 if (wold != NULL && wnew != NULL)
6897 retval = mch_wrename(wold, wnew);
6898 vim_free(wold);
6899 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006900 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902
6903 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006904 * No need to play tricks unless the file name contains a "~" as the
6905 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006907 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6908 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6909 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910
6911 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6912 * a directory, no error is returned and pszFilePart will be NULL. */
6913 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6914 || pszFilePart == NULL)
6915 return -1;
6916 *pszFilePart = NUL;
6917
6918 /* Get (and create) a unique temporary file name in directory of new file */
6919 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6920 return -2;
6921
6922 /* blow the temp file away */
6923 if (!DeleteFile(szTempFile))
6924 return -3;
6925
6926 /* rename old file to the temp file */
6927 if (!MoveFile(pszOldFile, szTempFile))
6928 return -4;
6929
6930 /* now create an empty file called pszOldFile; this prevents the operating
6931 * system using pszOldFile as an alias (SFN) if we're renaming within the
6932 * same directory. For example, we're editing a file called
6933 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6934 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6935 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006936 * cause all sorts of problems later in buf_write(). So, we create an
6937 * empty file called filena~1.txt and the system will have to find some
6938 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 */
6940 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6941 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6942 return -5;
6943 if (!CloseHandle(hf))
6944 return -6;
6945
6946 /* rename the temp file to the new file */
6947 if (!MoveFile(szTempFile, pszNewFile))
6948 {
6949 /* Renaming failed. Rename the file back to its old name, so that it
6950 * looks like nothing happened. */
6951 (void)MoveFile(szTempFile, pszOldFile);
6952
6953 return -7;
6954 }
6955
6956 /* Seems to be left around on Novell filesystems */
6957 DeleteFile(szTempFile);
6958
6959 /* finally, remove the empty old file */
6960 if (!DeleteFile(pszOldFile))
6961 return -8;
6962
6963 return 0; /* success */
6964}
6965
6966/*
6967 * Get the default shell for the current hardware platform
6968 */
6969 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006970default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 PlatformId();
6973
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006974 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975}
6976
6977/*
6978 * mch_access() extends access() to do more detailed check on network drives.
6979 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6980 */
6981 int
6982mch_access(char *n, int p)
6983{
6984 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 int retval = -1; /* default: fail */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 WCHAR *wn = NULL;
6987
6988 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006989 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006991 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 {
6993 char TempName[_MAX_PATH + 16] = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995
6996 if (p & R_OK)
6997 {
6998 /* Read check is performed by seeing if we can do a find file on
6999 * the directory for any file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 if (wn != NULL)
7001 {
7002 int i;
7003 WIN32_FIND_DATAW d;
7004
7005 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7006 TempNameW[i] = wn[i];
7007 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7008 TempNameW[i++] = '\\';
7009 TempNameW[i++] = '*';
7010 TempNameW[i++] = 0;
7011
7012 hFile = FindFirstFileW(TempNameW, &d);
7013 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007014 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 else
7016 (void)FindClose(hFile);
7017 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007018 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 {
7020 char *pch;
7021 WIN32_FIND_DATA d;
7022
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007023 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 pch = TempName + STRLEN(TempName) - 1;
7025 if (*pch != '\\' && *pch != '/')
7026 *++pch = '\\';
7027 *++pch = '*';
7028 *++pch = NUL;
7029
7030 hFile = FindFirstFile(TempName, &d);
7031 if (hFile == INVALID_HANDLE_VALUE)
7032 goto getout;
7033 (void)FindClose(hFile);
7034 }
7035 }
7036
7037 if (p & W_OK)
7038 {
7039 /* Trying to create a temporary file in the directory should catch
7040 * directories on read-only network shares. However, in
7041 * directories whose ACL allows writes but denies deletes will end
7042 * up keeping the temporary file :-(. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 if (wn != NULL)
7044 {
7045 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007046 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047 else
7048 DeleteFileW(TempNameW);
7049 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007050 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 {
7052 if (!GetTempFileName(n, "VIM", 0, TempName))
7053 goto getout;
7054 mch_remove((char_u *)TempName);
7055 }
7056 }
7057 }
7058 else
7059 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007060 // Don't consider a file read-only if another process has opened it.
7061 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7062
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063 /* Trying to open the file for the required access does ACL, read-only
7064 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007065 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7066 | ((p & R_OK) ? GENERIC_READ : 0);
7067
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007069 hFile = CreateFileW(wn, access_mode, share_mode,
7070 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007071 else
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007072 hFile = CreateFile(n, access_mode, share_mode,
7073 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 if (hFile == INVALID_HANDLE_VALUE)
7075 goto getout;
7076 CloseHandle(hFile);
7077 }
7078
7079 retval = 0; /* success */
7080getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 return retval;
7083}
7084
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007086 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 */
7088 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007089mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007091 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
Bram Moolenaara12a1612019-01-24 16:39:02 +01007092#ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 WCHAR *wn;
7094 int f;
7095
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007096 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007098 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007099 if (wn != NULL)
7100 {
7101 f = _wopen(wn, flags, mode);
7102 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007103 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 }
7105 }
Bram Moolenaara12a1612019-01-24 16:39:02 +01007106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007108 /* open() can open a file which name is longer than _MAX_PATH bytes
7109 * and shorter than _MAX_PATH characters successfully, but sometimes it
7110 * causes unexpected error in another part. We make it an error explicitly
7111 * here. */
7112 if (strlen(name) >= _MAX_PATH)
7113 return -1;
7114
Bram Moolenaar071d4272004-06-13 20:20:40 +00007115 return open(name, flags, mode);
7116}
7117
7118/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007119 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 */
7121 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007122mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123{
7124 WCHAR *wn, *wm;
7125 FILE *f = NULL;
7126
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007127 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 {
Bram Moolenaara12a1612019-01-24 16:39:02 +01007129#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007130 /* Work around an annoying assertion in the Microsoft debug CRT
7131 * when mode's text/binary setting doesn't match _get_fmode(). */
7132 char newMode = mode[strlen(mode) - 1];
7133 int oldMode = 0;
7134
7135 _get_fmode(&oldMode);
7136 if (newMode == 't')
7137 _set_fmode(_O_TEXT);
7138 else if (newMode == 'b')
7139 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007140#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007141 wn = enc_to_utf16((char_u *)name, NULL);
7142 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143 if (wn != NULL && wm != NULL)
7144 f = _wfopen(wn, wm);
7145 vim_free(wn);
7146 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007147
Bram Moolenaara12a1612019-01-24 16:39:02 +01007148#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007149 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007150#endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007151 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 }
7153
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007154 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7155 * and shorter than _MAX_PATH characters successfully, but sometimes it
7156 * causes unexpected error in another part. We make it an error explicitly
7157 * here. */
7158 if (strlen(name) >= _MAX_PATH)
7159 return NULL;
7160
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161 return fopen(name, mode);
7162}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164/*
7165 * SUB STREAM (aka info stream) handling:
7166 *
7167 * NTFS can have sub streams for each file. Normal contents of file is
7168 * stored in the main stream, and extra contents (author information and
7169 * title and so on) can be stored in sub stream. After Windows 2000, user
7170 * can access and store those informations in sub streams via explorer's
7171 * property menuitem in right click menu. Those informations in sub streams
7172 * were lost when copying only the main stream. So we have to copy sub
7173 * streams.
7174 *
7175 * Incomplete explanation:
7176 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7177 * More useful info and an example:
7178 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7179 */
7180
7181/*
7182 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7183 * and write to stream "substream" of file "to".
7184 * Errors are ignored.
7185 */
7186 static void
7187copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7188{
7189 HANDLE hTo;
7190 WCHAR *to_name;
7191
7192 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7193 wcscpy(to_name, to);
7194 wcscat(to_name, substream);
7195
7196 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7197 FILE_ATTRIBUTE_NORMAL, NULL);
7198 if (hTo != INVALID_HANDLE_VALUE)
7199 {
7200 long done;
7201 DWORD todo;
7202 DWORD readcnt, written;
7203 char buf[4096];
7204
7205 /* Copy block of bytes at a time. Abort when something goes wrong. */
7206 for (done = 0; done < len; done += written)
7207 {
7208 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007209 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7210 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7212 FALSE, FALSE, context)
7213 || readcnt != todo
7214 || !WriteFile(hTo, buf, todo, &written, NULL)
7215 || written != todo)
7216 break;
7217 }
7218 CloseHandle(hTo);
7219 }
7220
7221 free(to_name);
7222}
7223
7224/*
7225 * Copy info streams from file "from" to file "to".
7226 */
7227 static void
7228copy_infostreams(char_u *from, char_u *to)
7229{
7230 WCHAR *fromw;
7231 WCHAR *tow;
7232 HANDLE sh;
7233 WIN32_STREAM_ID sid;
7234 int headersize;
7235 WCHAR streamname[_MAX_PATH];
7236 DWORD readcount;
7237 void *context = NULL;
7238 DWORD lo, hi;
7239 int len;
7240
7241 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007242 fromw = enc_to_utf16(from, NULL);
7243 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 if (fromw != NULL && tow != NULL)
7245 {
7246 /* Open the file for reading. */
7247 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7248 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7249 if (sh != INVALID_HANDLE_VALUE)
7250 {
7251 /* Use BackupRead() to find the info streams. Repeat until we
7252 * have done them all.*/
7253 for (;;)
7254 {
7255 /* Get the header to find the length of the stream name. If
7256 * the "readcount" is zero we have done all info streams. */
7257 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007258 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7260 &readcount, FALSE, FALSE, &context)
7261 || readcount == 0)
7262 break;
7263
7264 /* We only deal with streams that have a name. The normal
7265 * file data appears to be without a name, even though docs
7266 * suggest it is called "::$DATA". */
7267 if (sid.dwStreamNameSize > 0)
7268 {
7269 /* Read the stream name. */
7270 if (!BackupRead(sh, (LPBYTE)streamname,
7271 sid.dwStreamNameSize,
7272 &readcount, FALSE, FALSE, &context))
7273 break;
7274
7275 /* Copy an info stream with a name ":anything:$DATA".
7276 * Skip "::$DATA", it has no stream name (examples suggest
7277 * it might be used for the normal file contents).
7278 * Note that BackupRead() counts bytes, but the name is in
7279 * wide characters. */
7280 len = readcount / sizeof(WCHAR);
7281 streamname[len] = 0;
7282 if (len > 7 && wcsicmp(streamname + len - 6,
7283 L":$DATA") == 0)
7284 {
7285 streamname[len - 6] = 0;
7286 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007287 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288 }
7289 }
7290
7291 /* Advance to the next stream. We might try seeking too far,
7292 * but BackupSeek() doesn't skip over stream borders, thus
7293 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007294 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 &lo, &hi, &context);
7296 }
7297
7298 /* Clear the context. */
7299 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7300
7301 CloseHandle(sh);
7302 }
7303 }
7304 vim_free(fromw);
7305 vim_free(tow);
7306}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307
7308/*
7309 * Copy file attributes from file "from" to file "to".
7310 * For Windows NT and later we copy info streams.
7311 * Always returns zero, errors are ignored.
7312 */
7313 int
7314mch_copy_file_attribute(char_u *from, char_u *to)
7315{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 /* File streams only work on Windows NT and later. */
7317 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007318 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007319 return 0;
7320}
7321
7322#if defined(MYRESETSTKOFLW) || defined(PROTO)
7323/*
7324 * Recreate a destroyed stack guard page in win32.
7325 * Written by Benjamin Peterson.
7326 */
7327
7328/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007329# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330
7331/*
7332 * This function does the same thing as _resetstkoflw(), which is only
7333 * available in DevStudio .net and later.
7334 * Returns 0 for failure, 1 for success.
7335 */
7336 int
7337myresetstkoflw(void)
7338{
7339 BYTE *pStackPtr;
7340 BYTE *pGuardPage;
7341 BYTE *pStackBase;
7342 BYTE *pLowestPossiblePage;
7343 MEMORY_BASIC_INFORMATION mbi;
7344 SYSTEM_INFO si;
7345 DWORD nPageSize;
7346 DWORD dummy;
7347
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349
7350 /* We need to know the system page size. */
7351 GetSystemInfo(&si);
7352 nPageSize = si.dwPageSize;
7353
7354 /* ...and the current stack pointer */
7355 pStackPtr = (BYTE*)_alloca(1);
7356
7357 /* ...and the base of the stack. */
7358 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7359 return 0;
7360 pStackBase = (BYTE*)mbi.AllocationBase;
7361
7362 /* ...and the page thats min_stack_req pages away from stack base; this is
7363 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007364 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007367 /* We want the first committed page in the stack Start at the stack
7368 * base and move forward through memory until we find a committed block.
7369 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370 BYTE *pBlock = pStackBase;
7371
Bram Moolenaara466c992005-07-09 21:03:22 +00007372 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 {
7374 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7375 return 0;
7376
7377 pBlock += mbi.RegionSize;
7378
7379 if (mbi.State & MEM_COMMIT)
7380 break;
7381 }
7382
7383 /* mbi now describes the first committed block in the stack. */
7384 if (mbi.Protect & PAGE_GUARD)
7385 return 1;
7386
7387 /* decide where the guard page should start */
7388 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7389 pGuardPage = pLowestPossiblePage;
7390 else
7391 pGuardPage = (BYTE*)mbi.BaseAddress;
7392
7393 /* allocate the guard page */
7394 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7395 return 0;
7396
7397 /* apply the guard attribute to the page */
7398 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7399 &dummy))
7400 return 0;
7401 }
7402
7403 return 1;
7404}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007405#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007407
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007408/*
7409 * The command line arguments in UCS2
7410 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007411static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007412static LPWSTR *ArglistW = NULL;
7413static int global_argc = 0;
7414static char **global_argv;
7415
7416static int used_file_argc = 0; /* last argument in global_argv[] used
7417 for the argument list. */
7418static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7419 command line arguments added to
7420 the argument list */
7421static int used_file_count = 0; /* nr of entries in used_file_indexes */
7422static int used_file_literal = FALSE; /* take file names literally */
7423static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007424static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007425static int used_alist_count = 0;
7426
7427
7428/*
7429 * Get the command line arguments. Unicode version.
7430 * Returns argc. Zero when something fails.
7431 */
7432 int
7433get_cmd_argsW(char ***argvp)
7434{
7435 char **argv = NULL;
7436 int argc = 0;
7437 int i;
7438
Bram Moolenaar14993322014-09-09 12:25:33 +02007439 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007440 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7441 if (ArglistW != NULL)
7442 {
7443 argv = malloc((nArgsW + 1) * sizeof(char *));
7444 if (argv != NULL)
7445 {
7446 argc = nArgsW;
7447 argv[argc] = NULL;
7448 for (i = 0; i < argc; ++i)
7449 {
7450 int len;
7451
7452 /* Convert each Unicode argument to the current codepage. */
7453 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007454 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007455 (LPSTR *)&argv[i], &len, 0, 0);
7456 if (argv[i] == NULL)
7457 {
7458 /* Out of memory, clear everything. */
7459 while (i > 0)
7460 free(argv[--i]);
7461 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007462 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007463 argc = 0;
7464 }
7465 }
7466 }
7467 }
7468
7469 global_argc = argc;
7470 global_argv = argv;
7471 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007472 {
7473 if (used_file_indexes != NULL)
7474 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007475 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007476 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007477
7478 if (argvp != NULL)
7479 *argvp = argv;
7480 return argc;
7481}
7482
7483 void
7484free_cmd_argsW(void)
7485{
7486 if (ArglistW != NULL)
7487 {
7488 GlobalFree(ArglistW);
7489 ArglistW = NULL;
7490 }
7491}
7492
7493/*
7494 * Remember "name" is an argument that was added to the argument list.
7495 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7496 * is called.
7497 */
7498 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007499used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007500{
7501 int i;
7502
7503 if (used_file_indexes == NULL)
7504 return;
7505 for (i = used_file_argc + 1; i < global_argc; ++i)
7506 if (STRCMP(global_argv[i], name) == 0)
7507 {
7508 used_file_argc = i;
7509 used_file_indexes[used_file_count++] = i;
7510 break;
7511 }
7512 used_file_literal = literal;
7513 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007514 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007515}
7516
7517/*
7518 * Remember the length of the argument list as it was. If it changes then we
7519 * leave it alone when 'encoding' is set.
7520 */
7521 void
7522set_alist_count(void)
7523{
7524 used_alist_count = GARGCOUNT;
7525}
7526
7527/*
7528 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7529 * has been changed while starting up. Use the UCS-2 command line arguments
7530 * and convert them to 'encoding'.
7531 */
7532 void
7533fix_arg_enc(void)
7534{
7535 int i;
7536 int idx;
7537 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007538 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539
7540 /* Safety checks:
7541 * - if argument count differs between the wide and non-wide argument
7542 * list, something must be wrong.
7543 * - the file name arguments must have been located.
7544 * - the length of the argument list wasn't changed by the user.
7545 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007546 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007547 || ArglistW == NULL
7548 || used_file_indexes == NULL
7549 || used_file_count == 0
7550 || used_alist_count != GARGCOUNT)
7551 return;
7552
Bram Moolenaar86b68352004-12-27 21:59:20 +00007553 /* Remember the buffer numbers for the arguments. */
7554 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7555 if (fnum_list == NULL)
7556 return; /* out of memory */
7557 for (i = 0; i < GARGCOUNT; ++i)
7558 fnum_list[i] = GARGLIST[i].ae_fnum;
7559
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007560 /* Clear the argument list. Make room for the new arguments. */
7561 alist_clear(&global_alist);
7562 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007563 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007564
7565 for (i = 0; i < used_file_count; ++i)
7566 {
7567 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007568 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007569 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007570 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007571 int literal = used_file_literal;
7572
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007573# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007574 /* When using diff mode may need to concatenate file name to
7575 * directory name. Just like it's done in main(). */
7576 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7577 && !mch_isdir(alist_name(&GARGLIST[0])))
7578 {
7579 char_u *r;
7580
7581 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7582 if (r != NULL)
7583 {
7584 vim_free(str);
7585 str = r;
7586 }
7587 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007588# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007589 /* Re-use the old buffer by renaming it. When not using literal
7590 * names it's done by alist_expand() below. */
7591 if (used_file_literal)
7592 buf_set_name(fnum_list[i], str);
7593
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007594 /* Check backtick literal. backtick literal is already expanded in
7595 * main.c, so this part add str as literal. */
7596 if (literal == FALSE)
7597 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007598 size_t len = STRLEN(str);
7599
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007600 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7601 literal = TRUE;
7602 }
7603 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007604 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007605 }
7606
7607 if (!used_file_literal)
7608 {
7609 /* Now expand wildcards in the arguments. */
7610 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7611 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007612 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7613 * Also, unset wildignore to not be influenced by this option.
7614 * The arguments specified in command-line should be kept even if
7615 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007616 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007617 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007618 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007619 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007620 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007621 }
7622
7623 /* If wildcard expansion failed, we are editing the first file of the
7624 * arglist and there is no file name: Edit the first argument now. */
7625 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7626 {
7627 do_cmdline_cmd((char_u *)":rewind");
7628 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007629 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007630 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007631
7632 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007633}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007634
7635 int
7636mch_setenv(char *var, char *value, int x)
7637{
7638 char_u *envbuf;
7639
7640 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7641 if (envbuf == NULL)
7642 return -1;
7643
7644 sprintf((char *)envbuf, "%s=%s", var, value);
7645
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007646 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7647 {
7648 WCHAR *p = enc_to_utf16(envbuf, NULL);
7649
7650 vim_free(envbuf);
7651 if (p == NULL)
7652 return -1;
7653 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007654#ifdef libintl_wputenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007655 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007656#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007657 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7658 vim_free(p);
7659 }
7660 else
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007661 {
7662 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007663#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007664 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007665#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007666 /* Unlike Un*x systems, we can free the string for _putenv(). */
7667 vim_free(envbuf);
7668 }
7669
7670 return 0;
7671}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007672
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007673/*
7674 * Support for 256 colors and 24-bit colors was added in Windows 10
7675 * version 1703 (Creators update).
7676 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007677#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7678
7679/*
7680 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007681 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007682 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007683#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7684#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007685
7686 static void
7687vtp_flag_init(void)
7688{
7689 DWORD ver = get_build_number();
7690#ifndef FEAT_GUI_W32
7691 DWORD mode;
7692 HANDLE out;
7693
7694 out = GetStdHandle(STD_OUTPUT_HANDLE);
7695
7696 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7697 GetConsoleMode(out, &mode);
7698 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7699 if (SetConsoleMode(out, mode) == 0)
7700 vtp_working = 0;
7701#endif
7702
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007703 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007704 conpty_working = 1;
7705 if (ver >= CONPTY_STABLE_BUILD)
7706 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007707
7708}
7709
7710#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007711
7712 static void
7713vtp_init(void)
7714{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007715 HMODULE hKerneldll;
7716 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007717# ifdef FEAT_TERMGUICOLORS
7718 COLORREF fg, bg;
7719# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007720
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007721 /* Use functions supported from Vista */
7722 hKerneldll = GetModuleHandle("kernel32.dll");
7723 if (hKerneldll != NULL)
7724 {
7725 pGetConsoleScreenBufferInfoEx =
7726 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7727 hKerneldll, "GetConsoleScreenBufferInfoEx");
7728 pSetConsoleScreenBufferInfoEx =
7729 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7730 hKerneldll, "SetConsoleScreenBufferInfoEx");
7731 if (pGetConsoleScreenBufferInfoEx != NULL
7732 && pSetConsoleScreenBufferInfoEx != NULL)
7733 has_csbiex = TRUE;
7734 }
7735
7736 csbi.cbSize = sizeof(csbi);
7737 if (has_csbiex)
7738 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007739 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7740 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7741
7742# ifdef FEAT_TERMGUICOLORS
7743 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7744 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7745 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7746 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7747 default_console_color_bg = bg;
7748 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007749# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007750
7751 set_console_color_rgb();
7752}
7753
7754 static void
7755vtp_exit(void)
7756{
7757 reset_console_color_rgb();
7758}
7759
7760 static int
7761vtp_printf(
7762 char *format,
7763 ...)
7764{
7765 char_u buf[100];
7766 va_list list;
7767 DWORD result;
7768
7769 va_start(list, format);
7770 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7771 va_end(list);
7772 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7773 return (int)result;
7774}
7775
7776 static void
7777vtp_sgr_bulk(
7778 int arg)
7779{
7780 int args[1];
7781
7782 args[0] = arg;
7783 vtp_sgr_bulks(1, args);
7784}
7785
7786 static void
7787vtp_sgr_bulks(
7788 int argc,
7789 int *args
7790)
7791{
7792 /* 2('\033[') + 4('255.') * 16 + NUL */
7793 char_u buf[2 + (4 * 16) + 1];
7794 char_u *p;
7795 int i;
7796
7797 p = buf;
7798 *p++ = '\033';
7799 *p++ = '[';
7800
7801 for (i = 0; i < argc; ++i)
7802 {
7803 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7804 *p++ = ';';
7805 }
7806 p--;
7807 *p++ = 'm';
7808 *p = NUL;
7809 vtp_printf((char *)buf);
7810}
7811
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007812# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007813 static int
7814ctermtoxterm(
7815 int cterm)
7816{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007817 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007818
7819 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7820 return (((int)r << 16) | ((int)g << 8) | (int)b);
7821}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007822# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007823
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007824 static void
7825set_console_color_rgb(void)
7826{
7827# ifdef FEAT_TERMGUICOLORS
7828 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7829 int id;
7830 guicolor_T fg = INVALCOLOR;
7831 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007832 int ctermfg;
7833 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007834
7835 if (!USE_VTP)
7836 return;
7837
7838 id = syn_name2id((char_u *)"Normal");
7839 if (id > 0)
7840 syn_id2colors(id, &fg, &bg);
7841 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007842 {
7843 ctermfg = -1;
7844 if (id > 0)
7845 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007846 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7847 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007848 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007849 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007850 {
7851 ctermbg = -1;
7852 if (id > 0)
7853 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007854 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7855 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007856 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007857 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7858 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7859
7860 csbi.cbSize = sizeof(csbi);
7861 if (has_csbiex)
7862 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7863
7864 csbi.cbSize = sizeof(csbi);
7865 csbi.srWindow.Right += 1;
7866 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007867 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7868 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007869 if (has_csbiex)
7870 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7871# endif
7872}
7873
7874 static void
7875reset_console_color_rgb(void)
7876{
7877# ifdef FEAT_TERMGUICOLORS
7878 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7879
7880 csbi.cbSize = sizeof(csbi);
7881 if (has_csbiex)
7882 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7883
7884 csbi.cbSize = sizeof(csbi);
7885 csbi.srWindow.Right += 1;
7886 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007887 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7888 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007889 if (has_csbiex)
7890 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7891# endif
7892}
7893
7894 void
7895control_console_color_rgb(void)
7896{
7897 if (USE_VTP)
7898 set_console_color_rgb();
7899 else
7900 reset_console_color_rgb();
7901}
7902
7903 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007904use_vtp(void)
7905{
7906 return USE_VTP;
7907}
7908
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007909 int
7910is_term_win32(void)
7911{
7912 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7913}
7914
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007915 int
7916has_vtp_working(void)
7917{
7918 return vtp_working;
7919}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007920
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007921#endif
7922
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007923 int
7924has_conpty_working(void)
7925{
7926 return conpty_working;
7927}
7928
7929 int
7930is_conpty_stable(void)
7931{
7932 return conpty_stable;
7933}