blob: 3ea1fe321e52349e0f5de0a2d269175b5e98dab4 [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();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100636 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200637 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 Moolenaarf9e3e092019-01-13 23:38:42 +0100651 semsg(_(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 Moolenaar0cc7b2d2018-10-07 15:49:56 +0200855// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 { 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 Moolenaar0cc7b2d2018-10-07 15:49:56 +0200868 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
869 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200871 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
872 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
873 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
874 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
875 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
876 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
877 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
878 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
879 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
880 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200882 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883
884#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200885 // Most people don't have F13-F20, but what the hell...
886 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
887 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
888 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
889 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
890 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
891 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
892 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
893 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200895 { 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 '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200900 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
901 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
902 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
903 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
904 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
905 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
906 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
907 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
908 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
909 // Sorry, out of number space! <negri>
910 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
911
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912};
913
914
915#ifdef _MSC_VER
916// The ToAscii bug destroys several registers. Need to turn off optimization
917// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000918# pragma warning(push)
919# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920# pragma optimize("", off)
921#endif
922
923#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200924# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200926# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927#endif
928
929/* The return code indicates key code size. */
930 static int
931#ifdef __BORLANDC__
932 __stdcall
933#endif
934win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000935 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936{
937 UINT uMods = pker->dwControlKeyState;
938 static int s_iIsDead = 0;
939 static WORD awAnsiCode[2];
940 static BYTE abKeystate[256];
941
942
943 if (s_iIsDead == 2)
944 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200945 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 s_iIsDead = 0;
947 return 1;
948 }
949
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 return 1;
952
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200953 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957
958 if (uMods & SHIFT_PRESSED)
959 abKeystate[VK_SHIFT] = 0x80;
960 if (uMods & CAPSLOCK_ON)
961 abKeystate[VK_CAPITAL] = 1;
962
963 if ((uMods & ALT_GR) == ALT_GR)
964 {
965 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
966 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
967 }
968
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200969 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
970 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971
972 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200973 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974
975 return s_iIsDead;
976}
977
978#ifdef _MSC_VER
979/* MUST switch optimization on again here, otherwise a call to
980 * decode_key_event() may crash (e.g. when hitting caps-lock) */
981# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000982# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
984# if (_MSC_VER < 1100)
985/* MUST turn off global optimisation for this next function, or
986 * pressing ctrl-minus in insert mode crashes Vim when built with
987 * VC4.1. -- negri. */
988# pragma optimize("g", off)
989# endif
990#endif
991
992static BOOL g_fJustGotFocus = FALSE;
993
994/*
995 * Decode a KEY_EVENT into one or two keystrokes
996 */
997 static BOOL
998decode_key_event(
999 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001000 WCHAR *pch,
1001 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 int *pmodifiers,
1003 BOOL fDoPost)
1004{
1005 int i;
1006 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1007
1008 *pch = *pch2 = NUL;
1009 g_fJustGotFocus = FALSE;
1010
1011 /* ignore key up events */
1012 if (!pker->bKeyDown)
1013 return FALSE;
1014
1015 /* ignore some keystrokes */
1016 switch (pker->wVirtualKeyCode)
1017 {
1018 /* modifiers */
1019 case VK_SHIFT:
1020 case VK_CONTROL:
1021 case VK_MENU: /* Alt key */
1022 return FALSE;
1023
1024 default:
1025 break;
1026 }
1027
1028 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001029 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 {
1031 /* Ctrl-6 is Ctrl-^ */
1032 if (pker->wVirtualKeyCode == '6')
1033 {
1034 *pch = Ctrl_HAT;
1035 return TRUE;
1036 }
1037 /* Ctrl-2 is Ctrl-@ */
1038 else if (pker->wVirtualKeyCode == '2')
1039 {
1040 *pch = NUL;
1041 return TRUE;
1042 }
1043 /* Ctrl-- is Ctrl-_ */
1044 else if (pker->wVirtualKeyCode == 0xBD)
1045 {
1046 *pch = Ctrl__;
1047 return TRUE;
1048 }
1049 }
1050
1051 /* Shift-TAB */
1052 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1053 {
1054 *pch = K_NUL;
1055 *pch2 = '\017';
1056 return TRUE;
1057 }
1058
1059 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1060 {
1061 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1062 {
1063 if (nModifs == 0)
1064 *pch = VirtKeyMap[i].chAlone;
1065 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1066 *pch = VirtKeyMap[i].chShift;
1067 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1068 *pch = VirtKeyMap[i].chCtrl;
1069 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1070 *pch = VirtKeyMap[i].chAlt;
1071
1072 if (*pch != 0)
1073 {
1074 if (VirtKeyMap[i].fAnsiKey)
1075 {
1076 *pch2 = *pch;
1077 *pch = K_NUL;
1078 }
1079
1080 return TRUE;
1081 }
1082 }
1083 }
1084
1085 i = win32_kbd_patch_key(pker);
1086
1087 if (i < 0)
1088 *pch = NUL;
1089 else
1090 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001091 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092
1093 if (pmodifiers != NULL)
1094 {
1095 /* Pass on the ALT key as a modifier, but only when not combined
1096 * with CTRL (which is ALTGR). */
1097 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1098 *pmodifiers |= MOD_MASK_ALT;
1099
1100 /* Pass on SHIFT only for special keys, because we don't know when
1101 * it's already included with the character. */
1102 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1103 *pmodifiers |= MOD_MASK_SHIFT;
1104
1105 /* Pass on CTRL only for non-special keys, because we don't know
1106 * when it's already included with the character. And not when
1107 * combined with ALT (which is ALTGR). */
1108 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1109 && *pch >= 0x20 && *pch < 0x80)
1110 *pmodifiers |= MOD_MASK_CTRL;
1111 }
1112 }
1113
1114 return (*pch != NUL);
1115}
1116
1117#ifdef _MSC_VER
1118# pragma optimize("", on)
1119#endif
1120
1121#endif /* FEAT_GUI_W32 */
1122
1123
1124#ifdef FEAT_MOUSE
1125
1126/*
1127 * For the GUI the mouse handling is in gui_w32.c.
1128 */
1129# ifdef FEAT_GUI_W32
1130 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001131mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132{
1133}
1134# else
1135static int g_fMouseAvail = FALSE; /* mouse present */
1136static int g_fMouseActive = FALSE; /* mouse enabled */
1137static int g_nMouseClick = -1; /* mouse status */
1138static int g_xMouse; /* mouse x coordinate */
1139static int g_yMouse; /* mouse y coordinate */
1140
1141/*
1142 * Enable or disable mouse input
1143 */
1144 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001145mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146{
1147 DWORD cmodein;
1148
1149 if (!g_fMouseAvail)
1150 return;
1151
1152 g_fMouseActive = on;
1153 GetConsoleMode(g_hConIn, &cmodein);
1154
1155 if (g_fMouseActive)
1156 cmodein |= ENABLE_MOUSE_INPUT;
1157 else
1158 cmodein &= ~ENABLE_MOUSE_INPUT;
1159
1160 SetConsoleMode(g_hConIn, cmodein);
1161}
1162
Bram Moolenaar157d8132018-03-06 17:09:20 +01001163
1164#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1165/*
1166 * Called when 'balloonevalterm' changed.
1167 */
1168 void
1169mch_bevalterm_changed(void)
1170{
1171 mch_setmouse(g_fMouseActive);
1172}
1173#endif
1174
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175/*
1176 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1177 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1178 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1179 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1180 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1181 * and we return the mouse position in g_xMouse and g_yMouse.
1182 *
1183 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1184 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1185 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1186 *
1187 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1188 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1189 *
1190 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1191 * moves, even if it stays within the same character cell. We ignore
1192 * all MOUSE_MOVED messages if the position hasn't really changed, and
1193 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1194 * we're only interested in MOUSE_DRAG).
1195 *
1196 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1197 * 2-button mouses by pressing the left & right buttons simultaneously.
1198 * In practice, it's almost impossible to click both at the same time,
1199 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1200 * in such cases, if the user is clicking quickly.
1201 */
1202 static BOOL
1203decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001204 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205{
1206 static int s_nOldButton = -1;
1207 static int s_nOldMouseClick = -1;
1208 static int s_xOldMouse = -1;
1209 static int s_yOldMouse = -1;
1210 static linenr_T s_old_topline = 0;
1211#ifdef FEAT_DIFF
1212 static int s_old_topfill = 0;
1213#endif
1214 static int s_cClicks = 1;
1215 static BOOL s_fReleased = TRUE;
1216 static DWORD s_dwLastClickTime = 0;
1217 static BOOL s_fNextIsMiddle = FALSE;
1218
1219 static DWORD cButtons = 0; /* number of buttons supported */
1220
1221 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1222 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1223 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1224 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1225
1226 int nButton;
1227
1228 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1229 cButtons = 2;
1230
1231 if (!g_fMouseAvail || !g_fMouseActive)
1232 {
1233 g_nMouseClick = -1;
1234 return FALSE;
1235 }
1236
1237 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1238 if (g_fJustGotFocus)
1239 {
1240 g_fJustGotFocus = FALSE;
1241 return FALSE;
1242 }
1243
1244 /* unprocessed mouse click? */
1245 if (g_nMouseClick != -1)
1246 return TRUE;
1247
1248 nButton = -1;
1249 g_xMouse = pmer->dwMousePosition.X;
1250 g_yMouse = pmer->dwMousePosition.Y;
1251
1252 if (pmer->dwEventFlags == MOUSE_MOVED)
1253 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001254 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255 * events even when the mouse moves only within a char cell.) */
1256 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1257 return FALSE;
1258 }
1259
1260 /* If no buttons are pressed... */
1261 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1262 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 nButton = MOUSE_RELEASE;
1264
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1266 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001267 {
1268#ifdef FEAT_BEVAL_TERM
1269 /* do return mouse move events when we want them */
1270 if (p_bevalterm)
1271 nButton = MOUSE_DRAG;
1272 else
1273#endif
1274 return FALSE;
1275 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 s_fReleased = TRUE;
1278 }
1279 else /* one or more buttons pressed */
1280 {
1281 /* on a 2-button mouse, hold down left and right buttons
1282 * simultaneously to get MIDDLE. */
1283
1284 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1285 {
1286 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1287
1288 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001289 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001290 if (dwLR == LEFT || dwLR == RIGHT)
1291 {
1292 for (;;)
1293 {
1294 /* wait a short time for next input event */
1295 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1296 != WAIT_OBJECT_0)
1297 break;
1298 else
1299 {
1300 DWORD cRecords = 0;
1301 INPUT_RECORD ir;
1302 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1303
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001304 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305
1306 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1307 || !(pmer2->dwButtonState & LEFT_RIGHT))
1308 break;
1309 else
1310 {
1311 if (pmer2->dwEventFlags != MOUSE_MOVED)
1312 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001313 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 return decode_mouse_event(pmer2);
1316 }
1317 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1318 s_yOldMouse == pmer2->dwMousePosition.Y)
1319 {
1320 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001321 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322
1323 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001324 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325
1326 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1327 break;
1328 }
1329 else
1330 break;
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 if (s_fNextIsMiddle)
1338 {
1339 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1340 ? MOUSE_DRAG : MOUSE_MIDDLE;
1341 s_fNextIsMiddle = FALSE;
1342 }
1343 else if (cButtons == 2 &&
1344 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1345 {
1346 nButton = MOUSE_MIDDLE;
1347
1348 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1349 {
1350 s_fNextIsMiddle = TRUE;
1351 nButton = MOUSE_RELEASE;
1352 }
1353 }
1354 else if ((pmer->dwButtonState & LEFT) == LEFT)
1355 nButton = MOUSE_LEFT;
1356 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1357 nButton = MOUSE_MIDDLE;
1358 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1359 nButton = MOUSE_RIGHT;
1360
1361 if (! s_fReleased && ! s_fNextIsMiddle
1362 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1363 return FALSE;
1364
1365 s_fReleased = s_fNextIsMiddle;
1366 }
1367
1368 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1369 {
1370 /* button pressed or released, without mouse moving */
1371 if (nButton != -1 && nButton != MOUSE_RELEASE)
1372 {
1373 DWORD dwCurrentTime = GetTickCount();
1374
1375 if (s_xOldMouse != g_xMouse
1376 || s_yOldMouse != g_yMouse
1377 || s_nOldButton != nButton
1378 || s_old_topline != curwin->w_topline
1379#ifdef FEAT_DIFF
1380 || s_old_topfill != curwin->w_topfill
1381#endif
1382 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1383 {
1384 s_cClicks = 1;
1385 }
1386 else if (++s_cClicks > 4)
1387 {
1388 s_cClicks = 1;
1389 }
1390
1391 s_dwLastClickTime = dwCurrentTime;
1392 }
1393 }
1394 else if (pmer->dwEventFlags == MOUSE_MOVED)
1395 {
1396 if (nButton != -1 && nButton != MOUSE_RELEASE)
1397 nButton = MOUSE_DRAG;
1398
1399 s_cClicks = 1;
1400 }
1401
1402 if (nButton == -1)
1403 return FALSE;
1404
1405 if (nButton != MOUSE_RELEASE)
1406 s_nOldButton = nButton;
1407
1408 g_nMouseClick = nButton;
1409
1410 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1411 g_nMouseClick |= MOUSE_SHIFT;
1412 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1413 g_nMouseClick |= MOUSE_CTRL;
1414 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1415 g_nMouseClick |= MOUSE_ALT;
1416
1417 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1418 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1419
1420 /* only pass on interesting (i.e., different) mouse events */
1421 if (s_xOldMouse == g_xMouse
1422 && s_yOldMouse == g_yMouse
1423 && s_nOldMouseClick == g_nMouseClick)
1424 {
1425 g_nMouseClick = -1;
1426 return FALSE;
1427 }
1428
1429 s_xOldMouse = g_xMouse;
1430 s_yOldMouse = g_yMouse;
1431 s_old_topline = curwin->w_topline;
1432#ifdef FEAT_DIFF
1433 s_old_topfill = curwin->w_topfill;
1434#endif
1435 s_nOldMouseClick = g_nMouseClick;
1436
1437 return TRUE;
1438}
1439
1440# endif /* FEAT_GUI_W32 */
1441#endif /* FEAT_MOUSE */
1442
1443
1444#ifdef MCH_CURSOR_SHAPE
1445/*
1446 * Set the shape of the cursor.
1447 * 'thickness' can be from 1 (thin) to 99 (block)
1448 */
1449 static void
1450mch_set_cursor_shape(int thickness)
1451{
1452 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1453 ConsoleCursorInfo.dwSize = thickness;
1454 ConsoleCursorInfo.bVisible = s_cursor_visible;
1455
1456 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1457 if (s_cursor_visible)
1458 SetConsoleCursorPosition(g_hConOut, g_coord);
1459}
1460
1461 void
1462mch_update_cursor(void)
1463{
1464 int idx;
1465 int thickness;
1466
1467 /*
1468 * How the cursor is drawn depends on the current mode.
1469 */
1470 idx = get_shape_idx(FALSE);
1471
1472 if (shape_table[idx].shape == SHAPE_BLOCK)
1473 thickness = 99; /* 100 doesn't work on W95 */
1474 else
1475 thickness = shape_table[idx].percentage;
1476 mch_set_cursor_shape(thickness);
1477}
1478#endif
1479
1480#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1481/*
1482 * Handle FOCUS_EVENT.
1483 */
1484 static void
1485handle_focus_event(INPUT_RECORD ir)
1486{
1487 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1488 ui_focus_change((int)g_fJustGotFocus);
1489}
1490
1491/*
1492 * Wait until console input from keyboard or mouse is available,
1493 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001494 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 * Return TRUE if something is available FALSE if not.
1496 */
1497 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001498WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499{
1500 DWORD dwNow = 0, dwEndTime = 0;
1501 INPUT_RECORD ir;
1502 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001503 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001504#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001505 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001506#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507
1508 if (msec > 0)
1509 /* Wait until the specified time has elapsed. */
1510 dwEndTime = GetTickCount() + msec;
1511 else if (msec < 0)
1512 /* Wait forever. */
1513 dwEndTime = INFINITE;
1514
1515 /* We need to loop until the end of the time period, because
1516 * we might get multiple unusable mouse events in that time.
1517 */
1518 for (;;)
1519 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001520 // Only process messages when waiting.
1521 if (msec != 0)
1522 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001523#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001524 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001525#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001526#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001527 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001530 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001532 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001533
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 if (0
1535#ifdef FEAT_MOUSE
1536 || g_nMouseClick != -1
1537#endif
1538#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001539 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540#endif
1541 )
1542 return TRUE;
1543
1544 if (msec > 0)
1545 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001546 /* If the specified wait time has passed, return. Beware that
1547 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001549 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 break;
1551 }
1552 if (msec != 0)
1553 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001554 DWORD dwWaitTime = dwEndTime - dwNow;
1555
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001556#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001557 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001558 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001559 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001560 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001561 /* If there is readahead then parse_queued_messages() timed out
1562 * and we should call it again soon. */
1563 if (channel_any_readahead())
1564 dwWaitTime = 10;
1565 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001566#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001567#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001568 if (p_beval && dwWaitTime > 100)
1569 /* The 'balloonexpr' may indirectly invoke a callback while
1570 * waiting for a character, need to check often. */
1571 dwWaitTime = 100;
1572#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001573#ifdef FEAT_MZSCHEME
1574 if (mzthreads_allowed() && p_mzq > 0
1575 && (msec < 0 || (long)dwWaitTime > p_mzq))
1576 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1577#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001578#ifdef FEAT_TIMERS
1579 {
1580 long due_time;
1581
1582 /* When waiting very briefly don't trigger timers. */
1583 if (dwWaitTime > 10)
1584 {
1585 /* Trigger timers and then get the time in msec until the
1586 * next one is due. Wait up to that time. */
1587 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001588 if (typebuf.tb_change_cnt != tb_change_cnt)
1589 {
1590 /* timer may have used feedkeys() */
1591 return FALSE;
1592 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1594 dwWaitTime = due_time;
1595 }
1596 }
1597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598#ifdef FEAT_CLIENTSERVER
1599 /* Wait for either an event on the console input or a message in
1600 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001601 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001602 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001604 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605#endif
1606 continue;
1607 }
1608
1609 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001610 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611
1612#ifdef FEAT_MBYTE_IME
1613 if (State & CMDLINE && msg_row == Rows - 1)
1614 {
1615 CONSOLE_SCREEN_BUFFER_INFO csbi;
1616
1617 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1618 {
1619 if (csbi.dwCursorPosition.Y != msg_row)
1620 {
1621 /* The screen is now messed up, must redraw the
1622 * command line and later all the windows. */
1623 redraw_all_later(CLEAR);
1624 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1625 redrawcmd();
1626 }
1627 }
1628 }
1629#endif
1630
1631 if (cRecords > 0)
1632 {
1633 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1634 {
1635#ifdef FEAT_MBYTE_IME
1636 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1637 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001638 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1640 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001641 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 continue;
1643 }
1644#endif
1645 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1646 NULL, FALSE))
1647 return TRUE;
1648 }
1649
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001650 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652 if (ir.EventType == FOCUS_EVENT)
1653 handle_focus_event(ir);
1654 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001655 {
1656 /* Only call shell_resized() when the size actually change to
1657 * avoid the screen is cleard. */
1658 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1659 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1660 shell_resized();
1661 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662#ifdef FEAT_MOUSE
1663 else if (ir.EventType == MOUSE_EVENT
1664 && decode_mouse_event(&ir.Event.MouseEvent))
1665 return TRUE;
1666#endif
1667 }
1668 else if (msec == 0)
1669 break;
1670 }
1671
1672#ifdef FEAT_CLIENTSERVER
1673 /* Something might have been received while we were waiting. */
1674 if (input_available())
1675 return TRUE;
1676#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001677
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 return FALSE;
1679}
1680
1681#ifndef FEAT_GUI_MSWIN
1682/*
1683 * return non-zero if a character is available
1684 */
1685 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001686mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001688 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001690
1691# if defined(FEAT_TERMINAL) || defined(PROTO)
1692/*
1693 * Check for any pending input or messages.
1694 */
1695 int
1696mch_check_messages(void)
1697{
1698 return WaitForChar(0L, TRUE);
1699}
1700# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701#endif
1702
1703/*
1704 * Create the console input. Used when reading stdin doesn't work.
1705 */
1706 static void
1707create_conin(void)
1708{
1709 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1710 FILE_SHARE_READ|FILE_SHARE_WRITE,
1711 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001712 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 did_create_conin = TRUE;
1714}
1715
1716/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001717 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001719 static WCHAR
1720tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001722 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723
1724 for (;;)
1725 {
1726 INPUT_RECORD ir;
1727 DWORD cRecords = 0;
1728
1729#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001730 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 if (input_available())
1732 return 0;
1733# ifdef FEAT_MOUSE
1734 if (g_nMouseClick != -1)
1735 return 0;
1736# endif
1737#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001738 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 {
1740 if (did_create_conin)
1741 read_error_exit();
1742 create_conin();
1743 continue;
1744 }
1745
1746 if (ir.EventType == KEY_EVENT)
1747 {
1748 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1749 pmodifiers, TRUE))
1750 return ch;
1751 }
1752 else if (ir.EventType == FOCUS_EVENT)
1753 handle_focus_event(ir);
1754 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1755 shell_resized();
1756#ifdef FEAT_MOUSE
1757 else if (ir.EventType == MOUSE_EVENT)
1758 {
1759 if (decode_mouse_event(&ir.Event.MouseEvent))
1760 return 0;
1761 }
1762#endif
1763 }
1764}
1765#endif /* !FEAT_GUI_W32 */
1766
1767
1768/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001769 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770 * Get one or more characters from the keyboard or the mouse.
1771 * If time == 0, do not wait for characters.
1772 * If time == n, wait a short time for characters.
1773 * If time == -1, wait forever for characters.
1774 * Returns the number of characters read into buf.
1775 */
1776 int
1777mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001778 char_u *buf UNUSED,
1779 int maxlen UNUSED,
1780 long time UNUSED,
1781 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782{
1783#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1784
1785 int len;
1786 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787#define TYPEAHEADLEN 20
1788 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1789 static int typeaheadlen = 0;
1790
1791 /* First use any typeahead that was kept because "buf" was too small. */
1792 if (typeaheadlen > 0)
1793 goto theend;
1794
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 if (time >= 0)
1796 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001797 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
1800 else /* time == -1, wait forever */
1801 {
1802 mch_set_winsize_now(); /* Allow winsize changes from now on */
1803
Bram Moolenaar3918c952005-03-15 22:34:55 +00001804 /*
1805 * If there is no character available within 2 seconds (default)
1806 * write the autoscript file to disk. Or cause the CursorHold event
1807 * to be triggered.
1808 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001809 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001811 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001813 buf[0] = K_SPECIAL;
1814 buf[1] = KS_EXTRA;
1815 buf[2] = (int)KE_CURSORHOLD;
1816 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001818 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 }
1820 }
1821
1822 /*
1823 * Try to read as many characters as there are, until the buffer is full.
1824 */
1825
1826 /* we will get at least one key. Get more if they are available. */
1827 g_fCBrkPressed = FALSE;
1828
1829#ifdef MCH_WRITE_DUMP
1830 if (fdDump)
1831 fputc('[', fdDump);
1832#endif
1833
1834 /* Keep looping until there is something in the typeahead buffer and more
1835 * to get and still room in the buffer (up to two bytes for a char and
1836 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001837 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 && typeaheadlen + 5 <= TYPEAHEADLEN)
1839 {
1840 if (typebuf_changed(tb_change_cnt))
1841 {
1842 /* "buf" may be invalid now if a client put something in the
1843 * typeahead buffer and "buf" is in the typeahead buffer. */
1844 typeaheadlen = 0;
1845 break;
1846 }
1847#ifdef FEAT_MOUSE
1848 if (g_nMouseClick != -1)
1849 {
1850# ifdef MCH_WRITE_DUMP
1851 if (fdDump)
1852 fprintf(fdDump, "{%02x @ %d, %d}",
1853 g_nMouseClick, g_xMouse, g_yMouse);
1854# endif
1855 typeahead[typeaheadlen++] = ESC + 128;
1856 typeahead[typeaheadlen++] = 'M';
1857 typeahead[typeaheadlen++] = g_nMouseClick;
1858 typeahead[typeaheadlen++] = g_xMouse + '!';
1859 typeahead[typeaheadlen++] = g_yMouse + '!';
1860 g_nMouseClick = -1;
1861 }
1862 else
1863#endif
1864 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001865 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001866 int modifiers = 0;
1867
1868 c = tgetch(&modifiers, &ch2);
1869
1870 if (typebuf_changed(tb_change_cnt))
1871 {
1872 /* "buf" may be invalid now if a client put something in the
1873 * typeahead buffer and "buf" is in the typeahead buffer. */
1874 typeaheadlen = 0;
1875 break;
1876 }
1877
1878 if (c == Ctrl_C && ctrl_c_interrupts)
1879 {
1880#if defined(FEAT_CLIENTSERVER)
1881 trash_input_buf();
1882#endif
1883 got_int = TRUE;
1884 }
1885
1886#ifdef FEAT_MOUSE
1887 if (g_nMouseClick == -1)
1888#endif
1889 {
1890 int n = 1;
1891
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001892#ifdef FEAT_MBYTE
1893 if (ch2 == NUL)
1894 {
1895 int i;
1896 char_u *p;
1897 WCHAR ch[2];
1898
1899 ch[0] = c;
1900 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1901 {
1902 ch[1] = tgetch(&modifiers, &ch2);
1903 n++;
1904 }
1905 p = utf16_to_enc(ch, &n);
1906 if (p != NULL)
1907 {
1908 for (i = 0; i < n; i++)
1909 typeahead[typeaheadlen + i] = p[i];
1910 vim_free(p);
1911 }
1912 }
1913 else
1914#endif
1915 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 if (ch2 != NUL)
1917 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001918 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001919 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001920 switch (ch2)
1921 {
1922 case (WCHAR)'\324': // SHIFT+Insert
1923 case (WCHAR)'\325': // CTRL+Insert
1924 case (WCHAR)'\327': // SHIFT+Delete
1925 case (WCHAR)'\330': // CTRL+Delete
1926 typeahead[typeaheadlen + n] = (char_u)ch2;
1927 n++;
1928 break;
1929
1930 default:
1931 typeahead[typeaheadlen + n] = 3;
1932 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1933 n += 2;
1934 break;
1935 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001936 }
1937 else
1938 {
1939 typeahead[typeaheadlen + n] = 3;
1940 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1941 n += 2;
1942 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001943 }
1944
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 /* Use the ALT key to set the 8th bit of the character
1946 * when it's one byte, the 8th bit isn't set yet and not
1947 * using a double-byte encoding (would become a lead
1948 * byte). */
1949 if ((modifiers & MOD_MASK_ALT)
1950 && n == 1
1951 && (typeahead[typeaheadlen] & 0x80) == 0
1952#ifdef FEAT_MBYTE
1953 && !enc_dbcs
1954#endif
1955 )
1956 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001957#ifdef FEAT_MBYTE
1958 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1959 typeahead + typeaheadlen);
1960#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001962#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 modifiers &= ~MOD_MASK_ALT;
1964 }
1965
1966 if (modifiers != 0)
1967 {
1968 /* Prepend modifiers to the character. */
1969 mch_memmove(typeahead + typeaheadlen + 3,
1970 typeahead + typeaheadlen, n);
1971 typeahead[typeaheadlen++] = K_SPECIAL;
1972 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1973 typeahead[typeaheadlen++] = modifiers;
1974 }
1975
1976 typeaheadlen += n;
1977
1978#ifdef MCH_WRITE_DUMP
1979 if (fdDump)
1980 fputc(c, fdDump);
1981#endif
1982 }
1983 }
1984 }
1985
1986#ifdef MCH_WRITE_DUMP
1987 if (fdDump)
1988 {
1989 fputs("]\n", fdDump);
1990 fflush(fdDump);
1991 }
1992#endif
1993
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994theend:
1995 /* Move typeahead to "buf", as much as fits. */
1996 len = 0;
1997 while (len < maxlen && typeaheadlen > 0)
1998 {
1999 buf[len++] = typeahead[0];
2000 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2001 }
2002 return len;
2003
2004#else /* FEAT_GUI_W32 */
2005 return 0;
2006#endif /* FEAT_GUI_W32 */
2007}
2008
Bram Moolenaar82881492012-11-20 16:53:39 +01002009#ifndef PROTO
2010# ifndef __MINGW32__
2011# include <shellapi.h> /* required for FindExecutable() */
2012# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013#endif
2014
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002015/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002016 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2017 * If "use_path" is FALSE: Return TRUE if "name" exists.
2018 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2019 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002020 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002021 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002023executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002025 char *dum;
2026 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002027 char *curpath, *newpath;
2028 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029
Bram Moolenaar43663192017-03-05 14:29:12 +01002030 if (!use_path)
2031 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002032 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002033 {
2034 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002035 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002036 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002037 *path = vim_strsave((char_u *)name);
2038 else
2039 *path = FullName_save((char_u *)name, FALSE);
2040 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002041 return TRUE;
2042 }
2043 return FALSE;
2044 }
2045
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002046#ifdef FEAT_MBYTE
2047 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002049 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002050 WCHAR fnamew[_MAX_PATH];
2051 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002052 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002053
2054 if (p != NULL)
2055 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002056 wcurpath = _wgetenv(L"PATH");
2057 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2058 * sizeof(WCHAR));
2059 if (wnewpath == NULL)
2060 return FALSE;
2061 wcscpy(wnewpath, L".;");
2062 wcscat(wnewpath, wcurpath);
2063 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2064 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002065 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002066 if (n == 0)
2067 return FALSE;
2068 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2069 return FALSE;
2070 if (path != NULL)
2071 *path = utf16_to_enc(fnamew, NULL);
2072 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002073 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002075#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002076
2077 curpath = getenv("PATH");
2078 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2079 if (newpath == NULL)
2080 return FALSE;
2081 STRCPY(newpath, ".;");
2082 STRCAT(newpath, curpath);
2083 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2084 vim_free(newpath);
2085 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002086 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002087 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002088 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002089 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002090 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002091 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092}
2093
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002094#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002095 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002096/*
2097 * Bad parameter handler.
2098 *
2099 * Certain MS CRT functions will intentionally crash when passed invalid
2100 * parameters to highlight possible security holes. Setting this function as
2101 * the bad parameter handler will prevent the crash.
2102 *
2103 * In debug builds the parameters contain CRT information that might help track
2104 * down the source of a problem, but in non-debug builds the arguments are all
2105 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2106 * worth allowing these to make debugging of issues easier.
2107 */
2108 static void
2109bad_param_handler(const wchar_t *expression,
2110 const wchar_t *function,
2111 const wchar_t *file,
2112 unsigned int line,
2113 uintptr_t pReserved)
2114{
2115}
2116
2117# define SET_INVALID_PARAM_HANDLER \
2118 ((void)_set_invalid_parameter_handler(bad_param_handler))
2119#else
2120# define SET_INVALID_PARAM_HANDLER
2121#endif
2122
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123#ifdef FEAT_GUI_W32
2124
2125/*
2126 * GUI version of mch_init().
2127 */
2128 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002129mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130{
2131#ifndef __MINGW32__
2132 extern int _fmode;
2133#endif
2134
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002135 /* Silently handle invalid parameters to CRT functions */
2136 SET_INVALID_PARAM_HANDLER;
2137
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 /* Let critical errors result in a failure, not in a dialog box. Required
2139 * for the timestamp test to work on removed floppies. */
2140 SetErrorMode(SEM_FAILCRITICALERRORS);
2141
2142 _fmode = O_BINARY; /* we do our own CR-LF translation */
2143
2144 /* Specify window size. Is there a place to get the default from? */
2145 Rows = 25;
2146 Columns = 80;
2147
2148 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 {
2150 char_u vimrun_location[_MAX_PATH + 4];
2151
2152 /* First try in same directory as gvim.exe */
2153 STRCPY(vimrun_location, exe_name);
2154 STRCPY(gettail(vimrun_location), "vimrun.exe");
2155 if (mch_getperm(vimrun_location) >= 0)
2156 {
2157 if (*skiptowhite(vimrun_location) != NUL)
2158 {
2159 /* Enclose path with white space in double quotes. */
2160 mch_memmove(vimrun_location + 1, vimrun_location,
2161 STRLEN(vimrun_location) + 1);
2162 *vimrun_location = '"';
2163 STRCPY(gettail(vimrun_location), "vimrun\" ");
2164 }
2165 else
2166 STRCPY(gettail(vimrun_location), "vimrun ");
2167
2168 vimrun_path = (char *)vim_strsave(vimrun_location);
2169 s_dont_use_vimrun = FALSE;
2170 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002171 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 s_dont_use_vimrun = FALSE;
2173
2174 /* Don't give the warning for a missing vimrun.exe right now, but only
2175 * when vimrun was supposed to be used. Don't bother people that do
2176 * not need vimrun.exe. */
2177 if (s_dont_use_vimrun)
2178 need_vimrun_warning = TRUE;
2179 }
2180
2181 /*
2182 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2183 * Otherwise the default "findstr /n" is used.
2184 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002185 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2187
2188#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002189 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190#endif
2191}
2192
2193
2194#else /* FEAT_GUI_W32 */
2195
2196#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2197#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2198
2199/*
2200 * ClearConsoleBuffer()
2201 * Description:
2202 * Clears the entire contents of the console screen buffer, using the
2203 * specified attribute.
2204 * Returns:
2205 * TRUE on success
2206 */
2207 static BOOL
2208ClearConsoleBuffer(WORD wAttribute)
2209{
2210 CONSOLE_SCREEN_BUFFER_INFO csbi;
2211 COORD coord;
2212 DWORD NumCells, dummy;
2213
2214 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2215 return FALSE;
2216
2217 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2218 coord.X = 0;
2219 coord.Y = 0;
2220 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2221 coord, &dummy))
2222 {
2223 return FALSE;
2224 }
2225 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2226 coord, &dummy))
2227 {
2228 return FALSE;
2229 }
2230
2231 return TRUE;
2232}
2233
2234/*
2235 * FitConsoleWindow()
2236 * Description:
2237 * Checks if the console window will fit within given buffer dimensions.
2238 * Also, if requested, will shrink the window to fit.
2239 * Returns:
2240 * TRUE on success
2241 */
2242 static BOOL
2243FitConsoleWindow(
2244 COORD dwBufferSize,
2245 BOOL WantAdjust)
2246{
2247 CONSOLE_SCREEN_BUFFER_INFO csbi;
2248 COORD dwWindowSize;
2249 BOOL NeedAdjust = FALSE;
2250
2251 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2252 {
2253 /*
2254 * A buffer resize will fail if the current console window does
2255 * not lie completely within that buffer. To avoid this, we might
2256 * have to move and possibly shrink the window.
2257 */
2258 if (csbi.srWindow.Right >= dwBufferSize.X)
2259 {
2260 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2261 if (dwWindowSize.X > dwBufferSize.X)
2262 dwWindowSize.X = dwBufferSize.X;
2263 csbi.srWindow.Right = dwBufferSize.X - 1;
2264 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2265 NeedAdjust = TRUE;
2266 }
2267 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2268 {
2269 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2270 if (dwWindowSize.Y > dwBufferSize.Y)
2271 dwWindowSize.Y = dwBufferSize.Y;
2272 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2273 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2274 NeedAdjust = TRUE;
2275 }
2276 if (NeedAdjust && WantAdjust)
2277 {
2278 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2279 return FALSE;
2280 }
2281 return TRUE;
2282 }
2283
2284 return FALSE;
2285}
2286
2287typedef struct ConsoleBufferStruct
2288{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002289 BOOL IsValid;
2290 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002291 PCHAR_INFO Buffer;
2292 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002293 PSMALL_RECT Regions;
2294 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002295} ConsoleBuffer;
2296
2297/*
2298 * SaveConsoleBuffer()
2299 * Description:
2300 * Saves important information about the console buffer, including the
2301 * actual buffer contents. The saved information is suitable for later
2302 * restoration by RestoreConsoleBuffer().
2303 * Returns:
2304 * TRUE if all information was saved; FALSE otherwise
2305 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2306 */
2307 static BOOL
2308SaveConsoleBuffer(
2309 ConsoleBuffer *cb)
2310{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002311 DWORD NumCells;
2312 COORD BufferCoord;
2313 SMALL_RECT ReadRegion;
2314 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002315 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002316
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 if (cb == NULL)
2318 return FALSE;
2319
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002320 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 {
2322 cb->IsValid = FALSE;
2323 return FALSE;
2324 }
2325 cb->IsValid = TRUE;
2326
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002327 /*
2328 * Allocate a buffer large enough to hold the entire console screen
2329 * buffer. If this ConsoleBuffer structure has already been initialized
2330 * with a buffer of the correct size, then just use that one.
2331 */
2332 if (!cb->IsValid || cb->Buffer == NULL ||
2333 cb->BufferSize.X != cb->Info.dwSize.X ||
2334 cb->BufferSize.Y != cb->Info.dwSize.Y)
2335 {
2336 cb->BufferSize.X = cb->Info.dwSize.X;
2337 cb->BufferSize.Y = cb->Info.dwSize.Y;
2338 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2339 vim_free(cb->Buffer);
2340 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2341 if (cb->Buffer == NULL)
2342 return FALSE;
2343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344
2345 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002346 * We will now copy the console screen buffer into our buffer.
2347 * ReadConsoleOutput() seems to be limited as far as how much you
2348 * can read at a time. Empirically, this number seems to be about
2349 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2350 * in chunks until it is all copied. The chunks will all have the
2351 * same horizontal characteristics, so initialize them now. The
2352 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002354 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002355 ReadRegion.Left = 0;
2356 ReadRegion.Right = cb->Info.dwSize.X - 1;
2357 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002358
2359 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2360 if (cb->Regions == NULL || numregions != cb->NumRegions)
2361 {
2362 cb->NumRegions = numregions;
2363 vim_free(cb->Regions);
2364 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2365 if (cb->Regions == NULL)
2366 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002367 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002368 return FALSE;
2369 }
2370 }
2371
2372 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002374 /*
2375 * Read into position (0, Y) in our buffer.
2376 */
2377 BufferCoord.Y = Y;
2378 /*
2379 * Read the region whose top left corner is (0, Y) and whose bottom
2380 * right corner is (width - 1, Y + Y_incr - 1). This should define
2381 * a region of size width by Y_incr. Don't worry if this region is
2382 * too large for the remaining buffer; it will be cropped.
2383 */
2384 ReadRegion.Top = Y;
2385 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002386 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002387 cb->Buffer, /* our buffer */
2388 cb->BufferSize, /* dimensions of our buffer */
2389 BufferCoord, /* offset in our buffer */
2390 &ReadRegion)) /* region to save */
2391 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002392 VIM_CLEAR(cb->Buffer);
2393 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002394 return FALSE;
2395 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002396 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 }
2398
2399 return TRUE;
2400}
2401
2402/*
2403 * RestoreConsoleBuffer()
2404 * Description:
2405 * Restores important information about the console buffer, including the
2406 * actual buffer contents, if desired. The information to restore is in
2407 * the same format used by SaveConsoleBuffer().
2408 * Returns:
2409 * TRUE on success
2410 */
2411 static BOOL
2412RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002413 ConsoleBuffer *cb,
2414 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002416 COORD BufferCoord;
2417 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002418 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419
2420 if (cb == NULL || !cb->IsValid)
2421 return FALSE;
2422
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002423 /*
2424 * Before restoring the buffer contents, clear the current buffer, and
2425 * restore the cursor position and window information. Doing this now
2426 * prevents old buffer contents from "flashing" onto the screen.
2427 */
2428 if (RestoreScreen)
2429 ClearConsoleBuffer(cb->Info.wAttributes);
2430
2431 FitConsoleWindow(cb->Info.dwSize, TRUE);
2432 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2433 return FALSE;
2434 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2435 return FALSE;
2436
2437 if (!RestoreScreen)
2438 {
2439 /*
2440 * No need to restore the screen buffer contents, so we're done.
2441 */
2442 return TRUE;
2443 }
2444
2445 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2446 return FALSE;
2447 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2448 return FALSE;
2449
2450 /*
2451 * Restore the screen buffer contents.
2452 */
2453 if (cb->Buffer != NULL)
2454 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002455 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002456 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002457 BufferCoord.X = cb->Regions[i].Left;
2458 BufferCoord.Y = cb->Regions[i].Top;
2459 WriteRegion = cb->Regions[i];
2460 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2461 cb->Buffer, /* our buffer */
2462 cb->BufferSize, /* dimensions of our buffer */
2463 BufferCoord, /* offset in our buffer */
2464 &WriteRegion)) /* region to restore */
2465 {
2466 return FALSE;
2467 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002468 }
2469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470
2471 return TRUE;
2472}
2473
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002474#define FEAT_RESTORE_ORIG_SCREEN
2475#ifdef FEAT_RESTORE_ORIG_SCREEN
2476static ConsoleBuffer g_cbOrig = { 0 };
2477#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478static ConsoleBuffer g_cbNonTermcap = { 0 };
2479static ConsoleBuffer g_cbTermcap = { 0 };
2480
2481#ifdef FEAT_TITLE
2482#ifdef __BORLANDC__
2483typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2484#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002485typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486#endif
2487char g_szOrigTitle[256] = { 0 };
2488HWND g_hWnd = NULL; /* also used in os_mswin.c */
2489static HICON g_hOrigIconSmall = NULL;
2490static HICON g_hOrigIcon = NULL;
2491static HICON g_hVimIcon = NULL;
2492static BOOL g_fCanChangeIcon = FALSE;
2493
2494/* ICON* are not defined in VC++ 4.0 */
2495#ifndef ICON_SMALL
2496#define ICON_SMALL 0
2497#endif
2498#ifndef ICON_BIG
2499#define ICON_BIG 1
2500#endif
2501/*
2502 * GetConsoleIcon()
2503 * Description:
2504 * Attempts to retrieve the small icon and/or the big icon currently in
2505 * use by a given window.
2506 * Returns:
2507 * TRUE on success
2508 */
2509 static BOOL
2510GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002511 HWND hWnd,
2512 HICON *phIconSmall,
2513 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514{
2515 if (hWnd == NULL)
2516 return FALSE;
2517
2518 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002519 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2520 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002522 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2523 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 return TRUE;
2525}
2526
2527/*
2528 * SetConsoleIcon()
2529 * Description:
2530 * Attempts to change the small icon and/or the big icon currently in
2531 * use by a given window.
2532 * Returns:
2533 * TRUE on success
2534 */
2535 static BOOL
2536SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002537 HWND hWnd,
2538 HICON hIconSmall,
2539 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 if (hWnd == NULL)
2542 return FALSE;
2543
2544 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002545 SendMessage(hWnd, WM_SETICON,
2546 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002548 SendMessage(hWnd, WM_SETICON,
2549 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 return TRUE;
2551}
2552
2553/*
2554 * SaveConsoleTitleAndIcon()
2555 * Description:
2556 * Saves the current console window title in g_szOrigTitle, for later
2557 * restoration. Also, attempts to obtain a handle to the console window,
2558 * and use it to save the small and big icons currently in use by the
2559 * console window. This is not always possible on some versions of Windows;
2560 * nor is it possible when running Vim remotely using Telnet (since the
2561 * console window the user sees is owned by a remote process).
2562 */
2563 static void
2564SaveConsoleTitleAndIcon(void)
2565{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566 /* Save the original title. */
2567 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2568 return;
2569
2570 /*
2571 * Obtain a handle to the console window using GetConsoleWindow() from
2572 * KERNEL32.DLL; we need to handle in order to change the window icon.
2573 * This function only exists on NT-based Windows, starting with Windows
2574 * 2000. On older operating systems, we can't change the window icon
2575 * anyway.
2576 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002577 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 if (g_hWnd == NULL)
2579 return;
2580
2581 /* Save the original console window icon. */
2582 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2583 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2584 return;
2585
2586 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002587 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002588 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 if (g_hVimIcon != NULL)
2590 g_fCanChangeIcon = TRUE;
2591}
2592#endif
2593
2594static int g_fWindInitCalled = FALSE;
2595static int g_fTermcapMode = FALSE;
2596static CONSOLE_CURSOR_INFO g_cci;
2597static DWORD g_cmodein = 0;
2598static DWORD g_cmodeout = 0;
2599
2600/*
2601 * non-GUI version of mch_init().
2602 */
2603 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002604mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002606#ifndef FEAT_RESTORE_ORIG_SCREEN
2607 CONSOLE_SCREEN_BUFFER_INFO csbi;
2608#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609#ifndef __MINGW32__
2610 extern int _fmode;
2611#endif
2612
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002613 /* Silently handle invalid parameters to CRT functions */
2614 SET_INVALID_PARAM_HANDLER;
2615
Bram Moolenaar071d4272004-06-13 20:20:40 +00002616 /* Let critical errors result in a failure, not in a dialog box. Required
2617 * for the timestamp test to work on removed floppies. */
2618 SetErrorMode(SEM_FAILCRITICALERRORS);
2619
2620 _fmode = O_BINARY; /* we do our own CR-LF translation */
2621 out_flush();
2622
2623 /* Obtain handles for the standard Console I/O devices */
2624 if (read_cmd_fd == 0)
2625 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2626 else
2627 create_conin();
2628 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2629
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002630#ifdef FEAT_RESTORE_ORIG_SCREEN
2631 /* Save the initial console buffer for later restoration */
2632 SaveConsoleBuffer(&g_cbOrig);
2633 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2634#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002636 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2637 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002639 if (cterm_normal_fg_color == 0)
2640 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2641 if (cterm_normal_bg_color == 0)
2642 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2643
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002644 // Fg and Bg color index nunmber at startup
2645 g_color_index_fg = g_attrDefault & 0xf;
2646 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2647
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 /* set termcap codes to current text attributes */
2649 update_tcap(g_attrCurrent);
2650
2651 GetConsoleCursorInfo(g_hConOut, &g_cci);
2652 GetConsoleMode(g_hConIn, &g_cmodein);
2653 GetConsoleMode(g_hConOut, &g_cmodeout);
2654
2655#ifdef FEAT_TITLE
2656 SaveConsoleTitleAndIcon();
2657 /*
2658 * Set both the small and big icons of the console window to Vim's icon.
2659 * Note that Vim presently only has one size of icon (32x32), but it
2660 * automatically gets scaled down to 16x16 when setting the small icon.
2661 */
2662 if (g_fCanChangeIcon)
2663 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2664#endif
2665
2666 ui_get_shellsize();
2667
2668#ifdef MCH_WRITE_DUMP
2669 fdDump = fopen("dump", "wt");
2670
2671 if (fdDump)
2672 {
2673 time_t t;
2674
2675 time(&t);
2676 fputs(ctime(&t), fdDump);
2677 fflush(fdDump);
2678 }
2679#endif
2680
2681 g_fWindInitCalled = TRUE;
2682
2683#ifdef FEAT_MOUSE
2684 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2685#endif
2686
2687#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002688 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002690
2691 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692}
2693
2694/*
2695 * non-GUI version of mch_exit().
2696 * Shut down and exit with status `r'
2697 * Careful: mch_exit() may be called before mch_init()!
2698 */
2699 void
2700mch_exit(int r)
2701{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002702 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002704 vtp_exit();
2705
Bram Moolenaar955f1982017-02-05 15:10:51 +01002706 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 if (g_fWindInitCalled)
2708 settmode(TMODE_COOK);
2709
2710 ml_close_all(TRUE); /* remove all memfiles */
2711
2712 if (g_fWindInitCalled)
2713 {
2714#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002715 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 /*
2717 * Restore both the small and big icons of the console window to
2718 * what they were at startup. Don't do this when the window is
2719 * closed, Vim would hang here.
2720 */
2721 if (g_fCanChangeIcon && !g_fForceExit)
2722 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2723#endif
2724
2725#ifdef MCH_WRITE_DUMP
2726 if (fdDump)
2727 {
2728 time_t t;
2729
2730 time(&t);
2731 fputs(ctime(&t), fdDump);
2732 fclose(fdDump);
2733 }
2734 fdDump = NULL;
2735#endif
2736 }
2737
2738 SetConsoleCursorInfo(g_hConOut, &g_cci);
2739 SetConsoleMode(g_hConIn, g_cmodein);
2740 SetConsoleMode(g_hConOut, g_cmodeout);
2741
2742#ifdef DYNAMIC_GETTEXT
2743 dyn_libintl_end();
2744#endif
2745
2746 exit(r);
2747}
2748#endif /* !FEAT_GUI_W32 */
2749
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750/*
2751 * Do we have an interactive window?
2752 */
2753 int
2754mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002755 int argc UNUSED,
2756 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757{
2758 get_exe_name();
2759
2760#ifdef FEAT_GUI_W32
2761 return OK; /* GUI always has a tty */
2762#else
2763 if (isatty(1))
2764 return OK;
2765 return FAIL;
2766#endif
2767}
2768
2769
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002770#ifdef FEAT_MBYTE
2771/*
2772 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2773 * if it already exists. When "len" is > 0, also expand short to long
2774 * filenames.
2775 * Return FAIL if wide functions are not available, OK otherwise.
2776 * NOTE: much of this is identical to fname_case(), keep in sync!
2777 */
2778 static int
2779fname_casew(
2780 WCHAR *name,
2781 int len)
2782{
2783 WCHAR szTrueName[_MAX_PATH + 2];
2784 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2785 WCHAR *ptrue, *ptruePrev;
2786 WCHAR *porig, *porigPrev;
2787 int flen;
2788 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002789 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002790 int c;
2791 int slen;
2792
2793 flen = (int)wcslen(name);
2794 if (flen > _MAX_PATH)
2795 return OK;
2796
2797 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2798
2799 /* Build the new name in szTrueName[] one component at a time. */
2800 porig = name;
2801 ptrue = szTrueName;
2802
2803 if (iswalpha(porig[0]) && porig[1] == L':')
2804 {
2805 /* copy leading drive letter */
2806 *ptrue++ = *porig++;
2807 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002808 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002809 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002810
2811 while (*porig != NUL)
2812 {
2813 /* copy \ characters */
2814 while (*porig == psepc)
2815 *ptrue++ = *porig++;
2816
2817 ptruePrev = ptrue;
2818 porigPrev = porig;
2819 while (*porig != NUL && *porig != psepc)
2820 {
2821 *ptrue++ = *porig++;
2822 }
2823 *ptrue = NUL;
2824
2825 /* To avoid a slow failure append "\*" when searching a directory,
2826 * server or network share. */
2827 wcscpy(szTrueNameTemp, szTrueName);
2828 slen = (int)wcslen(szTrueNameTemp);
2829 if (*porig == psepc && slen + 2 < _MAX_PATH)
2830 wcscpy(szTrueNameTemp + slen, L"\\*");
2831
2832 /* Skip "", "." and "..". */
2833 if (ptrue > ptruePrev
2834 && (ptruePrev[0] != L'.'
2835 || (ptruePrev[1] != NUL
2836 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2837 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2838 != INVALID_HANDLE_VALUE)
2839 {
2840 c = *porig;
2841 *porig = NUL;
2842
2843 /* Only use the match when it's the same name (ignoring case) or
2844 * expansion is allowed and there is a match with the short name
2845 * and there is enough room. */
2846 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2847 || (len > 0
2848 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2849 && (int)(ptruePrev - szTrueName)
2850 + (int)wcslen(fb.cFileName) < len)))
2851 {
2852 wcscpy(ptruePrev, fb.cFileName);
2853
2854 /* Look for exact match and prefer it if found. Must be a
2855 * long name, otherwise there would be only one match. */
2856 while (FindNextFileW(hFind, &fb))
2857 {
2858 if (*fb.cAlternateFileName != NUL
2859 && (wcscoll(porigPrev, fb.cFileName) == 0
2860 || (len > 0
2861 && (_wcsicoll(porigPrev,
2862 fb.cAlternateFileName) == 0
2863 && (int)(ptruePrev - szTrueName)
2864 + (int)wcslen(fb.cFileName) < len))))
2865 {
2866 wcscpy(ptruePrev, fb.cFileName);
2867 break;
2868 }
2869 }
2870 }
2871 FindClose(hFind);
2872 *porig = c;
2873 ptrue = ptruePrev + wcslen(ptruePrev);
2874 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002875 }
2876
2877 wcscpy(name, szTrueName);
2878 return OK;
2879}
2880#endif
2881
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882/*
2883 * fname_case(): Set the case of the file name, if it already exists.
2884 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002885 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886 */
2887 void
2888fname_case(
2889 char_u *name,
2890 int len)
2891{
2892 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002893 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894 char *ptrue, *ptruePrev;
2895 char *porig, *porigPrev;
2896 int flen;
2897 WIN32_FIND_DATA fb;
2898 HANDLE hFind;
2899 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002900 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002902 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 return;
2905
2906 slash_adjust(name);
2907
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002908#ifdef FEAT_MBYTE
2909 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2910 {
2911 WCHAR *p = enc_to_utf16(name, NULL);
2912
2913 if (p != NULL)
2914 {
2915 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002916 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002917
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002918 wcsncpy(buf, p, _MAX_PATH);
2919 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002920 vim_free(p);
2921
2922 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2923 {
2924 q = utf16_to_enc(buf, NULL);
2925 if (q != NULL)
2926 {
2927 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2928 vim_free(q);
2929 return;
2930 }
2931 }
2932 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002933 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002934 }
2935#endif
2936
2937 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2938 * So we should check this after calling wide function. */
2939 if (flen > _MAX_PATH)
2940 return;
2941
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002943 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 ptrue = szTrueName;
2945
2946 if (isalpha(porig[0]) && porig[1] == ':')
2947 {
2948 /* copy leading drive letter */
2949 *ptrue++ = *porig++;
2950 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002952 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953
2954 while (*porig != NUL)
2955 {
2956 /* copy \ characters */
2957 while (*porig == psepc)
2958 *ptrue++ = *porig++;
2959
2960 ptruePrev = ptrue;
2961 porigPrev = porig;
2962 while (*porig != NUL && *porig != psepc)
2963 {
2964#ifdef FEAT_MBYTE
2965 int l;
2966
2967 if (enc_dbcs)
2968 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002969 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 while (--l >= 0)
2971 *ptrue++ = *porig++;
2972 }
2973 else
2974#endif
2975 *ptrue++ = *porig++;
2976 }
2977 *ptrue = NUL;
2978
Bram Moolenaar464c9252010-10-13 20:37:41 +02002979 /* To avoid a slow failure append "\*" when searching a directory,
2980 * server or network share. */
2981 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002982 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002983 if (*porig == psepc && slen + 2 < _MAX_PATH)
2984 STRCPY(szTrueNameTemp + slen, "\\*");
2985
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 /* Skip "", "." and "..". */
2987 if (ptrue > ptruePrev
2988 && (ptruePrev[0] != '.'
2989 || (ptruePrev[1] != NUL
2990 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002991 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 != INVALID_HANDLE_VALUE)
2993 {
2994 c = *porig;
2995 *porig = NUL;
2996
2997 /* Only use the match when it's the same name (ignoring case) or
2998 * expansion is allowed and there is a match with the short name
2999 * and there is enough room. */
3000 if (_stricoll(porigPrev, fb.cFileName) == 0
3001 || (len > 0
3002 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
3003 && (int)(ptruePrev - szTrueName)
3004 + (int)strlen(fb.cFileName) < len)))
3005 {
3006 STRCPY(ptruePrev, fb.cFileName);
3007
3008 /* Look for exact match and prefer it if found. Must be a
3009 * long name, otherwise there would be only one match. */
3010 while (FindNextFile(hFind, &fb))
3011 {
3012 if (*fb.cAlternateFileName != NUL
3013 && (strcoll(porigPrev, fb.cFileName) == 0
3014 || (len > 0
3015 && (_stricoll(porigPrev,
3016 fb.cAlternateFileName) == 0
3017 && (int)(ptruePrev - szTrueName)
3018 + (int)strlen(fb.cFileName) < len))))
3019 {
3020 STRCPY(ptruePrev, fb.cFileName);
3021 break;
3022 }
3023 }
3024 }
3025 FindClose(hFind);
3026 *porig = c;
3027 ptrue = ptruePrev + strlen(ptruePrev);
3028 }
3029 }
3030
3031 STRCPY(name, szTrueName);
3032}
3033
3034
3035/*
3036 * Insert user name in s[len].
3037 */
3038 int
3039mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003040 char_u *s,
3041 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003043 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 DWORD cch = sizeof szUserName;
3045
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003046#ifdef FEAT_MBYTE
3047 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3048 {
3049 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3050 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3051
3052 if (GetUserNameW(wszUserName, &wcch))
3053 {
3054 char_u *p = utf16_to_enc(wszUserName, NULL);
3055
3056 if (p != NULL)
3057 {
3058 vim_strncpy(s, p, len - 1);
3059 vim_free(p);
3060 return OK;
3061 }
3062 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003063 }
3064#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 if (GetUserName(szUserName, &cch))
3066 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003067 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 return OK;
3069 }
3070 s[0] = NUL;
3071 return FAIL;
3072}
3073
3074
3075/*
3076 * Insert host name in s[len].
3077 */
3078 void
3079mch_get_host_name(
3080 char_u *s,
3081 int len)
3082{
3083 DWORD cch = len;
3084
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003085#ifdef FEAT_MBYTE
3086 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3087 {
3088 WCHAR wszHostName[256 + 1];
3089 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3090
3091 if (GetComputerNameW(wszHostName, &wcch))
3092 {
3093 char_u *p = utf16_to_enc(wszHostName, NULL);
3094
3095 if (p != NULL)
3096 {
3097 vim_strncpy(s, p, len - 1);
3098 vim_free(p);
3099 return;
3100 }
3101 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003102 }
3103#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003104 if (!GetComputerName((LPSTR)s, &cch))
3105 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106}
3107
3108
3109/*
3110 * return process ID
3111 */
3112 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003113mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114{
3115 return (long)GetCurrentProcessId();
3116}
3117
3118
3119/*
3120 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3121 * Return OK for success, FAIL for failure.
3122 */
3123 int
3124mch_dirname(
3125 char_u *buf,
3126 int len)
3127{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003128 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003129 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003130
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 /*
3132 * Originally this was:
3133 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3134 * But the Win32s known bug list says that getcwd() doesn't work
3135 * so use the Win32 system call instead. <Negri>
3136 */
3137#ifdef FEAT_MBYTE
3138 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3139 {
3140 WCHAR wbuf[_MAX_PATH + 1];
3141
3142 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3143 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003145 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003146
3147 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003148 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003149 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003150 if (STRLEN(p) >= (size_t)len)
3151 {
3152 // long path name is too long, fall back to short one
3153 vim_free(p);
3154 p = NULL;
3155 }
3156 }
3157 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003158 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159
3160 if (p != NULL)
3161 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003162 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 vim_free(p);
3164 return OK;
3165 }
3166 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003167 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 }
3169#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003170 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3171 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003172 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3173 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3174 // Failed to get long path name or it's too long: fall back to the
3175 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003176 return OK;
3177
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003178 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003179 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180}
3181
3182/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003183 * Get file permissions for "name".
3184 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 */
3186 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003187mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003189 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003190 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003192 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003193 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194}
3195
3196
3197/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003198 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003199 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003200 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 */
3202 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003203mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003205 long n = -1;
3206
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207#ifdef FEAT_MBYTE
3208 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3209 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003210 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211
3212 if (p != NULL)
3213 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003216 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 }
3219 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003220 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003222 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003223 if (n == -1)
3224 return FAIL;
3225
3226 win32_set_archive(name);
3227
3228 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229}
3230
3231/*
3232 * Set hidden flag for "name".
3233 */
3234 void
3235mch_hide(char_u *name)
3236{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003237 int attrs = win32_getattrs(name);
3238 if (attrs == -1)
3239 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 attrs |= FILE_ATTRIBUTE_HIDDEN;
3242 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243}
3244
3245/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003246 * Return TRUE if file "name" exists and is hidden.
3247 */
3248 int
3249mch_ishidden(char_u *name)
3250{
3251 int f = win32_getattrs(name);
3252
3253 if (f == -1)
3254 return FALSE; /* file does not exist at all */
3255
3256 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3257}
3258
3259/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260 * return TRUE if "name" is a directory
3261 * return FALSE if "name" is not a directory or upon error
3262 */
3263 int
3264mch_isdir(char_u *name)
3265{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003266 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267
3268 if (f == -1)
3269 return FALSE; /* file does not exist at all */
3270
3271 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3272}
3273
3274/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003275 * return TRUE if "name" is a directory, NOT a symlink to a directory
3276 * return FALSE if "name" is not a directory
3277 * return FALSE for error
3278 */
3279 int
3280mch_isrealdir(char_u *name)
3281{
3282 return mch_isdir(name) && !mch_is_symbolic_link(name);
3283}
3284
3285/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003286 * Create directory "name".
3287 * Return 0 on success, -1 on error.
3288 */
3289 int
3290mch_mkdir(char_u *name)
3291{
3292#ifdef FEAT_MBYTE
3293 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3294 {
3295 WCHAR *p;
3296 int retval;
3297
3298 p = enc_to_utf16(name, NULL);
3299 if (p == NULL)
3300 return -1;
3301 retval = _wmkdir(p);
3302 vim_free(p);
3303 return retval;
3304 }
3305#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003306 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003307}
3308
3309/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003310 * Delete directory "name".
3311 * Return 0 on success, -1 on error.
3312 */
3313 int
3314mch_rmdir(char_u *name)
3315{
3316#ifdef FEAT_MBYTE
3317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3318 {
3319 WCHAR *p;
3320 int retval;
3321
3322 p = enc_to_utf16(name, NULL);
3323 if (p == NULL)
3324 return -1;
3325 retval = _wrmdir(p);
3326 vim_free(p);
3327 return retval;
3328 }
3329#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003330 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003331}
3332
3333/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003334 * Return TRUE if file "fname" has more than one link.
3335 */
3336 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003337mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003338{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003339 BY_HANDLE_FILE_INFORMATION info;
3340
3341 return win32_fileinfo(fname, &info) == FILEINFO_OK
3342 && info.nNumberOfLinks > 1;
3343}
3344
3345/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003346 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 */
3348 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003349mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003350{
3351 HANDLE hFind;
3352 int res = FALSE;
3353 WIN32_FIND_DATAA findDataA;
3354 DWORD fileFlags = 0, reparseTag = 0;
3355#ifdef FEAT_MBYTE
3356 WCHAR *wn = NULL;
3357 WIN32_FIND_DATAW findDataW;
3358
3359 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003360 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361 if (wn != NULL)
3362 {
3363 hFind = FindFirstFileW(wn, &findDataW);
3364 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003365 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003366 {
3367 fileFlags = findDataW.dwFileAttributes;
3368 reparseTag = findDataW.dwReserved0;
3369 }
3370 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003371 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003372#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003373 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003374 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003375 if (hFind != INVALID_HANDLE_VALUE)
3376 {
3377 fileFlags = findDataA.dwFileAttributes;
3378 reparseTag = findDataA.dwReserved0;
3379 }
3380 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003381
3382 if (hFind != INVALID_HANDLE_VALUE)
3383 FindClose(hFind);
3384
3385 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003386 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3387 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003388 res = TRUE;
3389
3390 return res;
3391}
3392
3393/*
3394 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3395 * link.
3396 */
3397 int
3398mch_is_linked(char_u *fname)
3399{
3400 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3401 return TRUE;
3402 return FALSE;
3403}
3404
3405/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 * Get the by-handle-file-information for "fname".
3407 * Returns FILEINFO_OK when OK.
3408 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3409 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3410 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3411 */
3412 int
3413win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3414{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003415 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417#ifdef FEAT_MBYTE
3418 WCHAR *wn = NULL;
3419
3420 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003421 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003422 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003423 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003424 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003425 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003426 if (wn != NULL)
3427 {
3428 hFile = CreateFileW(wn, /* file name */
3429 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003430 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003431 NULL, /* security descriptor */
3432 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003433 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003434 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003435 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003436 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003437 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003438#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003439 hFile = CreateFile((LPCSTR)fname, /* file name */
3440 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003441 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003442 NULL, /* security descriptor */
3443 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003444 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003445 NULL); /* handle to template file */
3446
3447 if (hFile != INVALID_HANDLE_VALUE)
3448 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003449 if (GetFileInformationByHandle(hFile, info) != 0)
3450 res = FILEINFO_OK;
3451 else
3452 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003453 CloseHandle(hFile);
3454 }
3455
Bram Moolenaar03f48552006-02-28 23:52:23 +00003456 return res;
3457}
3458
3459/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460 * get file attributes for `name'
3461 * -1 : error
3462 * else FILE_ATTRIBUTE_* defined in winnt.h
3463 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003464 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003465win32_getattrs(char_u *name)
3466{
3467 int attr;
3468#ifdef FEAT_MBYTE
3469 WCHAR *p = NULL;
3470
3471 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3472 p = enc_to_utf16(name, NULL);
3473
3474 if (p != NULL)
3475 {
3476 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003477 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003479 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003480#endif
3481 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003482
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003483 return attr;
3484}
3485
3486/*
3487 * set file attributes for `name' to `attrs'
3488 *
3489 * return -1 for failure, 0 otherwise
3490 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003491 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003492win32_setattrs(char_u *name, int attrs)
3493{
3494 int res;
3495#ifdef FEAT_MBYTE
3496 WCHAR *p = NULL;
3497
3498 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3499 p = enc_to_utf16(name, NULL);
3500
3501 if (p != NULL)
3502 {
3503 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003504 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003505 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003506 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003507#endif
3508 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003509
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003510 return res ? 0 : -1;
3511}
3512
3513/*
3514 * Set archive flag for "name".
3515 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003516 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003517win32_set_archive(char_u *name)
3518{
3519 int attrs = win32_getattrs(name);
3520 if (attrs == -1)
3521 return -1;
3522
3523 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3524 return win32_setattrs(name, attrs);
3525}
3526
3527/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 * Return TRUE if file or directory "name" is writable (not readonly).
3529 * Strange semantics of Win32: a readonly directory is writable, but you can't
3530 * delete a file. Let's say this means it is writable.
3531 */
3532 int
3533mch_writable(char_u *name)
3534{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003535 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003537 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3538 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003539}
3540
Bram Moolenaar071d4272004-06-13 20:20:40 +00003541/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003542 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003543 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003544 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3545 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546 */
3547 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003548mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003550 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003551 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003552 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003553
3554 if (len >= _MAX_PATH) /* safety check */
3555 return FALSE;
3556
Bram Moolenaar82956662018-10-06 15:18:45 +02003557 /* Ty using the name directly when a Unix-shell like 'shell'. */
3558 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003559 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003560 return TRUE;
3561
3562 /*
3563 * Loop over all extensions in $PATHEXT.
3564 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003565 p = mch_getenv("PATHEXT");
3566 if (p == NULL)
3567 p = (char_u *)".com;.exe;.bat;.cmd";
3568 saved = vim_strsave(p);
3569 if (saved == NULL)
3570 return FALSE;
3571 p = saved;
3572 while (*p)
3573 {
3574 char_u *tmp = vim_strchr(p, ';');
3575
3576 if (tmp != NULL)
3577 *tmp = NUL;
3578 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3579 && executable_exists((char *)name, path, use_path))
3580 {
3581 vim_free(saved);
3582 return TRUE;
3583 }
3584 if (tmp == NULL)
3585 break;
3586 p = tmp + 1;
3587 }
3588 vim_free(saved);
3589
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003590 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003591 p = mch_getenv("PATHEXT");
3592 if (p == NULL)
3593 p = (char_u *)".com;.exe;.bat;.cmd";
3594 while (*p)
3595 {
3596 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3597 {
3598 /* A single "." means no extension is added. */
3599 buf[len] = NUL;
3600 ++p;
3601 if (*p)
3602 ++p;
3603 }
3604 else
3605 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003606 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003607 return TRUE;
3608 }
3609 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611
3612/*
3613 * Check what "name" is:
3614 * NODE_NORMAL: file or directory (or doesn't exist)
3615 * NODE_WRITABLE: writable device, socket, fifo, etc.
3616 * NODE_OTHER: non-writable things
3617 */
3618 int
3619mch_nodetype(char_u *name)
3620{
3621 HANDLE hFile;
3622 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003623#ifdef FEAT_MBYTE
3624 WCHAR *wn = NULL;
3625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626
Bram Moolenaar043545e2006-10-10 16:44:07 +00003627 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3628 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3629 * here. */
3630 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3631 return NODE_WRITABLE;
3632
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003633#ifdef FEAT_MBYTE
3634 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003635 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003636
3637 if (wn != NULL)
3638 {
3639 hFile = CreateFileW(wn, /* file name */
3640 GENERIC_WRITE, /* access mode */
3641 0, /* share mode */
3642 NULL, /* security descriptor */
3643 OPEN_EXISTING, /* creation disposition */
3644 0, /* file attributes */
3645 NULL); /* handle to template file */
3646 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003647 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003648 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003649#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003650 hFile = CreateFile((LPCSTR)name, /* file name */
3651 GENERIC_WRITE, /* access mode */
3652 0, /* share mode */
3653 NULL, /* security descriptor */
3654 OPEN_EXISTING, /* creation disposition */
3655 0, /* file attributes */
3656 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657
3658 if (hFile == INVALID_HANDLE_VALUE)
3659 return NODE_NORMAL;
3660
3661 type = GetFileType(hFile);
3662 CloseHandle(hFile);
3663 if (type == FILE_TYPE_CHAR)
3664 return NODE_WRITABLE;
3665 if (type == FILE_TYPE_DISK)
3666 return NODE_NORMAL;
3667 return NODE_OTHER;
3668}
3669
3670#ifdef HAVE_ACL
3671struct my_acl
3672{
3673 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3674 PSID pSidOwner;
3675 PSID pSidGroup;
3676 PACL pDacl;
3677 PACL pSacl;
3678};
3679#endif
3680
3681/*
3682 * Return a pointer to the ACL of file "fname" in allocated memory.
3683 * Return NULL if the ACL is not available for whatever reason.
3684 */
3685 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003686mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687{
3688#ifndef HAVE_ACL
3689 return (vim_acl_T)NULL;
3690#else
3691 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003692 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003694 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3695 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003697# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003698 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003699
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003700 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3701 wn = enc_to_utf16(fname, NULL);
3702 if (wn != NULL)
3703 {
3704 /* Try to retrieve the entire security descriptor. */
3705 err = GetNamedSecurityInfoW(
3706 wn, // 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)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003720 /* Retrieve only DACL. */
3721 (void)GetNamedSecurityInfoW(
3722 wn,
3723 SE_FILE_OBJECT,
3724 DACL_SECURITY_INFORMATION,
3725 NULL,
3726 NULL,
3727 &p->pDacl,
3728 NULL,
3729 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003730 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003731 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003732 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003733 mch_free_acl((vim_acl_T)p);
3734 p = NULL;
3735 }
3736 vim_free(wn);
3737 }
3738 else
3739# endif
3740 {
3741 /* Try to retrieve the entire security descriptor. */
3742 err = GetNamedSecurityInfo(
3743 (LPSTR)fname, // Abstract filename
3744 SE_FILE_OBJECT, // File Object
3745 OWNER_SECURITY_INFORMATION |
3746 GROUP_SECURITY_INFORMATION |
3747 DACL_SECURITY_INFORMATION |
3748 SACL_SECURITY_INFORMATION,
3749 &p->pSidOwner, // Ownership information.
3750 &p->pSidGroup, // Group membership.
3751 &p->pDacl, // Discretionary information.
3752 &p->pSacl, // For auditing purposes.
3753 &p->pSecurityDescriptor);
3754 if (err == ERROR_ACCESS_DENIED ||
3755 err == ERROR_PRIVILEGE_NOT_HELD)
3756 {
3757 /* Retrieve only DACL. */
3758 (void)GetNamedSecurityInfo(
3759 (LPSTR)fname,
3760 SE_FILE_OBJECT,
3761 DACL_SECURITY_INFORMATION,
3762 NULL,
3763 NULL,
3764 &p->pDacl,
3765 NULL,
3766 &p->pSecurityDescriptor);
3767 }
3768 if (p->pSecurityDescriptor == NULL)
3769 {
3770 mch_free_acl((vim_acl_T)p);
3771 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 }
3773 }
3774 }
3775
3776 return (vim_acl_T)p;
3777#endif
3778}
3779
Bram Moolenaar27515922013-06-29 15:36:26 +02003780#ifdef HAVE_ACL
3781/*
3782 * Check if "acl" contains inherited ACE.
3783 */
3784 static BOOL
3785is_acl_inherited(PACL acl)
3786{
3787 DWORD i;
3788 ACL_SIZE_INFORMATION acl_info;
3789 PACCESS_ALLOWED_ACE ace;
3790
3791 acl_info.AceCount = 0;
3792 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3793 for (i = 0; i < acl_info.AceCount; i++)
3794 {
3795 GetAce(acl, i, (LPVOID *)&ace);
3796 if (ace->Header.AceFlags & INHERITED_ACE)
3797 return TRUE;
3798 }
3799 return FALSE;
3800}
3801#endif
3802
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803/*
3804 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3805 * Errors are ignored.
3806 * This must only be called with "acl" equal to what mch_get_acl() returned.
3807 */
3808 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003809mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810{
3811#ifdef HAVE_ACL
3812 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003813 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003815 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003816 {
3817# ifdef FEAT_MBYTE
3818 WCHAR *wn = NULL;
3819# endif
3820
3821 /* Set security flags */
3822 if (p->pSidOwner)
3823 sec_info |= OWNER_SECURITY_INFORMATION;
3824 if (p->pSidGroup)
3825 sec_info |= GROUP_SECURITY_INFORMATION;
3826 if (p->pDacl)
3827 {
3828 sec_info |= DACL_SECURITY_INFORMATION;
3829 /* Do not inherit its parent's DACL.
3830 * If the DACL is inherited, Cygwin permissions would be changed.
3831 */
3832 if (!is_acl_inherited(p->pDacl))
3833 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3834 }
3835 if (p->pSacl)
3836 sec_info |= SACL_SECURITY_INFORMATION;
3837
3838# ifdef FEAT_MBYTE
3839 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3840 wn = enc_to_utf16(fname, NULL);
3841 if (wn != NULL)
3842 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003843 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003844 wn, // Abstract filename
3845 SE_FILE_OBJECT, // File Object
3846 sec_info,
3847 p->pSidOwner, // Ownership information.
3848 p->pSidGroup, // Group membership.
3849 p->pDacl, // Discretionary information.
3850 p->pSacl // For auditing purposes.
3851 );
3852 vim_free(wn);
3853 }
3854 else
3855# endif
3856 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003857 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003858 (LPSTR)fname, // Abstract filename
3859 SE_FILE_OBJECT, // File Object
3860 sec_info,
3861 p->pSidOwner, // Ownership information.
3862 p->pSidGroup, // Group membership.
3863 p->pDacl, // Discretionary information.
3864 p->pSacl // For auditing purposes.
3865 );
3866 }
3867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868#endif
3869}
3870
3871 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003872mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873{
3874#ifdef HAVE_ACL
3875 struct my_acl *p = (struct my_acl *)acl;
3876
3877 if (p != NULL)
3878 {
3879 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3880 vim_free(p);
3881 }
3882#endif
3883}
3884
3885#ifndef FEAT_GUI_W32
3886
3887/*
3888 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3889 */
3890 static BOOL WINAPI
3891handler_routine(
3892 DWORD dwCtrlType)
3893{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003894 INPUT_RECORD ir;
3895 DWORD out;
3896
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897 switch (dwCtrlType)
3898 {
3899 case CTRL_C_EVENT:
3900 if (ctrl_c_interrupts)
3901 g_fCtrlCPressed = TRUE;
3902 return TRUE;
3903
3904 case CTRL_BREAK_EVENT:
3905 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003906 ctrl_break_was_pressed = TRUE;
3907 /* ReadConsoleInput is blocking, send a key event to continue. */
3908 ir.EventType = KEY_EVENT;
3909 ir.Event.KeyEvent.bKeyDown = TRUE;
3910 ir.Event.KeyEvent.wRepeatCount = 1;
3911 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3912 ir.Event.KeyEvent.wVirtualScanCode = 0;
3913 ir.Event.KeyEvent.dwControlKeyState = 0;
3914 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3915 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 return TRUE;
3917
3918 /* fatal events: shut down gracefully */
3919 case CTRL_CLOSE_EVENT:
3920 case CTRL_LOGOFF_EVENT:
3921 case CTRL_SHUTDOWN_EVENT:
3922 windgoto((int)Rows - 1, 0);
3923 g_fForceExit = TRUE;
3924
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003925 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 (dwCtrlType == CTRL_CLOSE_EVENT
3927 ? _("close")
3928 : dwCtrlType == CTRL_LOGOFF_EVENT
3929 ? _("logoff")
3930 : _("shutdown")));
3931#ifdef DEBUG
3932 OutputDebugString(IObuff);
3933#endif
3934
3935 preserve_exit(); /* output IObuff, preserve files and exit */
3936
3937 return TRUE; /* not reached */
3938
3939 default:
3940 return FALSE;
3941 }
3942}
3943
3944
3945/*
3946 * set the tty in (raw) ? "raw" : "cooked" mode
3947 */
3948 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003949mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950{
3951 DWORD cmodein;
3952 DWORD cmodeout;
3953 BOOL bEnableHandler;
3954
3955 GetConsoleMode(g_hConIn, &cmodein);
3956 GetConsoleMode(g_hConOut, &cmodeout);
3957 if (tmode == TMODE_RAW)
3958 {
3959 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3960 ENABLE_ECHO_INPUT);
3961#ifdef FEAT_MOUSE
3962 if (g_fMouseActive)
3963 cmodein |= ENABLE_MOUSE_INPUT;
3964#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003965 cmodeout &= ~(
3966#ifdef FEAT_TERMGUICOLORS
3967 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3968 * VTP. */
3969 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3970#else
3971 ENABLE_PROCESSED_OUTPUT |
3972#endif
3973 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 bEnableHandler = TRUE;
3975 }
3976 else /* cooked */
3977 {
3978 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3979 ENABLE_ECHO_INPUT);
3980 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3981 bEnableHandler = FALSE;
3982 }
3983 SetConsoleMode(g_hConIn, cmodein);
3984 SetConsoleMode(g_hConOut, cmodeout);
3985 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3986
3987#ifdef MCH_WRITE_DUMP
3988 if (fdDump)
3989 {
3990 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3991 tmode == TMODE_RAW ? "raw" :
3992 tmode == TMODE_COOK ? "cooked" : "normal",
3993 cmodein, cmodeout);
3994 fflush(fdDump);
3995 }
3996#endif
3997}
3998
3999
4000/*
4001 * Get the size of the current window in `Rows' and `Columns'
4002 * Return OK when size could be determined, FAIL otherwise.
4003 */
4004 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004005mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006{
4007 CONSOLE_SCREEN_BUFFER_INFO csbi;
4008
4009 if (!g_fTermcapMode && g_cbTermcap.IsValid)
4010 {
4011 /*
4012 * For some reason, we are trying to get the screen dimensions
4013 * even though we are not in termcap mode. The 'Rows' and 'Columns'
4014 * variables are really intended to mean the size of Vim screen
4015 * while in termcap mode.
4016 */
4017 Rows = g_cbTermcap.Info.dwSize.Y;
4018 Columns = g_cbTermcap.Info.dwSize.X;
4019 }
4020 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4021 {
4022 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4023 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4024 }
4025 else
4026 {
4027 Rows = 25;
4028 Columns = 80;
4029 }
4030 return OK;
4031}
4032
4033/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004034 * Resize console buffer to 'COORD'
4035 */
4036 static void
4037ResizeConBuf(
4038 HANDLE hConsole,
4039 COORD coordScreen)
4040{
4041 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4042 {
4043#ifdef MCH_WRITE_DUMP
4044 if (fdDump)
4045 {
4046 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4047 GetLastError());
4048 fflush(fdDump);
4049 }
4050#endif
4051 }
4052}
4053
4054/*
4055 * Resize console window size to 'srWindowRect'
4056 */
4057 static void
4058ResizeWindow(
4059 HANDLE hConsole,
4060 SMALL_RECT srWindowRect)
4061{
4062 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4063 {
4064#ifdef MCH_WRITE_DUMP
4065 if (fdDump)
4066 {
4067 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4068 GetLastError());
4069 fflush(fdDump);
4070 }
4071#endif
4072 }
4073}
4074
4075/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004076 * Set a console window to `xSize' * `ySize'
4077 */
4078 static void
4079ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004080 HANDLE hConsole,
4081 int xSize,
4082 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083{
4084 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4085 SMALL_RECT srWindowRect; /* hold the new console size */
4086 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004087 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088
4089#ifdef MCH_WRITE_DUMP
4090 if (fdDump)
4091 {
4092 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4093 fflush(fdDump);
4094 }
4095#endif
4096
4097 /* get the largest size we can size the console window to */
4098 coordScreen = GetLargestConsoleWindowSize(hConsole);
4099
4100 /* define the new console window size and scroll position */
4101 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4102 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4103 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4104
4105 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4106 {
4107 int sx, sy;
4108
4109 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4110 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4111 if (sy < ySize || sx < xSize)
4112 {
4113 /*
4114 * Increasing number of lines/columns, do buffer first.
4115 * Use the maximal size in x and y direction.
4116 */
4117 if (sy < ySize)
4118 coordScreen.Y = ySize;
4119 else
4120 coordScreen.Y = sy;
4121 if (sx < xSize)
4122 coordScreen.X = xSize;
4123 else
4124 coordScreen.X = sx;
4125 SetConsoleScreenBufferSize(hConsole, coordScreen);
4126 }
4127 }
4128
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004129 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 coordScreen.X = xSize;
4131 coordScreen.Y = ySize;
4132
Bram Moolenaar2551c032018-08-23 22:38:31 +02004133 // In the new console call API, only the first time in reverse order
4134 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004136 ResizeWindow(hConsole, srWindowRect);
4137 ResizeConBuf(hConsole, coordScreen);
4138 }
4139 else
4140 {
4141 ResizeConBuf(hConsole, coordScreen);
4142 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004143 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 }
4145}
4146
4147
4148/*
4149 * Set the console window to `Rows' * `Columns'
4150 */
4151 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004152mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153{
4154 COORD coordScreen;
4155
4156 /* Don't change window size while still starting up */
4157 if (suppress_winsize != 0)
4158 {
4159 suppress_winsize = 2;
4160 return;
4161 }
4162
4163 if (term_console)
4164 {
4165 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4166
4167 /* Clamp Rows and Columns to reasonable values */
4168 if (Rows > coordScreen.Y)
4169 Rows = coordScreen.Y;
4170 if (Columns > coordScreen.X)
4171 Columns = coordScreen.X;
4172
4173 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4174 }
4175}
4176
4177/*
4178 * Rows and/or Columns has changed.
4179 */
4180 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004181mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182{
4183 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4184}
4185
4186
4187/*
4188 * Called when started up, to set the winsize that was delayed.
4189 */
4190 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004191mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192{
4193 if (suppress_winsize == 2)
4194 {
4195 suppress_winsize = 0;
4196 mch_set_shellsize();
4197 shell_resized();
4198 }
4199 suppress_winsize = 0;
4200}
4201#endif /* FEAT_GUI_W32 */
4202
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004203 static BOOL
4204vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004205 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004206 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004207 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004208 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004209 PROCESS_INFORMATION *pi,
4210 LPVOID *env,
4211 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004212{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004213#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004214 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4215 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004216 BOOL ret;
4217 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004218
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004219 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4220 if (wcmd == NULL)
4221 goto fallback;
4222 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004223 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004224 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4225 if (wcwd == NULL)
4226 {
4227 vim_free(wcmd);
4228 goto fallback;
4229 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004230 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004231
4232 ret = CreateProcessW(
4233 NULL, /* Executable name */
4234 wcmd, /* Command to execute */
4235 NULL, /* Process security attributes */
4236 NULL, /* Thread security attributes */
4237 inherit_handles, /* Inherit handles */
4238 flags, /* Creation flags */
4239 env, /* Environment */
4240 wcwd, /* Current directory */
4241 (LPSTARTUPINFOW)si, /* Startup information */
4242 pi); /* Process information */
4243 vim_free(wcmd);
4244 if (wcwd != NULL)
4245 vim_free(wcwd);
4246 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004247 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004248fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004249#endif
4250 return CreateProcess(
4251 NULL, /* Executable name */
4252 cmd, /* Command to execute */
4253 NULL, /* Process security attributes */
4254 NULL, /* Thread security attributes */
4255 inherit_handles, /* Inherit handles */
4256 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004257 env, /* Environment */
4258 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004259 si, /* Startup information */
4260 pi); /* Process information */
4261}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004262
4263
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004264 static HINSTANCE
4265vim_shell_execute(
4266 char *cmd,
4267 INT n_show_cmd)
4268{
4269#ifdef FEAT_MBYTE
4270 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4271 {
4272 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4273 if (wcmd != NULL)
4274 {
4275 HINSTANCE ret;
4276 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4277 vim_free(wcmd);
4278 return ret;
4279 }
4280 }
4281#endif
4282 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4283}
4284
4285
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286#if defined(FEAT_GUI_W32) || defined(PROTO)
4287
4288/*
4289 * Specialised version of system() for Win32 GUI mode.
4290 * This version proceeds as follows:
4291 * 1. Create a console window for use by the subprocess
4292 * 2. Run the subprocess (it gets the allocated console by default)
4293 * 3. Wait for the subprocess to terminate and get its exit code
4294 * 4. Prompt the user to press a key to close the console window
4295 */
4296 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004297mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298{
4299 STARTUPINFO si;
4300 PROCESS_INFORMATION pi;
4301 DWORD ret = 0;
4302 HWND hwnd = GetFocus();
4303
4304 si.cb = sizeof(si);
4305 si.lpReserved = NULL;
4306 si.lpDesktop = NULL;
4307 si.lpTitle = NULL;
4308 si.dwFlags = STARTF_USESHOWWINDOW;
4309 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004310 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004311 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004313 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004314 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 else
4316 si.wShowWindow = SW_SHOWNORMAL;
4317 si.cbReserved2 = 0;
4318 si.lpReserved2 = NULL;
4319
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004321 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004322 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4323 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324
4325 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326 {
4327#ifdef FEAT_GUI
4328 int delay = 1;
4329
4330 /* Keep updating the window while waiting for the shell to finish. */
4331 for (;;)
4332 {
4333 MSG msg;
4334
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004335 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 {
4337 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004338 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004339 delay = 1;
4340 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341 }
4342 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4343 break;
4344
4345 /* We start waiting for a very short time and then increase it, so
4346 * that we respond quickly when the process is quick, and don't
4347 * consume too much overhead when it's slow. */
4348 if (delay < 50)
4349 delay += 10;
4350 }
4351#else
4352 WaitForSingleObject(pi.hProcess, INFINITE);
4353#endif
4354
4355 /* Get the command exit code */
4356 GetExitCodeProcess(pi.hProcess, &ret);
4357 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358
4359 /* Close the handles to the subprocess, so that it goes away */
4360 CloseHandle(pi.hThread);
4361 CloseHandle(pi.hProcess);
4362
4363 /* Try to get input focus back. Doesn't always work though. */
4364 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4365
4366 return ret;
4367}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368
4369/*
4370 * Thread launched by the gui to send the current buffer data to the
4371 * process. This way avoid to hang up vim totally if the children
4372 * process take a long time to process the lines.
4373 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004374 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375sub_process_writer(LPVOID param)
4376{
4377 HANDLE g_hChildStd_IN_Wr = param;
4378 linenr_T lnum = curbuf->b_op_start.lnum;
4379 DWORD len = 0;
4380 DWORD l;
4381 char_u *lp = ml_get(lnum);
4382 char_u *s;
4383 int written = 0;
4384
4385 for (;;)
4386 {
4387 l = (DWORD)STRLEN(lp + written);
4388 if (l == 0)
4389 len = 0;
4390 else if (lp[written] == NL)
4391 {
4392 /* NL -> NUL translation */
4393 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4394 }
4395 else
4396 {
4397 s = vim_strchr(lp + written, NL);
4398 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4399 s == NULL ? l : (DWORD)(s - (lp + written)),
4400 &len, NULL);
4401 }
4402 if (len == (int)l)
4403 {
4404 /* Finished a line, add a NL, unless this line should not have
4405 * one. */
4406 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004407 || (!curbuf->b_p_bin
4408 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409 || (lnum != curbuf->b_no_eol_lnum
4410 && (lnum != curbuf->b_ml.ml_line_count
4411 || curbuf->b_p_eol)))
4412 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004413 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4414 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004415 }
4416
4417 ++lnum;
4418 if (lnum > curbuf->b_op_end.lnum)
4419 break;
4420
4421 lp = ml_get(lnum);
4422 written = 0;
4423 }
4424 else if (len > 0)
4425 written += len;
4426 }
4427
4428 /* finished all the lines, close pipe */
4429 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004430 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004431}
4432
4433
4434# define BUFLEN 100 /* length for buffer, stolen from unix version */
4435
4436/*
4437 * This function read from the children's stdout and write the
4438 * data on screen or in the buffer accordingly.
4439 */
4440 static void
4441dump_pipe(int options,
4442 HANDLE g_hChildStd_OUT_Rd,
4443 garray_T *ga,
4444 char_u buffer[],
4445 DWORD *buffer_off)
4446{
4447 DWORD availableBytes = 0;
4448 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 int ret;
4450 DWORD len;
4451 DWORD toRead;
4452 int repeatCount;
4453
4454 /* we query the pipe to see if there is any data to read
4455 * to avoid to perform a blocking read */
4456 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4457 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004458 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004459 NULL, /* number of read bytes */
4460 &availableBytes, /* available bytes total */
4461 NULL); /* byteLeft */
4462
4463 repeatCount = 0;
4464 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004465 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 {
4467 repeatCount++;
4468 toRead =
4469# ifdef FEAT_MBYTE
4470 (DWORD)(BUFLEN - *buffer_off);
4471# else
4472 (DWORD)BUFLEN;
4473# endif
4474 toRead = availableBytes < toRead ? availableBytes : toRead;
4475 ReadFile(g_hChildStd_OUT_Rd, buffer
4476# ifdef FEAT_MBYTE
4477 + *buffer_off, toRead
4478# else
4479 , toRead
4480# endif
4481 , &len, NULL);
4482
4483 /* If we haven't read anything, there is a problem */
4484 if (len == 0)
4485 break;
4486
4487 availableBytes -= len;
4488
4489 if (options & SHELL_READ)
4490 {
4491 /* Do NUL -> NL translation, append NL separated
4492 * lines to the current buffer. */
4493 for (i = 0; i < len; ++i)
4494 {
4495 if (buffer[i] == NL)
4496 append_ga_line(ga);
4497 else if (buffer[i] == NUL)
4498 ga_append(ga, NL);
4499 else
4500 ga_append(ga, buffer[i]);
4501 }
4502 }
4503# ifdef FEAT_MBYTE
4504 else if (has_mbyte)
4505 {
4506 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004507 int c;
4508 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004509
4510 len += *buffer_off;
4511 buffer[len] = NUL;
4512
4513 /* Check if the last character in buffer[] is
4514 * incomplete, keep these bytes for the next
4515 * round. */
4516 for (p = buffer; p < buffer + len; p += l)
4517 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004518 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004519 if (l == 0)
4520 l = 1; /* NUL byte? */
4521 else if (MB_BYTE2LEN(*p) != l)
4522 break;
4523 }
4524 if (p == buffer) /* no complete character */
4525 {
4526 /* avoid getting stuck at an illegal byte */
4527 if (len >= 12)
4528 ++p;
4529 else
4530 {
4531 *buffer_off = len;
4532 return;
4533 }
4534 }
4535 c = *p;
4536 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004537 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004538 if (p < buffer + len)
4539 {
4540 *p = c;
4541 *buffer_off = (DWORD)((buffer + len) - p);
4542 mch_memmove(buffer, p, *buffer_off);
4543 return;
4544 }
4545 *buffer_off = 0;
4546 }
4547# endif /* FEAT_MBYTE */
4548 else
4549 {
4550 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004551 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004552 }
4553
4554 windgoto(msg_row, msg_col);
4555 cursor_on();
4556 out_flush();
4557 }
4558}
4559
4560/*
4561 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4562 * for communication and doesn't open any new window.
4563 */
4564 static int
4565mch_system_piped(char *cmd, int options)
4566{
4567 STARTUPINFO si;
4568 PROCESS_INFORMATION pi;
4569 DWORD ret = 0;
4570
4571 HANDLE g_hChildStd_IN_Rd = NULL;
4572 HANDLE g_hChildStd_IN_Wr = NULL;
4573 HANDLE g_hChildStd_OUT_Rd = NULL;
4574 HANDLE g_hChildStd_OUT_Wr = NULL;
4575
4576 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4577 DWORD len;
4578
4579 /* buffer used to receive keys */
4580 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4581 int ta_len = 0; /* valid bytes in ta_buf[] */
4582
4583 DWORD i;
4584 int c;
4585 int noread_cnt = 0;
4586 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004587 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004588 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004589 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590
4591 SECURITY_ATTRIBUTES saAttr;
4592
4593 /* Set the bInheritHandle flag so pipe handles are inherited. */
4594 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4595 saAttr.bInheritHandle = TRUE;
4596 saAttr.lpSecurityDescriptor = NULL;
4597
4598 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4599 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004600 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004601 /* Create a pipe for the child process's STDIN. */
4602 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4603 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004604 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004605 {
4606 CloseHandle(g_hChildStd_IN_Rd);
4607 CloseHandle(g_hChildStd_IN_Wr);
4608 CloseHandle(g_hChildStd_OUT_Rd);
4609 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004610 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004611 }
4612
4613 si.cb = sizeof(si);
4614 si.lpReserved = NULL;
4615 si.lpDesktop = NULL;
4616 si.lpTitle = NULL;
4617 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4618
4619 /* set-up our file redirection */
4620 si.hStdError = g_hChildStd_OUT_Wr;
4621 si.hStdOutput = g_hChildStd_OUT_Wr;
4622 si.hStdInput = g_hChildStd_IN_Rd;
4623 si.wShowWindow = SW_HIDE;
4624 si.cbReserved2 = 0;
4625 si.lpReserved2 = NULL;
4626
4627 if (options & SHELL_READ)
4628 ga_init2(&ga, 1, BUFLEN);
4629
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004630 if (cmd != NULL)
4631 {
4632 p = (char *)vim_strsave((char_u *)cmd);
4633 if (p != NULL)
4634 unescape_shellxquote((char_u *)p, p_sxe);
4635 else
4636 p = cmd;
4637 }
4638
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004639 /* Now, run the command.
4640 * About "Inherit handles" being TRUE: this command can be litigious,
4641 * handle inheritance was deactivated for pending temp file, but, if we
4642 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004643 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4644 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004645
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004646 if (p != cmd)
4647 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004648
4649 /* Close our unused side of the pipes */
4650 CloseHandle(g_hChildStd_IN_Rd);
4651 CloseHandle(g_hChildStd_OUT_Wr);
4652
4653 if (options & SHELL_WRITE)
4654 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004655 HANDLE thread = (HANDLE)
4656 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004657 0, /* default stack size */
4658 sub_process_writer, /* function to be executed */
4659 g_hChildStd_IN_Wr, /* parameter */
4660 0, /* creation flag, start immediately */
4661 NULL); /* we don't care about thread id */
4662 CloseHandle(thread);
4663 g_hChildStd_IN_Wr = NULL;
4664 }
4665
4666 /* Keep updating the window while waiting for the shell to finish. */
4667 for (;;)
4668 {
4669 MSG msg;
4670
Bram Moolenaar175d0702013-12-11 18:36:33 +01004671 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004672 {
4673 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004674 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004675 }
4676
4677 /* write pipe information in the window */
4678 if ((options & (SHELL_READ|SHELL_WRITE))
4679# ifdef FEAT_GUI
4680 || gui.in_use
4681# endif
4682 )
4683 {
4684 len = 0;
4685 if (!(options & SHELL_EXPAND)
4686 && ((options &
4687 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4688 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4689# ifdef FEAT_GUI
4690 || gui.in_use
4691# endif
4692 )
4693 && (ta_len > 0 || noread_cnt > 4))
4694 {
4695 if (ta_len == 0)
4696 {
4697 /* Get extra characters when we don't have any. Reset the
4698 * counter and timer. */
4699 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004700 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4701 }
4702 if (ta_len > 0 || len > 0)
4703 {
4704 /*
4705 * For pipes: Check for CTRL-C: send interrupt signal to
4706 * child. Check for CTRL-D: EOF, close pipe to child.
4707 */
4708 if (len == 1 && cmd != NULL)
4709 {
4710 if (ta_buf[ta_len] == Ctrl_C)
4711 {
4712 /* Learn what exit code is expected, for
4713 * now put 9 as SIGKILL */
4714 TerminateProcess(pi.hProcess, 9);
4715 }
4716 if (ta_buf[ta_len] == Ctrl_D)
4717 {
4718 CloseHandle(g_hChildStd_IN_Wr);
4719 g_hChildStd_IN_Wr = NULL;
4720 }
4721 }
4722
4723 /* replace K_BS by <BS> and K_DEL by <DEL> */
4724 for (i = ta_len; i < ta_len + len; ++i)
4725 {
4726 if (ta_buf[i] == CSI && len - i > 2)
4727 {
4728 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4729 if (c == K_DEL || c == K_KDEL || c == K_BS)
4730 {
4731 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4732 (size_t)(len - i - 2));
4733 if (c == K_DEL || c == K_KDEL)
4734 ta_buf[i] = DEL;
4735 else
4736 ta_buf[i] = Ctrl_H;
4737 len -= 2;
4738 }
4739 }
4740 else if (ta_buf[i] == '\r')
4741 ta_buf[i] = '\n';
4742# ifdef FEAT_MBYTE
4743 if (has_mbyte)
4744 i += (*mb_ptr2len_len)(ta_buf + i,
4745 ta_len + len - i) - 1;
4746# endif
4747 }
4748
4749 /*
4750 * For pipes: echo the typed characters. For a pty this
4751 * does not seem to work.
4752 */
4753 for (i = ta_len; i < ta_len + len; ++i)
4754 {
4755 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4756 msg_putchar(ta_buf[i]);
4757# ifdef FEAT_MBYTE
4758 else if (has_mbyte)
4759 {
4760 int l = (*mb_ptr2len)(ta_buf + i);
4761
4762 msg_outtrans_len(ta_buf + i, l);
4763 i += l - 1;
4764 }
4765# endif
4766 else
4767 msg_outtrans_len(ta_buf + i, 1);
4768 }
4769 windgoto(msg_row, msg_col);
4770 out_flush();
4771
4772 ta_len += len;
4773
4774 /*
4775 * Write the characters to the child, unless EOF has been
4776 * typed for pipes. Write one character at a time, to
4777 * avoid losing too much typeahead. When writing buffer
4778 * lines, drop the typed characters (only check for
4779 * CTRL-C).
4780 */
4781 if (options & SHELL_WRITE)
4782 ta_len = 0;
4783 else if (g_hChildStd_IN_Wr != NULL)
4784 {
4785 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4786 1, &len, NULL);
4787 // if we are typing in, we want to keep things reactive
4788 delay = 1;
4789 if (len > 0)
4790 {
4791 ta_len -= len;
4792 mch_memmove(ta_buf, ta_buf + len, ta_len);
4793 }
4794 }
4795 }
4796 }
4797 }
4798
4799 if (ta_len)
4800 ui_inchar_undo(ta_buf, ta_len);
4801
4802 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4803 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004804 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004805 break;
4806 }
4807
4808 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004809 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004810
4811 /* We start waiting for a very short time and then increase it, so
4812 * that we respond quickly when the process is quick, and don't
4813 * consume too much overhead when it's slow. */
4814 if (delay < 50)
4815 delay += 10;
4816 }
4817
4818 /* Close the pipe */
4819 CloseHandle(g_hChildStd_OUT_Rd);
4820 if (g_hChildStd_IN_Wr != NULL)
4821 CloseHandle(g_hChildStd_IN_Wr);
4822
4823 WaitForSingleObject(pi.hProcess, INFINITE);
4824
4825 /* Get the command exit code */
4826 GetExitCodeProcess(pi.hProcess, &ret);
4827
4828 if (options & SHELL_READ)
4829 {
4830 if (ga.ga_len > 0)
4831 {
4832 append_ga_line(&ga);
4833 /* remember that the NL was missing */
4834 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4835 }
4836 else
4837 curbuf->b_no_eol_lnum = 0;
4838 ga_clear(&ga);
4839 }
4840
4841 /* Close the handles to the subprocess, so that it goes away */
4842 CloseHandle(pi.hThread);
4843 CloseHandle(pi.hProcess);
4844
4845 return ret;
4846}
4847
4848 static int
4849mch_system(char *cmd, int options)
4850{
4851 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004852 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004853 return mch_system_piped(cmd, options);
4854 else
4855 return mch_system_classic(cmd, options);
4856}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857#else
4858
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004859# ifdef FEAT_MBYTE
4860 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004861mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004862{
4863 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4864 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004865 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004866 if (wcmd != NULL)
4867 {
4868 int ret = _wsystem(wcmd);
4869 vim_free(wcmd);
4870 return ret;
4871 }
4872 }
4873 return system(cmd);
4874}
4875# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004876# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004877# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878
4879#endif
4880
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004881#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4882/*
4883 * Use a terminal window to run a shell command in.
4884 */
4885 static int
4886mch_call_shell_terminal(
4887 char_u *cmd,
4888 int options UNUSED) /* SHELL_*, see vim.h */
4889{
4890 jobopt_T opt;
4891 char_u *newcmd = NULL;
4892 typval_T argvar[2];
4893 long_u cmdlen;
4894 int retval = -1;
4895 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004896 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004897 aco_save_T aco;
4898 oparg_T oa; /* operator arguments */
4899
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004900 if (cmd == NULL)
4901 cmdlen = STRLEN(p_sh) + 1;
4902 else
4903 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004904 newcmd = lalloc(cmdlen, TRUE);
4905 if (newcmd == NULL)
4906 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004907 if (cmd == NULL)
4908 {
4909 STRCPY(newcmd, p_sh);
4910 ch_log(NULL, "starting terminal to run a shell");
4911 }
4912 else
4913 {
4914 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4915 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4916 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004917
4918 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004919
4920 argvar[0].v_type = VAR_STRING;
4921 argvar[0].vval.v_string = newcmd;
4922 argvar[1].v_type = VAR_UNKNOWN;
4923 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004924 if (buf == NULL)
4925 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004926
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004927 job = term_getjob(buf->b_term);
4928 ++job->jv_refcount;
4929
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004930 /* Find a window to make "buf" curbuf. */
4931 aucmd_prepbuf(&aco, buf);
4932
4933 clear_oparg(&oa);
4934 while (term_use_loop())
4935 {
4936 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4937 {
4938 /* If terminal_loop() returns OK we got a key that is handled
4939 * in Normal model. We don't do redrawing anyway. */
4940 if (terminal_loop(TRUE) == OK)
4941 normal_cmd(&oa, TRUE);
4942 }
4943 else
4944 normal_cmd(&oa, TRUE);
4945 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004946 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004947 ch_log(NULL, "system command finished");
4948
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004949 job_unref(job);
4950
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004951 /* restore curwin/curbuf and a few other things */
4952 aucmd_restbuf(&aco);
4953
4954 wait_return(TRUE);
4955 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4956
4957 vim_free(newcmd);
4958 return retval;
4959}
4960#endif
4961
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962/*
4963 * Either execute a command by calling the shell or start a new shell
4964 */
4965 int
4966mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004967 char_u *cmd,
4968 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969{
4970 int x = 0;
4971 int tmode = cur_tmode;
4972#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004973 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004974# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004975 int did_set_title = FALSE;
4976
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004977 /* Change the title to reflect that we are in a subshell. */
4978 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4979 {
4980 WCHAR szShellTitle[512];
4981
4982 if (GetConsoleTitleW(szShellTitle,
4983 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4984 {
4985 if (cmd == NULL)
4986 wcscat(szShellTitle, L" :sh");
4987 else
4988 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004989 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004990
4991 if (wn != NULL)
4992 {
4993 wcscat(szShellTitle, L" - !");
4994 if ((wcslen(szShellTitle) + wcslen(wn) <
4995 sizeof(szShellTitle)/sizeof(WCHAR)))
4996 wcscat(szShellTitle, wn);
4997 SetConsoleTitleW(szShellTitle);
4998 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004999 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02005000 }
5001 }
5002 }
5003 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005004 if (!did_set_title)
5005# endif
5006 /* Change the title to reflect that we are in a subshell. */
5007 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005009 if (cmd == NULL)
5010 strcat(szShellTitle, " :sh");
5011 else
5012 {
5013 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005014 if ((strlen(szShellTitle) + strlen((char *)cmd)
5015 < sizeof(szShellTitle)))
5016 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02005017 }
5018 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020#endif
5021
5022 out_flush();
5023
5024#ifdef MCH_WRITE_DUMP
5025 if (fdDump)
5026 {
5027 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5028 fflush(fdDump);
5029 }
5030#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005031#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5032 /* TODO: make the terminal window work with input or output redirected. */
5033 if (vim_strchr(p_go, GO_TERMINAL) != NULL
5034 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5035 {
5036 /* Use a terminal window to run the command in. */
5037 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01005038# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005039 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01005040# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005041 return x;
5042 }
5043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044
5045 /*
5046 * Catch all deadly signals while running the external command, because a
5047 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5048 */
5049 signal(SIGINT, SIG_IGN);
5050#if defined(__GNUC__) && !defined(__MINGW32__)
5051 signal(SIGKILL, SIG_IGN);
5052#else
5053 signal(SIGBREAK, SIG_IGN);
5054#endif
5055 signal(SIGILL, SIG_IGN);
5056 signal(SIGFPE, SIG_IGN);
5057 signal(SIGSEGV, SIG_IGN);
5058 signal(SIGTERM, SIG_IGN);
5059 signal(SIGABRT, SIG_IGN);
5060
5061 if (options & SHELL_COOKED)
5062 settmode(TMODE_COOK); /* set to normal mode */
5063
5064 if (cmd == NULL)
5065 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005066 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067 }
5068 else
5069 {
5070 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005071 char_u *newcmd = NULL;
5072 char_u *cmdbase = cmd;
5073 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005074
5075 /* Skip a leading ", ( and "(. */
5076 if (*cmdbase == '"' )
5077 ++cmdbase;
5078 if (*cmdbase == '(')
5079 ++cmdbase;
5080
Bram Moolenaar1c465442017-03-12 20:10:05 +01005081 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005082 {
5083 STARTUPINFO si;
5084 PROCESS_INFORMATION pi;
5085 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005086 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 char_u *p;
5088
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005089 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005090 si.cb = sizeof(si);
5091 si.lpReserved = NULL;
5092 si.lpDesktop = NULL;
5093 si.lpTitle = NULL;
5094 si.dwFlags = 0;
5095 si.cbReserved2 = 0;
5096 si.lpReserved2 = NULL;
5097
5098 cmdbase = skipwhite(cmdbase + 5);
5099 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005100 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005101 {
5102 cmdbase = skipwhite(cmdbase + 4);
5103 si.dwFlags = STARTF_USESHOWWINDOW;
5104 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005105 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005106 }
5107 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005108 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005109 {
5110 cmdbase = skipwhite(cmdbase + 2);
5111 flags = CREATE_NO_WINDOW;
5112 si.dwFlags = STARTF_USESTDHANDLES;
5113 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005114 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005115 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005116 NULL, // Security att.
5117 OPEN_EXISTING, // Open flags
5118 FILE_ATTRIBUTE_NORMAL, // File att.
5119 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005120 si.hStdOutput = si.hStdInput;
5121 si.hStdError = si.hStdInput;
5122 }
5123
5124 /* Remove a trailing ", ) and )" if they have a match
5125 * at the start of the command. */
5126 if (cmdbase > cmd)
5127 {
5128 p = cmdbase + STRLEN(cmdbase);
5129 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5130 *--p = NUL;
5131 if (p > cmdbase && p[-1] == ')'
5132 && (*cmd =='(' || cmd[1] == '('))
5133 *--p = NUL;
5134 }
5135
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005136 newcmd = cmdbase;
5137 unescape_shellxquote(cmdbase, p_sxe);
5138
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005139 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005140 * If creating new console, arguments are passed to the
5141 * 'cmd.exe' as-is. If it's not, arguments are not treated
5142 * correctly for current 'cmd.exe'. So unescape characters in
5143 * shellxescape except '|' for avoiding to be treated as
5144 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005145 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005146 if (flags != CREATE_NEW_CONSOLE)
5147 {
5148 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005149 char_u *cmd_shell = mch_getenv("COMSPEC");
5150
5151 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005152 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005153
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005154 subcmd = vim_strsave_escaped_ext(cmdbase,
5155 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005156 if (subcmd != NULL)
5157 {
5158 /* make "cmd.exe /c arguments" */
5159 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005160 newcmd = lalloc(cmdlen, TRUE);
5161 if (newcmd != NULL)
5162 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005163 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005164 else
5165 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005166 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005167 }
5168 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005169
5170 /*
5171 * Now, start the command as a process, so that it doesn't
5172 * inherit our handles which causes unpleasant dangling swap
5173 * files if we exit before the spawned process
5174 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005175 if (vim_create_process((char *)newcmd, FALSE, flags,
5176 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005177 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005178 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5179 > (HINSTANCE)32)
5180 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005181 else
5182 {
5183 x = -1;
5184#ifdef FEAT_GUI_W32
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005185 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005186#endif
5187 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005188
5189 if (newcmd != cmdbase)
5190 vim_free(newcmd);
5191
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005192 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005193 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005194 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005195 CloseHandle(si.hStdInput);
5196 }
5197 /* Close the handles to the subprocess, so that it goes away */
5198 CloseHandle(pi.hThread);
5199 CloseHandle(pi.hProcess);
5200 }
5201 else
5202 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005203 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005205 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005207 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5208
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005209 newcmd = lalloc(cmdlen, TRUE);
5210 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211 {
5212#if defined(FEAT_GUI_W32)
5213 if (need_vimrun_warning)
5214 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005215 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5216 "External commands will not pause after completion.\n"
5217 "See :help win32-vimrun for more information.");
5218 char *title = _("Vim Warning");
5219# ifdef FEAT_MBYTE
5220 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5221 {
5222 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5223 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5224
5225 if (wmsg != NULL && wtitle != NULL)
5226 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5227 vim_free(wmsg);
5228 vim_free(wtitle);
5229 }
5230 else
5231# endif
5232 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 need_vimrun_warning = FALSE;
5234 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005235 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236 /* Use vimrun to execute the command. It opens a console
5237 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005238 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239 vimrun_path,
5240 (msg_silent != 0 || (options & SHELL_DOOUT))
5241 ? "-s " : "",
5242 p_sh, p_shcf, cmd);
5243 else
5244#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005245 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005246 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005248 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250 }
5251 }
5252
5253 if (tmode == TMODE_RAW)
5254 settmode(TMODE_RAW); /* set to raw mode */
5255
5256 /* Print the return value, unless "vimrun" was used. */
5257 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5258#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005259 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260#endif
5261 )
5262 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005263 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264 msg_putchar('\n');
5265 }
5266#ifdef FEAT_TITLE
5267 resettitle();
5268#endif
5269
5270 signal(SIGINT, SIG_DFL);
5271#if defined(__GNUC__) && !defined(__MINGW32__)
5272 signal(SIGKILL, SIG_DFL);
5273#else
5274 signal(SIGBREAK, SIG_DFL);
5275#endif
5276 signal(SIGILL, SIG_DFL);
5277 signal(SIGFPE, SIG_DFL);
5278 signal(SIGSEGV, SIG_DFL);
5279 signal(SIGTERM, SIG_DFL);
5280 signal(SIGABRT, SIG_DFL);
5281
5282 return x;
5283}
5284
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005285#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005286 static HANDLE
5287job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005288 char_u *fname,
5289 DWORD dwDesiredAccess,
5290 DWORD dwShareMode,
5291 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5292 DWORD dwCreationDisposition,
5293 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005294{
5295 HANDLE h;
5296# ifdef FEAT_MBYTE
5297 WCHAR *wn = NULL;
5298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5299 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005300 wn = enc_to_utf16(fname, NULL);
5301 if (wn != NULL)
5302 {
5303 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5304 lpSecurityAttributes, dwCreationDisposition,
5305 dwFlagsAndAttributes, NULL);
5306 vim_free(wn);
5307 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005308 }
5309 if (wn == NULL)
5310# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005311 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5312 lpSecurityAttributes, dwCreationDisposition,
5313 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005314 return h;
5315}
5316
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005317/*
5318 * Turn the dictionary "env" into a NUL separated list that can be used as the
5319 * environment argument of vim_create_process().
5320 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005321 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005322win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005323{
5324 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005325 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005326 LPVOID base = GetEnvironmentStringsW();
5327
5328 /* for last \0 */
5329 if (ga_grow(gap, 1) == FAIL)
5330 return;
5331
5332 if (base)
5333 {
5334 WCHAR *p = (WCHAR*) base;
5335
5336 /* for last \0 */
5337 if (ga_grow(gap, 1) == FAIL)
5338 return;
5339
5340 while (*p != 0 || *(p + 1) != 0)
5341 {
5342 if (ga_grow(gap, 1) == OK)
5343 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5344 p++;
5345 }
5346 FreeEnvironmentStrings(base);
5347 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5348 }
5349
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005350 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005351 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005352 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005353 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005354 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005355 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005356 typval_T *item = &dict_lookup(hi)->di_tv;
5357 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005358 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005359 --todo;
5360 if (wkey != NULL && wval != NULL)
5361 {
5362 size_t n;
5363 size_t lkey = wcslen(wkey);
5364 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005365
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005366 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5367 continue;
5368 for (n = 0; n < lkey; n++)
5369 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5371 for (n = 0; n < lval; n++)
5372 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5373 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5374 }
5375 if (wkey != NULL) vim_free(wkey);
5376 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005377 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005378 }
5379 }
5380
Bram Moolenaar493359e2018-06-12 20:25:52 +02005381# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005382 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005383# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005384 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005385 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005386# endif
5387# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005388 char_u *version = get_vim_var_str(VV_VERSION);
5389 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005390# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005391 // size of "VIM_SERVERNAME=" and value,
5392 // plus "VIM_TERMINAL=" and value,
5393 // plus two terminating NULs
5394 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005395# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005396 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005397# endif
5398# ifdef FEAT_TERMINAL
5399 + 13 + version_len + 2
5400# endif
5401 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005402
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005403 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005404 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005405# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005406 for (n = 0; n < 15; n++)
5407 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5408 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005409 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005410 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5411 (WCHAR)servername[n];
5412 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005413# endif
5414# ifdef FEAT_TERMINAL
5415 if (is_terminal)
5416 {
5417 for (n = 0; n < 13; n++)
5418 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5419 (WCHAR)"VIM_TERMINAL="[n];
5420 for (n = 0; n < version_len; n++)
5421 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5422 (WCHAR)version[n];
5423 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5424 }
5425# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005426 }
5427 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005428# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005429}
5430
Bram Moolenaarb091f302019-01-19 14:37:00 +01005431/*
5432 * Create a pair of pipes.
5433 * Return TRUE for success, FALSE for failure.
5434 */
5435 static BOOL
5436create_pipe_pair(HANDLE handles[2])
5437{
5438 static LONG s;
5439 char name[64];
5440 SECURITY_ATTRIBUTES sa;
5441
5442 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5443 GetCurrentProcessId(),
5444 InterlockedIncrement(&s));
5445
5446 // Create named pipe. Max size of named pipe is 65535.
5447 handles[1] = CreateNamedPipe(
5448 name,
5449 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5450 PIPE_TYPE_BYTE | PIPE_NOWAIT,
5451 1, 65535, 0, 0, NULL);
5452
5453 if (handles[1] == INVALID_HANDLE_VALUE)
5454 return FALSE;
5455
5456 sa.nLength = sizeof(sa);
5457 sa.bInheritHandle = TRUE;
5458 sa.lpSecurityDescriptor = NULL;
5459
5460 handles[0] = CreateFile(name,
5461 FILE_GENERIC_READ,
5462 FILE_SHARE_READ, &sa,
5463 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5464
5465 if (handles[0] == INVALID_HANDLE_VALUE)
5466 {
5467 CloseHandle(handles[1]);
5468 return FALSE;
5469 }
5470
5471 return TRUE;
5472}
5473
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005474 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005475mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005476{
5477 STARTUPINFO si;
5478 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005479 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005480 SECURITY_ATTRIBUTES saAttr;
5481 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005482 HANDLE ifd[2];
5483 HANDLE ofd[2];
5484 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005485 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005486
5487 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5488 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5489 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5490 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5491 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5492 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5493 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5494
5495 if (use_out_for_err && use_null_for_out)
5496 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005497
5498 ifd[0] = INVALID_HANDLE_VALUE;
5499 ifd[1] = INVALID_HANDLE_VALUE;
5500 ofd[0] = INVALID_HANDLE_VALUE;
5501 ofd[1] = INVALID_HANDLE_VALUE;
5502 efd[0] = INVALID_HANDLE_VALUE;
5503 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005504 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005505
Bram Moolenaar14207f42016-10-27 21:13:10 +02005506 jo = CreateJobObject(NULL, NULL);
5507 if (jo == NULL)
5508 {
5509 job->jv_status = JOB_FAILED;
5510 goto failed;
5511 }
5512
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005513 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005514 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005515
Bram Moolenaar76467df2016-02-12 19:30:26 +01005516 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005517 ZeroMemory(&si, sizeof(si));
5518 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005519 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005520 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005521
Bram Moolenaard8070362016-02-15 21:56:54 +01005522 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5523 saAttr.bInheritHandle = TRUE;
5524 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005525
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005526 if (use_file_for_in)
5527 {
5528 char_u *fname = options->jo_io_name[PART_IN];
5529
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005530 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5531 FILE_SHARE_READ | FILE_SHARE_WRITE,
5532 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5533 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005534 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005535 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005536 goto failed;
5537 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005538 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005539 else if (!use_null_for_in
5540 && (!create_pipe_pair(ifd)
5541 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005542 goto failed;
5543
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005544 if (use_file_for_out)
5545 {
5546 char_u *fname = options->jo_io_name[PART_OUT];
5547
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005548 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5549 FILE_SHARE_READ | FILE_SHARE_WRITE,
5550 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5551 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005552 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005553 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005554 goto failed;
5555 }
5556 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005557 else if (!use_null_for_out &&
5558 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005559 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005560 goto failed;
5561
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005562 if (use_file_for_err)
5563 {
5564 char_u *fname = options->jo_io_name[PART_ERR];
5565
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005566 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5567 FILE_SHARE_READ | FILE_SHARE_WRITE,
5568 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5569 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005570 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005571 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005572 goto failed;
5573 }
5574 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005575 else if (!use_out_for_err && !use_null_for_err &&
5576 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005577 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005578 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005579
Bram Moolenaard8070362016-02-15 21:56:54 +01005580 si.dwFlags |= STARTF_USESTDHANDLES;
5581 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005582 si.hStdOutput = ofd[1];
5583 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5584
5585 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5586 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005587 if (options->jo_set & JO_CHANNEL)
5588 {
5589 channel = options->jo_channel;
5590 if (channel != NULL)
5591 ++channel->ch_refcount;
5592 }
5593 else
5594 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005595 if (channel == NULL)
5596 goto failed;
5597 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005598
5599 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005600 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005601 CREATE_DEFAULT_ERROR_MODE |
5602 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005603 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005604 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005605 &si, &pi,
5606 ga.ga_data,
5607 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005608 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005609 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005610 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005611 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005612 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005613
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005614 ga_clear(&ga);
5615
Bram Moolenaar14207f42016-10-27 21:13:10 +02005616 if (!AssignProcessToJobObject(jo, pi.hProcess))
5617 {
5618 /* if failing, switch the way to terminate
5619 * process with TerminateProcess. */
5620 CloseHandle(jo);
5621 jo = NULL;
5622 }
5623 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005624 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005625 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005626 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005627 job->jv_status = JOB_STARTED;
5628
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005629 CloseHandle(ifd[0]);
5630 CloseHandle(ofd[1]);
5631 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005632 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005633
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005634 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005635 if (channel != NULL)
5636 {
5637 channel_set_pipes(channel,
5638 use_file_for_in || use_null_for_in
5639 ? INVALID_FD : (sock_T)ifd[1],
5640 use_file_for_out || use_null_for_out
5641 ? INVALID_FD : (sock_T)ofd[0],
5642 use_out_for_err || use_file_for_err || use_null_for_err
5643 ? INVALID_FD : (sock_T)efd[0]);
5644 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005645 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005646 return;
5647
5648failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005649 CloseHandle(ifd[0]);
5650 CloseHandle(ofd[0]);
5651 CloseHandle(efd[0]);
5652 CloseHandle(ifd[1]);
5653 CloseHandle(ofd[1]);
5654 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005655 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005656 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005657}
5658
5659 char *
5660mch_job_status(job_T *job)
5661{
5662 DWORD dwExitCode = 0;
5663
Bram Moolenaar76467df2016-02-12 19:30:26 +01005664 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5665 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005666 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005667 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005668 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005669 {
5670 ch_log(job->jv_channel, "Job ended");
5671 job->jv_status = JOB_ENDED;
5672 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005673 return "dead";
5674 }
5675 return "run";
5676}
5677
Bram Moolenaar97792de2016-10-15 18:36:49 +02005678 job_T *
5679mch_detect_ended_job(job_T *job_list)
5680{
5681 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5682 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5683 job_T *job = job_list;
5684
5685 while (job != NULL)
5686 {
5687 DWORD n;
5688 DWORD result;
5689
5690 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5691 && job != NULL; job = job->jv_next)
5692 {
5693 if (job->jv_status == JOB_STARTED)
5694 {
5695 jobHandles[n] = job->jv_proc_info.hProcess;
5696 jobArray[n] = job;
5697 ++n;
5698 }
5699 }
5700 if (n == 0)
5701 continue;
5702 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5703 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5704 {
5705 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5706
5707 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5708 return wait_job;
5709 }
5710 }
5711 return NULL;
5712}
5713
Bram Moolenaarfb630902016-10-29 14:55:00 +02005714 static BOOL
5715terminate_all(HANDLE process, int code)
5716{
5717 PROCESSENTRY32 pe;
5718 HANDLE h = INVALID_HANDLE_VALUE;
5719 DWORD pid = GetProcessId(process);
5720
5721 if (pid != 0)
5722 {
5723 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5724 if (h != INVALID_HANDLE_VALUE)
5725 {
5726 pe.dwSize = sizeof(PROCESSENTRY32);
5727 if (!Process32First(h, &pe))
5728 goto theend;
5729
5730 do
5731 {
5732 if (pe.th32ParentProcessID == pid)
5733 {
5734 HANDLE ph = OpenProcess(
5735 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5736 if (ph != NULL)
5737 {
5738 terminate_all(ph, code);
5739 CloseHandle(ph);
5740 }
5741 }
5742 } while (Process32Next(h, &pe));
5743
5744 CloseHandle(h);
5745 }
5746 }
5747
5748theend:
5749 return TerminateProcess(process, code);
5750}
5751
5752/*
5753 * Send a (deadly) signal to "job".
5754 * Return FAIL if it didn't work.
5755 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005756 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005757mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005758{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005759 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005760
Bram Moolenaar923d9262016-02-25 20:56:01 +01005761 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005762 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005763 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005764 if (job->jv_job_object != NULL)
5765 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005766 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005767 }
5768
5769 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5770 return FAIL;
5771 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005772 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5773 job->jv_proc_info.dwProcessId)
5774 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005775 FreeConsole();
5776 return ret;
5777}
5778
5779/*
5780 * Clear the data related to "job".
5781 */
5782 void
5783mch_clear_job(job_T *job)
5784{
5785 if (job->jv_status != JOB_FAILED)
5786 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005787 if (job->jv_job_object != NULL)
5788 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005789 CloseHandle(job->jv_proc_info.hProcess);
5790 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005791}
5792#endif
5793
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794
5795#ifndef FEAT_GUI_W32
5796
5797/*
5798 * Start termcap mode
5799 */
5800 static void
5801termcap_mode_start(void)
5802{
5803 DWORD cmodein;
5804
5805 if (g_fTermcapMode)
5806 return;
5807
5808 SaveConsoleBuffer(&g_cbNonTermcap);
5809
5810 if (g_cbTermcap.IsValid)
5811 {
5812 /*
5813 * We've been in termcap mode before. Restore certain screen
5814 * characteristics, including the buffer size and the window
5815 * size. Since we will be redrawing the screen, we don't need
5816 * to restore the actual contents of the buffer.
5817 */
5818 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005819 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5821 Rows = g_cbTermcap.Info.dwSize.Y;
5822 Columns = g_cbTermcap.Info.dwSize.X;
5823 }
5824 else
5825 {
5826 /*
5827 * This is our first time entering termcap mode. Clear the console
5828 * screen buffer, and resize the buffer to match the current window
5829 * size. We will use this as the size of our editing environment.
5830 */
5831 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005832 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5834 }
5835
5836#ifdef FEAT_TITLE
5837 resettitle();
5838#endif
5839
5840 GetConsoleMode(g_hConIn, &cmodein);
5841#ifdef FEAT_MOUSE
5842 if (g_fMouseActive)
5843 cmodein |= ENABLE_MOUSE_INPUT;
5844 else
5845 cmodein &= ~ENABLE_MOUSE_INPUT;
5846#endif
5847 cmodein |= ENABLE_WINDOW_INPUT;
5848 SetConsoleMode(g_hConIn, cmodein);
5849
5850 redraw_later_clear();
5851 g_fTermcapMode = TRUE;
5852}
5853
5854
5855/*
5856 * End termcap mode
5857 */
5858 static void
5859termcap_mode_end(void)
5860{
5861 DWORD cmodein;
5862 ConsoleBuffer *cb;
5863 COORD coord;
5864 DWORD dwDummy;
5865
5866 if (!g_fTermcapMode)
5867 return;
5868
5869 SaveConsoleBuffer(&g_cbTermcap);
5870
5871 GetConsoleMode(g_hConIn, &cmodein);
5872 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5873 SetConsoleMode(g_hConIn, cmodein);
5874
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005875#ifdef FEAT_RESTORE_ORIG_SCREEN
5876 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5877#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005879#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005881 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 SetConsoleCursorInfo(g_hConOut, &g_cci);
5883
5884 if (p_rs || exiting)
5885 {
5886 /*
5887 * Clear anything that happens to be on the current line.
5888 */
5889 coord.X = 0;
5890 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5891 FillConsoleOutputCharacter(g_hConOut, ' ',
5892 cb->Info.dwSize.X, coord, &dwDummy);
5893 /*
5894 * The following is just for aesthetics. If we are exiting without
5895 * restoring the screen, then we want to have a prompt string
5896 * appear at the bottom line. However, the command interpreter
5897 * seems to always advance the cursor one line before displaying
5898 * the prompt string, which causes the screen to scroll. To
5899 * counter this, move the cursor up one line before exiting.
5900 */
5901 if (exiting && !p_rs)
5902 coord.Y--;
5903 /*
5904 * Position the cursor at the leftmost column of the desired row.
5905 */
5906 SetConsoleCursorPosition(g_hConOut, coord);
5907 }
5908
5909 g_fTermcapMode = FALSE;
5910}
5911#endif /* FEAT_GUI_W32 */
5912
5913
5914#ifdef FEAT_GUI_W32
5915 void
5916mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005917 char_u *s UNUSED,
5918 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919{
5920 /* never used */
5921}
5922
5923#else
5924
5925/*
5926 * clear `n' chars, starting from `coord'
5927 */
5928 static void
5929clear_chars(
5930 COORD coord,
5931 DWORD n)
5932{
5933 DWORD dwDummy;
5934
5935 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005936
5937 if (!USE_VTP)
5938 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5939 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005940 {
5941 set_console_color_rgb();
5942 gotoxy(coord.X + 1, coord.Y + 1);
5943 vtp_printf("\033[%dX", n);
5944 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945}
5946
5947
5948/*
5949 * Clear the screen
5950 */
5951 static void
5952clear_screen(void)
5953{
5954 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005955
5956 if (!USE_VTP)
5957 clear_chars(g_coord, Rows * Columns);
5958 else
5959 {
5960 set_console_color_rgb();
5961 gotoxy(1, 1);
5962 vtp_printf("\033[2J");
5963 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964}
5965
5966
5967/*
5968 * Clear to end of display
5969 */
5970 static void
5971clear_to_end_of_display(void)
5972{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005973 COORD save = g_coord;
5974
5975 if (!USE_VTP)
5976 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005978 else
5979 {
5980 set_console_color_rgb();
5981 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5982 vtp_printf("\033[0J");
5983
5984 gotoxy(save.X + 1, save.Y + 1);
5985 g_coord = save;
5986 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987}
5988
5989
5990/*
5991 * Clear to end of line
5992 */
5993 static void
5994clear_to_end_of_line(void)
5995{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005996 COORD save = g_coord;
5997
5998 if (!USE_VTP)
5999 clear_chars(g_coord, Columns - g_coord.X);
6000 else
6001 {
6002 set_console_color_rgb();
6003 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6004 vtp_printf("\033[0K");
6005
6006 gotoxy(save.X + 1, save.Y + 1);
6007 g_coord = save;
6008 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009}
6010
6011
6012/*
6013 * Scroll the scroll region up by `cLines' lines
6014 */
6015 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006016scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006017{
6018 COORD oldcoord = g_coord;
6019
6020 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
6021 delete_lines(cLines);
6022
6023 g_coord = oldcoord;
6024}
6025
6026
6027/*
6028 * Set the scroll region
6029 */
6030 static void
6031set_scroll_region(
6032 unsigned left,
6033 unsigned top,
6034 unsigned right,
6035 unsigned bottom)
6036{
6037 if (left >= right
6038 || top >= bottom
6039 || right > (unsigned) Columns - 1
6040 || bottom > (unsigned) Rows - 1)
6041 return;
6042
6043 g_srScrollRegion.Left = left;
6044 g_srScrollRegion.Top = top;
6045 g_srScrollRegion.Right = right;
6046 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006047
6048 if (USE_VTP)
6049 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050}
6051
6052
6053/*
6054 * Insert `cLines' lines at the current cursor position
6055 */
6056 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006057insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058{
6059 SMALL_RECT source;
6060 COORD dest;
6061 CHAR_INFO fill;
6062
6063 dest.X = 0;
6064 dest.Y = g_coord.Y + cLines;
6065
6066 source.Left = 0;
6067 source.Top = g_coord.Y;
6068 source.Right = g_srScrollRegion.Right;
6069 source.Bottom = g_srScrollRegion.Bottom - cLines;
6070
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006071 if (!USE_VTP)
6072 {
6073 fill.Char.AsciiChar = ' ';
6074 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006076 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6077 }
6078 else
6079 {
6080 set_console_color_rgb();
6081
6082 gotoxy(1, source.Top + 1);
6083 vtp_printf("\033[%dT", cLines);
6084 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085
6086 /* Here we have to deal with a win32 console flake: If the scroll
6087 * region looks like abc and we scroll c to a and fill with d we get
6088 * cbd... if we scroll block c one line at a time to a, we get cdd...
6089 * vim expects cdd consistently... So we have to deal with that
6090 * here... (this also occurs scrolling the same way in the other
6091 * direction). */
6092
6093 if (source.Bottom < dest.Y)
6094 {
6095 COORD coord;
6096
6097 coord.X = 0;
6098 coord.Y = source.Bottom;
6099 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6100 }
6101}
6102
6103
6104/*
6105 * Delete `cLines' lines at the current cursor position
6106 */
6107 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006108delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109{
6110 SMALL_RECT source;
6111 COORD dest;
6112 CHAR_INFO fill;
6113 int nb;
6114
6115 dest.X = 0;
6116 dest.Y = g_coord.Y;
6117
6118 source.Left = 0;
6119 source.Top = g_coord.Y + cLines;
6120 source.Right = g_srScrollRegion.Right;
6121 source.Bottom = g_srScrollRegion.Bottom;
6122
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006123 if (!USE_VTP)
6124 {
6125 fill.Char.AsciiChar = ' ';
6126 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006128 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6129 }
6130 else
6131 {
6132 set_console_color_rgb();
6133
6134 gotoxy(1, source.Top + 1);
6135 vtp_printf("\033[%dS", cLines);
6136 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137
6138 /* Here we have to deal with a win32 console flake: If the scroll
6139 * region looks like abc and we scroll c to a and fill with d we get
6140 * cbd... if we scroll block c one line at a time to a, we get cdd...
6141 * vim expects cdd consistently... So we have to deal with that
6142 * here... (this also occurs scrolling the same way in the other
6143 * direction). */
6144
6145 nb = dest.Y + (source.Bottom - source.Top) + 1;
6146
6147 if (nb < source.Top)
6148 {
6149 COORD coord;
6150
6151 coord.X = 0;
6152 coord.Y = nb;
6153 clear_chars(coord, Columns * (source.Top - nb));
6154 }
6155}
6156
6157
6158/*
6159 * Set the cursor position
6160 */
6161 static void
6162gotoxy(
6163 unsigned x,
6164 unsigned y)
6165{
6166 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6167 return;
6168
6169 /* external cursor coords are 1-based; internal are 0-based */
6170 g_coord.X = x - 1;
6171 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006172
6173 if (!USE_VTP)
6174 SetConsoleCursorPosition(g_hConOut, g_coord);
6175 else
6176 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177}
6178
6179
6180/*
6181 * Set the current text attribute = (foreground | background)
6182 * See ../doc/os_win32.txt for the numbers.
6183 */
6184 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006185textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006187 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188
6189 SetConsoleTextAttribute(g_hConOut, wAttr);
6190}
6191
6192
6193 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006194textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006196 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006198 if (!USE_VTP)
6199 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6200 else
6201 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202}
6203
6204
6205 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006206textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006208 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006210 if (!USE_VTP)
6211 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6212 else
6213 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214}
6215
6216
6217/*
6218 * restore the default text attribute (whatever we started with)
6219 */
6220 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006221normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006223 if (!USE_VTP)
6224 textattr(g_attrDefault);
6225 else
6226 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227}
6228
6229
6230static WORD g_attrPreStandout = 0;
6231
6232/*
6233 * Make the text standout, by brightening it
6234 */
6235 static void
6236standout(void)
6237{
6238 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006239
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6241}
6242
6243
6244/*
6245 * Turn off standout mode
6246 */
6247 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006248standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249{
6250 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006252
6253 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254}
6255
6256
6257/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006258 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 */
6260 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006261mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262{
6263 char_u *p;
6264 int n;
6265
6266 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6267 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006268 if (
6269#ifdef FEAT_TERMGUICOLORS
6270 !p_tgc &&
6271#endif
6272 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 {
6274 p = T_ME + 2;
6275 n = getdigits(&p);
6276 if (*p == 'm' && n > 0)
6277 {
6278 cterm_normal_fg_color = (n & 0xf) + 1;
6279 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6280 }
6281 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006282#ifdef FEAT_TERMGUICOLORS
6283 cterm_normal_fg_gui_color = INVALCOLOR;
6284 cterm_normal_bg_gui_color = INVALCOLOR;
6285#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286}
6287
6288
6289/*
6290 * visual bell: flash the screen
6291 */
6292 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006293visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294{
6295 COORD coordOrigin = {0, 0};
6296 WORD attrFlash = ~g_attrCurrent & 0xff;
6297
6298 DWORD dwDummy;
6299 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6300
6301 if (oldattrs == NULL)
6302 return;
6303 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6304 coordOrigin, &dwDummy);
6305 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6306 coordOrigin, &dwDummy);
6307
6308 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006309 if (!USE_VTP)
6310 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 coordOrigin, &dwDummy);
6312 vim_free(oldattrs);
6313}
6314
6315
6316/*
6317 * Make the cursor visible or invisible
6318 */
6319 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006320cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321{
6322 s_cursor_visible = fVisible;
6323#ifdef MCH_CURSOR_SHAPE
6324 mch_update_cursor();
6325#endif
6326}
6327
6328
6329/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006330 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006331 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006333 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006335 char_u *pchBuf,
6336 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337{
6338 COORD coord = g_coord;
6339 DWORD written;
6340
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006341#ifdef FEAT_MBYTE
6342 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6343 {
6344 static WCHAR *unicodebuf = NULL;
6345 static int unibuflen = 0;
6346 int length;
6347 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006349 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6350 if (unicodebuf == NULL || length > unibuflen)
6351 {
6352 vim_free(unicodebuf);
6353 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6354 unibuflen = length;
6355 }
6356 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6357 unicodebuf, unibuflen);
6358
6359 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006360
6361 if (!USE_VTP)
6362 {
6363 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6364 coord, &written);
6365 /* When writing fails or didn't write a single character, pretend one
6366 * character was written, otherwise we get stuck. */
6367 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6368 coord, &cchwritten) == 0
6369 || cchwritten == 0)
6370 cchwritten = 1;
6371 }
6372 else
6373 {
6374 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6375 NULL) == 0 || cchwritten == 0)
6376 cchwritten = 1;
6377 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006378
6379 if (cchwritten == length)
6380 {
6381 written = cbToWrite;
6382 g_coord.X += (SHORT)cells;
6383 }
6384 else
6385 {
6386 char_u *p = pchBuf;
6387 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006388 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006389 written = p - pchBuf;
6390 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6391 }
6392 }
6393 else
6394#endif
6395 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006396 if (!USE_VTP)
6397 {
6398 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6399 coord, &written);
6400 /* When writing fails or didn't write a single character, pretend one
6401 * character was written, otherwise we get stuck. */
6402 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6403 coord, &written) == 0
6404 || written == 0)
6405 written = 1;
6406 }
6407 else
6408 {
6409 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6410 NULL) == 0 || written == 0)
6411 written = 1;
6412 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006413
6414 g_coord.X += (SHORT) written;
6415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416
6417 while (g_coord.X > g_srScrollRegion.Right)
6418 {
6419 g_coord.X -= (SHORT) Columns;
6420 if (g_coord.Y < g_srScrollRegion.Bottom)
6421 g_coord.Y++;
6422 }
6423
6424 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6425
6426 return written;
6427}
6428
6429
6430/*
6431 * mch_write(): write the output buffer to the screen, translating ESC
6432 * sequences into calls to console output routines.
6433 */
6434 void
6435mch_write(
6436 char_u *s,
6437 int len)
6438{
6439 s[len] = NUL;
6440
6441 if (!term_console)
6442 {
6443 write(1, s, (unsigned)len);
6444 return;
6445 }
6446
6447 /* translate ESC | sequences into faked bios calls */
6448 while (len--)
6449 {
6450 /* optimization: use one single write_chars for runs of text,
6451 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006452 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453
6454 if (p_wd)
6455 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006456 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457 if (prefix != 0)
6458 prefix = 1;
6459 }
6460
6461 if (prefix != 0)
6462 {
6463 DWORD nWritten;
6464
6465 nWritten = write_chars(s, prefix);
6466#ifdef MCH_WRITE_DUMP
6467 if (fdDump)
6468 {
6469 fputc('>', fdDump);
6470 fwrite(s, sizeof(char_u), nWritten, fdDump);
6471 fputs("<\n", fdDump);
6472 }
6473#endif
6474 len -= (nWritten - 1);
6475 s += nWritten;
6476 }
6477 else if (s[0] == '\n')
6478 {
6479 /* \n, newline: go to the beginning of the next line or scroll */
6480 if (g_coord.Y == g_srScrollRegion.Bottom)
6481 {
6482 scroll(1);
6483 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6484 }
6485 else
6486 {
6487 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6488 }
6489#ifdef MCH_WRITE_DUMP
6490 if (fdDump)
6491 fputs("\\n\n", fdDump);
6492#endif
6493 s++;
6494 }
6495 else if (s[0] == '\r')
6496 {
6497 /* \r, carriage return: go to beginning of line */
6498 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6499#ifdef MCH_WRITE_DUMP
6500 if (fdDump)
6501 fputs("\\r\n", fdDump);
6502#endif
6503 s++;
6504 }
6505 else if (s[0] == '\b')
6506 {
6507 /* \b, backspace: move cursor one position left */
6508 if (g_coord.X > g_srScrollRegion.Left)
6509 g_coord.X--;
6510 else if (g_coord.Y > g_srScrollRegion.Top)
6511 {
6512 g_coord.X = g_srScrollRegion.Right;
6513 g_coord.Y--;
6514 }
6515 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6516#ifdef MCH_WRITE_DUMP
6517 if (fdDump)
6518 fputs("\\b\n", fdDump);
6519#endif
6520 s++;
6521 }
6522 else if (s[0] == '\a')
6523 {
6524 /* \a, bell */
6525 MessageBeep(0xFFFFFFFF);
6526#ifdef MCH_WRITE_DUMP
6527 if (fdDump)
6528 fputs("\\a\n", fdDump);
6529#endif
6530 s++;
6531 }
6532 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6533 {
6534#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006535 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006537 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006538 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539
6540 switch (s[2])
6541 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 case '0': case '1': case '2': case '3': case '4':
6543 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006544 p = s + 1;
6545 do
6546 {
6547 ++p;
6548 args[argc] = getdigits(&p);
6549 argc += (argc < 15) ? 1 : 0;
6550 if (p > s + len)
6551 break;
6552 } while (*p == ';');
6553
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 if (p > s + len)
6555 break;
6556
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006557 arg1 = args[0];
6558 arg2 = args[1];
6559 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006561 if (argc == 1 && args[0] == 0)
6562 normvideo();
6563 else if (argc == 1)
6564 {
6565 if (USE_VTP)
6566 textcolor((WORD) arg1);
6567 else
6568 textattr((WORD) arg1);
6569 }
6570 else if (USE_VTP)
6571 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006573 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006575 gotoxy(arg2, arg1);
6576 }
6577 else if (argc == 2 && *p == 'r')
6578 {
6579 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6580 }
6581 else if (argc == 1 && *p == 'A')
6582 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 gotoxy(g_coord.X + 1,
6584 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6585 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006586 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 {
6588 textbackground((WORD) arg1);
6589 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006590 else if (argc == 1 && *p == 'C')
6591 {
6592 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6593 g_coord.Y + 1);
6594 }
6595 else if (argc == 1 && *p == 'f')
6596 {
6597 textcolor((WORD) arg1);
6598 }
6599 else if (argc == 1 && *p == 'H')
6600 {
6601 gotoxy(1, arg1);
6602 }
6603 else if (argc == 1 && *p == 'L')
6604 {
6605 insert_lines(arg1);
6606 }
6607 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 {
6609 delete_lines(arg1);
6610 }
6611
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006612 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 s = p + 1;
6614 break;
6615
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 gotoxy(g_coord.X + 1,
6618 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6619 goto got3;
6620
6621 case 'B':
6622 visual_bell();
6623 goto got3;
6624
6625 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6627 g_coord.Y + 1);
6628 goto got3;
6629
6630 case 'E':
6631 termcap_mode_end();
6632 goto got3;
6633
6634 case 'F':
6635 standout();
6636 goto got3;
6637
6638 case 'f':
6639 standend();
6640 goto got3;
6641
6642 case 'H':
6643 gotoxy(1, 1);
6644 goto got3;
6645
6646 case 'j':
6647 clear_to_end_of_display();
6648 goto got3;
6649
6650 case 'J':
6651 clear_screen();
6652 goto got3;
6653
6654 case 'K':
6655 clear_to_end_of_line();
6656 goto got3;
6657
6658 case 'L':
6659 insert_lines(1);
6660 goto got3;
6661
6662 case 'M':
6663 delete_lines(1);
6664 goto got3;
6665
6666 case 'S':
6667 termcap_mode_start();
6668 goto got3;
6669
6670 case 'V':
6671 cursor_visible(TRUE);
6672 goto got3;
6673
6674 case 'v':
6675 cursor_visible(FALSE);
6676 goto got3;
6677
6678 got3:
6679 s += 3;
6680 len -= 2;
6681 }
6682
6683#ifdef MCH_WRITE_DUMP
6684 if (fdDump)
6685 {
6686 fputs("ESC | ", fdDump);
6687 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6688 fputc('\n', fdDump);
6689 }
6690#endif
6691 }
6692 else
6693 {
6694 /* Write a single character */
6695 DWORD nWritten;
6696
6697 nWritten = write_chars(s, 1);
6698#ifdef MCH_WRITE_DUMP
6699 if (fdDump)
6700 {
6701 fputc('>', fdDump);
6702 fwrite(s, sizeof(char_u), nWritten, fdDump);
6703 fputs("<\n", fdDump);
6704 }
6705#endif
6706
6707 len -= (nWritten - 1);
6708 s += nWritten;
6709 }
6710 }
6711
6712#ifdef MCH_WRITE_DUMP
6713 if (fdDump)
6714 fflush(fdDump);
6715#endif
6716}
6717
6718#endif /* FEAT_GUI_W32 */
6719
6720
6721/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006722 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 */
6724 void
6725mch_delay(
6726 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006727 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728{
6729#ifdef FEAT_GUI_W32
6730 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006731#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006733# ifdef FEAT_MZSCHEME
6734 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6735 {
6736 int towait = p_mzq;
6737
6738 /* if msec is large enough, wait by portions in p_mzq */
6739 while (msec > 0)
6740 {
6741 mzvim_check_threads();
6742 if (msec < towait)
6743 towait = msec;
6744 Sleep(towait);
6745 msec -= towait;
6746 }
6747 }
6748 else
6749# endif
6750 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006752 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753#endif
6754}
6755
6756
6757/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006758 * This version of remove is not scared by a readonly (backup) file.
6759 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 * Return 0 for success, -1 for failure.
6761 */
6762 int
6763mch_remove(char_u *name)
6764{
6765#ifdef FEAT_MBYTE
6766 WCHAR *wn = NULL;
6767 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006768#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769
Bram Moolenaar203258c2016-01-17 22:15:16 +01006770 /*
6771 * On Windows, deleting a directory's symbolic link is done by
6772 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6773 */
6774 if (mch_isdir(name) && mch_is_symbolic_link(name))
6775 return mch_rmdir(name);
6776
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006777 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6778
6779#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6781 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006782 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 if (wn != NULL)
6784 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 n = DeleteFileW(wn) ? 0 : -1;
6786 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006787 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788 }
6789 }
6790#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006791 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792}
6793
6794
6795/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006796 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 */
6798 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006799mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800{
6801#ifndef FEAT_GUI_W32 /* never used */
6802 if (g_fCtrlCPressed || g_fCBrkPressed)
6803 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006804 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6806 got_int = TRUE;
6807 }
6808#endif
6809}
6810
Bram Moolenaaree273972016-01-02 21:11:51 +01006811/* physical RAM to leave for the OS */
6812#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006813
6814/*
6815 * How much main memory in KiB that can be used by VIM.
6816 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006817 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006818mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006819{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006820 MEMORYSTATUSEX ms;
6821
Bram Moolenaaree273972016-01-02 21:11:51 +01006822 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006823 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6824 * what fits in 32 bits. But it's not always available. */
6825 ms.dwLength = sizeof(MEMORYSTATUSEX);
6826 GlobalMemoryStatusEx(&ms);
6827 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006828 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006829 /* Process address space fits in physical RAM, use all of it. */
6830 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006831 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006832 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006833 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006834 /* Catch old NT box or perverse hardware setup. */
6835 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006836 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006837 /* Use physical RAM less reserve for OS + data. */
6838 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006839}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841#ifdef FEAT_MBYTE
6842/*
6843 * Same code as below, but with wide functions and no comments.
6844 * Return 0 for success, non-zero for failure.
6845 */
6846 int
6847mch_wrename(WCHAR *wold, WCHAR *wnew)
6848{
6849 WCHAR *p;
6850 int i;
6851 WCHAR szTempFile[_MAX_PATH + 1];
6852 WCHAR szNewPath[_MAX_PATH + 1];
6853 HANDLE hf;
6854
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006855 p = wold;
6856 for (i = 0; wold[i] != NUL; ++i)
6857 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6858 && wold[i + 1] != 0)
6859 p = wold + i + 1;
6860 if ((int)(wold + i - p) < 8 || p[6] != '~')
6861 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862
6863 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6864 return -1;
6865 *p = NUL;
6866
6867 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6868 return -2;
6869
6870 if (!DeleteFileW(szTempFile))
6871 return -3;
6872
6873 if (!MoveFileW(wold, szTempFile))
6874 return -4;
6875
6876 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6877 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6878 return -5;
6879 if (!CloseHandle(hf))
6880 return -6;
6881
6882 if (!MoveFileW(szTempFile, wnew))
6883 {
6884 (void)MoveFileW(szTempFile, wold);
6885 return -7;
6886 }
6887
6888 DeleteFileW(szTempFile);
6889
6890 if (!DeleteFileW(wold))
6891 return -8;
6892
6893 return 0;
6894}
6895#endif
6896
6897
6898/*
6899 * mch_rename() works around a bug in rename (aka MoveFile) in
6900 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6901 * file whose short file name is "FOO.BAR" (its long file name will
6902 * be correct: "foo.bar~"). Because a file can be accessed by
6903 * either its SFN or its LFN, "foo.bar" has effectively been
6904 * renamed to "foo.bar", which is not at all what was wanted. This
6905 * seems to happen only when renaming files with three-character
6906 * extensions by appending a suffix that does not include ".".
6907 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6908 *
6909 * There is another problem, which isn't really a bug but isn't right either:
6910 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6911 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6912 * service pack 6. Doesn't seem to happen on Windows 98.
6913 *
6914 * Like rename(), returns 0 upon success, non-zero upon failure.
6915 * Should probably set errno appropriately when errors occur.
6916 */
6917 int
6918mch_rename(
6919 const char *pszOldFile,
6920 const char *pszNewFile)
6921{
6922 char szTempFile[_MAX_PATH+1];
6923 char szNewPath[_MAX_PATH+1];
6924 char *pszFilePart;
6925 HANDLE hf;
6926#ifdef FEAT_MBYTE
6927 WCHAR *wold = NULL;
6928 WCHAR *wnew = NULL;
6929 int retval = -1;
6930
6931 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6932 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006933 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6934 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 if (wold != NULL && wnew != NULL)
6936 retval = mch_wrename(wold, wnew);
6937 vim_free(wold);
6938 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006939 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 }
6941#endif
6942
6943 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006944 * No need to play tricks unless the file name contains a "~" as the
6945 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006947 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6948 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6949 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950
6951 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6952 * a directory, no error is returned and pszFilePart will be NULL. */
6953 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6954 || pszFilePart == NULL)
6955 return -1;
6956 *pszFilePart = NUL;
6957
6958 /* Get (and create) a unique temporary file name in directory of new file */
6959 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6960 return -2;
6961
6962 /* blow the temp file away */
6963 if (!DeleteFile(szTempFile))
6964 return -3;
6965
6966 /* rename old file to the temp file */
6967 if (!MoveFile(pszOldFile, szTempFile))
6968 return -4;
6969
6970 /* now create an empty file called pszOldFile; this prevents the operating
6971 * system using pszOldFile as an alias (SFN) if we're renaming within the
6972 * same directory. For example, we're editing a file called
6973 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6974 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6975 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006976 * cause all sorts of problems later in buf_write(). So, we create an
6977 * empty file called filena~1.txt and the system will have to find some
6978 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 */
6980 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6981 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6982 return -5;
6983 if (!CloseHandle(hf))
6984 return -6;
6985
6986 /* rename the temp file to the new file */
6987 if (!MoveFile(szTempFile, pszNewFile))
6988 {
6989 /* Renaming failed. Rename the file back to its old name, so that it
6990 * looks like nothing happened. */
6991 (void)MoveFile(szTempFile, pszOldFile);
6992
6993 return -7;
6994 }
6995
6996 /* Seems to be left around on Novell filesystems */
6997 DeleteFile(szTempFile);
6998
6999 /* finally, remove the empty old file */
7000 if (!DeleteFile(pszOldFile))
7001 return -8;
7002
7003 return 0; /* success */
7004}
7005
7006/*
7007 * Get the default shell for the current hardware platform
7008 */
7009 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007010default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 PlatformId();
7013
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007014 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015}
7016
7017/*
7018 * mch_access() extends access() to do more detailed check on network drives.
7019 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7020 */
7021 int
7022mch_access(char *n, int p)
7023{
7024 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 int retval = -1; /* default: fail */
7026#ifdef FEAT_MBYTE
7027 WCHAR *wn = NULL;
7028
7029 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007030 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031#endif
7032
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007033 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034 {
7035 char TempName[_MAX_PATH + 16] = "";
7036#ifdef FEAT_MBYTE
7037 WCHAR TempNameW[_MAX_PATH + 16] = L"";
7038#endif
7039
7040 if (p & R_OK)
7041 {
7042 /* Read check is performed by seeing if we can do a find file on
7043 * the directory for any file. */
7044#ifdef FEAT_MBYTE
7045 if (wn != NULL)
7046 {
7047 int i;
7048 WIN32_FIND_DATAW d;
7049
7050 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7051 TempNameW[i] = wn[i];
7052 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7053 TempNameW[i++] = '\\';
7054 TempNameW[i++] = '*';
7055 TempNameW[i++] = 0;
7056
7057 hFile = FindFirstFileW(TempNameW, &d);
7058 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007059 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 else
7061 (void)FindClose(hFile);
7062 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064#endif
7065 {
7066 char *pch;
7067 WIN32_FIND_DATA d;
7068
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007069 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 pch = TempName + STRLEN(TempName) - 1;
7071 if (*pch != '\\' && *pch != '/')
7072 *++pch = '\\';
7073 *++pch = '*';
7074 *++pch = NUL;
7075
7076 hFile = FindFirstFile(TempName, &d);
7077 if (hFile == INVALID_HANDLE_VALUE)
7078 goto getout;
7079 (void)FindClose(hFile);
7080 }
7081 }
7082
7083 if (p & W_OK)
7084 {
7085 /* Trying to create a temporary file in the directory should catch
7086 * directories on read-only network shares. However, in
7087 * directories whose ACL allows writes but denies deletes will end
7088 * up keeping the temporary file :-(. */
7089#ifdef FEAT_MBYTE
7090 if (wn != NULL)
7091 {
7092 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007093 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 else
7095 DeleteFileW(TempNameW);
7096 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007097 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098#endif
7099 {
7100 if (!GetTempFileName(n, "VIM", 0, TempName))
7101 goto getout;
7102 mch_remove((char_u *)TempName);
7103 }
7104 }
7105 }
7106 else
7107 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007108 // Don't consider a file read-only if another process has opened it.
7109 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7110
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 /* Trying to open the file for the required access does ACL, read-only
7112 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007113 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7114 | ((p & R_OK) ? GENERIC_READ : 0);
7115
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116#ifdef FEAT_MBYTE
7117 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007118 hFile = CreateFileW(wn, access_mode, share_mode,
7119 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007120 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007122 hFile = CreateFile(n, access_mode, share_mode,
7123 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007124 if (hFile == INVALID_HANDLE_VALUE)
7125 goto getout;
7126 CloseHandle(hFile);
7127 }
7128
7129 retval = 0; /* success */
7130getout:
7131#ifdef FEAT_MBYTE
7132 vim_free(wn);
7133#endif
7134 return retval;
7135}
7136
7137#if defined(FEAT_MBYTE) || defined(PROTO)
7138/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007139 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 */
7141 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007142mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007143{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007144 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7145# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 WCHAR *wn;
7147 int f;
7148
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007149 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007151 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007152 if (wn != NULL)
7153 {
7154 f = _wopen(wn, flags, mode);
7155 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007156 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 }
7158 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007159# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007161 /* open() can open a file which name is longer than _MAX_PATH bytes
7162 * and shorter than _MAX_PATH characters successfully, but sometimes it
7163 * causes unexpected error in another part. We make it an error explicitly
7164 * here. */
7165 if (strlen(name) >= _MAX_PATH)
7166 return -1;
7167
Bram Moolenaar071d4272004-06-13 20:20:40 +00007168 return open(name, flags, mode);
7169}
7170
7171/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007172 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 */
7174 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007175mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176{
7177 WCHAR *wn, *wm;
7178 FILE *f = NULL;
7179
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007180 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007182# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007183 /* Work around an annoying assertion in the Microsoft debug CRT
7184 * when mode's text/binary setting doesn't match _get_fmode(). */
7185 char newMode = mode[strlen(mode) - 1];
7186 int oldMode = 0;
7187
7188 _get_fmode(&oldMode);
7189 if (newMode == 't')
7190 _set_fmode(_O_TEXT);
7191 else if (newMode == 'b')
7192 _set_fmode(_O_BINARY);
7193# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007194 wn = enc_to_utf16((char_u *)name, NULL);
7195 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 if (wn != NULL && wm != NULL)
7197 f = _wfopen(wn, wm);
7198 vim_free(wn);
7199 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007200
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007201# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007202 _set_fmode(oldMode);
7203# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007204 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 }
7206
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007207 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7208 * and shorter than _MAX_PATH characters successfully, but sometimes it
7209 * causes unexpected error in another part. We make it an error explicitly
7210 * here. */
7211 if (strlen(name) >= _MAX_PATH)
7212 return NULL;
7213
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 return fopen(name, mode);
7215}
7216#endif
7217
7218#ifdef FEAT_MBYTE
7219/*
7220 * SUB STREAM (aka info stream) handling:
7221 *
7222 * NTFS can have sub streams for each file. Normal contents of file is
7223 * stored in the main stream, and extra contents (author information and
7224 * title and so on) can be stored in sub stream. After Windows 2000, user
7225 * can access and store those informations in sub streams via explorer's
7226 * property menuitem in right click menu. Those informations in sub streams
7227 * were lost when copying only the main stream. So we have to copy sub
7228 * streams.
7229 *
7230 * Incomplete explanation:
7231 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7232 * More useful info and an example:
7233 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7234 */
7235
7236/*
7237 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7238 * and write to stream "substream" of file "to".
7239 * Errors are ignored.
7240 */
7241 static void
7242copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7243{
7244 HANDLE hTo;
7245 WCHAR *to_name;
7246
7247 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7248 wcscpy(to_name, to);
7249 wcscat(to_name, substream);
7250
7251 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7252 FILE_ATTRIBUTE_NORMAL, NULL);
7253 if (hTo != INVALID_HANDLE_VALUE)
7254 {
7255 long done;
7256 DWORD todo;
7257 DWORD readcnt, written;
7258 char buf[4096];
7259
7260 /* Copy block of bytes at a time. Abort when something goes wrong. */
7261 for (done = 0; done < len; done += written)
7262 {
7263 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007264 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7265 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7267 FALSE, FALSE, context)
7268 || readcnt != todo
7269 || !WriteFile(hTo, buf, todo, &written, NULL)
7270 || written != todo)
7271 break;
7272 }
7273 CloseHandle(hTo);
7274 }
7275
7276 free(to_name);
7277}
7278
7279/*
7280 * Copy info streams from file "from" to file "to".
7281 */
7282 static void
7283copy_infostreams(char_u *from, char_u *to)
7284{
7285 WCHAR *fromw;
7286 WCHAR *tow;
7287 HANDLE sh;
7288 WIN32_STREAM_ID sid;
7289 int headersize;
7290 WCHAR streamname[_MAX_PATH];
7291 DWORD readcount;
7292 void *context = NULL;
7293 DWORD lo, hi;
7294 int len;
7295
7296 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007297 fromw = enc_to_utf16(from, NULL);
7298 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 if (fromw != NULL && tow != NULL)
7300 {
7301 /* Open the file for reading. */
7302 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7303 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7304 if (sh != INVALID_HANDLE_VALUE)
7305 {
7306 /* Use BackupRead() to find the info streams. Repeat until we
7307 * have done them all.*/
7308 for (;;)
7309 {
7310 /* Get the header to find the length of the stream name. If
7311 * the "readcount" is zero we have done all info streams. */
7312 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007313 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7315 &readcount, FALSE, FALSE, &context)
7316 || readcount == 0)
7317 break;
7318
7319 /* We only deal with streams that have a name. The normal
7320 * file data appears to be without a name, even though docs
7321 * suggest it is called "::$DATA". */
7322 if (sid.dwStreamNameSize > 0)
7323 {
7324 /* Read the stream name. */
7325 if (!BackupRead(sh, (LPBYTE)streamname,
7326 sid.dwStreamNameSize,
7327 &readcount, FALSE, FALSE, &context))
7328 break;
7329
7330 /* Copy an info stream with a name ":anything:$DATA".
7331 * Skip "::$DATA", it has no stream name (examples suggest
7332 * it might be used for the normal file contents).
7333 * Note that BackupRead() counts bytes, but the name is in
7334 * wide characters. */
7335 len = readcount / sizeof(WCHAR);
7336 streamname[len] = 0;
7337 if (len > 7 && wcsicmp(streamname + len - 6,
7338 L":$DATA") == 0)
7339 {
7340 streamname[len - 6] = 0;
7341 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007342 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343 }
7344 }
7345
7346 /* Advance to the next stream. We might try seeking too far,
7347 * but BackupSeek() doesn't skip over stream borders, thus
7348 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007349 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 &lo, &hi, &context);
7351 }
7352
7353 /* Clear the context. */
7354 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7355
7356 CloseHandle(sh);
7357 }
7358 }
7359 vim_free(fromw);
7360 vim_free(tow);
7361}
7362#endif
7363
7364/*
7365 * Copy file attributes from file "from" to file "to".
7366 * For Windows NT and later we copy info streams.
7367 * Always returns zero, errors are ignored.
7368 */
7369 int
7370mch_copy_file_attribute(char_u *from, char_u *to)
7371{
7372#ifdef FEAT_MBYTE
7373 /* File streams only work on Windows NT and later. */
7374 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007375 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376#endif
7377 return 0;
7378}
7379
7380#if defined(MYRESETSTKOFLW) || defined(PROTO)
7381/*
7382 * Recreate a destroyed stack guard page in win32.
7383 * Written by Benjamin Peterson.
7384 */
7385
7386/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007387# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388
7389/*
7390 * This function does the same thing as _resetstkoflw(), which is only
7391 * available in DevStudio .net and later.
7392 * Returns 0 for failure, 1 for success.
7393 */
7394 int
7395myresetstkoflw(void)
7396{
7397 BYTE *pStackPtr;
7398 BYTE *pGuardPage;
7399 BYTE *pStackBase;
7400 BYTE *pLowestPossiblePage;
7401 MEMORY_BASIC_INFORMATION mbi;
7402 SYSTEM_INFO si;
7403 DWORD nPageSize;
7404 DWORD dummy;
7405
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407
7408 /* We need to know the system page size. */
7409 GetSystemInfo(&si);
7410 nPageSize = si.dwPageSize;
7411
7412 /* ...and the current stack pointer */
7413 pStackPtr = (BYTE*)_alloca(1);
7414
7415 /* ...and the base of the stack. */
7416 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7417 return 0;
7418 pStackBase = (BYTE*)mbi.AllocationBase;
7419
7420 /* ...and the page thats min_stack_req pages away from stack base; this is
7421 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007422 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007425 /* We want the first committed page in the stack Start at the stack
7426 * base and move forward through memory until we find a committed block.
7427 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 BYTE *pBlock = pStackBase;
7429
Bram Moolenaara466c992005-07-09 21:03:22 +00007430 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 {
7432 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7433 return 0;
7434
7435 pBlock += mbi.RegionSize;
7436
7437 if (mbi.State & MEM_COMMIT)
7438 break;
7439 }
7440
7441 /* mbi now describes the first committed block in the stack. */
7442 if (mbi.Protect & PAGE_GUARD)
7443 return 1;
7444
7445 /* decide where the guard page should start */
7446 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7447 pGuardPage = pLowestPossiblePage;
7448 else
7449 pGuardPage = (BYTE*)mbi.BaseAddress;
7450
7451 /* allocate the guard page */
7452 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7453 return 0;
7454
7455 /* apply the guard attribute to the page */
7456 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7457 &dummy))
7458 return 0;
7459 }
7460
7461 return 1;
7462}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007465
7466#if defined(FEAT_MBYTE) || defined(PROTO)
7467/*
7468 * The command line arguments in UCS2
7469 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007470static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007471static LPWSTR *ArglistW = NULL;
7472static int global_argc = 0;
7473static char **global_argv;
7474
7475static int used_file_argc = 0; /* last argument in global_argv[] used
7476 for the argument list. */
7477static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7478 command line arguments added to
7479 the argument list */
7480static int used_file_count = 0; /* nr of entries in used_file_indexes */
7481static int used_file_literal = FALSE; /* take file names literally */
7482static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007483static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007484static int used_alist_count = 0;
7485
7486
7487/*
7488 * Get the command line arguments. Unicode version.
7489 * Returns argc. Zero when something fails.
7490 */
7491 int
7492get_cmd_argsW(char ***argvp)
7493{
7494 char **argv = NULL;
7495 int argc = 0;
7496 int i;
7497
Bram Moolenaar14993322014-09-09 12:25:33 +02007498 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007499 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7500 if (ArglistW != NULL)
7501 {
7502 argv = malloc((nArgsW + 1) * sizeof(char *));
7503 if (argv != NULL)
7504 {
7505 argc = nArgsW;
7506 argv[argc] = NULL;
7507 for (i = 0; i < argc; ++i)
7508 {
7509 int len;
7510
7511 /* Convert each Unicode argument to the current codepage. */
7512 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007513 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007514 (LPSTR *)&argv[i], &len, 0, 0);
7515 if (argv[i] == NULL)
7516 {
7517 /* Out of memory, clear everything. */
7518 while (i > 0)
7519 free(argv[--i]);
7520 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007521 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007522 argc = 0;
7523 }
7524 }
7525 }
7526 }
7527
7528 global_argc = argc;
7529 global_argv = argv;
7530 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007531 {
7532 if (used_file_indexes != NULL)
7533 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007534 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007535 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007536
7537 if (argvp != NULL)
7538 *argvp = argv;
7539 return argc;
7540}
7541
7542 void
7543free_cmd_argsW(void)
7544{
7545 if (ArglistW != NULL)
7546 {
7547 GlobalFree(ArglistW);
7548 ArglistW = NULL;
7549 }
7550}
7551
7552/*
7553 * Remember "name" is an argument that was added to the argument list.
7554 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7555 * is called.
7556 */
7557 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007558used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007559{
7560 int i;
7561
7562 if (used_file_indexes == NULL)
7563 return;
7564 for (i = used_file_argc + 1; i < global_argc; ++i)
7565 if (STRCMP(global_argv[i], name) == 0)
7566 {
7567 used_file_argc = i;
7568 used_file_indexes[used_file_count++] = i;
7569 break;
7570 }
7571 used_file_literal = literal;
7572 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007573 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007574}
7575
7576/*
7577 * Remember the length of the argument list as it was. If it changes then we
7578 * leave it alone when 'encoding' is set.
7579 */
7580 void
7581set_alist_count(void)
7582{
7583 used_alist_count = GARGCOUNT;
7584}
7585
7586/*
7587 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7588 * has been changed while starting up. Use the UCS-2 command line arguments
7589 * and convert them to 'encoding'.
7590 */
7591 void
7592fix_arg_enc(void)
7593{
7594 int i;
7595 int idx;
7596 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007597 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007598
7599 /* Safety checks:
7600 * - if argument count differs between the wide and non-wide argument
7601 * list, something must be wrong.
7602 * - the file name arguments must have been located.
7603 * - the length of the argument list wasn't changed by the user.
7604 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007605 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007606 || ArglistW == NULL
7607 || used_file_indexes == NULL
7608 || used_file_count == 0
7609 || used_alist_count != GARGCOUNT)
7610 return;
7611
Bram Moolenaar86b68352004-12-27 21:59:20 +00007612 /* Remember the buffer numbers for the arguments. */
7613 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7614 if (fnum_list == NULL)
7615 return; /* out of memory */
7616 for (i = 0; i < GARGCOUNT; ++i)
7617 fnum_list[i] = GARGLIST[i].ae_fnum;
7618
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007619 /* Clear the argument list. Make room for the new arguments. */
7620 alist_clear(&global_alist);
7621 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007622 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007623
7624 for (i = 0; i < used_file_count; ++i)
7625 {
7626 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007627 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007628 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007629 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007630 int literal = used_file_literal;
7631
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007632# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007633 /* When using diff mode may need to concatenate file name to
7634 * directory name. Just like it's done in main(). */
7635 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7636 && !mch_isdir(alist_name(&GARGLIST[0])))
7637 {
7638 char_u *r;
7639
7640 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7641 if (r != NULL)
7642 {
7643 vim_free(str);
7644 str = r;
7645 }
7646 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007647# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007648 /* Re-use the old buffer by renaming it. When not using literal
7649 * names it's done by alist_expand() below. */
7650 if (used_file_literal)
7651 buf_set_name(fnum_list[i], str);
7652
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007653 /* Check backtick literal. backtick literal is already expanded in
7654 * main.c, so this part add str as literal. */
7655 if (literal == FALSE)
7656 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007657 size_t len = STRLEN(str);
7658
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007659 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7660 literal = TRUE;
7661 }
7662 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007663 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007664 }
7665
7666 if (!used_file_literal)
7667 {
7668 /* Now expand wildcards in the arguments. */
7669 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7670 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007671 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7672 * Also, unset wildignore to not be influenced by this option.
7673 * The arguments specified in command-line should be kept even if
7674 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007675 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007676 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007677 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007678 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007679 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007680 }
7681
7682 /* If wildcard expansion failed, we are editing the first file of the
7683 * arglist and there is no file name: Edit the first argument now. */
7684 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7685 {
7686 do_cmdline_cmd((char_u *)":rewind");
7687 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007688 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007689 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007690
7691 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007692}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007694
7695 int
7696mch_setenv(char *var, char *value, int x)
7697{
7698 char_u *envbuf;
7699
7700 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7701 if (envbuf == NULL)
7702 return -1;
7703
7704 sprintf((char *)envbuf, "%s=%s", var, value);
7705
7706#ifdef FEAT_MBYTE
7707 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7708 {
7709 WCHAR *p = enc_to_utf16(envbuf, NULL);
7710
7711 vim_free(envbuf);
7712 if (p == NULL)
7713 return -1;
7714 _wputenv(p);
7715# ifdef libintl_wputenv
7716 libintl_wputenv(p);
7717# endif
7718 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7719 vim_free(p);
7720 }
7721 else
7722#endif
7723 {
7724 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007725#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007726 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007727#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007728 /* Unlike Un*x systems, we can free the string for _putenv(). */
7729 vim_free(envbuf);
7730 }
7731
7732 return 0;
7733}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007734
7735#ifndef FEAT_GUI_W32
7736
7737/*
7738 * Support for 256 colors and 24-bit colors was added in Windows 10
7739 * version 1703 (Creators update).
7740 */
7741# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7742
7743 static void
7744vtp_init(void)
7745{
7746 DWORD ver, mode;
7747 HMODULE hKerneldll;
7748 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007749# ifdef FEAT_TERMGUICOLORS
7750 COLORREF fg, bg;
7751# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007752
7753 ver = get_build_number();
7754 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7755 GetConsoleMode(g_hConOut, &mode);
7756 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7757 if (SetConsoleMode(g_hConOut, mode) == 0)
7758 vtp_working = 0;
7759
7760 /* Use functions supported from Vista */
7761 hKerneldll = GetModuleHandle("kernel32.dll");
7762 if (hKerneldll != NULL)
7763 {
7764 pGetConsoleScreenBufferInfoEx =
7765 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7766 hKerneldll, "GetConsoleScreenBufferInfoEx");
7767 pSetConsoleScreenBufferInfoEx =
7768 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7769 hKerneldll, "SetConsoleScreenBufferInfoEx");
7770 if (pGetConsoleScreenBufferInfoEx != NULL
7771 && pSetConsoleScreenBufferInfoEx != NULL)
7772 has_csbiex = TRUE;
7773 }
7774
7775 csbi.cbSize = sizeof(csbi);
7776 if (has_csbiex)
7777 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007778 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7779 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7780
7781# ifdef FEAT_TERMGUICOLORS
7782 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7783 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7784 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7785 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7786 default_console_color_bg = bg;
7787 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007788# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007789
7790 set_console_color_rgb();
7791}
7792
7793 static void
7794vtp_exit(void)
7795{
7796 reset_console_color_rgb();
7797}
7798
7799 static int
7800vtp_printf(
7801 char *format,
7802 ...)
7803{
7804 char_u buf[100];
7805 va_list list;
7806 DWORD result;
7807
7808 va_start(list, format);
7809 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7810 va_end(list);
7811 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7812 return (int)result;
7813}
7814
7815 static void
7816vtp_sgr_bulk(
7817 int arg)
7818{
7819 int args[1];
7820
7821 args[0] = arg;
7822 vtp_sgr_bulks(1, args);
7823}
7824
7825 static void
7826vtp_sgr_bulks(
7827 int argc,
7828 int *args
7829)
7830{
7831 /* 2('\033[') + 4('255.') * 16 + NUL */
7832 char_u buf[2 + (4 * 16) + 1];
7833 char_u *p;
7834 int i;
7835
7836 p = buf;
7837 *p++ = '\033';
7838 *p++ = '[';
7839
7840 for (i = 0; i < argc; ++i)
7841 {
7842 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7843 *p++ = ';';
7844 }
7845 p--;
7846 *p++ = 'm';
7847 *p = NUL;
7848 vtp_printf((char *)buf);
7849}
7850
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007851# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007852 static int
7853ctermtoxterm(
7854 int cterm)
7855{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007856 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007857
7858 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7859 return (((int)r << 16) | ((int)g << 8) | (int)b);
7860}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007861# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007862
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007863 static void
7864set_console_color_rgb(void)
7865{
7866# ifdef FEAT_TERMGUICOLORS
7867 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7868 int id;
7869 guicolor_T fg = INVALCOLOR;
7870 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007871 int ctermfg;
7872 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007873
7874 if (!USE_VTP)
7875 return;
7876
7877 id = syn_name2id((char_u *)"Normal");
7878 if (id > 0)
7879 syn_id2colors(id, &fg, &bg);
7880 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007881 {
7882 ctermfg = -1;
7883 if (id > 0)
7884 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007885 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7886 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007887 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007888 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007889 {
7890 ctermbg = -1;
7891 if (id > 0)
7892 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007893 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7894 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007895 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007896 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7897 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7898
7899 csbi.cbSize = sizeof(csbi);
7900 if (has_csbiex)
7901 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7902
7903 csbi.cbSize = sizeof(csbi);
7904 csbi.srWindow.Right += 1;
7905 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007906 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7907 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007908 if (has_csbiex)
7909 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7910# endif
7911}
7912
7913 static void
7914reset_console_color_rgb(void)
7915{
7916# ifdef FEAT_TERMGUICOLORS
7917 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7918
7919 csbi.cbSize = sizeof(csbi);
7920 if (has_csbiex)
7921 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7922
7923 csbi.cbSize = sizeof(csbi);
7924 csbi.srWindow.Right += 1;
7925 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007926 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7927 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007928 if (has_csbiex)
7929 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7930# endif
7931}
7932
7933 void
7934control_console_color_rgb(void)
7935{
7936 if (USE_VTP)
7937 set_console_color_rgb();
7938 else
7939 reset_console_color_rgb();
7940}
7941
7942 int
7943has_vtp_working(void)
7944{
7945 return vtp_working;
7946}
7947
7948 int
7949use_vtp(void)
7950{
7951 return USE_VTP;
7952}
7953
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007954 int
7955is_term_win32(void)
7956{
7957 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7958}
7959
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007960#endif