blob: c9f7d1cb8a9ddd83ee2d5416a578bdf43dae4e72 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void delete_lines(unsigned cLines);
175static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static int s_cursor_visible = TRUE;
178static int did_create_conin = FALSE;
179#else
180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100190static int vtp_working = 0;
191static void vtp_init();
192static void vtp_exit();
193static int vtp_printf(char *format, ...);
194static void vtp_sgr_bulk(int arg);
195static void vtp_sgr_bulks(int argc, int *argv);
196
197static guicolor_T save_console_bg_rgb;
198static guicolor_T save_console_fg_rgb;
199
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int g_color_index_bg = 0;
201static int g_color_index_fg = 7;
202
203# ifdef FEAT_TERMGUICOLORS
204static int default_console_color_bg = 0x000000; // black
205static int default_console_color_fg = 0xc0c0c0; // white
206# endif
207
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100208# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200209# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100210# else
211# define USE_VTP 0
212# endif
213
214static void set_console_color_rgb(void);
215static void reset_console_color_rgb(void);
216#endif
217
218/* This flag is newly created from Windows 10 */
219#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
220# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
221#endif
222
223#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static int suppress_winsize = 1; /* don't fiddle with console */
225#endif
226
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227static char_u *exe_path = NULL;
228
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229static BOOL win8_or_later = FALSE;
230
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100231#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232/* Dynamic loading for portability */
233typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
234{
235 ULONG cbSize;
236 COORD dwSize;
237 COORD dwCursorPosition;
238 WORD wAttributes;
239 SMALL_RECT srWindow;
240 COORD dwMaximumWindowSize;
241 WORD wPopupAttributes;
242 BOOL bFullscreenSupported;
243 COLORREF ColorTable[16];
244} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
245typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
246static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
247typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
248static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
249static BOOL has_csbiex = FALSE;
250
251/*
252 * Get version number including build number
253 */
254typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
255# define MAKE_VER(major, minor, build) \
256 (((major) << 24) | ((minor) << 16) | (build))
257
258 static DWORD
259get_build_number(void)
260{
261 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
262 HMODULE hNtdll;
263 PfnRtlGetVersion pRtlGetVersion;
264 DWORD ver = MAKE_VER(0, 0, 0);
265
266 hNtdll = GetModuleHandle("ntdll.dll");
267 if (hNtdll != NULL)
268 {
269 pRtlGetVersion =
270 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
271 pRtlGetVersion(&osver);
272 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
273 min(osver.dwMinorVersion, 255),
274 min(osver.dwBuildNumber, 32767));
275 }
276 return ver;
277}
278
279
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280/*
281 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100283 */
284 static BOOL
285read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 HANDLE hInput,
287 INPUT_RECORD *lpBuffer,
288 DWORD nLength,
289 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100290{
291 enum
292 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100293 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296 static DWORD s_dwIndex = 0;
297 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100299 int head;
300 int tail;
301 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 if (nLength == -2)
304 return (s_dwMax > 0) ? TRUE : FALSE;
305
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100306 if (!win8_or_later)
307 {
308 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200309 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
310 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 }
312
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 if (s_dwMax == 0)
314 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200316 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
317 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 s_dwIndex = 0;
320 s_dwMax = dwEvents;
321 if (dwEvents == 0)
322 {
323 *lpEvents = 0;
324 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100326
327 if (s_dwMax > 1)
328 {
329 head = 0;
330 tail = s_dwMax - 1;
331 while (head != tail)
332 {
333 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
334 && s_irCache[head + 1].EventType
335 == WINDOW_BUFFER_SIZE_EVENT)
336 {
337 /* Remove duplicate event to avoid flicker. */
338 for (i = head; i < tail; ++i)
339 s_irCache[i] = s_irCache[i + 1];
340 --tail;
341 continue;
342 }
343 head++;
344 }
345 s_dwMax = tail + 1;
346 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100348
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100349 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100352 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 return TRUE;
354}
355
356/*
357 * Version of PeekConsoleInput() that works with IME.
358 */
359 static BOOL
360peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 HANDLE hInput,
362 INPUT_RECORD *lpBuffer,
363 DWORD nLength,
364 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100365{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367}
368
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100369# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200370 static DWORD
371msg_wait_for_multiple_objects(
372 DWORD nCount,
373 LPHANDLE pHandles,
374 BOOL fWaitAll,
375 DWORD dwMilliseconds,
376 DWORD dwWakeMask)
377{
378 if (read_console_input(NULL, NULL, -2, NULL))
379 return WAIT_OBJECT_0;
380 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
381 dwMilliseconds, dwWakeMask);
382}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100383# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387wait_for_single_object(
388 HANDLE hHandle,
389 DWORD dwMilliseconds)
390{
391 if (read_console_input(NULL, NULL, -2, NULL))
392 return WAIT_OBJECT_0;
393 return WaitForSingleObject(hHandle, dwMilliseconds);
394}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100395# endif
396#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200397
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 static void
399get_exe_name(void)
400{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100401 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
402 * as the maximum length that works (plus a NUL byte). */
403#define MAX_ENV_PATH_LEN 8192
404 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406
407 if (exe_name == NULL)
408 {
409 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (*temp != NUL)
412 exe_name = FullName_save((char_u *)temp, FALSE);
413 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000414
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200415 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000416 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200417 exe_path = vim_strnsave(exe_name,
418 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 /* Append our starting directory to $PATH, so that when doing
422 * "!xxd" it's found in our starting directory. Needed because
423 * SearchPath() also looks there. */
424 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100425 if (p == NULL
426 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100428 if (p == NULL || *p == NUL)
429 temp[0] = NUL;
430 else
431 {
432 STRCPY(temp, p);
433 STRCAT(temp, ";");
434 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100436 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000438 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440}
441
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100443 * Unescape characters in "p" that appear in "escaped".
444 */
445 static void
446unescape_shellxquote(char_u *p, char_u *escaped)
447{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100448 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100449 int n;
450
451 while (*p != NUL)
452 {
453 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
454 mch_memmove(p, p + 1, l--);
455#ifdef FEAT_MBYTE
456 n = (*mb_ptr2len)(p);
457#else
458 n = 1;
459#endif
460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100495#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
496/*
497 * Get related information about 'funcname' which is imported by 'hInst'.
498 * If 'info' is 0, return the function address.
499 * If 'info' is 1, return the module name which the function is imported from.
500 */
501 static void *
502get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
503{
504 PBYTE pImage = (PBYTE)hInst;
505 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
506 PIMAGE_NT_HEADERS pPE;
507 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
508 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
509 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
510 PIMAGE_IMPORT_BY_NAME pImpName;
511
512 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
513 return NULL;
514 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
515 if (pPE->Signature != IMAGE_NT_SIGNATURE)
516 return NULL;
517 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
518 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
519 .VirtualAddress);
520 for (; pImpDesc->FirstThunk; ++pImpDesc)
521 {
522 if (!pImpDesc->OriginalFirstThunk)
523 continue;
524 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
525 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
526 for (; pIAT->u1.Function; ++pIAT, ++pINT)
527 {
528 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
529 continue;
530 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
531 + (UINT_PTR)(pINT->u1.AddressOfData));
532 if (strcmp((char *)pImpName->Name, funcname) == 0)
533 {
534 switch (info)
535 {
536 case 0:
537 return (void *)pIAT->u1.Function;
538 case 1:
539 return (void *)(pImage + pImpDesc->Name);
540 default:
541 return NULL;
542 }
543 }
544 }
545 }
546 return NULL;
547}
548
549/*
550 * Get the module handle which 'funcname' in 'hInst' is imported from.
551 */
552 HINSTANCE
553find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
554{
555 char *modulename;
556
557 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
558 if (modulename != NULL)
559 return GetModuleHandleA(modulename);
560 return NULL;
561}
562
563/*
564 * Get the address of 'funcname' which is imported by 'hInst' DLL.
565 */
566 void *
567get_dll_import_func(HINSTANCE hInst, const char *funcname)
568{
569 return get_imported_func_info(hInst, funcname, 0);
570}
571#endif
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
574# ifndef GETTEXT_DLL
575# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200576# define GETTEXT_DLL_ALT1 "libintl-8.dll"
577# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200579/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200581static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000582static char *null_libintl_textdomain(const char *);
583static char *null_libintl_bindtextdomain(const char *, const char *);
584static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100585static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100586static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200588static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200590char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
591 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000592char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
593char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
596 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100597int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100598int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599
600 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100601dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602{
603 int i;
604 static struct
605 {
606 char *name;
607 FARPROC *ptr;
608 } libintl_entry[] =
609 {
610 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
613 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
614 {NULL, NULL}
615 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100616 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617
Bram Moolenaar7554c542018-10-06 15:03:15 +0200618 // No need to initialize twice.
619 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200621 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100622 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200623#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100624 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200625 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
626#endif
627#ifdef GETTEXT_DLL_ALT2
628 if (!hLibintlDLL)
629 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100630#endif
631 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200633 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200635 verbose_enter();
636 EMSG2(_(e_loadlib), GETTEXT_DLL);
637 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200639 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 }
641 for (i = 0; libintl_entry[i].name != NULL
642 && libintl_entry[i].ptr != NULL; ++i)
643 {
644 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
645 libintl_entry[i].name)) == NULL)
646 {
647 dyn_libintl_end();
648 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000649 {
650 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000652 verbose_leave();
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 return 0;
655 }
656 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000657
658 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000659 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000660 "bind_textdomain_codeset");
661 if (dyn_libintl_bind_textdomain_codeset == NULL)
662 dyn_libintl_bind_textdomain_codeset =
663 null_libintl_bind_textdomain_codeset;
664
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100665 /* _putenv() function for the libintl.dll is optional. */
666 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
667 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100668 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100669 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
671 }
672 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100673 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100674 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
675 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 return 1;
678}
679
680 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100681dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682{
683 if (hLibintlDLL)
684 FreeLibrary(hLibintlDLL);
685 hLibintlDLL = NULL;
686 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200687 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 dyn_libintl_textdomain = null_libintl_textdomain;
689 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000690 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100692 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693}
694
695 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000696null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 return (char*)msgid;
699}
700
701 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702null_libintl_ngettext(
703 const char *msgid,
704 const char *msgid_plural,
705 unsigned long n)
706{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200707 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200708}
709
Bram Moolenaaree695f72016-08-03 22:08:45 +0200710 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100711null_libintl_bindtextdomain(
712 const char *domainname UNUSED,
713 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714{
715 return NULL;
716}
717
718 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100719null_libintl_bind_textdomain_codeset(
720 const char *domainname UNUSED,
721 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000722{
723 return NULL;
724}
725
726 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100727null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200732 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100734{
735 return 0;
736}
737
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200738 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100739null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100740{
741 return 0;
742}
743
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744#endif /* DYNAMIC_GETTEXT */
745
746/* This symbol is not defined in older versions of the SDK or Visual C++ */
747
748#ifndef VER_PLATFORM_WIN32_WINDOWS
749# define VER_PLATFORM_WIN32_WINDOWS 1
750#endif
751
752DWORD g_PlatformId;
753
754#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100755# ifndef PROTO
756# include <aclapi.h>
757# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200758# ifndef PROTECTED_DACL_SECURITY_INFORMATION
759# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#endif
762
Bram Moolenaar27515922013-06-29 15:36:26 +0200763#ifdef HAVE_ACL
764/*
765 * Enables or disables the specified privilege.
766 */
767 static BOOL
768win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
769{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100770 BOOL bResult;
771 LUID luid;
772 HANDLE hToken;
773 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200774
775 if (!OpenProcessToken(GetCurrentProcess(),
776 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
777 return FALSE;
778
779 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
780 {
781 CloseHandle(hToken);
782 return FALSE;
783 }
784
Bram Moolenaar45500912014-07-09 20:51:07 +0200785 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200786 tokenPrivileges.Privileges[0].Luid = luid;
787 tokenPrivileges.Privileges[0].Attributes = bEnable ?
788 SE_PRIVILEGE_ENABLED : 0;
789
790 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
791 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
792
793 CloseHandle(hToken);
794
795 return bResult && GetLastError() == ERROR_SUCCESS;
796}
797#endif
798
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799/*
800 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
801 * VER_PLATFORM_WIN32_WINDOWS (Win95).
802 */
803 void
804PlatformId(void)
805{
806 static int done = FALSE;
807
808 if (!done)
809 {
810 OSVERSIONINFO ovi;
811
812 ovi.dwOSVersionInfoSize = sizeof(ovi);
813 GetVersionEx(&ovi);
814
815 g_PlatformId = ovi.dwPlatformId;
816
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100817 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
818 || ovi.dwMajorVersion > 6)
819 win8_or_later = TRUE;
820
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200822 /* Enable privilege for getting or setting SACLs. */
823 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#endif
825 done = TRUE;
826 }
827}
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifndef FEAT_GUI_W32
830
831#define SHIFT (SHIFT_PRESSED)
832#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
833#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
834#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
835
836
837/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
838 * We map function keys to their ANSI terminal equivalents, as produced
839 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
840 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
841 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
842 * combinations of function/arrow/etc keys.
843 */
844
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000845static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846{
847 WORD wVirtKey;
848 BOOL fAnsiKey;
849 int chAlone;
850 int chShift;
851 int chCtrl;
852 int chAlt;
853} VirtKeyMap[] =
854{
Bram 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;
4537 msg_puts(buffer);
4538 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;
4551 msg_puts(buffer);
4552 }
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);
4610 MSG_PUTS(_("\nCannot create pipes\n"));
4611 }
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
5185 EMSG(_("E371: Command not found"));
5186#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 Moolenaar6aa2cd42016-02-16 15:06:59 +01005263 smsg((char_u *)_("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 Moolenaar942d6b22016-02-07 19:57:16 +01005431 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005432mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005433{
5434 STARTUPINFO si;
5435 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005436 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005437 SECURITY_ATTRIBUTES saAttr;
5438 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005439 HANDLE ifd[2];
5440 HANDLE ofd[2];
5441 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005442 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005443
5444 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5445 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5446 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5447 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5448 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5449 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5450 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5451
5452 if (use_out_for_err && use_null_for_out)
5453 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005454
5455 ifd[0] = INVALID_HANDLE_VALUE;
5456 ifd[1] = INVALID_HANDLE_VALUE;
5457 ofd[0] = INVALID_HANDLE_VALUE;
5458 ofd[1] = INVALID_HANDLE_VALUE;
5459 efd[0] = INVALID_HANDLE_VALUE;
5460 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005461 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005462
Bram Moolenaar14207f42016-10-27 21:13:10 +02005463 jo = CreateJobObject(NULL, NULL);
5464 if (jo == NULL)
5465 {
5466 job->jv_status = JOB_FAILED;
5467 goto failed;
5468 }
5469
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005470 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005471 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005472
Bram Moolenaar76467df2016-02-12 19:30:26 +01005473 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005474 ZeroMemory(&si, sizeof(si));
5475 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005476 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005477 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005478
Bram Moolenaard8070362016-02-15 21:56:54 +01005479 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5480 saAttr.bInheritHandle = TRUE;
5481 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005482
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005483 if (use_file_for_in)
5484 {
5485 char_u *fname = options->jo_io_name[PART_IN];
5486
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005487 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5488 FILE_SHARE_READ | FILE_SHARE_WRITE,
5489 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5490 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005491 {
5492 EMSG2(_(e_notopen), fname);
5493 goto failed;
5494 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005495 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005496 else if (!use_null_for_in &&
5497 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005498 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005499 goto failed;
5500
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005501 if (use_file_for_out)
5502 {
5503 char_u *fname = options->jo_io_name[PART_OUT];
5504
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005505 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5506 FILE_SHARE_READ | FILE_SHARE_WRITE,
5507 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5508 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005509 {
5510 EMSG2(_(e_notopen), fname);
5511 goto failed;
5512 }
5513 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005514 else if (!use_null_for_out &&
5515 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005516 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005517 goto failed;
5518
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005519 if (use_file_for_err)
5520 {
5521 char_u *fname = options->jo_io_name[PART_ERR];
5522
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005523 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5524 FILE_SHARE_READ | FILE_SHARE_WRITE,
5525 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5526 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005527 {
5528 EMSG2(_(e_notopen), fname);
5529 goto failed;
5530 }
5531 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005532 else if (!use_out_for_err && !use_null_for_err &&
5533 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005534 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005535 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005536
Bram Moolenaard8070362016-02-15 21:56:54 +01005537 si.dwFlags |= STARTF_USESTDHANDLES;
5538 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005539 si.hStdOutput = ofd[1];
5540 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5541
5542 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5543 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005544 if (options->jo_set & JO_CHANNEL)
5545 {
5546 channel = options->jo_channel;
5547 if (channel != NULL)
5548 ++channel->ch_refcount;
5549 }
5550 else
5551 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005552 if (channel == NULL)
5553 goto failed;
5554 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005555
5556 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005557 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005558 CREATE_DEFAULT_ERROR_MODE |
5559 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005560 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005561 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005562 &si, &pi,
5563 ga.ga_data,
5564 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005565 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005566 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005567 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005568 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005569 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005570
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005571 ga_clear(&ga);
5572
Bram Moolenaar14207f42016-10-27 21:13:10 +02005573 if (!AssignProcessToJobObject(jo, pi.hProcess))
5574 {
5575 /* if failing, switch the way to terminate
5576 * process with TerminateProcess. */
5577 CloseHandle(jo);
5578 jo = NULL;
5579 }
5580 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005581 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005582 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005583 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005584 job->jv_status = JOB_STARTED;
5585
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005586 CloseHandle(ifd[0]);
5587 CloseHandle(ofd[1]);
5588 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005589 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005590
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005591 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005592 if (channel != NULL)
5593 {
5594 channel_set_pipes(channel,
5595 use_file_for_in || use_null_for_in
5596 ? INVALID_FD : (sock_T)ifd[1],
5597 use_file_for_out || use_null_for_out
5598 ? INVALID_FD : (sock_T)ofd[0],
5599 use_out_for_err || use_file_for_err || use_null_for_err
5600 ? INVALID_FD : (sock_T)efd[0]);
5601 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005602 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005603 return;
5604
5605failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005606 CloseHandle(ifd[0]);
5607 CloseHandle(ofd[0]);
5608 CloseHandle(efd[0]);
5609 CloseHandle(ifd[1]);
5610 CloseHandle(ofd[1]);
5611 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005612 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005613 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005614}
5615
5616 char *
5617mch_job_status(job_T *job)
5618{
5619 DWORD dwExitCode = 0;
5620
Bram Moolenaar76467df2016-02-12 19:30:26 +01005621 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5622 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005623 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005624 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005625 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005626 {
5627 ch_log(job->jv_channel, "Job ended");
5628 job->jv_status = JOB_ENDED;
5629 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005630 return "dead";
5631 }
5632 return "run";
5633}
5634
Bram Moolenaar97792de2016-10-15 18:36:49 +02005635 job_T *
5636mch_detect_ended_job(job_T *job_list)
5637{
5638 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5639 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5640 job_T *job = job_list;
5641
5642 while (job != NULL)
5643 {
5644 DWORD n;
5645 DWORD result;
5646
5647 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5648 && job != NULL; job = job->jv_next)
5649 {
5650 if (job->jv_status == JOB_STARTED)
5651 {
5652 jobHandles[n] = job->jv_proc_info.hProcess;
5653 jobArray[n] = job;
5654 ++n;
5655 }
5656 }
5657 if (n == 0)
5658 continue;
5659 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5660 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5661 {
5662 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5663
5664 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5665 return wait_job;
5666 }
5667 }
5668 return NULL;
5669}
5670
Bram Moolenaarfb630902016-10-29 14:55:00 +02005671 static BOOL
5672terminate_all(HANDLE process, int code)
5673{
5674 PROCESSENTRY32 pe;
5675 HANDLE h = INVALID_HANDLE_VALUE;
5676 DWORD pid = GetProcessId(process);
5677
5678 if (pid != 0)
5679 {
5680 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5681 if (h != INVALID_HANDLE_VALUE)
5682 {
5683 pe.dwSize = sizeof(PROCESSENTRY32);
5684 if (!Process32First(h, &pe))
5685 goto theend;
5686
5687 do
5688 {
5689 if (pe.th32ParentProcessID == pid)
5690 {
5691 HANDLE ph = OpenProcess(
5692 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5693 if (ph != NULL)
5694 {
5695 terminate_all(ph, code);
5696 CloseHandle(ph);
5697 }
5698 }
5699 } while (Process32Next(h, &pe));
5700
5701 CloseHandle(h);
5702 }
5703 }
5704
5705theend:
5706 return TerminateProcess(process, code);
5707}
5708
5709/*
5710 * Send a (deadly) signal to "job".
5711 * Return FAIL if it didn't work.
5712 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005713 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005714mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005715{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005716 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005717
Bram Moolenaar923d9262016-02-25 20:56:01 +01005718 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005719 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005720 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005721 if (job->jv_job_object != NULL)
5722 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005723 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005724 }
5725
5726 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5727 return FAIL;
5728 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005729 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5730 job->jv_proc_info.dwProcessId)
5731 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005732 FreeConsole();
5733 return ret;
5734}
5735
5736/*
5737 * Clear the data related to "job".
5738 */
5739 void
5740mch_clear_job(job_T *job)
5741{
5742 if (job->jv_status != JOB_FAILED)
5743 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005744 if (job->jv_job_object != NULL)
5745 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005746 CloseHandle(job->jv_proc_info.hProcess);
5747 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005748}
5749#endif
5750
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751
5752#ifndef FEAT_GUI_W32
5753
5754/*
5755 * Start termcap mode
5756 */
5757 static void
5758termcap_mode_start(void)
5759{
5760 DWORD cmodein;
5761
5762 if (g_fTermcapMode)
5763 return;
5764
5765 SaveConsoleBuffer(&g_cbNonTermcap);
5766
5767 if (g_cbTermcap.IsValid)
5768 {
5769 /*
5770 * We've been in termcap mode before. Restore certain screen
5771 * characteristics, including the buffer size and the window
5772 * size. Since we will be redrawing the screen, we don't need
5773 * to restore the actual contents of the buffer.
5774 */
5775 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005776 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5778 Rows = g_cbTermcap.Info.dwSize.Y;
5779 Columns = g_cbTermcap.Info.dwSize.X;
5780 }
5781 else
5782 {
5783 /*
5784 * This is our first time entering termcap mode. Clear the console
5785 * screen buffer, and resize the buffer to match the current window
5786 * size. We will use this as the size of our editing environment.
5787 */
5788 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005789 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5791 }
5792
5793#ifdef FEAT_TITLE
5794 resettitle();
5795#endif
5796
5797 GetConsoleMode(g_hConIn, &cmodein);
5798#ifdef FEAT_MOUSE
5799 if (g_fMouseActive)
5800 cmodein |= ENABLE_MOUSE_INPUT;
5801 else
5802 cmodein &= ~ENABLE_MOUSE_INPUT;
5803#endif
5804 cmodein |= ENABLE_WINDOW_INPUT;
5805 SetConsoleMode(g_hConIn, cmodein);
5806
5807 redraw_later_clear();
5808 g_fTermcapMode = TRUE;
5809}
5810
5811
5812/*
5813 * End termcap mode
5814 */
5815 static void
5816termcap_mode_end(void)
5817{
5818 DWORD cmodein;
5819 ConsoleBuffer *cb;
5820 COORD coord;
5821 DWORD dwDummy;
5822
5823 if (!g_fTermcapMode)
5824 return;
5825
5826 SaveConsoleBuffer(&g_cbTermcap);
5827
5828 GetConsoleMode(g_hConIn, &cmodein);
5829 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5830 SetConsoleMode(g_hConIn, cmodein);
5831
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005832#ifdef FEAT_RESTORE_ORIG_SCREEN
5833 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5834#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005838 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839 SetConsoleCursorInfo(g_hConOut, &g_cci);
5840
5841 if (p_rs || exiting)
5842 {
5843 /*
5844 * Clear anything that happens to be on the current line.
5845 */
5846 coord.X = 0;
5847 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5848 FillConsoleOutputCharacter(g_hConOut, ' ',
5849 cb->Info.dwSize.X, coord, &dwDummy);
5850 /*
5851 * The following is just for aesthetics. If we are exiting without
5852 * restoring the screen, then we want to have a prompt string
5853 * appear at the bottom line. However, the command interpreter
5854 * seems to always advance the cursor one line before displaying
5855 * the prompt string, which causes the screen to scroll. To
5856 * counter this, move the cursor up one line before exiting.
5857 */
5858 if (exiting && !p_rs)
5859 coord.Y--;
5860 /*
5861 * Position the cursor at the leftmost column of the desired row.
5862 */
5863 SetConsoleCursorPosition(g_hConOut, coord);
5864 }
5865
5866 g_fTermcapMode = FALSE;
5867}
5868#endif /* FEAT_GUI_W32 */
5869
5870
5871#ifdef FEAT_GUI_W32
5872 void
5873mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005874 char_u *s UNUSED,
5875 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876{
5877 /* never used */
5878}
5879
5880#else
5881
5882/*
5883 * clear `n' chars, starting from `coord'
5884 */
5885 static void
5886clear_chars(
5887 COORD coord,
5888 DWORD n)
5889{
5890 DWORD dwDummy;
5891
5892 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005893
5894 if (!USE_VTP)
5895 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5896 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005897 {
5898 set_console_color_rgb();
5899 gotoxy(coord.X + 1, coord.Y + 1);
5900 vtp_printf("\033[%dX", n);
5901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904
5905/*
5906 * Clear the screen
5907 */
5908 static void
5909clear_screen(void)
5910{
5911 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005912
5913 if (!USE_VTP)
5914 clear_chars(g_coord, Rows * Columns);
5915 else
5916 {
5917 set_console_color_rgb();
5918 gotoxy(1, 1);
5919 vtp_printf("\033[2J");
5920 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921}
5922
5923
5924/*
5925 * Clear to end of display
5926 */
5927 static void
5928clear_to_end_of_display(void)
5929{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005930 COORD save = g_coord;
5931
5932 if (!USE_VTP)
5933 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005935 else
5936 {
5937 set_console_color_rgb();
5938 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5939 vtp_printf("\033[0J");
5940
5941 gotoxy(save.X + 1, save.Y + 1);
5942 g_coord = save;
5943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944}
5945
5946
5947/*
5948 * Clear to end of line
5949 */
5950 static void
5951clear_to_end_of_line(void)
5952{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005953 COORD save = g_coord;
5954
5955 if (!USE_VTP)
5956 clear_chars(g_coord, Columns - g_coord.X);
5957 else
5958 {
5959 set_console_color_rgb();
5960 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5961 vtp_printf("\033[0K");
5962
5963 gotoxy(save.X + 1, save.Y + 1);
5964 g_coord = save;
5965 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966}
5967
5968
5969/*
5970 * Scroll the scroll region up by `cLines' lines
5971 */
5972 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005973scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974{
5975 COORD oldcoord = g_coord;
5976
5977 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5978 delete_lines(cLines);
5979
5980 g_coord = oldcoord;
5981}
5982
5983
5984/*
5985 * Set the scroll region
5986 */
5987 static void
5988set_scroll_region(
5989 unsigned left,
5990 unsigned top,
5991 unsigned right,
5992 unsigned bottom)
5993{
5994 if (left >= right
5995 || top >= bottom
5996 || right > (unsigned) Columns - 1
5997 || bottom > (unsigned) Rows - 1)
5998 return;
5999
6000 g_srScrollRegion.Left = left;
6001 g_srScrollRegion.Top = top;
6002 g_srScrollRegion.Right = right;
6003 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006004
6005 if (USE_VTP)
6006 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007}
6008
6009
6010/*
6011 * Insert `cLines' lines at the current cursor position
6012 */
6013 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006014insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015{
6016 SMALL_RECT source;
6017 COORD dest;
6018 CHAR_INFO fill;
6019
6020 dest.X = 0;
6021 dest.Y = g_coord.Y + cLines;
6022
6023 source.Left = 0;
6024 source.Top = g_coord.Y;
6025 source.Right = g_srScrollRegion.Right;
6026 source.Bottom = g_srScrollRegion.Bottom - cLines;
6027
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006028 if (!USE_VTP)
6029 {
6030 fill.Char.AsciiChar = ' ';
6031 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006033 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6034 }
6035 else
6036 {
6037 set_console_color_rgb();
6038
6039 gotoxy(1, source.Top + 1);
6040 vtp_printf("\033[%dT", cLines);
6041 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042
6043 /* Here we have to deal with a win32 console flake: If the scroll
6044 * region looks like abc and we scroll c to a and fill with d we get
6045 * cbd... if we scroll block c one line at a time to a, we get cdd...
6046 * vim expects cdd consistently... So we have to deal with that
6047 * here... (this also occurs scrolling the same way in the other
6048 * direction). */
6049
6050 if (source.Bottom < dest.Y)
6051 {
6052 COORD coord;
6053
6054 coord.X = 0;
6055 coord.Y = source.Bottom;
6056 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6057 }
6058}
6059
6060
6061/*
6062 * Delete `cLines' lines at the current cursor position
6063 */
6064 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006065delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066{
6067 SMALL_RECT source;
6068 COORD dest;
6069 CHAR_INFO fill;
6070 int nb;
6071
6072 dest.X = 0;
6073 dest.Y = g_coord.Y;
6074
6075 source.Left = 0;
6076 source.Top = g_coord.Y + cLines;
6077 source.Right = g_srScrollRegion.Right;
6078 source.Bottom = g_srScrollRegion.Bottom;
6079
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006080 if (!USE_VTP)
6081 {
6082 fill.Char.AsciiChar = ' ';
6083 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006085 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6086 }
6087 else
6088 {
6089 set_console_color_rgb();
6090
6091 gotoxy(1, source.Top + 1);
6092 vtp_printf("\033[%dS", cLines);
6093 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094
6095 /* Here we have to deal with a win32 console flake: If the scroll
6096 * region looks like abc and we scroll c to a and fill with d we get
6097 * cbd... if we scroll block c one line at a time to a, we get cdd...
6098 * vim expects cdd consistently... So we have to deal with that
6099 * here... (this also occurs scrolling the same way in the other
6100 * direction). */
6101
6102 nb = dest.Y + (source.Bottom - source.Top) + 1;
6103
6104 if (nb < source.Top)
6105 {
6106 COORD coord;
6107
6108 coord.X = 0;
6109 coord.Y = nb;
6110 clear_chars(coord, Columns * (source.Top - nb));
6111 }
6112}
6113
6114
6115/*
6116 * Set the cursor position
6117 */
6118 static void
6119gotoxy(
6120 unsigned x,
6121 unsigned y)
6122{
6123 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6124 return;
6125
6126 /* external cursor coords are 1-based; internal are 0-based */
6127 g_coord.X = x - 1;
6128 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006129
6130 if (!USE_VTP)
6131 SetConsoleCursorPosition(g_hConOut, g_coord);
6132 else
6133 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134}
6135
6136
6137/*
6138 * Set the current text attribute = (foreground | background)
6139 * See ../doc/os_win32.txt for the numbers.
6140 */
6141 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006142textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006144 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145
6146 SetConsoleTextAttribute(g_hConOut, wAttr);
6147}
6148
6149
6150 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006151textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006153 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006155 if (!USE_VTP)
6156 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6157 else
6158 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159}
6160
6161
6162 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006163textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006165 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006167 if (!USE_VTP)
6168 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6169 else
6170 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171}
6172
6173
6174/*
6175 * restore the default text attribute (whatever we started with)
6176 */
6177 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006178normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006180 if (!USE_VTP)
6181 textattr(g_attrDefault);
6182 else
6183 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184}
6185
6186
6187static WORD g_attrPreStandout = 0;
6188
6189/*
6190 * Make the text standout, by brightening it
6191 */
6192 static void
6193standout(void)
6194{
6195 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006196
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6198}
6199
6200
6201/*
6202 * Turn off standout mode
6203 */
6204 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006205standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206{
6207 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006209
6210 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211}
6212
6213
6214/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006215 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 */
6217 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006218mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219{
6220 char_u *p;
6221 int n;
6222
6223 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6224 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006225 if (
6226#ifdef FEAT_TERMGUICOLORS
6227 !p_tgc &&
6228#endif
6229 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 {
6231 p = T_ME + 2;
6232 n = getdigits(&p);
6233 if (*p == 'm' && n > 0)
6234 {
6235 cterm_normal_fg_color = (n & 0xf) + 1;
6236 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6237 }
6238 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006239#ifdef FEAT_TERMGUICOLORS
6240 cterm_normal_fg_gui_color = INVALCOLOR;
6241 cterm_normal_bg_gui_color = INVALCOLOR;
6242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243}
6244
6245
6246/*
6247 * visual bell: flash the screen
6248 */
6249 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006250visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251{
6252 COORD coordOrigin = {0, 0};
6253 WORD attrFlash = ~g_attrCurrent & 0xff;
6254
6255 DWORD dwDummy;
6256 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6257
6258 if (oldattrs == NULL)
6259 return;
6260 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6261 coordOrigin, &dwDummy);
6262 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6263 coordOrigin, &dwDummy);
6264
6265 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006266 if (!USE_VTP)
6267 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 coordOrigin, &dwDummy);
6269 vim_free(oldattrs);
6270}
6271
6272
6273/*
6274 * Make the cursor visible or invisible
6275 */
6276 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006277cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278{
6279 s_cursor_visible = fVisible;
6280#ifdef MCH_CURSOR_SHAPE
6281 mch_update_cursor();
6282#endif
6283}
6284
6285
6286/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006287 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006288 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006290 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006292 char_u *pchBuf,
6293 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294{
6295 COORD coord = g_coord;
6296 DWORD written;
6297
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006298#ifdef FEAT_MBYTE
6299 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6300 {
6301 static WCHAR *unicodebuf = NULL;
6302 static int unibuflen = 0;
6303 int length;
6304 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006306 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6307 if (unicodebuf == NULL || length > unibuflen)
6308 {
6309 vim_free(unicodebuf);
6310 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6311 unibuflen = length;
6312 }
6313 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6314 unicodebuf, unibuflen);
6315
6316 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006317
6318 if (!USE_VTP)
6319 {
6320 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6321 coord, &written);
6322 /* When writing fails or didn't write a single character, pretend one
6323 * character was written, otherwise we get stuck. */
6324 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6325 coord, &cchwritten) == 0
6326 || cchwritten == 0)
6327 cchwritten = 1;
6328 }
6329 else
6330 {
6331 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6332 NULL) == 0 || cchwritten == 0)
6333 cchwritten = 1;
6334 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006335
6336 if (cchwritten == length)
6337 {
6338 written = cbToWrite;
6339 g_coord.X += (SHORT)cells;
6340 }
6341 else
6342 {
6343 char_u *p = pchBuf;
6344 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006345 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006346 written = p - pchBuf;
6347 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6348 }
6349 }
6350 else
6351#endif
6352 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006353 if (!USE_VTP)
6354 {
6355 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6356 coord, &written);
6357 /* When writing fails or didn't write a single character, pretend one
6358 * character was written, otherwise we get stuck. */
6359 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6360 coord, &written) == 0
6361 || written == 0)
6362 written = 1;
6363 }
6364 else
6365 {
6366 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6367 NULL) == 0 || written == 0)
6368 written = 1;
6369 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006370
6371 g_coord.X += (SHORT) written;
6372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373
6374 while (g_coord.X > g_srScrollRegion.Right)
6375 {
6376 g_coord.X -= (SHORT) Columns;
6377 if (g_coord.Y < g_srScrollRegion.Bottom)
6378 g_coord.Y++;
6379 }
6380
6381 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6382
6383 return written;
6384}
6385
6386
6387/*
6388 * mch_write(): write the output buffer to the screen, translating ESC
6389 * sequences into calls to console output routines.
6390 */
6391 void
6392mch_write(
6393 char_u *s,
6394 int len)
6395{
6396 s[len] = NUL;
6397
6398 if (!term_console)
6399 {
6400 write(1, s, (unsigned)len);
6401 return;
6402 }
6403
6404 /* translate ESC | sequences into faked bios calls */
6405 while (len--)
6406 {
6407 /* optimization: use one single write_chars for runs of text,
6408 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006409 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410
6411 if (p_wd)
6412 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006413 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414 if (prefix != 0)
6415 prefix = 1;
6416 }
6417
6418 if (prefix != 0)
6419 {
6420 DWORD nWritten;
6421
6422 nWritten = write_chars(s, prefix);
6423#ifdef MCH_WRITE_DUMP
6424 if (fdDump)
6425 {
6426 fputc('>', fdDump);
6427 fwrite(s, sizeof(char_u), nWritten, fdDump);
6428 fputs("<\n", fdDump);
6429 }
6430#endif
6431 len -= (nWritten - 1);
6432 s += nWritten;
6433 }
6434 else if (s[0] == '\n')
6435 {
6436 /* \n, newline: go to the beginning of the next line or scroll */
6437 if (g_coord.Y == g_srScrollRegion.Bottom)
6438 {
6439 scroll(1);
6440 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6441 }
6442 else
6443 {
6444 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6445 }
6446#ifdef MCH_WRITE_DUMP
6447 if (fdDump)
6448 fputs("\\n\n", fdDump);
6449#endif
6450 s++;
6451 }
6452 else if (s[0] == '\r')
6453 {
6454 /* \r, carriage return: go to beginning of line */
6455 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6456#ifdef MCH_WRITE_DUMP
6457 if (fdDump)
6458 fputs("\\r\n", fdDump);
6459#endif
6460 s++;
6461 }
6462 else if (s[0] == '\b')
6463 {
6464 /* \b, backspace: move cursor one position left */
6465 if (g_coord.X > g_srScrollRegion.Left)
6466 g_coord.X--;
6467 else if (g_coord.Y > g_srScrollRegion.Top)
6468 {
6469 g_coord.X = g_srScrollRegion.Right;
6470 g_coord.Y--;
6471 }
6472 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6473#ifdef MCH_WRITE_DUMP
6474 if (fdDump)
6475 fputs("\\b\n", fdDump);
6476#endif
6477 s++;
6478 }
6479 else if (s[0] == '\a')
6480 {
6481 /* \a, bell */
6482 MessageBeep(0xFFFFFFFF);
6483#ifdef MCH_WRITE_DUMP
6484 if (fdDump)
6485 fputs("\\a\n", fdDump);
6486#endif
6487 s++;
6488 }
6489 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6490 {
6491#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006492 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006494 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006495 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496
6497 switch (s[2])
6498 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 case '0': case '1': case '2': case '3': case '4':
6500 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006501 p = s + 1;
6502 do
6503 {
6504 ++p;
6505 args[argc] = getdigits(&p);
6506 argc += (argc < 15) ? 1 : 0;
6507 if (p > s + len)
6508 break;
6509 } while (*p == ';');
6510
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511 if (p > s + len)
6512 break;
6513
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006514 arg1 = args[0];
6515 arg2 = args[1];
6516 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006518 if (argc == 1 && args[0] == 0)
6519 normvideo();
6520 else if (argc == 1)
6521 {
6522 if (USE_VTP)
6523 textcolor((WORD) arg1);
6524 else
6525 textattr((WORD) arg1);
6526 }
6527 else if (USE_VTP)
6528 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006530 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006532 gotoxy(arg2, arg1);
6533 }
6534 else if (argc == 2 && *p == 'r')
6535 {
6536 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6537 }
6538 else if (argc == 1 && *p == 'A')
6539 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 gotoxy(g_coord.X + 1,
6541 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6542 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006543 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 {
6545 textbackground((WORD) arg1);
6546 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006547 else if (argc == 1 && *p == 'C')
6548 {
6549 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6550 g_coord.Y + 1);
6551 }
6552 else if (argc == 1 && *p == 'f')
6553 {
6554 textcolor((WORD) arg1);
6555 }
6556 else if (argc == 1 && *p == 'H')
6557 {
6558 gotoxy(1, arg1);
6559 }
6560 else if (argc == 1 && *p == 'L')
6561 {
6562 insert_lines(arg1);
6563 }
6564 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 {
6566 delete_lines(arg1);
6567 }
6568
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006569 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 s = p + 1;
6571 break;
6572
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006574 gotoxy(g_coord.X + 1,
6575 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6576 goto got3;
6577
6578 case 'B':
6579 visual_bell();
6580 goto got3;
6581
6582 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6584 g_coord.Y + 1);
6585 goto got3;
6586
6587 case 'E':
6588 termcap_mode_end();
6589 goto got3;
6590
6591 case 'F':
6592 standout();
6593 goto got3;
6594
6595 case 'f':
6596 standend();
6597 goto got3;
6598
6599 case 'H':
6600 gotoxy(1, 1);
6601 goto got3;
6602
6603 case 'j':
6604 clear_to_end_of_display();
6605 goto got3;
6606
6607 case 'J':
6608 clear_screen();
6609 goto got3;
6610
6611 case 'K':
6612 clear_to_end_of_line();
6613 goto got3;
6614
6615 case 'L':
6616 insert_lines(1);
6617 goto got3;
6618
6619 case 'M':
6620 delete_lines(1);
6621 goto got3;
6622
6623 case 'S':
6624 termcap_mode_start();
6625 goto got3;
6626
6627 case 'V':
6628 cursor_visible(TRUE);
6629 goto got3;
6630
6631 case 'v':
6632 cursor_visible(FALSE);
6633 goto got3;
6634
6635 got3:
6636 s += 3;
6637 len -= 2;
6638 }
6639
6640#ifdef MCH_WRITE_DUMP
6641 if (fdDump)
6642 {
6643 fputs("ESC | ", fdDump);
6644 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6645 fputc('\n', fdDump);
6646 }
6647#endif
6648 }
6649 else
6650 {
6651 /* Write a single character */
6652 DWORD nWritten;
6653
6654 nWritten = write_chars(s, 1);
6655#ifdef MCH_WRITE_DUMP
6656 if (fdDump)
6657 {
6658 fputc('>', fdDump);
6659 fwrite(s, sizeof(char_u), nWritten, fdDump);
6660 fputs("<\n", fdDump);
6661 }
6662#endif
6663
6664 len -= (nWritten - 1);
6665 s += nWritten;
6666 }
6667 }
6668
6669#ifdef MCH_WRITE_DUMP
6670 if (fdDump)
6671 fflush(fdDump);
6672#endif
6673}
6674
6675#endif /* FEAT_GUI_W32 */
6676
6677
6678/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006679 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 */
6681 void
6682mch_delay(
6683 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006684 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685{
6686#ifdef FEAT_GUI_W32
6687 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006688#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006690# ifdef FEAT_MZSCHEME
6691 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6692 {
6693 int towait = p_mzq;
6694
6695 /* if msec is large enough, wait by portions in p_mzq */
6696 while (msec > 0)
6697 {
6698 mzvim_check_threads();
6699 if (msec < towait)
6700 towait = msec;
6701 Sleep(towait);
6702 msec -= towait;
6703 }
6704 }
6705 else
6706# endif
6707 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006709 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710#endif
6711}
6712
6713
6714/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006715 * This version of remove is not scared by a readonly (backup) file.
6716 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 * Return 0 for success, -1 for failure.
6718 */
6719 int
6720mch_remove(char_u *name)
6721{
6722#ifdef FEAT_MBYTE
6723 WCHAR *wn = NULL;
6724 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006725#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726
Bram Moolenaar203258c2016-01-17 22:15:16 +01006727 /*
6728 * On Windows, deleting a directory's symbolic link is done by
6729 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6730 */
6731 if (mch_isdir(name) && mch_is_symbolic_link(name))
6732 return mch_rmdir(name);
6733
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006734 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6735
6736#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006737 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6738 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006739 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 if (wn != NULL)
6741 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742 n = DeleteFileW(wn) ? 0 : -1;
6743 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006744 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 }
6746 }
6747#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006748 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749}
6750
6751
6752/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006753 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 */
6755 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006756mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757{
6758#ifndef FEAT_GUI_W32 /* never used */
6759 if (g_fCtrlCPressed || g_fCBrkPressed)
6760 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006761 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6763 got_int = TRUE;
6764 }
6765#endif
6766}
6767
Bram Moolenaaree273972016-01-02 21:11:51 +01006768/* physical RAM to leave for the OS */
6769#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006770
6771/*
6772 * How much main memory in KiB that can be used by VIM.
6773 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006774 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006775mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006776{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006777 MEMORYSTATUSEX ms;
6778
Bram Moolenaaree273972016-01-02 21:11:51 +01006779 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006780 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6781 * what fits in 32 bits. But it's not always available. */
6782 ms.dwLength = sizeof(MEMORYSTATUSEX);
6783 GlobalMemoryStatusEx(&ms);
6784 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006785 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006786 /* Process address space fits in physical RAM, use all of it. */
6787 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006788 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006789 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006790 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006791 /* Catch old NT box or perverse hardware setup. */
6792 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006793 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006794 /* Use physical RAM less reserve for OS + data. */
6795 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006796}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798#ifdef FEAT_MBYTE
6799/*
6800 * Same code as below, but with wide functions and no comments.
6801 * Return 0 for success, non-zero for failure.
6802 */
6803 int
6804mch_wrename(WCHAR *wold, WCHAR *wnew)
6805{
6806 WCHAR *p;
6807 int i;
6808 WCHAR szTempFile[_MAX_PATH + 1];
6809 WCHAR szNewPath[_MAX_PATH + 1];
6810 HANDLE hf;
6811
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006812 p = wold;
6813 for (i = 0; wold[i] != NUL; ++i)
6814 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6815 && wold[i + 1] != 0)
6816 p = wold + i + 1;
6817 if ((int)(wold + i - p) < 8 || p[6] != '~')
6818 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819
6820 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6821 return -1;
6822 *p = NUL;
6823
6824 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6825 return -2;
6826
6827 if (!DeleteFileW(szTempFile))
6828 return -3;
6829
6830 if (!MoveFileW(wold, szTempFile))
6831 return -4;
6832
6833 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6834 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6835 return -5;
6836 if (!CloseHandle(hf))
6837 return -6;
6838
6839 if (!MoveFileW(szTempFile, wnew))
6840 {
6841 (void)MoveFileW(szTempFile, wold);
6842 return -7;
6843 }
6844
6845 DeleteFileW(szTempFile);
6846
6847 if (!DeleteFileW(wold))
6848 return -8;
6849
6850 return 0;
6851}
6852#endif
6853
6854
6855/*
6856 * mch_rename() works around a bug in rename (aka MoveFile) in
6857 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6858 * file whose short file name is "FOO.BAR" (its long file name will
6859 * be correct: "foo.bar~"). Because a file can be accessed by
6860 * either its SFN or its LFN, "foo.bar" has effectively been
6861 * renamed to "foo.bar", which is not at all what was wanted. This
6862 * seems to happen only when renaming files with three-character
6863 * extensions by appending a suffix that does not include ".".
6864 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6865 *
6866 * There is another problem, which isn't really a bug but isn't right either:
6867 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6868 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6869 * service pack 6. Doesn't seem to happen on Windows 98.
6870 *
6871 * Like rename(), returns 0 upon success, non-zero upon failure.
6872 * Should probably set errno appropriately when errors occur.
6873 */
6874 int
6875mch_rename(
6876 const char *pszOldFile,
6877 const char *pszNewFile)
6878{
6879 char szTempFile[_MAX_PATH+1];
6880 char szNewPath[_MAX_PATH+1];
6881 char *pszFilePart;
6882 HANDLE hf;
6883#ifdef FEAT_MBYTE
6884 WCHAR *wold = NULL;
6885 WCHAR *wnew = NULL;
6886 int retval = -1;
6887
6888 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6889 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006890 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6891 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 if (wold != NULL && wnew != NULL)
6893 retval = mch_wrename(wold, wnew);
6894 vim_free(wold);
6895 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006896 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 }
6898#endif
6899
6900 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006901 * No need to play tricks unless the file name contains a "~" as the
6902 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006904 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6905 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6906 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907
6908 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6909 * a directory, no error is returned and pszFilePart will be NULL. */
6910 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6911 || pszFilePart == NULL)
6912 return -1;
6913 *pszFilePart = NUL;
6914
6915 /* Get (and create) a unique temporary file name in directory of new file */
6916 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6917 return -2;
6918
6919 /* blow the temp file away */
6920 if (!DeleteFile(szTempFile))
6921 return -3;
6922
6923 /* rename old file to the temp file */
6924 if (!MoveFile(pszOldFile, szTempFile))
6925 return -4;
6926
6927 /* now create an empty file called pszOldFile; this prevents the operating
6928 * system using pszOldFile as an alias (SFN) if we're renaming within the
6929 * same directory. For example, we're editing a file called
6930 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6931 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6932 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006933 * cause all sorts of problems later in buf_write(). So, we create an
6934 * empty file called filena~1.txt and the system will have to find some
6935 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 */
6937 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6938 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6939 return -5;
6940 if (!CloseHandle(hf))
6941 return -6;
6942
6943 /* rename the temp file to the new file */
6944 if (!MoveFile(szTempFile, pszNewFile))
6945 {
6946 /* Renaming failed. Rename the file back to its old name, so that it
6947 * looks like nothing happened. */
6948 (void)MoveFile(szTempFile, pszOldFile);
6949
6950 return -7;
6951 }
6952
6953 /* Seems to be left around on Novell filesystems */
6954 DeleteFile(szTempFile);
6955
6956 /* finally, remove the empty old file */
6957 if (!DeleteFile(pszOldFile))
6958 return -8;
6959
6960 return 0; /* success */
6961}
6962
6963/*
6964 * Get the default shell for the current hardware platform
6965 */
6966 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006967default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 PlatformId();
6970
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006971 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972}
6973
6974/*
6975 * mch_access() extends access() to do more detailed check on network drives.
6976 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6977 */
6978 int
6979mch_access(char *n, int p)
6980{
6981 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 int retval = -1; /* default: fail */
6983#ifdef FEAT_MBYTE
6984 WCHAR *wn = NULL;
6985
6986 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006987 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988#endif
6989
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006990 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 {
6992 char TempName[_MAX_PATH + 16] = "";
6993#ifdef FEAT_MBYTE
6994 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6995#endif
6996
6997 if (p & R_OK)
6998 {
6999 /* Read check is performed by seeing if we can do a find file on
7000 * the directory for any file. */
7001#ifdef FEAT_MBYTE
7002 if (wn != NULL)
7003 {
7004 int i;
7005 WIN32_FIND_DATAW d;
7006
7007 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7008 TempNameW[i] = wn[i];
7009 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7010 TempNameW[i++] = '\\';
7011 TempNameW[i++] = '*';
7012 TempNameW[i++] = 0;
7013
7014 hFile = FindFirstFileW(TempNameW, &d);
7015 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007016 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 else
7018 (void)FindClose(hFile);
7019 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007020 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021#endif
7022 {
7023 char *pch;
7024 WIN32_FIND_DATA d;
7025
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007026 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 pch = TempName + STRLEN(TempName) - 1;
7028 if (*pch != '\\' && *pch != '/')
7029 *++pch = '\\';
7030 *++pch = '*';
7031 *++pch = NUL;
7032
7033 hFile = FindFirstFile(TempName, &d);
7034 if (hFile == INVALID_HANDLE_VALUE)
7035 goto getout;
7036 (void)FindClose(hFile);
7037 }
7038 }
7039
7040 if (p & W_OK)
7041 {
7042 /* Trying to create a temporary file in the directory should catch
7043 * directories on read-only network shares. However, in
7044 * directories whose ACL allows writes but denies deletes will end
7045 * up keeping the temporary file :-(. */
7046#ifdef FEAT_MBYTE
7047 if (wn != NULL)
7048 {
7049 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007050 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 else
7052 DeleteFileW(TempNameW);
7053 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007054 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055#endif
7056 {
7057 if (!GetTempFileName(n, "VIM", 0, TempName))
7058 goto getout;
7059 mch_remove((char_u *)TempName);
7060 }
7061 }
7062 }
7063 else
7064 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007065 // Don't consider a file read-only if another process has opened it.
7066 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7067
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 /* Trying to open the file for the required access does ACL, read-only
7069 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007070 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7071 | ((p & R_OK) ? GENERIC_READ : 0);
7072
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073#ifdef FEAT_MBYTE
7074 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007075 hFile = CreateFileW(wn, access_mode, share_mode,
7076 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007077 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007079 hFile = CreateFile(n, access_mode, share_mode,
7080 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 if (hFile == INVALID_HANDLE_VALUE)
7082 goto getout;
7083 CloseHandle(hFile);
7084 }
7085
7086 retval = 0; /* success */
7087getout:
7088#ifdef FEAT_MBYTE
7089 vim_free(wn);
7090#endif
7091 return retval;
7092}
7093
7094#if defined(FEAT_MBYTE) || defined(PROTO)
7095/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007096 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 */
7098 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007099mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007101 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7102# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 WCHAR *wn;
7104 int f;
7105
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007106 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007108 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 if (wn != NULL)
7110 {
7111 f = _wopen(wn, flags, mode);
7112 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007113 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 }
7115 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007116# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007118 /* open() can open a file which name is longer than _MAX_PATH bytes
7119 * and shorter than _MAX_PATH characters successfully, but sometimes it
7120 * causes unexpected error in another part. We make it an error explicitly
7121 * here. */
7122 if (strlen(name) >= _MAX_PATH)
7123 return -1;
7124
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 return open(name, flags, mode);
7126}
7127
7128/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007129 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130 */
7131 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007132mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133{
7134 WCHAR *wn, *wm;
7135 FILE *f = NULL;
7136
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007137 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007138 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007139# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007140 /* Work around an annoying assertion in the Microsoft debug CRT
7141 * when mode's text/binary setting doesn't match _get_fmode(). */
7142 char newMode = mode[strlen(mode) - 1];
7143 int oldMode = 0;
7144
7145 _get_fmode(&oldMode);
7146 if (newMode == 't')
7147 _set_fmode(_O_TEXT);
7148 else if (newMode == 'b')
7149 _set_fmode(_O_BINARY);
7150# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007151 wn = enc_to_utf16((char_u *)name, NULL);
7152 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 if (wn != NULL && wm != NULL)
7154 f = _wfopen(wn, wm);
7155 vim_free(wn);
7156 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007157
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007158# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007159 _set_fmode(oldMode);
7160# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007161 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007162 }
7163
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007164 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7165 * and shorter than _MAX_PATH characters successfully, but sometimes it
7166 * causes unexpected error in another part. We make it an error explicitly
7167 * here. */
7168 if (strlen(name) >= _MAX_PATH)
7169 return NULL;
7170
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 return fopen(name, mode);
7172}
7173#endif
7174
7175#ifdef FEAT_MBYTE
7176/*
7177 * SUB STREAM (aka info stream) handling:
7178 *
7179 * NTFS can have sub streams for each file. Normal contents of file is
7180 * stored in the main stream, and extra contents (author information and
7181 * title and so on) can be stored in sub stream. After Windows 2000, user
7182 * can access and store those informations in sub streams via explorer's
7183 * property menuitem in right click menu. Those informations in sub streams
7184 * were lost when copying only the main stream. So we have to copy sub
7185 * streams.
7186 *
7187 * Incomplete explanation:
7188 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7189 * More useful info and an example:
7190 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7191 */
7192
7193/*
7194 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7195 * and write to stream "substream" of file "to".
7196 * Errors are ignored.
7197 */
7198 static void
7199copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7200{
7201 HANDLE hTo;
7202 WCHAR *to_name;
7203
7204 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7205 wcscpy(to_name, to);
7206 wcscat(to_name, substream);
7207
7208 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7209 FILE_ATTRIBUTE_NORMAL, NULL);
7210 if (hTo != INVALID_HANDLE_VALUE)
7211 {
7212 long done;
7213 DWORD todo;
7214 DWORD readcnt, written;
7215 char buf[4096];
7216
7217 /* Copy block of bytes at a time. Abort when something goes wrong. */
7218 for (done = 0; done < len; done += written)
7219 {
7220 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007221 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7222 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7224 FALSE, FALSE, context)
7225 || readcnt != todo
7226 || !WriteFile(hTo, buf, todo, &written, NULL)
7227 || written != todo)
7228 break;
7229 }
7230 CloseHandle(hTo);
7231 }
7232
7233 free(to_name);
7234}
7235
7236/*
7237 * Copy info streams from file "from" to file "to".
7238 */
7239 static void
7240copy_infostreams(char_u *from, char_u *to)
7241{
7242 WCHAR *fromw;
7243 WCHAR *tow;
7244 HANDLE sh;
7245 WIN32_STREAM_ID sid;
7246 int headersize;
7247 WCHAR streamname[_MAX_PATH];
7248 DWORD readcount;
7249 void *context = NULL;
7250 DWORD lo, hi;
7251 int len;
7252
7253 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007254 fromw = enc_to_utf16(from, NULL);
7255 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256 if (fromw != NULL && tow != NULL)
7257 {
7258 /* Open the file for reading. */
7259 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7260 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7261 if (sh != INVALID_HANDLE_VALUE)
7262 {
7263 /* Use BackupRead() to find the info streams. Repeat until we
7264 * have done them all.*/
7265 for (;;)
7266 {
7267 /* Get the header to find the length of the stream name. If
7268 * the "readcount" is zero we have done all info streams. */
7269 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007270 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7272 &readcount, FALSE, FALSE, &context)
7273 || readcount == 0)
7274 break;
7275
7276 /* We only deal with streams that have a name. The normal
7277 * file data appears to be without a name, even though docs
7278 * suggest it is called "::$DATA". */
7279 if (sid.dwStreamNameSize > 0)
7280 {
7281 /* Read the stream name. */
7282 if (!BackupRead(sh, (LPBYTE)streamname,
7283 sid.dwStreamNameSize,
7284 &readcount, FALSE, FALSE, &context))
7285 break;
7286
7287 /* Copy an info stream with a name ":anything:$DATA".
7288 * Skip "::$DATA", it has no stream name (examples suggest
7289 * it might be used for the normal file contents).
7290 * Note that BackupRead() counts bytes, but the name is in
7291 * wide characters. */
7292 len = readcount / sizeof(WCHAR);
7293 streamname[len] = 0;
7294 if (len > 7 && wcsicmp(streamname + len - 6,
7295 L":$DATA") == 0)
7296 {
7297 streamname[len - 6] = 0;
7298 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007299 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 }
7301 }
7302
7303 /* Advance to the next stream. We might try seeking too far,
7304 * but BackupSeek() doesn't skip over stream borders, thus
7305 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007306 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 &lo, &hi, &context);
7308 }
7309
7310 /* Clear the context. */
7311 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7312
7313 CloseHandle(sh);
7314 }
7315 }
7316 vim_free(fromw);
7317 vim_free(tow);
7318}
7319#endif
7320
7321/*
7322 * Copy file attributes from file "from" to file "to".
7323 * For Windows NT and later we copy info streams.
7324 * Always returns zero, errors are ignored.
7325 */
7326 int
7327mch_copy_file_attribute(char_u *from, char_u *to)
7328{
7329#ifdef FEAT_MBYTE
7330 /* File streams only work on Windows NT and later. */
7331 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007332 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333#endif
7334 return 0;
7335}
7336
7337#if defined(MYRESETSTKOFLW) || defined(PROTO)
7338/*
7339 * Recreate a destroyed stack guard page in win32.
7340 * Written by Benjamin Peterson.
7341 */
7342
7343/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007344# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345
7346/*
7347 * This function does the same thing as _resetstkoflw(), which is only
7348 * available in DevStudio .net and later.
7349 * Returns 0 for failure, 1 for success.
7350 */
7351 int
7352myresetstkoflw(void)
7353{
7354 BYTE *pStackPtr;
7355 BYTE *pGuardPage;
7356 BYTE *pStackBase;
7357 BYTE *pLowestPossiblePage;
7358 MEMORY_BASIC_INFORMATION mbi;
7359 SYSTEM_INFO si;
7360 DWORD nPageSize;
7361 DWORD dummy;
7362
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364
7365 /* We need to know the system page size. */
7366 GetSystemInfo(&si);
7367 nPageSize = si.dwPageSize;
7368
7369 /* ...and the current stack pointer */
7370 pStackPtr = (BYTE*)_alloca(1);
7371
7372 /* ...and the base of the stack. */
7373 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7374 return 0;
7375 pStackBase = (BYTE*)mbi.AllocationBase;
7376
7377 /* ...and the page thats min_stack_req pages away from stack base; this is
7378 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007379 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007382 /* We want the first committed page in the stack Start at the stack
7383 * base and move forward through memory until we find a committed block.
7384 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 BYTE *pBlock = pStackBase;
7386
Bram Moolenaara466c992005-07-09 21:03:22 +00007387 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 {
7389 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7390 return 0;
7391
7392 pBlock += mbi.RegionSize;
7393
7394 if (mbi.State & MEM_COMMIT)
7395 break;
7396 }
7397
7398 /* mbi now describes the first committed block in the stack. */
7399 if (mbi.Protect & PAGE_GUARD)
7400 return 1;
7401
7402 /* decide where the guard page should start */
7403 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7404 pGuardPage = pLowestPossiblePage;
7405 else
7406 pGuardPage = (BYTE*)mbi.BaseAddress;
7407
7408 /* allocate the guard page */
7409 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7410 return 0;
7411
7412 /* apply the guard attribute to the page */
7413 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7414 &dummy))
7415 return 0;
7416 }
7417
7418 return 1;
7419}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007420#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007422
7423#if defined(FEAT_MBYTE) || defined(PROTO)
7424/*
7425 * The command line arguments in UCS2
7426 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007427static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007428static LPWSTR *ArglistW = NULL;
7429static int global_argc = 0;
7430static char **global_argv;
7431
7432static int used_file_argc = 0; /* last argument in global_argv[] used
7433 for the argument list. */
7434static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7435 command line arguments added to
7436 the argument list */
7437static int used_file_count = 0; /* nr of entries in used_file_indexes */
7438static int used_file_literal = FALSE; /* take file names literally */
7439static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007440static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007441static int used_alist_count = 0;
7442
7443
7444/*
7445 * Get the command line arguments. Unicode version.
7446 * Returns argc. Zero when something fails.
7447 */
7448 int
7449get_cmd_argsW(char ***argvp)
7450{
7451 char **argv = NULL;
7452 int argc = 0;
7453 int i;
7454
Bram Moolenaar14993322014-09-09 12:25:33 +02007455 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007456 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7457 if (ArglistW != NULL)
7458 {
7459 argv = malloc((nArgsW + 1) * sizeof(char *));
7460 if (argv != NULL)
7461 {
7462 argc = nArgsW;
7463 argv[argc] = NULL;
7464 for (i = 0; i < argc; ++i)
7465 {
7466 int len;
7467
7468 /* Convert each Unicode argument to the current codepage. */
7469 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007470 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007471 (LPSTR *)&argv[i], &len, 0, 0);
7472 if (argv[i] == NULL)
7473 {
7474 /* Out of memory, clear everything. */
7475 while (i > 0)
7476 free(argv[--i]);
7477 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007478 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007479 argc = 0;
7480 }
7481 }
7482 }
7483 }
7484
7485 global_argc = argc;
7486 global_argv = argv;
7487 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007488 {
7489 if (used_file_indexes != NULL)
7490 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007491 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007492 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007493
7494 if (argvp != NULL)
7495 *argvp = argv;
7496 return argc;
7497}
7498
7499 void
7500free_cmd_argsW(void)
7501{
7502 if (ArglistW != NULL)
7503 {
7504 GlobalFree(ArglistW);
7505 ArglistW = NULL;
7506 }
7507}
7508
7509/*
7510 * Remember "name" is an argument that was added to the argument list.
7511 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7512 * is called.
7513 */
7514 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007515used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007516{
7517 int i;
7518
7519 if (used_file_indexes == NULL)
7520 return;
7521 for (i = used_file_argc + 1; i < global_argc; ++i)
7522 if (STRCMP(global_argv[i], name) == 0)
7523 {
7524 used_file_argc = i;
7525 used_file_indexes[used_file_count++] = i;
7526 break;
7527 }
7528 used_file_literal = literal;
7529 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007530 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007531}
7532
7533/*
7534 * Remember the length of the argument list as it was. If it changes then we
7535 * leave it alone when 'encoding' is set.
7536 */
7537 void
7538set_alist_count(void)
7539{
7540 used_alist_count = GARGCOUNT;
7541}
7542
7543/*
7544 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7545 * has been changed while starting up. Use the UCS-2 command line arguments
7546 * and convert them to 'encoding'.
7547 */
7548 void
7549fix_arg_enc(void)
7550{
7551 int i;
7552 int idx;
7553 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007554 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007555
7556 /* Safety checks:
7557 * - if argument count differs between the wide and non-wide argument
7558 * list, something must be wrong.
7559 * - the file name arguments must have been located.
7560 * - the length of the argument list wasn't changed by the user.
7561 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007562 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007563 || ArglistW == NULL
7564 || used_file_indexes == NULL
7565 || used_file_count == 0
7566 || used_alist_count != GARGCOUNT)
7567 return;
7568
Bram Moolenaar86b68352004-12-27 21:59:20 +00007569 /* Remember the buffer numbers for the arguments. */
7570 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7571 if (fnum_list == NULL)
7572 return; /* out of memory */
7573 for (i = 0; i < GARGCOUNT; ++i)
7574 fnum_list[i] = GARGLIST[i].ae_fnum;
7575
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007576 /* Clear the argument list. Make room for the new arguments. */
7577 alist_clear(&global_alist);
7578 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007579 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007580
7581 for (i = 0; i < used_file_count; ++i)
7582 {
7583 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007584 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007585 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007586 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007587 int literal = used_file_literal;
7588
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007589# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007590 /* When using diff mode may need to concatenate file name to
7591 * directory name. Just like it's done in main(). */
7592 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7593 && !mch_isdir(alist_name(&GARGLIST[0])))
7594 {
7595 char_u *r;
7596
7597 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7598 if (r != NULL)
7599 {
7600 vim_free(str);
7601 str = r;
7602 }
7603 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007604# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007605 /* Re-use the old buffer by renaming it. When not using literal
7606 * names it's done by alist_expand() below. */
7607 if (used_file_literal)
7608 buf_set_name(fnum_list[i], str);
7609
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007610 /* Check backtick literal. backtick literal is already expanded in
7611 * main.c, so this part add str as literal. */
7612 if (literal == FALSE)
7613 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007614 size_t len = STRLEN(str);
7615
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007616 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7617 literal = TRUE;
7618 }
7619 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007620 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007621 }
7622
7623 if (!used_file_literal)
7624 {
7625 /* Now expand wildcards in the arguments. */
7626 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7627 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007628 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7629 * Also, unset wildignore to not be influenced by this option.
7630 * The arguments specified in command-line should be kept even if
7631 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007632 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007633 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007634 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007635 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007636 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007637 }
7638
7639 /* If wildcard expansion failed, we are editing the first file of the
7640 * arglist and there is no file name: Edit the first argument now. */
7641 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7642 {
7643 do_cmdline_cmd((char_u *)":rewind");
7644 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007645 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007646 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007647
7648 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007649}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007651
7652 int
7653mch_setenv(char *var, char *value, int x)
7654{
7655 char_u *envbuf;
7656
7657 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7658 if (envbuf == NULL)
7659 return -1;
7660
7661 sprintf((char *)envbuf, "%s=%s", var, value);
7662
7663#ifdef FEAT_MBYTE
7664 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7665 {
7666 WCHAR *p = enc_to_utf16(envbuf, NULL);
7667
7668 vim_free(envbuf);
7669 if (p == NULL)
7670 return -1;
7671 _wputenv(p);
7672# ifdef libintl_wputenv
7673 libintl_wputenv(p);
7674# endif
7675 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7676 vim_free(p);
7677 }
7678 else
7679#endif
7680 {
7681 _putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007682#ifdef libintl_putenv
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007683 libintl_putenv((char *)envbuf);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007684#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007685 /* Unlike Un*x systems, we can free the string for _putenv(). */
7686 vim_free(envbuf);
7687 }
7688
7689 return 0;
7690}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007691
7692#ifndef FEAT_GUI_W32
7693
7694/*
7695 * Support for 256 colors and 24-bit colors was added in Windows 10
7696 * version 1703 (Creators update).
7697 */
7698# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7699
7700 static void
7701vtp_init(void)
7702{
7703 DWORD ver, mode;
7704 HMODULE hKerneldll;
7705 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007706# ifdef FEAT_TERMGUICOLORS
7707 COLORREF fg, bg;
7708# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007709
7710 ver = get_build_number();
7711 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7712 GetConsoleMode(g_hConOut, &mode);
7713 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7714 if (SetConsoleMode(g_hConOut, mode) == 0)
7715 vtp_working = 0;
7716
7717 /* Use functions supported from Vista */
7718 hKerneldll = GetModuleHandle("kernel32.dll");
7719 if (hKerneldll != NULL)
7720 {
7721 pGetConsoleScreenBufferInfoEx =
7722 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7723 hKerneldll, "GetConsoleScreenBufferInfoEx");
7724 pSetConsoleScreenBufferInfoEx =
7725 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7726 hKerneldll, "SetConsoleScreenBufferInfoEx");
7727 if (pGetConsoleScreenBufferInfoEx != NULL
7728 && pSetConsoleScreenBufferInfoEx != NULL)
7729 has_csbiex = TRUE;
7730 }
7731
7732 csbi.cbSize = sizeof(csbi);
7733 if (has_csbiex)
7734 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007735 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7736 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7737
7738# ifdef FEAT_TERMGUICOLORS
7739 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7740 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7741 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7742 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7743 default_console_color_bg = bg;
7744 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007745# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007746
7747 set_console_color_rgb();
7748}
7749
7750 static void
7751vtp_exit(void)
7752{
7753 reset_console_color_rgb();
7754}
7755
7756 static int
7757vtp_printf(
7758 char *format,
7759 ...)
7760{
7761 char_u buf[100];
7762 va_list list;
7763 DWORD result;
7764
7765 va_start(list, format);
7766 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7767 va_end(list);
7768 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7769 return (int)result;
7770}
7771
7772 static void
7773vtp_sgr_bulk(
7774 int arg)
7775{
7776 int args[1];
7777
7778 args[0] = arg;
7779 vtp_sgr_bulks(1, args);
7780}
7781
7782 static void
7783vtp_sgr_bulks(
7784 int argc,
7785 int *args
7786)
7787{
7788 /* 2('\033[') + 4('255.') * 16 + NUL */
7789 char_u buf[2 + (4 * 16) + 1];
7790 char_u *p;
7791 int i;
7792
7793 p = buf;
7794 *p++ = '\033';
7795 *p++ = '[';
7796
7797 for (i = 0; i < argc; ++i)
7798 {
7799 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7800 *p++ = ';';
7801 }
7802 p--;
7803 *p++ = 'm';
7804 *p = NUL;
7805 vtp_printf((char *)buf);
7806}
7807
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007808# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007809 static int
7810ctermtoxterm(
7811 int cterm)
7812{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007813 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007814
7815 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7816 return (((int)r << 16) | ((int)g << 8) | (int)b);
7817}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007818# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007819
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007820 static void
7821set_console_color_rgb(void)
7822{
7823# ifdef FEAT_TERMGUICOLORS
7824 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7825 int id;
7826 guicolor_T fg = INVALCOLOR;
7827 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007828 int ctermfg;
7829 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007830
7831 if (!USE_VTP)
7832 return;
7833
7834 id = syn_name2id((char_u *)"Normal");
7835 if (id > 0)
7836 syn_id2colors(id, &fg, &bg);
7837 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007838 {
7839 ctermfg = -1;
7840 if (id > 0)
7841 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007842 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7843 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007844 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007845 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007846 {
7847 ctermbg = -1;
7848 if (id > 0)
7849 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007850 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7851 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007852 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007853 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7854 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7855
7856 csbi.cbSize = sizeof(csbi);
7857 if (has_csbiex)
7858 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7859
7860 csbi.cbSize = sizeof(csbi);
7861 csbi.srWindow.Right += 1;
7862 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007863 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7864 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007865 if (has_csbiex)
7866 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7867# endif
7868}
7869
7870 static void
7871reset_console_color_rgb(void)
7872{
7873# ifdef FEAT_TERMGUICOLORS
7874 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7875
7876 csbi.cbSize = sizeof(csbi);
7877 if (has_csbiex)
7878 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7879
7880 csbi.cbSize = sizeof(csbi);
7881 csbi.srWindow.Right += 1;
7882 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007883 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7884 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007885 if (has_csbiex)
7886 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7887# endif
7888}
7889
7890 void
7891control_console_color_rgb(void)
7892{
7893 if (USE_VTP)
7894 set_console_color_rgb();
7895 else
7896 reset_console_color_rgb();
7897}
7898
7899 int
7900has_vtp_working(void)
7901{
7902 return vtp_working;
7903}
7904
7905 int
7906use_vtp(void)
7907{
7908 return USE_VTP;
7909}
7910
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007911 int
7912is_term_win32(void)
7913{
7914 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7915}
7916
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007917#endif