blob: 4ba060bb909b7ebcbcb3df95fe3f1b28a8a091b2 [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 Moolenaar071d4272004-06-13 20:20:40 +0000174static void delete_lines(unsigned cLines);
175static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static int s_cursor_visible = TRUE;
178static int did_create_conin = FALSE;
179#else
180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100190static int vtp_working = 0;
191static void vtp_init();
192static void vtp_exit();
193static int vtp_printf(char *format, ...);
194static void vtp_sgr_bulk(int arg);
195static void vtp_sgr_bulks(int argc, int *argv);
196
197static guicolor_T save_console_bg_rgb;
198static guicolor_T save_console_fg_rgb;
199
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int g_color_index_bg = 0;
201static int g_color_index_fg = 7;
202
203# ifdef FEAT_TERMGUICOLORS
204static int default_console_color_bg = 0x000000; // black
205static int default_console_color_fg = 0xc0c0c0; // white
206# endif
207
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100208# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200209# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100210# else
211# define USE_VTP 0
212# endif
213
214static void set_console_color_rgb(void);
215static void reset_console_color_rgb(void);
216#endif
217
218/* This flag is newly created from Windows 10 */
219#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
220# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
221#endif
222
223#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static int suppress_winsize = 1; /* don't fiddle with console */
225#endif
226
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227static char_u *exe_path = NULL;
228
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229static BOOL win8_or_later = FALSE;
230
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100231#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232/* Dynamic loading for portability */
233typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
234{
235 ULONG cbSize;
236 COORD dwSize;
237 COORD dwCursorPosition;
238 WORD wAttributes;
239 SMALL_RECT srWindow;
240 COORD dwMaximumWindowSize;
241 WORD wPopupAttributes;
242 BOOL bFullscreenSupported;
243 COLORREF ColorTable[16];
244} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
245typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
246static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
247typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
248static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
249static BOOL has_csbiex = FALSE;
250
251/*
252 * Get version number including build number
253 */
254typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
255# define MAKE_VER(major, minor, build) \
256 (((major) << 24) | ((minor) << 16) | (build))
257
258 static DWORD
259get_build_number(void)
260{
261 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
262 HMODULE hNtdll;
263 PfnRtlGetVersion pRtlGetVersion;
264 DWORD ver = MAKE_VER(0, 0, 0);
265
266 hNtdll = GetModuleHandle("ntdll.dll");
267 if (hNtdll != NULL)
268 {
269 pRtlGetVersion =
270 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
271 pRtlGetVersion(&osver);
272 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
273 min(osver.dwMinorVersion, 255),
274 min(osver.dwBuildNumber, 32767));
275 }
276 return ver;
277}
278
279
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280/*
281 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100283 */
284 static BOOL
285read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 HANDLE hInput,
287 INPUT_RECORD *lpBuffer,
288 DWORD nLength,
289 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100290{
291 enum
292 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100293 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296 static DWORD s_dwIndex = 0;
297 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100299 int head;
300 int tail;
301 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 if (nLength == -2)
304 return (s_dwMax > 0) ? TRUE : FALSE;
305
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100306 if (!win8_or_later)
307 {
308 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200309 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
310 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 }
312
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 if (s_dwMax == 0)
314 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200316 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
317 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 s_dwIndex = 0;
320 s_dwMax = dwEvents;
321 if (dwEvents == 0)
322 {
323 *lpEvents = 0;
324 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100326
327 if (s_dwMax > 1)
328 {
329 head = 0;
330 tail = s_dwMax - 1;
331 while (head != tail)
332 {
333 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
334 && s_irCache[head + 1].EventType
335 == WINDOW_BUFFER_SIZE_EVENT)
336 {
337 /* Remove duplicate event to avoid flicker. */
338 for (i = head; i < tail; ++i)
339 s_irCache[i] = s_irCache[i + 1];
340 --tail;
341 continue;
342 }
343 head++;
344 }
345 s_dwMax = tail + 1;
346 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100348
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100349 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100352 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 return TRUE;
354}
355
356/*
357 * Version of PeekConsoleInput() that works with IME.
358 */
359 static BOOL
360peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 HANDLE hInput,
362 INPUT_RECORD *lpBuffer,
363 DWORD nLength,
364 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100365{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367}
368
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100369# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200370 static DWORD
371msg_wait_for_multiple_objects(
372 DWORD nCount,
373 LPHANDLE pHandles,
374 BOOL fWaitAll,
375 DWORD dwMilliseconds,
376 DWORD dwWakeMask)
377{
378 if (read_console_input(NULL, NULL, -2, NULL))
379 return WAIT_OBJECT_0;
380 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
381 dwMilliseconds, dwWakeMask);
382}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100383# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387wait_for_single_object(
388 HANDLE hHandle,
389 DWORD dwMilliseconds)
390{
391 if (read_console_input(NULL, NULL, -2, NULL))
392 return WAIT_OBJECT_0;
393 return WaitForSingleObject(hHandle, dwMilliseconds);
394}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100395# endif
396#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200397
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 static void
399get_exe_name(void)
400{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100401 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
402 * as the maximum length that works (plus a NUL byte). */
403#define MAX_ENV_PATH_LEN 8192
404 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406
407 if (exe_name == NULL)
408 {
409 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (*temp != NUL)
412 exe_name = FullName_save((char_u *)temp, FALSE);
413 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000414
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200415 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000416 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200417 exe_path = vim_strnsave(exe_name,
418 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 /* Append our starting directory to $PATH, so that when doing
422 * "!xxd" it's found in our starting directory. Needed because
423 * SearchPath() also looks there. */
424 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100425 if (p == NULL
426 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100428 if (p == NULL || *p == NUL)
429 temp[0] = NUL;
430 else
431 {
432 STRCPY(temp, p);
433 STRCAT(temp, ";");
434 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100436 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000438 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440}
441
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100443 * Unescape characters in "p" that appear in "escaped".
444 */
445 static void
446unescape_shellxquote(char_u *p, char_u *escaped)
447{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100448 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100449 int n;
450
451 while (*p != NUL)
452 {
453 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
454 mch_memmove(p, p + 1, l--);
455#ifdef FEAT_MBYTE
456 n = (*mb_ptr2len)(p);
457#else
458 n = 1;
459#endif
460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100495#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
496/*
497 * Get related information about 'funcname' which is imported by 'hInst'.
498 * If 'info' is 0, return the function address.
499 * If 'info' is 1, return the module name which the function is imported from.
500 */
501 static void *
502get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
503{
504 PBYTE pImage = (PBYTE)hInst;
505 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
506 PIMAGE_NT_HEADERS pPE;
507 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
508 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
509 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
510 PIMAGE_IMPORT_BY_NAME pImpName;
511
512 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
513 return NULL;
514 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
515 if (pPE->Signature != IMAGE_NT_SIGNATURE)
516 return NULL;
517 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
518 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
519 .VirtualAddress);
520 for (; pImpDesc->FirstThunk; ++pImpDesc)
521 {
522 if (!pImpDesc->OriginalFirstThunk)
523 continue;
524 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
525 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
526 for (; pIAT->u1.Function; ++pIAT, ++pINT)
527 {
528 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
529 continue;
530 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
531 + (UINT_PTR)(pINT->u1.AddressOfData));
532 if (strcmp((char *)pImpName->Name, funcname) == 0)
533 {
534 switch (info)
535 {
536 case 0:
537 return (void *)pIAT->u1.Function;
538 case 1:
539 return (void *)(pImage + pImpDesc->Name);
540 default:
541 return NULL;
542 }
543 }
544 }
545 }
546 return NULL;
547}
548
549/*
550 * Get the module handle which 'funcname' in 'hInst' is imported from.
551 */
552 HINSTANCE
553find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
554{
555 char *modulename;
556
557 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
558 if (modulename != NULL)
559 return GetModuleHandleA(modulename);
560 return NULL;
561}
562
563/*
564 * Get the address of 'funcname' which is imported by 'hInst' DLL.
565 */
566 void *
567get_dll_import_func(HINSTANCE hInst, const char *funcname)
568{
569 return get_imported_func_info(hInst, funcname, 0);
570}
571#endif
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
574# ifndef GETTEXT_DLL
575# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200576# define GETTEXT_DLL_ALT1 "libintl-8.dll"
577# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200579/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200581static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000582static char *null_libintl_textdomain(const char *);
583static char *null_libintl_bindtextdomain(const char *, const char *);
584static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100586static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200588static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200590char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
591 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
593char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
596 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100598int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599
600 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100601dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602{
603 int i;
604 static struct
605 {
606 char *name;
607 FARPROC *ptr;
608 } libintl_entry[] =
609 {
610 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
613 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
614 {NULL, NULL}
615 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100616 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617
Bram Moolenaar7554c542018-10-06 15:03:15 +0200618 // No need to initialize twice.
619 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200621 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100622 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200623#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100624 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
626#endif
627#ifdef GETTEXT_DLL_ALT2
628 if (!hLibintlDLL)
629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#endif
631 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200633 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 verbose_enter();
636 EMSG2(_(e_loadlib), GETTEXT_DLL);
637 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 }
641 for (i = 0; libintl_entry[i].name != NULL
642 && libintl_entry[i].ptr != NULL; ++i)
643 {
644 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
645 libintl_entry[i].name)) == NULL)
646 {
647 dyn_libintl_end();
648 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000649 {
650 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 verbose_leave();
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 return 0;
655 }
656 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000657
658 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000659 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660 "bind_textdomain_codeset");
661 if (dyn_libintl_bind_textdomain_codeset == NULL)
662 dyn_libintl_bind_textdomain_codeset =
663 null_libintl_bind_textdomain_codeset;
664
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100665 /* _putenv() function for the libintl.dll is optional. */
666 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
667 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100668 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
671 }
672 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
675 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 return 1;
678}
679
680 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100681dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682{
683 if (hLibintlDLL)
684 FreeLibrary(hLibintlDLL);
685 hLibintlDLL = NULL;
686 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200687 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 dyn_libintl_textdomain = null_libintl_textdomain;
689 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100692 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693}
694
695 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000696null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 return (char*)msgid;
699}
700
701 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702null_libintl_ngettext(
703 const char *msgid,
704 const char *msgid_plural,
705 unsigned long n)
706{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200707 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200708}
709
Bram Moolenaaree695f72016-08-03 22:08:45 +0200710 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100711null_libintl_bindtextdomain(
712 const char *domainname UNUSED,
713 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714{
715 return NULL;
716}
717
718 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100719null_libintl_bind_textdomain_codeset(
720 const char *domainname UNUSED,
721 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000722{
723 return NULL;
724}
725
726 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100727null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200732 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100734{
735 return 0;
736}
737
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200738 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100739null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100740{
741 return 0;
742}
743
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744#endif /* DYNAMIC_GETTEXT */
745
746/* This symbol is not defined in older versions of the SDK or Visual C++ */
747
748#ifndef VER_PLATFORM_WIN32_WINDOWS
749# define VER_PLATFORM_WIN32_WINDOWS 1
750#endif
751
752DWORD g_PlatformId;
753
754#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100755# ifndef PROTO
756# include <aclapi.h>
757# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200758# ifndef PROTECTED_DACL_SECURITY_INFORMATION
759# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#endif
762
Bram Moolenaar27515922013-06-29 15:36:26 +0200763#ifdef HAVE_ACL
764/*
765 * Enables or disables the specified privilege.
766 */
767 static BOOL
768win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
769{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100770 BOOL bResult;
771 LUID luid;
772 HANDLE hToken;
773 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200774
775 if (!OpenProcessToken(GetCurrentProcess(),
776 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
777 return FALSE;
778
779 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
780 {
781 CloseHandle(hToken);
782 return FALSE;
783 }
784
Bram Moolenaar45500912014-07-09 20:51:07 +0200785 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200786 tokenPrivileges.Privileges[0].Luid = luid;
787 tokenPrivileges.Privileges[0].Attributes = bEnable ?
788 SE_PRIVILEGE_ENABLED : 0;
789
790 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
791 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
792
793 CloseHandle(hToken);
794
795 return bResult && GetLastError() == ERROR_SUCCESS;
796}
797#endif
798
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799/*
800 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
801 * VER_PLATFORM_WIN32_WINDOWS (Win95).
802 */
803 void
804PlatformId(void)
805{
806 static int done = FALSE;
807
808 if (!done)
809 {
810 OSVERSIONINFO ovi;
811
812 ovi.dwOSVersionInfoSize = sizeof(ovi);
813 GetVersionEx(&ovi);
814
815 g_PlatformId = ovi.dwPlatformId;
816
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100817 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
818 || ovi.dwMajorVersion > 6)
819 win8_or_later = TRUE;
820
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200822 /* Enable privilege for getting or setting SACLs. */
823 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#endif
825 done = TRUE;
826 }
827}
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifndef FEAT_GUI_W32
830
831#define SHIFT (SHIFT_PRESSED)
832#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
833#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
834#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
835
836
837/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
838 * We map function keys to their ANSI terminal equivalents, as produced
839 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
840 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
841 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
842 * combinations of function/arrow/etc keys.
843 */
844
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000845static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 WORD wVirtKey;
848 BOOL fAnsiKey;
849 int chAlone;
850 int chShift;
851 int chCtrl;
852 int chAlt;
853} VirtKeyMap[] =
854{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855/* Key ANSI alone shift ctrl alt */
856 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
857
858 { VK_F1, TRUE, ';', 'T', '^', 'h', },
859 { VK_F2, TRUE, '<', 'U', '_', 'i', },
860 { VK_F3, TRUE, '=', 'V', '`', 'j', },
861 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
862 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
863 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
864 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
865 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
866 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
867 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200868 { VK_F11, TRUE, 0x85, 0x87, 0x89, 0x8B, },
869 { VK_F12, TRUE, 0x86, 0x88, 0x8a, 0x8c, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200871 { VK_HOME, TRUE, 'G', 0xc2, 'w', 0xc3, },
872 { VK_UP, TRUE, 'H', 0xc4, 0xc5, 0xc6, },
873 { VK_PRIOR, TRUE, 'I', 0xc7, 0x84, 0xc8, }, /*PgUp*/
874 { VK_LEFT, TRUE, 'K', 0xc9, 's', 0xca, },
875 { VK_RIGHT, TRUE, 'M', 0xcb, 't', 0xcc, },
876 { VK_END, TRUE, 'O', 0xcd, 'u', 0xce, },
877 { VK_DOWN, TRUE, 'P', 0xcf, 0xd0, 0xd1, },
878 { VK_NEXT, TRUE, 'Q', 0xd2, 'v', 0xd3, }, /*PgDn*/
879 { VK_INSERT,TRUE, 'R', 0xd4, 0xd5, 0xd6, },
880 { VK_DELETE,TRUE, 'S', 0xd7, 0xd8, 0xd9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881
882 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
883
884#if 0
885 /* Most people don't have F13-F20, but what the hell... */
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200886 { VK_F13, TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
887 { VK_F14, TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
888 { VK_F15, TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
889 { VK_F16, TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
890 { VK_F17, TRUE, 0xea, 0xeb, 0xec, 0xed, },
891 { VK_F18, TRUE, 0xee, 0xef, 0xf0, 0xf1, },
892 { VK_F19, TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
893 { VK_F20, TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894#endif
895 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
896 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
897 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
898 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
899
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200900 { VK_NUMPAD0,TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
901 { VK_NUMPAD1,TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
902 { VK_NUMPAD2,TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
903 { VK_NUMPAD3,TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
904 { VK_NUMPAD4,TRUE, 0xea, 0xeb, 0xec, 0xed, },
905 { VK_NUMPAD5,TRUE, 0xee, 0xef, 0xf0, 0xf1, },
906 { VK_NUMPAD6,TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
907 { VK_NUMPAD7,TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
908 { VK_NUMPAD8,TRUE, 0xfa, 0xfb, 0xfc, 0xfd, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 /* Sorry, out of number space! <negri>*/
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200910 { VK_NUMPAD9,TRUE, 0xfe, 0xff, 0xff, 0xf7, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911};
912
913
914#ifdef _MSC_VER
915// The ToAscii bug destroys several registers. Need to turn off optimization
916// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000917# pragma warning(push)
918# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919# pragma optimize("", off)
920#endif
921
922#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200923# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200925# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926#endif
927
928/* The return code indicates key code size. */
929 static int
930#ifdef __BORLANDC__
931 __stdcall
932#endif
933win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000934 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935{
936 UINT uMods = pker->dwControlKeyState;
937 static int s_iIsDead = 0;
938 static WORD awAnsiCode[2];
939 static BYTE abKeystate[256];
940
941
942 if (s_iIsDead == 2)
943 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200944 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 s_iIsDead = 0;
946 return 1;
947 }
948
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200949 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 return 1;
951
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200952 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200955 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956
957 if (uMods & SHIFT_PRESSED)
958 abKeystate[VK_SHIFT] = 0x80;
959 if (uMods & CAPSLOCK_ON)
960 abKeystate[VK_CAPITAL] = 1;
961
962 if ((uMods & ALT_GR) == ALT_GR)
963 {
964 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
965 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
966 }
967
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200968 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
969 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970
971 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200972 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
974 return s_iIsDead;
975}
976
977#ifdef _MSC_VER
978/* MUST switch optimization on again here, otherwise a call to
979 * decode_key_event() may crash (e.g. when hitting caps-lock) */
980# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000981# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982
983# if (_MSC_VER < 1100)
984/* MUST turn off global optimisation for this next function, or
985 * pressing ctrl-minus in insert mode crashes Vim when built with
986 * VC4.1. -- negri. */
987# pragma optimize("g", off)
988# endif
989#endif
990
991static BOOL g_fJustGotFocus = FALSE;
992
993/*
994 * Decode a KEY_EVENT into one or two keystrokes
995 */
996 static BOOL
997decode_key_event(
998 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200999 WCHAR *pch,
1000 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001 int *pmodifiers,
1002 BOOL fDoPost)
1003{
1004 int i;
1005 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1006
1007 *pch = *pch2 = NUL;
1008 g_fJustGotFocus = FALSE;
1009
1010 /* ignore key up events */
1011 if (!pker->bKeyDown)
1012 return FALSE;
1013
1014 /* ignore some keystrokes */
1015 switch (pker->wVirtualKeyCode)
1016 {
1017 /* modifiers */
1018 case VK_SHIFT:
1019 case VK_CONTROL:
1020 case VK_MENU: /* Alt key */
1021 return FALSE;
1022
1023 default:
1024 break;
1025 }
1026
1027 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001028 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029 {
1030 /* Ctrl-6 is Ctrl-^ */
1031 if (pker->wVirtualKeyCode == '6')
1032 {
1033 *pch = Ctrl_HAT;
1034 return TRUE;
1035 }
1036 /* Ctrl-2 is Ctrl-@ */
1037 else if (pker->wVirtualKeyCode == '2')
1038 {
1039 *pch = NUL;
1040 return TRUE;
1041 }
1042 /* Ctrl-- is Ctrl-_ */
1043 else if (pker->wVirtualKeyCode == 0xBD)
1044 {
1045 *pch = Ctrl__;
1046 return TRUE;
1047 }
1048 }
1049
1050 /* Shift-TAB */
1051 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1052 {
1053 *pch = K_NUL;
1054 *pch2 = '\017';
1055 return TRUE;
1056 }
1057
1058 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1059 {
1060 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1061 {
1062 if (nModifs == 0)
1063 *pch = VirtKeyMap[i].chAlone;
1064 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1065 *pch = VirtKeyMap[i].chShift;
1066 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1067 *pch = VirtKeyMap[i].chCtrl;
1068 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1069 *pch = VirtKeyMap[i].chAlt;
1070
1071 if (*pch != 0)
1072 {
1073 if (VirtKeyMap[i].fAnsiKey)
1074 {
1075 *pch2 = *pch;
1076 *pch = K_NUL;
1077 }
1078
1079 return TRUE;
1080 }
1081 }
1082 }
1083
1084 i = win32_kbd_patch_key(pker);
1085
1086 if (i < 0)
1087 *pch = NUL;
1088 else
1089 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001090 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091
1092 if (pmodifiers != NULL)
1093 {
1094 /* Pass on the ALT key as a modifier, but only when not combined
1095 * with CTRL (which is ALTGR). */
1096 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1097 *pmodifiers |= MOD_MASK_ALT;
1098
1099 /* Pass on SHIFT only for special keys, because we don't know when
1100 * it's already included with the character. */
1101 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1102 *pmodifiers |= MOD_MASK_SHIFT;
1103
1104 /* Pass on CTRL only for non-special keys, because we don't know
1105 * when it's already included with the character. And not when
1106 * combined with ALT (which is ALTGR). */
1107 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1108 && *pch >= 0x20 && *pch < 0x80)
1109 *pmodifiers |= MOD_MASK_CTRL;
1110 }
1111 }
1112
1113 return (*pch != NUL);
1114}
1115
1116#ifdef _MSC_VER
1117# pragma optimize("", on)
1118#endif
1119
1120#endif /* FEAT_GUI_W32 */
1121
1122
1123#ifdef FEAT_MOUSE
1124
1125/*
1126 * For the GUI the mouse handling is in gui_w32.c.
1127 */
1128# ifdef FEAT_GUI_W32
1129 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001130mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131{
1132}
1133# else
1134static int g_fMouseAvail = FALSE; /* mouse present */
1135static int g_fMouseActive = FALSE; /* mouse enabled */
1136static int g_nMouseClick = -1; /* mouse status */
1137static int g_xMouse; /* mouse x coordinate */
1138static int g_yMouse; /* mouse y coordinate */
1139
1140/*
1141 * Enable or disable mouse input
1142 */
1143 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001144mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145{
1146 DWORD cmodein;
1147
1148 if (!g_fMouseAvail)
1149 return;
1150
1151 g_fMouseActive = on;
1152 GetConsoleMode(g_hConIn, &cmodein);
1153
1154 if (g_fMouseActive)
1155 cmodein |= ENABLE_MOUSE_INPUT;
1156 else
1157 cmodein &= ~ENABLE_MOUSE_INPUT;
1158
1159 SetConsoleMode(g_hConIn, cmodein);
1160}
1161
Bram Moolenaar157d8132018-03-06 17:09:20 +01001162
1163#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1164/*
1165 * Called when 'balloonevalterm' changed.
1166 */
1167 void
1168mch_bevalterm_changed(void)
1169{
1170 mch_setmouse(g_fMouseActive);
1171}
1172#endif
1173
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174/*
1175 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1176 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1177 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1178 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1179 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1180 * and we return the mouse position in g_xMouse and g_yMouse.
1181 *
1182 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1183 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1184 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1185 *
1186 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1187 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1188 *
1189 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1190 * moves, even if it stays within the same character cell. We ignore
1191 * all MOUSE_MOVED messages if the position hasn't really changed, and
1192 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1193 * we're only interested in MOUSE_DRAG).
1194 *
1195 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1196 * 2-button mouses by pressing the left & right buttons simultaneously.
1197 * In practice, it's almost impossible to click both at the same time,
1198 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1199 * in such cases, if the user is clicking quickly.
1200 */
1201 static BOOL
1202decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001203 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204{
1205 static int s_nOldButton = -1;
1206 static int s_nOldMouseClick = -1;
1207 static int s_xOldMouse = -1;
1208 static int s_yOldMouse = -1;
1209 static linenr_T s_old_topline = 0;
1210#ifdef FEAT_DIFF
1211 static int s_old_topfill = 0;
1212#endif
1213 static int s_cClicks = 1;
1214 static BOOL s_fReleased = TRUE;
1215 static DWORD s_dwLastClickTime = 0;
1216 static BOOL s_fNextIsMiddle = FALSE;
1217
1218 static DWORD cButtons = 0; /* number of buttons supported */
1219
1220 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1221 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1222 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1223 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1224
1225 int nButton;
1226
1227 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1228 cButtons = 2;
1229
1230 if (!g_fMouseAvail || !g_fMouseActive)
1231 {
1232 g_nMouseClick = -1;
1233 return FALSE;
1234 }
1235
1236 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1237 if (g_fJustGotFocus)
1238 {
1239 g_fJustGotFocus = FALSE;
1240 return FALSE;
1241 }
1242
1243 /* unprocessed mouse click? */
1244 if (g_nMouseClick != -1)
1245 return TRUE;
1246
1247 nButton = -1;
1248 g_xMouse = pmer->dwMousePosition.X;
1249 g_yMouse = pmer->dwMousePosition.Y;
1250
1251 if (pmer->dwEventFlags == MOUSE_MOVED)
1252 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001253 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254 * events even when the mouse moves only within a char cell.) */
1255 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1256 return FALSE;
1257 }
1258
1259 /* If no buttons are pressed... */
1260 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1261 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001262 nButton = MOUSE_RELEASE;
1263
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1265 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001266 {
1267#ifdef FEAT_BEVAL_TERM
1268 /* do return mouse move events when we want them */
1269 if (p_bevalterm)
1270 nButton = MOUSE_DRAG;
1271 else
1272#endif
1273 return FALSE;
1274 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276 s_fReleased = TRUE;
1277 }
1278 else /* one or more buttons pressed */
1279 {
1280 /* on a 2-button mouse, hold down left and right buttons
1281 * simultaneously to get MIDDLE. */
1282
1283 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1284 {
1285 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1286
1287 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001288 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 if (dwLR == LEFT || dwLR == RIGHT)
1290 {
1291 for (;;)
1292 {
1293 /* wait a short time for next input event */
1294 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1295 != WAIT_OBJECT_0)
1296 break;
1297 else
1298 {
1299 DWORD cRecords = 0;
1300 INPUT_RECORD ir;
1301 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1302
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001303 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304
1305 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1306 || !(pmer2->dwButtonState & LEFT_RIGHT))
1307 break;
1308 else
1309 {
1310 if (pmer2->dwEventFlags != MOUSE_MOVED)
1311 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001312 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313
1314 return decode_mouse_event(pmer2);
1315 }
1316 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1317 s_yOldMouse == pmer2->dwMousePosition.Y)
1318 {
1319 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001320 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321
1322 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001323 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324
1325 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1326 break;
1327 }
1328 else
1329 break;
1330 }
1331 }
1332 }
1333 }
1334 }
1335
1336 if (s_fNextIsMiddle)
1337 {
1338 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1339 ? MOUSE_DRAG : MOUSE_MIDDLE;
1340 s_fNextIsMiddle = FALSE;
1341 }
1342 else if (cButtons == 2 &&
1343 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1344 {
1345 nButton = MOUSE_MIDDLE;
1346
1347 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1348 {
1349 s_fNextIsMiddle = TRUE;
1350 nButton = MOUSE_RELEASE;
1351 }
1352 }
1353 else if ((pmer->dwButtonState & LEFT) == LEFT)
1354 nButton = MOUSE_LEFT;
1355 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1356 nButton = MOUSE_MIDDLE;
1357 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1358 nButton = MOUSE_RIGHT;
1359
1360 if (! s_fReleased && ! s_fNextIsMiddle
1361 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1362 return FALSE;
1363
1364 s_fReleased = s_fNextIsMiddle;
1365 }
1366
1367 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1368 {
1369 /* button pressed or released, without mouse moving */
1370 if (nButton != -1 && nButton != MOUSE_RELEASE)
1371 {
1372 DWORD dwCurrentTime = GetTickCount();
1373
1374 if (s_xOldMouse != g_xMouse
1375 || s_yOldMouse != g_yMouse
1376 || s_nOldButton != nButton
1377 || s_old_topline != curwin->w_topline
1378#ifdef FEAT_DIFF
1379 || s_old_topfill != curwin->w_topfill
1380#endif
1381 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1382 {
1383 s_cClicks = 1;
1384 }
1385 else if (++s_cClicks > 4)
1386 {
1387 s_cClicks = 1;
1388 }
1389
1390 s_dwLastClickTime = dwCurrentTime;
1391 }
1392 }
1393 else if (pmer->dwEventFlags == MOUSE_MOVED)
1394 {
1395 if (nButton != -1 && nButton != MOUSE_RELEASE)
1396 nButton = MOUSE_DRAG;
1397
1398 s_cClicks = 1;
1399 }
1400
1401 if (nButton == -1)
1402 return FALSE;
1403
1404 if (nButton != MOUSE_RELEASE)
1405 s_nOldButton = nButton;
1406
1407 g_nMouseClick = nButton;
1408
1409 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1410 g_nMouseClick |= MOUSE_SHIFT;
1411 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1412 g_nMouseClick |= MOUSE_CTRL;
1413 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1414 g_nMouseClick |= MOUSE_ALT;
1415
1416 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1417 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1418
1419 /* only pass on interesting (i.e., different) mouse events */
1420 if (s_xOldMouse == g_xMouse
1421 && s_yOldMouse == g_yMouse
1422 && s_nOldMouseClick == g_nMouseClick)
1423 {
1424 g_nMouseClick = -1;
1425 return FALSE;
1426 }
1427
1428 s_xOldMouse = g_xMouse;
1429 s_yOldMouse = g_yMouse;
1430 s_old_topline = curwin->w_topline;
1431#ifdef FEAT_DIFF
1432 s_old_topfill = curwin->w_topfill;
1433#endif
1434 s_nOldMouseClick = g_nMouseClick;
1435
1436 return TRUE;
1437}
1438
1439# endif /* FEAT_GUI_W32 */
1440#endif /* FEAT_MOUSE */
1441
1442
1443#ifdef MCH_CURSOR_SHAPE
1444/*
1445 * Set the shape of the cursor.
1446 * 'thickness' can be from 1 (thin) to 99 (block)
1447 */
1448 static void
1449mch_set_cursor_shape(int thickness)
1450{
1451 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1452 ConsoleCursorInfo.dwSize = thickness;
1453 ConsoleCursorInfo.bVisible = s_cursor_visible;
1454
1455 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1456 if (s_cursor_visible)
1457 SetConsoleCursorPosition(g_hConOut, g_coord);
1458}
1459
1460 void
1461mch_update_cursor(void)
1462{
1463 int idx;
1464 int thickness;
1465
1466 /*
1467 * How the cursor is drawn depends on the current mode.
1468 */
1469 idx = get_shape_idx(FALSE);
1470
1471 if (shape_table[idx].shape == SHAPE_BLOCK)
1472 thickness = 99; /* 100 doesn't work on W95 */
1473 else
1474 thickness = shape_table[idx].percentage;
1475 mch_set_cursor_shape(thickness);
1476}
1477#endif
1478
1479#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1480/*
1481 * Handle FOCUS_EVENT.
1482 */
1483 static void
1484handle_focus_event(INPUT_RECORD ir)
1485{
1486 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1487 ui_focus_change((int)g_fJustGotFocus);
1488}
1489
1490/*
1491 * Wait until console input from keyboard or mouse is available,
1492 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001493 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 * Return TRUE if something is available FALSE if not.
1495 */
1496 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001497WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498{
1499 DWORD dwNow = 0, dwEndTime = 0;
1500 INPUT_RECORD ir;
1501 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001502 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001503#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001504 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506
1507 if (msec > 0)
1508 /* Wait until the specified time has elapsed. */
1509 dwEndTime = GetTickCount() + msec;
1510 else if (msec < 0)
1511 /* Wait forever. */
1512 dwEndTime = INFINITE;
1513
1514 /* We need to loop until the end of the time period, because
1515 * we might get multiple unusable mouse events in that time.
1516 */
1517 for (;;)
1518 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001519 // Only process messages when waiting.
1520 if (msec != 0)
1521 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001522#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001524#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001525#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001526 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001527#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001529 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001531 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001532
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 if (0
1534#ifdef FEAT_MOUSE
1535 || g_nMouseClick != -1
1536#endif
1537#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001538 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539#endif
1540 )
1541 return TRUE;
1542
1543 if (msec > 0)
1544 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001545 /* If the specified wait time has passed, return. Beware that
1546 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001548 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 break;
1550 }
1551 if (msec != 0)
1552 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001553 DWORD dwWaitTime = dwEndTime - dwNow;
1554
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001555#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001556 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001557 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001558 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001559 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001560 /* If there is readahead then parse_queued_messages() timed out
1561 * and we should call it again soon. */
1562 if (channel_any_readahead())
1563 dwWaitTime = 10;
1564 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001565#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001566#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001567 if (p_beval && dwWaitTime > 100)
1568 /* The 'balloonexpr' may indirectly invoke a callback while
1569 * waiting for a character, need to check often. */
1570 dwWaitTime = 100;
1571#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001572#ifdef FEAT_MZSCHEME
1573 if (mzthreads_allowed() && p_mzq > 0
1574 && (msec < 0 || (long)dwWaitTime > p_mzq))
1575 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1576#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001577#ifdef FEAT_TIMERS
1578 {
1579 long due_time;
1580
1581 /* When waiting very briefly don't trigger timers. */
1582 if (dwWaitTime > 10)
1583 {
1584 /* Trigger timers and then get the time in msec until the
1585 * next one is due. Wait up to that time. */
1586 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001587 if (typebuf.tb_change_cnt != tb_change_cnt)
1588 {
1589 /* timer may have used feedkeys() */
1590 return FALSE;
1591 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001592 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1593 dwWaitTime = due_time;
1594 }
1595 }
1596#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597#ifdef FEAT_CLIENTSERVER
1598 /* Wait for either an event on the console input or a message in
1599 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001600 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001601 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001603 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604#endif
1605 continue;
1606 }
1607
1608 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001609 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610
1611#ifdef FEAT_MBYTE_IME
1612 if (State & CMDLINE && msg_row == Rows - 1)
1613 {
1614 CONSOLE_SCREEN_BUFFER_INFO csbi;
1615
1616 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1617 {
1618 if (csbi.dwCursorPosition.Y != msg_row)
1619 {
1620 /* The screen is now messed up, must redraw the
1621 * command line and later all the windows. */
1622 redraw_all_later(CLEAR);
1623 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1624 redrawcmd();
1625 }
1626 }
1627 }
1628#endif
1629
1630 if (cRecords > 0)
1631 {
1632 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1633 {
1634#ifdef FEAT_MBYTE_IME
1635 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1636 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001637 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1639 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001640 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 continue;
1642 }
1643#endif
1644 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1645 NULL, FALSE))
1646 return TRUE;
1647 }
1648
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001649 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
1651 if (ir.EventType == FOCUS_EVENT)
1652 handle_focus_event(ir);
1653 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001654 {
1655 /* Only call shell_resized() when the size actually change to
1656 * avoid the screen is cleard. */
1657 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1658 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1659 shell_resized();
1660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661#ifdef FEAT_MOUSE
1662 else if (ir.EventType == MOUSE_EVENT
1663 && decode_mouse_event(&ir.Event.MouseEvent))
1664 return TRUE;
1665#endif
1666 }
1667 else if (msec == 0)
1668 break;
1669 }
1670
1671#ifdef FEAT_CLIENTSERVER
1672 /* Something might have been received while we were waiting. */
1673 if (input_available())
1674 return TRUE;
1675#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001676
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 return FALSE;
1678}
1679
1680#ifndef FEAT_GUI_MSWIN
1681/*
1682 * return non-zero if a character is available
1683 */
1684 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001685mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001687 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001689
1690# if defined(FEAT_TERMINAL) || defined(PROTO)
1691/*
1692 * Check for any pending input or messages.
1693 */
1694 int
1695mch_check_messages(void)
1696{
1697 return WaitForChar(0L, TRUE);
1698}
1699# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700#endif
1701
1702/*
1703 * Create the console input. Used when reading stdin doesn't work.
1704 */
1705 static void
1706create_conin(void)
1707{
1708 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1709 FILE_SHARE_READ|FILE_SHARE_WRITE,
1710 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001711 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 did_create_conin = TRUE;
1713}
1714
1715/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001716 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001718 static WCHAR
1719tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001721 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722
1723 for (;;)
1724 {
1725 INPUT_RECORD ir;
1726 DWORD cRecords = 0;
1727
1728#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001729 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (input_available())
1731 return 0;
1732# ifdef FEAT_MOUSE
1733 if (g_nMouseClick != -1)
1734 return 0;
1735# endif
1736#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001737 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001738 {
1739 if (did_create_conin)
1740 read_error_exit();
1741 create_conin();
1742 continue;
1743 }
1744
1745 if (ir.EventType == KEY_EVENT)
1746 {
1747 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1748 pmodifiers, TRUE))
1749 return ch;
1750 }
1751 else if (ir.EventType == FOCUS_EVENT)
1752 handle_focus_event(ir);
1753 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1754 shell_resized();
1755#ifdef FEAT_MOUSE
1756 else if (ir.EventType == MOUSE_EVENT)
1757 {
1758 if (decode_mouse_event(&ir.Event.MouseEvent))
1759 return 0;
1760 }
1761#endif
1762 }
1763}
1764#endif /* !FEAT_GUI_W32 */
1765
1766
1767/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001768 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 * Get one or more characters from the keyboard or the mouse.
1770 * If time == 0, do not wait for characters.
1771 * If time == n, wait a short time for characters.
1772 * If time == -1, wait forever for characters.
1773 * Returns the number of characters read into buf.
1774 */
1775 int
1776mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001777 char_u *buf UNUSED,
1778 int maxlen UNUSED,
1779 long time UNUSED,
1780 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781{
1782#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1783
1784 int len;
1785 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786#define TYPEAHEADLEN 20
1787 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1788 static int typeaheadlen = 0;
1789
1790 /* First use any typeahead that was kept because "buf" was too small. */
1791 if (typeaheadlen > 0)
1792 goto theend;
1793
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 if (time >= 0)
1795 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001796 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799 else /* time == -1, wait forever */
1800 {
1801 mch_set_winsize_now(); /* Allow winsize changes from now on */
1802
Bram Moolenaar3918c952005-03-15 22:34:55 +00001803 /*
1804 * If there is no character available within 2 seconds (default)
1805 * write the autoscript file to disk. Or cause the CursorHold event
1806 * to be triggered.
1807 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001808 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001810 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001812 buf[0] = K_SPECIAL;
1813 buf[1] = KS_EXTRA;
1814 buf[2] = (int)KE_CURSORHOLD;
1815 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001817 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819 }
1820
1821 /*
1822 * Try to read as many characters as there are, until the buffer is full.
1823 */
1824
1825 /* we will get at least one key. Get more if they are available. */
1826 g_fCBrkPressed = FALSE;
1827
1828#ifdef MCH_WRITE_DUMP
1829 if (fdDump)
1830 fputc('[', fdDump);
1831#endif
1832
1833 /* Keep looping until there is something in the typeahead buffer and more
1834 * to get and still room in the buffer (up to two bytes for a char and
1835 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001836 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837 && typeaheadlen + 5 <= TYPEAHEADLEN)
1838 {
1839 if (typebuf_changed(tb_change_cnt))
1840 {
1841 /* "buf" may be invalid now if a client put something in the
1842 * typeahead buffer and "buf" is in the typeahead buffer. */
1843 typeaheadlen = 0;
1844 break;
1845 }
1846#ifdef FEAT_MOUSE
1847 if (g_nMouseClick != -1)
1848 {
1849# ifdef MCH_WRITE_DUMP
1850 if (fdDump)
1851 fprintf(fdDump, "{%02x @ %d, %d}",
1852 g_nMouseClick, g_xMouse, g_yMouse);
1853# endif
1854 typeahead[typeaheadlen++] = ESC + 128;
1855 typeahead[typeaheadlen++] = 'M';
1856 typeahead[typeaheadlen++] = g_nMouseClick;
1857 typeahead[typeaheadlen++] = g_xMouse + '!';
1858 typeahead[typeaheadlen++] = g_yMouse + '!';
1859 g_nMouseClick = -1;
1860 }
1861 else
1862#endif
1863 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001864 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865 int modifiers = 0;
1866
1867 c = tgetch(&modifiers, &ch2);
1868
1869 if (typebuf_changed(tb_change_cnt))
1870 {
1871 /* "buf" may be invalid now if a client put something in the
1872 * typeahead buffer and "buf" is in the typeahead buffer. */
1873 typeaheadlen = 0;
1874 break;
1875 }
1876
1877 if (c == Ctrl_C && ctrl_c_interrupts)
1878 {
1879#if defined(FEAT_CLIENTSERVER)
1880 trash_input_buf();
1881#endif
1882 got_int = TRUE;
1883 }
1884
1885#ifdef FEAT_MOUSE
1886 if (g_nMouseClick == -1)
1887#endif
1888 {
1889 int n = 1;
1890
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001891#ifdef FEAT_MBYTE
1892 if (ch2 == NUL)
1893 {
1894 int i;
1895 char_u *p;
1896 WCHAR ch[2];
1897
1898 ch[0] = c;
1899 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1900 {
1901 ch[1] = tgetch(&modifiers, &ch2);
1902 n++;
1903 }
1904 p = utf16_to_enc(ch, &n);
1905 if (p != NULL)
1906 {
1907 for (i = 0; i < n; i++)
1908 typeahead[typeaheadlen + i] = p[i];
1909 vim_free(p);
1910 }
1911 }
1912 else
1913#endif
1914 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 if (ch2 != NUL)
1916 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001917 if (c == K_NUL && (ch2 & 0xff00) != 0)
1918 {
1919 /* fAnsiKey with modifier keys */
1920 typeahead[typeaheadlen + n] = (char_u)ch2;
1921 n++;
1922 }
1923 else
1924 {
1925 typeahead[typeaheadlen + n] = 3;
1926 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1927 n += 2;
1928 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001929 }
1930
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 /* Use the ALT key to set the 8th bit of the character
1932 * when it's one byte, the 8th bit isn't set yet and not
1933 * using a double-byte encoding (would become a lead
1934 * byte). */
1935 if ((modifiers & MOD_MASK_ALT)
1936 && n == 1
1937 && (typeahead[typeaheadlen] & 0x80) == 0
1938#ifdef FEAT_MBYTE
1939 && !enc_dbcs
1940#endif
1941 )
1942 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001943#ifdef FEAT_MBYTE
1944 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1945 typeahead + typeaheadlen);
1946#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001948#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 modifiers &= ~MOD_MASK_ALT;
1950 }
1951
1952 if (modifiers != 0)
1953 {
1954 /* Prepend modifiers to the character. */
1955 mch_memmove(typeahead + typeaheadlen + 3,
1956 typeahead + typeaheadlen, n);
1957 typeahead[typeaheadlen++] = K_SPECIAL;
1958 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1959 typeahead[typeaheadlen++] = modifiers;
1960 }
1961
1962 typeaheadlen += n;
1963
1964#ifdef MCH_WRITE_DUMP
1965 if (fdDump)
1966 fputc(c, fdDump);
1967#endif
1968 }
1969 }
1970 }
1971
1972#ifdef MCH_WRITE_DUMP
1973 if (fdDump)
1974 {
1975 fputs("]\n", fdDump);
1976 fflush(fdDump);
1977 }
1978#endif
1979
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980theend:
1981 /* Move typeahead to "buf", as much as fits. */
1982 len = 0;
1983 while (len < maxlen && typeaheadlen > 0)
1984 {
1985 buf[len++] = typeahead[0];
1986 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1987 }
1988 return len;
1989
1990#else /* FEAT_GUI_W32 */
1991 return 0;
1992#endif /* FEAT_GUI_W32 */
1993}
1994
Bram Moolenaar82881492012-11-20 16:53:39 +01001995#ifndef PROTO
1996# ifndef __MINGW32__
1997# include <shellapi.h> /* required for FindExecutable() */
1998# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999#endif
2000
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002001/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002002 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2003 * If "use_path" is FALSE: Return TRUE if "name" exists.
2004 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2005 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002006 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002007 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002009executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002011 char *dum;
2012 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002013 char *curpath, *newpath;
2014 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015
Bram Moolenaar43663192017-03-05 14:29:12 +01002016 if (!use_path)
2017 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002018 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002019 {
2020 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002021 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002022 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002023 *path = vim_strsave((char_u *)name);
2024 else
2025 *path = FullName_save((char_u *)name, FALSE);
2026 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002027 return TRUE;
2028 }
2029 return FALSE;
2030 }
2031
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002032#ifdef FEAT_MBYTE
2033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002035 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002036 WCHAR fnamew[_MAX_PATH];
2037 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002038 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002039
2040 if (p != NULL)
2041 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002042 wcurpath = _wgetenv(L"PATH");
2043 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2044 * sizeof(WCHAR));
2045 if (wnewpath == NULL)
2046 return FALSE;
2047 wcscpy(wnewpath, L".;");
2048 wcscat(wnewpath, wcurpath);
2049 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2050 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002051 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002052 if (n == 0)
2053 return FALSE;
2054 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2055 return FALSE;
2056 if (path != NULL)
2057 *path = utf16_to_enc(fnamew, NULL);
2058 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002059 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002061#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002062
2063 curpath = getenv("PATH");
2064 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2065 if (newpath == NULL)
2066 return FALSE;
2067 STRCPY(newpath, ".;");
2068 STRCAT(newpath, curpath);
2069 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2070 vim_free(newpath);
2071 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002072 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002073 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002075 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002076 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002077 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002078}
2079
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002080#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002081 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002082/*
2083 * Bad parameter handler.
2084 *
2085 * Certain MS CRT functions will intentionally crash when passed invalid
2086 * parameters to highlight possible security holes. Setting this function as
2087 * the bad parameter handler will prevent the crash.
2088 *
2089 * In debug builds the parameters contain CRT information that might help track
2090 * down the source of a problem, but in non-debug builds the arguments are all
2091 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2092 * worth allowing these to make debugging of issues easier.
2093 */
2094 static void
2095bad_param_handler(const wchar_t *expression,
2096 const wchar_t *function,
2097 const wchar_t *file,
2098 unsigned int line,
2099 uintptr_t pReserved)
2100{
2101}
2102
2103# define SET_INVALID_PARAM_HANDLER \
2104 ((void)_set_invalid_parameter_handler(bad_param_handler))
2105#else
2106# define SET_INVALID_PARAM_HANDLER
2107#endif
2108
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109#ifdef FEAT_GUI_W32
2110
2111/*
2112 * GUI version of mch_init().
2113 */
2114 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002115mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116{
2117#ifndef __MINGW32__
2118 extern int _fmode;
2119#endif
2120
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002121 /* Silently handle invalid parameters to CRT functions */
2122 SET_INVALID_PARAM_HANDLER;
2123
Bram Moolenaar071d4272004-06-13 20:20:40 +00002124 /* Let critical errors result in a failure, not in a dialog box. Required
2125 * for the timestamp test to work on removed floppies. */
2126 SetErrorMode(SEM_FAILCRITICALERRORS);
2127
2128 _fmode = O_BINARY; /* we do our own CR-LF translation */
2129
2130 /* Specify window size. Is there a place to get the default from? */
2131 Rows = 25;
2132 Columns = 80;
2133
2134 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 {
2136 char_u vimrun_location[_MAX_PATH + 4];
2137
2138 /* First try in same directory as gvim.exe */
2139 STRCPY(vimrun_location, exe_name);
2140 STRCPY(gettail(vimrun_location), "vimrun.exe");
2141 if (mch_getperm(vimrun_location) >= 0)
2142 {
2143 if (*skiptowhite(vimrun_location) != NUL)
2144 {
2145 /* Enclose path with white space in double quotes. */
2146 mch_memmove(vimrun_location + 1, vimrun_location,
2147 STRLEN(vimrun_location) + 1);
2148 *vimrun_location = '"';
2149 STRCPY(gettail(vimrun_location), "vimrun\" ");
2150 }
2151 else
2152 STRCPY(gettail(vimrun_location), "vimrun ");
2153
2154 vimrun_path = (char *)vim_strsave(vimrun_location);
2155 s_dont_use_vimrun = FALSE;
2156 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002157 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 s_dont_use_vimrun = FALSE;
2159
2160 /* Don't give the warning for a missing vimrun.exe right now, but only
2161 * when vimrun was supposed to be used. Don't bother people that do
2162 * not need vimrun.exe. */
2163 if (s_dont_use_vimrun)
2164 need_vimrun_warning = TRUE;
2165 }
2166
2167 /*
2168 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2169 * Otherwise the default "findstr /n" is used.
2170 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002171 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2173
2174#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002175 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176#endif
2177}
2178
2179
2180#else /* FEAT_GUI_W32 */
2181
2182#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2183#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2184
2185/*
2186 * ClearConsoleBuffer()
2187 * Description:
2188 * Clears the entire contents of the console screen buffer, using the
2189 * specified attribute.
2190 * Returns:
2191 * TRUE on success
2192 */
2193 static BOOL
2194ClearConsoleBuffer(WORD wAttribute)
2195{
2196 CONSOLE_SCREEN_BUFFER_INFO csbi;
2197 COORD coord;
2198 DWORD NumCells, dummy;
2199
2200 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2201 return FALSE;
2202
2203 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2204 coord.X = 0;
2205 coord.Y = 0;
2206 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2207 coord, &dummy))
2208 {
2209 return FALSE;
2210 }
2211 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2212 coord, &dummy))
2213 {
2214 return FALSE;
2215 }
2216
2217 return TRUE;
2218}
2219
2220/*
2221 * FitConsoleWindow()
2222 * Description:
2223 * Checks if the console window will fit within given buffer dimensions.
2224 * Also, if requested, will shrink the window to fit.
2225 * Returns:
2226 * TRUE on success
2227 */
2228 static BOOL
2229FitConsoleWindow(
2230 COORD dwBufferSize,
2231 BOOL WantAdjust)
2232{
2233 CONSOLE_SCREEN_BUFFER_INFO csbi;
2234 COORD dwWindowSize;
2235 BOOL NeedAdjust = FALSE;
2236
2237 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2238 {
2239 /*
2240 * A buffer resize will fail if the current console window does
2241 * not lie completely within that buffer. To avoid this, we might
2242 * have to move and possibly shrink the window.
2243 */
2244 if (csbi.srWindow.Right >= dwBufferSize.X)
2245 {
2246 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2247 if (dwWindowSize.X > dwBufferSize.X)
2248 dwWindowSize.X = dwBufferSize.X;
2249 csbi.srWindow.Right = dwBufferSize.X - 1;
2250 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2251 NeedAdjust = TRUE;
2252 }
2253 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2254 {
2255 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2256 if (dwWindowSize.Y > dwBufferSize.Y)
2257 dwWindowSize.Y = dwBufferSize.Y;
2258 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2259 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2260 NeedAdjust = TRUE;
2261 }
2262 if (NeedAdjust && WantAdjust)
2263 {
2264 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2265 return FALSE;
2266 }
2267 return TRUE;
2268 }
2269
2270 return FALSE;
2271}
2272
2273typedef struct ConsoleBufferStruct
2274{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 BOOL IsValid;
2276 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002277 PCHAR_INFO Buffer;
2278 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002279 PSMALL_RECT Regions;
2280 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281} ConsoleBuffer;
2282
2283/*
2284 * SaveConsoleBuffer()
2285 * Description:
2286 * Saves important information about the console buffer, including the
2287 * actual buffer contents. The saved information is suitable for later
2288 * restoration by RestoreConsoleBuffer().
2289 * Returns:
2290 * TRUE if all information was saved; FALSE otherwise
2291 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2292 */
2293 static BOOL
2294SaveConsoleBuffer(
2295 ConsoleBuffer *cb)
2296{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002297 DWORD NumCells;
2298 COORD BufferCoord;
2299 SMALL_RECT ReadRegion;
2300 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002301 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002302
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 if (cb == NULL)
2304 return FALSE;
2305
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002306 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 {
2308 cb->IsValid = FALSE;
2309 return FALSE;
2310 }
2311 cb->IsValid = TRUE;
2312
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002313 /*
2314 * Allocate a buffer large enough to hold the entire console screen
2315 * buffer. If this ConsoleBuffer structure has already been initialized
2316 * with a buffer of the correct size, then just use that one.
2317 */
2318 if (!cb->IsValid || cb->Buffer == NULL ||
2319 cb->BufferSize.X != cb->Info.dwSize.X ||
2320 cb->BufferSize.Y != cb->Info.dwSize.Y)
2321 {
2322 cb->BufferSize.X = cb->Info.dwSize.X;
2323 cb->BufferSize.Y = cb->Info.dwSize.Y;
2324 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2325 vim_free(cb->Buffer);
2326 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2327 if (cb->Buffer == NULL)
2328 return FALSE;
2329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330
2331 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002332 * We will now copy the console screen buffer into our buffer.
2333 * ReadConsoleOutput() seems to be limited as far as how much you
2334 * can read at a time. Empirically, this number seems to be about
2335 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2336 * in chunks until it is all copied. The chunks will all have the
2337 * same horizontal characteristics, so initialize them now. The
2338 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002340 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002341 ReadRegion.Left = 0;
2342 ReadRegion.Right = cb->Info.dwSize.X - 1;
2343 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002344
2345 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2346 if (cb->Regions == NULL || numregions != cb->NumRegions)
2347 {
2348 cb->NumRegions = numregions;
2349 vim_free(cb->Regions);
2350 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2351 if (cb->Regions == NULL)
2352 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002353 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002354 return FALSE;
2355 }
2356 }
2357
2358 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360 /*
2361 * Read into position (0, Y) in our buffer.
2362 */
2363 BufferCoord.Y = Y;
2364 /*
2365 * Read the region whose top left corner is (0, Y) and whose bottom
2366 * right corner is (width - 1, Y + Y_incr - 1). This should define
2367 * a region of size width by Y_incr. Don't worry if this region is
2368 * too large for the remaining buffer; it will be cropped.
2369 */
2370 ReadRegion.Top = Y;
2371 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002372 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002373 cb->Buffer, /* our buffer */
2374 cb->BufferSize, /* dimensions of our buffer */
2375 BufferCoord, /* offset in our buffer */
2376 &ReadRegion)) /* region to save */
2377 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002378 VIM_CLEAR(cb->Buffer);
2379 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002380 return FALSE;
2381 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002382 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 }
2384
2385 return TRUE;
2386}
2387
2388/*
2389 * RestoreConsoleBuffer()
2390 * Description:
2391 * Restores important information about the console buffer, including the
2392 * actual buffer contents, if desired. The information to restore is in
2393 * the same format used by SaveConsoleBuffer().
2394 * Returns:
2395 * TRUE on success
2396 */
2397 static BOOL
2398RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002399 ConsoleBuffer *cb,
2400 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002402 COORD BufferCoord;
2403 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002404 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405
2406 if (cb == NULL || !cb->IsValid)
2407 return FALSE;
2408
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002409 /*
2410 * Before restoring the buffer contents, clear the current buffer, and
2411 * restore the cursor position and window information. Doing this now
2412 * prevents old buffer contents from "flashing" onto the screen.
2413 */
2414 if (RestoreScreen)
2415 ClearConsoleBuffer(cb->Info.wAttributes);
2416
2417 FitConsoleWindow(cb->Info.dwSize, TRUE);
2418 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2419 return FALSE;
2420 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2421 return FALSE;
2422
2423 if (!RestoreScreen)
2424 {
2425 /*
2426 * No need to restore the screen buffer contents, so we're done.
2427 */
2428 return TRUE;
2429 }
2430
2431 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2432 return FALSE;
2433 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2434 return FALSE;
2435
2436 /*
2437 * Restore the screen buffer contents.
2438 */
2439 if (cb->Buffer != NULL)
2440 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002441 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002442 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002443 BufferCoord.X = cb->Regions[i].Left;
2444 BufferCoord.Y = cb->Regions[i].Top;
2445 WriteRegion = cb->Regions[i];
2446 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2447 cb->Buffer, /* our buffer */
2448 cb->BufferSize, /* dimensions of our buffer */
2449 BufferCoord, /* offset in our buffer */
2450 &WriteRegion)) /* region to restore */
2451 {
2452 return FALSE;
2453 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002454 }
2455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456
2457 return TRUE;
2458}
2459
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002460#define FEAT_RESTORE_ORIG_SCREEN
2461#ifdef FEAT_RESTORE_ORIG_SCREEN
2462static ConsoleBuffer g_cbOrig = { 0 };
2463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464static ConsoleBuffer g_cbNonTermcap = { 0 };
2465static ConsoleBuffer g_cbTermcap = { 0 };
2466
2467#ifdef FEAT_TITLE
2468#ifdef __BORLANDC__
2469typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2470#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002471typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472#endif
2473char g_szOrigTitle[256] = { 0 };
2474HWND g_hWnd = NULL; /* also used in os_mswin.c */
2475static HICON g_hOrigIconSmall = NULL;
2476static HICON g_hOrigIcon = NULL;
2477static HICON g_hVimIcon = NULL;
2478static BOOL g_fCanChangeIcon = FALSE;
2479
2480/* ICON* are not defined in VC++ 4.0 */
2481#ifndef ICON_SMALL
2482#define ICON_SMALL 0
2483#endif
2484#ifndef ICON_BIG
2485#define ICON_BIG 1
2486#endif
2487/*
2488 * GetConsoleIcon()
2489 * Description:
2490 * Attempts to retrieve the small icon and/or the big icon currently in
2491 * use by a given window.
2492 * Returns:
2493 * TRUE on success
2494 */
2495 static BOOL
2496GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002497 HWND hWnd,
2498 HICON *phIconSmall,
2499 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500{
2501 if (hWnd == NULL)
2502 return FALSE;
2503
2504 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002505 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2506 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002508 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2509 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 return TRUE;
2511}
2512
2513/*
2514 * SetConsoleIcon()
2515 * Description:
2516 * Attempts to change the small icon and/or the big icon currently in
2517 * use by a given window.
2518 * Returns:
2519 * TRUE on success
2520 */
2521 static BOOL
2522SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002523 HWND hWnd,
2524 HICON hIconSmall,
2525 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 if (hWnd == NULL)
2528 return FALSE;
2529
2530 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002531 SendMessage(hWnd, WM_SETICON,
2532 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002534 SendMessage(hWnd, WM_SETICON,
2535 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 return TRUE;
2537}
2538
2539/*
2540 * SaveConsoleTitleAndIcon()
2541 * Description:
2542 * Saves the current console window title in g_szOrigTitle, for later
2543 * restoration. Also, attempts to obtain a handle to the console window,
2544 * and use it to save the small and big icons currently in use by the
2545 * console window. This is not always possible on some versions of Windows;
2546 * nor is it possible when running Vim remotely using Telnet (since the
2547 * console window the user sees is owned by a remote process).
2548 */
2549 static void
2550SaveConsoleTitleAndIcon(void)
2551{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 /* Save the original title. */
2553 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2554 return;
2555
2556 /*
2557 * Obtain a handle to the console window using GetConsoleWindow() from
2558 * KERNEL32.DLL; we need to handle in order to change the window icon.
2559 * This function only exists on NT-based Windows, starting with Windows
2560 * 2000. On older operating systems, we can't change the window icon
2561 * anyway.
2562 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002563 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 if (g_hWnd == NULL)
2565 return;
2566
2567 /* Save the original console window icon. */
2568 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2569 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2570 return;
2571
2572 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002573 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002574 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 if (g_hVimIcon != NULL)
2576 g_fCanChangeIcon = TRUE;
2577}
2578#endif
2579
2580static int g_fWindInitCalled = FALSE;
2581static int g_fTermcapMode = FALSE;
2582static CONSOLE_CURSOR_INFO g_cci;
2583static DWORD g_cmodein = 0;
2584static DWORD g_cmodeout = 0;
2585
2586/*
2587 * non-GUI version of mch_init().
2588 */
2589 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002590mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002592#ifndef FEAT_RESTORE_ORIG_SCREEN
2593 CONSOLE_SCREEN_BUFFER_INFO csbi;
2594#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595#ifndef __MINGW32__
2596 extern int _fmode;
2597#endif
2598
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002599 /* Silently handle invalid parameters to CRT functions */
2600 SET_INVALID_PARAM_HANDLER;
2601
Bram Moolenaar071d4272004-06-13 20:20:40 +00002602 /* Let critical errors result in a failure, not in a dialog box. Required
2603 * for the timestamp test to work on removed floppies. */
2604 SetErrorMode(SEM_FAILCRITICALERRORS);
2605
2606 _fmode = O_BINARY; /* we do our own CR-LF translation */
2607 out_flush();
2608
2609 /* Obtain handles for the standard Console I/O devices */
2610 if (read_cmd_fd == 0)
2611 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2612 else
2613 create_conin();
2614 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2615
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002616#ifdef FEAT_RESTORE_ORIG_SCREEN
2617 /* Save the initial console buffer for later restoration */
2618 SaveConsoleBuffer(&g_cbOrig);
2619 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2620#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002622 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2623 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2624#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 if (cterm_normal_fg_color == 0)
2626 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2627 if (cterm_normal_bg_color == 0)
2628 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2629
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002630 // Fg and Bg color index nunmber at startup
2631 g_color_index_fg = g_attrDefault & 0xf;
2632 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2633
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 /* set termcap codes to current text attributes */
2635 update_tcap(g_attrCurrent);
2636
2637 GetConsoleCursorInfo(g_hConOut, &g_cci);
2638 GetConsoleMode(g_hConIn, &g_cmodein);
2639 GetConsoleMode(g_hConOut, &g_cmodeout);
2640
2641#ifdef FEAT_TITLE
2642 SaveConsoleTitleAndIcon();
2643 /*
2644 * Set both the small and big icons of the console window to Vim's icon.
2645 * Note that Vim presently only has one size of icon (32x32), but it
2646 * automatically gets scaled down to 16x16 when setting the small icon.
2647 */
2648 if (g_fCanChangeIcon)
2649 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2650#endif
2651
2652 ui_get_shellsize();
2653
2654#ifdef MCH_WRITE_DUMP
2655 fdDump = fopen("dump", "wt");
2656
2657 if (fdDump)
2658 {
2659 time_t t;
2660
2661 time(&t);
2662 fputs(ctime(&t), fdDump);
2663 fflush(fdDump);
2664 }
2665#endif
2666
2667 g_fWindInitCalled = TRUE;
2668
2669#ifdef FEAT_MOUSE
2670 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2671#endif
2672
2673#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002674 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002676
2677 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002678}
2679
2680/*
2681 * non-GUI version of mch_exit().
2682 * Shut down and exit with status `r'
2683 * Careful: mch_exit() may be called before mch_init()!
2684 */
2685 void
2686mch_exit(int r)
2687{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002688 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002690 vtp_exit();
2691
Bram Moolenaar955f1982017-02-05 15:10:51 +01002692 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 if (g_fWindInitCalled)
2694 settmode(TMODE_COOK);
2695
2696 ml_close_all(TRUE); /* remove all memfiles */
2697
2698 if (g_fWindInitCalled)
2699 {
2700#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002701 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 /*
2703 * Restore both the small and big icons of the console window to
2704 * what they were at startup. Don't do this when the window is
2705 * closed, Vim would hang here.
2706 */
2707 if (g_fCanChangeIcon && !g_fForceExit)
2708 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2709#endif
2710
2711#ifdef MCH_WRITE_DUMP
2712 if (fdDump)
2713 {
2714 time_t t;
2715
2716 time(&t);
2717 fputs(ctime(&t), fdDump);
2718 fclose(fdDump);
2719 }
2720 fdDump = NULL;
2721#endif
2722 }
2723
2724 SetConsoleCursorInfo(g_hConOut, &g_cci);
2725 SetConsoleMode(g_hConIn, g_cmodein);
2726 SetConsoleMode(g_hConOut, g_cmodeout);
2727
2728#ifdef DYNAMIC_GETTEXT
2729 dyn_libintl_end();
2730#endif
2731
2732 exit(r);
2733}
2734#endif /* !FEAT_GUI_W32 */
2735
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736/*
2737 * Do we have an interactive window?
2738 */
2739 int
2740mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002741 int argc UNUSED,
2742 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743{
2744 get_exe_name();
2745
2746#ifdef FEAT_GUI_W32
2747 return OK; /* GUI always has a tty */
2748#else
2749 if (isatty(1))
2750 return OK;
2751 return FAIL;
2752#endif
2753}
2754
2755
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002756#ifdef FEAT_MBYTE
2757/*
2758 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2759 * if it already exists. When "len" is > 0, also expand short to long
2760 * filenames.
2761 * Return FAIL if wide functions are not available, OK otherwise.
2762 * NOTE: much of this is identical to fname_case(), keep in sync!
2763 */
2764 static int
2765fname_casew(
2766 WCHAR *name,
2767 int len)
2768{
2769 WCHAR szTrueName[_MAX_PATH + 2];
2770 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2771 WCHAR *ptrue, *ptruePrev;
2772 WCHAR *porig, *porigPrev;
2773 int flen;
2774 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002775 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002776 int c;
2777 int slen;
2778
2779 flen = (int)wcslen(name);
2780 if (flen > _MAX_PATH)
2781 return OK;
2782
2783 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2784
2785 /* Build the new name in szTrueName[] one component at a time. */
2786 porig = name;
2787 ptrue = szTrueName;
2788
2789 if (iswalpha(porig[0]) && porig[1] == L':')
2790 {
2791 /* copy leading drive letter */
2792 *ptrue++ = *porig++;
2793 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002794 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002795 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796
2797 while (*porig != NUL)
2798 {
2799 /* copy \ characters */
2800 while (*porig == psepc)
2801 *ptrue++ = *porig++;
2802
2803 ptruePrev = ptrue;
2804 porigPrev = porig;
2805 while (*porig != NUL && *porig != psepc)
2806 {
2807 *ptrue++ = *porig++;
2808 }
2809 *ptrue = NUL;
2810
2811 /* To avoid a slow failure append "\*" when searching a directory,
2812 * server or network share. */
2813 wcscpy(szTrueNameTemp, szTrueName);
2814 slen = (int)wcslen(szTrueNameTemp);
2815 if (*porig == psepc && slen + 2 < _MAX_PATH)
2816 wcscpy(szTrueNameTemp + slen, L"\\*");
2817
2818 /* Skip "", "." and "..". */
2819 if (ptrue > ptruePrev
2820 && (ptruePrev[0] != L'.'
2821 || (ptruePrev[1] != NUL
2822 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2823 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2824 != INVALID_HANDLE_VALUE)
2825 {
2826 c = *porig;
2827 *porig = NUL;
2828
2829 /* Only use the match when it's the same name (ignoring case) or
2830 * expansion is allowed and there is a match with the short name
2831 * and there is enough room. */
2832 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2833 || (len > 0
2834 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2835 && (int)(ptruePrev - szTrueName)
2836 + (int)wcslen(fb.cFileName) < len)))
2837 {
2838 wcscpy(ptruePrev, fb.cFileName);
2839
2840 /* Look for exact match and prefer it if found. Must be a
2841 * long name, otherwise there would be only one match. */
2842 while (FindNextFileW(hFind, &fb))
2843 {
2844 if (*fb.cAlternateFileName != NUL
2845 && (wcscoll(porigPrev, fb.cFileName) == 0
2846 || (len > 0
2847 && (_wcsicoll(porigPrev,
2848 fb.cAlternateFileName) == 0
2849 && (int)(ptruePrev - szTrueName)
2850 + (int)wcslen(fb.cFileName) < len))))
2851 {
2852 wcscpy(ptruePrev, fb.cFileName);
2853 break;
2854 }
2855 }
2856 }
2857 FindClose(hFind);
2858 *porig = c;
2859 ptrue = ptruePrev + wcslen(ptruePrev);
2860 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002861 }
2862
2863 wcscpy(name, szTrueName);
2864 return OK;
2865}
2866#endif
2867
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868/*
2869 * fname_case(): Set the case of the file name, if it already exists.
2870 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002871 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 */
2873 void
2874fname_case(
2875 char_u *name,
2876 int len)
2877{
2878 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002879 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 char *ptrue, *ptruePrev;
2881 char *porig, *porigPrev;
2882 int flen;
2883 WIN32_FIND_DATA fb;
2884 HANDLE hFind;
2885 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002886 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002888 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002889 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 return;
2891
2892 slash_adjust(name);
2893
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002894#ifdef FEAT_MBYTE
2895 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2896 {
2897 WCHAR *p = enc_to_utf16(name, NULL);
2898
2899 if (p != NULL)
2900 {
2901 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002902 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002904 wcsncpy(buf, p, _MAX_PATH);
2905 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002906 vim_free(p);
2907
2908 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2909 {
2910 q = utf16_to_enc(buf, NULL);
2911 if (q != NULL)
2912 {
2913 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2914 vim_free(q);
2915 return;
2916 }
2917 }
2918 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002919 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002920 }
2921#endif
2922
2923 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2924 * So we should check this after calling wide function. */
2925 if (flen > _MAX_PATH)
2926 return;
2927
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002929 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 ptrue = szTrueName;
2931
2932 if (isalpha(porig[0]) && porig[1] == ':')
2933 {
2934 /* copy leading drive letter */
2935 *ptrue++ = *porig++;
2936 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002938 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939
2940 while (*porig != NUL)
2941 {
2942 /* copy \ characters */
2943 while (*porig == psepc)
2944 *ptrue++ = *porig++;
2945
2946 ptruePrev = ptrue;
2947 porigPrev = porig;
2948 while (*porig != NUL && *porig != psepc)
2949 {
2950#ifdef FEAT_MBYTE
2951 int l;
2952
2953 if (enc_dbcs)
2954 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002955 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 while (--l >= 0)
2957 *ptrue++ = *porig++;
2958 }
2959 else
2960#endif
2961 *ptrue++ = *porig++;
2962 }
2963 *ptrue = NUL;
2964
Bram Moolenaar464c9252010-10-13 20:37:41 +02002965 /* To avoid a slow failure append "\*" when searching a directory,
2966 * server or network share. */
2967 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002968 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002969 if (*porig == psepc && slen + 2 < _MAX_PATH)
2970 STRCPY(szTrueNameTemp + slen, "\\*");
2971
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972 /* Skip "", "." and "..". */
2973 if (ptrue > ptruePrev
2974 && (ptruePrev[0] != '.'
2975 || (ptruePrev[1] != NUL
2976 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002977 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978 != INVALID_HANDLE_VALUE)
2979 {
2980 c = *porig;
2981 *porig = NUL;
2982
2983 /* Only use the match when it's the same name (ignoring case) or
2984 * expansion is allowed and there is a match with the short name
2985 * and there is enough room. */
2986 if (_stricoll(porigPrev, fb.cFileName) == 0
2987 || (len > 0
2988 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2989 && (int)(ptruePrev - szTrueName)
2990 + (int)strlen(fb.cFileName) < len)))
2991 {
2992 STRCPY(ptruePrev, fb.cFileName);
2993
2994 /* Look for exact match and prefer it if found. Must be a
2995 * long name, otherwise there would be only one match. */
2996 while (FindNextFile(hFind, &fb))
2997 {
2998 if (*fb.cAlternateFileName != NUL
2999 && (strcoll(porigPrev, fb.cFileName) == 0
3000 || (len > 0
3001 && (_stricoll(porigPrev,
3002 fb.cAlternateFileName) == 0
3003 && (int)(ptruePrev - szTrueName)
3004 + (int)strlen(fb.cFileName) < len))))
3005 {
3006 STRCPY(ptruePrev, fb.cFileName);
3007 break;
3008 }
3009 }
3010 }
3011 FindClose(hFind);
3012 *porig = c;
3013 ptrue = ptruePrev + strlen(ptruePrev);
3014 }
3015 }
3016
3017 STRCPY(name, szTrueName);
3018}
3019
3020
3021/*
3022 * Insert user name in s[len].
3023 */
3024 int
3025mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003026 char_u *s,
3027 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003029 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 DWORD cch = sizeof szUserName;
3031
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003032#ifdef FEAT_MBYTE
3033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3034 {
3035 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3036 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3037
3038 if (GetUserNameW(wszUserName, &wcch))
3039 {
3040 char_u *p = utf16_to_enc(wszUserName, NULL);
3041
3042 if (p != NULL)
3043 {
3044 vim_strncpy(s, p, len - 1);
3045 vim_free(p);
3046 return OK;
3047 }
3048 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003049 }
3050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 if (GetUserName(szUserName, &cch))
3052 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003053 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 return OK;
3055 }
3056 s[0] = NUL;
3057 return FAIL;
3058}
3059
3060
3061/*
3062 * Insert host name in s[len].
3063 */
3064 void
3065mch_get_host_name(
3066 char_u *s,
3067 int len)
3068{
3069 DWORD cch = len;
3070
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003071#ifdef FEAT_MBYTE
3072 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3073 {
3074 WCHAR wszHostName[256 + 1];
3075 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3076
3077 if (GetComputerNameW(wszHostName, &wcch))
3078 {
3079 char_u *p = utf16_to_enc(wszHostName, NULL);
3080
3081 if (p != NULL)
3082 {
3083 vim_strncpy(s, p, len - 1);
3084 vim_free(p);
3085 return;
3086 }
3087 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003088 }
3089#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003090 if (!GetComputerName((LPSTR)s, &cch))
3091 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092}
3093
3094
3095/*
3096 * return process ID
3097 */
3098 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003099mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100{
3101 return (long)GetCurrentProcessId();
3102}
3103
3104
3105/*
3106 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3107 * Return OK for success, FAIL for failure.
3108 */
3109 int
3110mch_dirname(
3111 char_u *buf,
3112 int len)
3113{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003114 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003115 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003116
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 /*
3118 * Originally this was:
3119 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3120 * But the Win32s known bug list says that getcwd() doesn't work
3121 * so use the Win32 system call instead. <Negri>
3122 */
3123#ifdef FEAT_MBYTE
3124 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 }
3155#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003156 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3157 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003158 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3159 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3160 // Failed to get long path name or it's too long: fall back to the
3161 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003162 return OK;
3163
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003164 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003165 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166}
3167
3168/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003169 * Get file permissions for "name".
3170 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 */
3172 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003173mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003175 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003176 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003178 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003179 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180}
3181
3182
3183/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003184 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003185 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 */
3188 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003189mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003191 long n = -1;
3192
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193#ifdef FEAT_MBYTE
3194 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3195 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003196 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197
3198 if (p != NULL)
3199 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003202 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003203 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 }
3205 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003206 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003208 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209 if (n == -1)
3210 return FAIL;
3211
3212 win32_set_archive(name);
3213
3214 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215}
3216
3217/*
3218 * Set hidden flag for "name".
3219 */
3220 void
3221mch_hide(char_u *name)
3222{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223 int attrs = win32_getattrs(name);
3224 if (attrs == -1)
3225 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 attrs |= FILE_ATTRIBUTE_HIDDEN;
3228 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229}
3230
3231/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003232 * Return TRUE if file "name" exists and is hidden.
3233 */
3234 int
3235mch_ishidden(char_u *name)
3236{
3237 int f = win32_getattrs(name);
3238
3239 if (f == -1)
3240 return FALSE; /* file does not exist at all */
3241
3242 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3243}
3244
3245/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 * return TRUE if "name" is a directory
3247 * return FALSE if "name" is not a directory or upon error
3248 */
3249 int
3250mch_isdir(char_u *name)
3251{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003252 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253
3254 if (f == -1)
3255 return FALSE; /* file does not exist at all */
3256
3257 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3258}
3259
3260/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003261 * return TRUE if "name" is a directory, NOT a symlink to a directory
3262 * return FALSE if "name" is not a directory
3263 * return FALSE for error
3264 */
3265 int
3266mch_isrealdir(char_u *name)
3267{
3268 return mch_isdir(name) && !mch_is_symbolic_link(name);
3269}
3270
3271/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003272 * Create directory "name".
3273 * Return 0 on success, -1 on error.
3274 */
3275 int
3276mch_mkdir(char_u *name)
3277{
3278#ifdef FEAT_MBYTE
3279 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3280 {
3281 WCHAR *p;
3282 int retval;
3283
3284 p = enc_to_utf16(name, NULL);
3285 if (p == NULL)
3286 return -1;
3287 retval = _wmkdir(p);
3288 vim_free(p);
3289 return retval;
3290 }
3291#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003292 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003293}
3294
3295/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003296 * Delete directory "name".
3297 * Return 0 on success, -1 on error.
3298 */
3299 int
3300mch_rmdir(char_u *name)
3301{
3302#ifdef FEAT_MBYTE
3303 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3304 {
3305 WCHAR *p;
3306 int retval;
3307
3308 p = enc_to_utf16(name, NULL);
3309 if (p == NULL)
3310 return -1;
3311 retval = _wrmdir(p);
3312 vim_free(p);
3313 return retval;
3314 }
3315#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003316 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003317}
3318
3319/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 * Return TRUE if file "fname" has more than one link.
3321 */
3322 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003323mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003324{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003325 BY_HANDLE_FILE_INFORMATION info;
3326
3327 return win32_fileinfo(fname, &info) == FILEINFO_OK
3328 && info.nNumberOfLinks > 1;
3329}
3330
3331/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003332 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003333 */
3334 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003335mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336{
3337 HANDLE hFind;
3338 int res = FALSE;
3339 WIN32_FIND_DATAA findDataA;
3340 DWORD fileFlags = 0, reparseTag = 0;
3341#ifdef FEAT_MBYTE
3342 WCHAR *wn = NULL;
3343 WIN32_FIND_DATAW findDataW;
3344
3345 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003346 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 if (wn != NULL)
3348 {
3349 hFind = FindFirstFileW(wn, &findDataW);
3350 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003351 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003352 {
3353 fileFlags = findDataW.dwFileAttributes;
3354 reparseTag = findDataW.dwReserved0;
3355 }
3356 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003357 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003359 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003360 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003361 if (hFind != INVALID_HANDLE_VALUE)
3362 {
3363 fileFlags = findDataA.dwFileAttributes;
3364 reparseTag = findDataA.dwReserved0;
3365 }
3366 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367
3368 if (hFind != INVALID_HANDLE_VALUE)
3369 FindClose(hFind);
3370
3371 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003372 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3373 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 res = TRUE;
3375
3376 return res;
3377}
3378
3379/*
3380 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3381 * link.
3382 */
3383 int
3384mch_is_linked(char_u *fname)
3385{
3386 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3387 return TRUE;
3388 return FALSE;
3389}
3390
3391/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003392 * Get the by-handle-file-information for "fname".
3393 * Returns FILEINFO_OK when OK.
3394 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3395 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3396 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3397 */
3398 int
3399win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3400{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003401 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003402 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003403#ifdef FEAT_MBYTE
3404 WCHAR *wn = NULL;
3405
3406 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003407 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003408 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003409 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003410 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412 if (wn != NULL)
3413 {
3414 hFile = CreateFileW(wn, /* 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 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003422 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003423 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003424#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003425 hFile = CreateFile((LPCSTR)fname, /* file name */
3426 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003427 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428 NULL, /* security descriptor */
3429 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003430 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003431 NULL); /* handle to template file */
3432
3433 if (hFile != INVALID_HANDLE_VALUE)
3434 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003435 if (GetFileInformationByHandle(hFile, info) != 0)
3436 res = FILEINFO_OK;
3437 else
3438 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439 CloseHandle(hFile);
3440 }
3441
Bram Moolenaar03f48552006-02-28 23:52:23 +00003442 return res;
3443}
3444
3445/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446 * get file attributes for `name'
3447 * -1 : error
3448 * else FILE_ATTRIBUTE_* defined in winnt.h
3449 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003450 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003451win32_getattrs(char_u *name)
3452{
3453 int attr;
3454#ifdef FEAT_MBYTE
3455 WCHAR *p = NULL;
3456
3457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3458 p = enc_to_utf16(name, NULL);
3459
3460 if (p != NULL)
3461 {
3462 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003463 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003464 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003465 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466#endif
3467 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003468
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003469 return attr;
3470}
3471
3472/*
3473 * set file attributes for `name' to `attrs'
3474 *
3475 * return -1 for failure, 0 otherwise
3476 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003477 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478win32_setattrs(char_u *name, int attrs)
3479{
3480 int res;
3481#ifdef FEAT_MBYTE
3482 WCHAR *p = NULL;
3483
3484 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3485 p = enc_to_utf16(name, NULL);
3486
3487 if (p != NULL)
3488 {
3489 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003490 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003492 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003493#endif
3494 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003495
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003496 return res ? 0 : -1;
3497}
3498
3499/*
3500 * Set archive flag for "name".
3501 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003502 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003503win32_set_archive(char_u *name)
3504{
3505 int attrs = win32_getattrs(name);
3506 if (attrs == -1)
3507 return -1;
3508
3509 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3510 return win32_setattrs(name, attrs);
3511}
3512
3513/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 * Return TRUE if file or directory "name" is writable (not readonly).
3515 * Strange semantics of Win32: a readonly directory is writable, but you can't
3516 * delete a file. Let's say this means it is writable.
3517 */
3518 int
3519mch_writable(char_u *name)
3520{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003521 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003523 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3524 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525}
3526
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003528 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003529 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003530 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3531 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 */
3533 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003534mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003536 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003537 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003538 char_u *p;
3539
3540 if (len >= _MAX_PATH) /* safety check */
3541 return FALSE;
3542
3543 /* If there already is an extension try using the name directly. Also do
3544 * this with a Unix-shell like 'shell'. */
3545 if (vim_strchr(gettail(name), '.') != NULL
3546 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003547 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003548 return TRUE;
3549
3550 /*
3551 * Loop over all extensions in $PATHEXT.
3552 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003553 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003554 p = mch_getenv("PATHEXT");
3555 if (p == NULL)
3556 p = (char_u *)".com;.exe;.bat;.cmd";
3557 while (*p)
3558 {
3559 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3560 {
3561 /* A single "." means no extension is added. */
3562 buf[len] = NUL;
3563 ++p;
3564 if (*p)
3565 ++p;
3566 }
3567 else
3568 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003569 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003570 return TRUE;
3571 }
3572 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574
3575/*
3576 * Check what "name" is:
3577 * NODE_NORMAL: file or directory (or doesn't exist)
3578 * NODE_WRITABLE: writable device, socket, fifo, etc.
3579 * NODE_OTHER: non-writable things
3580 */
3581 int
3582mch_nodetype(char_u *name)
3583{
3584 HANDLE hFile;
3585 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003586#ifdef FEAT_MBYTE
3587 WCHAR *wn = NULL;
3588#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589
Bram Moolenaar043545e2006-10-10 16:44:07 +00003590 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3591 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3592 * here. */
3593 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3594 return NODE_WRITABLE;
3595
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003596#ifdef FEAT_MBYTE
3597 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003598 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003599
3600 if (wn != NULL)
3601 {
3602 hFile = CreateFileW(wn, /* file name */
3603 GENERIC_WRITE, /* access mode */
3604 0, /* share mode */
3605 NULL, /* security descriptor */
3606 OPEN_EXISTING, /* creation disposition */
3607 0, /* file attributes */
3608 NULL); /* handle to template file */
3609 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003610 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003611 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003612#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003613 hFile = CreateFile((LPCSTR)name, /* file name */
3614 GENERIC_WRITE, /* access mode */
3615 0, /* share mode */
3616 NULL, /* security descriptor */
3617 OPEN_EXISTING, /* creation disposition */
3618 0, /* file attributes */
3619 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620
3621 if (hFile == INVALID_HANDLE_VALUE)
3622 return NODE_NORMAL;
3623
3624 type = GetFileType(hFile);
3625 CloseHandle(hFile);
3626 if (type == FILE_TYPE_CHAR)
3627 return NODE_WRITABLE;
3628 if (type == FILE_TYPE_DISK)
3629 return NODE_NORMAL;
3630 return NODE_OTHER;
3631}
3632
3633#ifdef HAVE_ACL
3634struct my_acl
3635{
3636 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3637 PSID pSidOwner;
3638 PSID pSidGroup;
3639 PACL pDacl;
3640 PACL pSacl;
3641};
3642#endif
3643
3644/*
3645 * Return a pointer to the ACL of file "fname" in allocated memory.
3646 * Return NULL if the ACL is not available for whatever reason.
3647 */
3648 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003649mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003650{
3651#ifndef HAVE_ACL
3652 return (vim_acl_T)NULL;
3653#else
3654 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003655 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003657 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3658 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003660# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003661 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003662
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003663 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3664 wn = enc_to_utf16(fname, NULL);
3665 if (wn != NULL)
3666 {
3667 /* Try to retrieve the entire security descriptor. */
3668 err = GetNamedSecurityInfoW(
3669 wn, // Abstract filename
3670 SE_FILE_OBJECT, // File Object
3671 OWNER_SECURITY_INFORMATION |
3672 GROUP_SECURITY_INFORMATION |
3673 DACL_SECURITY_INFORMATION |
3674 SACL_SECURITY_INFORMATION,
3675 &p->pSidOwner, // Ownership information.
3676 &p->pSidGroup, // Group membership.
3677 &p->pDacl, // Discretionary information.
3678 &p->pSacl, // For auditing purposes.
3679 &p->pSecurityDescriptor);
3680 if (err == ERROR_ACCESS_DENIED ||
3681 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003683 /* Retrieve only DACL. */
3684 (void)GetNamedSecurityInfoW(
3685 wn,
3686 SE_FILE_OBJECT,
3687 DACL_SECURITY_INFORMATION,
3688 NULL,
3689 NULL,
3690 &p->pDacl,
3691 NULL,
3692 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003693 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003694 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003695 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003696 mch_free_acl((vim_acl_T)p);
3697 p = NULL;
3698 }
3699 vim_free(wn);
3700 }
3701 else
3702# endif
3703 {
3704 /* Try to retrieve the entire security descriptor. */
3705 err = GetNamedSecurityInfo(
3706 (LPSTR)fname, // Abstract filename
3707 SE_FILE_OBJECT, // File Object
3708 OWNER_SECURITY_INFORMATION |
3709 GROUP_SECURITY_INFORMATION |
3710 DACL_SECURITY_INFORMATION |
3711 SACL_SECURITY_INFORMATION,
3712 &p->pSidOwner, // Ownership information.
3713 &p->pSidGroup, // Group membership.
3714 &p->pDacl, // Discretionary information.
3715 &p->pSacl, // For auditing purposes.
3716 &p->pSecurityDescriptor);
3717 if (err == ERROR_ACCESS_DENIED ||
3718 err == ERROR_PRIVILEGE_NOT_HELD)
3719 {
3720 /* Retrieve only DACL. */
3721 (void)GetNamedSecurityInfo(
3722 (LPSTR)fname,
3723 SE_FILE_OBJECT,
3724 DACL_SECURITY_INFORMATION,
3725 NULL,
3726 NULL,
3727 &p->pDacl,
3728 NULL,
3729 &p->pSecurityDescriptor);
3730 }
3731 if (p->pSecurityDescriptor == NULL)
3732 {
3733 mch_free_acl((vim_acl_T)p);
3734 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 }
3736 }
3737 }
3738
3739 return (vim_acl_T)p;
3740#endif
3741}
3742
Bram Moolenaar27515922013-06-29 15:36:26 +02003743#ifdef HAVE_ACL
3744/*
3745 * Check if "acl" contains inherited ACE.
3746 */
3747 static BOOL
3748is_acl_inherited(PACL acl)
3749{
3750 DWORD i;
3751 ACL_SIZE_INFORMATION acl_info;
3752 PACCESS_ALLOWED_ACE ace;
3753
3754 acl_info.AceCount = 0;
3755 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3756 for (i = 0; i < acl_info.AceCount; i++)
3757 {
3758 GetAce(acl, i, (LPVOID *)&ace);
3759 if (ace->Header.AceFlags & INHERITED_ACE)
3760 return TRUE;
3761 }
3762 return FALSE;
3763}
3764#endif
3765
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766/*
3767 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3768 * Errors are ignored.
3769 * This must only be called with "acl" equal to what mch_get_acl() returned.
3770 */
3771 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003772mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773{
3774#ifdef HAVE_ACL
3775 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003776 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003778 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003779 {
3780# ifdef FEAT_MBYTE
3781 WCHAR *wn = NULL;
3782# endif
3783
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
3801# ifdef FEAT_MBYTE
3802 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3803 wn = enc_to_utf16(fname, NULL);
3804 if (wn != NULL)
3805 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003806 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003807 wn, // Abstract filename
3808 SE_FILE_OBJECT, // File Object
3809 sec_info,
3810 p->pSidOwner, // Ownership information.
3811 p->pSidGroup, // Group membership.
3812 p->pDacl, // Discretionary information.
3813 p->pSacl // For auditing purposes.
3814 );
3815 vim_free(wn);
3816 }
3817 else
3818# endif
3819 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003820 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003821 (LPSTR)fname, // Abstract filename
3822 SE_FILE_OBJECT, // File Object
3823 sec_info,
3824 p->pSidOwner, // Ownership information.
3825 p->pSidGroup, // Group membership.
3826 p->pDacl, // Discretionary information.
3827 p->pSacl // For auditing purposes.
3828 );
3829 }
3830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831#endif
3832}
3833
3834 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003835mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836{
3837#ifdef HAVE_ACL
3838 struct my_acl *p = (struct my_acl *)acl;
3839
3840 if (p != NULL)
3841 {
3842 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3843 vim_free(p);
3844 }
3845#endif
3846}
3847
3848#ifndef FEAT_GUI_W32
3849
3850/*
3851 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3852 */
3853 static BOOL WINAPI
3854handler_routine(
3855 DWORD dwCtrlType)
3856{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003857 INPUT_RECORD ir;
3858 DWORD out;
3859
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 switch (dwCtrlType)
3861 {
3862 case CTRL_C_EVENT:
3863 if (ctrl_c_interrupts)
3864 g_fCtrlCPressed = TRUE;
3865 return TRUE;
3866
3867 case CTRL_BREAK_EVENT:
3868 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003869 ctrl_break_was_pressed = TRUE;
3870 /* ReadConsoleInput is blocking, send a key event to continue. */
3871 ir.EventType = KEY_EVENT;
3872 ir.Event.KeyEvent.bKeyDown = TRUE;
3873 ir.Event.KeyEvent.wRepeatCount = 1;
3874 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3875 ir.Event.KeyEvent.wVirtualScanCode = 0;
3876 ir.Event.KeyEvent.dwControlKeyState = 0;
3877 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3878 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879 return TRUE;
3880
3881 /* fatal events: shut down gracefully */
3882 case CTRL_CLOSE_EVENT:
3883 case CTRL_LOGOFF_EVENT:
3884 case CTRL_SHUTDOWN_EVENT:
3885 windgoto((int)Rows - 1, 0);
3886 g_fForceExit = TRUE;
3887
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003888 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 (dwCtrlType == CTRL_CLOSE_EVENT
3890 ? _("close")
3891 : dwCtrlType == CTRL_LOGOFF_EVENT
3892 ? _("logoff")
3893 : _("shutdown")));
3894#ifdef DEBUG
3895 OutputDebugString(IObuff);
3896#endif
3897
3898 preserve_exit(); /* output IObuff, preserve files and exit */
3899
3900 return TRUE; /* not reached */
3901
3902 default:
3903 return FALSE;
3904 }
3905}
3906
3907
3908/*
3909 * set the tty in (raw) ? "raw" : "cooked" mode
3910 */
3911 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003912mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913{
3914 DWORD cmodein;
3915 DWORD cmodeout;
3916 BOOL bEnableHandler;
3917
3918 GetConsoleMode(g_hConIn, &cmodein);
3919 GetConsoleMode(g_hConOut, &cmodeout);
3920 if (tmode == TMODE_RAW)
3921 {
3922 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3923 ENABLE_ECHO_INPUT);
3924#ifdef FEAT_MOUSE
3925 if (g_fMouseActive)
3926 cmodein |= ENABLE_MOUSE_INPUT;
3927#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003928 cmodeout &= ~(
3929#ifdef FEAT_TERMGUICOLORS
3930 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3931 * VTP. */
3932 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3933#else
3934 ENABLE_PROCESSED_OUTPUT |
3935#endif
3936 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937 bEnableHandler = TRUE;
3938 }
3939 else /* cooked */
3940 {
3941 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3942 ENABLE_ECHO_INPUT);
3943 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3944 bEnableHandler = FALSE;
3945 }
3946 SetConsoleMode(g_hConIn, cmodein);
3947 SetConsoleMode(g_hConOut, cmodeout);
3948 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3949
3950#ifdef MCH_WRITE_DUMP
3951 if (fdDump)
3952 {
3953 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3954 tmode == TMODE_RAW ? "raw" :
3955 tmode == TMODE_COOK ? "cooked" : "normal",
3956 cmodein, cmodeout);
3957 fflush(fdDump);
3958 }
3959#endif
3960}
3961
3962
3963/*
3964 * Get the size of the current window in `Rows' and `Columns'
3965 * Return OK when size could be determined, FAIL otherwise.
3966 */
3967 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003968mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969{
3970 CONSOLE_SCREEN_BUFFER_INFO csbi;
3971
3972 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3973 {
3974 /*
3975 * For some reason, we are trying to get the screen dimensions
3976 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3977 * variables are really intended to mean the size of Vim screen
3978 * while in termcap mode.
3979 */
3980 Rows = g_cbTermcap.Info.dwSize.Y;
3981 Columns = g_cbTermcap.Info.dwSize.X;
3982 }
3983 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3984 {
3985 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3986 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3987 }
3988 else
3989 {
3990 Rows = 25;
3991 Columns = 80;
3992 }
3993 return OK;
3994}
3995
3996/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003997 * Resize console buffer to 'COORD'
3998 */
3999 static void
4000ResizeConBuf(
4001 HANDLE hConsole,
4002 COORD coordScreen)
4003{
4004 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4005 {
4006#ifdef MCH_WRITE_DUMP
4007 if (fdDump)
4008 {
4009 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4010 GetLastError());
4011 fflush(fdDump);
4012 }
4013#endif
4014 }
4015}
4016
4017/*
4018 * Resize console window size to 'srWindowRect'
4019 */
4020 static void
4021ResizeWindow(
4022 HANDLE hConsole,
4023 SMALL_RECT srWindowRect)
4024{
4025 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4026 {
4027#ifdef MCH_WRITE_DUMP
4028 if (fdDump)
4029 {
4030 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4031 GetLastError());
4032 fflush(fdDump);
4033 }
4034#endif
4035 }
4036}
4037
4038/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039 * Set a console window to `xSize' * `ySize'
4040 */
4041 static void
4042ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004043 HANDLE hConsole,
4044 int xSize,
4045 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046{
4047 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4048 SMALL_RECT srWindowRect; /* hold the new console size */
4049 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004050 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051
4052#ifdef MCH_WRITE_DUMP
4053 if (fdDump)
4054 {
4055 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4056 fflush(fdDump);
4057 }
4058#endif
4059
4060 /* get the largest size we can size the console window to */
4061 coordScreen = GetLargestConsoleWindowSize(hConsole);
4062
4063 /* define the new console window size and scroll position */
4064 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4065 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4066 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4067
4068 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4069 {
4070 int sx, sy;
4071
4072 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4073 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4074 if (sy < ySize || sx < xSize)
4075 {
4076 /*
4077 * Increasing number of lines/columns, do buffer first.
4078 * Use the maximal size in x and y direction.
4079 */
4080 if (sy < ySize)
4081 coordScreen.Y = ySize;
4082 else
4083 coordScreen.Y = sy;
4084 if (sx < xSize)
4085 coordScreen.X = xSize;
4086 else
4087 coordScreen.X = sx;
4088 SetConsoleScreenBufferSize(hConsole, coordScreen);
4089 }
4090 }
4091
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004092 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 coordScreen.X = xSize;
4094 coordScreen.Y = ySize;
4095
Bram Moolenaar2551c032018-08-23 22:38:31 +02004096 // In the new console call API, only the first time in reverse order
4097 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004099 ResizeWindow(hConsole, srWindowRect);
4100 ResizeConBuf(hConsole, coordScreen);
4101 }
4102 else
4103 {
4104 ResizeConBuf(hConsole, coordScreen);
4105 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004106 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 }
4108}
4109
4110
4111/*
4112 * Set the console window to `Rows' * `Columns'
4113 */
4114 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004115mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116{
4117 COORD coordScreen;
4118
4119 /* Don't change window size while still starting up */
4120 if (suppress_winsize != 0)
4121 {
4122 suppress_winsize = 2;
4123 return;
4124 }
4125
4126 if (term_console)
4127 {
4128 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4129
4130 /* Clamp Rows and Columns to reasonable values */
4131 if (Rows > coordScreen.Y)
4132 Rows = coordScreen.Y;
4133 if (Columns > coordScreen.X)
4134 Columns = coordScreen.X;
4135
4136 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4137 }
4138}
4139
4140/*
4141 * Rows and/or Columns has changed.
4142 */
4143 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004144mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145{
4146 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4147}
4148
4149
4150/*
4151 * Called when started up, to set the winsize that was delayed.
4152 */
4153 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004154mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155{
4156 if (suppress_winsize == 2)
4157 {
4158 suppress_winsize = 0;
4159 mch_set_shellsize();
4160 shell_resized();
4161 }
4162 suppress_winsize = 0;
4163}
4164#endif /* FEAT_GUI_W32 */
4165
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 static BOOL
4167vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004168 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004169 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004170 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004171 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004172 PROCESS_INFORMATION *pi,
4173 LPVOID *env,
4174 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004175{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004176#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004177 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4178 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004179 BOOL ret;
4180 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004182 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4183 if (wcmd == NULL)
4184 goto fallback;
4185 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004186 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004187 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4188 if (wcwd == NULL)
4189 {
4190 vim_free(wcmd);
4191 goto fallback;
4192 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004193 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004194
4195 ret = CreateProcessW(
4196 NULL, /* Executable name */
4197 wcmd, /* Command to execute */
4198 NULL, /* Process security attributes */
4199 NULL, /* Thread security attributes */
4200 inherit_handles, /* Inherit handles */
4201 flags, /* Creation flags */
4202 env, /* Environment */
4203 wcwd, /* Current directory */
4204 (LPSTARTUPINFOW)si, /* Startup information */
4205 pi); /* Process information */
4206 vim_free(wcmd);
4207 if (wcwd != NULL)
4208 vim_free(wcwd);
4209 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004210 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004211fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004212#endif
4213 return CreateProcess(
4214 NULL, /* Executable name */
4215 cmd, /* Command to execute */
4216 NULL, /* Process security attributes */
4217 NULL, /* Thread security attributes */
4218 inherit_handles, /* Inherit handles */
4219 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004220 env, /* Environment */
4221 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004222 si, /* Startup information */
4223 pi); /* Process information */
4224}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225
4226
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004227 static HINSTANCE
4228vim_shell_execute(
4229 char *cmd,
4230 INT n_show_cmd)
4231{
4232#ifdef FEAT_MBYTE
4233 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4234 {
4235 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4236 if (wcmd != NULL)
4237 {
4238 HINSTANCE ret;
4239 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4240 vim_free(wcmd);
4241 return ret;
4242 }
4243 }
4244#endif
4245 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4246}
4247
4248
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249#if defined(FEAT_GUI_W32) || defined(PROTO)
4250
4251/*
4252 * Specialised version of system() for Win32 GUI mode.
4253 * This version proceeds as follows:
4254 * 1. Create a console window for use by the subprocess
4255 * 2. Run the subprocess (it gets the allocated console by default)
4256 * 3. Wait for the subprocess to terminate and get its exit code
4257 * 4. Prompt the user to press a key to close the console window
4258 */
4259 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004260mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261{
4262 STARTUPINFO si;
4263 PROCESS_INFORMATION pi;
4264 DWORD ret = 0;
4265 HWND hwnd = GetFocus();
4266
4267 si.cb = sizeof(si);
4268 si.lpReserved = NULL;
4269 si.lpDesktop = NULL;
4270 si.lpTitle = NULL;
4271 si.dwFlags = STARTF_USESHOWWINDOW;
4272 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004273 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004274 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004276 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004277 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004278 else
4279 si.wShowWindow = SW_SHOWNORMAL;
4280 si.cbReserved2 = 0;
4281 si.lpReserved2 = NULL;
4282
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004284 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004285 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4286 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287
4288 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 {
4290#ifdef FEAT_GUI
4291 int delay = 1;
4292
4293 /* Keep updating the window while waiting for the shell to finish. */
4294 for (;;)
4295 {
4296 MSG msg;
4297
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004298 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 {
4300 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004301 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004302 delay = 1;
4303 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 }
4305 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4306 break;
4307
4308 /* We start waiting for a very short time and then increase it, so
4309 * that we respond quickly when the process is quick, and don't
4310 * consume too much overhead when it's slow. */
4311 if (delay < 50)
4312 delay += 10;
4313 }
4314#else
4315 WaitForSingleObject(pi.hProcess, INFINITE);
4316#endif
4317
4318 /* Get the command exit code */
4319 GetExitCodeProcess(pi.hProcess, &ret);
4320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321
4322 /* Close the handles to the subprocess, so that it goes away */
4323 CloseHandle(pi.hThread);
4324 CloseHandle(pi.hProcess);
4325
4326 /* Try to get input focus back. Doesn't always work though. */
4327 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4328
4329 return ret;
4330}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004331
4332/*
4333 * Thread launched by the gui to send the current buffer data to the
4334 * process. This way avoid to hang up vim totally if the children
4335 * process take a long time to process the lines.
4336 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004337 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004338sub_process_writer(LPVOID param)
4339{
4340 HANDLE g_hChildStd_IN_Wr = param;
4341 linenr_T lnum = curbuf->b_op_start.lnum;
4342 DWORD len = 0;
4343 DWORD l;
4344 char_u *lp = ml_get(lnum);
4345 char_u *s;
4346 int written = 0;
4347
4348 for (;;)
4349 {
4350 l = (DWORD)STRLEN(lp + written);
4351 if (l == 0)
4352 len = 0;
4353 else if (lp[written] == NL)
4354 {
4355 /* NL -> NUL translation */
4356 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4357 }
4358 else
4359 {
4360 s = vim_strchr(lp + written, NL);
4361 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4362 s == NULL ? l : (DWORD)(s - (lp + written)),
4363 &len, NULL);
4364 }
4365 if (len == (int)l)
4366 {
4367 /* Finished a line, add a NL, unless this line should not have
4368 * one. */
4369 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004370 || (!curbuf->b_p_bin
4371 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372 || (lnum != curbuf->b_no_eol_lnum
4373 && (lnum != curbuf->b_ml.ml_line_count
4374 || curbuf->b_p_eol)))
4375 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004376 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4377 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004378 }
4379
4380 ++lnum;
4381 if (lnum > curbuf->b_op_end.lnum)
4382 break;
4383
4384 lp = ml_get(lnum);
4385 written = 0;
4386 }
4387 else if (len > 0)
4388 written += len;
4389 }
4390
4391 /* finished all the lines, close pipe */
4392 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004393 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394}
4395
4396
4397# define BUFLEN 100 /* length for buffer, stolen from unix version */
4398
4399/*
4400 * This function read from the children's stdout and write the
4401 * data on screen or in the buffer accordingly.
4402 */
4403 static void
4404dump_pipe(int options,
4405 HANDLE g_hChildStd_OUT_Rd,
4406 garray_T *ga,
4407 char_u buffer[],
4408 DWORD *buffer_off)
4409{
4410 DWORD availableBytes = 0;
4411 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004412 int ret;
4413 DWORD len;
4414 DWORD toRead;
4415 int repeatCount;
4416
4417 /* we query the pipe to see if there is any data to read
4418 * to avoid to perform a blocking read */
4419 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4420 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004421 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 NULL, /* number of read bytes */
4423 &availableBytes, /* available bytes total */
4424 NULL); /* byteLeft */
4425
4426 repeatCount = 0;
4427 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004428 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004429 {
4430 repeatCount++;
4431 toRead =
4432# ifdef FEAT_MBYTE
4433 (DWORD)(BUFLEN - *buffer_off);
4434# else
4435 (DWORD)BUFLEN;
4436# endif
4437 toRead = availableBytes < toRead ? availableBytes : toRead;
4438 ReadFile(g_hChildStd_OUT_Rd, buffer
4439# ifdef FEAT_MBYTE
4440 + *buffer_off, toRead
4441# else
4442 , toRead
4443# endif
4444 , &len, NULL);
4445
4446 /* If we haven't read anything, there is a problem */
4447 if (len == 0)
4448 break;
4449
4450 availableBytes -= len;
4451
4452 if (options & SHELL_READ)
4453 {
4454 /* Do NUL -> NL translation, append NL separated
4455 * lines to the current buffer. */
4456 for (i = 0; i < len; ++i)
4457 {
4458 if (buffer[i] == NL)
4459 append_ga_line(ga);
4460 else if (buffer[i] == NUL)
4461 ga_append(ga, NL);
4462 else
4463 ga_append(ga, buffer[i]);
4464 }
4465 }
4466# ifdef FEAT_MBYTE
4467 else if (has_mbyte)
4468 {
4469 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004470 int c;
4471 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472
4473 len += *buffer_off;
4474 buffer[len] = NUL;
4475
4476 /* Check if the last character in buffer[] is
4477 * incomplete, keep these bytes for the next
4478 * round. */
4479 for (p = buffer; p < buffer + len; p += l)
4480 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004481 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482 if (l == 0)
4483 l = 1; /* NUL byte? */
4484 else if (MB_BYTE2LEN(*p) != l)
4485 break;
4486 }
4487 if (p == buffer) /* no complete character */
4488 {
4489 /* avoid getting stuck at an illegal byte */
4490 if (len >= 12)
4491 ++p;
4492 else
4493 {
4494 *buffer_off = len;
4495 return;
4496 }
4497 }
4498 c = *p;
4499 *p = NUL;
4500 msg_puts(buffer);
4501 if (p < buffer + len)
4502 {
4503 *p = c;
4504 *buffer_off = (DWORD)((buffer + len) - p);
4505 mch_memmove(buffer, p, *buffer_off);
4506 return;
4507 }
4508 *buffer_off = 0;
4509 }
4510# endif /* FEAT_MBYTE */
4511 else
4512 {
4513 buffer[len] = NUL;
4514 msg_puts(buffer);
4515 }
4516
4517 windgoto(msg_row, msg_col);
4518 cursor_on();
4519 out_flush();
4520 }
4521}
4522
4523/*
4524 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4525 * for communication and doesn't open any new window.
4526 */
4527 static int
4528mch_system_piped(char *cmd, int options)
4529{
4530 STARTUPINFO si;
4531 PROCESS_INFORMATION pi;
4532 DWORD ret = 0;
4533
4534 HANDLE g_hChildStd_IN_Rd = NULL;
4535 HANDLE g_hChildStd_IN_Wr = NULL;
4536 HANDLE g_hChildStd_OUT_Rd = NULL;
4537 HANDLE g_hChildStd_OUT_Wr = NULL;
4538
4539 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4540 DWORD len;
4541
4542 /* buffer used to receive keys */
4543 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4544 int ta_len = 0; /* valid bytes in ta_buf[] */
4545
4546 DWORD i;
4547 int c;
4548 int noread_cnt = 0;
4549 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004550 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004551 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004552 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004553
4554 SECURITY_ATTRIBUTES saAttr;
4555
4556 /* Set the bInheritHandle flag so pipe handles are inherited. */
4557 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4558 saAttr.bInheritHandle = TRUE;
4559 saAttr.lpSecurityDescriptor = NULL;
4560
4561 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4562 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004563 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004564 /* Create a pipe for the child process's STDIN. */
4565 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4566 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004567 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004568 {
4569 CloseHandle(g_hChildStd_IN_Rd);
4570 CloseHandle(g_hChildStd_IN_Wr);
4571 CloseHandle(g_hChildStd_OUT_Rd);
4572 CloseHandle(g_hChildStd_OUT_Wr);
4573 MSG_PUTS(_("\nCannot create pipes\n"));
4574 }
4575
4576 si.cb = sizeof(si);
4577 si.lpReserved = NULL;
4578 si.lpDesktop = NULL;
4579 si.lpTitle = NULL;
4580 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4581
4582 /* set-up our file redirection */
4583 si.hStdError = g_hChildStd_OUT_Wr;
4584 si.hStdOutput = g_hChildStd_OUT_Wr;
4585 si.hStdInput = g_hChildStd_IN_Rd;
4586 si.wShowWindow = SW_HIDE;
4587 si.cbReserved2 = 0;
4588 si.lpReserved2 = NULL;
4589
4590 if (options & SHELL_READ)
4591 ga_init2(&ga, 1, BUFLEN);
4592
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004593 if (cmd != NULL)
4594 {
4595 p = (char *)vim_strsave((char_u *)cmd);
4596 if (p != NULL)
4597 unescape_shellxquote((char_u *)p, p_sxe);
4598 else
4599 p = cmd;
4600 }
4601
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004602 /* Now, run the command.
4603 * About "Inherit handles" being TRUE: this command can be litigious,
4604 * handle inheritance was deactivated for pending temp file, but, if we
4605 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004606 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4607 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004608
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004609 if (p != cmd)
4610 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611
4612 /* Close our unused side of the pipes */
4613 CloseHandle(g_hChildStd_IN_Rd);
4614 CloseHandle(g_hChildStd_OUT_Wr);
4615
4616 if (options & SHELL_WRITE)
4617 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004618 HANDLE thread = (HANDLE)
4619 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004620 0, /* default stack size */
4621 sub_process_writer, /* function to be executed */
4622 g_hChildStd_IN_Wr, /* parameter */
4623 0, /* creation flag, start immediately */
4624 NULL); /* we don't care about thread id */
4625 CloseHandle(thread);
4626 g_hChildStd_IN_Wr = NULL;
4627 }
4628
4629 /* Keep updating the window while waiting for the shell to finish. */
4630 for (;;)
4631 {
4632 MSG msg;
4633
Bram Moolenaar175d0702013-12-11 18:36:33 +01004634 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635 {
4636 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004637 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004638 }
4639
4640 /* write pipe information in the window */
4641 if ((options & (SHELL_READ|SHELL_WRITE))
4642# ifdef FEAT_GUI
4643 || gui.in_use
4644# endif
4645 )
4646 {
4647 len = 0;
4648 if (!(options & SHELL_EXPAND)
4649 && ((options &
4650 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4651 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4652# ifdef FEAT_GUI
4653 || gui.in_use
4654# endif
4655 )
4656 && (ta_len > 0 || noread_cnt > 4))
4657 {
4658 if (ta_len == 0)
4659 {
4660 /* Get extra characters when we don't have any. Reset the
4661 * counter and timer. */
4662 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004663 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4664 }
4665 if (ta_len > 0 || len > 0)
4666 {
4667 /*
4668 * For pipes: Check for CTRL-C: send interrupt signal to
4669 * child. Check for CTRL-D: EOF, close pipe to child.
4670 */
4671 if (len == 1 && cmd != NULL)
4672 {
4673 if (ta_buf[ta_len] == Ctrl_C)
4674 {
4675 /* Learn what exit code is expected, for
4676 * now put 9 as SIGKILL */
4677 TerminateProcess(pi.hProcess, 9);
4678 }
4679 if (ta_buf[ta_len] == Ctrl_D)
4680 {
4681 CloseHandle(g_hChildStd_IN_Wr);
4682 g_hChildStd_IN_Wr = NULL;
4683 }
4684 }
4685
4686 /* replace K_BS by <BS> and K_DEL by <DEL> */
4687 for (i = ta_len; i < ta_len + len; ++i)
4688 {
4689 if (ta_buf[i] == CSI && len - i > 2)
4690 {
4691 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4692 if (c == K_DEL || c == K_KDEL || c == K_BS)
4693 {
4694 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4695 (size_t)(len - i - 2));
4696 if (c == K_DEL || c == K_KDEL)
4697 ta_buf[i] = DEL;
4698 else
4699 ta_buf[i] = Ctrl_H;
4700 len -= 2;
4701 }
4702 }
4703 else if (ta_buf[i] == '\r')
4704 ta_buf[i] = '\n';
4705# ifdef FEAT_MBYTE
4706 if (has_mbyte)
4707 i += (*mb_ptr2len_len)(ta_buf + i,
4708 ta_len + len - i) - 1;
4709# endif
4710 }
4711
4712 /*
4713 * For pipes: echo the typed characters. For a pty this
4714 * does not seem to work.
4715 */
4716 for (i = ta_len; i < ta_len + len; ++i)
4717 {
4718 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4719 msg_putchar(ta_buf[i]);
4720# ifdef FEAT_MBYTE
4721 else if (has_mbyte)
4722 {
4723 int l = (*mb_ptr2len)(ta_buf + i);
4724
4725 msg_outtrans_len(ta_buf + i, l);
4726 i += l - 1;
4727 }
4728# endif
4729 else
4730 msg_outtrans_len(ta_buf + i, 1);
4731 }
4732 windgoto(msg_row, msg_col);
4733 out_flush();
4734
4735 ta_len += len;
4736
4737 /*
4738 * Write the characters to the child, unless EOF has been
4739 * typed for pipes. Write one character at a time, to
4740 * avoid losing too much typeahead. When writing buffer
4741 * lines, drop the typed characters (only check for
4742 * CTRL-C).
4743 */
4744 if (options & SHELL_WRITE)
4745 ta_len = 0;
4746 else if (g_hChildStd_IN_Wr != NULL)
4747 {
4748 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4749 1, &len, NULL);
4750 // if we are typing in, we want to keep things reactive
4751 delay = 1;
4752 if (len > 0)
4753 {
4754 ta_len -= len;
4755 mch_memmove(ta_buf, ta_buf + len, ta_len);
4756 }
4757 }
4758 }
4759 }
4760 }
4761
4762 if (ta_len)
4763 ui_inchar_undo(ta_buf, ta_len);
4764
4765 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4766 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004767 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768 break;
4769 }
4770
4771 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004772 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004773
4774 /* We start waiting for a very short time and then increase it, so
4775 * that we respond quickly when the process is quick, and don't
4776 * consume too much overhead when it's slow. */
4777 if (delay < 50)
4778 delay += 10;
4779 }
4780
4781 /* Close the pipe */
4782 CloseHandle(g_hChildStd_OUT_Rd);
4783 if (g_hChildStd_IN_Wr != NULL)
4784 CloseHandle(g_hChildStd_IN_Wr);
4785
4786 WaitForSingleObject(pi.hProcess, INFINITE);
4787
4788 /* Get the command exit code */
4789 GetExitCodeProcess(pi.hProcess, &ret);
4790
4791 if (options & SHELL_READ)
4792 {
4793 if (ga.ga_len > 0)
4794 {
4795 append_ga_line(&ga);
4796 /* remember that the NL was missing */
4797 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4798 }
4799 else
4800 curbuf->b_no_eol_lnum = 0;
4801 ga_clear(&ga);
4802 }
4803
4804 /* Close the handles to the subprocess, so that it goes away */
4805 CloseHandle(pi.hThread);
4806 CloseHandle(pi.hProcess);
4807
4808 return ret;
4809}
4810
4811 static int
4812mch_system(char *cmd, int options)
4813{
4814 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004815 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004816 return mch_system_piped(cmd, options);
4817 else
4818 return mch_system_classic(cmd, options);
4819}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820#else
4821
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004822# ifdef FEAT_MBYTE
4823 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004824mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004825{
4826 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4827 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004828 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004829 if (wcmd != NULL)
4830 {
4831 int ret = _wsystem(wcmd);
4832 vim_free(wcmd);
4833 return ret;
4834 }
4835 }
4836 return system(cmd);
4837}
4838# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004839# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004840# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841
4842#endif
4843
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004844#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4845/*
4846 * Use a terminal window to run a shell command in.
4847 */
4848 static int
4849mch_call_shell_terminal(
4850 char_u *cmd,
4851 int options UNUSED) /* SHELL_*, see vim.h */
4852{
4853 jobopt_T opt;
4854 char_u *newcmd = NULL;
4855 typval_T argvar[2];
4856 long_u cmdlen;
4857 int retval = -1;
4858 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004859 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004860 aco_save_T aco;
4861 oparg_T oa; /* operator arguments */
4862
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004863 if (cmd == NULL)
4864 cmdlen = STRLEN(p_sh) + 1;
4865 else
4866 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004867 newcmd = lalloc(cmdlen, TRUE);
4868 if (newcmd == NULL)
4869 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004870 if (cmd == NULL)
4871 {
4872 STRCPY(newcmd, p_sh);
4873 ch_log(NULL, "starting terminal to run a shell");
4874 }
4875 else
4876 {
4877 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4878 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4879 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004880
4881 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004882
4883 argvar[0].v_type = VAR_STRING;
4884 argvar[0].vval.v_string = newcmd;
4885 argvar[1].v_type = VAR_UNKNOWN;
4886 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004887 if (buf == NULL)
4888 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004889
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004890 job = term_getjob(buf->b_term);
4891 ++job->jv_refcount;
4892
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004893 /* Find a window to make "buf" curbuf. */
4894 aucmd_prepbuf(&aco, buf);
4895
4896 clear_oparg(&oa);
4897 while (term_use_loop())
4898 {
4899 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4900 {
4901 /* If terminal_loop() returns OK we got a key that is handled
4902 * in Normal model. We don't do redrawing anyway. */
4903 if (terminal_loop(TRUE) == OK)
4904 normal_cmd(&oa, TRUE);
4905 }
4906 else
4907 normal_cmd(&oa, TRUE);
4908 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004909 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004910 ch_log(NULL, "system command finished");
4911
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004912 job_unref(job);
4913
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004914 /* restore curwin/curbuf and a few other things */
4915 aucmd_restbuf(&aco);
4916
4917 wait_return(TRUE);
4918 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4919
4920 vim_free(newcmd);
4921 return retval;
4922}
4923#endif
4924
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925/*
4926 * Either execute a command by calling the shell or start a new shell
4927 */
4928 int
4929mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004930 char_u *cmd,
4931 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932{
4933 int x = 0;
4934 int tmode = cur_tmode;
4935#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004936 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004937# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004938 int did_set_title = FALSE;
4939
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004940 /* Change the title to reflect that we are in a subshell. */
4941 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4942 {
4943 WCHAR szShellTitle[512];
4944
4945 if (GetConsoleTitleW(szShellTitle,
4946 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4947 {
4948 if (cmd == NULL)
4949 wcscat(szShellTitle, L" :sh");
4950 else
4951 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004952 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004953
4954 if (wn != NULL)
4955 {
4956 wcscat(szShellTitle, L" - !");
4957 if ((wcslen(szShellTitle) + wcslen(wn) <
4958 sizeof(szShellTitle)/sizeof(WCHAR)))
4959 wcscat(szShellTitle, wn);
4960 SetConsoleTitleW(szShellTitle);
4961 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004962 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004963 }
4964 }
4965 }
4966 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004967 if (!did_set_title)
4968# endif
4969 /* Change the title to reflect that we are in a subshell. */
4970 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004972 if (cmd == NULL)
4973 strcat(szShellTitle, " :sh");
4974 else
4975 {
4976 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004977 if ((strlen(szShellTitle) + strlen((char *)cmd)
4978 < sizeof(szShellTitle)))
4979 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004980 }
4981 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983#endif
4984
4985 out_flush();
4986
4987#ifdef MCH_WRITE_DUMP
4988 if (fdDump)
4989 {
4990 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4991 fflush(fdDump);
4992 }
4993#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004994#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4995 /* TODO: make the terminal window work with input or output redirected. */
4996 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4997 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4998 {
4999 /* Use a terminal window to run the command in. */
5000 x = mch_call_shell_terminal(cmd, options);
5001#ifdef FEAT_TITLE
5002 resettitle();
5003#endif
5004 return x;
5005 }
5006#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007
5008 /*
5009 * Catch all deadly signals while running the external command, because a
5010 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5011 */
5012 signal(SIGINT, SIG_IGN);
5013#if defined(__GNUC__) && !defined(__MINGW32__)
5014 signal(SIGKILL, SIG_IGN);
5015#else
5016 signal(SIGBREAK, SIG_IGN);
5017#endif
5018 signal(SIGILL, SIG_IGN);
5019 signal(SIGFPE, SIG_IGN);
5020 signal(SIGSEGV, SIG_IGN);
5021 signal(SIGTERM, SIG_IGN);
5022 signal(SIGABRT, SIG_IGN);
5023
5024 if (options & SHELL_COOKED)
5025 settmode(TMODE_COOK); /* set to normal mode */
5026
5027 if (cmd == NULL)
5028 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005029 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030 }
5031 else
5032 {
5033 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005034 char_u *newcmd = NULL;
5035 char_u *cmdbase = cmd;
5036 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005037
5038 /* Skip a leading ", ( and "(. */
5039 if (*cmdbase == '"' )
5040 ++cmdbase;
5041 if (*cmdbase == '(')
5042 ++cmdbase;
5043
Bram Moolenaar1c465442017-03-12 20:10:05 +01005044 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005045 {
5046 STARTUPINFO si;
5047 PROCESS_INFORMATION pi;
5048 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005049 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005050 char_u *p;
5051
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005052 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005053 si.cb = sizeof(si);
5054 si.lpReserved = NULL;
5055 si.lpDesktop = NULL;
5056 si.lpTitle = NULL;
5057 si.dwFlags = 0;
5058 si.cbReserved2 = 0;
5059 si.lpReserved2 = NULL;
5060
5061 cmdbase = skipwhite(cmdbase + 5);
5062 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005063 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005064 {
5065 cmdbase = skipwhite(cmdbase + 4);
5066 si.dwFlags = STARTF_USESHOWWINDOW;
5067 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005068 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 }
5070 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005071 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005072 {
5073 cmdbase = skipwhite(cmdbase + 2);
5074 flags = CREATE_NO_WINDOW;
5075 si.dwFlags = STARTF_USESTDHANDLES;
5076 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005077 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005078 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005079 NULL, // Security att.
5080 OPEN_EXISTING, // Open flags
5081 FILE_ATTRIBUTE_NORMAL, // File att.
5082 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005083 si.hStdOutput = si.hStdInput;
5084 si.hStdError = si.hStdInput;
5085 }
5086
5087 /* Remove a trailing ", ) and )" if they have a match
5088 * at the start of the command. */
5089 if (cmdbase > cmd)
5090 {
5091 p = cmdbase + STRLEN(cmdbase);
5092 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5093 *--p = NUL;
5094 if (p > cmdbase && p[-1] == ')'
5095 && (*cmd =='(' || cmd[1] == '('))
5096 *--p = NUL;
5097 }
5098
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005099 newcmd = cmdbase;
5100 unescape_shellxquote(cmdbase, p_sxe);
5101
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005102 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005103 * If creating new console, arguments are passed to the
5104 * 'cmd.exe' as-is. If it's not, arguments are not treated
5105 * correctly for current 'cmd.exe'. So unescape characters in
5106 * shellxescape except '|' for avoiding to be treated as
5107 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005108 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005109 if (flags != CREATE_NEW_CONSOLE)
5110 {
5111 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005112 char_u *cmd_shell = mch_getenv("COMSPEC");
5113
5114 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005115 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005116
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005117 subcmd = vim_strsave_escaped_ext(cmdbase,
5118 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005119 if (subcmd != NULL)
5120 {
5121 /* make "cmd.exe /c arguments" */
5122 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005123 newcmd = lalloc(cmdlen, TRUE);
5124 if (newcmd != NULL)
5125 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005126 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005127 else
5128 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005129 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005130 }
5131 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005132
5133 /*
5134 * Now, start the command as a process, so that it doesn't
5135 * inherit our handles which causes unpleasant dangling swap
5136 * files if we exit before the spawned process
5137 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005138 if (vim_create_process((char *)newcmd, FALSE, flags,
5139 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005140 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005141 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5142 > (HINSTANCE)32)
5143 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005144 else
5145 {
5146 x = -1;
5147#ifdef FEAT_GUI_W32
5148 EMSG(_("E371: Command not found"));
5149#endif
5150 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005151
5152 if (newcmd != cmdbase)
5153 vim_free(newcmd);
5154
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005155 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005156 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005157 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005158 CloseHandle(si.hStdInput);
5159 }
5160 /* Close the handles to the subprocess, so that it goes away */
5161 CloseHandle(pi.hThread);
5162 CloseHandle(pi.hProcess);
5163 }
5164 else
5165 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005166 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005167#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005168 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005170 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5171
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005172 newcmd = lalloc(cmdlen, TRUE);
5173 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174 {
5175#if defined(FEAT_GUI_W32)
5176 if (need_vimrun_warning)
5177 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005178 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5179 "External commands will not pause after completion.\n"
5180 "See :help win32-vimrun for more information.");
5181 char *title = _("Vim Warning");
5182# ifdef FEAT_MBYTE
5183 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5184 {
5185 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5186 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5187
5188 if (wmsg != NULL && wtitle != NULL)
5189 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5190 vim_free(wmsg);
5191 vim_free(wtitle);
5192 }
5193 else
5194# endif
5195 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 need_vimrun_warning = FALSE;
5197 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005198 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005199 /* Use vimrun to execute the command. It opens a console
5200 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005201 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202 vimrun_path,
5203 (msg_silent != 0 || (options & SHELL_DOOUT))
5204 ? "-s " : "",
5205 p_sh, p_shcf, cmd);
5206 else
5207#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005208 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005209 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005211 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 }
5214 }
5215
5216 if (tmode == TMODE_RAW)
5217 settmode(TMODE_RAW); /* set to raw mode */
5218
5219 /* Print the return value, unless "vimrun" was used. */
5220 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5221#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005222 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223#endif
5224 )
5225 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005226 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 msg_putchar('\n');
5228 }
5229#ifdef FEAT_TITLE
5230 resettitle();
5231#endif
5232
5233 signal(SIGINT, SIG_DFL);
5234#if defined(__GNUC__) && !defined(__MINGW32__)
5235 signal(SIGKILL, SIG_DFL);
5236#else
5237 signal(SIGBREAK, SIG_DFL);
5238#endif
5239 signal(SIGILL, SIG_DFL);
5240 signal(SIGFPE, SIG_DFL);
5241 signal(SIGSEGV, SIG_DFL);
5242 signal(SIGTERM, SIG_DFL);
5243 signal(SIGABRT, SIG_DFL);
5244
5245 return x;
5246}
5247
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005248#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005249 static HANDLE
5250job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005251 char_u *fname,
5252 DWORD dwDesiredAccess,
5253 DWORD dwShareMode,
5254 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5255 DWORD dwCreationDisposition,
5256 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005257{
5258 HANDLE h;
5259# ifdef FEAT_MBYTE
5260 WCHAR *wn = NULL;
5261 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5262 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005263 wn = enc_to_utf16(fname, NULL);
5264 if (wn != NULL)
5265 {
5266 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5267 lpSecurityAttributes, dwCreationDisposition,
5268 dwFlagsAndAttributes, NULL);
5269 vim_free(wn);
5270 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005271 }
5272 if (wn == NULL)
5273# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005274 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5275 lpSecurityAttributes, dwCreationDisposition,
5276 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005277 return h;
5278}
5279
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005280/*
5281 * Turn the dictionary "env" into a NUL separated list that can be used as the
5282 * environment argument of vim_create_process().
5283 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005284 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005285win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286{
5287 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005288 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005289 LPVOID base = GetEnvironmentStringsW();
5290
5291 /* for last \0 */
5292 if (ga_grow(gap, 1) == FAIL)
5293 return;
5294
5295 if (base)
5296 {
5297 WCHAR *p = (WCHAR*) base;
5298
5299 /* for last \0 */
5300 if (ga_grow(gap, 1) == FAIL)
5301 return;
5302
5303 while (*p != 0 || *(p + 1) != 0)
5304 {
5305 if (ga_grow(gap, 1) == OK)
5306 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5307 p++;
5308 }
5309 FreeEnvironmentStrings(base);
5310 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5311 }
5312
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005313 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005314 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005316 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005317 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005318 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005319 typval_T *item = &dict_lookup(hi)->di_tv;
5320 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5321 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5322 --todo;
5323 if (wkey != NULL && wval != NULL)
5324 {
5325 size_t n;
5326 size_t lkey = wcslen(wkey);
5327 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005328
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005329 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5330 continue;
5331 for (n = 0; n < lkey; n++)
5332 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5333 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5334 for (n = 0; n < lval; n++)
5335 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5336 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5337 }
5338 if (wkey != NULL) vim_free(wkey);
5339 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005340 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005341 }
5342 }
5343
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005345 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005346# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005347 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005348 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005349# endif
5350# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005351 char_u *version = get_vim_var_str(VV_VERSION);
5352 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005353# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005354 // size of "VIM_SERVERNAME=" and value,
5355 // plus "VIM_TERMINAL=" and value,
5356 // plus two terminating NULs
5357 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005358# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005359 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005360# endif
5361# ifdef FEAT_TERMINAL
5362 + 13 + version_len + 2
5363# endif
5364 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005365
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005366 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005367 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005368# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005369 for (n = 0; n < 15; n++)
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5371 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005372 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005373 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5374 (WCHAR)servername[n];
5375 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005376# endif
5377# ifdef FEAT_TERMINAL
5378 if (is_terminal)
5379 {
5380 for (n = 0; n < 13; n++)
5381 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5382 (WCHAR)"VIM_TERMINAL="[n];
5383 for (n = 0; n < version_len; n++)
5384 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5385 (WCHAR)version[n];
5386 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5387 }
5388# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005389 }
5390 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005391# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005392}
5393
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005394 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005395mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005396{
5397 STARTUPINFO si;
5398 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005399 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005400 SECURITY_ATTRIBUTES saAttr;
5401 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005402 HANDLE ifd[2];
5403 HANDLE ofd[2];
5404 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005405 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005406
5407 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5408 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5409 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5410 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5411 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5412 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5413 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5414
5415 if (use_out_for_err && use_null_for_out)
5416 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005417
5418 ifd[0] = INVALID_HANDLE_VALUE;
5419 ifd[1] = INVALID_HANDLE_VALUE;
5420 ofd[0] = INVALID_HANDLE_VALUE;
5421 ofd[1] = INVALID_HANDLE_VALUE;
5422 efd[0] = INVALID_HANDLE_VALUE;
5423 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005424 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005425
Bram Moolenaar14207f42016-10-27 21:13:10 +02005426 jo = CreateJobObject(NULL, NULL);
5427 if (jo == NULL)
5428 {
5429 job->jv_status = JOB_FAILED;
5430 goto failed;
5431 }
5432
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005433 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005434 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005435
Bram Moolenaar76467df2016-02-12 19:30:26 +01005436 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005437 ZeroMemory(&si, sizeof(si));
5438 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005439 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005440 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005441
Bram Moolenaard8070362016-02-15 21:56:54 +01005442 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5443 saAttr.bInheritHandle = TRUE;
5444 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005445
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005446 if (use_file_for_in)
5447 {
5448 char_u *fname = options->jo_io_name[PART_IN];
5449
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005450 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5451 FILE_SHARE_READ | FILE_SHARE_WRITE,
5452 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5453 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005454 {
5455 EMSG2(_(e_notopen), fname);
5456 goto failed;
5457 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005458 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005459 else if (!use_null_for_in &&
5460 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005461 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005462 goto failed;
5463
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005464 if (use_file_for_out)
5465 {
5466 char_u *fname = options->jo_io_name[PART_OUT];
5467
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005468 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5469 FILE_SHARE_READ | FILE_SHARE_WRITE,
5470 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5471 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005472 {
5473 EMSG2(_(e_notopen), fname);
5474 goto failed;
5475 }
5476 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005477 else if (!use_null_for_out &&
5478 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005479 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005480 goto failed;
5481
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005482 if (use_file_for_err)
5483 {
5484 char_u *fname = options->jo_io_name[PART_ERR];
5485
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005486 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5487 FILE_SHARE_READ | FILE_SHARE_WRITE,
5488 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5489 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005490 {
5491 EMSG2(_(e_notopen), fname);
5492 goto failed;
5493 }
5494 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005495 else if (!use_out_for_err && !use_null_for_err &&
5496 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005497 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005498 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005499
Bram Moolenaard8070362016-02-15 21:56:54 +01005500 si.dwFlags |= STARTF_USESTDHANDLES;
5501 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005502 si.hStdOutput = ofd[1];
5503 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5504
5505 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5506 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005507 if (options->jo_set & JO_CHANNEL)
5508 {
5509 channel = options->jo_channel;
5510 if (channel != NULL)
5511 ++channel->ch_refcount;
5512 }
5513 else
5514 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005515 if (channel == NULL)
5516 goto failed;
5517 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005518
5519 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005520 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005521 CREATE_DEFAULT_ERROR_MODE |
5522 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005523 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005524 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005525 &si, &pi,
5526 ga.ga_data,
5527 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005528 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005529 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005530 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005531 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005532 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005533
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005534 ga_clear(&ga);
5535
Bram Moolenaar14207f42016-10-27 21:13:10 +02005536 if (!AssignProcessToJobObject(jo, pi.hProcess))
5537 {
5538 /* if failing, switch the way to terminate
5539 * process with TerminateProcess. */
5540 CloseHandle(jo);
5541 jo = NULL;
5542 }
5543 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005544 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005545 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005546 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005547 job->jv_status = JOB_STARTED;
5548
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005549 CloseHandle(ifd[0]);
5550 CloseHandle(ofd[1]);
5551 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005552 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005553
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005554 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005555 if (channel != NULL)
5556 {
5557 channel_set_pipes(channel,
5558 use_file_for_in || use_null_for_in
5559 ? INVALID_FD : (sock_T)ifd[1],
5560 use_file_for_out || use_null_for_out
5561 ? INVALID_FD : (sock_T)ofd[0],
5562 use_out_for_err || use_file_for_err || use_null_for_err
5563 ? INVALID_FD : (sock_T)efd[0]);
5564 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005565 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005566 return;
5567
5568failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005569 CloseHandle(ifd[0]);
5570 CloseHandle(ofd[0]);
5571 CloseHandle(efd[0]);
5572 CloseHandle(ifd[1]);
5573 CloseHandle(ofd[1]);
5574 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005575 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005576 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005577}
5578
5579 char *
5580mch_job_status(job_T *job)
5581{
5582 DWORD dwExitCode = 0;
5583
Bram Moolenaar76467df2016-02-12 19:30:26 +01005584 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5585 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005586 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005587 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005588 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005589 {
5590 ch_log(job->jv_channel, "Job ended");
5591 job->jv_status = JOB_ENDED;
5592 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005593 return "dead";
5594 }
5595 return "run";
5596}
5597
Bram Moolenaar97792de2016-10-15 18:36:49 +02005598 job_T *
5599mch_detect_ended_job(job_T *job_list)
5600{
5601 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5602 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5603 job_T *job = job_list;
5604
5605 while (job != NULL)
5606 {
5607 DWORD n;
5608 DWORD result;
5609
5610 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5611 && job != NULL; job = job->jv_next)
5612 {
5613 if (job->jv_status == JOB_STARTED)
5614 {
5615 jobHandles[n] = job->jv_proc_info.hProcess;
5616 jobArray[n] = job;
5617 ++n;
5618 }
5619 }
5620 if (n == 0)
5621 continue;
5622 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5623 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5624 {
5625 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5626
5627 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5628 return wait_job;
5629 }
5630 }
5631 return NULL;
5632}
5633
Bram Moolenaarfb630902016-10-29 14:55:00 +02005634 static BOOL
5635terminate_all(HANDLE process, int code)
5636{
5637 PROCESSENTRY32 pe;
5638 HANDLE h = INVALID_HANDLE_VALUE;
5639 DWORD pid = GetProcessId(process);
5640
5641 if (pid != 0)
5642 {
5643 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5644 if (h != INVALID_HANDLE_VALUE)
5645 {
5646 pe.dwSize = sizeof(PROCESSENTRY32);
5647 if (!Process32First(h, &pe))
5648 goto theend;
5649
5650 do
5651 {
5652 if (pe.th32ParentProcessID == pid)
5653 {
5654 HANDLE ph = OpenProcess(
5655 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5656 if (ph != NULL)
5657 {
5658 terminate_all(ph, code);
5659 CloseHandle(ph);
5660 }
5661 }
5662 } while (Process32Next(h, &pe));
5663
5664 CloseHandle(h);
5665 }
5666 }
5667
5668theend:
5669 return TerminateProcess(process, code);
5670}
5671
5672/*
5673 * Send a (deadly) signal to "job".
5674 * Return FAIL if it didn't work.
5675 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005676 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005677mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005678{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005679 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005680
Bram Moolenaar923d9262016-02-25 20:56:01 +01005681 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005682 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005683 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005684 if (job->jv_job_object != NULL)
5685 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005686 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005687 }
5688
5689 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5690 return FAIL;
5691 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005692 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5693 job->jv_proc_info.dwProcessId)
5694 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005695 FreeConsole();
5696 return ret;
5697}
5698
5699/*
5700 * Clear the data related to "job".
5701 */
5702 void
5703mch_clear_job(job_T *job)
5704{
5705 if (job->jv_status != JOB_FAILED)
5706 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005707 if (job->jv_job_object != NULL)
5708 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005709 CloseHandle(job->jv_proc_info.hProcess);
5710 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005711}
5712#endif
5713
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714
5715#ifndef FEAT_GUI_W32
5716
5717/*
5718 * Start termcap mode
5719 */
5720 static void
5721termcap_mode_start(void)
5722{
5723 DWORD cmodein;
5724
5725 if (g_fTermcapMode)
5726 return;
5727
5728 SaveConsoleBuffer(&g_cbNonTermcap);
5729
5730 if (g_cbTermcap.IsValid)
5731 {
5732 /*
5733 * We've been in termcap mode before. Restore certain screen
5734 * characteristics, including the buffer size and the window
5735 * size. Since we will be redrawing the screen, we don't need
5736 * to restore the actual contents of the buffer.
5737 */
5738 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005739 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005740 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5741 Rows = g_cbTermcap.Info.dwSize.Y;
5742 Columns = g_cbTermcap.Info.dwSize.X;
5743 }
5744 else
5745 {
5746 /*
5747 * This is our first time entering termcap mode. Clear the console
5748 * screen buffer, and resize the buffer to match the current window
5749 * size. We will use this as the size of our editing environment.
5750 */
5751 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005752 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5754 }
5755
5756#ifdef FEAT_TITLE
5757 resettitle();
5758#endif
5759
5760 GetConsoleMode(g_hConIn, &cmodein);
5761#ifdef FEAT_MOUSE
5762 if (g_fMouseActive)
5763 cmodein |= ENABLE_MOUSE_INPUT;
5764 else
5765 cmodein &= ~ENABLE_MOUSE_INPUT;
5766#endif
5767 cmodein |= ENABLE_WINDOW_INPUT;
5768 SetConsoleMode(g_hConIn, cmodein);
5769
5770 redraw_later_clear();
5771 g_fTermcapMode = TRUE;
5772}
5773
5774
5775/*
5776 * End termcap mode
5777 */
5778 static void
5779termcap_mode_end(void)
5780{
5781 DWORD cmodein;
5782 ConsoleBuffer *cb;
5783 COORD coord;
5784 DWORD dwDummy;
5785
5786 if (!g_fTermcapMode)
5787 return;
5788
5789 SaveConsoleBuffer(&g_cbTermcap);
5790
5791 GetConsoleMode(g_hConIn, &cmodein);
5792 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5793 SetConsoleMode(g_hConIn, cmodein);
5794
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005795#ifdef FEAT_RESTORE_ORIG_SCREEN
5796 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5797#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005799#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005801 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802 SetConsoleCursorInfo(g_hConOut, &g_cci);
5803
5804 if (p_rs || exiting)
5805 {
5806 /*
5807 * Clear anything that happens to be on the current line.
5808 */
5809 coord.X = 0;
5810 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5811 FillConsoleOutputCharacter(g_hConOut, ' ',
5812 cb->Info.dwSize.X, coord, &dwDummy);
5813 /*
5814 * The following is just for aesthetics. If we are exiting without
5815 * restoring the screen, then we want to have a prompt string
5816 * appear at the bottom line. However, the command interpreter
5817 * seems to always advance the cursor one line before displaying
5818 * the prompt string, which causes the screen to scroll. To
5819 * counter this, move the cursor up one line before exiting.
5820 */
5821 if (exiting && !p_rs)
5822 coord.Y--;
5823 /*
5824 * Position the cursor at the leftmost column of the desired row.
5825 */
5826 SetConsoleCursorPosition(g_hConOut, coord);
5827 }
5828
5829 g_fTermcapMode = FALSE;
5830}
5831#endif /* FEAT_GUI_W32 */
5832
5833
5834#ifdef FEAT_GUI_W32
5835 void
5836mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005837 char_u *s UNUSED,
5838 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839{
5840 /* never used */
5841}
5842
5843#else
5844
5845/*
5846 * clear `n' chars, starting from `coord'
5847 */
5848 static void
5849clear_chars(
5850 COORD coord,
5851 DWORD n)
5852{
5853 DWORD dwDummy;
5854
5855 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005856
5857 if (!USE_VTP)
5858 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5859 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005860 {
5861 set_console_color_rgb();
5862 gotoxy(coord.X + 1, coord.Y + 1);
5863 vtp_printf("\033[%dX", n);
5864 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865}
5866
5867
5868/*
5869 * Clear the screen
5870 */
5871 static void
5872clear_screen(void)
5873{
5874 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005875
5876 if (!USE_VTP)
5877 clear_chars(g_coord, Rows * Columns);
5878 else
5879 {
5880 set_console_color_rgb();
5881 gotoxy(1, 1);
5882 vtp_printf("\033[2J");
5883 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884}
5885
5886
5887/*
5888 * Clear to end of display
5889 */
5890 static void
5891clear_to_end_of_display(void)
5892{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005893 COORD save = g_coord;
5894
5895 if (!USE_VTP)
5896 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005897 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005898 else
5899 {
5900 set_console_color_rgb();
5901 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5902 vtp_printf("\033[0J");
5903
5904 gotoxy(save.X + 1, save.Y + 1);
5905 g_coord = save;
5906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907}
5908
5909
5910/*
5911 * Clear to end of line
5912 */
5913 static void
5914clear_to_end_of_line(void)
5915{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005916 COORD save = g_coord;
5917
5918 if (!USE_VTP)
5919 clear_chars(g_coord, Columns - g_coord.X);
5920 else
5921 {
5922 set_console_color_rgb();
5923 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5924 vtp_printf("\033[0K");
5925
5926 gotoxy(save.X + 1, save.Y + 1);
5927 g_coord = save;
5928 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929}
5930
5931
5932/*
5933 * Scroll the scroll region up by `cLines' lines
5934 */
5935 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005936scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937{
5938 COORD oldcoord = g_coord;
5939
5940 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5941 delete_lines(cLines);
5942
5943 g_coord = oldcoord;
5944}
5945
5946
5947/*
5948 * Set the scroll region
5949 */
5950 static void
5951set_scroll_region(
5952 unsigned left,
5953 unsigned top,
5954 unsigned right,
5955 unsigned bottom)
5956{
5957 if (left >= right
5958 || top >= bottom
5959 || right > (unsigned) Columns - 1
5960 || bottom > (unsigned) Rows - 1)
5961 return;
5962
5963 g_srScrollRegion.Left = left;
5964 g_srScrollRegion.Top = top;
5965 g_srScrollRegion.Right = right;
5966 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005967
5968 if (USE_VTP)
5969 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970}
5971
5972
5973/*
5974 * Insert `cLines' lines at the current cursor position
5975 */
5976 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005977insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005978{
5979 SMALL_RECT source;
5980 COORD dest;
5981 CHAR_INFO fill;
5982
5983 dest.X = 0;
5984 dest.Y = g_coord.Y + cLines;
5985
5986 source.Left = 0;
5987 source.Top = g_coord.Y;
5988 source.Right = g_srScrollRegion.Right;
5989 source.Bottom = g_srScrollRegion.Bottom - cLines;
5990
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005991 if (!USE_VTP)
5992 {
5993 fill.Char.AsciiChar = ' ';
5994 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005996 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5997 }
5998 else
5999 {
6000 set_console_color_rgb();
6001
6002 gotoxy(1, source.Top + 1);
6003 vtp_printf("\033[%dT", cLines);
6004 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005
6006 /* Here we have to deal with a win32 console flake: If the scroll
6007 * region looks like abc and we scroll c to a and fill with d we get
6008 * cbd... if we scroll block c one line at a time to a, we get cdd...
6009 * vim expects cdd consistently... So we have to deal with that
6010 * here... (this also occurs scrolling the same way in the other
6011 * direction). */
6012
6013 if (source.Bottom < dest.Y)
6014 {
6015 COORD coord;
6016
6017 coord.X = 0;
6018 coord.Y = source.Bottom;
6019 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6020 }
6021}
6022
6023
6024/*
6025 * Delete `cLines' lines at the current cursor position
6026 */
6027 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006028delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029{
6030 SMALL_RECT source;
6031 COORD dest;
6032 CHAR_INFO fill;
6033 int nb;
6034
6035 dest.X = 0;
6036 dest.Y = g_coord.Y;
6037
6038 source.Left = 0;
6039 source.Top = g_coord.Y + cLines;
6040 source.Right = g_srScrollRegion.Right;
6041 source.Bottom = g_srScrollRegion.Bottom;
6042
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006043 if (!USE_VTP)
6044 {
6045 fill.Char.AsciiChar = ' ';
6046 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006048 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6049 }
6050 else
6051 {
6052 set_console_color_rgb();
6053
6054 gotoxy(1, source.Top + 1);
6055 vtp_printf("\033[%dS", cLines);
6056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057
6058 /* Here we have to deal with a win32 console flake: If the scroll
6059 * region looks like abc and we scroll c to a and fill with d we get
6060 * cbd... if we scroll block c one line at a time to a, we get cdd...
6061 * vim expects cdd consistently... So we have to deal with that
6062 * here... (this also occurs scrolling the same way in the other
6063 * direction). */
6064
6065 nb = dest.Y + (source.Bottom - source.Top) + 1;
6066
6067 if (nb < source.Top)
6068 {
6069 COORD coord;
6070
6071 coord.X = 0;
6072 coord.Y = nb;
6073 clear_chars(coord, Columns * (source.Top - nb));
6074 }
6075}
6076
6077
6078/*
6079 * Set the cursor position
6080 */
6081 static void
6082gotoxy(
6083 unsigned x,
6084 unsigned y)
6085{
6086 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6087 return;
6088
6089 /* external cursor coords are 1-based; internal are 0-based */
6090 g_coord.X = x - 1;
6091 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006092
6093 if (!USE_VTP)
6094 SetConsoleCursorPosition(g_hConOut, g_coord);
6095 else
6096 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097}
6098
6099
6100/*
6101 * Set the current text attribute = (foreground | background)
6102 * See ../doc/os_win32.txt for the numbers.
6103 */
6104 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006105textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006107 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108
6109 SetConsoleTextAttribute(g_hConOut, wAttr);
6110}
6111
6112
6113 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006114textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006116 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006118 if (!USE_VTP)
6119 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6120 else
6121 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122}
6123
6124
6125 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006126textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006128 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006130 if (!USE_VTP)
6131 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6132 else
6133 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134}
6135
6136
6137/*
6138 * restore the default text attribute (whatever we started with)
6139 */
6140 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006141normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006143 if (!USE_VTP)
6144 textattr(g_attrDefault);
6145 else
6146 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147}
6148
6149
6150static WORD g_attrPreStandout = 0;
6151
6152/*
6153 * Make the text standout, by brightening it
6154 */
6155 static void
6156standout(void)
6157{
6158 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006159
Bram Moolenaar071d4272004-06-13 20:20:40 +00006160 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6161}
6162
6163
6164/*
6165 * Turn off standout mode
6166 */
6167 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006168standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169{
6170 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172
6173 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174}
6175
6176
6177/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006178 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 */
6180 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006181mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182{
6183 char_u *p;
6184 int n;
6185
6186 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6187 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006188 if (
6189#ifdef FEAT_TERMGUICOLORS
6190 !p_tgc &&
6191#endif
6192 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193 {
6194 p = T_ME + 2;
6195 n = getdigits(&p);
6196 if (*p == 'm' && n > 0)
6197 {
6198 cterm_normal_fg_color = (n & 0xf) + 1;
6199 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6200 }
6201 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006202#ifdef FEAT_TERMGUICOLORS
6203 cterm_normal_fg_gui_color = INVALCOLOR;
6204 cterm_normal_bg_gui_color = INVALCOLOR;
6205#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206}
6207
6208
6209/*
6210 * visual bell: flash the screen
6211 */
6212 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006213visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214{
6215 COORD coordOrigin = {0, 0};
6216 WORD attrFlash = ~g_attrCurrent & 0xff;
6217
6218 DWORD dwDummy;
6219 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6220
6221 if (oldattrs == NULL)
6222 return;
6223 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6224 coordOrigin, &dwDummy);
6225 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6226 coordOrigin, &dwDummy);
6227
6228 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006229 if (!USE_VTP)
6230 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 coordOrigin, &dwDummy);
6232 vim_free(oldattrs);
6233}
6234
6235
6236/*
6237 * Make the cursor visible or invisible
6238 */
6239 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006240cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241{
6242 s_cursor_visible = fVisible;
6243#ifdef MCH_CURSOR_SHAPE
6244 mch_update_cursor();
6245#endif
6246}
6247
6248
6249/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006250 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006251 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006253 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006255 char_u *pchBuf,
6256 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257{
6258 COORD coord = g_coord;
6259 DWORD written;
6260
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261#ifdef FEAT_MBYTE
6262 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6263 {
6264 static WCHAR *unicodebuf = NULL;
6265 static int unibuflen = 0;
6266 int length;
6267 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006269 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6270 if (unicodebuf == NULL || length > unibuflen)
6271 {
6272 vim_free(unicodebuf);
6273 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6274 unibuflen = length;
6275 }
6276 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6277 unicodebuf, unibuflen);
6278
6279 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006280
6281 if (!USE_VTP)
6282 {
6283 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6284 coord, &written);
6285 /* When writing fails or didn't write a single character, pretend one
6286 * character was written, otherwise we get stuck. */
6287 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6288 coord, &cchwritten) == 0
6289 || cchwritten == 0)
6290 cchwritten = 1;
6291 }
6292 else
6293 {
6294 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6295 NULL) == 0 || cchwritten == 0)
6296 cchwritten = 1;
6297 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006298
6299 if (cchwritten == length)
6300 {
6301 written = cbToWrite;
6302 g_coord.X += (SHORT)cells;
6303 }
6304 else
6305 {
6306 char_u *p = pchBuf;
6307 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006308 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006309 written = p - pchBuf;
6310 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6311 }
6312 }
6313 else
6314#endif
6315 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006316 if (!USE_VTP)
6317 {
6318 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6319 coord, &written);
6320 /* When writing fails or didn't write a single character, pretend one
6321 * character was written, otherwise we get stuck. */
6322 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6323 coord, &written) == 0
6324 || written == 0)
6325 written = 1;
6326 }
6327 else
6328 {
6329 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6330 NULL) == 0 || written == 0)
6331 written = 1;
6332 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006333
6334 g_coord.X += (SHORT) written;
6335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336
6337 while (g_coord.X > g_srScrollRegion.Right)
6338 {
6339 g_coord.X -= (SHORT) Columns;
6340 if (g_coord.Y < g_srScrollRegion.Bottom)
6341 g_coord.Y++;
6342 }
6343
6344 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6345
6346 return written;
6347}
6348
6349
6350/*
6351 * mch_write(): write the output buffer to the screen, translating ESC
6352 * sequences into calls to console output routines.
6353 */
6354 void
6355mch_write(
6356 char_u *s,
6357 int len)
6358{
6359 s[len] = NUL;
6360
6361 if (!term_console)
6362 {
6363 write(1, s, (unsigned)len);
6364 return;
6365 }
6366
6367 /* translate ESC | sequences into faked bios calls */
6368 while (len--)
6369 {
6370 /* optimization: use one single write_chars for runs of text,
6371 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006372 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373
6374 if (p_wd)
6375 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006376 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 if (prefix != 0)
6378 prefix = 1;
6379 }
6380
6381 if (prefix != 0)
6382 {
6383 DWORD nWritten;
6384
6385 nWritten = write_chars(s, prefix);
6386#ifdef MCH_WRITE_DUMP
6387 if (fdDump)
6388 {
6389 fputc('>', fdDump);
6390 fwrite(s, sizeof(char_u), nWritten, fdDump);
6391 fputs("<\n", fdDump);
6392 }
6393#endif
6394 len -= (nWritten - 1);
6395 s += nWritten;
6396 }
6397 else if (s[0] == '\n')
6398 {
6399 /* \n, newline: go to the beginning of the next line or scroll */
6400 if (g_coord.Y == g_srScrollRegion.Bottom)
6401 {
6402 scroll(1);
6403 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6404 }
6405 else
6406 {
6407 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6408 }
6409#ifdef MCH_WRITE_DUMP
6410 if (fdDump)
6411 fputs("\\n\n", fdDump);
6412#endif
6413 s++;
6414 }
6415 else if (s[0] == '\r')
6416 {
6417 /* \r, carriage return: go to beginning of line */
6418 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6419#ifdef MCH_WRITE_DUMP
6420 if (fdDump)
6421 fputs("\\r\n", fdDump);
6422#endif
6423 s++;
6424 }
6425 else if (s[0] == '\b')
6426 {
6427 /* \b, backspace: move cursor one position left */
6428 if (g_coord.X > g_srScrollRegion.Left)
6429 g_coord.X--;
6430 else if (g_coord.Y > g_srScrollRegion.Top)
6431 {
6432 g_coord.X = g_srScrollRegion.Right;
6433 g_coord.Y--;
6434 }
6435 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6436#ifdef MCH_WRITE_DUMP
6437 if (fdDump)
6438 fputs("\\b\n", fdDump);
6439#endif
6440 s++;
6441 }
6442 else if (s[0] == '\a')
6443 {
6444 /* \a, bell */
6445 MessageBeep(0xFFFFFFFF);
6446#ifdef MCH_WRITE_DUMP
6447 if (fdDump)
6448 fputs("\\a\n", fdDump);
6449#endif
6450 s++;
6451 }
6452 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6453 {
6454#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006455 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006457 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006458 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459
6460 switch (s[2])
6461 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 case '0': case '1': case '2': case '3': case '4':
6463 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006464 p = s + 1;
6465 do
6466 {
6467 ++p;
6468 args[argc] = getdigits(&p);
6469 argc += (argc < 15) ? 1 : 0;
6470 if (p > s + len)
6471 break;
6472 } while (*p == ';');
6473
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474 if (p > s + len)
6475 break;
6476
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006477 arg1 = args[0];
6478 arg2 = args[1];
6479 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006481 if (argc == 1 && args[0] == 0)
6482 normvideo();
6483 else if (argc == 1)
6484 {
6485 if (USE_VTP)
6486 textcolor((WORD) arg1);
6487 else
6488 textattr((WORD) arg1);
6489 }
6490 else if (USE_VTP)
6491 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006493 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006495 gotoxy(arg2, arg1);
6496 }
6497 else if (argc == 2 && *p == 'r')
6498 {
6499 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6500 }
6501 else if (argc == 1 && *p == 'A')
6502 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 gotoxy(g_coord.X + 1,
6504 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6505 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006506 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 {
6508 textbackground((WORD) arg1);
6509 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006510 else if (argc == 1 && *p == 'C')
6511 {
6512 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6513 g_coord.Y + 1);
6514 }
6515 else if (argc == 1 && *p == 'f')
6516 {
6517 textcolor((WORD) arg1);
6518 }
6519 else if (argc == 1 && *p == 'H')
6520 {
6521 gotoxy(1, arg1);
6522 }
6523 else if (argc == 1 && *p == 'L')
6524 {
6525 insert_lines(arg1);
6526 }
6527 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 {
6529 delete_lines(arg1);
6530 }
6531
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006532 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 s = p + 1;
6534 break;
6535
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 gotoxy(g_coord.X + 1,
6538 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6539 goto got3;
6540
6541 case 'B':
6542 visual_bell();
6543 goto got3;
6544
6545 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6547 g_coord.Y + 1);
6548 goto got3;
6549
6550 case 'E':
6551 termcap_mode_end();
6552 goto got3;
6553
6554 case 'F':
6555 standout();
6556 goto got3;
6557
6558 case 'f':
6559 standend();
6560 goto got3;
6561
6562 case 'H':
6563 gotoxy(1, 1);
6564 goto got3;
6565
6566 case 'j':
6567 clear_to_end_of_display();
6568 goto got3;
6569
6570 case 'J':
6571 clear_screen();
6572 goto got3;
6573
6574 case 'K':
6575 clear_to_end_of_line();
6576 goto got3;
6577
6578 case 'L':
6579 insert_lines(1);
6580 goto got3;
6581
6582 case 'M':
6583 delete_lines(1);
6584 goto got3;
6585
6586 case 'S':
6587 termcap_mode_start();
6588 goto got3;
6589
6590 case 'V':
6591 cursor_visible(TRUE);
6592 goto got3;
6593
6594 case 'v':
6595 cursor_visible(FALSE);
6596 goto got3;
6597
6598 got3:
6599 s += 3;
6600 len -= 2;
6601 }
6602
6603#ifdef MCH_WRITE_DUMP
6604 if (fdDump)
6605 {
6606 fputs("ESC | ", fdDump);
6607 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6608 fputc('\n', fdDump);
6609 }
6610#endif
6611 }
6612 else
6613 {
6614 /* Write a single character */
6615 DWORD nWritten;
6616
6617 nWritten = write_chars(s, 1);
6618#ifdef MCH_WRITE_DUMP
6619 if (fdDump)
6620 {
6621 fputc('>', fdDump);
6622 fwrite(s, sizeof(char_u), nWritten, fdDump);
6623 fputs("<\n", fdDump);
6624 }
6625#endif
6626
6627 len -= (nWritten - 1);
6628 s += nWritten;
6629 }
6630 }
6631
6632#ifdef MCH_WRITE_DUMP
6633 if (fdDump)
6634 fflush(fdDump);
6635#endif
6636}
6637
6638#endif /* FEAT_GUI_W32 */
6639
6640
6641/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006642 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 */
6644 void
6645mch_delay(
6646 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006647 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648{
6649#ifdef FEAT_GUI_W32
6650 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006651#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006653# ifdef FEAT_MZSCHEME
6654 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6655 {
6656 int towait = p_mzq;
6657
6658 /* if msec is large enough, wait by portions in p_mzq */
6659 while (msec > 0)
6660 {
6661 mzvim_check_threads();
6662 if (msec < towait)
6663 towait = msec;
6664 Sleep(towait);
6665 msec -= towait;
6666 }
6667 }
6668 else
6669# endif
6670 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006672 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673#endif
6674}
6675
6676
6677/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006678 * This version of remove is not scared by a readonly (backup) file.
6679 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 * Return 0 for success, -1 for failure.
6681 */
6682 int
6683mch_remove(char_u *name)
6684{
6685#ifdef FEAT_MBYTE
6686 WCHAR *wn = NULL;
6687 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006688#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689
Bram Moolenaar203258c2016-01-17 22:15:16 +01006690 /*
6691 * On Windows, deleting a directory's symbolic link is done by
6692 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6693 */
6694 if (mch_isdir(name) && mch_is_symbolic_link(name))
6695 return mch_rmdir(name);
6696
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006697 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6698
6699#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6701 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006702 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 if (wn != NULL)
6704 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 n = DeleteFileW(wn) ? 0 : -1;
6706 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006707 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 }
6709 }
6710#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006711 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712}
6713
6714
6715/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006716 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 */
6718 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006719mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720{
6721#ifndef FEAT_GUI_W32 /* never used */
6722 if (g_fCtrlCPressed || g_fCBrkPressed)
6723 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006724 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6726 got_int = TRUE;
6727 }
6728#endif
6729}
6730
Bram Moolenaaree273972016-01-02 21:11:51 +01006731/* physical RAM to leave for the OS */
6732#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006733
6734/*
6735 * How much main memory in KiB that can be used by VIM.
6736 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006737 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006738mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006739{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006740 MEMORYSTATUSEX ms;
6741
Bram Moolenaaree273972016-01-02 21:11:51 +01006742 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006743 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6744 * what fits in 32 bits. But it's not always available. */
6745 ms.dwLength = sizeof(MEMORYSTATUSEX);
6746 GlobalMemoryStatusEx(&ms);
6747 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006748 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006749 /* Process address space fits in physical RAM, use all of it. */
6750 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006751 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006752 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006753 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006754 /* Catch old NT box or perverse hardware setup. */
6755 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006756 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006757 /* Use physical RAM less reserve for OS + data. */
6758 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006759}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761#ifdef FEAT_MBYTE
6762/*
6763 * Same code as below, but with wide functions and no comments.
6764 * Return 0 for success, non-zero for failure.
6765 */
6766 int
6767mch_wrename(WCHAR *wold, WCHAR *wnew)
6768{
6769 WCHAR *p;
6770 int i;
6771 WCHAR szTempFile[_MAX_PATH + 1];
6772 WCHAR szNewPath[_MAX_PATH + 1];
6773 HANDLE hf;
6774
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006775 p = wold;
6776 for (i = 0; wold[i] != NUL; ++i)
6777 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6778 && wold[i + 1] != 0)
6779 p = wold + i + 1;
6780 if ((int)(wold + i - p) < 8 || p[6] != '~')
6781 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782
6783 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6784 return -1;
6785 *p = NUL;
6786
6787 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6788 return -2;
6789
6790 if (!DeleteFileW(szTempFile))
6791 return -3;
6792
6793 if (!MoveFileW(wold, szTempFile))
6794 return -4;
6795
6796 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6797 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6798 return -5;
6799 if (!CloseHandle(hf))
6800 return -6;
6801
6802 if (!MoveFileW(szTempFile, wnew))
6803 {
6804 (void)MoveFileW(szTempFile, wold);
6805 return -7;
6806 }
6807
6808 DeleteFileW(szTempFile);
6809
6810 if (!DeleteFileW(wold))
6811 return -8;
6812
6813 return 0;
6814}
6815#endif
6816
6817
6818/*
6819 * mch_rename() works around a bug in rename (aka MoveFile) in
6820 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6821 * file whose short file name is "FOO.BAR" (its long file name will
6822 * be correct: "foo.bar~"). Because a file can be accessed by
6823 * either its SFN or its LFN, "foo.bar" has effectively been
6824 * renamed to "foo.bar", which is not at all what was wanted. This
6825 * seems to happen only when renaming files with three-character
6826 * extensions by appending a suffix that does not include ".".
6827 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6828 *
6829 * There is another problem, which isn't really a bug but isn't right either:
6830 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6831 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6832 * service pack 6. Doesn't seem to happen on Windows 98.
6833 *
6834 * Like rename(), returns 0 upon success, non-zero upon failure.
6835 * Should probably set errno appropriately when errors occur.
6836 */
6837 int
6838mch_rename(
6839 const char *pszOldFile,
6840 const char *pszNewFile)
6841{
6842 char szTempFile[_MAX_PATH+1];
6843 char szNewPath[_MAX_PATH+1];
6844 char *pszFilePart;
6845 HANDLE hf;
6846#ifdef FEAT_MBYTE
6847 WCHAR *wold = NULL;
6848 WCHAR *wnew = NULL;
6849 int retval = -1;
6850
6851 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6852 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006853 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6854 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 if (wold != NULL && wnew != NULL)
6856 retval = mch_wrename(wold, wnew);
6857 vim_free(wold);
6858 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006859 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 }
6861#endif
6862
6863 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006864 * No need to play tricks unless the file name contains a "~" as the
6865 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006867 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6868 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6869 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870
6871 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6872 * a directory, no error is returned and pszFilePart will be NULL. */
6873 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6874 || pszFilePart == NULL)
6875 return -1;
6876 *pszFilePart = NUL;
6877
6878 /* Get (and create) a unique temporary file name in directory of new file */
6879 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6880 return -2;
6881
6882 /* blow the temp file away */
6883 if (!DeleteFile(szTempFile))
6884 return -3;
6885
6886 /* rename old file to the temp file */
6887 if (!MoveFile(pszOldFile, szTempFile))
6888 return -4;
6889
6890 /* now create an empty file called pszOldFile; this prevents the operating
6891 * system using pszOldFile as an alias (SFN) if we're renaming within the
6892 * same directory. For example, we're editing a file called
6893 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6894 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6895 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006896 * cause all sorts of problems later in buf_write(). So, we create an
6897 * empty file called filena~1.txt and the system will have to find some
6898 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 */
6900 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6901 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6902 return -5;
6903 if (!CloseHandle(hf))
6904 return -6;
6905
6906 /* rename the temp file to the new file */
6907 if (!MoveFile(szTempFile, pszNewFile))
6908 {
6909 /* Renaming failed. Rename the file back to its old name, so that it
6910 * looks like nothing happened. */
6911 (void)MoveFile(szTempFile, pszOldFile);
6912
6913 return -7;
6914 }
6915
6916 /* Seems to be left around on Novell filesystems */
6917 DeleteFile(szTempFile);
6918
6919 /* finally, remove the empty old file */
6920 if (!DeleteFile(pszOldFile))
6921 return -8;
6922
6923 return 0; /* success */
6924}
6925
6926/*
6927 * Get the default shell for the current hardware platform
6928 */
6929 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006930default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 PlatformId();
6933
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006934 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935}
6936
6937/*
6938 * mch_access() extends access() to do more detailed check on network drives.
6939 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6940 */
6941 int
6942mch_access(char *n, int p)
6943{
6944 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 int retval = -1; /* default: fail */
6946#ifdef FEAT_MBYTE
6947 WCHAR *wn = NULL;
6948
6949 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006950 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951#endif
6952
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006953 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954 {
6955 char TempName[_MAX_PATH + 16] = "";
6956#ifdef FEAT_MBYTE
6957 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6958#endif
6959
6960 if (p & R_OK)
6961 {
6962 /* Read check is performed by seeing if we can do a find file on
6963 * the directory for any file. */
6964#ifdef FEAT_MBYTE
6965 if (wn != NULL)
6966 {
6967 int i;
6968 WIN32_FIND_DATAW d;
6969
6970 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6971 TempNameW[i] = wn[i];
6972 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6973 TempNameW[i++] = '\\';
6974 TempNameW[i++] = '*';
6975 TempNameW[i++] = 0;
6976
6977 hFile = FindFirstFileW(TempNameW, &d);
6978 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006979 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 else
6981 (void)FindClose(hFile);
6982 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006983 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984#endif
6985 {
6986 char *pch;
6987 WIN32_FIND_DATA d;
6988
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006989 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 pch = TempName + STRLEN(TempName) - 1;
6991 if (*pch != '\\' && *pch != '/')
6992 *++pch = '\\';
6993 *++pch = '*';
6994 *++pch = NUL;
6995
6996 hFile = FindFirstFile(TempName, &d);
6997 if (hFile == INVALID_HANDLE_VALUE)
6998 goto getout;
6999 (void)FindClose(hFile);
7000 }
7001 }
7002
7003 if (p & W_OK)
7004 {
7005 /* Trying to create a temporary file in the directory should catch
7006 * directories on read-only network shares. However, in
7007 * directories whose ACL allows writes but denies deletes will end
7008 * up keeping the temporary file :-(. */
7009#ifdef FEAT_MBYTE
7010 if (wn != NULL)
7011 {
7012 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007013 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 else
7015 DeleteFileW(TempNameW);
7016 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007017 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018#endif
7019 {
7020 if (!GetTempFileName(n, "VIM", 0, TempName))
7021 goto getout;
7022 mch_remove((char_u *)TempName);
7023 }
7024 }
7025 }
7026 else
7027 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007028 // Don't consider a file read-only if another process has opened it.
7029 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7030
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 /* Trying to open the file for the required access does ACL, read-only
7032 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007033 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7034 | ((p & R_OK) ? GENERIC_READ : 0);
7035
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036#ifdef FEAT_MBYTE
7037 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007038 hFile = CreateFileW(wn, access_mode, share_mode,
7039 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007040 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007042 hFile = CreateFile(n, access_mode, share_mode,
7043 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 if (hFile == INVALID_HANDLE_VALUE)
7045 goto getout;
7046 CloseHandle(hFile);
7047 }
7048
7049 retval = 0; /* success */
7050getout:
7051#ifdef FEAT_MBYTE
7052 vim_free(wn);
7053#endif
7054 return retval;
7055}
7056
7057#if defined(FEAT_MBYTE) || defined(PROTO)
7058/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007059 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 */
7061 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007062mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007064 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7065# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066 WCHAR *wn;
7067 int f;
7068
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007069 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007071 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072 if (wn != NULL)
7073 {
7074 f = _wopen(wn, flags, mode);
7075 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007076 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 }
7078 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007079# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007081 /* open() can open a file which name is longer than _MAX_PATH bytes
7082 * and shorter than _MAX_PATH characters successfully, but sometimes it
7083 * causes unexpected error in another part. We make it an error explicitly
7084 * here. */
7085 if (strlen(name) >= _MAX_PATH)
7086 return -1;
7087
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 return open(name, flags, mode);
7089}
7090
7091/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007092 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 */
7094 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007095mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096{
7097 WCHAR *wn, *wm;
7098 FILE *f = NULL;
7099
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007100 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007102# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007103 /* Work around an annoying assertion in the Microsoft debug CRT
7104 * when mode's text/binary setting doesn't match _get_fmode(). */
7105 char newMode = mode[strlen(mode) - 1];
7106 int oldMode = 0;
7107
7108 _get_fmode(&oldMode);
7109 if (newMode == 't')
7110 _set_fmode(_O_TEXT);
7111 else if (newMode == 'b')
7112 _set_fmode(_O_BINARY);
7113# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007114 wn = enc_to_utf16((char_u *)name, NULL);
7115 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 if (wn != NULL && wm != NULL)
7117 f = _wfopen(wn, wm);
7118 vim_free(wn);
7119 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007120
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007121# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007122 _set_fmode(oldMode);
7123# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007124 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 }
7126
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007127 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7128 * and shorter than _MAX_PATH characters successfully, but sometimes it
7129 * causes unexpected error in another part. We make it an error explicitly
7130 * here. */
7131 if (strlen(name) >= _MAX_PATH)
7132 return NULL;
7133
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 return fopen(name, mode);
7135}
7136#endif
7137
7138#ifdef FEAT_MBYTE
7139/*
7140 * SUB STREAM (aka info stream) handling:
7141 *
7142 * NTFS can have sub streams for each file. Normal contents of file is
7143 * stored in the main stream, and extra contents (author information and
7144 * title and so on) can be stored in sub stream. After Windows 2000, user
7145 * can access and store those informations in sub streams via explorer's
7146 * property menuitem in right click menu. Those informations in sub streams
7147 * were lost when copying only the main stream. So we have to copy sub
7148 * streams.
7149 *
7150 * Incomplete explanation:
7151 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7152 * More useful info and an example:
7153 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7154 */
7155
7156/*
7157 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7158 * and write to stream "substream" of file "to".
7159 * Errors are ignored.
7160 */
7161 static void
7162copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7163{
7164 HANDLE hTo;
7165 WCHAR *to_name;
7166
7167 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7168 wcscpy(to_name, to);
7169 wcscat(to_name, substream);
7170
7171 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7172 FILE_ATTRIBUTE_NORMAL, NULL);
7173 if (hTo != INVALID_HANDLE_VALUE)
7174 {
7175 long done;
7176 DWORD todo;
7177 DWORD readcnt, written;
7178 char buf[4096];
7179
7180 /* Copy block of bytes at a time. Abort when something goes wrong. */
7181 for (done = 0; done < len; done += written)
7182 {
7183 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007184 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7185 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007186 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7187 FALSE, FALSE, context)
7188 || readcnt != todo
7189 || !WriteFile(hTo, buf, todo, &written, NULL)
7190 || written != todo)
7191 break;
7192 }
7193 CloseHandle(hTo);
7194 }
7195
7196 free(to_name);
7197}
7198
7199/*
7200 * Copy info streams from file "from" to file "to".
7201 */
7202 static void
7203copy_infostreams(char_u *from, char_u *to)
7204{
7205 WCHAR *fromw;
7206 WCHAR *tow;
7207 HANDLE sh;
7208 WIN32_STREAM_ID sid;
7209 int headersize;
7210 WCHAR streamname[_MAX_PATH];
7211 DWORD readcount;
7212 void *context = NULL;
7213 DWORD lo, hi;
7214 int len;
7215
7216 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007217 fromw = enc_to_utf16(from, NULL);
7218 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 if (fromw != NULL && tow != NULL)
7220 {
7221 /* Open the file for reading. */
7222 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7223 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7224 if (sh != INVALID_HANDLE_VALUE)
7225 {
7226 /* Use BackupRead() to find the info streams. Repeat until we
7227 * have done them all.*/
7228 for (;;)
7229 {
7230 /* Get the header to find the length of the stream name. If
7231 * the "readcount" is zero we have done all info streams. */
7232 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007233 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7235 &readcount, FALSE, FALSE, &context)
7236 || readcount == 0)
7237 break;
7238
7239 /* We only deal with streams that have a name. The normal
7240 * file data appears to be without a name, even though docs
7241 * suggest it is called "::$DATA". */
7242 if (sid.dwStreamNameSize > 0)
7243 {
7244 /* Read the stream name. */
7245 if (!BackupRead(sh, (LPBYTE)streamname,
7246 sid.dwStreamNameSize,
7247 &readcount, FALSE, FALSE, &context))
7248 break;
7249
7250 /* Copy an info stream with a name ":anything:$DATA".
7251 * Skip "::$DATA", it has no stream name (examples suggest
7252 * it might be used for the normal file contents).
7253 * Note that BackupRead() counts bytes, but the name is in
7254 * wide characters. */
7255 len = readcount / sizeof(WCHAR);
7256 streamname[len] = 0;
7257 if (len > 7 && wcsicmp(streamname + len - 6,
7258 L":$DATA") == 0)
7259 {
7260 streamname[len - 6] = 0;
7261 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007262 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263 }
7264 }
7265
7266 /* Advance to the next stream. We might try seeking too far,
7267 * but BackupSeek() doesn't skip over stream borders, thus
7268 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007269 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 &lo, &hi, &context);
7271 }
7272
7273 /* Clear the context. */
7274 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7275
7276 CloseHandle(sh);
7277 }
7278 }
7279 vim_free(fromw);
7280 vim_free(tow);
7281}
7282#endif
7283
7284/*
7285 * Copy file attributes from file "from" to file "to".
7286 * For Windows NT and later we copy info streams.
7287 * Always returns zero, errors are ignored.
7288 */
7289 int
7290mch_copy_file_attribute(char_u *from, char_u *to)
7291{
7292#ifdef FEAT_MBYTE
7293 /* File streams only work on Windows NT and later. */
7294 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007295 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296#endif
7297 return 0;
7298}
7299
7300#if defined(MYRESETSTKOFLW) || defined(PROTO)
7301/*
7302 * Recreate a destroyed stack guard page in win32.
7303 * Written by Benjamin Peterson.
7304 */
7305
7306/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307#define MIN_STACK_WINNT 2
7308
7309/*
7310 * This function does the same thing as _resetstkoflw(), which is only
7311 * available in DevStudio .net and later.
7312 * Returns 0 for failure, 1 for success.
7313 */
7314 int
7315myresetstkoflw(void)
7316{
7317 BYTE *pStackPtr;
7318 BYTE *pGuardPage;
7319 BYTE *pStackBase;
7320 BYTE *pLowestPossiblePage;
7321 MEMORY_BASIC_INFORMATION mbi;
7322 SYSTEM_INFO si;
7323 DWORD nPageSize;
7324 DWORD dummy;
7325
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327
7328 /* We need to know the system page size. */
7329 GetSystemInfo(&si);
7330 nPageSize = si.dwPageSize;
7331
7332 /* ...and the current stack pointer */
7333 pStackPtr = (BYTE*)_alloca(1);
7334
7335 /* ...and the base of the stack. */
7336 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7337 return 0;
7338 pStackBase = (BYTE*)mbi.AllocationBase;
7339
7340 /* ...and the page thats min_stack_req pages away from stack base; this is
7341 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007342 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007345 /* We want the first committed page in the stack Start at the stack
7346 * base and move forward through memory until we find a committed block.
7347 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 BYTE *pBlock = pStackBase;
7349
Bram Moolenaara466c992005-07-09 21:03:22 +00007350 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 {
7352 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7353 return 0;
7354
7355 pBlock += mbi.RegionSize;
7356
7357 if (mbi.State & MEM_COMMIT)
7358 break;
7359 }
7360
7361 /* mbi now describes the first committed block in the stack. */
7362 if (mbi.Protect & PAGE_GUARD)
7363 return 1;
7364
7365 /* decide where the guard page should start */
7366 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7367 pGuardPage = pLowestPossiblePage;
7368 else
7369 pGuardPage = (BYTE*)mbi.BaseAddress;
7370
7371 /* allocate the guard page */
7372 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7373 return 0;
7374
7375 /* apply the guard attribute to the page */
7376 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7377 &dummy))
7378 return 0;
7379 }
7380
7381 return 1;
7382}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007383#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007385
7386#if defined(FEAT_MBYTE) || defined(PROTO)
7387/*
7388 * The command line arguments in UCS2
7389 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007390static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007391static LPWSTR *ArglistW = NULL;
7392static int global_argc = 0;
7393static char **global_argv;
7394
7395static int used_file_argc = 0; /* last argument in global_argv[] used
7396 for the argument list. */
7397static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7398 command line arguments added to
7399 the argument list */
7400static int used_file_count = 0; /* nr of entries in used_file_indexes */
7401static int used_file_literal = FALSE; /* take file names literally */
7402static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007403static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007404static int used_alist_count = 0;
7405
7406
7407/*
7408 * Get the command line arguments. Unicode version.
7409 * Returns argc. Zero when something fails.
7410 */
7411 int
7412get_cmd_argsW(char ***argvp)
7413{
7414 char **argv = NULL;
7415 int argc = 0;
7416 int i;
7417
Bram Moolenaar14993322014-09-09 12:25:33 +02007418 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007419 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7420 if (ArglistW != NULL)
7421 {
7422 argv = malloc((nArgsW + 1) * sizeof(char *));
7423 if (argv != NULL)
7424 {
7425 argc = nArgsW;
7426 argv[argc] = NULL;
7427 for (i = 0; i < argc; ++i)
7428 {
7429 int len;
7430
7431 /* Convert each Unicode argument to the current codepage. */
7432 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007433 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007434 (LPSTR *)&argv[i], &len, 0, 0);
7435 if (argv[i] == NULL)
7436 {
7437 /* Out of memory, clear everything. */
7438 while (i > 0)
7439 free(argv[--i]);
7440 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007441 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007442 argc = 0;
7443 }
7444 }
7445 }
7446 }
7447
7448 global_argc = argc;
7449 global_argv = argv;
7450 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007451 {
7452 if (used_file_indexes != NULL)
7453 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007454 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007455 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007456
7457 if (argvp != NULL)
7458 *argvp = argv;
7459 return argc;
7460}
7461
7462 void
7463free_cmd_argsW(void)
7464{
7465 if (ArglistW != NULL)
7466 {
7467 GlobalFree(ArglistW);
7468 ArglistW = NULL;
7469 }
7470}
7471
7472/*
7473 * Remember "name" is an argument that was added to the argument list.
7474 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7475 * is called.
7476 */
7477 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007478used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007479{
7480 int i;
7481
7482 if (used_file_indexes == NULL)
7483 return;
7484 for (i = used_file_argc + 1; i < global_argc; ++i)
7485 if (STRCMP(global_argv[i], name) == 0)
7486 {
7487 used_file_argc = i;
7488 used_file_indexes[used_file_count++] = i;
7489 break;
7490 }
7491 used_file_literal = literal;
7492 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007493 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007494}
7495
7496/*
7497 * Remember the length of the argument list as it was. If it changes then we
7498 * leave it alone when 'encoding' is set.
7499 */
7500 void
7501set_alist_count(void)
7502{
7503 used_alist_count = GARGCOUNT;
7504}
7505
7506/*
7507 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7508 * has been changed while starting up. Use the UCS-2 command line arguments
7509 * and convert them to 'encoding'.
7510 */
7511 void
7512fix_arg_enc(void)
7513{
7514 int i;
7515 int idx;
7516 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007517 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007518
7519 /* Safety checks:
7520 * - if argument count differs between the wide and non-wide argument
7521 * list, something must be wrong.
7522 * - the file name arguments must have been located.
7523 * - the length of the argument list wasn't changed by the user.
7524 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007525 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007526 || ArglistW == NULL
7527 || used_file_indexes == NULL
7528 || used_file_count == 0
7529 || used_alist_count != GARGCOUNT)
7530 return;
7531
Bram Moolenaar86b68352004-12-27 21:59:20 +00007532 /* Remember the buffer numbers for the arguments. */
7533 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7534 if (fnum_list == NULL)
7535 return; /* out of memory */
7536 for (i = 0; i < GARGCOUNT; ++i)
7537 fnum_list[i] = GARGLIST[i].ae_fnum;
7538
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007539 /* Clear the argument list. Make room for the new arguments. */
7540 alist_clear(&global_alist);
7541 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007542 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007543
7544 for (i = 0; i < used_file_count; ++i)
7545 {
7546 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007547 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007548 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007549 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007550 int literal = used_file_literal;
7551
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007552#ifdef FEAT_DIFF
7553 /* When using diff mode may need to concatenate file name to
7554 * directory name. Just like it's done in main(). */
7555 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7556 && !mch_isdir(alist_name(&GARGLIST[0])))
7557 {
7558 char_u *r;
7559
7560 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7561 if (r != NULL)
7562 {
7563 vim_free(str);
7564 str = r;
7565 }
7566 }
7567#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007568 /* Re-use the old buffer by renaming it. When not using literal
7569 * names it's done by alist_expand() below. */
7570 if (used_file_literal)
7571 buf_set_name(fnum_list[i], str);
7572
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007573 /* Check backtick literal. backtick literal is already expanded in
7574 * main.c, so this part add str as literal. */
7575 if (literal == FALSE)
7576 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007577 size_t len = STRLEN(str);
7578
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007579 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7580 literal = TRUE;
7581 }
7582 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007583 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007584 }
7585
7586 if (!used_file_literal)
7587 {
7588 /* Now expand wildcards in the arguments. */
7589 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7590 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007591 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7592 * Also, unset wildignore to not be influenced by this option.
7593 * The arguments specified in command-line should be kept even if
7594 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007595 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007596 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007597 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007598 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007599 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007600 }
7601
7602 /* If wildcard expansion failed, we are editing the first file of the
7603 * arglist and there is no file name: Edit the first argument now. */
7604 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7605 {
7606 do_cmdline_cmd((char_u *)":rewind");
7607 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007608 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007609 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007610
7611 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007612}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007614
7615 int
7616mch_setenv(char *var, char *value, int x)
7617{
7618 char_u *envbuf;
7619
7620 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7621 if (envbuf == NULL)
7622 return -1;
7623
7624 sprintf((char *)envbuf, "%s=%s", var, value);
7625
7626#ifdef FEAT_MBYTE
7627 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7628 {
7629 WCHAR *p = enc_to_utf16(envbuf, NULL);
7630
7631 vim_free(envbuf);
7632 if (p == NULL)
7633 return -1;
7634 _wputenv(p);
7635# ifdef libintl_wputenv
7636 libintl_wputenv(p);
7637# endif
7638 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7639 vim_free(p);
7640 }
7641 else
7642#endif
7643 {
7644 _putenv((char *)envbuf);
7645# ifdef libintl_putenv
7646 libintl_putenv((char *)envbuf);
7647# endif
7648 /* Unlike Un*x systems, we can free the string for _putenv(). */
7649 vim_free(envbuf);
7650 }
7651
7652 return 0;
7653}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007654
7655#ifndef FEAT_GUI_W32
7656
7657/*
7658 * Support for 256 colors and 24-bit colors was added in Windows 10
7659 * version 1703 (Creators update).
7660 */
7661# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7662
7663 static void
7664vtp_init(void)
7665{
7666 DWORD ver, mode;
7667 HMODULE hKerneldll;
7668 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007669# ifdef FEAT_TERMGUICOLORS
7670 COLORREF fg, bg;
7671# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007672
7673 ver = get_build_number();
7674 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7675 GetConsoleMode(g_hConOut, &mode);
7676 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7677 if (SetConsoleMode(g_hConOut, mode) == 0)
7678 vtp_working = 0;
7679
7680 /* Use functions supported from Vista */
7681 hKerneldll = GetModuleHandle("kernel32.dll");
7682 if (hKerneldll != NULL)
7683 {
7684 pGetConsoleScreenBufferInfoEx =
7685 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7686 hKerneldll, "GetConsoleScreenBufferInfoEx");
7687 pSetConsoleScreenBufferInfoEx =
7688 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7689 hKerneldll, "SetConsoleScreenBufferInfoEx");
7690 if (pGetConsoleScreenBufferInfoEx != NULL
7691 && pSetConsoleScreenBufferInfoEx != NULL)
7692 has_csbiex = TRUE;
7693 }
7694
7695 csbi.cbSize = sizeof(csbi);
7696 if (has_csbiex)
7697 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007698 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7699 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7700
7701# ifdef FEAT_TERMGUICOLORS
7702 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7703 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7704 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7705 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7706 default_console_color_bg = bg;
7707 default_console_color_fg = fg;
7708#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007709
7710 set_console_color_rgb();
7711}
7712
7713 static void
7714vtp_exit(void)
7715{
7716 reset_console_color_rgb();
7717}
7718
7719 static int
7720vtp_printf(
7721 char *format,
7722 ...)
7723{
7724 char_u buf[100];
7725 va_list list;
7726 DWORD result;
7727
7728 va_start(list, format);
7729 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7730 va_end(list);
7731 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7732 return (int)result;
7733}
7734
7735 static void
7736vtp_sgr_bulk(
7737 int arg)
7738{
7739 int args[1];
7740
7741 args[0] = arg;
7742 vtp_sgr_bulks(1, args);
7743}
7744
7745 static void
7746vtp_sgr_bulks(
7747 int argc,
7748 int *args
7749)
7750{
7751 /* 2('\033[') + 4('255.') * 16 + NUL */
7752 char_u buf[2 + (4 * 16) + 1];
7753 char_u *p;
7754 int i;
7755
7756 p = buf;
7757 *p++ = '\033';
7758 *p++ = '[';
7759
7760 for (i = 0; i < argc; ++i)
7761 {
7762 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7763 *p++ = ';';
7764 }
7765 p--;
7766 *p++ = 'm';
7767 *p = NUL;
7768 vtp_printf((char *)buf);
7769}
7770
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007771# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007772 static int
7773ctermtoxterm(
7774 int cterm)
7775{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007776 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007777
7778 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7779 return (((int)r << 16) | ((int)g << 8) | (int)b);
7780}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007781# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007782
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007783 static void
7784set_console_color_rgb(void)
7785{
7786# ifdef FEAT_TERMGUICOLORS
7787 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7788 int id;
7789 guicolor_T fg = INVALCOLOR;
7790 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007791 int ctermfg;
7792 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007793
7794 if (!USE_VTP)
7795 return;
7796
7797 id = syn_name2id((char_u *)"Normal");
7798 if (id > 0)
7799 syn_id2colors(id, &fg, &bg);
7800 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007801 {
7802 ctermfg = -1;
7803 if (id > 0)
7804 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007805 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7806 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007807 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007808 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007809 {
7810 ctermbg = -1;
7811 if (id > 0)
7812 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007813 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7814 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007815 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007816 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7817 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7818
7819 csbi.cbSize = sizeof(csbi);
7820 if (has_csbiex)
7821 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7822
7823 csbi.cbSize = sizeof(csbi);
7824 csbi.srWindow.Right += 1;
7825 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007826 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7827 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007828 if (has_csbiex)
7829 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7830# endif
7831}
7832
7833 static void
7834reset_console_color_rgb(void)
7835{
7836# ifdef FEAT_TERMGUICOLORS
7837 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7838
7839 csbi.cbSize = sizeof(csbi);
7840 if (has_csbiex)
7841 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7842
7843 csbi.cbSize = sizeof(csbi);
7844 csbi.srWindow.Right += 1;
7845 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007846 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7847 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007848 if (has_csbiex)
7849 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7850# endif
7851}
7852
7853 void
7854control_console_color_rgb(void)
7855{
7856 if (USE_VTP)
7857 set_console_color_rgb();
7858 else
7859 reset_console_color_rgb();
7860}
7861
7862 int
7863has_vtp_working(void)
7864{
7865 return vtp_working;
7866}
7867
7868 int
7869use_vtp(void)
7870{
7871 return USE_VTP;
7872}
7873
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007874 int
7875is_term_win32(void)
7876{
7877 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7878}
7879
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007880#endif